From 54bf57c68a01f03731a9df5dd28ec6fb522bce0e Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Wed, 18 May 2016 14:32:18 -0400 Subject: [PATCH 01/21] First cut at animations --- src/components/drawing/index.js | 13 +- src/core.js | 1 + src/plot_api/plot_api.js | 111 ++++++++++++++ src/traces/scatter/animate.js | 246 ++++++++++++++++++++++++++++++++ src/traces/scatter/index.js | 1 + 5 files changed, 370 insertions(+), 2 deletions(-) create mode 100644 src/traces/scatter/animate.js diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 44d3076184c..f0a286a2f75 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -46,7 +46,7 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya) { +drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasing) { s.each(function(d) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), @@ -55,7 +55,16 @@ drawing.translatePoints = function(s, xa, ya) { if(isNumeric(x) && isNumeric(y)) { // for multiline text this works better if(this.nodeName==='text') p.attr('x',x).attr('y',y); - else p.attr('transform', 'translate('+x+','+y+')'); + else { + if (isNumeric(transitionDuration)) { + p.transition() + .duration(transitionDuration) + .ease(transitionEasing) + .attr('transform', 'translate('+x+','+y+')'); + } else { + p.attr('transform', 'translate('+x+','+y+')'); + } + } } else p.remove(); }); diff --git a/src/core.js b/src/core.js index 8cded13f097..c6dc9a5019d 100644 --- a/src/core.js +++ b/src/core.js @@ -21,6 +21,7 @@ exports.version = '1.10.0'; exports.plot = Plotly.plot; exports.newPlot = Plotly.newPlot; exports.restyle = Plotly.restyle; +exports.animate = Plotly.animate; exports.relayout = Plotly.relayout; exports.redraw = Plotly.redraw; exports.extendTraces = Plotly.extendTraces; diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 24f06adc781..f70139195d9 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1502,6 +1502,117 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { return promise; }; +// ----------------------------------------------------- +// animate the changing of data +// ----------------------------------------------------- +// Sequence is: +// +// 1. prepare for animation (store copy of current data, if necessary) +// 2. update gd.data +// 3. update gl._fullData +// 4. doCalcdata +// 5. begin animation +Plotly.animate = function animate (gd, newData, transitionOpts, traces) { + var i; + + gd = getGraphDiv(gd); + window.gd = gd; + + if(isNumeric(traces)) traces=[traces]; + else if(!Array.isArray(traces) || !traces.length) { + traces = gd._fullData.map(function (v,i) {return i;}); + } + + for (var i = 0; i < traces.length; i++) { + var newTraceData = newData[i]; + var data = gd.data[traces[i]]; + var trace = gd._fullData[traces[i]]; + + for (var ai in newTraceData) { + var value = newTraceData[ai]; + var param = Lib.nestedProperty(data, ai); + param.set(value); + } + } + + // Placeholder for more general transfer of data: + for (var i = 0; i < traces.length; i++) { + gd._fullData[traces[i]].x = gd.data[traces[i]].x; + gd._fullData[traces[i]].y = gd.data[traces[i]].y; + } + + doCalcdata(gd); + + for (var i = 0; i < traces.length; i++) { + var module = trace._module; + var cd = []; + + if(module && trace.visible === true) { + if(module.calc) cd = module.calc(gd, trace); + } + + // make sure there is a first point + // this ensures there is a calcdata item for every trace, + // even if cartesian logic doesn't handle it + if(!Array.isArray(cd) || !cd[0]) cd = [{x: false, y: false}]; + + // add the trace-wide properties to the first point, + // per point properties to every point + // t is the holder for trace-wide properties + if(!cd[0].t) cd[0].t = {}; + cd[0].trace = trace; + + Lib.markTime('done with calcdata for '+i); + gd.calcdata[traces[i]] = cd; + } + + for (i = 0; i < traces.length; i++) { + + var idx = traces[i]; + + var cont = gd.data[idx]; + var contFull = gd._fullData[idx]; + var module = contFull._module; + + if (module.animate) { + module.animate(gd, contFull, newData[i], transitionOpts); + } + } + + /* + for(var i = 0; i < gd.calcdata.length; i++) { + gd.calcdata[i][0].trace = gd._fullData[i]; + } + + var seq; + seq = [Plots.previousPromises]; + + seq.push(function doAnimate () { + for (var i = 0; i < traces.length; i++) { + //var cont = gd.data[traces[i]]; + var trace = gd._fullData[traces[i]]; + var mod = trace._module; + + if (mod.animate) { + mod.animate(gd, trace, data[i], transitionOpts); + } + } + return Plots.previousPromises(gd); + }); + + var plotDone = Lib.syncOrAsync(seq, gd); + + if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); + + return plotDone.then(function() { + gd.emit('plotly_beginanimate', [traces]); + return gd; + }); + */ + + +} + // ----------------------------------------------------- // restyle and relayout: these two control all redrawing // for data (restyle) and everything else (relayout) diff --git a/src/traces/scatter/animate.js b/src/traces/scatter/animate.js new file mode 100644 index 00000000000..877739b2132 --- /dev/null +++ b/src/traces/scatter/animate.js @@ -0,0 +1,246 @@ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var d3 = require('d3'); + +var Lib = require('../../lib'); +var Drawing = require('../../components/drawing'); +var ErrorBars = require('../../components/errorbars'); + +var subTypes = require('./subtypes'); +var arraysToCalcdata = require('./arrays_to_calcdata'); +var linePoints = require('./line_points'); +var isNumeric = require('fast-isnumeric'); + +module.exports = function animate (gd, trace, data, opts) { + var axisName = trace.xaxis + trace.yaxis; + var plotinfo = gd._fullLayout._plots[axisName]; + var cdscatter = gd.calcdata + + opts = opts || {}; + var transitionDuration = isNumeric(opts.duration) ? opts.duration : 250; + var transitionEasing = !!opts.easing ? opts.easing : 'cubic-in-out'; + + window.scattertraces = plotinfo.plot.select('.scatterlayer') + + /*return + + var scattertraces = plotinfo.plot.select('.scatterlayer') + .selectAll('g.trace.scatter') + .data(gd.calcdata[trace.index]) + + + scattertraces.selectAll('g.points') + .each(function (d) { + console.log('d =', d) + }); + + + var prevpath = '', + ownFillEl3, ownFillDir, tonext, nexttonext;*/ + + window.trace = trace; + var xa = plotinfo.x(), + ya = plotinfo.y(); + + // make the container for scatter plots + // (so error bars can find them along with bars) + var scattertraces = plotinfo.plot.select('.scatterlayer') + .selectAll('g.trace.scatter') + .data(cdscatter); + + //scattertraces.enter().append('g') + //.attr('class', 'trace scatter') + //.style('stroke-miterlimit', 2); + + // error bars are at the bottom + //scattertraces.call(ErrorBars.plot, plotinfo); + + // BUILD LINES AND FILLS + var prevpath = '', + ownFillEl3, ownFillDir, tonext, nexttonext; + + scattertraces.each(function(d) { + var trace = d[0].trace, + line = trace.line, + tr = d3.select(this); + if(trace.visible !== true) return; + + ownFillDir = trace.fill.charAt(trace.fill.length - 1); + if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; + + d[0].node3 = tr; // store node for tweaking by selectPoints + + arraysToCalcdata(d); + + if(!subTypes.hasLines(trace) && trace.fill === 'none') return; + + var thispath, + thisrevpath, + // fullpath is all paths for this curve, joined together straight + // across gaps, for filling + fullpath = '', + // revpath is fullpath reversed, for fill-to-next + revpath = '', + // functions for converting a point array to a path + pathfn, revpathbase, revpathfn; + + // make the fill-to-zero path now, so it shows behind the line + // fill to next puts the fill associated with one trace + // grouped with the previous + /*if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || + (trace.fill.substr(0, 2) === 'to' && !prevpath)) { + ownFillEl3 = tr.append('path') + .classed('js-fill', true); + } + else ownFillEl3 = null;*/ + + // make the fill-to-next path now for the NEXT trace, so it shows + // behind both lines. + // nexttonext was created last time, but give it + // this curve's data for fill color + if(nexttonext) tonext = nexttonext.datum(d); + + // now make a new nexttonext for next time + //nexttonext = tr.append('path').classed('js-fill', true); + + if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { + pathfn = Drawing.steps(line.shape); + revpathbase = Drawing.steps( + line.shape.split('').reverse().join('') + ); + } + else if(line.shape === 'spline') { + pathfn = revpathbase = function(pts) { + var pLast = pts[pts.length - 1]; + if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { + // identical start and end points: treat it as a + // closed curve so we don't get a kink + return Drawing.smoothclosed(pts.slice(1), line.smoothing); + } + else { + return Drawing.smoothopen(pts, line.smoothing); + } + }; + } + else { + pathfn = revpathbase = function(pts) { + return 'M' + pts.join('L'); + }; + } + + revpathfn = function(pts) { + // note: this is destructive (reverses pts in place) so can't use pts after this + return revpathbase(pts.reverse()); + }; + + var segments = linePoints(d, { + xaxis: xa, + yaxis: ya, + connectGaps: trace.connectgaps, + baseTolerance: Math.max(line.width || 1, 3) / 4, + linear: line.shape === 'linear' + }); + + if(segments.length) { + var pt0 = segments[0][0], + lastSegment = segments[segments.length - 1], + pt1 = lastSegment[lastSegment.length - 1]; + + for(var i = 0; i < segments.length; i++) { + var pts = segments[i]; + thispath = pathfn(pts); + thisrevpath = revpathfn(pts); + if(!fullpath) { + fullpath = thispath; + revpath = thisrevpath; + } + else if(ownFillDir) { + fullpath += 'L' + thispath.substr(1); + revpath = thisrevpath + ('L' + revpath.substr(1)); + } + else { + fullpath += 'Z' + thispath; + revpath = thisrevpath + 'Z' + revpath; + } + + if(subTypes.hasLines(trace) && pts.length > 1) { + tr.select('path.js-line') + .transition() + .ease(transitionEasing) + .duration(transitionDuration).attr('d', thispath); + } + } + /*if(ownFillEl3) { + if(pt0 && pt1) { + if(ownFillDir) { + if(ownFillDir === 'y') { + pt0[1] = pt1[1] = ya.c2p(0, true); + } + else if(ownFillDir === 'x') { + pt0[0] = pt1[0] = xa.c2p(0, true); + } + + // fill to zero: full trace path, plus extension of + // the endpoints to the appropriate axis + ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + } + // fill to self: just join the path to itself + else ownFillEl3.attr('d', fullpath + 'Z'); + } + } + else*/ + if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { + // fill to next: full trace path, plus the previous path reversed + if(trace.fill === 'tonext') { + // tonext: for use by concentric shapes, like manually constructed + // contours, we just add the two paths closed on themselves. + // This makes strange results if one path is *not* entirely + // inside the other, but then that is a strange usage. + tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); + } + else { + // tonextx/y: for now just connect endpoints with lines. This is + // the correct behavior if the endpoints are at the same value of + // y/x, but if they *aren't*, we should ideally do more complicated + // things depending on whether the new endpoint projects onto the + // existing curve or off the end of it + tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + } + } + prevpath = revpath; + } + }); + + // remove paths that didn't get used + // scattertraces.selectAll('path:not([d])').remove(); + + function visFilter(d) { + return d.filter(function(v) { return v.vis; }); + } + + scattertraces.select('g.points') + .each(function(d) { + var trace = d[0].trace, + s = d3.select(this), + showMarkers = subTypes.hasMarkers(trace), + showText = subTypes.hasText(trace); + + if((!showMarkers && !showText) || trace.visible !== true) s.remove(); + else { + if(showMarkers) { + s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing); + } + } + }); + +}; diff --git a/src/traces/scatter/index.js b/src/traces/scatter/index.js index 3b576a561d0..511e996711e 100644 --- a/src/traces/scatter/index.js +++ b/src/traces/scatter/index.js @@ -29,6 +29,7 @@ Scatter.colorbar = require('./colorbar'); Scatter.style = require('./style'); Scatter.hoverPoints = require('./hover'); Scatter.selectPoints = require('./select'); +Scatter.animate = require('./animate'); Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; From c3517c23975f1ab61c31432843460a705108b6d5 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Tue, 31 May 2016 12:30:31 -0400 Subject: [PATCH 02/21] Slightly ugly hack to animate point styles --- src/components/drawing/index.js | 13 +++++++++---- src/plot_api/plot_api.js | 9 +++++++-- src/traces/scatter/animate.js | 33 +++++++++++++++++---------------- 3 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index f0a286a2f75..df8f7632449 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -46,7 +46,7 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasing) { +drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasing, trace) { s.each(function(d) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), @@ -56,11 +56,16 @@ drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasi // for multiline text this works better if(this.nodeName==='text') p.attr('x',x).attr('y',y); else { - if (isNumeric(transitionDuration)) { - p.transition() + var join = p; + if (isNumeric(transitionDuration) && transitionDuration > 0) { + var trans = p.transition() .duration(transitionDuration) .ease(transitionEasing) - .attr('transform', 'translate('+x+','+y+')'); + .attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } } else { p.attr('transform', 'translate('+x+','+y+')'); } diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index f70139195d9..1069a51adda 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1516,13 +1516,13 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var i; gd = getGraphDiv(gd); - window.gd = gd; - if(isNumeric(traces)) traces=[traces]; + if(isNumeric(traces)) traces = [traces]; else if(!Array.isArray(traces) || !traces.length) { traces = gd._fullData.map(function (v,i) {return i;}); } + for (var i = 0; i < traces.length; i++) { var newTraceData = newData[i]; var data = gd.data[traces[i]]; @@ -1537,6 +1537,9 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { // Placeholder for more general transfer of data: for (var i = 0; i < traces.length; i++) { + if (gd.data[traces[i]].marker && gd.data[traces[i]].marker.size) { + gd._fullData[traces[i]].marker.size = gd.data[traces[i]].marker.size + } gd._fullData[traces[i]].x = gd.data[traces[i]].x; gd._fullData[traces[i]].y = gd.data[traces[i]].y; } @@ -1544,6 +1547,7 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { doCalcdata(gd); for (var i = 0; i < traces.length; i++) { + var trace = gd._fullData[traces[i]]; var module = trace._module; var cd = []; @@ -1560,6 +1564,7 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { // per point properties to every point // t is the holder for trace-wide properties if(!cd[0].t) cd[0].t = {}; + cd[0].trace = trace; Lib.markTime('done with calcdata for '+i); diff --git a/src/traces/scatter/animate.js b/src/traces/scatter/animate.js index 877739b2132..2da7bf05607 100644 --- a/src/traces/scatter/animate.js +++ b/src/traces/scatter/animate.js @@ -28,30 +28,32 @@ module.exports = function animate (gd, trace, data, opts) { var transitionDuration = isNumeric(opts.duration) ? opts.duration : 250; var transitionEasing = !!opts.easing ? opts.easing : 'cubic-in-out'; - window.scattertraces = plotinfo.plot.select('.scatterlayer') + //window.scattertraces = plotinfo.plot.select('.scatterlayer') - /*return + /*return - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(gd.calcdata[trace.index]) + var scattertraces = plotinfo.plot.select('.scatterlayer') + .selectAll('g.trace.scatter') + .data(gd.calcdata[trace.index]) - scattertraces.selectAll('g.points') - .each(function (d) { - console.log('d =', d) - }); + scattertraces.selectAll('g.points') + .each(function (d) { + console.log('d =', d) + }); - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext;*/ + var prevpath = '', + ownFillEl3, ownFillDir, tonext, nexttonext;*/ - window.trace = trace; + window.trace = trace; + window.plotinfo = plotinfo var xa = plotinfo.x(), ya = plotinfo.y(); // make the container for scatter plots // (so error bars can find them along with bars) + var scattertraces = plotinfo.plot.select('.scatterlayer') .selectAll('g.trace.scatter') .data(cdscatter); @@ -178,7 +180,7 @@ module.exports = function animate (gd, trace, data, opts) { .duration(transitionDuration).attr('d', thispath); } } - /*if(ownFillEl3) { + if(ownFillEl3) { if(pt0 && pt1) { if(ownFillDir) { if(ownFillDir === 'y') { @@ -196,8 +198,7 @@ module.exports = function animate (gd, trace, data, opts) { else ownFillEl3.attr('d', fullpath + 'Z'); } } - else*/ - if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { + else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { // fill to next: full trace path, plus the previous path reversed if(trace.fill === 'tonext') { // tonext: for use by concentric shapes, like manually constructed @@ -238,7 +239,7 @@ module.exports = function animate (gd, trace, data, opts) { if(showMarkers) { s.selectAll('path.point') .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing); + .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace); } } }); From 2eae93a7a2caa9c9d6f55d1b3d86b4d55a2a692d Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Thu, 2 Jun 2016 11:04:07 -0400 Subject: [PATCH 03/21] Remove stray markTime --- src/plot_api/plot_api.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 7f45d50615d..136481513ec 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1575,7 +1575,6 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { cd[0].trace = trace; - Lib.markTime('done with calcdata for '+i); gd.calcdata[traces[i]] = cd; } From e9bcf90576cd049ab3d50ba37037e5c33a308c1c Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Thu, 2 Jun 2016 17:38:44 -0400 Subject: [PATCH 04/21] A method to clone input traces --- src/lib/index.js | 86 ++++++++++++++++++++++++++++++++ src/plot_api/plot_api.js | 41 ++++++++++++--- src/traces/scatter/attributes.js | 4 ++ 3 files changed, 124 insertions(+), 7 deletions(-) diff --git a/src/lib/index.js b/src/lib/index.js index 32f3f811a67..4d5170d96c8 100644 --- a/src/lib/index.js +++ b/src/lib/index.js @@ -585,3 +585,89 @@ lib.numSeparate = function(value, separators) { return x1 + x2; }; + +/* + * Deep copy of an object, subject to some caveats. Adapted from + * http://stackoverflow.com/questions/10728412/in-javascript-when-performing-a-deep-copy-how-do-i-avoid-a-cycle-due-to-a-pro#answer-10729242 + * + * It does some basics like avoiding infinite loops, but leaves some gaps + * regarding prototypes and functions. But those shouldn't be part of the + * layout anyway, which is the intended use. + * + * @param {object} object the object to be cloned + * @param {function} shallowFilter a callback executed on each attribute name + * @param {Array} path a stack representing the current attr path + * + * @return {object} the cloned object + */ +lib.deepClone = function deepClone (object, shallowFilter, path) { + var nextPath, isShallow; + var gdcc = "__getDeepCircularCopy__"; + if (object !== Object(object)) { + return object; // primitive value + } + + var set = gdcc in object; + var cache = object[gdcc]; + var result; + if (set && typeof cache == "function") { + return cache(); + } + // else + object[gdcc] = function () { return result; }; // overwrite + + if (object instanceof Array) { + result = []; + for (var i=0; i= 0; i--) { + if (gd.data[i][isClonedFlag]) continue; + + // Clone this trace if it's not already cloned. Otherwise the original input + // to Plotly.plot gets mangled and we can't use it again, which is inconvenient. + // Notably, this does *not* copy data arrays. + type = gd._fullData[i].type; + schema = Plotly.PlotSchema.get().traces[type] + gd.data[i] = Lib.deepCloneTrace(gd.data[i], schema); + gd.data[i][isClonedFlag] = true; + } +} diff --git a/src/traces/scatter/attributes.js b/src/traces/scatter/attributes.js index 072af6dc6b8..43cb07175b5 100644 --- a/src/traces/scatter/attributes.js +++ b/src/traces/scatter/attributes.js @@ -62,6 +62,10 @@ module.exports = { 'See `y0` for more info.' ].join(' ') }, + key: { + valType: 'data_array', + description: 'A list of keys for object constancy of data points during animation' + }, text: { valType: 'string', role: 'info', From 5497e7dd2312cf2613d941ce757e5348ea815db1 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Wed, 8 Jun 2016 12:39:26 -0400 Subject: [PATCH 05/21] Make animations promise-based --- src/components/drawing/index.js | 43 ++++++++--- src/plot_api/plot_api.js | 127 +++++++++++++++++++++----------- src/traces/scatter/animate.js | 53 ++++++++++++- src/traces/scatter/calc.js | 4 + src/traces/scatter/defaults.js | 1 + src/traces/scatter/plot.js | 12 ++- 6 files changed, 184 insertions(+), 56 deletions(-) diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 11480bc6dcf..96ceb571373 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -46,8 +46,8 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasing, trace) { - s.each(function(d) { +drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasing, trace, dir, transitionDelay, transitionCascade) { + s.each(function(d, i) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), y = d.yp || ya.c2p(d.y), @@ -57,16 +57,39 @@ drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasi if(this.nodeName==='text') { p.attr('x',x).attr('y',y); } else { - var join = p; if (isNumeric(transitionDuration) && transitionDuration > 0) { - var trans = p.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('transform', 'translate('+x+','+y+')') - - if (trace) { - trans.call(drawing.pointStyle, trace) + var trans; + if (!dir) { + trans = p.transition() + .delay(transitionDelay + transitionCascade * i) + .duration(transitionDuration) + .ease(transitionEasing) + .attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } + } else if (dir === -1) { + trans = p.style('opacity', 1) + .transition() + .duration(transitionDuration) + .ease(transitionEasing) + .style('opacity', 0) + .remove(); + } else if (dir === 1) { + trans = p.attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } + + trans.style('opacity', 0) + .transition() + .duration(transitionDuration) + .ease(transitionEasing) + .style('opacity', 1) } + } else { p.attr('transform', 'translate('+x+','+y+')'); } diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 5cb0d397e75..d0b5e5cdc3c 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -839,13 +839,14 @@ Plotly.newPlot = function(gd, data, layout, config) { return Plotly.plot(gd, data, layout, config); }; -function doCalcdata(gd) { +function doCalcdata(gd, traces) { var axList = Plotly.Axes.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; var i, trace, module, cd; + var oldCalcdata = (gd.calcdata || []).slice(0); var calcdata = gd.calcdata = new Array(fullData.length); // extra helper variables @@ -870,6 +871,13 @@ function doCalcdata(gd) { } for(i = 0; i < fullData.length; i++) { + // If traces were specified and this trace was not included, then transfer it over from + // the old calcdata: + if (Array.isArray(traces) && traces.indexOf(i) === -1) { + calcdata[i] = oldCalcdata[i]; + continue; + } + trace = fullData[i]; module = trace._module; cd = []; @@ -1521,7 +1529,18 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { // 4. doCalcdata // 5. begin animation Plotly.animate = function animate (gd, newData, transitionOpts, traces) { - var i, newTraceData, curData, value; + var i, newTraceData, curData, value, traceIdx; + + if (!Array.isArray(newData)) { + Lib.warn('Animate fail. newData must be an array of traces'); + return Promise.reject(); + } + + transitionOpts = transitionOpts || {}; + transitionOpts.duration = transitionOpts.duration === undefined ? 250 : transitionOpts.duration; + transitionOpts.easing = transitionOpts.easing === undefined ? 'cubic-in-out' : transitionOpts.easing; + transitionOpts.cascade = transitionOpts.cascade === undefined ? 0 : transitionOpts.cascade; + transitionOpts.leadingEdgeRestyle = transitionOpts.leadingEdgeRestyle === undefined ? false : transitionOpts.leadingEdgeRestyle; gd = getGraphDiv(gd); @@ -1532,30 +1551,58 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { cloneTraceDefinitions(gd); + var animatedTraces = []; + for (i = 0; i < traces.length; i++) { + var traceIdx = traces[i]; + var trace = gd._fullData[traceIdx]; + var module = trace._module; + + if (!module.animate) { + continue; + } + + animatedTraces.push(traceIdx); + newTraceData = newData[i]; curData = gd.data[traces[i]]; - //var trace = gd._fullData[traces[i]]; for (var ai in newTraceData) { var value = newTraceData[ai]; Lib.nestedProperty(curData, ai).set(value); } - } - // Placeholder for more general transfer of data: - for (var i = 0; i < traces.length; i++) { - if (gd.data[traces[i]].marker && gd.data[traces[i]].marker.size) { - gd._fullData[traces[i]].marker.size = gd.data[traces[i]].marker.size + + var traceIdx = traces[i]; + if (gd.data[traceIdx].marker && gd.data[traceIdx].marker.size) { + gd._fullData[traceIdx].marker.size = gd.data[traceIdx].marker.size } - gd._fullData[traces[i]].x = gd.data[traces[i]].x; - gd._fullData[traces[i]].y = gd.data[traces[i]].y; + gd._fullData[traceIdx].x = gd.data[traceIdx].x; + gd._fullData[traceIdx].y = gd.data[traceIdx].y; + gd._fullData[traceIdx].z = gd.data[traceIdx].z; + gd._fullData[traceIdx].key = gd.data[traceIdx].key; } - doCalcdata(gd); + doCalcdata(gd, animatedTraces); + + var animateList = []; + var restyleList = []; + + function doAnimations () { + var a; + for (i = 0; i < animateList.length; i++) { + a = animateList[i]; + a.module.animate(gd, a.contFull, a.newData, transitionOpts); + } + if (!transitionOpts.leadingEdgeRestyle) { + return new Promise(function(resolve, reject) { + setTimeout(resolve, transitionOpts.duration); + }); + } + } - for (var i = 0; i < traces.length; i++) { - var trace = gd._fullData[traces[i]]; + for (var i = 0; i < animatedTraces.length; i++) { + var trace = gd._fullData[animatedTraces[i]]; var module = trace._module; var cd = []; @@ -1579,50 +1626,46 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { } for (i = 0; i < traces.length; i++) { + var traceIdx = traces[i]; - var idx = traces[i]; - - var cont = gd.data[idx]; - var contFull = gd._fullData[idx]; + var cont = gd.data[traceIdx]; + var contFull = gd._fullData[traceIdx]; var module = contFull._module; if (module.animate) { - module.animate(gd, contFull, newData[i], transitionOpts); - } - } - - /* - for(var i = 0; i < gd.calcdata.length; i++) { - gd.calcdata[i][0].trace = gd._fullData[i]; - } - - var seq; - seq = [Plots.previousPromises]; - - seq.push(function doAnimate () { - for (var i = 0; i < traces.length; i++) { - //var cont = gd.data[traces[i]]; - var trace = gd._fullData[traces[i]]; - var mod = trace._module; + animateList.push({ + module: module, + contFull: contFull, + newData: newData[i] + }); + } else { + var thisTrace = [traceIdx]; + var thisUpdate = {}; - if (mod.animate) { - mod.animate(gd, trace, data[i], transitionOpts); + for (ai in newData[i]) { + thisUpdate[ai] = [newData[i][ai]]; } + + restyleList.push((function (md, data, traces) { + return function () { + return Plotly.restyle(gd, data, traces); + } + }(module, thisUpdate, [traceIdx]))); } - return Plots.previousPromises(gd); - }); + } + + var seq = [Plots.previousPromises]; + seq.push(doAnimations); + seq = seq.concat(restyleList); var plotDone = Lib.syncOrAsync(seq, gd); if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); return plotDone.then(function() { - gd.emit('plotly_beginanimate', [traces]); + gd.emit('plotly_animate', []); return gd; }); - */ - - } // ----------------------------------------------------- diff --git a/src/traces/scatter/animate.js b/src/traces/scatter/animate.js index 2da7bf05607..af2eb5eaf63 100644 --- a/src/traces/scatter/animate.js +++ b/src/traces/scatter/animate.js @@ -27,6 +27,7 @@ module.exports = function animate (gd, trace, data, opts) { opts = opts || {}; var transitionDuration = isNumeric(opts.duration) ? opts.duration : 250; var transitionEasing = !!opts.easing ? opts.easing : 'cubic-in-out'; + var transitionCascade = !!opts.cascade ? opts.cascade : 0; //window.scattertraces = plotinfo.plot.select('.scatterlayer') @@ -227,6 +228,16 @@ module.exports = function animate (gd, trace, data, opts) { return d.filter(function(v) { return v.vis; }); } + function keyFunc (d) { + return d.key; + } + + function getKeyFunc(trace) { + if (trace.key) { + return keyFunc; + } + } + scattertraces.select('g.points') .each(function(d) { var trace = d[0].trace, @@ -237,11 +248,47 @@ module.exports = function animate (gd, trace, data, opts) { if((!showMarkers && !showText) || trace.visible !== true) s.remove(); else { if(showMarkers) { - s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace); + var selection = s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) + + //console.log('d:', d.length); + //console.log('transitionCascade:', transitionCascade); + selection.call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, null, 0, transitionCascade / d.length); + + var enter = selection.enter().append('path') + .classed('point', true) + .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 1) + + selection.exit() + .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, -1) } } }); }; + + /* + window.gd = gd; + + scattertraces.select('g.points') + .each(function(d) { + var trace = d[0].trace, + s = d3.select(this), + showMarkers = subTypes.hasMarkers(trace), + showText = subTypes.hasText(trace); + + if((!showMarkers && !showText) || trace.visible !== true) s.remove(); + else { + if(showMarkers) { + var selection = s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)); + + selection.call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace); + + selection.enter().append('path') + .classed('point', true) + .call(Drawing.translatePoints, xa, ya); + } + } + }); +};*/ diff --git a/src/traces/scatter/calc.js b/src/traces/scatter/calc.js index 21304864b93..055fc6ce574 100644 --- a/src/traces/scatter/calc.js +++ b/src/traces/scatter/calc.js @@ -115,6 +115,10 @@ module.exports = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ? {x: x[i], y: y[i]} : {x: false, y: false}; + + if (trace.key && trace.key[i]) { + cd[i].key = trace.key[i]; + } } // this has migrated up from arraysToCalcdata as we have a reference to 's' here diff --git a/src/traces/scatter/defaults.js b/src/traces/scatter/defaults.js index 3690160053f..79b7eac8b0d 100644 --- a/src/traces/scatter/defaults.js +++ b/src/traces/scatter/defaults.js @@ -36,6 +36,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout return; } + coerce('key'); coerce('text'); coerce('mode', defaultMode); diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 2044c854fa1..1547fbb43bb 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -197,6 +197,16 @@ module.exports = function plot(gd, plotinfo, cdscatter) { return d.filter(function(v) { return v.vis; }); } + function keyFunc (d) { + return d.key; + } + + function getKeyFunc(trace) { + if (trace.key) { + return keyFunc; + } + } + scattertraces.append('g') .attr('class', 'points') .each(function(d) { @@ -209,7 +219,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { else { if(showMarkers) { s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) .enter().append('path') .classed('point', true) .call(Drawing.translatePoints, xa, ya); From c159dae653ecb7e69ffd79dd08729c794d4e841a Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Wed, 8 Jun 2016 19:31:06 -0400 Subject: [PATCH 06/21] Non-working commit in the right direction... --- src/plot_api/plot_api.js | 7 ++++++- src/plots/cartesian/index.js | 11 +++++++--- src/traces/scatter/animate.js | 35 ++++++++++++++++++++++--------- src/traces/scatter/line_points.js | 2 +- src/traces/scatter/plot.js | 3 +++ 5 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index d0b5e5cdc3c..f0c4e7037a5 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1529,6 +1529,7 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { // 4. doCalcdata // 5. begin animation Plotly.animate = function animate (gd, newData, transitionOpts, traces) { + var fullLayout = gd._fullLayout; var i, newTraceData, curData, value, traceIdx; if (!Array.isArray(newData)) { @@ -1592,7 +1593,11 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var a; for (i = 0; i < animateList.length; i++) { a = animateList[i]; - a.module.animate(gd, a.contFull, a.newData, transitionOpts); + //a.module.animate(gd, a.contFull, a.newData, transitionOpts); + var basePlotModules = fullLayout._basePlotModules; + for(i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd, transitionOpts); + } } if (!transitionOpts.leadingEdgeRestyle) { return new Promise(function(resolve, reject) { diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index 56f827f0ec6..a50e77cf85d 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -25,7 +25,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd) { +exports.plot = function(gd, animationConfig) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -69,7 +69,7 @@ exports.plot = function(gd) { // remove old traces, then redraw everything // TODO: use enter/exit appropriately in the plot functions // so we don't need this - should sometimes be a big speedup - if(subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove(); + if(!animationConfig && subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove(); for(var j = 0; j < modules.length; j++) { var _module = modules[j]; @@ -79,7 +79,12 @@ exports.plot = function(gd) { // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); - _module.plot(gd, subplotInfo, cdModule); + + if (animationConfig) { + _module.animate(gd, subplotInfo, cdModule, transtionOpts); + } else { + _module.plot(gd, subplotInfo, cdModule); + } } } }; diff --git a/src/traces/scatter/animate.js b/src/traces/scatter/animate.js index af2eb5eaf63..fe5e344749b 100644 --- a/src/traces/scatter/animate.js +++ b/src/traces/scatter/animate.js @@ -98,21 +98,24 @@ module.exports = function animate (gd, trace, data, opts) { // make the fill-to-zero path now, so it shows behind the line // fill to next puts the fill associated with one trace // grouped with the previous - /*if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || + var fills = tr.selectAll('.js-fill')[0]; + if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || (trace.fill.substr(0, 2) === 'to' && !prevpath)) { - ownFillEl3 = tr.append('path') - .classed('js-fill', true); + ownFillEl3 = d3.select(fills[0]); } - else ownFillEl3 = null;*/ + else ownFillEl3 = null; // make the fill-to-next path now for the NEXT trace, so it shows // behind both lines. // nexttonext was created last time, but give it // this curve's data for fill color - if(nexttonext) tonext = nexttonext.datum(d); + if(nexttonext) tonext = nexttonext.data(d); // now make a new nexttonext for next time - //nexttonext = tr.append('path').classed('js-fill', true); + nexttonext = d3.select(fills[ownFillEl3 ? 0 : 1]); + + console.log('ownFillEl3:', ownFillEl3); + console.log('nexttonext:', nexttonext); if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { pathfn = Drawing.steps(line.shape); @@ -193,10 +196,16 @@ module.exports = function animate (gd, trace, data, opts) { // fill to zero: full trace path, plus extension of // the endpoints to the appropriate axis - ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + ownFillEl3.transition() + .duration(transitionDuration) + .ease(transitionEasing) + .attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); } // fill to self: just join the path to itself - else ownFillEl3.attr('d', fullpath + 'Z'); + else ownFillEl3.transition() + .duration(transitionDuration) + .ease(transitionEasing) + .attr('d', fullpath + 'Z'); } } else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { @@ -206,7 +215,10 @@ module.exports = function animate (gd, trace, data, opts) { // contours, we just add the two paths closed on themselves. // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. - tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); + tonext.transition() + .duration(transitionDuration) + .ease(transitionEasing) + .attr('d', fullpath + 'Z' + prevpath + 'Z'); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -214,7 +226,10 @@ module.exports = function animate (gd, trace, data, opts) { // y/x, but if they *aren't*, we should ideally do more complicated // things depending on whether the new endpoint projects onto the // existing curve or off the end of it - tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + tonext.transition() + .duration(transitionDuration) + .ease(transitionEasing) + .attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); } } prevpath = revpath; diff --git a/src/traces/scatter/line_points.js b/src/traces/scatter/line_points.js index 60d7e3c77ea..df5e40bb7e3 100644 --- a/src/traces/scatter/line_points.js +++ b/src/traces/scatter/line_points.js @@ -60,7 +60,7 @@ module.exports = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length, yFrac = pt[1] / ya._length; - return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance * 0; } function ptDist(pt1, pt2) { diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 1547fbb43bb..0d901e64b3a 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -23,6 +23,8 @@ var linePoints = require('./line_points'); module.exports = function plot(gd, plotinfo, cdscatter) { selectMarkers(gd, plotinfo, cdscatter); + //console.log('value:', value); + var xa = plotinfo.x(), ya = plotinfo.y(); @@ -44,6 +46,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { ownFillEl3, ownFillDir, tonext, nexttonext; scattertraces.each(function(d) { + console.log('plot d:', d); var trace = d[0].trace, line = trace.line, tr = d3.select(this); From 1449cc511735e78312ef58885a2fa8d220fe7a97 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Thu, 9 Jun 2016 18:07:14 -0400 Subject: [PATCH 07/21] Partial trace refactor --- src/plot_api/plot_api.js | 22 ++ src/plots/cartesian/index.js | 30 ++- src/traces/scatter/index.js | 1 + src/traces/scatter/plot.js | 385 ++++++++++++++-------------- src/traces/scatter/set_positions.js | 45 ++++ 5 files changed, 284 insertions(+), 199 deletions(-) create mode 100644 src/traces/scatter/set_positions.js diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index f0c4e7037a5..3c02f0a2bdc 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1586,6 +1586,28 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { doCalcdata(gd, animatedTraces); + function doSetPositions () { + var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'); + var modules = fullLayout._modules; + + // position and range calculations for traces that + // depend on each other ie bars (stacked or grouped) + // and boxes (grouped) push each other out of the way + + var subplotInfo, _module; + + for(var i = 0; i < subplots.length; i++) { + subplotInfo = fullLayout._plots[subplots[i]]; + + for(var j = 0; j < modules.length; j++) { + _module = modules[j]; + if(_module.setPositions) _module.setPositions(gd, subplotInfo); + } + } + } + + doSetPositions(); + var animateList = []; var restyleList = []; diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index a50e77cf85d..dc74430ffce 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -11,6 +11,8 @@ var Plots = require('../plots'); +var d3 = require('d3'); + var constants = require('./constants'); exports.name = 'cartesian'; @@ -61,30 +63,36 @@ exports.plot = function(gd, animationConfig) { return cdModule; } + function keyFunc (d) { + return d[0].trace.uid; + } + for(var i = 0; i < subplots.length; i++) { var subplot = subplots[i], subplotInfo = fullLayout._plots[subplot], cdSubplot = getCdSubplot(calcdata, subplot); - // remove old traces, then redraw everything - // TODO: use enter/exit appropriately in the plot functions - // so we don't need this - should sometimes be a big speedup - if(!animationConfig && subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove(); - for(var j = 0; j < modules.length; j++) { var _module = modules[j]; - // skip over non-cartesian trace modules if(_module.basePlotModule.name !== 'cartesian') continue; // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); - if (animationConfig) { - _module.animate(gd, subplotInfo, cdModule, transtionOpts); - } else { - _module.plot(gd, subplotInfo, cdModule); - } + var tracelayer = subplotInfo.plot.select('g.' + _module.name + 'layer'); + var subplotJoin = tracelayer.selectAll('g.trace').data(cdModule, keyFunc); + + subplotJoin.enter() + .append('g') + .classed('trace', true) + .classed(_module.name, true) + .each(function(d) { + d[0].trace._module.plot(gd, subplotInfo, d, this) + }); + + subplotJoin.exit() + .remove() } } }; diff --git a/src/traces/scatter/index.js b/src/traces/scatter/index.js index 511e996711e..8606e0adf7d 100644 --- a/src/traces/scatter/index.js +++ b/src/traces/scatter/index.js @@ -23,6 +23,7 @@ Scatter.attributes = require('./attributes'); Scatter.supplyDefaults = require('./defaults'); Scatter.cleanData = require('./clean_data'); Scatter.calc = require('./calc'); +Scatter.setPositions = require('./set_positions'); Scatter.arraysToCalcdata = require('./arrays_to_calcdata'); Scatter.plot = require('./plot'); Scatter.colorbar = require('./colorbar'); diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 0d901e64b3a..8096c11b368 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -20,181 +20,189 @@ var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); -module.exports = function plot(gd, plotinfo, cdscatter) { +module.exports = function plot(gd, plotinfo, cdscatter, group) { selectMarkers(gd, plotinfo, cdscatter); - //console.log('value:', value); - var xa = plotinfo.x(), ya = plotinfo.y(); - // make the container for scatter plots - // (so error bars can find them along with bars) - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(cdscatter); + console.log('xa:', xa.range); + console.log('xa:', xa.domain); - scattertraces.enter().append('g') - .attr('class', 'trace scatter') - .style('stroke-miterlimit', 2); + var trace = cdscatter[0].trace, + line = trace.line, + tr = d3.select(group); + tr.style('stroke-miterlimit', 2); + + // (so error bars can find them along with bars) // error bars are at the bottom - scattertraces.call(ErrorBars.plot, plotinfo); + tr.call(ErrorBars.plot, plotinfo); + + if(trace.visible !== true) return; + // BUILD LINES AND FILLS - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext; - - scattertraces.each(function(d) { - console.log('plot d:', d); - var trace = d[0].trace, - line = trace.line, - tr = d3.select(this); - if(trace.visible !== true) return; - - ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; - - d[0].node3 = tr; // store node for tweaking by selectPoints - - arraysToCalcdata(d); - - if(!subTypes.hasLines(trace) && trace.fill === 'none') return; - - var thispath, - thisrevpath, - // fullpath is all paths for this curve, joined together straight - // across gaps, for filling - fullpath = '', - // revpath is fullpath reversed, for fill-to-next - revpath = '', - // functions for converting a point array to a path - pathfn, revpathbase, revpathfn; - - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous - if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevpath)) { - ownFillEl3 = tr.append('path') - .classed('js-fill', true); - } - else ownFillEl3 = null; - - // make the fill-to-next path now for the NEXT trace, so it shows - // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if(nexttonext) tonext = nexttonext.datum(d); - - // now make a new nexttonext for next time - nexttonext = tr.append('path').classed('js-fill', true); - - if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = Drawing.steps(line.shape); - revpathbase = Drawing.steps( - line.shape.split('').reverse().join('') - ); - } - else if(line.shape === 'spline') { - pathfn = revpathbase = function(pts) { - var pLast = pts[pts.length - 1]; - if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { - // identical start and end points: treat it as a - // closed curve so we don't get a kink - return Drawing.smoothclosed(pts.slice(1), line.smoothing); - } - else { - return Drawing.smoothopen(pts, line.smoothing); - } - }; - } - else { - pathfn = revpathbase = function(pts) { - return 'M' + pts.join('L'); - }; - } + var ownFillEl3, tonext, nexttonext; + + var ownFillDir = trace.fill.charAt(trace.fill.length - 1); + + if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; + + // store node for tweaking by selectPoints + cdscatter[0].node3 = tr; - revpathfn = function(pts) { - // note: this is destructive (reverses pts in place) so can't use pts after this - return revpathbase(pts.reverse()); + arraysToCalcdata(cdscatter); + + if(!subTypes.hasLines(trace) && trace.fill === 'none') return; + + var prevpath = ''; + var prevtrace = trace._prevtrace; + + if (prevtrace) { + prevpath = prevtrace._revpath || ''; + tonext = prevtrace._nexttonext; + } + + var thispath, + thisrevpath, + // fullpath is all paths for this curve, joined together straight + // across gaps, for filling + fullpath = '', + // revpath is fullpath reversed, for fill-to-next + revpath = '', + // functions for converting a point array to a path + pathfn, revpathbase, revpathfn; + + // make the fill-to-zero path now, so it shows behind the line + // fill to next puts the fill associated with one trace + // grouped with the previous + if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || + (trace.fill.substr(0, 2) === 'to' && !prevtrace)) { + ownFillEl3 = tr.append('path') + .classed('js-fill', true); + } else { + ownFillEl3 = null; + } + + // make the fill-to-next path now for the NEXT trace, so it shows + // behind both lines. + // nexttonext was created last time, but give it + // this curve's data for fill color + if (trace._nexttrace) { + trace._nexttonext = tr.append('path').classed('js-fill', true); + } + + if (tonext) { + // This tells .style which trace to use for fill information: + tonext.datum(cdscatter); + } + + if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { + pathfn = Drawing.steps(line.shape); + revpathbase = Drawing.steps( + line.shape.split('').reverse().join('') + ); + } + else if(line.shape === 'spline') { + pathfn = revpathbase = function(pts) { + var pLast = pts[pts.length - 1]; + if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { + // identical start and end points: treat it as a + // closed curve so we don't get a kink + return Drawing.smoothclosed(pts.slice(1), line.smoothing); + } + else { + return Drawing.smoothopen(pts, line.smoothing); + } }; + } + else { + pathfn = revpathbase = function(pts) { + return 'M' + pts.join('L'); + }; + } - var segments = linePoints(d, { - xaxis: xa, - yaxis: ya, - connectGaps: trace.connectgaps, - baseTolerance: Math.max(line.width || 1, 3) / 4, - linear: line.shape === 'linear' - }); + revpathfn = function(pts) { + // note: this is destructive (reverses pts in place) so can't use pts after this + return revpathbase(pts.reverse()); + }; + + var segments = linePoints(cdscatter, { + xaxis: xa, + yaxis: ya, + connectGaps: trace.connectgaps, + baseTolerance: Math.max(line.width || 1, 3) / 4, + linear: line.shape === 'linear' + }); - if(segments.length) { - var pt0 = segments[0][0], - lastSegment = segments[segments.length - 1], - pt1 = lastSegment[lastSegment.length - 1]; - - for(var i = 0; i < segments.length; i++) { - var pts = segments[i]; - thispath = pathfn(pts); - thisrevpath = revpathfn(pts); - if(!fullpath) { - fullpath = thispath; - revpath = thisrevpath; - } - else if(ownFillDir) { - fullpath += 'L' + thispath.substr(1); - revpath = thisrevpath + ('L' + revpath.substr(1)); - } - else { - fullpath += 'Z' + thispath; - revpath = thisrevpath + 'Z' + revpath; - } - if(subTypes.hasLines(trace) && pts.length > 1) { - tr.append('path').classed('js-line', true).attr('d', thispath); - } + if(segments.length) { + var pt0 = segments[0][0], + lastSegment = segments[segments.length - 1], + pt1 = lastSegment[lastSegment.length - 1]; + + for(var i = 0; i < segments.length; i++) { + var pts = segments[i]; + thispath = pathfn(pts); + thisrevpath = revpathfn(pts); + if(!fullpath) { + fullpath = thispath; + revpath = thisrevpath; + } + else if(ownFillDir) { + fullpath += 'L' + thispath.substr(1); + revpath = thisrevpath + ('L' + revpath.substr(1)); + } + else { + fullpath += 'Z' + thispath; + revpath = thisrevpath + 'Z' + revpath; } - if(ownFillEl3) { - if(pt0 && pt1) { - if(ownFillDir) { - if(ownFillDir === 'y') { - pt0[1] = pt1[1] = ya.c2p(0, true); - } - else if(ownFillDir === 'x') { - pt0[0] = pt1[0] = xa.c2p(0, true); - } - - // fill to zero: full trace path, plus extension of - // the endpoints to the appropriate axis - ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + if(subTypes.hasLines(trace) && pts.length > 1) { + tr.append('path').classed('js-line', true).attr('d', thispath); + } + } + if(ownFillEl3) { + if(pt0 && pt1) { + if(ownFillDir) { + if(ownFillDir === 'y') { + pt0[1] = pt1[1] = ya.c2p(0, true); + } + else if(ownFillDir === 'x') { + pt0[0] = pt1[0] = xa.c2p(0, true); } - // fill to self: just join the path to itself - else ownFillEl3.attr('d', fullpath + 'Z'); + + // fill to zero: full trace path, plus extension of + // the endpoints to the appropriate axis + ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); } + // fill to self: just join the path to itself + else ownFillEl3.attr('d', fullpath + 'Z'); } - else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { - // fill to next: full trace path, plus the previous path reversed - if(trace.fill === 'tonext') { - // tonext: for use by concentric shapes, like manually constructed - // contours, we just add the two paths closed on themselves. - // This makes strange results if one path is *not* entirely - // inside the other, but then that is a strange usage. - tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); - } - else { - // tonextx/y: for now just connect endpoints with lines. This is - // the correct behavior if the endpoints are at the same value of - // y/x, but if they *aren't*, we should ideally do more complicated - // things depending on whether the new endpoint projects onto the - // existing curve or off the end of it - tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); - } + } + else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { + // fill to next: full trace path, plus the previous path reversed + if(trace.fill === 'tonext') { + // tonext: for use by concentric shapes, like manually constructed + // contours, we just add the two paths closed on themselves. + // This makes strange results if one path is *not* entirely + // inside the other, but then that is a strange usage. + tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); + } + else { + // tonextx/y: for now just connect endpoints with lines. This is + // the correct behavior if the endpoints are at the same value of + // y/x, but if they *aren't*, we should ideally do more complicated + // things depending on whether the new endpoint projects onto the + // existing curve or off the end of it + tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); } - prevpath = revpath; } - }); + } + + trace._revpath = revpath; // remove paths that didn't get used - scattertraces.selectAll('path:not([d])').remove(); + //tr.selectAll('path:not([d])').remove(); function visFilter(d) { return d.filter(function(v) { return v.vis; }); @@ -210,7 +218,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { } } - scattertraces.append('g') + tr.append('g') .attr('class', 'points') .each(function(d) { var trace = d[0].trace, @@ -246,40 +254,41 @@ function selectMarkers(gd, plotinfo, cdscatter) { xr = d3.extent(xa.range.map(xa.l2c)), yr = d3.extent(ya.range.map(ya.l2c)); - cdscatter.forEach(function(d, i) { - var trace = d[0].trace; - if(!subTypes.hasMarkers(trace)) return; - // if marker.maxdisplayed is used, select a maximum of - // mnum markers to show, from the set that are in the viewport - var mnum = trace.marker.maxdisplayed; - - // TODO: remove some as we get away from the viewport? - if(mnum === 0) return; - - var cd = d.filter(function(v) { - return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; - }), - inc = Math.ceil(cd.length / mnum), - tnum = 0; - cdscatter.forEach(function(cdj, j) { - var tracei = cdj[0].trace; - if(subTypes.hasMarkers(tracei) && - tracei.marker.maxdisplayed > 0 && j < i) { - tnum++; - } - }); + // XXX: Not okay. Just makes it work for now. + var i = 0; + + var trace = cdscatter[0].trace; + if(!subTypes.hasMarkers(trace)) return; + // if marker.maxdisplayed is used, select a maximum of + // mnum markers to show, from the set that are in the viewport + var mnum = trace.marker.maxdisplayed; + + // TODO: remove some as we get away from the viewport? + if(mnum === 0) return; + + var cd = cdscatter.filter(function(v) { + return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; + }), + inc = Math.ceil(cd.length / mnum), + tnum = 0; + cdscatter.forEach(function(cdj, j) { + var tracei = cdj[0].trace; + if(subTypes.hasMarkers(tracei) && + tracei.marker.maxdisplayed > 0 && j < i) { + tnum++; + } + }); - // if multiple traces use maxdisplayed, stagger which markers we - // display this formula offsets successive traces by 1/3 of the - // increment, adding an extra small amount after each triplet so - // it's not quite periodic - var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); - - // for error bars: save in cd which markers to show - // so we don't have to repeat this - d.forEach(function(v) { delete v.vis; }); - cd.forEach(function(v, i) { - if(Math.round((i + i0) % inc) === 0) v.vis = true; - }); + // if multiple traces use maxdisplayed, stagger which markers we + // display this formula offsets successive traces by 1/3 of the + // increment, adding an extra small amount after each triplet so + // it's not quite periodic + var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); + + // for error bars: save in cd which markers to show + // so we don't have to repeat this + cdscatter.forEach(function(v) { delete v.vis; }); + cd.forEach(function(v, i) { + if(Math.round((i + i0) % inc) === 0) v.vis = true; }); } diff --git a/src/traces/scatter/set_positions.js b/src/traces/scatter/set_positions.js new file mode 100644 index 00000000000..15cd0260216 --- /dev/null +++ b/src/traces/scatter/set_positions.js @@ -0,0 +1,45 @@ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); +var Axes = require('../../plots/cartesian/axes'); +var Lib = require('../../lib'); + +/** + * setPositions is a bit of a misnomer here. It comes from the box plot + * type that actually does setting of positions. It's the hook though + * that we need to set up links between traces so that trace-level .plot + * doesn't require any links between traces. + */ +module.exports = function setPositions(gd, plotinfo) { + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < gd.calcdata.length; ++i) { + cd = gd.calcdata[i]; + trace = cd[0].trace; + + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + prevtrace._nexttrace = trace; + } + + prevtrace = trace; + } + } +}; From 99b4bed5cea53dab6013042a2262ab2cdbdaaf99 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Fri, 10 Jun 2016 12:30:19 -0400 Subject: [PATCH 08/21] Scattertrace element persistence cleanup --- src/plots/cartesian/index.js | 8 ++- src/traces/scatter/plot.js | 116 ++++++++++++++++++++++------------- 2 files changed, 82 insertions(+), 42 deletions(-) diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index dc74430ffce..5ee39c62dfe 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -27,7 +27,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd, animationConfig) { +exports.plot = function(gd, transitionOpts) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -91,6 +91,12 @@ exports.plot = function(gd, animationConfig) { d[0].trace._module.plot(gd, subplotInfo, d, this) }); + subplotJoin.transition() + .each(function(d) { + d[0].trace._module.plot(gd, subplotInfo, d, this, transitionOpts) + }); + + subplotJoin.exit() .remove() } diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 8096c11b368..bf83b48b818 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -20,15 +20,23 @@ var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); -module.exports = function plot(gd, plotinfo, cdscatter, group) { +module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { selectMarkers(gd, plotinfo, cdscatter); + transitionOpts = transitionOpts || {}; + + var transitionDuration = transitionOpts.duration === undefined ? 0 : transitionOpts.duration; + var transitionEasing = transitionOpts.easing === undefined ? 'in-out-cubic' : transitionOpts.easing; + + function transition (selection) { + return selection.transition() + .duration(transitionDuration) + .ease(transitionEasing); + } + var xa = plotinfo.x(), ya = plotinfo.y(); - console.log('xa:', xa.range); - console.log('xa:', xa.domain); - var trace = cdscatter[0].trace, line = trace.line, tr = d3.select(group); @@ -44,9 +52,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { // BUILD LINES AND FILLS var ownFillEl3, tonext, nexttonext; - var ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; // store node for tweaking by selectPoints @@ -79,9 +85,12 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { // grouped with the previous if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || (trace.fill.substr(0, 2) === 'to' && !prevtrace)) { - ownFillEl3 = tr.append('path') - .classed('js-fill', true); + ownFillEl3 = tr.select('.js-fill.js-tozero'); + if (!ownFillEl3.size()) { + ownFillEl3 = tr.append('path').attr('class', 'js-fill js-tozero'); + } } else { + tr.selectAll('.js-fill.js-tozero').remove(); ownFillEl3 = null; } @@ -90,7 +99,13 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { // nexttonext was created last time, but give it // this curve's data for fill color if (trace._nexttrace) { - trace._nexttonext = tr.append('path').classed('js-fill', true); + trace._nexttonext = tr.select('.js-fill.js-tonext'); + if (!trace._nexttonext.size()) { + trace._nexttonext = tr.append('path').attr('class', 'js-fill js-tonext'); + } + } else { + tr.selectAll('.js-fill.js-tonext').remove(); + trace._nexttonext = null; } if (tonext) { @@ -158,7 +173,12 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { revpath = thisrevpath + 'Z' + revpath; } if(subTypes.hasLines(trace) && pts.length > 1) { - tr.append('path').classed('js-line', true).attr('d', thispath); + var lineJoin = tr.selectAll('.js-line').data([cdscatter]); + + lineJoin.enter() + .append('path').classed('js-line', true).attr('d', thispath); + + transition(lineJoin).attr('d', thispath); } } if(ownFillEl3) { @@ -173,10 +193,11 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { // fill to zero: full trace path, plus extension of // the endpoints to the appropriate axis - ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + transition(ownFillEl3).attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + } else { + // fill to self: just join the path to itself + transition(ownFillEl3).attr('d', fullpath + 'Z'); } - // fill to self: just join the path to itself - else ownFillEl3.attr('d', fullpath + 'Z'); } } else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { @@ -186,7 +207,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { // contours, we just add the two paths closed on themselves. // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. - tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); + transition(tonext).attr('d', fullpath + 'Z' + prevpath + 'Z'); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -194,7 +215,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { // y/x, but if they *aren't*, we should ideally do more complicated // things depending on whether the new endpoint projects onto the // existing curve or off the end of it - tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + transition(tonext).attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); } } } @@ -218,34 +239,47 @@ module.exports = function plot(gd, plotinfo, cdscatter, group) { } } - tr.append('g') - .attr('class', 'points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) - .enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya); - } - if(showText) { - s.selectAll('g') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - // each text needs to go in its own 'g' in case - // it gets converted to mathjax - .enter().append('g') - .append('text') - .call(Drawing.translatePoints, xa, ya); - } + function makePoints (d) { + var trace = d[0].trace, + s = d3.select(this), + showMarkers = subTypes.hasMarkers(trace), + showText = subTypes.hasText(trace); + + if((!showMarkers && !showText) || trace.visible !== true) s.remove(); + else { + if(showMarkers) { + var join = s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) + + join.enter().append('path') + .classed('point', true) + .call(Drawing.translatePoints, xa, ya); + + join.transition() + .duration(0) + .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 0, 0, 0); } - }); + if(showText) { + s.selectAll('g') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + // each text needs to go in its own 'g' in case + // it gets converted to mathjax + .enter().append('g') + .append('text') + .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 0, 0, 0); + } + } + } + + var pointJoin = tr.selectAll('.points').data([cdscatter]); + + pointJoin.enter().append('g') + .classed('points', true) + .each(makePoints); + + pointJoin.transition() + .each(makePoints); }; function selectMarkers(gd, plotinfo, cdscatter) { From 7285a0a5c7f67844ffc91046af137410f6d42014 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Sat, 11 Jun 2016 17:27:27 -0400 Subject: [PATCH 09/21] Further animation progress and cleanup --- .editorconfig | 3 + src/components/drawing/index.js | 31 ++-- src/plot_api/plot_api.js | 9 +- src/plots/cartesian/index.js | 3 + src/traces/scatter/plot.js | 231 +++++++++++++++------------- src/traces/scatter/set_positions.js | 5 +- 6 files changed, 155 insertions(+), 127 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000000..16ff240eee5 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,3 @@ +[*.js] +indent_style = space +indent_size = 4 diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 96ceb571373..78ba1ae2407 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -46,7 +46,14 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasing, trace, dir, transitionDelay, transitionCascade) { +drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { + + var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; + + if (hasTransition) { + var size = s.size(); + } + s.each(function(d, i) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), @@ -57,26 +64,26 @@ drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasi if(this.nodeName==='text') { p.attr('x',x).attr('y',y); } else { - if (isNumeric(transitionDuration) && transitionDuration > 0) { + if (hasTransition) { var trans; - if (!dir) { + if (!transitionConfig.direction) { trans = p.transition() - .delay(transitionDelay + transitionCascade * i) - .duration(transitionDuration) - .ease(transitionEasing) + .delay(transitionConfig.delay + transitionConfig.cascade / size * i) + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) .attr('transform', 'translate('+x+','+y+')') if (trace) { trans.call(drawing.pointStyle, trace) } - } else if (dir === -1) { + } else if (transitionConfig.direction === -1) { trans = p.style('opacity', 1) .transition() - .duration(transitionDuration) - .ease(transitionEasing) + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) .style('opacity', 0) .remove(); - } else if (dir === 1) { + } else if (transitionConfig.direction === 1) { trans = p.attr('transform', 'translate('+x+','+y+')') if (trace) { @@ -85,8 +92,8 @@ drawing.translatePoints = function(s, xa, ya, transitionDuration, transitionEasi trans.style('opacity', 0) .transition() - .duration(transitionDuration) - .ease(transitionEasing) + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) .style('opacity', 1) } diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 3c02f0a2bdc..70eb4bd9799 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1611,16 +1611,17 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var animateList = []; var restyleList = []; + function doAnimations () { - var a; + var a, i, j; for (i = 0; i < animateList.length; i++) { a = animateList[i]; - //a.module.animate(gd, a.contFull, a.newData, transitionOpts); var basePlotModules = fullLayout._basePlotModules; - for(i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd, transitionOpts); + for(j = 0; j < basePlotModules.length; j++) { + basePlotModules[j].plot(gd, transitionOpts); } } + if (!transitionOpts.leadingEdgeRestyle) { return new Promise(function(resolve, reject) { setTimeout(resolve, transitionOpts.duration); diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index 5ee39c62dfe..384142aadf6 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -74,6 +74,9 @@ exports.plot = function(gd, transitionOpts) { for(var j = 0; j < modules.length; j++) { var _module = modules[j]; + + if(_module.setPositions) _module.setPositions(gd, subplotInfo); + // skip over non-cartesian trace modules if(_module.basePlotModule.name !== 'cartesian') continue; diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index bf83b48b818..33137418f3a 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -23,15 +23,20 @@ var linePoints = require('./line_points'); module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { selectMarkers(gd, plotinfo, cdscatter); - transitionOpts = transitionOpts || {}; + var transitionConfig = Lib.extendFlat({}, transitionOpts || {}); + transitionConfig = Lib.extendFlat({ + duration: 0, + easing: 'in-out-cubic', + cascade: 0, + delay: 0, + }, transitionConfig); - var transitionDuration = transitionOpts.duration === undefined ? 0 : transitionOpts.duration; - var transitionEasing = transitionOpts.easing === undefined ? 'in-out-cubic' : transitionOpts.easing; + var hasTransition = transitionConfig.duration > 0; function transition (selection) { return selection.transition() - .duration(transitionDuration) - .ease(transitionEasing); + .duration(transitionConfig.duration) + .ease(transitionConfig.easing); } var xa = plotinfo.x(), @@ -60,8 +65,6 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { arraysToCalcdata(cdscatter); - if(!subTypes.hasLines(trace) && trace.fill === 'none') return; - var prevpath = ''; var prevtrace = trace._prevtrace; @@ -80,6 +83,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // functions for converting a point array to a path pathfn, revpathbase, revpathfn; + // make the fill-to-zero path now, so it shows behind the line // fill to next puts the fill associated with one trace // grouped with the previous @@ -108,119 +112,123 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { trace._nexttonext = null; } - if (tonext) { - // This tells .style which trace to use for fill information: - tonext.datum(cdscatter); - } + if(subTypes.hasLines(trace) || trace.fill !== 'none') { - if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = Drawing.steps(line.shape); - revpathbase = Drawing.steps( - line.shape.split('').reverse().join('') - ); - } - else if(line.shape === 'spline') { - pathfn = revpathbase = function(pts) { - var pLast = pts[pts.length - 1]; - if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { - // identical start and end points: treat it as a - // closed curve so we don't get a kink - return Drawing.smoothclosed(pts.slice(1), line.smoothing); - } - else { - return Drawing.smoothopen(pts, line.smoothing); - } - }; - } - else { - pathfn = revpathbase = function(pts) { - return 'M' + pts.join('L'); - }; - } + if (tonext) { + // This tells .style which trace to use for fill information: + tonext.datum(cdscatter); + } - revpathfn = function(pts) { - // note: this is destructive (reverses pts in place) so can't use pts after this - return revpathbase(pts.reverse()); - }; - - var segments = linePoints(cdscatter, { - xaxis: xa, - yaxis: ya, - connectGaps: trace.connectgaps, - baseTolerance: Math.max(line.width || 1, 3) / 4, - linear: line.shape === 'linear' - }); + if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { + pathfn = Drawing.steps(line.shape); + revpathbase = Drawing.steps( + line.shape.split('').reverse().join('') + ); + } + else if(line.shape === 'spline') { + pathfn = revpathbase = function(pts) { + var pLast = pts[pts.length - 1]; + if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { + // identical start and end points: treat it as a + // closed curve so we don't get a kink + return Drawing.smoothclosed(pts.slice(1), line.smoothing); + } + else { + return Drawing.smoothopen(pts, line.smoothing); + } + }; + } + else { + pathfn = revpathbase = function(pts) { + return 'M' + pts.join('L'); + }; + } - if(segments.length) { - var pt0 = segments[0][0], - lastSegment = segments[segments.length - 1], - pt1 = lastSegment[lastSegment.length - 1]; - - for(var i = 0; i < segments.length; i++) { - var pts = segments[i]; - thispath = pathfn(pts); - thisrevpath = revpathfn(pts); - if(!fullpath) { - fullpath = thispath; - revpath = thisrevpath; - } - else if(ownFillDir) { - fullpath += 'L' + thispath.substr(1); - revpath = thisrevpath + ('L' + revpath.substr(1)); - } - else { - fullpath += 'Z' + thispath; - revpath = thisrevpath + 'Z' + revpath; - } - if(subTypes.hasLines(trace) && pts.length > 1) { - var lineJoin = tr.selectAll('.js-line').data([cdscatter]); + revpathfn = function(pts) { + // note: this is destructive (reverses pts in place) so can't use pts after this + return revpathbase(pts.reverse()); + }; - lineJoin.enter() - .append('path').classed('js-line', true).attr('d', thispath); + var segments = linePoints(cdscatter, { + xaxis: xa, + yaxis: ya, + connectGaps: trace.connectgaps, + baseTolerance: Math.max(line.width || 1, 3) / 4, + linear: line.shape === 'linear' + }); + + if(segments.length) { + var pt0 = segments[0][0], + lastSegment = segments[segments.length - 1], + pt1 = lastSegment[lastSegment.length - 1]; + + for(var i = 0; i < segments.length; i++) { + var pts = segments[i]; + thispath = pathfn(pts); + thisrevpath = revpathfn(pts); + if(!fullpath) { + fullpath = thispath; + revpath = thisrevpath; + } + else if(ownFillDir) { + fullpath += 'L' + thispath.substr(1); + revpath = thisrevpath + ('L' + revpath.substr(1)); + } + else { + fullpath += 'Z' + thispath; + revpath = thisrevpath + 'Z' + revpath; + } + if(subTypes.hasLines(trace) && pts.length > 1) { + var lineJoin = tr.selectAll('.js-line').data([cdscatter]); - transition(lineJoin).attr('d', thispath); - } - } - if(ownFillEl3) { - if(pt0 && pt1) { - if(ownFillDir) { - if(ownFillDir === 'y') { - pt0[1] = pt1[1] = ya.c2p(0, true); - } - else if(ownFillDir === 'x') { - pt0[0] = pt1[0] = xa.c2p(0, true); - } + lineJoin.enter() + .append('path').classed('js-line', true).attr('d', thispath); - // fill to zero: full trace path, plus extension of - // the endpoints to the appropriate axis - transition(ownFillEl3).attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); - } else { - // fill to self: just join the path to itself - transition(ownFillEl3).attr('d', fullpath + 'Z'); + transition(lineJoin).attr('d', thispath); } } - } - else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { - // fill to next: full trace path, plus the previous path reversed - if(trace.fill === 'tonext') { - // tonext: for use by concentric shapes, like manually constructed - // contours, we just add the two paths closed on themselves. - // This makes strange results if one path is *not* entirely - // inside the other, but then that is a strange usage. - transition(tonext).attr('d', fullpath + 'Z' + prevpath + 'Z'); + if(ownFillEl3) { + if(pt0 && pt1) { + if(ownFillDir) { + if(ownFillDir === 'y') { + pt0[1] = pt1[1] = ya.c2p(0, true); + } + else if(ownFillDir === 'x') { + pt0[0] = pt1[0] = xa.c2p(0, true); + } + + // fill to zero: full trace path, plus extension of + // the endpoints to the appropriate axis + transition(ownFillEl3).attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + } else { + // fill to self: just join the path to itself + transition(ownFillEl3).attr('d', fullpath + 'Z'); + } + } } - else { - // tonextx/y: for now just connect endpoints with lines. This is - // the correct behavior if the endpoints are at the same value of - // y/x, but if they *aren't*, we should ideally do more complicated - // things depending on whether the new endpoint projects onto the - // existing curve or off the end of it - transition(tonext).attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { + // fill to next: full trace path, plus the previous path reversed + if(trace.fill === 'tonext') { + // tonext: for use by concentric shapes, like manually constructed + // contours, we just add the two paths closed on themselves. + // This makes strange results if one path is *not* entirely + // inside the other, but then that is a strange usage. + transition(tonext).attr('d', fullpath + 'Z' + prevpath + 'Z'); + } + else { + // tonextx/y: for now just connect endpoints with lines. This is + // the correct behavior if the endpoints are at the same value of + // y/x, but if they *aren't*, we should ideally do more complicated + // things depending on whether the new endpoint projects onto the + // existing curve or off the end of it + transition(tonext).attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + } } } + + trace._revpath = revpath; } - trace._revpath = revpath; // remove paths that didn't get used //tr.selectAll('path:not([d])').remove(); @@ -254,11 +262,14 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { join.enter().append('path') .classed('point', true) - .call(Drawing.translatePoints, xa, ya); + .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace) join.transition() .duration(0) - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 0, 0, 0); + .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace); + + join.exit() + .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); } if(showText) { s.selectAll('g') @@ -267,7 +278,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // it gets converted to mathjax .enter().append('g') .append('text') - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 0, 0, 0); + .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace); } } } diff --git a/src/traces/scatter/set_positions.js b/src/traces/scatter/set_positions.js index 15cd0260216..a8031b8fa19 100644 --- a/src/traces/scatter/set_positions.js +++ b/src/traces/scatter/set_positions.js @@ -36,7 +36,10 @@ module.exports = function setPositions(gd, plotinfo) { if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { trace._prevtrace = prevtrace; - prevtrace._nexttrace = trace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } } prevtrace = trace; From 8dc302c2703d05907f155c606aa4f8f7aa4109ed Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Sat, 11 Jun 2016 23:34:19 -0400 Subject: [PATCH 10/21] Scatter trace optimization --- src/components/drawing/index.js | 9 +++++---- src/plot_api/plot_api.js | 2 ++ src/traces/scatter/plot.js | 14 +++++++++++--- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 78ba1ae2407..1f0c35721fa 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -50,6 +50,7 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; + if (hasTransition) { var size = s.size(); } @@ -98,7 +99,7 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { } } else { - p.attr('transform', 'translate('+x+','+y+')'); + p.attr('transform', 'translate('+x+','+y+')'); } } } @@ -263,7 +264,7 @@ drawing.pointStyle = function(s, trace) { markerScale = drawing.tryColorscale(marker, markerIn, ''), lineScale = drawing.tryColorscale(marker, markerIn, 'line.'); - s.each(function(d) { + s.each(function(d, i) { // 'so' is suspected outliers, for box plots var fillColor, lineColor, @@ -280,11 +281,11 @@ drawing.pointStyle = function(s, trace) { if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(Array.isArray(markerLine.color)) lineColor = Color.defaultLine; + else if(Array.isArray(markerLine.color)) lineColor = marker.color[i]; else lineColor = markerLine.color; if('mc' in d) fillColor = d.mcc = markerScale(d.mc); - else if(Array.isArray(marker.color)) fillColor = Color.defaultLine; + else if(Array.isArray(marker.color)) fillColor = marker.color[i]; else fillColor = marker.color || 'rgba(0,0,0,0)'; } diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 70eb4bd9799..8966b066858 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1529,6 +1529,8 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { // 4. doCalcdata // 5. begin animation Plotly.animate = function animate (gd, newData, transitionOpts, traces) { + gd = getGraphDiv(gd); + var fullLayout = gd._fullLayout; var i, newTraceData, curData, value, traceIdx; diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 33137418f3a..08344a968ea 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -46,6 +46,8 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { line = trace.line, tr = d3.select(group); + /* + tr.style('stroke-miterlimit', 2); // (so error bars can find them along with bars) @@ -232,6 +234,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // remove paths that didn't get used //tr.selectAll('path:not([d])').remove(); + */ function visFilter(d) { return d.filter(function(v) { return v.vis; }); @@ -263,13 +266,15 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { join.enter().append('path') .classed('point', true) .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace) + .call(Drawing.pointStyle, trace) join.transition() .duration(0) - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace); + .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace) + .call(Drawing.pointStyle, trace) - join.exit() - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); + join.exit().remove(); + //.call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); } if(showText) { s.selectAll('g') @@ -290,7 +295,10 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { .each(makePoints); pointJoin.transition() + .duration(0) .each(makePoints); + + pointJoin.exit().remove(); }; function selectMarkers(gd, plotinfo, cdscatter) { From 5a624de94baec95a5120a1fc9d4eb5e67cd5e097 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Sat, 11 Jun 2016 23:34:19 -0400 Subject: [PATCH 11/21] Scatter trace optimization --- src/components/drawing/index.js | 9 +++++---- src/plot_api/plot_api.js | 4 ++++ src/plots/cartesian/index.js | 2 -- src/traces/scatter/plot.js | 16 ++++++++++++---- src/traces/scatter/set_positions.js | 10 ++++++++++ 5 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 78ba1ae2407..1f0c35721fa 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -50,6 +50,7 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; + if (hasTransition) { var size = s.size(); } @@ -98,7 +99,7 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { } } else { - p.attr('transform', 'translate('+x+','+y+')'); + p.attr('transform', 'translate('+x+','+y+')'); } } } @@ -263,7 +264,7 @@ drawing.pointStyle = function(s, trace) { markerScale = drawing.tryColorscale(marker, markerIn, ''), lineScale = drawing.tryColorscale(marker, markerIn, 'line.'); - s.each(function(d) { + s.each(function(d, i) { // 'so' is suspected outliers, for box plots var fillColor, lineColor, @@ -280,11 +281,11 @@ drawing.pointStyle = function(s, trace) { if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(Array.isArray(markerLine.color)) lineColor = Color.defaultLine; + else if(Array.isArray(markerLine.color)) lineColor = marker.color[i]; else lineColor = markerLine.color; if('mc' in d) fillColor = d.mcc = markerScale(d.mc); - else if(Array.isArray(marker.color)) fillColor = Color.defaultLine; + else if(Array.isArray(marker.color)) fillColor = marker.color[i]; else fillColor = marker.color || 'rgba(0,0,0,0)'; } diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 70eb4bd9799..5a0fcd53f91 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1529,6 +1529,8 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { // 4. doCalcdata // 5. begin animation Plotly.animate = function animate (gd, newData, transitionOpts, traces) { + gd = getGraphDiv(gd); + var fullLayout = gd._fullLayout; var i, newTraceData, curData, value, traceIdx; @@ -1597,9 +1599,11 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var subplotInfo, _module; for(var i = 0; i < subplots.length; i++) { + console.log('i:', i); subplotInfo = fullLayout._plots[subplots[i]]; for(var j = 0; j < modules.length; j++) { + console.log('j:', j); _module = modules[j]; if(_module.setPositions) _module.setPositions(gd, subplotInfo); } diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index 384142aadf6..791a2f9c2e8 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -75,8 +75,6 @@ exports.plot = function(gd, transitionOpts) { for(var j = 0; j < modules.length; j++) { var _module = modules[j]; - if(_module.setPositions) _module.setPositions(gd, subplotInfo); - // skip over non-cartesian trace modules if(_module.basePlotModule.name !== 'cartesian') continue; diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 33137418f3a..e54564c0922 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -46,6 +46,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { line = trace.line, tr = d3.select(group); + console.log('start plot of ', trace.uid); tr.style('stroke-miterlimit', 2); // (so error bars can find them along with bars) @@ -54,7 +55,6 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { if(trace.visible !== true) return; - // BUILD LINES AND FILLS var ownFillEl3, tonext, nexttonext; var ownFillDir = trace.fill.charAt(trace.fill.length - 1); @@ -72,6 +72,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { prevpath = prevtrace._revpath || ''; tonext = prevtrace._nexttonext; } + console.log(trace.uid, trace._prevtrace && trace._prevtrace.uid, 'prevtrace:', prevtrace, tonext); var thispath, thisrevpath, @@ -103,11 +104,13 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // nexttonext was created last time, but give it // this curve's data for fill color if (trace._nexttrace) { + console.log(trace.uid, 'has nexttrace'); trace._nexttonext = tr.select('.js-fill.js-tonext'); if (!trace._nexttonext.size()) { trace._nexttonext = tr.append('path').attr('class', 'js-fill js-tonext'); } } else { + console.log(trace.uid, 'does not have nexttrace'); tr.selectAll('.js-fill.js-tonext').remove(); trace._nexttonext = null; } @@ -263,13 +266,15 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { join.enter().append('path') .classed('point', true) .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace) + .call(Drawing.pointStyle, trace) join.transition() .duration(0) - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace); + .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace) + .call(Drawing.pointStyle, trace) - join.exit() - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); + join.exit().remove(); + //.call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); } if(showText) { s.selectAll('g') @@ -290,7 +295,10 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { .each(makePoints); pointJoin.transition() + .duration(0) .each(makePoints); + + pointJoin.exit().remove(); }; function selectMarkers(gd, plotinfo, cdscatter) { diff --git a/src/traces/scatter/set_positions.js b/src/traces/scatter/set_positions.js index a8031b8fa19..15a2261795e 100644 --- a/src/traces/scatter/set_positions.js +++ b/src/traces/scatter/set_positions.js @@ -19,6 +19,7 @@ var Lib = require('../../lib'); * doesn't require any links between traces. */ module.exports = function setPositions(gd, plotinfo) { + console.log('setPositions:', plotinfo); var i, cd, trace; var fullLayout = gd._fullLayout; var xa = plotinfo.x(); @@ -30,10 +31,13 @@ module.exports = function setPositions(gd, plotinfo) { cd = gd.calcdata[i]; trace = cd[0].trace; + console.log('visible:', trace.uid, trace.visible); if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && trace.xaxis === xa._id && trace.yaxis === ya._id) { + trace._nexttrace = null; + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { trace._prevtrace = prevtrace; @@ -43,6 +47,12 @@ module.exports = function setPositions(gd, plotinfo) { } prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; } } + for(i = 0; i < gd.calcdata.length; ++i) { + var trace = gd.calcdata[i][0].trace; + console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + } }; From 81e2182fcc030ff0cdbab4fb4a860dfa1f7e9c1f Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Tue, 14 Jun 2016 12:42:23 -0400 Subject: [PATCH 12/21] Refactor scatter traces --- src/components/drawing/index.js | 8 +- src/plot_api/plot_api.js | 13 +- src/plots/cartesian/index.js | 38 ++-- src/traces/scatter/animate.js | 309 ---------------------------- src/traces/scatter/calc.js | 2 +- src/traces/scatter/link_traces.js | 50 +++++ src/traces/scatter/plot.js | 155 +++++++++----- src/traces/scatter/set_positions.js | 6 +- 8 files changed, 185 insertions(+), 396 deletions(-) delete mode 100644 src/traces/scatter/animate.js create mode 100644 src/traces/scatter/link_traces.js diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 1f0c35721fa..8ff37c0ad7b 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -46,7 +46,7 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { +drawing.translatePoints = function(s, xa, ya, trace, transitionConfig, joinDirection) { var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; @@ -67,7 +67,7 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { } else { if (hasTransition) { var trans; - if (!transitionConfig.direction) { + if (!joinDirection) { trans = p.transition() .delay(transitionConfig.delay + transitionConfig.cascade / size * i) .duration(transitionConfig.duration) @@ -77,14 +77,14 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { if (trace) { trans.call(drawing.pointStyle, trace) } - } else if (transitionConfig.direction === -1) { + } else if (joinDirection === -1) { trans = p.style('opacity', 1) .transition() .duration(transitionConfig.duration) .ease(transitionConfig.easing) .style('opacity', 0) .remove(); - } else if (transitionConfig.direction === 1) { + } else if (joinDirection === 1) { trans = p.attr('transform', 'translate('+x+','+y+')') if (trace) { diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 5a0fcd53f91..7307e7a1575 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1599,11 +1599,9 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var subplotInfo, _module; for(var i = 0; i < subplots.length; i++) { - console.log('i:', i); subplotInfo = fullLayout._plots[subplots[i]]; for(var j = 0; j < modules.length; j++) { - console.log('j:', j); _module = modules[j]; if(_module.setPositions) _module.setPositions(gd, subplotInfo); } @@ -1618,14 +1616,11 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { function doAnimations () { var a, i, j; - for (i = 0; i < animateList.length; i++) { - a = animateList[i]; - var basePlotModules = fullLayout._basePlotModules; - for(j = 0; j < basePlotModules.length; j++) { - basePlotModules[j].plot(gd, transitionOpts); - } + var animatableModules = []; + var basePlotModules = fullLayout._basePlotModules; + for(j = 0; j < basePlotModules.length; j++) { + basePlotModules[j].plot(gd, animatedTraces, transitionOpts); } - if (!transitionOpts.leadingEdgeRestyle) { return new Promise(function(resolve, reject) { setTimeout(resolve, transitionOpts.duration); diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index 791a2f9c2e8..544ac495ca4 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -27,7 +27,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd, transitionOpts) { +exports.plot = function(gd, traces, transitionOpts) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -40,6 +40,9 @@ exports.plot = function(gd, transitionOpts) { var cd = calcdata[i]; var trace = cd[0].trace; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { cdSubplot.push(cd); } @@ -63,15 +66,20 @@ exports.plot = function(gd, transitionOpts) { return cdModule; } - function keyFunc (d) { - return d[0].trace.uid; - } - for(var i = 0; i < subplots.length; i++) { var subplot = subplots[i], subplotInfo = fullLayout._plots[subplot], cdSubplot = getCdSubplot(calcdata, subplot); + // remove old traces, then redraw everything + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(subplotInfo.plot) { + subplotInfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + } + for(var j = 0; j < modules.length; j++) { var _module = modules[j]; @@ -81,25 +89,7 @@ exports.plot = function(gd, transitionOpts) { // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); - var tracelayer = subplotInfo.plot.select('g.' + _module.name + 'layer'); - var subplotJoin = tracelayer.selectAll('g.trace').data(cdModule, keyFunc); - - subplotJoin.enter() - .append('g') - .classed('trace', true) - .classed(_module.name, true) - .each(function(d) { - d[0].trace._module.plot(gd, subplotInfo, d, this) - }); - - subplotJoin.transition() - .each(function(d) { - d[0].trace._module.plot(gd, subplotInfo, d, this, transitionOpts) - }); - - - subplotJoin.exit() - .remove() + _module.plot(gd, subplotInfo, cdModule, traces, transitionOpts); } } }; diff --git a/src/traces/scatter/animate.js b/src/traces/scatter/animate.js deleted file mode 100644 index fe5e344749b..00000000000 --- a/src/traces/scatter/animate.js +++ /dev/null @@ -1,309 +0,0 @@ -/** -* Copyright 2012-2016, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var d3 = require('d3'); - -var Lib = require('../../lib'); -var Drawing = require('../../components/drawing'); -var ErrorBars = require('../../components/errorbars'); - -var subTypes = require('./subtypes'); -var arraysToCalcdata = require('./arrays_to_calcdata'); -var linePoints = require('./line_points'); -var isNumeric = require('fast-isnumeric'); - -module.exports = function animate (gd, trace, data, opts) { - var axisName = trace.xaxis + trace.yaxis; - var plotinfo = gd._fullLayout._plots[axisName]; - var cdscatter = gd.calcdata - - opts = opts || {}; - var transitionDuration = isNumeric(opts.duration) ? opts.duration : 250; - var transitionEasing = !!opts.easing ? opts.easing : 'cubic-in-out'; - var transitionCascade = !!opts.cascade ? opts.cascade : 0; - - //window.scattertraces = plotinfo.plot.select('.scatterlayer') - - /*return - - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(gd.calcdata[trace.index]) - - - scattertraces.selectAll('g.points') - .each(function (d) { - console.log('d =', d) - }); - - - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext;*/ - - window.trace = trace; - window.plotinfo = plotinfo - var xa = plotinfo.x(), - ya = plotinfo.y(); - - // make the container for scatter plots - // (so error bars can find them along with bars) - - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(cdscatter); - - //scattertraces.enter().append('g') - //.attr('class', 'trace scatter') - //.style('stroke-miterlimit', 2); - - // error bars are at the bottom - //scattertraces.call(ErrorBars.plot, plotinfo); - - // BUILD LINES AND FILLS - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext; - - scattertraces.each(function(d) { - var trace = d[0].trace, - line = trace.line, - tr = d3.select(this); - if(trace.visible !== true) return; - - ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; - - d[0].node3 = tr; // store node for tweaking by selectPoints - - arraysToCalcdata(d); - - if(!subTypes.hasLines(trace) && trace.fill === 'none') return; - - var thispath, - thisrevpath, - // fullpath is all paths for this curve, joined together straight - // across gaps, for filling - fullpath = '', - // revpath is fullpath reversed, for fill-to-next - revpath = '', - // functions for converting a point array to a path - pathfn, revpathbase, revpathfn; - - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous - var fills = tr.selectAll('.js-fill')[0]; - if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevpath)) { - ownFillEl3 = d3.select(fills[0]); - } - else ownFillEl3 = null; - - // make the fill-to-next path now for the NEXT trace, so it shows - // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if(nexttonext) tonext = nexttonext.data(d); - - // now make a new nexttonext for next time - nexttonext = d3.select(fills[ownFillEl3 ? 0 : 1]); - - console.log('ownFillEl3:', ownFillEl3); - console.log('nexttonext:', nexttonext); - - if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = Drawing.steps(line.shape); - revpathbase = Drawing.steps( - line.shape.split('').reverse().join('') - ); - } - else if(line.shape === 'spline') { - pathfn = revpathbase = function(pts) { - var pLast = pts[pts.length - 1]; - if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { - // identical start and end points: treat it as a - // closed curve so we don't get a kink - return Drawing.smoothclosed(pts.slice(1), line.smoothing); - } - else { - return Drawing.smoothopen(pts, line.smoothing); - } - }; - } - else { - pathfn = revpathbase = function(pts) { - return 'M' + pts.join('L'); - }; - } - - revpathfn = function(pts) { - // note: this is destructive (reverses pts in place) so can't use pts after this - return revpathbase(pts.reverse()); - }; - - var segments = linePoints(d, { - xaxis: xa, - yaxis: ya, - connectGaps: trace.connectgaps, - baseTolerance: Math.max(line.width || 1, 3) / 4, - linear: line.shape === 'linear' - }); - - if(segments.length) { - var pt0 = segments[0][0], - lastSegment = segments[segments.length - 1], - pt1 = lastSegment[lastSegment.length - 1]; - - for(var i = 0; i < segments.length; i++) { - var pts = segments[i]; - thispath = pathfn(pts); - thisrevpath = revpathfn(pts); - if(!fullpath) { - fullpath = thispath; - revpath = thisrevpath; - } - else if(ownFillDir) { - fullpath += 'L' + thispath.substr(1); - revpath = thisrevpath + ('L' + revpath.substr(1)); - } - else { - fullpath += 'Z' + thispath; - revpath = thisrevpath + 'Z' + revpath; - } - - if(subTypes.hasLines(trace) && pts.length > 1) { - tr.select('path.js-line') - .transition() - .ease(transitionEasing) - .duration(transitionDuration).attr('d', thispath); - } - } - if(ownFillEl3) { - if(pt0 && pt1) { - if(ownFillDir) { - if(ownFillDir === 'y') { - pt0[1] = pt1[1] = ya.c2p(0, true); - } - else if(ownFillDir === 'x') { - pt0[0] = pt1[0] = xa.c2p(0, true); - } - - // fill to zero: full trace path, plus extension of - // the endpoints to the appropriate axis - ownFillEl3.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); - } - // fill to self: just join the path to itself - else ownFillEl3.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'Z'); - } - } - else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { - // fill to next: full trace path, plus the previous path reversed - if(trace.fill === 'tonext') { - // tonext: for use by concentric shapes, like manually constructed - // contours, we just add the two paths closed on themselves. - // This makes strange results if one path is *not* entirely - // inside the other, but then that is a strange usage. - tonext.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'Z' + prevpath + 'Z'); - } - else { - // tonextx/y: for now just connect endpoints with lines. This is - // the correct behavior if the endpoints are at the same value of - // y/x, but if they *aren't*, we should ideally do more complicated - // things depending on whether the new endpoint projects onto the - // existing curve or off the end of it - tonext.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); - } - } - prevpath = revpath; - } - }); - - // remove paths that didn't get used - // scattertraces.selectAll('path:not([d])').remove(); - - function visFilter(d) { - return d.filter(function(v) { return v.vis; }); - } - - function keyFunc (d) { - return d.key; - } - - function getKeyFunc(trace) { - if (trace.key) { - return keyFunc; - } - } - - scattertraces.select('g.points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); - - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - var selection = s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) - - //console.log('d:', d.length); - //console.log('transitionCascade:', transitionCascade); - selection.call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, null, 0, transitionCascade / d.length); - - var enter = selection.enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 1) - - selection.exit() - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, -1) - } - } - }); - -}; - - /* - window.gd = gd; - - scattertraces.select('g.points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); - - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - var selection = s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)); - - selection.call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace); - - selection.enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya); - } - } - }); -};*/ diff --git a/src/traces/scatter/calc.js b/src/traces/scatter/calc.js index 055fc6ce574..0a8b9efdba7 100644 --- a/src/traces/scatter/calc.js +++ b/src/traces/scatter/calc.js @@ -116,7 +116,7 @@ module.exports = function calc(gd, trace) { cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ? {x: x[i], y: y[i]} : {x: false, y: false}; - if (trace.key && trace.key[i]) { + if (trace.key && trace.key[i] !== undefined) { cd[i].key = trace.key[i]; } } diff --git a/src/traces/scatter/link_traces.js b/src/traces/scatter/link_traces.js new file mode 100644 index 00000000000..f19149e7255 --- /dev/null +++ b/src/traces/scatter/link_traces.js @@ -0,0 +1,50 @@ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); + +module.exports = function linkTraces(gd, plotinfo, cdscatter) { + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < cdscatter.length; ++i) { + cd = cdscatter[i]; + trace = cd[0].trace; + + // console.log('visible:', trace.uid, trace.visible); + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + trace._nexttrace = null; + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + + prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; + } + } + + /*for(i = 0; i < cdscatter.length; ++i) { + var trace = cdscatter[i][0].trace; + console.log('gd.cdscatter[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + }*/ +} diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 46e0607e346..b15f49a798d 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -18,12 +18,17 @@ var ErrorBars = require('../../components/errorbars'); var subTypes = require('./subtypes'); var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); +var linkTraces = require('./link_traces'); +function cdscatterKey (d) { + return d[0].trace.uid; +} -module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { - selectMarkers(gd, plotinfo, cdscatter); +module.exports = function plot(gd, plotinfo, cdscatter, traces, transitionOpts) { + var i, uids, noremove; var transitionConfig = Lib.extendFlat({}, transitionOpts || {}); + transitionConfig = Lib.extendFlat({ duration: 0, easing: 'in-out-cubic', @@ -33,6 +38,101 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { var hasTransition = transitionConfig.duration > 0; + if (!traces) { + // If no traces provided, redraw all: + for (i = 0, traces = []; i < cdscatter.length; i++) { + traces[i] = i; + } + noremove = false; + } else { + // If this is a partial update, then don't remove traces whose data is not updated + noremove = true; + } + + var scatterlayer = plotinfo.plot.select('g.scatterlayer'); + var traceJoin = scatterlayer.selectAll('g.trace').data(cdscatter, cdscatterKey); + + var traceEnter = traceJoin.enter().append('g') + .attr('class', 'trace scatter') + .style('stroke-miterlimit', 2) + + // After the elements are created but before they've been draw, we have to do + // this extra step of linking the traces due to z-ordering + linkTraces(gd, plotinfo, cdscatter) + createFills(gd, scatterlayer, cdscatter, traces) + + traceEnter.each(function(d) { + //console.log('enter:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); + + traceJoin.transition() + .duration(0) + .each(function(d) { + //console.log('transition:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); + + + if (!noremove) { + traceJoin.exit().remove(); + } + + // Sort the traces, once created, so that the ordering is preserved even when + // traces are shown and hidden. This is now needed since we're not just wiping + // everything out and recreating on every update. + for (i = 0, uids = []; i < cdscatter.length; i++) { + uids[i] = cdscatter[i][0].trace.uid; + } + + scatterlayer.selectAll('g.trace').sort(function (a, b) { + var idx1 = uids.indexOf(a[0].trace.uid); + var idx2 = uids.indexOf(b[0].trace.uid); + return idx1 > idx2 ? 1 : -1; + }); + + // remove paths that didn't get used + // scatterlayer.selectAll('path:not([d])').remove(); +}; + +function createFills (gd, scatterlayer, cdscatter, traces) { + var i, trace, prevtrace; + + scatterlayer.selectAll('g.trace').each(function (d) { + var tr = d3.select(this); + + // Loop only over the traces being redrawn: + trace = d[0].trace; + + if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || + (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)) { + trace._ownFill = tr.select('.js-fill.js-tozero'); + if (!trace._ownFill.size()) { + trace._ownFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tozero'); + } + } else { + tr.selectAll('.js-fill.js-tozero').remove(); + trace._ownFill = null; + } + + // make the fill-to-next path now for the NEXT trace, so it shows + // behind both lines. + if (trace._nexttrace) { + trace._nextFill = tr.select('.js-fill.js-tonext'); + if (!trace._nextFill.size()) { + trace._nextFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tonext'); + } + } else { + tr.selectAll('.js-fill.js-tonext').remove(); + trace._nextFill = null; + } + }); +} + + +function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { + selectMarkers(gd, plotinfo, cdscatter); + function transition (selection) { return selection.transition() .duration(transitionConfig.duration) @@ -46,8 +146,6 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { line = trace.line, tr = d3.select(group); - tr.style('stroke-miterlimit', 2); - // (so error bars can find them along with bars) // error bars are at the bottom tr.call(ErrorBars.plot, plotinfo); @@ -69,9 +167,8 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { if (prevtrace) { prevpath = prevtrace._revpath || ''; - tonext = prevtrace._nexttonext; + tonext = prevtrace._nextFill; } - console.log(trace.uid, trace._prevtrace && trace._prevtrace.uid, 'prevtrace:', prevtrace, tonext); var thispath, thisrevpath, @@ -83,36 +180,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // functions for converting a point array to a path pathfn, revpathbase, revpathfn; - - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous - if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevtrace)) { - ownFillEl3 = tr.select('.js-fill.js-tozero'); - if (!ownFillEl3.size()) { - ownFillEl3 = tr.append('path').attr('class', 'js-fill js-tozero'); - } - } else { - tr.selectAll('.js-fill.js-tozero').remove(); - ownFillEl3 = null; - } - - // make the fill-to-next path now for the NEXT trace, so it shows - // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if (trace._nexttrace) { - console.log(trace.uid, 'has nexttrace'); - trace._nexttonext = tr.select('.js-fill.js-tonext'); - if (!trace._nexttonext.size()) { - trace._nexttonext = tr.append('path').attr('class', 'js-fill js-tonext'); - } - } else { - console.log(trace.uid, 'does not have nexttrace'); - tr.selectAll('.js-fill.js-tonext').remove(); - trace._nexttonext = null; - } + ownFillEl3 = trace._ownFill; if(subTypes.hasLines(trace) || trace.fill !== 'none') { @@ -232,10 +300,6 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { } - // remove paths that didn't get used - //tr.selectAll('path:not([d])').remove(); - */ - function visFilter(d) { return d.filter(function(v) { return v.vis; }); } @@ -265,16 +329,15 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { join.enter().append('path') .classed('point', true) - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace) .call(Drawing.pointStyle, trace) + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1) join.transition() - .duration(0) - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace) + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 0) .call(Drawing.pointStyle, trace) - join.exit().remove(); - //.call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); + join.exit() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); } if(showText) { s.selectAll('g') @@ -283,7 +346,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // it gets converted to mathjax .enter().append('g') .append('text') - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace); + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1); } } } diff --git a/src/traces/scatter/set_positions.js b/src/traces/scatter/set_positions.js index 15a2261795e..412ff399447 100644 --- a/src/traces/scatter/set_positions.js +++ b/src/traces/scatter/set_positions.js @@ -19,7 +19,7 @@ var Lib = require('../../lib'); * doesn't require any links between traces. */ module.exports = function setPositions(gd, plotinfo) { - console.log('setPositions:', plotinfo); + // console.log('setPositions:', plotinfo); var i, cd, trace; var fullLayout = gd._fullLayout; var xa = plotinfo.x(); @@ -31,7 +31,7 @@ module.exports = function setPositions(gd, plotinfo) { cd = gd.calcdata[i]; trace = cd[0].trace; - console.log('visible:', trace.uid, trace.visible); + // console.log('visible:', trace.uid, trace.visible); if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && trace.xaxis === xa._id && trace.yaxis === ya._id) { @@ -53,6 +53,6 @@ module.exports = function setPositions(gd, plotinfo) { } for(i = 0; i < gd.calcdata.length; ++i) { var trace = gd.calcdata[i][0].trace; - console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + // console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) } }; From 82071e371876c6db03985b66b537d1463a831d59 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Tue, 14 Jun 2016 12:42:23 -0400 Subject: [PATCH 13/21] Refactor scatter traces --- src/components/drawing/index.js | 9 +- src/plot_api/plot_api.js | 30 +-- src/plots/cartesian/index.js | 38 ++-- src/traces/scatter/animate.js | 309 ---------------------------- src/traces/scatter/calc.js | 2 +- src/traces/scatter/index.js | 2 +- src/traces/scatter/link_traces.js | 50 +++++ src/traces/scatter/plot.js | 155 +++++++++----- src/traces/scatter/set_positions.js | 6 +- 9 files changed, 189 insertions(+), 412 deletions(-) delete mode 100644 src/traces/scatter/animate.js create mode 100644 src/traces/scatter/link_traces.js diff --git a/src/components/drawing/index.js b/src/components/drawing/index.js index 1f0c35721fa..6beffebd4fb 100644 --- a/src/components/drawing/index.js +++ b/src/components/drawing/index.js @@ -46,11 +46,10 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { +drawing.translatePoints = function(s, xa, ya, trace, transitionConfig, joinDirection) { var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; - if (hasTransition) { var size = s.size(); } @@ -67,7 +66,7 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { } else { if (hasTransition) { var trans; - if (!transitionConfig.direction) { + if (!joinDirection) { trans = p.transition() .delay(transitionConfig.delay + transitionConfig.cascade / size * i) .duration(transitionConfig.duration) @@ -77,14 +76,14 @@ drawing.translatePoints = function(s, xa, ya, transitionConfig, trace) { if (trace) { trans.call(drawing.pointStyle, trace) } - } else if (transitionConfig.direction === -1) { + } else if (joinDirection === -1) { trans = p.style('opacity', 1) .transition() .duration(transitionConfig.duration) .ease(transitionConfig.easing) .style('opacity', 0) .remove(); - } else if (transitionConfig.direction === 1) { + } else if (joinDirection === 1) { trans = p.attr('transform', 'translate('+x+','+y+')') if (trace) { diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 5a0fcd53f91..79749f407fd 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1561,7 +1561,7 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var trace = gd._fullData[traceIdx]; var module = trace._module; - if (!module.animate) { + if (!module.animatable) { continue; } @@ -1599,11 +1599,9 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { var subplotInfo, _module; for(var i = 0; i < subplots.length; i++) { - console.log('i:', i); subplotInfo = fullLayout._plots[subplots[i]]; for(var j = 0; j < modules.length; j++) { - console.log('j:', j); _module = modules[j]; if(_module.setPositions) _module.setPositions(gd, subplotInfo); } @@ -1612,20 +1610,14 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { doSetPositions(); - var animateList = []; var restyleList = []; - function doAnimations () { var a, i, j; - for (i = 0; i < animateList.length; i++) { - a = animateList[i]; - var basePlotModules = fullLayout._basePlotModules; - for(j = 0; j < basePlotModules.length; j++) { - basePlotModules[j].plot(gd, transitionOpts); - } + var basePlotModules = fullLayout._basePlotModules; + for(j = 0; j < basePlotModules.length; j++) { + basePlotModules[j].plot(gd, animatedTraces, transitionOpts); } - if (!transitionOpts.leadingEdgeRestyle) { return new Promise(function(resolve, reject) { setTimeout(resolve, transitionOpts.duration); @@ -1633,7 +1625,7 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { } } - for (var i = 0; i < animatedTraces.length; i++) { + /*for (var i = 0; i < animatedTraces.length; i++) { var trace = gd._fullData[animatedTraces[i]]; var module = trace._module; var cd = []; @@ -1655,22 +1647,14 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { cd[0].trace = trace; gd.calcdata[traces[i]] = cd; - } + }*/ for (i = 0; i < traces.length; i++) { var traceIdx = traces[i]; - - var cont = gd.data[traceIdx]; var contFull = gd._fullData[traceIdx]; var module = contFull._module; - if (module.animate) { - animateList.push({ - module: module, - contFull: contFull, - newData: newData[i] - }); - } else { + if (!module.animatable) { var thisTrace = [traceIdx]; var thisUpdate = {}; diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index 791a2f9c2e8..544ac495ca4 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -27,7 +27,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd, transitionOpts) { +exports.plot = function(gd, traces, transitionOpts) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -40,6 +40,9 @@ exports.plot = function(gd, transitionOpts) { var cd = calcdata[i]; var trace = cd[0].trace; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { cdSubplot.push(cd); } @@ -63,15 +66,20 @@ exports.plot = function(gd, transitionOpts) { return cdModule; } - function keyFunc (d) { - return d[0].trace.uid; - } - for(var i = 0; i < subplots.length; i++) { var subplot = subplots[i], subplotInfo = fullLayout._plots[subplot], cdSubplot = getCdSubplot(calcdata, subplot); + // remove old traces, then redraw everything + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(subplotInfo.plot) { + subplotInfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + } + for(var j = 0; j < modules.length; j++) { var _module = modules[j]; @@ -81,25 +89,7 @@ exports.plot = function(gd, transitionOpts) { // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); - var tracelayer = subplotInfo.plot.select('g.' + _module.name + 'layer'); - var subplotJoin = tracelayer.selectAll('g.trace').data(cdModule, keyFunc); - - subplotJoin.enter() - .append('g') - .classed('trace', true) - .classed(_module.name, true) - .each(function(d) { - d[0].trace._module.plot(gd, subplotInfo, d, this) - }); - - subplotJoin.transition() - .each(function(d) { - d[0].trace._module.plot(gd, subplotInfo, d, this, transitionOpts) - }); - - - subplotJoin.exit() - .remove() + _module.plot(gd, subplotInfo, cdModule, traces, transitionOpts); } } }; diff --git a/src/traces/scatter/animate.js b/src/traces/scatter/animate.js deleted file mode 100644 index fe5e344749b..00000000000 --- a/src/traces/scatter/animate.js +++ /dev/null @@ -1,309 +0,0 @@ -/** -* Copyright 2012-2016, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var d3 = require('d3'); - -var Lib = require('../../lib'); -var Drawing = require('../../components/drawing'); -var ErrorBars = require('../../components/errorbars'); - -var subTypes = require('./subtypes'); -var arraysToCalcdata = require('./arrays_to_calcdata'); -var linePoints = require('./line_points'); -var isNumeric = require('fast-isnumeric'); - -module.exports = function animate (gd, trace, data, opts) { - var axisName = trace.xaxis + trace.yaxis; - var plotinfo = gd._fullLayout._plots[axisName]; - var cdscatter = gd.calcdata - - opts = opts || {}; - var transitionDuration = isNumeric(opts.duration) ? opts.duration : 250; - var transitionEasing = !!opts.easing ? opts.easing : 'cubic-in-out'; - var transitionCascade = !!opts.cascade ? opts.cascade : 0; - - //window.scattertraces = plotinfo.plot.select('.scatterlayer') - - /*return - - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(gd.calcdata[trace.index]) - - - scattertraces.selectAll('g.points') - .each(function (d) { - console.log('d =', d) - }); - - - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext;*/ - - window.trace = trace; - window.plotinfo = plotinfo - var xa = plotinfo.x(), - ya = plotinfo.y(); - - // make the container for scatter plots - // (so error bars can find them along with bars) - - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(cdscatter); - - //scattertraces.enter().append('g') - //.attr('class', 'trace scatter') - //.style('stroke-miterlimit', 2); - - // error bars are at the bottom - //scattertraces.call(ErrorBars.plot, plotinfo); - - // BUILD LINES AND FILLS - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext; - - scattertraces.each(function(d) { - var trace = d[0].trace, - line = trace.line, - tr = d3.select(this); - if(trace.visible !== true) return; - - ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; - - d[0].node3 = tr; // store node for tweaking by selectPoints - - arraysToCalcdata(d); - - if(!subTypes.hasLines(trace) && trace.fill === 'none') return; - - var thispath, - thisrevpath, - // fullpath is all paths for this curve, joined together straight - // across gaps, for filling - fullpath = '', - // revpath is fullpath reversed, for fill-to-next - revpath = '', - // functions for converting a point array to a path - pathfn, revpathbase, revpathfn; - - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous - var fills = tr.selectAll('.js-fill')[0]; - if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevpath)) { - ownFillEl3 = d3.select(fills[0]); - } - else ownFillEl3 = null; - - // make the fill-to-next path now for the NEXT trace, so it shows - // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if(nexttonext) tonext = nexttonext.data(d); - - // now make a new nexttonext for next time - nexttonext = d3.select(fills[ownFillEl3 ? 0 : 1]); - - console.log('ownFillEl3:', ownFillEl3); - console.log('nexttonext:', nexttonext); - - if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { - pathfn = Drawing.steps(line.shape); - revpathbase = Drawing.steps( - line.shape.split('').reverse().join('') - ); - } - else if(line.shape === 'spline') { - pathfn = revpathbase = function(pts) { - var pLast = pts[pts.length - 1]; - if(pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) { - // identical start and end points: treat it as a - // closed curve so we don't get a kink - return Drawing.smoothclosed(pts.slice(1), line.smoothing); - } - else { - return Drawing.smoothopen(pts, line.smoothing); - } - }; - } - else { - pathfn = revpathbase = function(pts) { - return 'M' + pts.join('L'); - }; - } - - revpathfn = function(pts) { - // note: this is destructive (reverses pts in place) so can't use pts after this - return revpathbase(pts.reverse()); - }; - - var segments = linePoints(d, { - xaxis: xa, - yaxis: ya, - connectGaps: trace.connectgaps, - baseTolerance: Math.max(line.width || 1, 3) / 4, - linear: line.shape === 'linear' - }); - - if(segments.length) { - var pt0 = segments[0][0], - lastSegment = segments[segments.length - 1], - pt1 = lastSegment[lastSegment.length - 1]; - - for(var i = 0; i < segments.length; i++) { - var pts = segments[i]; - thispath = pathfn(pts); - thisrevpath = revpathfn(pts); - if(!fullpath) { - fullpath = thispath; - revpath = thisrevpath; - } - else if(ownFillDir) { - fullpath += 'L' + thispath.substr(1); - revpath = thisrevpath + ('L' + revpath.substr(1)); - } - else { - fullpath += 'Z' + thispath; - revpath = thisrevpath + 'Z' + revpath; - } - - if(subTypes.hasLines(trace) && pts.length > 1) { - tr.select('path.js-line') - .transition() - .ease(transitionEasing) - .duration(transitionDuration).attr('d', thispath); - } - } - if(ownFillEl3) { - if(pt0 && pt1) { - if(ownFillDir) { - if(ownFillDir === 'y') { - pt0[1] = pt1[1] = ya.c2p(0, true); - } - else if(ownFillDir === 'x') { - pt0[0] = pt1[0] = xa.c2p(0, true); - } - - // fill to zero: full trace path, plus extension of - // the endpoints to the appropriate axis - ownFillEl3.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); - } - // fill to self: just join the path to itself - else ownFillEl3.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'Z'); - } - } - else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { - // fill to next: full trace path, plus the previous path reversed - if(trace.fill === 'tonext') { - // tonext: for use by concentric shapes, like manually constructed - // contours, we just add the two paths closed on themselves. - // This makes strange results if one path is *not* entirely - // inside the other, but then that is a strange usage. - tonext.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'Z' + prevpath + 'Z'); - } - else { - // tonextx/y: for now just connect endpoints with lines. This is - // the correct behavior if the endpoints are at the same value of - // y/x, but if they *aren't*, we should ideally do more complicated - // things depending on whether the new endpoint projects onto the - // existing curve or off the end of it - tonext.transition() - .duration(transitionDuration) - .ease(transitionEasing) - .attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); - } - } - prevpath = revpath; - } - }); - - // remove paths that didn't get used - // scattertraces.selectAll('path:not([d])').remove(); - - function visFilter(d) { - return d.filter(function(v) { return v.vis; }); - } - - function keyFunc (d) { - return d.key; - } - - function getKeyFunc(trace) { - if (trace.key) { - return keyFunc; - } - } - - scattertraces.select('g.points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); - - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - var selection = s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) - - //console.log('d:', d.length); - //console.log('transitionCascade:', transitionCascade); - selection.call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, null, 0, transitionCascade / d.length); - - var enter = selection.enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, 1) - - selection.exit() - .call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace, -1) - } - } - }); - -}; - - /* - window.gd = gd; - - scattertraces.select('g.points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); - - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - var selection = s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)); - - selection.call(Drawing.translatePoints, xa, ya, transitionDuration, transitionEasing, trace); - - selection.enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya); - } - } - }); -};*/ diff --git a/src/traces/scatter/calc.js b/src/traces/scatter/calc.js index 055fc6ce574..0a8b9efdba7 100644 --- a/src/traces/scatter/calc.js +++ b/src/traces/scatter/calc.js @@ -116,7 +116,7 @@ module.exports = function calc(gd, trace) { cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ? {x: x[i], y: y[i]} : {x: false, y: false}; - if (trace.key && trace.key[i]) { + if (trace.key && trace.key[i] !== undefined) { cd[i].key = trace.key[i]; } } diff --git a/src/traces/scatter/index.js b/src/traces/scatter/index.js index 8606e0adf7d..152489788f1 100644 --- a/src/traces/scatter/index.js +++ b/src/traces/scatter/index.js @@ -30,10 +30,10 @@ Scatter.colorbar = require('./colorbar'); Scatter.style = require('./style'); Scatter.hoverPoints = require('./hover'); Scatter.selectPoints = require('./select'); -Scatter.animate = require('./animate'); Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; +Scatter.animatable = true; Scatter.basePlotModule = require('../../plots/cartesian'); Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend']; Scatter.meta = { diff --git a/src/traces/scatter/link_traces.js b/src/traces/scatter/link_traces.js new file mode 100644 index 00000000000..f19149e7255 --- /dev/null +++ b/src/traces/scatter/link_traces.js @@ -0,0 +1,50 @@ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); + +module.exports = function linkTraces(gd, plotinfo, cdscatter) { + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < cdscatter.length; ++i) { + cd = cdscatter[i]; + trace = cd[0].trace; + + // console.log('visible:', trace.uid, trace.visible); + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + trace._nexttrace = null; + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + + prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; + } + } + + /*for(i = 0; i < cdscatter.length; ++i) { + var trace = cdscatter[i][0].trace; + console.log('gd.cdscatter[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + }*/ +} diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index 46e0607e346..b15f49a798d 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -18,12 +18,17 @@ var ErrorBars = require('../../components/errorbars'); var subTypes = require('./subtypes'); var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); +var linkTraces = require('./link_traces'); +function cdscatterKey (d) { + return d[0].trace.uid; +} -module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { - selectMarkers(gd, plotinfo, cdscatter); +module.exports = function plot(gd, plotinfo, cdscatter, traces, transitionOpts) { + var i, uids, noremove; var transitionConfig = Lib.extendFlat({}, transitionOpts || {}); + transitionConfig = Lib.extendFlat({ duration: 0, easing: 'in-out-cubic', @@ -33,6 +38,101 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { var hasTransition = transitionConfig.duration > 0; + if (!traces) { + // If no traces provided, redraw all: + for (i = 0, traces = []; i < cdscatter.length; i++) { + traces[i] = i; + } + noremove = false; + } else { + // If this is a partial update, then don't remove traces whose data is not updated + noremove = true; + } + + var scatterlayer = plotinfo.plot.select('g.scatterlayer'); + var traceJoin = scatterlayer.selectAll('g.trace').data(cdscatter, cdscatterKey); + + var traceEnter = traceJoin.enter().append('g') + .attr('class', 'trace scatter') + .style('stroke-miterlimit', 2) + + // After the elements are created but before they've been draw, we have to do + // this extra step of linking the traces due to z-ordering + linkTraces(gd, plotinfo, cdscatter) + createFills(gd, scatterlayer, cdscatter, traces) + + traceEnter.each(function(d) { + //console.log('enter:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); + + traceJoin.transition() + .duration(0) + .each(function(d) { + //console.log('transition:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); + + + if (!noremove) { + traceJoin.exit().remove(); + } + + // Sort the traces, once created, so that the ordering is preserved even when + // traces are shown and hidden. This is now needed since we're not just wiping + // everything out and recreating on every update. + for (i = 0, uids = []; i < cdscatter.length; i++) { + uids[i] = cdscatter[i][0].trace.uid; + } + + scatterlayer.selectAll('g.trace').sort(function (a, b) { + var idx1 = uids.indexOf(a[0].trace.uid); + var idx2 = uids.indexOf(b[0].trace.uid); + return idx1 > idx2 ? 1 : -1; + }); + + // remove paths that didn't get used + // scatterlayer.selectAll('path:not([d])').remove(); +}; + +function createFills (gd, scatterlayer, cdscatter, traces) { + var i, trace, prevtrace; + + scatterlayer.selectAll('g.trace').each(function (d) { + var tr = d3.select(this); + + // Loop only over the traces being redrawn: + trace = d[0].trace; + + if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || + (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)) { + trace._ownFill = tr.select('.js-fill.js-tozero'); + if (!trace._ownFill.size()) { + trace._ownFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tozero'); + } + } else { + tr.selectAll('.js-fill.js-tozero').remove(); + trace._ownFill = null; + } + + // make the fill-to-next path now for the NEXT trace, so it shows + // behind both lines. + if (trace._nexttrace) { + trace._nextFill = tr.select('.js-fill.js-tonext'); + if (!trace._nextFill.size()) { + trace._nextFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tonext'); + } + } else { + tr.selectAll('.js-fill.js-tonext').remove(); + trace._nextFill = null; + } + }); +} + + +function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { + selectMarkers(gd, plotinfo, cdscatter); + function transition (selection) { return selection.transition() .duration(transitionConfig.duration) @@ -46,8 +146,6 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { line = trace.line, tr = d3.select(group); - tr.style('stroke-miterlimit', 2); - // (so error bars can find them along with bars) // error bars are at the bottom tr.call(ErrorBars.plot, plotinfo); @@ -69,9 +167,8 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { if (prevtrace) { prevpath = prevtrace._revpath || ''; - tonext = prevtrace._nexttonext; + tonext = prevtrace._nextFill; } - console.log(trace.uid, trace._prevtrace && trace._prevtrace.uid, 'prevtrace:', prevtrace, tonext); var thispath, thisrevpath, @@ -83,36 +180,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // functions for converting a point array to a path pathfn, revpathbase, revpathfn; - - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous - if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevtrace)) { - ownFillEl3 = tr.select('.js-fill.js-tozero'); - if (!ownFillEl3.size()) { - ownFillEl3 = tr.append('path').attr('class', 'js-fill js-tozero'); - } - } else { - tr.selectAll('.js-fill.js-tozero').remove(); - ownFillEl3 = null; - } - - // make the fill-to-next path now for the NEXT trace, so it shows - // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if (trace._nexttrace) { - console.log(trace.uid, 'has nexttrace'); - trace._nexttonext = tr.select('.js-fill.js-tonext'); - if (!trace._nexttonext.size()) { - trace._nexttonext = tr.append('path').attr('class', 'js-fill js-tonext'); - } - } else { - console.log(trace.uid, 'does not have nexttrace'); - tr.selectAll('.js-fill.js-tonext').remove(); - trace._nexttonext = null; - } + ownFillEl3 = trace._ownFill; if(subTypes.hasLines(trace) || trace.fill !== 'none') { @@ -232,10 +300,6 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { } - // remove paths that didn't get used - //tr.selectAll('path:not([d])').remove(); - */ - function visFilter(d) { return d.filter(function(v) { return v.vis; }); } @@ -265,16 +329,15 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { join.enter().append('path') .classed('point', true) - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace) .call(Drawing.pointStyle, trace) + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1) join.transition() - .duration(0) - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 0}), trace) + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 0) .call(Drawing.pointStyle, trace) - join.exit().remove(); - //.call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: -1}), trace); + join.exit() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); } if(showText) { s.selectAll('g') @@ -283,7 +346,7 @@ module.exports = function plot(gd, plotinfo, cdscatter, group, transitionOpts) { // it gets converted to mathjax .enter().append('g') .append('text') - .call(Drawing.translatePoints, xa, ya, Lib.extendFlat(transitionConfig, {direction: 1}), trace); + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1); } } } diff --git a/src/traces/scatter/set_positions.js b/src/traces/scatter/set_positions.js index 15a2261795e..412ff399447 100644 --- a/src/traces/scatter/set_positions.js +++ b/src/traces/scatter/set_positions.js @@ -19,7 +19,7 @@ var Lib = require('../../lib'); * doesn't require any links between traces. */ module.exports = function setPositions(gd, plotinfo) { - console.log('setPositions:', plotinfo); + // console.log('setPositions:', plotinfo); var i, cd, trace; var fullLayout = gd._fullLayout; var xa = plotinfo.x(); @@ -31,7 +31,7 @@ module.exports = function setPositions(gd, plotinfo) { cd = gd.calcdata[i]; trace = cd[0].trace; - console.log('visible:', trace.uid, trace.visible); + // console.log('visible:', trace.uid, trace.visible); if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && trace.xaxis === xa._id && trace.yaxis === ya._id) { @@ -53,6 +53,6 @@ module.exports = function setPositions(gd, plotinfo) { } for(i = 0; i < gd.calcdata.length; ++i) { var trace = gd.calcdata[i][0].trace; - console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + // console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) } }; From aa19ac0fea26929c406b2a09585b8541e3157f69 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Tue, 14 Jun 2016 15:28:46 -0400 Subject: [PATCH 14/21] Add build --- dist/plotly-with-meta.js | 85181 +++++++++++++++++++------------------ dist/plotly.js | 85181 +++++++++++++++++++------------------ dist/plotly.min.js | 79 +- 3 files changed, 87843 insertions(+), 82598 deletions(-) diff --git a/dist/plotly-with-meta.js b/dist/plotly-with-meta.js index e5256ee78b4..ec9126e0053 100644 --- a/dist/plotly-with-meta.js +++ b/dist/plotly-with-meta.js @@ -68,7 +68,7 @@ for(var selector in rules) { Plotly.Lib.addStyleRule(fullSelector, rules[selector]); } -},{"../src/plotly":402}],2:[function(require,module,exports){ +},{"../src/plotly":1147}],2:[function(require,module,exports){ 'use strict'; module.exports = { @@ -199,7 +199,7 @@ module.exports = { module.exports = require('../src/traces/bar'); -},{"../src/traces/bar":480}],4:[function(require,module,exports){ +},{"../src/traces/bar":1225}],4:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -210,7 +210,7 @@ module.exports = require('../src/traces/bar'); module.exports = require('../src/traces/box'); -},{"../src/traces/box":491}],5:[function(require,module,exports){ +},{"../src/traces/box":1236}],5:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -221,7 +221,7 @@ module.exports = require('../src/traces/box'); module.exports = require('../src/traces/choropleth'); -},{"../src/traces/choropleth":500}],6:[function(require,module,exports){ +},{"../src/traces/choropleth":1245}],6:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -232,7 +232,7 @@ module.exports = require('../src/traces/choropleth'); module.exports = require('../src/traces/contour'); -},{"../src/traces/contour":507}],7:[function(require,module,exports){ +},{"../src/traces/contour":1252}],7:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -243,7 +243,7 @@ module.exports = require('../src/traces/contour'); module.exports = require('../src/core'); -},{"../src/core":371}],8:[function(require,module,exports){ +},{"../src/core":1116}],8:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -254,7 +254,7 @@ module.exports = require('../src/core'); module.exports = require('../src/traces/heatmap'); -},{"../src/traces/heatmap":519}],9:[function(require,module,exports){ +},{"../src/traces/heatmap":1264}],9:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -265,7 +265,7 @@ module.exports = require('../src/traces/heatmap'); module.exports = require('../src/traces/histogram'); -},{"../src/traces/histogram":530}],10:[function(require,module,exports){ +},{"../src/traces/histogram":1275}],10:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -276,7 +276,7 @@ module.exports = require('../src/traces/histogram'); module.exports = require('../src/traces/histogram2d'); -},{"../src/traces/histogram2d":535}],11:[function(require,module,exports){ +},{"../src/traces/histogram2d":1280}],11:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -287,7 +287,7 @@ module.exports = require('../src/traces/histogram2d'); module.exports = require('../src/traces/histogram2dcontour'); -},{"../src/traces/histogram2dcontour":539}],12:[function(require,module,exports){ +},{"../src/traces/histogram2dcontour":1284}],12:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -336,7 +336,7 @@ module.exports = Core; module.exports = require('../src/traces/mesh3d'); -},{"../src/traces/mesh3d":543}],14:[function(require,module,exports){ +},{"../src/traces/mesh3d":1288}],14:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -347,7 +347,7 @@ module.exports = require('../src/traces/mesh3d'); module.exports = require('../src/traces/pie'); -},{"../src/traces/pie":549}],15:[function(require,module,exports){ +},{"../src/traces/pie":1294}],15:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -358,7 +358,7 @@ module.exports = require('../src/traces/pie'); module.exports = require('../src/traces/scatter3d'); -},{"../src/traces/scatter3d":583}],16:[function(require,module,exports){ +},{"../src/traces/scatter3d":1330}],16:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -369,7 +369,7 @@ module.exports = require('../src/traces/scatter3d'); module.exports = require('../src/traces/scattergeo'); -},{"../src/traces/scattergeo":587}],17:[function(require,module,exports){ +},{"../src/traces/scattergeo":1334}],17:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -380,7 +380,7 @@ module.exports = require('../src/traces/scattergeo'); module.exports = require('../src/traces/scattergl'); -},{"../src/traces/scattergl":592}],18:[function(require,module,exports){ +},{"../src/traces/scattergl":1339}],18:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -391,7 +391,7 @@ module.exports = require('../src/traces/scattergl'); module.exports = require('../src/traces/scatterternary'); -},{"../src/traces/scatterternary":597}],19:[function(require,module,exports){ +},{"../src/traces/scatterternary":1344}],19:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -402,300 +402,206 @@ module.exports = require('../src/traces/scatterternary'); module.exports = require('../src/traces/surface'); -},{"../src/traces/surface":606}],20:[function(require,module,exports){ +},{"../src/traces/surface":1353}],20:[function(require,module,exports){ 'use strict' -module.exports = createFilteredVector +var bsearch = require('binary-search-bounds') +var m4interp = require('mat4-interpolate') +var invert44 = require('gl-mat4/invert') +var rotateX = require('gl-mat4/rotateX') +var rotateY = require('gl-mat4/rotateY') +var rotateZ = require('gl-mat4/rotateZ') +var lookAt = require('gl-mat4/lookAt') +var translate = require('gl-mat4/translate') +var scale = require('gl-mat4/scale') +var normalize = require('gl-vec3/normalize') -var cubicHermite = require('cubic-hermite') -var bsearch = require('binary-search-bounds') +var DEFAULT_CENTER = [0,0,0] -function clamp(lo, hi, x) { - return Math.min(hi, Math.max(lo, x)) -} +module.exports = createMatrixCameraController -function FilteredVector(state0, velocity0, t0) { - this.dimension = state0.length - this.bounds = [ new Array(this.dimension), new Array(this.dimension) ] - for(var i=0; i= n-1) { - var ptr = state.length-1 - var tf = t - time[n-1] - for(var i=0; i= n-1) { - var ptr = state.length-1 - var tf = t - time[n-1] - for(var i=0; i=0; --i) { - if(velocity[--ptr]) { - return false - } + var imat = this.computedInverse + invert44(imat, mat) + var eye = this.computedEye + var w = imat[15] + eye[0] = imat[12]/w + eye[1] = imat[13]/w + eye[2] = imat[14]/w + + var center = this.computedCenter + var radius = Math.exp(this.computedRadius[0]) + for(var i=0; i<3; ++i) { + center[i] = eye[i] - mat[2+4*i] * radius } - return true } -proto.jump = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t < t0 || arguments.length !== d+1) { +proto.idle = function(t) { + if(t < this.lastT()) { return } - var state = this._state - var velocity = this._velocity - var ptr = state.length-this.dimension - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - this._time.push(t0, t) - for(var j=0; j<2; ++j) { - for(var i=0; i0; --i) { - state.push(clamp(lo[i-1], hi[i-1], arguments[i])) - velocity.push(0) - } } -proto.push = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t < t0 || arguments.length !== d+1) { +proto.flush = function(t) { + var idx = bsearch.gt(this._time, t) - 2 + if(idx < 0) { return } - var state = this._state - var velocity = this._velocity - var ptr = state.length-this.dimension - var dt = t - t0 - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var sf = (dt > 1e-6) ? 1/dt : 0 - this._time.push(t) - for(var i=d; i>0; --i) { - var xc = clamp(lo[i-1], hi[i-1], arguments[i]) - state.push(xc) - velocity.push((xc - state[ptr++]) * sf) - } + this._time.slice(0, idx) + this._components.slice(0, 16*idx) } -proto.set = function(t) { - var d = this.dimension - if(t < this.lastT() || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - this._time.push(t) - for(var i=d; i>0; --i) { - state.push(clamp(lo[i-1], hi[i-1], arguments[i])) - velocity.push(0) - } +proto.lastT = function() { + return this._time[this._time.length-1] } -proto.move = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t <= t0 || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var statePtr = state.length - this.dimension - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var dt = t - t0 - var sf = (dt > 1e-6) ? 1/dt : 0.0 - this._time.push(t) - for(var i=d; i>0; --i) { - var dx = arguments[i] - state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx)) - velocity.push(dx * sf) +proto.lookAt = function(t, eye, center, up) { + this.recalcMatrix(t) + eye = eye || this.computedEye + center = center || DEFAULT_CENTER + up = up || this.computedUp + this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) + var d2 = 0.0 + for(var i=0; i<3; ++i) { + d2 += Math.pow(center[i] - eye[i], 2) } + d2 = Math.log(Math.sqrt(d2)) + this.computedRadius[0] = d2 } -proto.idle = function(t) { - var t0 = this.lastT() - if(t < t0) { +proto.rotate = function(t, yaw, pitch, roll) { + this.recalcMatrix(t) + var mat = this.computedInverse + if(yaw) rotateY(mat, mat, yaw) + if(pitch) rotateX(mat, mat, pitch) + if(roll) rotateZ(mat, mat, roll) + this.setMatrix(t, invert44(this.computedMatrix, mat)) +} + +var tvec = [0,0,0] + +proto.pan = function(t, dx, dy, dz) { + tvec[0] = -(dx || 0.0) + tvec[1] = -(dy || 0.0) + tvec[2] = -(dz || 0.0) + this.recalcMatrix(t) + var mat = this.computedInverse + translate(mat, mat, tvec) + this.setMatrix(t, invert44(mat, mat)) +} + +proto.translate = function(t, dx, dy, dz) { + tvec[0] = dx || 0.0 + tvec[1] = dy || 0.0 + tvec[2] = dz || 0.0 + this.recalcMatrix(t) + var mat = this.computedMatrix + translate(mat, mat, tvec) + this.setMatrix(t, mat) +} + +proto.setMatrix = function(t, mat) { + if(t < this.lastT()) { return } - var d = this.dimension - var state = this._state - var velocity = this._velocity - var statePtr = state.length-d - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var dt = t - t0 this._time.push(t) - for(var i=d-1; i>=0; --i) { - state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) - velocity.push(0) - statePtr += 1 + for(var i=0; i<16; ++i) { + this._components.push(mat[i]) } } -function getZero(d) { - var result = new Array(d) - for(var i=0; i=0; --i) { - f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i] - } - return f - } - return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1 -} - -function cubicHermite(p0, v0, p1, v1, t, f) { - var ti = (t-1), t2 = t*t, ti2 = ti*ti, - h00 = (1+2*t)*ti2, - h10 = t*ti2, - h01 = t2*(3-2*t), - h11 = t2*ti - if(p0.length) { - if(!f) { - f = new Array(p0.length) - } - for(var i=p0.length-1; i>=0; --i) { - f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i] - } - return f - } - return h00*p0 + h10*v0 + h01*p1 + h11*v1 -} - -module.exports = cubicHermite -module.exports.derivative = dcubicHermite -},{}],23:[function(require,module,exports){ module.exports = cross; /** @@ -817,7 +683,7 @@ function cross(out, a, b) { out[2] = ax * by - ay * bx return out } -},{}],24:[function(require,module,exports){ +},{}],23:[function(require,module,exports){ module.exports = dot; /** @@ -830,7 +696,7 @@ module.exports = dot; function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -},{}],25:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ module.exports = length; /** @@ -845,7 +711,7 @@ function length(a) { z = a[2] return Math.sqrt(x*x + y*y + z*z) } -},{}],26:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ module.exports = lerp; /** @@ -866,7 +732,7 @@ function lerp(out, a, b, t) { out[2] = az + t * (b[2] - az) return out } -},{}],27:[function(require,module,exports){ +},{}],26:[function(require,module,exports){ module.exports = normalize; /** @@ -890,252 +756,51 @@ function normalize(out, a) { } return out } -},{}],28:[function(require,module,exports){ -'use strict' +},{}],27:[function(require,module,exports){ +var lerp = require('gl-vec3/lerp') -var bsearch = require('binary-search-bounds') -var m4interp = require('mat4-interpolate') -var invert44 = require('gl-mat4/invert') -var rotateX = require('gl-mat4/rotateX') -var rotateY = require('gl-mat4/rotateY') -var rotateZ = require('gl-mat4/rotateZ') -var lookAt = require('gl-mat4/lookAt') -var translate = require('gl-mat4/translate') -var scale = require('gl-mat4/scale') -var normalize = require('gl-vec3/normalize') +var recompose = require('mat4-recompose') +var decompose = require('mat4-decompose') +var determinant = require('gl-mat4/determinant') +var slerp = require('quat-slerp') -var DEFAULT_CENTER = [0,0,0] +var state0 = state() +var state1 = state() +var tmp = state() -module.exports = createMatrixCameraController +module.exports = interpolate +function interpolate(out, start, end, alpha) { + if (determinant(start) === 0 || determinant(end) === 0) + return false -function MatrixCameraController(initialMatrix) { - this._components = initialMatrix.slice() - this._time = [0] - this.prevMatrix = initialMatrix.slice() - this.nextMatrix = initialMatrix.slice() - this.computedMatrix = initialMatrix.slice() - this.computedInverse = initialMatrix.slice() - this.computedEye = [0,0,0] - this.computedUp = [0,0,0] - this.computedCenter = [0,0,0] - this.computedRadius = [0] - this._limits = [-Infinity, Infinity] + //decompose the start and end matrices into individual components + var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) + var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) + if (!r0 || !r1) + return false + + + //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) + lerp(tmp.translate, state0.translate, state1.translate, alpha) + lerp(tmp.skew, state0.skew, state1.skew, alpha) + lerp(tmp.scale, state0.scale, state1.scale, alpha) + lerp(tmp.perspective, state0.perspective, state1.perspective, alpha) + slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha) + + //and recompose into our 'out' matrix + recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion) + return true } -var proto = MatrixCameraController.prototype - -proto.recalcMatrix = function(t) { - var time = this._time - var tidx = bsearch.le(time, t) - var mat = this.computedMatrix - if(tidx < 0) { - return - } - var comps = this._components - if(tidx === time.length-1) { - var ptr = 16*tidx - for(var i=0; i<16; ++i) { - mat[i] = comps[ptr++] - } - } else { - var dt = (time[tidx+1] - time[tidx]) - var ptr = 16*tidx - var prev = this.prevMatrix - var allEqual = true - for(var i=0; i<16; ++i) { - prev[i] = comps[ptr++] - } - var next = this.nextMatrix - for(var i=0; i<16; ++i) { - next[i] = comps[ptr++] - allEqual = allEqual && (prev[i] === next[i]) - } - if(dt < 1e-6 || allEqual) { - for(var i=0; i<16; ++i) { - mat[i] = prev[i] - } - } else { - m4interp(mat, prev, next, (t - time[tidx])/dt) - } - } - - var up = this.computedUp - up[0] = mat[1] - up[1] = mat[5] - up[2] = mat[6] - normalize(up, up) - - var imat = this.computedInverse - invert44(imat, mat) - var eye = this.computedEye - var w = imat[15] - eye[0] = imat[12]/w - eye[1] = imat[13]/w - eye[2] = imat[14]/w - - var center = this.computedCenter - var radius = Math.exp(this.computedRadius[0]) - for(var i=0; i<3; ++i) { - center[i] = eye[i] - mat[2+4*i] * radius - } -} - -proto.idle = function(t) { - if(t < this.lastT()) { - return - } - var mc = this._components - var ptr = mc.length-16 - for(var i=0; i<16; ++i) { - mc.push(mc[ptr++]) - } - this._time.push(t) -} - -proto.flush = function(t) { - var idx = bsearch.gt(this._time, t) - 2 - if(idx < 0) { - return - } - this._time.slice(0, idx) - this._components.slice(0, 16*idx) -} - -proto.lastT = function() { - return this._time[this._time.length-1] -} - -proto.lookAt = function(t, eye, center, up) { - this.recalcMatrix(t) - eye = eye || this.computedEye - center = center || DEFAULT_CENTER - up = up || this.computedUp - this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) - var d2 = 0.0 - for(var i=0; i<3; ++i) { - d2 += Math.pow(center[i] - eye[i], 2) - } - d2 = Math.log(Math.sqrt(d2)) - this.computedRadius[0] = d2 -} - -proto.rotate = function(t, yaw, pitch, roll) { - this.recalcMatrix(t) - var mat = this.computedInverse - if(yaw) rotateY(mat, mat, yaw) - if(pitch) rotateX(mat, mat, pitch) - if(roll) rotateZ(mat, mat, roll) - this.setMatrix(t, invert44(this.computedMatrix, mat)) -} - -var tvec = [0,0,0] - -proto.pan = function(t, dx, dy, dz) { - tvec[0] = -(dx || 0.0) - tvec[1] = -(dy || 0.0) - tvec[2] = -(dz || 0.0) - this.recalcMatrix(t) - var mat = this.computedInverse - translate(mat, mat, tvec) - this.setMatrix(t, invert44(mat, mat)) -} - -proto.translate = function(t, dx, dy, dz) { - tvec[0] = dx || 0.0 - tvec[1] = dy || 0.0 - tvec[2] = dz || 0.0 - this.recalcMatrix(t) - var mat = this.computedMatrix - translate(mat, mat, tvec) - this.setMatrix(t, mat) -} - -proto.setMatrix = function(t, mat) { - if(t < this.lastT()) { - return - } - this._time.push(t) - for(var i=0; i<16; ++i) { - this._components.push(mat[i]) - } -} - -proto.setDistance = function(t, d) { - this.computedRadius[0] = d -} - -proto.setDistanceLimits = function(a,b) { - var lim = this._limits - lim[0] = a - lim[1] = b -} - -proto.getDistanceLimits = function(out) { - var lim = this._limits - if(out) { - out[0] = lim[0] - out[1] = lim[1] - return out - } - return lim -} - -function createMatrixCameraController(options) { - options = options || {} - var matrix = options.matrix || - [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] - return new MatrixCameraController(matrix) -} -},{"binary-search-bounds":29,"gl-mat4/invert":137,"gl-mat4/lookAt":138,"gl-mat4/rotateX":142,"gl-mat4/rotateY":143,"gl-mat4/rotateZ":144,"gl-mat4/scale":145,"gl-mat4/translate":146,"gl-vec3/normalize":27,"mat4-interpolate":30}],29:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],30:[function(require,module,exports){ -var lerp = require('gl-vec3/lerp') - -var recompose = require('mat4-recompose') -var decompose = require('mat4-decompose') -var determinant = require('gl-mat4/determinant') -var slerp = require('quat-slerp') - -var state0 = state() -var state1 = state() -var tmp = state() - -module.exports = interpolate -function interpolate(out, start, end, alpha) { - if (determinant(start) === 0 || determinant(end) === 0) - return false - - //decompose the start and end matrices into individual components - var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) - var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) - if (!r0 || !r1) - return false - - - //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) - lerp(tmp.translate, state0.translate, state1.translate, alpha) - lerp(tmp.skew, state0.skew, state1.skew, alpha) - lerp(tmp.scale, state0.scale, state1.scale, alpha) - lerp(tmp.perspective, state0.perspective, state1.perspective, alpha) - slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha) - - //and recompose into our 'out' matrix - recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion) - return true -} - -function state() { - return { - translate: vec3(), - scale: vec3(1), - skew: vec3(), - perspective: vec4(), - quaternion: vec4() - } -} +function state() { + return { + translate: vec3(), + scale: vec3(1), + skew: vec3(), + perspective: vec4(), + quaternion: vec4() + } +} function vec3(n) { return [n||0,n||0,n||0] @@ -1144,7 +809,7 @@ function vec3(n) { function vec4() { return [0,0,0,1] } -},{"gl-mat4/determinant":133,"gl-vec3/lerp":26,"mat4-decompose":31,"mat4-recompose":33,"quat-slerp":34}],31:[function(require,module,exports){ +},{"gl-mat4/determinant":236,"gl-vec3/lerp":25,"mat4-decompose":28,"mat4-recompose":30,"quat-slerp":31}],28:[function(require,module,exports){ /*jshint unused:true*/ /* Input: matrix ; a 4x4 matrix @@ -1324,7 +989,7 @@ function combine(out, a, b, scale1, scale2) { out[1] = a[1] * scale1 + b[1] * scale2 out[2] = a[2] * scale1 + b[2] * scale2 } -},{"./normalize":32,"gl-mat4/clone":131,"gl-mat4/create":132,"gl-mat4/determinant":133,"gl-mat4/invert":137,"gl-mat4/transpose":147,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/length":25,"gl-vec3/normalize":27}],32:[function(require,module,exports){ +},{"./normalize":29,"gl-mat4/clone":234,"gl-mat4/create":235,"gl-mat4/determinant":236,"gl-mat4/invert":240,"gl-mat4/transpose":250,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],29:[function(require,module,exports){ module.exports = function normalize(out, mat) { var m44 = mat[15] // Cannot normalize. @@ -1335,7 +1000,7 @@ module.exports = function normalize(out, mat) { out[i] = mat[i] * scale return true } -},{}],33:[function(require,module,exports){ +},{}],30:[function(require,module,exports){ /* Input: translation ; a 3 component vector scale ; a 3 component vector @@ -1396,9 +1061,9 @@ module.exports = function recomposeMat4(matrix, translation, scale, skew, perspe mat4.scale(matrix, matrix, scale) return matrix } -},{"gl-mat4/create":132,"gl-mat4/fromRotationTranslation":135,"gl-mat4/identity":136,"gl-mat4/multiply":139,"gl-mat4/scale":145,"gl-mat4/translate":146}],34:[function(require,module,exports){ +},{"gl-mat4/create":235,"gl-mat4/fromRotationTranslation":238,"gl-mat4/identity":239,"gl-mat4/multiply":242,"gl-mat4/scale":248,"gl-mat4/translate":249}],31:[function(require,module,exports){ module.exports = require('gl-quat/slerp') -},{"gl-quat/slerp":35}],35:[function(require,module,exports){ +},{"gl-quat/slerp":32}],32:[function(require,module,exports){ module.exports = slerp /** @@ -1451,7 +1116,7 @@ function slerp (out, a, b, t) { return out } -},{}],36:[function(require,module,exports){ +},{}],33:[function(require,module,exports){ 'use strict' module.exports = quatFromFrame @@ -1493,135 +1158,470 @@ function quatFromFrame( } return out } -},{}],37:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ 'use strict' -module.exports = createOrbitController - -var filterVector = require('filtered-vector') -var lookAt = require('gl-mat4/lookAt') -var mat4FromQuat = require('gl-mat4/fromQuat') -var invert44 = require('gl-mat4/invert') -var quatFromFrame = require('./lib/quatFromFrame') +module.exports = createFilteredVector -function len3(x,y,z) { - return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) -} +var cubicHermite = require('cubic-hermite') +var bsearch = require('binary-search-bounds') -function len4(w,x,y,z) { - return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) +function clamp(lo, hi, x) { + return Math.min(hi, Math.max(lo, x)) } -function normalize4(out, a) { - var ax = a[0] - var ay = a[1] - var az = a[2] - var aw = a[3] - var al = len4(ax, ay, az, aw) - if(al > 1e-6) { - out[0] = ax/al - out[1] = ay/al - out[2] = az/al - out[3] = aw/al - } else { - out[0] = out[1] = out[2] = 0.0 - out[3] = 1.0 +function FilteredVector(state0, velocity0, t0) { + this.dimension = state0.length + this.bounds = [ new Array(this.dimension), new Array(this.dimension) ] + for(var i=0; i= n-1) { + var ptr = state.length-1 + var tf = t - time[n-1] + for(var i=0; i= n-1) { + var ptr = state.length-1 + var tf = t - time[n-1] + for(var i=0; i=0; --i) { + if(velocity[--ptr]) { + return false } - mat[12+i] = -rr } + return true } -proto.getMatrix = function(t, result) { - this.recalcMatrix(t) - var m = this.computedMatrix - if(result) { - for(var i=0; i<16; ++i) { - result[i] = m[i] +proto.jump = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t < t0 || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var ptr = state.length-this.dimension + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + this._time.push(t0, t) + for(var j=0; j<2; ++j) { + for(var i=0; i0; --i) { + state.push(clamp(lo[i-1], hi[i-1], arguments[i])) + velocity.push(0) + } } -proto.idle = function(t) { - this.center.idle(t) - this.radius.idle(t) - this.rotation.idle(t) +proto.push = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t < t0 || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var ptr = state.length-this.dimension + var dt = t - t0 + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var sf = (dt > 1e-6) ? 1/dt : 0 + this._time.push(t) + for(var i=d; i>0; --i) { + var xc = clamp(lo[i-1], hi[i-1], arguments[i]) + state.push(xc) + velocity.push((xc - state[ptr++]) * sf) + } } -proto.flush = function(t) { - this.center.flush(t) - this.radius.flush(t) - this.rotation.flush(t) +proto.set = function(t) { + var d = this.dimension + if(t < this.lastT() || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + this._time.push(t) + for(var i=d; i>0; --i) { + state.push(clamp(lo[i-1], hi[i-1], arguments[i])) + velocity.push(0) + } } -proto.pan = function(t, dx, dy, dz) { - dx = dx || 0.0 - dy = dy || 0.0 - dz = dz || 0.0 - - this.recalcMatrix(t) - var mat = this.computedMatrix +proto.move = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t <= t0 || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var statePtr = state.length - this.dimension + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var dt = t - t0 + var sf = (dt > 1e-6) ? 1/dt : 0.0 + this._time.push(t) + for(var i=d; i>0; --i) { + var dx = arguments[i] + state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx)) + velocity.push(dx * sf) + } +} - var ux = mat[1] - var uy = mat[5] - var uz = mat[9] - var ul = len3(ux, uy, uz) - ux /= ul +proto.idle = function(t) { + var t0 = this.lastT() + if(t < t0) { + return + } + var d = this.dimension + var state = this._state + var velocity = this._velocity + var statePtr = state.length-d + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var dt = t - t0 + this._time.push(t) + for(var i=d-1; i>=0; --i) { + state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) + velocity.push(0) + statePtr += 1 + } +} + +function getZero(d) { + var result = new Array(d) + for(var i=0; i=0; --i) { + f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i] + } + return f + } + return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1 +} + +function cubicHermite(p0, v0, p1, v1, t, f) { + var ti = (t-1), t2 = t*t, ti2 = ti*ti, + h00 = (1+2*t)*ti2, + h10 = t*ti2, + h01 = t2*(3-2*t), + h11 = t2*ti + if(p0.length) { + if(!f) { + f = new Array(p0.length) + } + for(var i=p0.length-1; i>=0; --i) { + f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i] + } + return f + } + return h00*p0 + h10*v0 + h01*p1 + h11*v1 +} + +module.exports = cubicHermite +module.exports.derivative = dcubicHermite +},{}],37:[function(require,module,exports){ +'use strict' + +module.exports = createOrbitController + +var filterVector = require('filtered-vector') +var lookAt = require('gl-mat4/lookAt') +var mat4FromQuat = require('gl-mat4/fromQuat') +var invert44 = require('gl-mat4/invert') +var quatFromFrame = require('./lib/quatFromFrame') + +function len3(x,y,z) { + return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) +} + +function len4(w,x,y,z) { + return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) +} + +function normalize4(out, a) { + var ax = a[0] + var ay = a[1] + var az = a[2] + var aw = a[3] + var al = len4(ax, ay, az, aw) + if(al > 1e-6) { + out[0] = ax/al + out[1] = ay/al + out[2] = az/al + out[3] = aw/al + } else { + out[0] = out[1] = out[2] = 0.0 + out[3] = 1.0 + } +} + +function OrbitCameraController(initQuat, initCenter, initRadius) { + this.radius = filterVector([initRadius]) + this.center = filterVector(initCenter) + this.rotation = filterVector(initQuat) + + this.computedRadius = this.radius.curve(0) + this.computedCenter = this.center.curve(0) + this.computedRotation = this.rotation.curve(0) + this.computedUp = [0.1,0,0] + this.computedEye = [0.1,0,0] + this.computedMatrix = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] + + this.recalcMatrix(0) +} + +var proto = OrbitCameraController.prototype + +proto.lastT = function() { + return Math.max( + this.radius.lastT(), + this.center.lastT(), + this.rotation.lastT()) +} + +proto.recalcMatrix = function(t) { + this.radius.curve(t) + this.center.curve(t) + this.rotation.curve(t) + + var quat = this.computedRotation + normalize4(quat, quat) + + var mat = this.computedMatrix + mat4FromQuat(mat, quat) + + var center = this.computedCenter + var eye = this.computedEye + var up = this.computedUp + var radius = Math.exp(this.computedRadius[0]) + + eye[0] = center[0] + radius * mat[2] + eye[1] = center[1] + radius * mat[6] + eye[2] = center[2] + radius * mat[10] + up[0] = mat[1] + up[1] = mat[5] + up[2] = mat[9] + + for(var i=0; i<3; ++i) { + var rr = 0.0 + for(var j=0; j<3; ++j) { + rr += mat[i+4*j] * eye[j] + } + mat[12+i] = -rr + } +} + +proto.getMatrix = function(t, result) { + this.recalcMatrix(t) + var m = this.computedMatrix + if(result) { + for(var i=0; i<16; ++i) { + result[i] = m[i] + } + return result + } + return m +} + +proto.idle = function(t) { + this.center.idle(t) + this.radius.idle(t) + this.rotation.idle(t) +} + +proto.flush = function(t) { + this.center.flush(t) + this.radius.flush(t) + this.rotation.flush(t) +} + +proto.pan = function(t, dx, dy, dz) { + dx = dx || 0.0 + dy = dy || 0.0 + dz = dz || 0.0 + + this.recalcMatrix(t) + var mat = this.computedMatrix + + var ux = mat[1] + var uy = mat[5] + var uz = mat[9] + var ul = len3(ux, uy, uz) + ux /= ul uy /= ul uz /= ul @@ -1887,7 +1887,19 @@ function createOrbitController(options) { return result } -},{"./lib/quatFromFrame":36,"filtered-vector":20,"gl-mat4/fromQuat":134,"gl-mat4/invert":137,"gl-mat4/lookAt":138}],38:[function(require,module,exports){ +},{"./lib/quatFromFrame":33,"filtered-vector":34,"gl-mat4/fromQuat":237,"gl-mat4/invert":240,"gl-mat4/lookAt":241}],38:[function(require,module,exports){ +arguments[4][34][0].apply(exports,arguments) +},{"binary-search-bounds":39,"cubic-hermite":40,"dup":34}],39:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],40:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],41:[function(require,module,exports){ +arguments[4][22][0].apply(exports,arguments) +},{"dup":22}],42:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"dup":23}],43:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"dup":26}],44:[function(require,module,exports){ 'use strict' module.exports = createTurntableController @@ -2460,7 +2472,7 @@ function createTurntableController(options) { theta, phi) } -},{"filtered-vector":20,"gl-mat4/invert":137,"gl-mat4/rotate":141,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/normalize":27}],39:[function(require,module,exports){ +},{"filtered-vector":38,"gl-mat4/invert":240,"gl-mat4/rotate":244,"gl-vec3/cross":41,"gl-vec3/dot":42,"gl-vec3/normalize":43}],45:[function(require,module,exports){ 'use strict' module.exports = createViewController @@ -2583,7 +2595,7 @@ function createViewController(options) { matrix: matrix }, mode) } -},{"matrix-camera-controller":28,"orbit-camera-controller":37,"turntable-camera-controller":38}],40:[function(require,module,exports){ +},{"matrix-camera-controller":20,"orbit-camera-controller":37,"turntable-camera-controller":44}],46:[function(require,module,exports){ module.exports = alphaShape var ac = require('alpha-complex') @@ -2592,7 +2604,7 @@ var bnd = require('simplicial-complex-boundary') function alphaShape(alpha, points) { return bnd(ac(alpha, points)) } -},{"alpha-complex":41,"simplicial-complex-boundary":44}],41:[function(require,module,exports){ +},{"alpha-complex":47,"simplicial-complex-boundary":58}],47:[function(require,module,exports){ 'use strict' module.exports = alphaComplex @@ -2609,7 +2621,7 @@ function alphaComplex(alpha, points) { return circumradius(simplex) * alpha < 1 }) } -},{"circumradius":42,"delaunay-triangulate":114}],42:[function(require,module,exports){ +},{"circumradius":48,"delaunay-triangulate":88}],48:[function(require,module,exports){ module.exports = circumradius var circumcenter = require('circumcenter') @@ -2625,7 +2637,7 @@ function circumradius(points) { } return Math.sqrt(avgDist / points.length) } -},{"circumcenter":43}],43:[function(require,module,exports){ +},{"circumcenter":49}],49:[function(require,module,exports){ "use strict" var dup = require("dup") @@ -2694,504 +2706,885 @@ function circumcenter(points) { circumcenter.barycenetric = barycentricCircumcenter module.exports = circumcenter -},{"dup":115,"robust-linear-solve":256}],44:[function(require,module,exports){ -'use strict' - -module.exports = boundary - -var bnd = require('boundary-cells') -var reduce = require('reduce-simplicial-complex') - -function boundary(cells) { - return reduce(bnd(cells)) -} - -},{"boundary-cells":45,"reduce-simplicial-complex":48}],45:[function(require,module,exports){ +},{"dup":50,"robust-linear-solve":51}],50:[function(require,module,exports){ "use strict" -module.exports = boundary - -function boundary(cells) { - var n = cells.length - var sz = 0 - for(var i=0; i 0) { + return dupe_number(count|0, value) + } + break + case "object": + if(typeof (count.length) === "number") { + return dupe_array(count, value, 0) + } + break + } + return [] } -},{"cell-orientation":46,"compare-cell":101}],48:[function(require,module,exports){ -'use strict' +module.exports = dupe +},{}],51:[function(require,module,exports){ +"use strict" -var compareCell = require('compare-cell') -var compareOrientedCell = require('compare-oriented-cell') -var orientation = require('cell-orientation') +var determinant = require("robust-determinant") -module.exports = reduceCellComplex +var NUM_EXPAND = 6 -function reduceCellComplex(cells) { - cells.sort(compareOrientedCell) - var n = cells.length - var ptr = 0 +function generateSolver(n) { + var funcName = "robustLinearSolve" + n + "d" + var code = ["function ", funcName, "(A,b){return ["] for(var i=0; i 0) { - var f = cells[ptr-1] - if(compareCell(c, f) === 0 && - orientation(f) !== o) { - ptr -= 1 - continue + code.push("det([") + for(var j=0; j 0) { + code.push(",") + } + code.push("[") + for(var k=0; k 0) { + code.push(",") + } + if(k === i) { + code.push("+b[", j, "]") + } else { + code.push("+A[", j, "][", k, "]") + } } + code.push("]") } - cells[ptr++] = c + code.push("]),") } - cells.length = ptr - return cells + code.push("det(A)]}return ", funcName) + var proc = new Function("det", code.join("")) + if(n < 6) { + return proc(determinant[n]) + } + return proc(determinant) } -},{"cell-orientation":46,"compare-cell":101,"compare-oriented-cell":47}],49:[function(require,module,exports){ -'use strict'; - -var arraytools = function () { +function robustLinearSolve0d() { + return [ 0 ] +} - var that = {}; +function robustLinearSolve1d(A, b) { + return [ [ b[0] ], [ A[0][0] ] ] +} - var RGB_REGEX = /^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/; - var RGB_GROUP_REGEX = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/; +var CACHE = [ + robustLinearSolve0d, + robustLinearSolve1d +] - function isPlainObject (v) { - return !Array.isArray(v) && v !== null && typeof v === 'object'; +function generateDispatch() { + while(CACHE.length < NUM_EXPAND) { + CACHE.push(generateSolver(CACHE.length)) } - - function linspace (start, end, num) { - var inc = (end - start) / Math.max(num - 1, 1); - var a = []; - for( var ii = 0; ii < num; ii++) - a.push(start + ii*inc); - return a; + var procArgs = [] + var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] + for(var i=0; i=0; --i) { + var a = Q + var b = e[i] + Q = a + b + var bv = Q - a + var q = b - bv + if(q) { + e[--bottom] = Q + Q = q } - - return carr; } - - - function copy1D (arr) { - var carr = []; - for (var i = 0; i < arr.length; ++i) { - carr[i] = arr[i]; + var top = 0 + for(var i=bottom; i1 or 0->255 rgb array - var rgb, - match; - - if (typeof str !== 'string') return str; - - rgb = []; - // hex notation - if (str[0] === '#') { - str = str.substr(1) // remove hash - if (str.length === 3) str += str // fff -> ffffff - match = parseInt(str, 16); - rgb[0] = ((match >> 16) & 255); - rgb[1] = ((match >> 8) & 255); - rgb[2] = (match & 255); +function scaleLinearExpansion(e, scale) { + var n = e.length + if(n === 1) { + var ts = twoProduct(e[0], scale) + if(ts[0]) { + return ts } - - // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation - else if (RGB_REGEX.test(str)) { - match = str.match(RGB_GROUP_REGEX); - rgb[0] = parseInt(match[1]); - rgb[1] = parseInt(match[2]); - rgb[2] = parseInt(match[3]); + return [ ts[1] ] + } + var g = new Array(2 * n) + var q = [0.1, 0.1] + var t = [0.1, 0.1] + var count = 0 + twoProduct(e[0], scale, q) + if(q[0]) { + g[count++] = q[0] + } + for(var i=1; i1 or 0->255 rgb array - var rgb, - match; - - if (typeof str !== 'string') return str; +//Easy case: Add two scalars +function scalarScalar(a, b) { + var x = a + b + var bv = x - a + var av = x - bv + var br = b - bv + var ar = a - av + var y = ar + br + if(y) { + return [y, x] + } + return [x] +} - rgb = []; - // hex notation - if (str[0] === '#') { - str = str.substr(1) // remove hash - if (str.length === 3) str += str // fff -> ffffff - match = parseInt(str, 16); - rgb[0] = ((match >> 16) & 255); - rgb[1] = ((match >> 8) & 255); - rgb[2] = (match & 255); +function linearExpansionSum(e, f) { + var ne = e.length|0 + var nf = f.length|0 + if(ne === 1 && nf === 1) { + return scalarScalar(e[0], f[0]) + } + var n = ne + nf + var g = new Array(n) + var count = 0 + var eptr = 0 + var fptr = 0 + var abs = Math.abs + var ei = e[eptr] + var ea = abs(ei) + var fi = f[fptr] + var fa = abs(fi) + var a, b + if(ea < fa) { + b = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) } - - // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation - else if (RGB_REGEX.test(str)) { - match = str.match(RGB_GROUP_REGEX); - rgb[0] = parseInt(match[1]); - rgb[1] = parseInt(match[2]); - rgb[2] = parseInt(match[3]); - if (match[4]) rgb[3] = parseFloat(match[4]); - else rgb[3] = 1.0; + } else { + b = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) } - - - - if (!twoFiftySix) { - for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 + } + if((eptr < ne && ea < fa) || (fptr >= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) } - - - return rgb; } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } + } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + } + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g +} +},{}],56:[function(require,module,exports){ +"use strict" +module.exports = twoProduct +var SPLITTER = +(Math.pow(2, 27) + 1.0) +function twoProduct(a, b, result) { + var x = a * b + var c = SPLITTER * a + var abig = c - a + var ahi = c - abig + var alo = a - ahi - that.isPlainObject = isPlainObject; - that.linspace = linspace; - that.zip3 = zip3; - that.sum = sum; - that.zip = zip; - that.isEqual = isEqual; - that.copy2D = copy2D; - that.copy1D = copy1D; - that.str2RgbArray = str2RgbArray; - that.str2RgbaArray = str2RgbaArray; - - return that - -} + var d = SPLITTER * b + var bbig = d - b + var bhi = d - bbig + var blo = b - bhi + var err1 = x - (ahi * bhi) + var err2 = err1 - (alo * bhi) + var err3 = err2 - (ahi * blo) -module.exports = arraytools(); + var y = alo * blo - err3 -},{}],50:[function(require,module,exports){ -/** - * Bit twiddling hacks for JavaScript. - * - * Author: Mikola Lysenko - * - * Ported from Stanford bit twiddling hack library: - * http://graphics.stanford.edu/~seander/bithacks.html - */ + if(result) { + result[0] = y + result[1] = x + return result + } -"use strict"; "use restrict"; + return [ y, x ] +} +},{}],57:[function(require,module,exports){ +"use strict" -//Number of bits in an integer -var INT_BITS = 32; +var twoProduct = require("two-product") +var robustSum = require("robust-sum") +var robustScale = require("robust-scale") +var compress = require("robust-compress") -//Constants -exports.INT_BITS = INT_BITS; -exports.INT_MAX = 0x7fffffff; -exports.INT_MIN = -1<<(INT_BITS-1); +var NUM_EXPANDED = 6 -//Returns -1, 0, +1 depending on sign of x -exports.sign = function(v) { - return (v > 0) - (v < 0); +function cofactor(m, c) { + var result = new Array(m.length-1) + for(var i=1; i> (INT_BITS-1); - return (v ^ mask) - mask; +function matrix(n) { + var result = new Array(n) + for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") + } } -//Checks if a number is a power of two -exports.isPow2 = function(v) { - return !(v & (v-1)) && (!!v); +function determinant(m) { + if(m.length === 2) { + return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") + } else { + var expr = [] + for(var i=0; i 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); +function compileDeterminant(n) { + var proc = new Function("sum", "scale", "prod", "compress", [ + "function robustDeterminant",n, "(m){return compress(", + determinant(matrix(n)), + ")};return robustDeterminant", n].join("")) + return proc(robustSum, robustScale, twoProduct, compress) } -//Computes log base 10 of v -exports.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} +var CACHE = [ + function robustDeterminant0() { return [0] }, + function robustDeterminant1(m) { return [m[0][0]] } +] -//Counts number of bits -exports.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +function generateDispatch() { + while(CACHE.length < NUM_EXPANDED) { + CACHE.push(compileDeterminant(CACHE.length)) + } + var procArgs = [] + var code = ["function robustDeterminant(m){switch(m.length){"] + for(var i=0; i>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; -} +module.exports = boundary -//Rounds down to previous power of 2 -exports.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); -} +var bnd = require('boundary-cells') +var reduce = require('reduce-simplicial-complex') -//Computes parity of word -exports.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; +function boundary(cells) { + return reduce(bnd(cells)) } -var REVERSE_TABLE = new Array(256); +},{"boundary-cells":59,"reduce-simplicial-complex":63}],59:[function(require,module,exports){ +'use strict' -(function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; +module.exports = boundary + +function boundary (cells) { + var i, j, k + var n = cells.length + var sz = 0 + for (i = 0; i < n; ++i) { + sz += cells[i].length + } + var result = new Array(sz) + var ptr = 0 + for (i = 0; i < n; ++i) { + var c = cells[i] + var d = c.length + for (j = 0; j < d; ++j) { + var b = result[ptr++] = new Array(d - 1) + var p = 0 + for (k = 0; k < d; ++k) { + if (k === j) { + continue + } + b[p++] = c[k] + } + if (j & 1) { + var tmp = b[1] + b[1] = b[0] + b[0] = tmp + } } - tab[i] = (r << s) & 0xff; } -})(REVERSE_TABLE); - -//Reverse bits in a 32 bit word -exports.reverse = function(v) { - return (REVERSE_TABLE[ v & 0xff] << 24) | - (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; + return result } -//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -exports.interleave2 = function(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; +},{}],60:[function(require,module,exports){ +'use strict' - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; +module.exports = orientation - return x | (y << 1); +function orientation(s) { + var p = 1 + for(var i=1; i>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; +},{}],61:[function(require,module,exports){ +module.exports = compareCells + +var min = Math.min + +function compareInt(a, b) { + return a - b +} + +function compareCells(a, b) { + var n = a.length + , t = a.length - b.length + if(t) { + return t + } + switch(n) { + case 0: + return 0 + case 1: + return a[0] - b[0] + case 2: + return (a[0]+a[1]-b[0]-b[1]) || + min(a[0],a[1]) - min(b[0],b[1]) + case 3: + var l1 = a[0]+a[1] + , m1 = b[0]+b[1] + t = l1+a[2] - (m1+b[2]) + if(t) { + return t + } + var l0 = min(a[0], a[1]) + , m0 = min(b[0], b[1]) + return min(l0, a[2]) - min(m0, b[2]) || + min(l0+a[2], l1) - min(m0+b[2], m1) + case 4: + var aw=a[0], ax=a[1], ay=a[2], az=a[3] + , bw=b[0], bx=b[1], by=b[2], bz=b[3] + return (aw+ax+ay+az)-(bw+bx+by+bz) || + min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) || + min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) - + min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) || + min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) - + min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz) + default: + var as = a.slice().sort(compareInt) + var bs = b.slice().sort(compareInt) + for(var i=0; i>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; +},{"cell-orientation":60,"compare-cell":61}],63:[function(require,module,exports){ +'use strict' + +var compareCell = require('compare-cell') +var compareOrientedCell = require('compare-oriented-cell') +var orientation = require('cell-orientation') + +module.exports = reduceCellComplex + +function reduceCellComplex(cells) { + cells.sort(compareOrientedCell) + var n = cells.length + var ptr = 0 + for(var i=0; i 0) { + var f = cells[ptr-1] + if(compareCell(c, f) === 0 && + orientation(f) !== o) { + ptr -= 1 + continue + } + } + cells[ptr++] = c + } + cells.length = ptr + return cells } -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -exports.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +},{"cell-orientation":60,"compare-cell":61,"compare-oriented-cell":62}],64:[function(require,module,exports){ +'use strict'; + +var arraytools = function () { + + var that = {}; + + var RGB_REGEX = /^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/; + var RGB_GROUP_REGEX = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/; + + function isPlainObject (v) { + return !Array.isArray(v) && v !== null && typeof v === 'object'; + } + + function linspace (start, end, num) { + var inc = (end - start) / Math.max(num - 1, 1); + var a = []; + for( var ii = 0; ii < num; ii++) + a.push(start + ii*inc); + return a; + } + + function zip () { + var arrays = [].slice.call(arguments); + var lengths = arrays.map(function (a) {return a.length;}); + var len = Math.min.apply(null, lengths); + var zipped = []; + for (var i = 0; i < len; i++) { + zipped[i] = []; + for (var j = 0; j < arrays.length; ++j) { + zipped[i][j] = arrays[j][i]; + } + } + return zipped; + } + + function zip3 (a, b, c) { + var len = Math.min.apply(null, [a.length, b.length, c.length]); + var result = []; + for (var n = 0; n < len; n++) { + result.push([a[n], b[n], c[n]]); + } + return result; + } + + function sum (A) { + var acc = 0; + accumulate(A, acc); + function accumulate(x) { + for (var i = 0; i < x.length; i++) { + if (Array.isArray(x[i])) + accumulate(x[i], acc); + else + acc += x[i]; + } + } + return acc; + } + + function copy2D (arr) { + var carr = []; + for (var i = 0; i < arr.length; ++i) { + carr[i] = []; + for (var j = 0; j < arr[i].length; ++j) { + carr[i][j] = arr[i][j]; + } + } + + return carr; + } + + + function copy1D (arr) { + var carr = []; + for (var i = 0; i < arr.length; ++i) { + carr[i] = arr[i]; + } + + return carr; + } + + + function isEqual(arr1, arr2) { + if(arr1.length !== arr2.length) + return false; + for(var i = arr1.length; i--;) { + if(arr1[i] !== arr2[i]) + return false; + } + + return true; + } + + + function str2RgbArray(str, twoFiftySix) { + // convert hex or rbg strings to 0->1 or 0->255 rgb array + var rgb, + match; + + if (typeof str !== 'string') return str; + + rgb = []; + // hex notation + if (str[0] === '#') { + str = str.substr(1) // remove hash + if (str.length === 3) str += str // fff -> ffffff + match = parseInt(str, 16); + rgb[0] = ((match >> 16) & 255); + rgb[1] = ((match >> 8) & 255); + rgb[2] = (match & 255); + } + + // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation + else if (RGB_REGEX.test(str)) { + match = str.match(RGB_GROUP_REGEX); + rgb[0] = parseInt(match[1]); + rgb[1] = parseInt(match[2]); + rgb[2] = parseInt(match[3]); + } + + if (!twoFiftySix) { + for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 + } + + + return rgb; + } + + + function str2RgbaArray(str, twoFiftySix) { + // convert hex or rbg strings to 0->1 or 0->255 rgb array + var rgb, + match; + + if (typeof str !== 'string') return str; + + rgb = []; + // hex notation + if (str[0] === '#') { + str = str.substr(1) // remove hash + if (str.length === 3) str += str // fff -> ffffff + match = parseInt(str, 16); + rgb[0] = ((match >> 16) & 255); + rgb[1] = ((match >> 8) & 255); + rgb[2] = (match & 255); + } + + // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation + else if (RGB_REGEX.test(str)) { + match = str.match(RGB_GROUP_REGEX); + rgb[0] = parseInt(match[1]); + rgb[1] = parseInt(match[2]); + rgb[2] = parseInt(match[3]); + if (match[4]) rgb[3] = parseFloat(match[4]); + else rgb[3] = 1.0; + } + + + + if (!twoFiftySix) { + for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 + } + + + return rgb; + } + + + + + + that.isPlainObject = isPlainObject; + that.linspace = linspace; + that.zip3 = zip3; + that.sum = sum; + that.zip = zip; + that.isEqual = isEqual; + that.copy2D = copy2D; + that.copy1D = copy1D; + that.str2RgbArray = str2RgbArray; + that.str2RgbaArray = str2RgbaArray; + + return that + } -},{}],51:[function(require,module,exports){ +module.exports = arraytools(); + +},{}],65:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -3210,9 +3603,6 @@ var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 -Buffer.poolSize = 8192 // not used by this implementation - -var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -3242,6 +3632,11 @@ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + function typedArraySupport () { try { var arr = new Uint8Array(1) @@ -3260,6 +3655,25 @@ function kMaxLength () { : 0x3fffffff } +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of @@ -3269,183 +3683,208 @@ function kMaxLength () { * * The `Uint8Array` prototype remains unmodified. */ -function Buffer (arg) { - if (!(this instanceof Buffer)) { - // Avoid going through an ArgumentsAdaptorTrampoline in the common case. - if (arguments.length > 1) return new Buffer(arg, arguments[1]) - return new Buffer(arg) - } - if (!Buffer.TYPED_ARRAY_SUPPORT) { - this.length = 0 - this.parent = undefined +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { - return fromNumber(this, arg) - } - - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) } - - // Unusual. - return fromObject(this, arg) + return from(this, arg, encodingOrOffset, length) } +Buffer.poolSize = 8192 // not used by this implementation + // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } -function fromNumber (that, length) { - that = allocate(that, length < 0 ? 0 : checked(length) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < length; i++) { - that[i] = 0 - } +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') } - return that -} -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - // Assumption: byteLength() return value is always < kMaxLength. - var length = byteLength(string, encoding) | 0 - that = allocate(that, length) + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } - that.write(string, encoding) - return that + return fromObject(that, value) } -function fromObject (that, object) { - if (Buffer.isBuffer(object)) return fromBuffer(that, object) - - if (isArray(object)) return fromArray(that, object) +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} - if (object == null) { - throw new TypeError('must start with number, buffer, array or string') +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) } +} - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) - } +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') } +} - if (object.length) return fromArrayLike(that, object) - - return fromJsonObject(that, object) +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) } -function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) } -function fromArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; i++) { + that[i] = 0 + } } return that } -// Duplicate of fromArray() to keep fromArray() monomorphic. -function fromTypedArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - // Truncating the elements is probably not what people expect from typed - // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior - // of the old Buffer constructor. - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) } -function fromArrayBuffer (that, array) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(array) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromTypedArray(that, new Uint8Array(array)) + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + that.write(string, encoding) return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 - that = allocate(that, length) + that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } -// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. -// Returns a zero-length buffer for inputs that don't conform to the spec. -function fromJsonObject (that, object) { - var array - var length = 0 +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') } - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') } - return that -} -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) + if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) } -} else { - // pre-set for values that may exist in the future - Buffer.prototype.length = undefined - Buffer.prototype.parent = undefined -} -function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) + that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class - that.length = length + that = fromArrayLike(that, array) } + return that +} - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) - return that + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { @@ -3458,12 +3897,11 @@ function checked (length) { return length | 0 } -function SlowBuffer (subject, encoding) { - if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) - - var buf = new Buffer(subject, encoding) - delete buf.parent - return buf +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { @@ -3480,17 +3918,12 @@ Buffer.compare = function compare (a, b) { var x = a.length var y = b.length - var i = 0 - var len = Math.min(x, y) - while (i < len) { - if (a[i] !== b[i]) break - - ++i - } - - if (i !== len) { - x = a[i] - y = b[i] + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } } if (x < y) return -1 @@ -3518,10 +3951,12 @@ Buffer.isEncoding = function isEncoding (encoding) { } Buffer.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } if (list.length === 0) { - return new Buffer(0) + return Buffer.alloc(0) } var i @@ -3532,18 +3967,30 @@ Buffer.concat = function concat (list, length) { } } - var buf = new Buffer(length) + var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length } - return buf + return buffer } function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } var len = string.length if (len === 0) return 0 @@ -3560,6 +4007,7 @@ function byteLength (string, encoding) { return len case 'utf8': case 'utf-8': + case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': @@ -3582,13 +4030,39 @@ Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' while (true) { switch (encoding) { @@ -3626,6 +4100,35 @@ function slowToString (encoding, start, end) { // Buffer instances. Buffer.prototype._isBuffer = true +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' @@ -3649,16 +4152,115 @@ Buffer.prototype.inspect = function inspect () { return '' } -Buffer.prototype.compare = function compare (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return 0 - return Buffer.compare(this, b) -} +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } -Buffer.prototype.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +function arrayIndexOf (arr, val, byteOffset, encoding) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var foundIndex = -1 + for (var i = 0; byteOffset + i < arrLength; i++) { + if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + return -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 @@ -3667,35 +4269,30 @@ Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { - if (val.length === 0) return -1 // special case: looking for empty string always fails - return String.prototype.indexOf.call(this, val, byteOffset) + val = Buffer.from(val, encoding) } + if (Buffer.isBuffer(val)) { - return arrayIndexOf(this, val, byteOffset) + // special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(this, val, byteOffset, encoding) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } - return arrayIndexOf(this, [ val ], byteOffset) - } - - function arrayIndexOf (arr, val, byteOffset) { - var foundIndex = -1 - for (var i = 0; byteOffset + i < arr.length; i++) { - if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex - } else { - foundIndex = -1 - } - } - return -1 + return arrayIndexOf(this, [ val ], byteOffset, encoding) } throw new TypeError('val must be string, number or Buffer') } +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset @@ -3717,7 +4314,7 @@ function hexWrite (buf, string, offset, length) { } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) throw new Error('Invalid hex string') + if (isNaN(parsed)) return i buf[offset + i] = parsed } return i @@ -3766,17 +4363,16 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { - var swap = encoding - encoding = offset - offset = length | 0 - length = swap + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' @@ -4001,8 +4597,6 @@ Buffer.prototype.slice = function slice (start, end) { } } - if (newBuf.length) newBuf.parent = this.parent || this - return newBuf } @@ -4171,16 +4765,19 @@ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { } function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var mul = 1 var i = 0 @@ -4196,7 +4793,10 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var i = byteLength - 1 var mul = 1 @@ -4299,9 +4899,12 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no var i = 0 var mul = 1 - var sub = value < 0 ? 1 : 0 + var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -4319,9 +4922,12 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no var i = byteLength - 1 var mul = 1 - var sub = value < 0 ? 1 : 0 + var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -4396,8 +5002,8 @@ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) } function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('index out of range') - if (offset < 0) throw new RangeError('index out of range') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { @@ -4481,31 +5087,63 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { return len } -// fill(value, start=0, end=buffer.length) -Buffer.prototype.fill = function fill (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } - if (end < start) throw new RangeError('end < start') + if (end <= start) { + return this + } - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') - if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + if (!val) val = 0 var i - if (typeof value === 'number') { + if (typeof val === 'number') { for (i = start; i < end; i++) { - this[i] = value + this[i] = val } } else { - var bytes = utf8ToBytes(value.toString()) + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] + for (i = 0; i < end - start; i++) { + this[i + start] = bytes[i % len] } } @@ -4656,8 +5294,12 @@ function blitBuffer (src, dst, offset, length) { return i } +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":52,"ieee754":53,"isarray":54}],52:[function(require,module,exports){ +},{"base64-js":66,"ieee754":67,"isarray":68}],66:[function(require,module,exports){ 'use strict' exports.toByteArray = toByteArray @@ -4668,17 +5310,12 @@ var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array function init () { - var i var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - var len = code.length - - for (i = 0; i < len; i++) { + for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] - } - - for (i = 0; i < len; ++i) { revLookup[code.charCodeAt(i)] = i } + revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 } @@ -4710,8 +5347,8 @@ function toByteArray (b64) { for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp & 0xFF0000) >> 16 - arr[L++] = (tmp & 0xFF00) >> 8 + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } @@ -4773,7 +5410,7 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],53:[function(require,module,exports){ +},{}],67:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -4859,14 +5496,14 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],54:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],55:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -5166,16 +5803,44 @@ function isUndefined(arg) { return arg === void 0; } -},{}],56:[function(require,module,exports){ +},{}],70:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +(function () { + try { + cachedSetTimeout = setTimeout; + } catch (e) { + cachedSetTimeout = function () { + throw new Error('setTimeout is not defined'); + } + } + try { + cachedClearTimeout = clearTimeout; + } catch (e) { + cachedClearTimeout = function () { + throw new Error('clearTimeout is not defined'); + } + } +} ()) var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); @@ -5191,7 +5856,7 @@ function drainQueue() { if (draining) { return; } - var timeout = setTimeout(cleanUpNextTick); + var timeout = cachedSetTimeout(cleanUpNextTick); draining = true; var len = queue.length; @@ -5208,7 +5873,7 @@ function drainQueue() { } currentQueue = null; draining = false; - clearTimeout(timeout); + cachedClearTimeout(timeout); } process.nextTick = function (fun) { @@ -5220,7 +5885,7 @@ process.nextTick = function (fun) { } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { - setTimeout(drainQueue, 0); + cachedSetTimeout(drainQueue, 0); } }; @@ -5259,34921 +5924,36483 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],57:[function(require,module,exports){ -'use strict' - -var monotoneTriangulate = require('./lib/monotone') -var makeIndex = require('./lib/triangulation') -var delaunayFlip = require('./lib/delaunay') -var filterTriangulation = require('./lib/filter') - -module.exports = cdt2d - -function canonicalizeEdge(e) { - return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] -} - -function compareEdge(a, b) { - return a[0]-b[0] || a[1]-b[1] -} - -function canonicalizeEdges(edges) { - return edges.map(canonicalizeEdge).sort(compareEdge) -} +},{}],71:[function(require,module,exports){ +"use strict" -function getDefault(options, property, dflt) { - if(property in options) { - return options[property] - } - return dflt -} +var convexHull1d = require('./lib/ch1d') +var convexHull2d = require('./lib/ch2d') +var convexHullnd = require('./lib/chnd') -function cdt2d(points, edges, options) { +module.exports = convexHull - if(!Array.isArray(edges)) { - options = edges || {} - edges = [] - } else { - options = options || {} - edges = edges || [] +function convexHull(points) { + var n = points.length + if(n === 0) { + return [] + } else if(n === 1) { + return [[0]] } - - //Parse out options - var delaunay = !!getDefault(options, 'delaunay', true) - var interior = !!getDefault(options, 'interior', true) - var exterior = !!getDefault(options, 'exterior', true) - var infinity = !!getDefault(options, 'infinity', false) - - //Handle trivial case - if((!interior && !exterior) || points.length === 0) { + var d = points[0].length + if(d === 0) { return [] + } else if(d === 1) { + return convexHull1d(points) + } else if(d === 2) { + return convexHull2d(points) } + return convexHullnd(points, d) +} +},{"./lib/ch1d":72,"./lib/ch2d":73,"./lib/chnd":74}],72:[function(require,module,exports){ +"use strict" - //Construct initial triangulation - var cells = monotoneTriangulate(points, edges) - - //If delaunay refinement needed, then improve quality by edge flipping - if(delaunay || interior !== exterior || infinity) { - - //Index all of the cells to support fast neighborhood queries - var triangulation = makeIndex(points.length, canonicalizeEdges(edges)) - for(var i=0; i points[hi][0]) { + hi = i } - + } + if(lo < hi) { + return [[lo], [hi]] + } else if(lo > hi) { + return [[hi], [lo]] } else { - return cells + return [[lo]] } } - -},{"./lib/delaunay":58,"./lib/filter":59,"./lib/monotone":60,"./lib/triangulation":61}],58:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ 'use strict' -var inCircle = require('robust-in-sphere')[4] -var bsearch = require('binary-search-bounds') - -module.exports = delaunayRefine +module.exports = convexHull2D -function testFlip(points, triangulation, stack, a, b, x) { - var y = triangulation.opposite(a, b) +var monotoneHull = require('monotone-convex-hull-2d') - //Test boundary edge - if(y < 0) { - return +function convexHull2D(points) { + var hull = monotoneHull(points) + var h = hull.length + if(h <= 2) { + return [] } - - //Swap edge if order flipped - if(b < a) { - var tmp = a + var edges = new Array(h) + var a = hull[h-1] + for(var i=0; i= front[k]) { + x += 1 + } } + c[j] = x } + } + } + return cells +} - //If this is a boundary edge, don't flip it - if(y < 0) { - continue - } - - //If edge is in circle, flip it - if(inCircle(points[a], points[b], points[x], points[y]) < 0) { - stack.push(a, b) - } +function convexHullnD(points, d) { + try { + return ich(points, true) + } catch(e) { + //If point set is degenerate, try to find a basis and rerun it + var ah = aff(points) + if(ah.length <= d) { + //No basis, no try + return [] } + var npoints = permute(points, ah) + var nhull = ich(npoints, true) + return invPermute(nhull, ah) } +} +},{"affine-hull":75,"incremental-convex-hull":76}],75:[function(require,module,exports){ +'use strict' - while(stack.length > 0) { - var b = stack.pop() - var a = stack.pop() +module.exports = affineHull - //Find opposite pairs - var x = -1, y = -1 - var star = stars[a] - for(var i=1; i= 0) { +function affineHull(points) { + var n = points.length + if(n === 0) { + return [] + } + if(n === 1) { + return [0] + } + var d = points[0].length + var frame = [ points[0] ] + var index = [ 0 ] + for(var i=1; i 0) { + code.push(",") } + code.push("tuple[", i, "]") } - cells.sort(compareCell) - - //Initialize flag array - var flags = new Array(nc) - for(var i=0; i 0 || next.length > 0) { - while(active.length > 0) { - var t = active.pop() - if(flags[t] === -side) { + //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate + var toVisit = [ cell ] + cell.lastVisited = -n + while(toVisit.length > 0) { + cell = toVisit.pop() + var cellVerts = cell.vertices + var cellAdj = cell.adjacent + for(var i=0; i<=d; ++i) { + var neighbor = cellAdj[i] + if(!neighbor.boundary || neighbor.lastVisited <= -n) { continue } - flags[t] = side - var c = cells[t] - for(var j=0; j<3; ++j) { - var f = neighbor[3*t+j] - if(f >= 0 && flags[f] === 0) { - if(constraint[3*t+j]) { - next.push(f) - } else { - active.push(f) - flags[f] = side - } + var nv = neighbor.vertices + for(var j=0; j<=d; ++j) { + var vv = nv[j] + if(vv < 0) { + tuple[j] = point + } else { + tuple[j] = verts[vv] } } + var o = this.orient() + if(o > 0) { + return neighbor + } + neighbor.lastVisited = -n + if(o === 0) { + toVisit.push(neighbor) + } } - - //Swap arrays and loop - var tmp = next - next = active - active = tmp - next.length = 0 - side = -side - } - - var result = filterCells(cells, flags, target) - if(infinity) { - return result.concat(index.boundary) } - return result + return null } -},{"binary-search-bounds":62}],60:[function(require,module,exports){ -'use strict' +proto.walk = function(point, random) { + //Alias local properties + var n = this.vertices.length - 1 + var d = this.dimension + var verts = this.vertices + var tuple = this.tuple -var bsearch = require('binary-search-bounds') -var orient = require('robust-orientation')[3] + //Compute initial jump cell + var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1) + var cell = this.interior[ initIndex ] -var EVENT_POINT = 0 -var EVENT_END = 1 -var EVENT_START = 2 + //Start walking +outerLoop: + while(!cell.boundary) { + var cellVerts = cell.vertices + var cellAdj = cell.adjacent -module.exports = monotoneTriangulate + for(var i=0; i<=d; ++i) { + tuple[i] = verts[cellVerts[i]] + } + cell.lastVisited = n -//A partial convex hull fragment, made of two unimonotone polygons -function PartialHull(a, b, idx, lowerIds, upperIds) { - this.a = a - this.b = b - this.idx = idx - this.lowerIds = lowerIds - this.upperIds = upperIds -} + //Find farthest adjacent cell + for(var i=0; i<=d; ++i) { + var neighbor = cellAdj[i] + if(neighbor.lastVisited >= n) { + continue + } + var prev = tuple[i] + tuple[i] = point + var o = this.orient() + tuple[i] = prev + if(o < 0) { + cell = neighbor + continue outerLoop + } else { + if(!neighbor.boundary) { + neighbor.lastVisited = n + } else { + neighbor.lastVisited = -n + } + } + } + return + } -//An event in the sweep line procedure -function Event(a, b, type, idx) { - this.a = a - this.b = b - this.type = type - this.idx = idx + return cell } -//This is used to compare events for the sweep line procedure -// Points are: -// 1. sorted lexicographically -// 2. sorted by type (point < end < start) -// 3. segments sorted by winding order -// 4. sorted by index -function compareEvent(a, b) { - var d = - (a.a[0] - b.a[0]) || - (a.a[1] - b.a[1]) || - (a.type - b.type) - if(d) { return d } - if(a.type !== EVENT_POINT) { - d = orient(a.a, a.b, b.b) - if(d) { return d } - } - return a.idx - b.idx -} +proto.addPeaks = function(point, cell) { + var n = this.vertices.length - 1 + var d = this.dimension + var verts = this.vertices + var tuple = this.tuple + var interior = this.interior + var simplices = this.simplices -function testPoint(hull, p) { - return orient(hull.a, hull.b, p) -} + //Walking finished at boundary, time to add peaks + var tovisit = [ cell ] -function addPoint(cells, hulls, points, p, idx) { - var lo = bsearch.lt(hulls, p, testPoint) - var hi = bsearch.gt(hulls, p, testPoint) - for(var i=lo; i 1 && orient( - points[lowerIds[m-2]], - points[lowerIds[m-1]], - p) > 0) { - cells.push( - [lowerIds[m-1], - lowerIds[m-2], - idx]) - m -= 1 - } - lowerIds.length = m - lowerIds.push(idx) + //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done + var glueFacets = [] - //Insert p into upper hull - var upperIds = hull.upperIds - var m = upperIds.length - while(m > 1 && orient( - points[upperIds[m-2]], - points[upperIds[m-1]], - p) < 0) { - cells.push( - [upperIds[m-2], - upperIds[m-1], - idx]) - m -= 1 + //Do a traversal of the boundary walking outward from starting peak + while(tovisit.length > 0) { + //Pop off peak and walk over adjacent cells + var cell = tovisit.pop() + var cellVerts = cell.vertices + var cellAdj = cell.adjacent + var indexOfN = cellVerts.indexOf(n) + if(indexOfN < 0) { + continue } - upperIds.length = m - upperIds.push(idx) - } -} -function findSplit(hull, edge) { - var d - if(hull.a[0] < edge.a[0]) { - d = orient(hull.a, hull.b, edge.a) - } else { - d = orient(edge.b, edge.a, hull.a) - } - if(d) { return d } - if(edge.b[0] < hull.b[0]) { - d = orient(hull.a, hull.b, edge.b) - } else { - d = orient(edge.b, edge.a, hull.b) - } - return d || hull.idx - edge.idx -} + for(var i=0; i<=d; ++i) { + if(i === indexOfN) { + continue + } -function splitHulls(hulls, points, event) { - var splitIdx = bsearch.le(hulls, event, findSplit) - var hull = hulls[splitIdx] - var upperIds = hull.upperIds - var x = upperIds[upperIds.length-1] - hull.upperIds = [x] - hulls.splice(splitIdx+1, 0, - new PartialHull(event.a, event.b, event.idx, [x], upperIds)) -} + //For each boundary neighbor of the cell + var neighbor = cellAdj[i] + if(!neighbor.boundary || neighbor.lastVisited >= n) { + continue + } + var nv = neighbor.vertices -function mergeHulls(hulls, points, event) { - //Swap pointers for merge search - var tmp = event.a - event.a = event.b - event.b = tmp - var mergeIdx = bsearch.eq(hulls, event, findSplit) - var upper = hulls[mergeIdx] - var lower = hulls[mergeIdx-1] - lower.upperIds = upper.upperIds - hulls.splice(mergeIdx, 1) -} + //Test if neighbor is a peak + if(neighbor.lastVisited !== -n) { + //Compute orientation of p relative to each boundary peak + var indexOfNeg1 = 0 + for(var j=0; j<=d; ++j) { + if(nv[j] < 0) { + indexOfNeg1 = j + tuple[j] = point + } else { + tuple[j] = verts[nv[j]] + } + } + var o = this.orient() + //Test if neighbor cell is also a peak + if(o > 0) { + nv[indexOfNeg1] = n + neighbor.boundary = false + interior.push(neighbor) + tovisit.push(neighbor) + neighbor.lastVisited = n + continue + } else { + neighbor.lastVisited = -n + } + } -function monotoneTriangulate(points, edges) { + var na = neighbor.adjacent - var numPoints = points.length - var numEdges = edges.length + //Otherwise, replace neighbor with new face + var vverts = cellVerts.slice() + var vadj = cellAdj.slice() + var ncell = new Simplex(vverts, vadj, true) + simplices.push(ncell) - var events = [] + //Connect to neighbor + var opposite = na.indexOf(cell) + if(opposite < 0) { + continue + } + na[opposite] = ncell + vadj[indexOfN] = neighbor - //Create point events - for(var i=0; i b[0]) { - events.push( - new Event(b, a, EVENT_START, i), - new Event(a, b, EVENT_END, i)) + //Flip facet + ncell.flip() + + //Add to glue list + for(var j=0; j<=d; ++j) { + var uu = vverts[j] + if(uu < 0 || uu === n) { + continue + } + var nface = new Array(d-1) + var nptr = 0 + for(var k=0; k<=d; ++k) { + var vv = vverts[k] + if(vv < 0 || k === j) { + continue + } + nface[nptr++] = vv + } + glueFacets.push(new GlueFacet(nface, ncell, j)) + } } } - //Sort events - events.sort(compareEvent) - - //Initialize hull - var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52) - var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ] + //Glue boundary facets together + glueFacets.sort(compareGlue) - //Process events in order - var cells = [] - for(var i=0, numEvents=events.length; i= 0 + var o = this.orient(tuple) + if(o < 0) { + return + } else if(o === 0) { + cell = this.handleBoundaryDegeneracy(cell, point) + if(!cell) { + return + } } -})() -proto.removeTriangle = function(i, j, k) { - var stars = this.stars - removePair(stars[i], j, k) - removePair(stars[j], k, i) - removePair(stars[k], i, j) + //Add peaks + this.addPeaks(point, cell) } -proto.addTriangle = function(i, j, k) { - var stars = this.stars - stars[i].push(j, k) - stars[j].push(k, i) - stars[k].push(i, j) -} - -proto.opposite = function(j, i) { - var list = this.stars[i] - for(var k=1, n=list.length; k= 0) { + bcell[ptr++] = cv[j] + } else { + parity = j&1 + } + } + if(parity === (d&1)) { + var t = bcell[0] + bcell[0] = bcell[1] + bcell[1] = t + } + boundary.push(bcell) } } - return -1 + return boundary } -proto.flip = function(i, j) { - var a = this.opposite(i, j) - var b = this.opposite(j, i) - this.removeTriangle(i, j, a) - this.removeTriangle(j, i, b) - this.addTriangle(i, b, a) - this.addTriangle(j, a, b) -} +function incrementalConvexHull(points, randomSearch) { + var n = points.length + if(n === 0) { + throw new Error("Must have at least d+1 points") + } + var d = points[0].length + if(n <= d) { + throw new Error("Must input at least d+1 points") + } -proto.edges = function() { - var stars = this.stars - var result = [] - for(var i=0, n=stars.length; i>>1,x=a[m]"] - if(earlyOut) { - if(predicate.indexOf("c") < 0) { - code.push(";if(x===y){return m}else if(x<=y){") - } else { - code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") - } - } else { - code.push(";if(", predicate, "){i=m;") - } - if(reversed) { - code.push("l=m+1}else{h=m-1}") - } else { - code.push("h=m-1}else{l=m+1}") - } - code.push("}") - if(earlyOut) { - code.push("return -1};") - } else { - code.push("return i};") + //Insert remaining points + var useRandom = !!randomSearch + for(var i=d+1; i 0) - (v < 0); } -module.exports = { - ge: compileBoundsSearch(">=", false, "GE"), - gt: compileBoundsSearch(">", false, "GT"), - lt: compileBoundsSearch("<", true, "LT"), - le: compileBoundsSearch("<=", true, "LE"), - eq: compileBoundsSearch("-", true, "EQ", true) +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; } -},{}],63:[function(require,module,exports){ -"use strict" +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} -var twoProduct = require("two-product") -var robustSum = require("robust-sum") -var robustDiff = require("robust-subtract") -var robustScale = require("robust-scale") +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} -var NUM_EXPAND = 6 +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} -function cofactor(m, c) { - var result = new Array(m.length-1) - for(var i=1; i 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); } -function matrix(n) { - var result = new Array(n) - for(var i=0; i= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } -function generateSum(expr) { - if(expr.length === 1) { - return expr[0] - } else if(expr.length === 2) { - return ["sum(", expr[0], ",", expr[1], ")"].join("") - } else { - var m = expr.length>>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; } -function makeProduct(a, b) { - if(a.charAt(0) === "m") { - if(b.charAt(0) === "w") { - var toks = a.split("[") - return ["w", b.substr(1), "m", toks[0].substr(1)].join("") - } else { - return ["prod(", a, ",", b, ")"].join("") - } - } else { - return makeProduct(b, a) - } +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; } +exports.countTrailingZeros = countTrailingZeros; -function sign(s) { - if(s & 1 !== 0) { - return "-" - } - return "" +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; } -function determinant(m) { - if(m.length === 2) { - return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] - } else { - var expr = [] - for(var i=0; i>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); } -function makeSquare(d, n) { - var terms = [] - for(var i=0; i>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; } -function orientation(n) { - var pos = [] - var neg = [] - var m = matrix(n) - for(var i=0; i>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; } + tab[i] = (r << s) & 0xff; } - code.push("var p=", posExpr, ",n=", negExpr, ",d=diff(p,n);return d[d.length-1];}return ", funcName) - var proc = new Function("sum", "diff", "prod", "scale", code.join("")) - return proc(robustSum, robustDiff, twoProduct, robustScale) +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; } -function inSphere0() { return 0 } -function inSphere1() { return 0 } -function inSphere2() { return 0 } +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; -var CACHED = [ - inSphere0, - inSphere1, - inSphere2 -] + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; -function slowInSphere(args) { - var proc = CACHED[args.length] - if(!proc) { - proc = CACHED[args.length] = orientation(args.length) - } - return proc.apply(undefined, args) + return x | (y << 1); } -function generateInSphereTest() { - while(CACHED.length <= NUM_EXPAND) { - CACHED.push(orientation(CACHED.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=NUM_EXPAND; ++i) { - args.push("a" + i) - procArgs.push("o" + i) - } - var code = [ - "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=NUM_EXPAND; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") - } - code.push("}var s=new Array(arguments.length);for(var i=0;i>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; } -generateInSphereTest() -},{"robust-scale":260,"robust-subtract":261,"robust-sum":262,"two-product":276}],64:[function(require,module,exports){ -'use strict' -module.exports = cleanPSLG +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; -var UnionFind = require('union-find') -var boxIntersect = require('box-intersect') -var compareCell = require('compare-cell') -var segseg = require('robust-segment-intersect') -var rat = require('big-rat') -var ratCmp = require('big-rat/cmp') -var ratToFloat = require('big-rat/to-float') -var ratVec = require('rat-vec') -var nextafter = require('nextafter') + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} -var solveIntersection = require('./lib/rat-seg-intersect') +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} -//Bounds on a rational number when rounded to a float -function boundRat(r) { - var f = ratToFloat(r) - var cmp = ratCmp(rat(f), r) - if(cmp < 0) { - return [f, nextafter(f, Infinity)] - } else if(cmp > 0) { - return [nextafter(f, -Infinity), f] - } else { - return [f, f] - } +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } -//Convert a list of edges in a pslg to bounding boxes -function boundEdges(points, edges) { - var bounds = new Array(edges.length) - for(var i=0; i= floatPoints.length) { - return ratPoints[idx-floatPoints.length] - } - var p = floatPoints[idx] - return [ rat(p[0]), rat(p[1]) ] +//Returns a deep copy of cells +function cloneCells(cells) { + var ncells = new Array(cells.length) + for(var i=0, il=cells.length; i=0; --i) { - var junction = junctions[i] - var e = junction[0] +//Ranks a pair of cells up to permutation +function compareCells(a, b) { + var n = a.length + , t = a.length - b.length + , min = Math.min + if(t) { + return t + } + switch(n) { + case 0: + return 0; + case 1: + return a[0] - b[0]; + case 2: + var d = a[0]+a[1]-b[0]-b[1] + if(d) { + return d + } + return min(a[0],a[1]) - min(b[0],b[1]) + case 3: + var l1 = a[0]+a[1] + , m1 = b[0]+b[1] + d = l1+a[2] - (m1+b[2]) + if(d) { + return d + } + var l0 = min(a[0], a[1]) + , m0 = min(b[0], b[1]) + , d = min(l0, a[2]) - min(m0, b[2]) + if(d) { + return d + } + return min(l0+a[2], l1) - min(m0+b[2], m1) + + //TODO: Maybe optimize n=4 as well? + + default: + var as = a.slice(0) + as.sort() + var bs = b.slice(0) + bs.sort() + for(var i=0; i 0 && junctions[i-1][0] === e) { - var junction = junctions[--i] - var next = junction[1] - if(useColor) { - edges.push([last, next, color]) - } else { - edges.push([last, next]) +//Removes all duplicate cells in the complex +function unique(cells) { + if(cells.length === 0) { + return [] + } + var ptr = 1 + , len = cells.length + for(var i=1; i> 1 + , s = compareCells(cells[mid], c) + if(s <= 0) { + if(s === 0) { + r = mid + } + lo = mid + 1 + } else if(s > 0) { + hi = mid - 1 } } - - //Return constructed rational points - return ratPoints + return r } +exports.findCell = findCell; -//Merge overlapping points -function dedupPoints(floatPoints, ratPoints, floatBounds) { - var numPoints = floatPoints.length + ratPoints.length - var uf = new UnionFind(numPoints) - - //Compute rational bounds - var bounds = floatBounds - for(var i=0; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { + break + } + } } } - floatPoints.length = ptr + return index +} +exports.incidence = incidence - //If no duplicates, return null to signal termination - if(noDupes) { - return null +//Computes the dual of the mesh. This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices +function dual(cells, vertex_count) { + if(!vertex_count) { + return incidence(unique(skeleton(cells, 0)), cells, 0) } - - //Do a second pass to fix up missing labels - for(var i=0; i b[2]) { - return 1 +//Enumerates all cells in the complex +function explode(cells) { + var result = [] + for(var i=0, il=cells.length; i>> k) & 1) { + b.push(c[k]) + } + } + result.push(b) + } } - return 0 + return normalize(result) } +exports.explode = explode -//Remove duplicate edge labels -function dedupEdges(edges, labels, useColor) { - if(edges.length === 0) { - return +//Enumerates all of the n-cells of a cell complex +function skeleton(cells, n) { + if(n < 0) { + return [] } - if(labels) { - for(var i=0; i 0 || tjunctions.length > 0) - } - - // More iterations necessary - return true -} - -//Main loop, runs PSLG clean up until completion -function cleanPSLG(points, edges, colors) { - var modified = false - - //If using colors, augment edges with color data - var prevEdges - if(colors) { - prevEdges = edges - var augEdges = new Array(edges.length) - for(var i=0; i 0) { - a = a.shln(shift) - } else if(shift < 0) { - b = b.shln(-shift) } - return rationalize(a, b) + return components } -},{"./div":68,"./is-rat":70,"./lib/is-bn":74,"./lib/num-to-bn":75,"./lib/rationalize":76,"./lib/str-to-bn":77}],70:[function(require,module,exports){ -'use strict' - -var isBN = require('./lib/is-bn') - -module.exports = isRat - -function isRat(x) { - return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1]) +//Computes connected components for a cell complex +function connectedComponents(cells, vertex_count) { + if(vertex_count) { + return connectedComponents_dense(cells, vertex_count) + } + return connectedComponents_sparse(cells) } +exports.connectedComponents = connectedComponents -},{"./lib/is-bn":74}],71:[function(require,module,exports){ +},{"bit-twiddle":77,"union-find":78}],80:[function(require,module,exports){ 'use strict' -var bn = require('bn.js') - -module.exports = sign - -function sign(x) { - return x.cmp(new bn(0)) -} +module.exports = monotoneConvexHull2D -},{"bn.js":79}],72:[function(require,module,exports){ -'use strict' +var orient = require('robust-orientation')[3] -module.exports = bn2num +function monotoneConvexHull2D(points) { + var n = points.length -//TODO: Make this better -function bn2num(b) { - var l = b.length - var words = b.words - var out = 0 - if (l === 1) { - out = words[0] - } else if (l === 2) { - out = words[0] + (words[1] * 0x4000000) - } else { - var out = 0 - for (var i = 0; i < l; i++) { - var w = words[i] - out += w * Math.pow(0x4000000, i) + if(n < 3) { + var result = new Array(n) + for(var i=0; i 20) { - return 52 + return result } - return h + 32 -} - -},{"bit-twiddle":50,"double-bits":90}],74:[function(require,module,exports){ -'use strict' - -var BN = require('bn.js') - -module.exports = isBN - -//Test if x is a bignumber -//FIXME: obviously this is the wrong way to do it -function isBN(x) { - return x && typeof x === 'object' && Boolean(x.words) -} - -},{"bn.js":79}],75:[function(require,module,exports){ -'use strict' - -var BN = require('bn.js') -var db = require('double-bits') -module.exports = num2bn - -function num2bn(x) { - var e = db.exponent(x) - if(e < 52) { - return new BN(x) - } else { - return (new BN(x * Math.pow(2, 52-e))).shln(e-52) + //Sort point indices along x-axis + var sorted = new Array(n) + for(var i=0; i 1 && orient( + points[lower[m-2]], + points[lower[m-1]], + p) <= 0) { + m -= 1 + lower.pop() + } + lower.push(idx) -function rationalize(numer, denom) { - var snumer = sign(numer) - var sdenom = sign(denom) - if(snumer === 0) { - return [num2bn(0), num2bn(1)] - } - if(sdenom === 0) { - return [num2bn(0), num2bn(0)] - } - if(sdenom < 0) { - numer = numer.neg() - denom = denom.neg() - } - var d = numer.gcd(denom) - if(d.cmpn(1)) { - return [ numer.div(d), denom.div(d) ] + //Insert into upper list + m = upper.length + while(m > 1 && orient( + points[upper[m-2]], + points[upper[m-1]], + p) >= 0) { + m -= 1 + upper.pop() + } + upper.push(idx) } - return [ numer, denom ] -} - -},{"./bn-sign":71,"./num-to-bn":75}],77:[function(require,module,exports){ -'use strict' - -var BN = require('bn.js') - -module.exports = str2BN - -function str2BN(x) { - return new BN(x) -} - -},{"bn.js":79}],78:[function(require,module,exports){ -'use strict' - -var rationalize = require('./lib/rationalize') - -module.exports = mul - -function mul(a, b) { - return rationalize(a[0].mul(b[0]), a[1].mul(b[1])) -} - -},{"./lib/rationalize":76}],79:[function(require,module,exports){ -(function (module, exports) { - -'use strict'; - -// Utils - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -// Could use `inherits` module, but don't want to move from single file -// architecture yet. -function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; -} - -// BN -function BN(number, base, endian) { - // May be `new BN(bn)` ? - if (number !== null && - typeof number === 'object' && - Array.isArray(number.words)) { - return number; + //Merge lists together + var result = new Array(upper.length + lower.length - 2) + var ptr = 0 + for(var i=0, nl=lower.length; i0; --j) { + result[ptr++] = upper[j] } - if (number !== null) - this._init(number || 0, base || 10, endian || 'be'); + //Return result + return result } -if (typeof module === 'object') - module.exports = BN; -else - exports.BN = BN; - -BN.BN = BN; -BN.wordSize = 26; - -BN.prototype._init = function init(number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } else if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - if (base === 'hex') - base = 16; - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') - start++; - - if (base === 16) - this._parseHex(number, start); - else - this._parseBase(number, base, start); - - if (number[0] === '-') - this.sign = true; - - this.strip(); - - if (endian !== 'le') - return; - - this._initArray(this.toArray(), base, endian); -}; - -BN.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.sign = true; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') - return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); +},{"robust-orientation":1040}],81:[function(require,module,exports){ +module.exports = { + AFG: "afghan", + ALA: "\\b\\wland", + ALB: "albania", + DZA: "algeria", + ASM: "^(?=.*americ).*samoa", + AND: "andorra", + AGO: "angola", + AIA: "anguill?a", + ATA: "antarctica", + ATG: "antigua", + ARG: "argentin", + ARM: "armenia", + ABW: "^(?!.*bonaire).*\\baruba", + AUS: "australia", + AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp", + AZE: "azerbaijan", + BHS: "bahamas", + BHR: "bahrain", + BGD: "bangladesh|^(?=.*east).*paki?stan", + BRB: "barbados", + BLR: "belarus|byelo", + BEL: "^(?!.*luxem).*belgium", + BLZ: "belize|^(?=.*british).*honduras", + BEN: "benin|dahome", + BMU: "bermuda", + BTN: "bhutan", + BOL: "bolivia", + BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands", + BIH: "herzegovina|bosnia", + BWA: "botswana|bechuana", + BVT: "bouvet", + BRA: "brazil", + IOT: "british.?indian.?ocean", + BRN: "brunei", + BGR: "bulgaria", + BFA: "burkina|\\bfaso|upper.?volta", + BDI: "burundi", + KHM: "cambodia|kampuchea|khmer", + CMR: "cameroon", + CAN: "canada", + CPV: "verde", + CYM: "cayman", + CAF: "\\bcentral.african.republic", + TCD: "\\bchad", + CHL: "\\bchile", + CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china", + CXR: "christmas", + CCK: "\\bcocos|keeling", + COL: "colombia", + COM: "comoro", + COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc", + COG: "^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo", + COK: "\\bcook", + CRI: "costa.?rica", + CIV: "ivoire|ivory", + HRV: "croatia", + CUB: "\\bcuba", + CUW: "^(?!.*bonaire).*\\bcura(c|ç)ao", + CYP: "cyprus", + CZE: "^(?=.*rep).*czech|czechia|bohemia", + CSK: "czechoslovakia", + DNK: "denmark", + DJI: "djibouti", + DMA: "dominica(?!n)", + DOM: "dominican.rep", + ECU: "ecuador", + EGY: "egypt", + SLV: "el.?salvador", + GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea", + ERI: "eritrea", + EST: "estonia", + ETH: "ethiopia|abyssinia", + FLK: "falkland|malvinas", + FRO: "faroe|faeroe", + FJI: "fiji", + FIN: "finland", + FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul", + GUF: "^(?=.*french).*guiana", + PYF: "french.?polynesia|tahiti", + ATF: "french.?southern", + GAB: "gabon", + GMB: "gambia", + GEO: "^(?!.*south).*georgia", + DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany", + DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german", + GHA: "ghana|gold.?coast", + GIB: "gibraltar", + GRC: "greece|hellenic|hellas", + GRL: "greenland", + GRD: "grenada", + GLP: "guadeloupe", + GUM: "\\bguam", + GTM: "guatemala", + GGY: "guernsey", + GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea", + GNB: "bissau|^(?=.*portu).*guinea", + GUY: "guyana|british.?guiana", + HTI: "haiti", + HMD: "heard.*mcdonald", + VAT: "holy.?see|vatican|papal.?st", + HND: "^(?!.*brit).*honduras", + HKG: "hong.?kong", + HUN: "^(?!.*austr).*hungary", + ISL: "iceland", + IND: "india(?!.*ocea)", + IDN: "indonesia", + IRN: "\\biran|persia", + IRQ: "\\biraq|mesopotamia", + IRL: "ireland", + IMN: "^(?=.*isle).*\\bman", + ISR: "israel", + ITA: "italy", + JAM: "jamaica", + JPN: "japan", + JEY: "jersey", + JOR: "jordan", + KAZ: "kazak", + KEN: "kenya|british.?east.?africa|east.?africa.?prot", + KIR: "kiribati", + PRK: "^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk", + KOR: "^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea", + KWT: "kuwait", + KGZ: "kyrgyz|kirghiz", + LAO: "\\blaos?\\b", + LVA: "latvia", + LBN: "lebanon", + LSO: "lesotho|basuto", + LBR: "liberia", + LBY: "libya", + LIE: "liechtenstein", + LTU: "lithuania", + LUX: "^(?!.*belg).*luxem", + MAC: "maca(o|u)", + MKD: "macedonia|fyrom", + MDG: "madagascar|malagasy", + MWI: "malawi|nyasa", + MYS: "malaysia", + MDV: "maldive", + MLI: "\\bmali\\b", + MLT: "\\bmalta", + MHL: "marshall", + MTQ: "martinique", + MRT: "mauritania", + MUS: "mauritius", + MYT: "\\bmayotte", + MEX: "\\bmexic", + FSM: "micronesia", + MDA: "moldov|b(a|e)ssarabia", + MCO: "monaco", + MNG: "mongolia", + MNE: "^(?!.*serbia).*montenegro", + MSR: "montserrat", + MAR: "morocco|\\bmaroc", + MOZ: "mozambique", + MMR: "myanmar|burma", + NAM: "namibia", + NRU: "nauru", + NPL: "nepal", + NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands", + ANT: "^(?=.*\\bant).*(nether|dutch)", + NCL: "new.?caledonia", + NZL: "new.?zealand", + NIC: "nicaragua", + NER: "\\bniger(?!ia)", + NGA: "nigeria", + NIU: "niue", + NFK: "norfolk", + MNP: "mariana", + NOR: "norway", + OMN: "\\boman|trucial", + PAK: "^(?!.*east).*paki?stan", + PLW: "palau", + PSE: "palestin|\\bgaza|west.?bank", + PAN: "panama", + PNG: "papua|new.?guinea", + PRY: "paraguay", + PER: "peru", + PHL: "philippines", + PCN: "pitcairn", + POL: "poland", + PRT: "portugal", + PRI: "puerto.?rico", + QAT: "qatar", + REU: "r(e|é)union", + ROU: "r(o|u|ou)mania", + RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics", + RWA: "rwanda", + BLM: "barth(e|é)lemy", + SHN: "helena", + KNA: "kitts|\\bnevis", + LCA: "\\blucia", + MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)", + SPM: "miquelon", + VCT: "vincent", + WSM: "^(?!.*amer).*samoa", + SMR: "san.?marino", + STP: "\\bs(a|ã)o.?tom(e|é)", + SAU: "\\bsa\\w*.?arabia", + SEN: "senegal", + SRB: "^(?!.*monte).*serbia", + SYC: "seychell", + SLE: "sierra", + SGP: "singapore", + SXM: "^(?!.*martin)(?!.*saba).*maarten", + SVK: "^(?!.*cze).*slovak", + SVN: "slovenia", + SLB: "solomon", + SOM: "somali", + ZAF: "\\bs\\w*.?africa", + SGS: "south.?georgia|sandwich", + SSD: "\\bs\\w*.?sudan", + ESP: "spain", + LKA: "sri.?lanka|ceylon", + SDN: "^(?!.*\\bs(?!u)).*sudan", + SUR: "surinam|dutch.?guiana", + SJM: "svalbard", + SWZ: "swaziland", + SWE: "sweden", + CHE: "switz|swiss", + SYR: "syria", + TWN: "taiwan|taipei|formosa", + TJK: "tajik", + TZA: "tanzania", + THA: "thailand|\\bsiam", + TLS: "^(?=.*leste).*timor|^(?=.*east).*timor", + TGO: "togo", + TKL: "tokelau", + TON: "tonga", + TTO: "trinidad|tobago", + TUN: "tunisia", + TUR: "turkey", + TKM: "turkmen", + TCA: "turks", + TUV: "tuvalu", + UGA: "uganda", + UKR: "ukrain", + ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em", + GBR: "united.?kingdom|britain|^u\\.?k\\.?$", + USA: "united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)", + UMI: "minor.?outlying.?is", + URY: "uruguay", + UZB: "uzbek", + VUT: "vanuatu|new.?hebrides", + VEN: "venezuela", + VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam", + VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin", + VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin", + WLF: "futuna|wallis", + ESH: "western.sahara", + YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen", + YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen", + YUG: "yugoslavia", + ZMB: "zambia|northern.?rhodesia", + EAZ: "zanzibar", + ZWE: "zimbabwe|^(?!.*northern).*rhodesia" }; -BN.prototype._initArray = function _initArray(number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; +},{}],82:[function(require,module,exports){ +!function() { + var d3 = { + version: "3.5.17" + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = this.document; + function d3_documentElement(node) { + return node && (node.ownerDocument || node.document || node).documentElement; } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - var off = 0; - if (endian === 'be') { - for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { - var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (var i = 0, j = 0; i < number.length; i += 3) { - var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } + function d3_window(node) { + return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); } - return this.strip(); -}; - -function parseHex(str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) - r |= c - 49 + 0xa; - - // 'A' - 'F' - else if (c >= 17 && c <= 22) - r |= c - 17 + 0xa; - - // '0' - '9' - else - r |= c & 0xf; + if (d3_document) { + try { + d3_array(d3_document.documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array = new Array(i); + while (i--) array[i] = list[i]; + return array; + }; + } } - return r; -} - -BN.prototype._parseHex = function _parseHex(number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - // Scan 24-bit chunks and add them to the number - var off = 0; - for (var i = number.length - 6, j = 0; i >= start; i -= 6) { - var w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + if (!Date.now) Date.now = function() { + return +new Date(); + }; + if (d3_document) { + try { + d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name, value) { + d3_element_setAttribute.call(this, name, value + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value) { + d3_element_setAttributeNS.call(this, space, local, value + ""); + }; + d3_style_prototype.setProperty = function(name, value, priority) { + d3_style_setProperty.call(this, name, value + "", priority); + }; } } - if (i + 6 !== start) { - var w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + d3.ascending = d3_ascending; + function d3_ascending(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } - this.strip(); -}; - -function parseBase(str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) - r += c - 49 + 0xa; - - // 'A' - else if (c >= 17) - r += c - 17 + 0xa; - - // '0' - '9' - else - r += c; + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; + }; + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; + }; + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; + }; + function d3_number(x) { + return x === null ? NaN : +x; } - return r; -} - -BN.prototype._parseBase = function _parseBase(number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) - limbLen++; - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) - this.words[0] += word; - else - this._iaddn(word); + function d3_numeric(x) { + return !isNaN(x); } - - if (mod !== 0) { - var pow = 1; - var word = parseBase(number, i, number.length, base); - - for (var i = 0; i < mod; i++) - pow *= base; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) - this.words[0] += word; - else - this._iaddn(word); - } -}; - -BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - dest.words[i] = this.words[i]; - dest.length = this.length; - dest.sign = this.sign; - dest.red = this.red; -}; - -BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; -}; - -// Remove leading `0` from `this` -BN.prototype.strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) - this.length--; - return this._normSign(); -}; - -BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) - this.sign = false; - return this; -}; - -BN.prototype.inspect = function inspect() { - return (this.red ? ''; -}; - -/* - -var zeros = []; -var groupSizes = []; -var groupBases = []; - -var s = ''; -var i = -1; -while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; -} -groupSizes[0] = 0; -groupSizes[1] = 0; -groupBases[0] = 0; -groupBases[1] = 0; -var base = 2 - 1; -while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; -} - -*/ - -var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' -]; - -var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 -]; - -var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 -]; - -BN.prototype.toString = function toString(base, padding) { - base = base || 10; - if (base === 16 || base === 'hex') { - var out = ''; - var off = 0; - var padding = padding | 0 || 1; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) - out = zeros[6 - word.length] + word + out; - else - out = word + out; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = +array[i])) s += a; + } else { + while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; } - if (carry !== 0) - out = carry.toString(16) + out; - while (out.length % padding !== 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - var out = ''; - var c = this.clone(); - c.sign = false; - while (c.cmpn(0) !== 0) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (c.cmpn(0) !== 0) - out = zeros[groupSize - r.length] + r + out; - else - out = r + out; + return s; + }; + d3.mean = function(array, f) { + var s = 0, n = array.length, a, i = -1, j = n; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; } - if (this.cmpn(0) === 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else { - assert(false, 'Base should be between 2 and 36'); + if (j) return s / j; + }; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + var numbers = [], n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); + } + if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); + }; + d3.variance = function(array, f) { + var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) { + if (d3_numeric(a = d3_number(array[i]))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } else { + while (++i < n) { + if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } + if (j > 1) return s / (j - 1); + }; + d3.deviation = function() { + var v = d3.variance.apply(this, arguments); + return v ? Math.sqrt(v) : v; + }; + function d3_bisector(compare) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; + } + return lo; + } + }; } -}; - -BN.prototype.toJSON = function toJSON() { - return this.toString(16); -}; - -BN.prototype.toArray = function toArray(endian) { - this.strip(); - var res = new Array(this.byteLength()); - res[0] = 0; - - var q = this.clone(); - if (endian !== 'le') { - // Assume big-endian - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); - - res[res.length - i - 1] = b; + var d3_bisect = d3_bisector(d3_ascending); + d3.bisectLeft = d3_bisect.left; + d3.bisect = d3.bisectRight = d3_bisect.right; + d3.bisector = function(f) { + return d3_bisector(f.length === 1 ? function(d, x) { + return d3_ascending(f(d), x); + } : f); + }; + d3.shuffle = function(array, i0, i1) { + if ((m = arguments.length) < 3) { + i1 = array.length; + if (m < 2) i0 = 0; } - } else { - // Assume little-endian - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); - - res[i] = b; + var m = i1 - i0, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; + } + return array; + }; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.transpose = function(matrix) { + if (!(n = matrix.length)) return []; + for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { + for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { + row[j] = matrix[j][i]; + } } + return transpose; + }; + function d3_transposeLength(d) { + return d.length; } - - return res; -}; - -if (Math.clz32) { - BN.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); + d3.zip = function() { + return d3.transpose(arguments); }; -} else { - BN.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; + } } - if (t >= 0x40) { - r += 7; - t >>>= 7; + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } } - if (t >= 0x8) { - r += 4; - t >>>= 4; + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); } - if (t >= 0x02) { - r += 2; - t >>>= 2; + } + d3.map = function(object, f) { + var map = new d3_Map(); + if (object instanceof d3_Map) { + object.forEach(function(key, value) { + map.set(key, value); + }); + } else if (Array.isArray(object)) { + var i = -1, n = object.length, o; + if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); + } else { + for (var key in object) map.set(key, object[key]); } - return r + t; + return map; }; -} - -BN.prototype._zeroBits = function _zeroBits(w) { - // Short-cut - if (w === 0) - return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; + function d3_Map() { + this._ = Object.create(null); } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; + var d3_map_proto = "__proto__", d3_map_zero = "\x00"; + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this._[d3_map_escape(key)]; + }, + set: function(key, value) { + return this._[d3_map_escape(key)] = value; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + for (var key in this._) values.push(this._[key]); + return values; + }, + entries: function() { + var entries = []; + for (var key in this._) entries.push({ + key: d3_map_unescape(key), + value: this._[key] + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); + } + }); + function d3_map_escape(key) { + return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; + function d3_map_unescape(key) { + return (key += "")[0] === d3_map_zero ? key.slice(1) : key; } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; + function d3_map_has(key) { + return d3_map_escape(key) in this._; } - if ((t & 0x1) === 0) - r++; - return r; -}; - -// Return number of used bits in a BN -BN.prototype.bitLength = function bitLength() { - var hi = 0; - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; -}; - -// Number of trailing zero bits -BN.prototype.zeroBits = function zeroBits() { - if (this.cmpn(0) === 0) - return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) - break; + function d3_map_remove(key) { + return (key = d3_map_escape(key)) in this._ && delete this._[key]; } - return r; -}; - -BN.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); -}; - -// Return negative clone of `this` -BN.prototype.neg = function neg() { - if (this.cmpn(0) === 0) - return this.clone(); - - var r = this.clone(); - r.sign = !this.sign; - return r; -}; - - -// Or `num` with `this` in-place -BN.prototype.ior = function ior(num) { - this.sign = this.sign || num.sign; - - while (this.length < num.length) - this.words[this.length++] = 0; - - for (var i = 0; i < num.length; i++) - this.words[i] = this.words[i] | num.words[i]; - - return this.strip(); -}; - - -// Or `num` with `this` -BN.prototype.or = function or(num) { - if (this.length > num.length) - return this.clone().ior(num); - else - return num.clone().ior(this); -}; - - -// And `num` with `this` in-place -BN.prototype.iand = function iand(num) { - this.sign = this.sign && num.sign; - - // b = min-length(num, this) - var b; - if (this.length > num.length) - b = num; - else - b = this; - - for (var i = 0; i < b.length; i++) - this.words[i] = this.words[i] & num.words[i]; - - this.length = b.length; - - return this.strip(); -}; - - -// And `num` with `this` -BN.prototype.and = function and(num) { - if (this.length > num.length) - return this.clone().iand(num); - else - return num.clone().iand(this); -}; - - -// Xor `num` with `this` in-place -BN.prototype.ixor = function ixor(num) { - this.sign = this.sign || num.sign; - - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + function d3_map_keys() { + var keys = []; + for (var key in this._) keys.push(d3_map_unescape(key)); + return keys; } - - for (var i = 0; i < b.length; i++) - this.words[i] = a.words[i] ^ b.words[i]; - - if (this !== a) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - - this.length = a.length; - - return this.strip(); -}; - - -// Xor `num` with `this` -BN.prototype.xor = function xor(num) { - if (this.length > num.length) - return this.clone().ixor(num); - else - return num.clone().ixor(this); -}; - - -// Set `bit` of `this` -BN.prototype.setn = function setn(bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - while (this.length <= off) - this.words[this.length++] = 0; - - if (val) - this.words[off] = this.words[off] | (1 << wbit); - else - this.words[off] = this.words[off] & ~(1 << wbit); - - return this.strip(); -}; - - -// Add `num` to `this` in-place -BN.prototype.iadd = function iadd(num) { - // negative + positive - if (this.sign && !num.sign) { - this.sign = false; - var r = this.isub(num); - this.sign = !this.sign; - return this._normSign(); - - // positive + negative - } else if (!this.sign && num.sign) { - num.sign = false; - var r = this.isub(num); - num.sign = true; - return r._normSign(); + function d3_map_size() { + var size = 0; + for (var key in this._) ++size; + return size; } - - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + function d3_map_empty() { + for (var key in this._) return false; + return true; } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] + b.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); + } + } + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; + } + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); + }; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() { + this._ = Object.create(null); } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; + d3_class(d3_Set, { + has: d3_map_has, + add: function(key) { + this._[d3_map_escape(key += "")] = true; + return key; + }, + remove: d3_map_remove, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key)); + } + }); + d3.behavior = {}; + function d3_identity(d) { + return d; } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) - this.words[i] = a.words[i]; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; } - - return this; -}; - -// Add `num` to `this` -BN.prototype.add = function add(num) { - if (num.sign && !this.sign) { - num.sign = false; - var res = this.sub(num); - num.sign = true; - return res; - } else if (!num.sign && this.sign) { - this.sign = false; - var res = num.sub(this); - this.sign = true; - return res; + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.slice(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } } - - if (this.length > num.length) - return this.clone().iadd(num); - else - return num.clone().iadd(this); -}; - -// Subtract `num` from `this` in-place -BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.sign) { - num.sign = false; - var r = this.iadd(num); - num.sign = true; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.sign) { - this.sign = false; - this.iadd(num); - this.sign = true; - return this._normSign(); + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.slice(i + 1); + type = type.slice(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.sign = false; - this.length = 1; - this.words[0] = 0; - return this; + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); } - - // a > b - var a; - var b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] - b.words[i] + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - this.length = Math.max(this.length, i); - - if (a !== this) - this.sign = true; - - return this.strip(); -}; - -// Subtract `num` from `this` -BN.prototype.sub = function sub(num) { - return this.clone().isub(num); -}; - -/* -// NOTE: This could be potentionally used to generate loop-less multiplications -function _genCombMulTo(alen, blen) { - var len = alen + blen - 1; - var src = [ - 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + - 'mask = 0x3ffffff, shift = 0x4000000;', - 'out.length = ' + len + ';' - ]; - for (var k = 0; k < len; k++) { - var minJ = Math.max(0, k - alen + 1); - var maxJ = Math.min(k, blen - 1); - - for (var j = minJ; j <= maxJ; j++) { - var i = k - j; - var mul = 'a[' + i + '] * b[' + j + ']'; - - if (j === minJ) { - src.push('w = ' + mul + ' + c;'); - src.push('c = (w / shift) | 0;'); - } else { - src.push('w += ' + mul + ';'); - src.push('c += (w / shift) | 0;'); + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatches = function(n, s) { + var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; + d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + return d3_selectMatches(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = Sizzle; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3.select(d3_document.documentElement); + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } } - src.push('w &= mask;'); } - src.push('o[' + k + '] = w;'); + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; } - src.push('if (c !== 0) {', - ' o[' + k + '] = c;', - ' out.length++;', - '}', - 'return out;'); - - return src.join('\n'); -} -*/ - -BN.prototype._smallMulTo = function _smallMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; - - var carry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } } - out.words[k] = rword; - carry = ncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; } - - return out.strip(); -}; - -BN.prototype._bigMulTo = function _bigMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; + var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: d3_nsXhtml, + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); -}; - -BN.prototype.mulTo = function mulTo(num, out) { - var res; - if (this.length + num.length < 63) - res = this._smallMulTo(num, out); - else - res = this._bigMulTo(num, out); - return res; -}; - -// Multiply `this` by `num` -BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); -}; - -// In-place Multiplication -BN.prototype.imul = function imul(num) { - if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { - this.words[0] = 0; - this.length = 1; - return this; - } - - var tlen = this.length; - var nlen = num.length; - - this.sign = num.sign !== this.sign; - this.length = this.length + num.length; - this.words[this.length - 1] = 0; - - for (var k = this.length - 2; k >= 0; k--) { - // Sum all words with the same `i + j = k` and accumulate `carry`, - // note that carry could be >= 0x3ffffff - var carry = 0; - var rword = 0; - var maxJ = Math.min(k, nlen - 1); - for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i]; - var b = num.words[j]; - var r = a * b; - - var lo = r & 0x3ffffff; - carry += (r / 0x4000000) | 0; - lo += rword; - rword = lo & 0x3ffffff; - carry += lo >>> 26; + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; } - this.words[k] = rword; - this.words[k + 1] += carry; - carry = 0; - } - - // Propagate overflows - var carry = 0; - for (var i = 1; i < this.length; i++) { - var w = this.words[i] + carry; - this.words[i] = w & 0x3ffffff; - carry = w >>> 26; - } - - return this.strip(); -}; - -BN.prototype.imuln = function imuln(num) { - assert(typeof num === 'number'); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i] * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; -}; - -BN.prototype.muln = function muln(num) { - return this.clone().imuln(num); -}; - -// `this` * `this` -BN.prototype.sqr = function sqr() { - return this.mul(this); -}; - -// `this` * `this` in-place -BN.prototype.isqr = function isqr() { - return this.mul(this); -}; - -// Shift-left in-place -BN.prototype.ishln = function ishln(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - - if (r !== 0) { - var carry = 0; - for (var i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); } - if (carry) { - this.words[i] = carry; - this.length++; + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); } + function attrConstant() { + this.setAttribute(name, value); + } + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); + } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); + } + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + } + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } - - if (s !== 0) { - for (var i = this.length - 1; i >= 0; i--) - this.words[i + s] = this.words[i]; - for (var i = 0; i < s; i++) - this.words[i] = 0; - this.length += s; - } - - return this.strip(); -}; - -// Shift-right in-place -// NOTE: `hint` is a lowest bit before trailing zeroes -// NOTE: if `extended` is present - it will be filled with destroyed bits -BN.prototype.ishrn = function ishrn(bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) - h = (hint - (hint % 26)) / 26; - else - h = 0; - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) - maskedWords.words[i] = this.words[i]; - maskedWords.length = s; + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (var i = 0; i < this.length; i++) - this.words[i] = this.words[i + s]; - } else { - this.words[0] = 0; - this.length = 1; + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; + } + return true; + } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; + } + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } - - var carry = 0; - for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i]; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; + function d3_selection_classes(name) { + return (name + "").trim().split(/^|\s+/); } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) - maskedWords.words[maskedWords.length++] = carry; - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; + function d3_selection_classed(name, value) { + name = d3_selection_classes(name).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); + } + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; } - - this.strip(); - - return this; -}; - -// Shift-left -BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); -}; - -// Shift-right -BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); -}; - -// Test if n bit is set -BN.prototype.testn = function testn(bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - return false; + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); + } + }; } - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); -}; - -// Return only lowers bits of number (in-place) -BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(!this.sign, 'imaskn works only with positive numbers'); - - if (r !== 0) - s++; - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) { + var node = this.node(); + return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); + } + priority = ""; + } + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); + } + function styleConstant() { + this.style.setProperty(name, value, priority); + } + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + } + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; } - - return this.strip(); -}; - -// Return only lowers bits of number -BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); -}; - -// Add plain number `num` to `this` -BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.isubn(-num); - - // Possible sign change - if (this.sign) { - if (this.length === 1 && this.words[0] < num) { - this.words[0] = num - this.words[0]; - this.sign = false; + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); return this; } - - this.sign = false; - this.isubn(num); - this.sign = true; - return this; - } - - // Add without checks - return this._iaddn(num); -}; - -BN.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) - this.words[i + 1] = 1; - else - this.words[i + 1]++; - } - this.length = Math.max(this.length, i + 1); - - return this; -}; - -// Subtract plain number `num` from `this` -BN.prototype.isubn = function isubn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.iaddn(-num); - - if (this.sign) { - this.sign = false; - this.iaddn(num); - this.sign = true; - return this; + return this.each(d3_selection_property(name, value)); + }; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; + } + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; } - - this.words[0] -= num; - - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - - return this.strip(); -}; - -BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); -}; - -BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); -}; - -BN.prototype.iabs = function iabs() { - this.sign = false; - - return this; -}; - -BN.prototype.abs = function abs() { - return this.clone().iabs(); -}; - -BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { - // Bigger storage is needed - var len = num.length + shift; - var i; - if (this.words.length < len) { - var t = new Array(len); - for (var i = 0; i < this.length; i++) - t[i] = this.words[i]; - this.words = t; - } else { - i = this.length; - } - - // Zeroify rest - this.length = Math.max(this.length, len); - for (; i < this.length; i++) - this.words[i] = 0; - - var carry = 0; - for (var i = 0; i < num.length; i++) { - var w = this.words[i + shift] + carry; - var right = num.words[i] * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - var w = this.words[i + shift] + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) - return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (var i = 0; i < this.length; i++) { - var w = -this.words[i] + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.sign = true; - - return this.strip(); -}; - -BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1]; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.shln(shift); - a.ishln(shift); - bhi = b.words[b.length - 1]; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) - q.words[i] = 0; - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (!diff.sign) { - a = diff; - if (q) - q.words[m] = 1; - } - - for (var j = m - 1; j >= 0; j--) { - var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1]; - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.sign) { - qj--; - a.sign = false; - a._ishlnsubmul(b, 1, j); - if (a.cmpn(0) !== 0) - a.sign = !a.sign; + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + function create() { + var document = this.ownerDocument, namespace = this.namespaceURI; + return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); } - if (q) - q.words[j] = qj; - } - if (q) - q.strip(); - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) - a.ishrn(shift); - return { div: q ? q : null, mod: a }; -}; - -BN.prototype.divmod = function divmod(num, mode) { - assert(num.cmpn(0) !== 0); - - if (this.sign && !num.sign) { - var res = this.neg().divmod(num, mode); - var div; - var mod; - if (mode !== 'mod') - div = res.div.neg(); - if (mode !== 'div') - mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); - return { - div: div, - mod: mod - }; - } else if (!this.sign && num.sign) { - var res = this.divmod(num.neg(), mode); - var div; - if (mode !== 'mod') - div = res.div.neg(); - return { div: div, mod: res.mod }; - } else if (this.sign && num.sign) { - return this.neg().divmod(num.neg(), mode); - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) - return { div: new BN(0), mod: this }; - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') - return { div: this.divn(num.words[0]), mod: null }; - else if (mode === 'mod') - return { div: null, mod: new BN(this.modn(num.words[0])) }; - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); -}; - -// Find `this` / `num` -BN.prototype.div = function div(num) { - return this.divmod(num, 'div').div; -}; - -// Find `this` % `num` -BN.prototype.mod = function mod(num) { - return this.divmod(num, 'mod').mod; -}; - -// Find Round(`this` / `num`) -BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.cmpn(0) === 0) - return dm.div; - - var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; - - var half = num.shrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) - return dm.div; - - // Round up - return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); -}; - -BN.prototype.modn = function modn(num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) - acc = (p * acc + this.words[i]) % num; - - return acc; -}; - -// In-place division by number -BN.prototype.idivn = function idivn(num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = this.words[i] + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; + function createNS() { + return this.ownerDocument.createElementNS(name.space, name.local); + } + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; } - - return this.strip(); -}; - -BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); -}; - -BN.prototype.egcd = function egcd(p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); - - var x = this; - var y = p.clone(); - - if (x.sign) - x = x.mod(p); - else - x = x.clone(); - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.ishrn(1); - y.ishrn(1); - ++g; + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(d3_selectionRemove); + }; + function d3_selectionRemove() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); } - - var yp = y.clone(); - var xp = x.clone(); - - while (x.cmpn(0) !== 0) { - while (x.isEven()) { - x.ishrn(1); - if (A.isEven() && B.isEven()) { - A.ishrn(1); - B.ishrn(1); - } else { - A.iadd(yp).ishrn(1); - B.isub(xp).ishrn(1); + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } } + return value; } - - while (y.isEven()) { - y.ishrn(1); - if (C.isEven() && D.isEven()) { - C.ishrn(1); - D.ishrn(1); + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; + for (i = -1; ++i < n; ) { + if (node = group[i]) { + if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues[i] = keyValue; + } + } + for (i = -1; ++i < m; ) { + if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } else if (node !== true) { + updateNodes[i] = node; + node.__data__ = nodeData; + } + nodeByKeyValue.set(keyValue, true); + } + for (i = -1; ++i < n; ) { + if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { + exitNodes[i] = group[i]; + } + } } else { - C.iadd(yp).ishrn(1); - D.isub(xp).ishrn(1); + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } } else { - y.isub(x); - C.isub(A); - D.isub(B); + while (++i < n) { + bind(group = this[i], value); + } } + update.enter = function() { + return enter; + }; + update.exit = function() { + return exit; + }; + return update; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; } - - return { - a: C, - b: D, - gcd: y.ishln(g) + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); }; -}; - -// This is reduced incarnation of the binary EEA -// above, designated to invert members of the -// _prime_ fields F(p) at a maximal speed -BN.prototype._invmp = function _invmp(p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); - - var a = this; - var b = p.clone(); - - if (a.sign) - a = a.mod(p); - else - a = a.clone(); - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - while (a.isEven()) { - a.ishrn(1); - if (x1.isEven()) - x1.ishrn(1); - else - x1.iadd(delta).ishrn(1); - } - while (b.isEven()) { - b.ishrn(1); - if (x2.isEven()) - x2.ishrn(1); - else - x2.iadd(delta).ishrn(1); + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3_ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; } - if (a.cmpn(1) === 0) - return x1; - else - return x2; -}; - -BN.prototype.gcd = function gcd(num) { - if (this.cmpn(0) === 0) - return num.clone(); - if (num.cmpn(0) === 0) - return this.clone(); - - var a = this.clone(); - var b = num.clone(); - a.sign = false; - b.sign = false; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.ishrn(1); - b.ishrn(1); - } - - do { - while (a.isEven()) - a.ishrn(1); - while (b.isEven()) - b.ishrn(1); - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } } - - a.isub(b); - } while (true); - - return b.ishln(shift); -}; - -// Invert number in the field F(num) -BN.prototype.invm = function invm(num) { - return this.egcd(num).a.mod(num); -}; - -BN.prototype.isEven = function isEven() { - return (this.words[0] & 1) === 0; -}; - -BN.prototype.isOdd = function isOdd() { - return (this.words[0] & 1) === 1; -}; - -// And first word and num -BN.prototype.andln = function andln(num) { - return this.words[0] & num; -}; - -// Increment at the bit position in-line -BN.prototype.bincn = function bincn(bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - for (var i = this.length; i < s + 1; i++) - this.words[i] = 0; - this.words[s] |= q; - this.length = s + 1; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i]; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; + return groups; } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + d3_selection_each(this, function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; } - return this; -}; - -BN.prototype.cmpn = function cmpn(num) { - var sign = num < 0; - if (sign) - num = -num; - - if (this.sign && !sign) - return -1; - else if (!this.sign && sign) - return 1; - - num &= 0x3ffffff; - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - var w = this.words[0]; - res = w === num ? 0 : w < num ? -1 : 1; + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; } - if (this.sign) - res = -res; - return res; -}; - -// Compare two numbers and return: -// 1 - if `this` > `num` -// 0 - if `this` == `num` -// -1 - if `this` < `num` -BN.prototype.cmp = function cmp(num) { - if (this.sign && !num.sign) - return -1; - else if (!this.sign && num.sign) - return 1; - - var res = this.ucmp(num); - if (this.sign) - return -res; - else - return res; -}; - -// Unsigned comparison -BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) - return 1; - else if (this.length < num.length) - return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i]; - var b = num.words[i]; - - if (a === b) - continue; - if (a < b) - res = -1; - else if (a > b) - res = 1; - break; + d3.select = function(node) { + var group; + if (typeof node === "string") { + group = [ d3_select(node, d3_document) ]; + group.parentNode = d3_document.documentElement; + } else { + group = [ node ]; + group.parentNode = d3_documentElement(node); + } + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group; + if (typeof nodes === "string") { + group = d3_array(d3_selectAll(nodes, d3_document)); + group.parentNode = d3_document.documentElement; + } else { + group = d3_array(nodes); + group.parentNode = null; + } + return d3_selection([ group ]); + }; + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.slice(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; } - return res; -}; - -// -// A reduce context, could be using montgomery or something better, depending -// on the `m` itself. -// -BN.red = function red(num) { - return new Red(num); -}; - -BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(!this.sign, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); -}; - -BN.prototype.fromRed = function fromRed() { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); -}; - -BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; -}; - -BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); -}; - -BN.prototype.redAdd = function redAdd(num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); -}; - -BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); -}; - -BN.prototype.redSub = function redSub(num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); -}; - -BN.prototype.redISub = function redISub(num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); -}; - -BN.prototype.redShl = function redShl(num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); -}; - -BN.prototype.redMul = function redMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); -}; - -BN.prototype.redIMul = function redIMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); -}; - -BN.prototype.redSqr = function redSqr() { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); -}; - -BN.prototype.redISqr = function redISqr() { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); -}; - -// Square root over p -BN.prototype.redSqrt = function redSqrt() { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); -}; - -BN.prototype.redInvm = function redInvm() { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); -}; - -// Return negative clone of `this` % `red modulo` -BN.prototype.redNeg = function redNeg() { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); -}; - -BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); -}; - -// Prime numbers with efficient reduction -var primes = { - k256: null, - p224: null, - p192: null, - p25519: null -}; - -// Pseudo-Mersenne prime -function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).ishln(this.n).isub(this.p); - - this.tmp = this._tmp(); -} - -MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; -}; - -MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + if (d3_document) { + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); } - - return r; -}; - -MPrime.prototype.split = function split(input, out) { - input.ishrn(this.n, 0, out); -}; - -MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); -}; - -function K256() { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); -} -inherits(K256, MPrime); - -K256.prototype.split = function split(input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d3.event = o; + } + }; } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (var i = 10; i < input.length; i++) { - var next = input.words[i]; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; } - input.words[i - 10] = prev >>> 22; - input.length -= 9; -}; - -K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var hi; - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i]; - hi = w * 0x40; - lo += w * 0x3d1; - hi += (lo / 0x4000000) | 0; - lo &= 0x3ffffff; - - num.words[i] = lo; - - lo = hi; + var d3_event_dragSelect, d3_event_dragId = 0; + function d3_event_dragSuppress(node) { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect == null) { + d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); + } + if (d3_event_dragSelect) { + var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + var off = function() { + w.on(click, null); + }; + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) - num.length--; + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0) { + var window = d3_window(container); + if (window.scrollX || window.scrollY) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; + } + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; } - return num; -}; - -function P224() { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); -} -inherits(P224, MPrime); - -function P192() { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); -} -inherits(P192, MPrime); - -function P25519() { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); -} -inherits(P25519, MPrime); - -P25519.prototype.imulK = function imulK(num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = num.words[i] * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; + d3.touch = function(container, touches, identifier) { + if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; + if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { + if ((touch = touches[i]).identifier === identifier) { + return d3_mousePoint(container, touch); + } + } + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function dragstart(id, position, subject, move, end) { + return function() { + var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); + if (origin) { + dragOffset = origin.apply(that, arguments); + dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; + } else { + dragOffset = [ 0, 0 ]; + } + dispatch({ + type: "dragstart" + }); + function moved() { + var position1 = position(parent, dragId), dx, dy; + if (!position1) return; + dx = position1[0] - position0[0]; + dy = position1[1] - position0[1]; + dragged |= dx | dy; + position0 = position1; + dispatch({ + type: "drag", + x: position1[0] + dragOffset[0], + y: position1[1] + dragOffset[1], + dx: dx, + dy: dy + }); + } + function ended() { + if (!position(parent, dragId)) return; + dragSubject.on(move + dragName, null).on(end + dragName, null); + dragRestore(dragged); + dispatch({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d3.rebind(drag, event, "on"); + }; + function d3_behavior_dragTouchId() { + return d3.event.changedTouches[0].identifier; } - if (carry !== 0) - num.words[num.length++] = carry; - return num; -}; - -// Exported mostly for testing purposes, use plain name instead -BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) - return primes[name]; - - var prime; - if (name === 'k256') - prime = new K256(); - else if (name === 'p224') - prime = new P224(); - else if (name === 'p192') - prime = new P192(); - else if (name === 'p25519') - prime = new P25519(); - else - throw new Error('Unknown prime ' + name); - primes[name] = prime; - - return prime; -}; - -// -// Base reduction engine -// -function Red(m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - this.m = m; - this.prime = null; + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; } -} - -Red.prototype._verify1 = function _verify1(a) { - assert(!a.sign, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); -}; - -Red.prototype._verify2 = function _verify2(a, b) { - assert(!a.sign && !b.sign, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); -}; - -Red.prototype.imod = function imod(a) { - if (this.prime) - return this.prime.ireduce(a)._forceRed(this); - return a.mod(this.m)._forceRed(this); -}; - -Red.prototype.neg = function neg(a) { - var r = a.clone(); - r.sign = !r.sign; - return r.iadd(this.m)._forceRed(this); -}; - -Red.prototype.add = function add(a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res._forceRed(this); -}; - -Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res; -}; - -Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res._forceRed(this); -}; - -Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res; -}; - -Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.shln(num)); -}; - -Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); -}; - -Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); -}; - -Red.prototype.isqr = function isqr(a) { - return this.imul(a, a); -}; - -Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); -}; - -Red.prototype.sqrt = function sqrt(a) { - if (a.cmpn(0) === 0) - return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).ishrn(2); - var r = this.pow(a, pow); - return r; + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (q.cmpn(0) !== 0 && q.andln(1) === 0) { - s++; - q.ishrn(1); + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); } - assert(q.cmpn(0) !== 0); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).ishrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - while (this.pow(z, lpow).cmp(nOne) !== 0) - z.redIAdd(nOne); - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).ishrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) - tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).ishln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); } - - return r; -}; - -Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); - if (inv.sign) { - inv.sign = false; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; } -}; - -Red.prototype.pow = function pow(a, num) { - var w = []; - - if (num.cmpn(0) === 0) - return new BN(1); - - var q = num.clone(); - - while (q.cmpn(0) !== 0) { - w.push(q.andln(1)); - q.ishrn(1); + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; } - - // Skip leading zeroes - var res = a; - for (var i = 0; i < w.length; i++, res = this.sqr(res)) - if (w[i] !== 0) - break; - - if (++i < w.length) { - for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { - if (w[i] === 0) - continue; - res = this.mul(res, q); - } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); } - - return res; -}; - -Red.prototype.convertTo = function convertTo(num) { - var r = num.mod(this.m); - if (r === num) - return r.clone(); - else - return r; -}; - -Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; -}; - -// -// Montgomery method engine -// - -BN.mont = function mont(num) { - return new Mont(num); -}; - -function Mont(m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) - this.shift += 26 - (this.shift % 26); - this.r = new BN(1).ishln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv.sign = true; - this.minv = this.minv.mod(this.r); -} -inherits(Mont, Red); - -Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.shln(this.shift)); -}; - -Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; -}; - -Mont.prototype.imul = function imul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { - a.words[0] = 0; - a.length = 1; - return a; + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); - - return res._forceRed(this); -}; - -Mont.prototype.mul = function mul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) - return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); - - return res._forceRed(this); -}; - -Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); -}; - -})(typeof module === 'undefined' || module, this); - -},{}],80:[function(require,module,exports){ -'use strict' - -var bnsign = require('./lib/bn-sign') - -module.exports = sign - -function sign(x) { - return bnsign(x[0]) * bnsign(x[1]) -} - -},{"./lib/bn-sign":71}],81:[function(require,module,exports){ -'use strict' - -var rationalize = require('./lib/rationalize') - -module.exports = sub - -function sub(a, b) { - return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) -} - -},{"./lib/rationalize":76}],82:[function(require,module,exports){ -'use strict' - -var bn2num = require('./lib/bn-to-num') -var ctz = require('./lib/ctz') - -module.exports = roundRat - -//Round a rational to the closest float -function roundRat(f) { - var a = f[0] - var b = f[1] - if(a.cmpn(0) === 0) { - return 0 - } - var h = a.divmod(b) - var iv = h.div - var x = bn2num(iv) - var ir = h.mod - if(ir.cmpn(0) === 0) { - return x - } - if(x) { - var s = ctz(x) + 4 - var y = bn2num(ir.shln(s).divRound(b)) - - // flip the sign of y if x is negative - if (x<0) { - y = -y; + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < ε2) { + S = Math.log(w1 / w0) / ρ; + i = function(t) { + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; + }; + } else { + var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); + S = (r1 - r0) / ρ; + i = function(t) { + var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + }; } - - return x + y * Math.pow(2, -s) - } else { - var ybits = b.bitLength() - ir.bitLength() + 53 - var y = bn2num(ir.shln(ybits).divRound(b)) - if(ybits < 1023) { - return y * Math.pow(2, -ybits) + i.duration = S * 1e3; + return i; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + if (!d3_behavior_zoomWheel) { + d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); } - y *= Math.pow(2, -1023) - return y * Math.pow(2, 1023-ybits) - } -} - -},{"./lib/bn-to-num":72,"./lib/ctz":73}],83:[function(require,module,exports){ -'use strict' - -module.exports = boxIntersectWrapper - -var pool = require('typedarray-pool') -var sweep = require('./lib/sweep') -var boxIntersectIter = require('./lib/intersect') - -function boxEmpty(d, box) { - for(var j=0; j>>1 - if(d <= 0) { - return - } - - var retval - - //Convert red boxes - var redList = pool.mallocDouble(2*d*n) - var redIds = pool.mallocInt32(n) - n = convertBoxes(red, d, redList, redIds) - - if(n > 0) { - if(d === 1 && full) { - //Special case: 1d complete - sweep.init(n) - retval = sweep.sweepComplete( - d, visit, - 0, n, redList, redIds, - 0, n, redList, redIds) - } else { - - //Convert blue boxes - var blueList = pool.mallocDouble(2*d*m) - var blueIds = pool.mallocInt32(m) - m = convertBoxes(blue, d, blueList, blueIds) - - if(m > 0) { - sweep.init(n+m) - - if(d === 1) { - //Special case: 1d bipartite - retval = sweep.sweepBipartite( - d, visit, - 0, n, redList, redIds, - 0, m, blueList, blueIds) - } else { - //General case: d>1 - retval = boxIntersectIter( - d, visit, full, - n, redList, redIds, - m, blueList, blueIds) + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function zoomTo(that, p, l, k) { + that.__chart__ = { + x: view.x, + y: view.y, + k: view.k + }; + scaleTo(Math.pow(2, k)); + translateTo(center0 = p, l); + that = d3.select(that); + if (duration > 0) that = that.transition().duration(duration); + that.call(zoom.event); + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(dispatch) { + if (!zooming++) dispatch({ + type: "zoomstart" + }); + } + function zoomed(dispatch) { + rescale(); + dispatch({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(dispatch) { + if (!--zooming) dispatch({ + type: "zoomend" + }), center0 = null; + } + function mousedowned() { + var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); + d3_selection_interrupt.call(that); + zoomstarted(dispatch); + function moved() { + dragged = 1; + translateTo(d3.mouse(that), location0); + zoomed(dispatch); + } + function ended() { + subject.on(mousemove, null).on(mouseup, null); + dragRestore(dragged); + zoomended(dispatch); + } + } + function touchstarted() { + var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); + started(); + zoomstarted(dispatch); + subject.on(mousedown, null).on(touchstart, started); + function relocate() { + var touches = d3.touches(that); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var target = d3.event.target; + d3.select(target).on(touchmove, moved).on(touchend, ended); + targets.push(target); + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; } - - pool.free(blueList) - pool.free(blueIds) + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0]; + zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); + d3_eventPreventDefault(); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d3.touches(that), p0, l0, p1, l1; + d3_selection_interrupt.call(that); + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(dispatch); + } + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + d3.selectAll(targets).on(zoomName, null); + subject.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(dispatch); } } - - pool.free(redList) - pool.free(redIds) + function mousewheeled() { + var dispatch = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), + translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(dispatch); + }, 50); + d3_eventPreventDefault(); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(center0, translate0); + zoomed(dispatch); + } + function dblclicked() { + var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; + zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + } + return d3.rebind(zoom, event, "on"); + }; + var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; + d3.color = d3_color; + function d3_color() {} + d3_color.prototype.toString = function() { + return this.rgb() + ""; + }; + d3.hsl = d3_hsl; + function d3_hsl(h, s, l) { + return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); } - - return retval -} - - -var RESULT - -function appendItem(i,j) { - RESULT.push([i,j]) -} - -function intersectFullArray(x) { - RESULT = [] - boxIntersect(x, x, appendItem, true) - return RESULT -} - -function intersectBipartiteArray(x, y) { - RESULT = [] - boxIntersect(x, y, appendItem, false) - return RESULT -} - -//User-friendly wrapper, handle full input and no-visitor cases -function boxIntersectWrapper(arg0, arg1, arg2) { - var result - switch(arguments.length) { - case 1: - return intersectFullArray(arg0) - case 2: - if(typeof arg1 === 'function') { - return boxIntersect(arg0, arg0, arg1, true) - } else { - return intersectBipartiteArray(arg0, arg1) - } - case 3: - return boxIntersect(arg0, arg1, arg2, false) - default: - throw new Error('box-intersect: Invalid arguments') + var d3_hslPrototype = d3_hsl.prototype = new d3_color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; + } + function vv(h) { + return Math.round(v(h) * 255); + } + return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } -} -},{"./lib/intersect":85,"./lib/sweep":89,"typedarray-pool":278}],84:[function(require,module,exports){ -'use strict' - -var DIMENSION = 'd' -var AXIS = 'ax' -var VISIT = 'vv' -var FLIP = 'fp' - -var ELEM_SIZE = 'es' - -var RED_START = 'rs' -var RED_END = 're' -var RED_BOXES = 'rb' -var RED_INDEX = 'ri' -var RED_PTR = 'rp' - -var BLUE_START = 'bs' -var BLUE_END = 'be' -var BLUE_BOXES = 'bb' -var BLUE_INDEX = 'bi' -var BLUE_PTR = 'bp' - -var RETVAL = 'rv' - -var INNER_LABEL = 'Q' - -var ARGS = [ - DIMENSION, - AXIS, - VISIT, - RED_START, - RED_END, - RED_BOXES, - RED_INDEX, - BLUE_START, - BLUE_END, - BLUE_BOXES, - BLUE_INDEX -] - -function generateBruteForce(redMajor, flip, full) { - var funcName = 'bruteForce' + - (redMajor ? 'Red' : 'Blue') + - (flip ? 'Flip' : '') + - (full ? 'Full' : '') - - var code = ['function ', funcName, '(', ARGS.join(), '){', - 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] - - var redLoop = - 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + - 'i<' + RED_END +';' + - '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + - 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + - 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + - 'xi=' + RED_INDEX + '[i];' - - var blueLoop = - 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + - 'j<' + BLUE_END + ';' + - '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + - 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + - (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + - 'yi=' + BLUE_INDEX + '[j];' - - if(redMajor) { - code.push(redLoop, INNER_LABEL, ':', blueLoop) - } else { - code.push(blueLoop, INNER_LABEL, ':', redLoop) + d3.hcl = d3_hcl; + function d3_hcl(h, c, l) { + return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); } - - if(full) { - code.push('if(y1 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); } - - var code = ['function ' + funcName + '(' + fargs.join() + '){'] - - function invoke(redMajor, flip) { - var res = generateBruteForce(redMajor, flip, full) - prefix.push(res.code) - code.push('return ' + res.name + '(' + ARGS.join() + ');') + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; } - - code.push('if(' + RED_END + '-' + RED_START + '>' + - BLUE_END + '-' + BLUE_START + '){') - - if(full) { - invoke(true, false) - code.push('}else{') - invoke(false, false) - } else { - code.push('if(' + FLIP + '){') - invoke(true, true) - code.push('}else{') - invoke(true, false) - code.push('}}else{if(' + FLIP + '){') - invoke(false, true) - code.push('}else{') - invoke(false, false) - code.push('}') + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; } - code.push('}}return ' + funcName) - - var codeStr = prefix.join('') + code.join('') - var proc = new Function(codeStr) - return proc() -} - - -exports.partial = bruteForcePlanner(false) -exports.full = bruteForcePlanner(true) -},{}],85:[function(require,module,exports){ -'use strict' - -module.exports = boxIntersectIter - -var pool = require('typedarray-pool') -var bits = require('bit-twiddle') -var bruteForce = require('./brute') -var bruteForcePartial = bruteForce.partial -var bruteForceFull = bruteForce.full -var sweep = require('./sweep') -var findMedian = require('./median') -var genPartition = require('./partition') - -//Twiddle parameters -var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search -var SCAN_CUTOFF = (1<<22) //Cut off for two way scan -var SCAN_COMPLETE_CUTOFF = (1<<22) - -//Partition functions -var partitionInteriorContainsInterval = genPartition( - '!(lo>=p0)&&!(p1>=hi)', - ['p0', 'p1']) - -var partitionStartEqual = genPartition( - 'lo===p0', - ['p0']) - -var partitionStartLessThan = genPartition( - 'lo> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return new d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_rgb(k * this.r, k * this.g, k * this.b); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format, rgb, hsl) { + var r = 0, g = 0, b = 0, m1, m2, color; + m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": + { + return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } -red_loop: - for(var i=redStart, redPtr=redStart*elemSize; i> 4; + r = r >> 4 | r; + g = color & 240; + g = g >> 4 | g; + b = color & 15; + b = b << 4 | b; + } else if (format.length === 7) { + r = (color & 16711680) >> 16; + g = (color & 65280) >> 8; + b = color & 255; } } - var retval - if(flip) { - retval = visit(blueId, redId) + return rgb(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; } else { - retval = visit(redId, blueId) - } - if(retval !== void 0) { - return retval + h = NaN; + s = l > 0 && l < 1 ? 0 : h; } + return new d3_hsl(h, s, l); } -} - -//Special case: Intersect one point with list of intervals -function onePointFull( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueOffset, blue, blueId) { - - var elemSize = 2 * d - var bluePtr = blueOffset * elemSize - var blueX = blue[bluePtr + axis] - -red_loop: - for(var i=redStart, redPtr=redStart*elemSize; i 0) { - top -= 1 - - var iptr = top * IFRAME_SIZE - var axis = BOX_ISTACK[iptr] - var redStart = BOX_ISTACK[iptr+1] - var redEnd = BOX_ISTACK[iptr+2] - var blueStart = BOX_ISTACK[iptr+3] - var blueEnd = BOX_ISTACK[iptr+4] - var state = BOX_ISTACK[iptr+5] - - var dptr = top * DFRAME_SIZE - var lo = BOX_DSTACK[dptr] - var hi = BOX_DSTACK[dptr+1] - - //Unpack state info - var flip = (state & 1) - var full = !!(state & 16) - - //Unpack indices - var red = xBoxes - var redIndex = xIndex - var blue = yBoxes - var blueIndex = yIndex - if(flip) { - red = yBoxes - redIndex = yIndex - blue = xBoxes - blueIndex = xIndex - } - - if(state & 2) { - redEnd = partitionStartLessThan( - d, axis, - redStart, redEnd, red, redIndex, - hi) - if(redStart >= redEnd) { - continue - } - } - if(state & 4) { - redStart = partitionEndLessThanEqual( - d, axis, - redStart, redEnd, red, redIndex, - lo) - if(redStart >= redEnd) { - continue - } - } - - var redCount = redEnd - redStart - var blueCount = blueEnd - blueStart - - if(full) { - if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { - retval = sweep.scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } - } else { - if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { - //If input small, then use brute force - retval = bruteForcePartial( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } else if(d * redCount * blueCount < SCAN_CUTOFF) { - //If input medium sized, then use sweep and prune - retval = sweep.scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d3.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value) { + d3_rgb_names.set(key, d3_rgbNumber(value)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d3.functor = d3_functor; + d3.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, + mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; } - continue + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); } } - - //First, find all red intervals whose interior contains (lo,hi) - var red0 = partitionInteriorContainsInterval( - d, axis, - redStart, redEnd, red, redIndex, - lo, hi) - - //Lower dimensional case - if(redStart < red0) { - - if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { - //Special case for small inputs: use brute force - retval = bruteForceFull( - d, axis+1, visit, - redStart, red0, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; + } + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + function d3_xhrHasResponse(request) { + var type = request.responseType; + return type && type !== "text" ? request.response : request.responseText; + } + d3.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); + xhr.row = function(_) { + return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; + }; + return xhr; + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = new Function("d", "return {" + row.map(function(name, i) { + return JSON.stringify(name) + ": d[" + i + "]"; + }).join(",") + "}"); + o = f ? function(row, i) { + return f(a(row), i); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.slice(j + 1, i).replace(/""/g, '"'); } - } else if(axis === d-2) { - if(flip) { - retval = sweep.sweepBipartite( - d, visit, - blueStart, blueEnd, blue, blueIndex, - redStart, red0, red, redIndex) - } else { - retval = sweep.sweepBipartite( - d, visit, - redStart, red0, red, redIndex, - blueStart, blueEnd, blue, blueIndex) + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.slice(j, I - k); } - if(retval !== void 0) { - return retval + return text.slice(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); } - } else { - iterPush(top++, - axis+1, - redStart, red0, - blueStart, blueEnd, - flip, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blueStart, blueEnd, - redStart, red0, - flip^1, - -Infinity, Infinity) + if (f && (a = f(a, n++)) == null) continue; + rows.push(a); } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); } - - //Divide and conquer phase - if(red0 < redEnd) { - - //Cut blue into 3 parts: - // - // Points < mid point - // Points = mid point - // Points > mid point - // - var blue0 = findMedian( - d, axis, - blueStart, blueEnd, blue, blueIndex) - var mid = blue[elemSize * blue0 + axis] - var blue1 = partitionStartEqual( - d, axis, - blue0, blueEnd, blue, blueIndex, - mid) - - //Right case - if(blue1 < blueEnd) { - iterPush(top++, - axis, - red0, redEnd, - blue1, blueEnd, - (flip|4) + (full ? 16 : 0), - mid, hi) + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function() { + d3_timer.apply(this, arguments); + }; + function d3_timer(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + return timer; + } + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); } - - //Left case - if(blueStart < blue0) { - iterPush(top++, - axis, - red0, redEnd, - blueStart, blue0, - (flip|2) + (full ? 16 : 0), - lo, mid) - } - - //Center case (the hard part) - if(blue0 + 1 === blue1) { - //Optimization: Range with exactly 1 point, use a brute force scan - if(full) { - retval = onePointFull( - d, axis, visit, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) - } else { - retval = onePointPartial( - d, axis, visit, flip, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) - } - if(retval !== void 0) { - return retval - } - } else if(blue0 < blue1) { - var red1 - if(full) { - //If full intersection, need to handle special case - red1 = partitionContainsPoint( - d, axis, - red0, redEnd, red, redIndex, - mid) - if(red0 < red1) { - var redX = partitionStartEqual( - d, axis, - red0, red1, red, redIndex, - mid) - if(axis === d-2) { - //Degenerate sweep intersection: - // [red0, redX] with [blue0, blue1] - if(red0 < redX) { - retval = sweep.sweepComplete( - d, visit, - red0, redX, red, redIndex, - blue0, blue1, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } - - //Normal sweep intersection: - // [redX, red1] with [blue0, blue1] - if(redX < red1) { - retval = sweep.sweepBipartite( - d, visit, - redX, red1, red, redIndex, - blue0, blue1, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } - } else { - if(red0 < redX) { - iterPush(top++, - axis+1, - red0, redX, - blue0, blue1, - 16, - -Infinity, Infinity) - } - if(redX < red1) { - iterPush(top++, - axis+1, - redX, red1, - blue0, blue1, - 0, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blue0, blue1, - redX, red1, - 1, - -Infinity, Infinity) - } - } - } - } else { - if(flip) { - red1 = partitionContainsPointProper( - d, axis, - red0, redEnd, red, redIndex, - mid) - } else { - red1 = partitionContainsPoint( - d, axis, - red0, redEnd, red, redIndex, - mid) - } - if(red0 < red1) { - if(axis === d-2) { - if(flip) { - retval = sweep.sweepBipartite( - d, visit, - blue0, blue1, blue, blueIndex, - red0, red1, red, redIndex) - } else { - retval = sweep.sweepBipartite( - d, visit, - red0, red1, red, redIndex, - blue0, blue1, blue, blueIndex) - } - } else { - iterPush(top++, - axis+1, - red0, red1, - blue0, blue1, - flip, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blue0, blue1, - red0, red1, - flip^1, - -Infinity, Infinity) - } - } - } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(), timer = d3_timer_queueHead; + while (timer) { + if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; + timer = timer.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.c) { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } else { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } } + d3_timer_queueTail = t0; + return time; } -} -},{"./brute":84,"./median":86,"./partition":87,"./sweep":89,"bit-twiddle":50,"typedarray-pool":278}],86:[function(require,module,exports){ -'use strict' + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value = +value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); + } + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + function d3_locale_numberFormat(locale) { + var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { + var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; + while (i > 0 && g > 0) { + if (length + g + 1 > width) g = Math.max(1, width - length); + t.push(value.substring(i -= g, i + g)); + if ((length += g + 1) > width) break; + g = locale_grouping[j = (j + 1) % locale_grouping.length]; + } + return t.reverse().join(locale_thousands); + } : d3_identity; + return function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; + } + switch (type) { + case "n": + comma = true; + type = "g"; + break; -module.exports = findMedian + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; -var genPartition = require('./partition') + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; -var partitionStartLessThan = genPartition('lostart && boxes[ptr+axis] > x; - --j, ptr-=elemSize) { - //Swap - var aPtr = ptr - var bPtr = ptr+elemSize - for(var k=0; k" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; + }; + }; + } + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); } + }); + function d3_format_typeDefault(x) { + return x + ""; } -} - -//Find median using quick select algorithm -// takes O(n) time with high probability -function findMedian(d, axis, start, end, boxes, ids) { - if(end <= start+1) { - return start + var d3_time = d3.time = {}, d3_date = Date; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } - - var lo = start - var hi = end - var mid = ((end + start) >>> 1) - var elemSize = 2*d - var pivot = mid - var value = boxes[elemSize*mid+axis] - - while(lo < hi) { - if(hi - lo < PARTITION_THRESHOLD) { - insertionSort(d, axis, lo, hi, boxes, ids) - value = boxes[elemSize*mid+axis] - break + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); } - - //Select pivot using median-of-3 - var count = hi - lo - var pivot0 = (Math.random()*count+lo)|0 - var value0 = boxes[elemSize*pivot0 + axis] - var pivot1 = (Math.random()*count+lo)|0 - var value1 = boxes[elemSize*pivot1 + axis] - var pivot2 = (Math.random()*count+lo)|0 - var value2 = boxes[elemSize*pivot2 + axis] - if(value0 <= value1) { - if(value2 >= value1) { - pivot = pivot1 - value = value1 - } else if(value0 >= value2) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } - } else { - if(value1 >= value2) { - pivot = pivot1 - value = value1 - } else if(value2 >= value0) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } + }; + var d3_time_prototype = Date.prototype; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; } - - //Swap pivot to end of array - var aPtr = elemSize * (hi-1) - var bPtr = elemSize * pivot - for(var i=0; i 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); } - hi += 1 - } else if(pivot < mid) { - lo = pivot + 1 - while(lo < hi && - boxes[elemSize*lo+axis] === value) { - lo += 1 + return times; + } + function range_utc(t0, t1, dt) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; } - } else { - break } + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; } - - //Make sure pivot is at start - return partitionStartLessThan( - d, axis, - start, mid, boxes, ids, - boxes[elemSize*mid+axis]) -} -},{"./partition":87}],87:[function(require,module,exports){ -'use strict' - -module.exports = genPartition - -var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' - -function genPartition(predicate, args) { - var fargs ='abcdef'.split('').concat(args) - var reads = [] - if(predicate.indexOf('lo') >= 0) { - reads.push('lo=e[k+n]') - } - if(predicate.indexOf('hi') >= 0) { - reads.push('hi=e[k+o]') + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; } - fargs.push( - code.replace('_', reads.join()) - .replace('$', predicate)) - return Function.apply(void 0, fargs) -} -},{}],88:[function(require,module,exports){ -'use strict'; - -//This code is extracted from ndarray-sort -//It is inlined here as a temporary workaround - -module.exports = wrapper; - -var INSERT_SORT_CUTOFF = 32 - -function wrapper(data, n0) { - if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data); - } else { - quickSort(0, n0 - 1, data); - } -} - -function insertionSort(left, right, data) { - var ptr = 2*(left+1) - for(var i=left+1; i<=right; ++i) { - var a = data[ptr++] - var b = data[ptr++] - var j = i - var jptr = ptr-2 - while(j-- > left) { - var x = data[jptr-2] - var y = data[jptr-1] - if(x < a) { - break - } else if(x === a && y < b) { - break + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + function d3_locale_timeFormat(locale) { + var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.slice(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; + } + } + string.push(template.slice(j, i)); + return string.join(""); } - data[jptr] = x - data[jptr+1] = y - jptr -= 2 + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { + if (!("w" in d)) d.w = "W" in d ? 1 : 0; + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; } - data[jptr] = a - data[jptr+1] = b + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + d3_time_format.utc = function(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } + } + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; + } + }; + format.toString = local.toString; + return format; + }; + d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; + var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); + locale_periods.forEach(function(p, i) { + d3_time_periodLookup.set(p.toLowerCase(), i); + }); + var d3_time_formats = { + a: function(d) { + return locale_shortDays[d.getDay()]; + }, + A: function(d) { + return locale_days[d.getDay()]; + }, + b: function(d) { + return locale_shortMonths[d.getMonth()]; + }, + B: function(d) { + return locale_months[d.getMonth()]; + }, + c: d3_time_format(locale_dateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return locale_periods[+(d.getHours() >= 12)]; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(locale_date), + X: d3_time_format(locale_time), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; + } + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + } + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + } + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); + } + return d3_time_format; } -} - -function swap(i, j, data) { - i *= 2 - j *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = x - data[j+1] = y -} - -function move(i, j, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[i+1] = data[j+1] -} - -function rotate(i, j, k, data) { - i *= 2 - j *= 2 - k *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = data[k] - data[j+1] = data[k+1] - data[k] = x - data[k+1] = y -} - -function shufflePivot(i, j, px, py, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[j] = px - data[i+1] = data[j+1] - data[j+1] = py -} - -function compare(i, j, data) { - i *= 2 - j *= 2 - var x = data[i], - y = data[j] - if(x < y) { - return false - } else if(x === y) { - return data[i+1] > data[j+1] + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } - return true -} - -function comparePivot(i, y, b, data) { - i *= 2 - var x = data[i] - if(x < y) { - return true - } else if(x === y) { - return data[i+1] < b + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); } - return false -} - -function quickSort(left, right, data) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, - tmp = 0 - if(compare(el1, el2, data)) { - tmp = el1 - el1 = el2 - el2 = tmp + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; } - if(compare(el1, el3, data)) { - tmp = el1 - el1 = el3 - el3 = tmp + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; } - if(compare(el1, el4, data)) { - tmp = el1 - el1 = el4 - el4 = tmp + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; } - if(compare(el3, el4, data)) { - tmp = el3 - el3 = el4 - el4 = tmp + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; } - if(compare(el2, el5, data)) { - tmp = el2 - el2 = el5 - el5 = tmp + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, + i + 5) : -1; } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; } - - var pivot1X = data[2*el2] - var pivot1Y = data[2*el2+1] - var pivot2X = data[2*el4] - var pivot2Y = data[2*el4+1] - - var ptr0 = 2 * el1; - var ptr2 = 2 * el3; - var ptr4 = 2 * el5; - var ptr5 = 2 * index1; - var ptr6 = 2 * index3; - var ptr7 = 2 * index5; - for (var i1 = 0; i1 < 2; ++i1) { - var x = data[ptr0+i1]; - var y = data[ptr2+i1]; - var z = data[ptr4+i1]; - data[ptr5+i1] = x; - data[ptr6+i1] = y; - data[ptr7+i1] = z; + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; } - - move(index2, left, data) - move(index4, right, data) - for (var k = less; k <= great; ++k) { - if (comparePivot(k, pivot1X, pivot1Y, data)) { - if (k !== less) { - swap(k, less, data) - } - ++less; - } else { - if (!comparePivot(k, pivot2X, pivot2Y, data)) { - while (true) { - if (!comparePivot(great, pivot2X, pivot2Y, data)) { - if (--great < k) { - break; - } - continue; - } else { - if (comparePivot(great, pivot1X, pivot1Y, data)) { - rotate(k, less, great, data) - ++less; - --great; - } else { - swap(k, great, data) - --great; - } - break; - } - } - } - } - } - shufflePivot(left, less-1, pivot1X, pivot1Y, data) - shufflePivot(right, great+1, pivot2X, pivot2Y, data) - if (less - 2 - left <= INSERT_SORT_CUTOFF) { - insertionSort(left, less - 2, data); - } else { - quickSort(left, less - 2, data); + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; } - if (right - (great + 2) <= INSERT_SORT_CUTOFF) { - insertionSort(great + 2, right, data); - } else { - quickSort(great + 2, right, data); + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; } - if (great - less <= INSERT_SORT_CUTOFF) { - insertionSort(less, great, data); - } else { - quickSort(less, great, data); + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; } -} -},{}],89:[function(require,module,exports){ -'use strict' - -module.exports = { - init: sqInit, - sweepBipartite: sweepBipartite, - sweepComplete: sweepComplete, - scanBipartite: scanBipartite, - scanComplete: scanComplete -} - -var pool = require('typedarray-pool') -var bits = require('bit-twiddle') -var isort = require('./sort') - -//Flag for blue -var BLUE_FLAG = (1<<28) - -//1D sweep event queue stuff (use pool to save space) -var INIT_CAPACITY = 1024 -var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) - -//Reserves memory for the 1D sweep data structures -function sqInit(count) { - var rcount = bits.nextPow2(count) - if(RED_SWEEP_QUEUE.length < rcount) { - pool.free(RED_SWEEP_QUEUE) - RED_SWEEP_QUEUE = pool.mallocInt32(rcount) + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; } - if(RED_SWEEP_INDEX.length < rcount) { - pool.free(RED_SWEEP_INDEX) - RED_SWEEP_INDEX = pool.mallocInt32(rcount) + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; } - if(BLUE_SWEEP_QUEUE.length < rcount) { - pool.free(BLUE_SWEEP_QUEUE) - BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); } - if(BLUE_SWEEP_INDEX.length < rcount) { - pool.free(BLUE_SWEEP_INDEX) - BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.slice(i, i + 1)); + return n ? i + n[0].length : -1; } - if(COMMON_SWEEP_QUEUE.length < rcount) { - pool.free(COMMON_SWEEP_QUEUE) - COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) + function d3_time_formatMulti(formats) { + var n = formats.length, i = -1; + while (++i < n) formats[i][0] = this(formats[i][0]); + return function(date) { + var i = 0, f = formats[i]; + while (!f[1](date)) f = formats[++i]; + return f[0](date); + }; } - if(COMMON_SWEEP_INDEX.length < rcount) { - pool.free(COMMON_SWEEP_INDEX) - COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) + d3.locale = function(locale) { + return { + numberFormat: d3_locale_numberFormat(locale), + timeFormat: d3_locale_timeFormat(locale) + }; + }; + var d3_locale_enUS = d3.locale({ + decimal: ".", + thousands: ",", + grouping: [ 3 ], + currency: [ "$", "" ], + dateTime: "%a %b %e %X %Y", + date: "%m/%d/%Y", + time: "%H:%M:%S", + periods: [ "AM", "PM" ], + days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], + shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], + months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], + shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] + }); + d3.format = d3_locale_enUS.numberFormat; + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; + } + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); } - var eventLength = 8 * rcount - if(SWEEP_EVENTS.length < eventLength) { - pool.free(SWEEP_EVENTS) - SWEEP_EVENTS = pool.mallocDouble(eventLength) + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); + } + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); + } } -} - -//Remove an item from the active queue in O(1) -function sqPop(queue, index, count, item) { - var idx = index[item] - var top = queue[count-1] - queue[idx] = top - index[top] = idx -} - -//Insert an item into the active queue in O(1) -function sqPush(queue, index, count, item) { - queue[count] = item - index[item] = count -} - -//Recursion base case: use 1D sweep algorithm -function sweepBipartite( - d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - //store events as pairs [coordinate, idx] - // - // red create: -(idx+1) - // red destroy: idx - // blue create: -(idx+BLUE_FLAG) - // blue destroy: idx+BLUE_FLAG - // - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - for(var i=0; i= BLUE_FLAG) { - //blue destroy event - e = (e-BLUE_FLAG)|0 - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) - } else if(e >= 0) { - //red destroy event - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) - } else if(e <= -BLUE_FLAG) { - //blue create event - e = (-e-BLUE_FLAG)|0 - for(var j=0; j= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; } -} - -//Complete sweep -function sweepComplete(d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - var commonActive = 0 - for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { - color = 2 - i += 1 + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; + } + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; } - - if(e < 0) { - //Create event - var id = -(e>>1) - 1 - - //Intersect with common - for(var j=0; j 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; + } else { + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; } - } - - if(color !== 0) { - //Intersect with red - for(var j=0; j angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } - } - } - - if(color !== 1) { - //Intersect with blue - for(var j=0; j= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } } } + } else { + point(λ, φ); } - - if(color === 0) { - //Red - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id) - } else if(color === 1) { - //Blue - sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id) - } else if(color === 2) { - //Both - sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id) - } - } else { - //Destroy event - var id = (e>>1) - 1 - if(color === 0) { - //Red - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) - } else if(color === 1) { - //Blue - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) - } else if(color === 2) { - //Both - sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) + p0 = p, λ_ = λ; + } + function lineStart() { + bound.point = linePoint; + } + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; + } + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); + } + function ringStart() { + d3_geo_area.lineStart(); + } + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; + } + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + } + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } -} - -//Sweep and prune/scanline algorithm: -// Scan along axis, detect intersections -// Brute force all boxes along axis -function scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d - - var redShift = 1 - var blueShift = 1 - if(flip) { - blueShift = BLUE_FLAG - } else { - redShift = BLUE_FLAG + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; } - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - isRed = !flip - idx -= BLUE_FLAG - } else { - isRed = !!flip - idx -= 1 + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; + } + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; } - if(isRed) { - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) - } else { - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] - -red_loop: - for(var j=0; j= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); } + current = current.p; } - } - } else { - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift) + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); } } -} - -function scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG - } else { - idx -= 1 - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] - -red_loop: - for(var j=0; j=0; --j) { - if(RED_SWEEP_QUEUE[j] === idx) { - for(var k=j+1; k 0) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); } - break + return; } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); } - --redActive - } + return clip; + }; } -} -},{"./sort":88,"bit-twiddle":50,"typedarray-pool":278}],90:[function(require,module,exports){ -(function (Buffer){ -var hasTypedArrays = false -if(typeof Float64Array !== "undefined") { - var DOUBLE_VIEW = new Float64Array(1) - , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) - DOUBLE_VIEW[0] = 1.0 - hasTypedArrays = true - if(UINT_VIEW[1] === 0x3ff00000) { - //Use little endian - module.exports = function doubleBitsLE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[0], UINT_VIEW[1] ] - } - function toDoubleLE(lo, hi) { - UINT_VIEW[0] = lo - UINT_VIEW[1] = hi - return DOUBLE_VIEW[0] - } - module.exports.pack = toDoubleLE - function lowUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - module.exports.lo = lowUintLE - function highUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - module.exports.hi = highUintLE - } else if(UINT_VIEW[0] === 0x3ff00000) { - //Use big endian - module.exports = function doubleBitsBE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[1], UINT_VIEW[0] ] - } - function toDoubleBE(lo, hi) { - UINT_VIEW[1] = lo - UINT_VIEW[0] = hi - return DOUBLE_VIEW[0] - } - module.exports.pack = toDoubleBE - function lowUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - module.exports.lo = lowUintBE - function highUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - module.exports.hi = highUintBE - } else { - hasTypedArrays = false - } -} -if(!hasTypedArrays) { - var buffer = new Buffer(8) - module.exports = function doubleBits(n) { - buffer.writeDoubleLE(n, 0, true) - return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] - } - function toDouble(lo, hi) { - buffer.writeUInt32LE(lo, 0, true) - buffer.writeUInt32LE(hi, 4, true) - return buffer.readDoubleLE(0, true) - } - module.exports.pack = toDouble - function lowUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(0, true) + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; } - module.exports.lo = lowUint - function highUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(4, true) + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; } - module.exports.hi = highUint -} - -module.exports.sign = function(n) { - return module.exports.hi(n) >>> 31 -} - -module.exports.exponent = function(n) { - var b = module.exports.hi(n) - return ((b<<1) >>> 21) - 1023 -} - -module.exports.fraction = function(n) { - var lo = module.exports.lo(n) - var hi = module.exports.hi(n) - var b = hi & ((1<<20) - 1) - if(hi & 0x7ff00000) { - b += (1<<20) + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } - return [lo, b] -} - -module.exports.denormalized = function(n) { - var hi = module.exports.hi(n) - return !(hi & 0x7ff00000) -} -}).call(this,require("buffer").Buffer) -},{"buffer":51}],91:[function(require,module,exports){ -"use strict" - -var doubleBits = require("double-bits") - -var SMALLEST_DENORM = Math.pow(2, -1074) -var UINT_MAX = (-1)>>>0 - -module.exports = nextafter - -function nextafter(x, y) { - if(isNaN(x) || isNaN(y)) { - return NaN + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); + if (abs(dλ - π) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= π) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; + } + }; } - if(x === y) { - return x + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; } - if(x === 0) { - if(y < 0) { - return -SMALLEST_DENORM + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfπ; + listener.point(-π, φ); + listener.point(0, φ); + listener.point(π, φ); + listener.point(π, 0); + listener.point(π, -φ); + listener.point(0, -φ); + listener.point(-π, -φ); + listener.point(-π, 0); + listener.point(-π, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); } else { - return SMALLEST_DENORM + listener.point(to[0], to[1]); } } - var hi = doubleBits.hi(x) - var lo = doubleBits.lo(x) - if((y > x) === (x > 0)) { - if(lo === UINT_MAX) { - hi += 1 - lo = 0 - } else { - lo += 1 - } - } else { - if(lo === 0) { - lo = UINT_MAX - hi -= 1 - } else { - lo -= 1 + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); + polarAngle += antimeridian ? dλ + sdλ * τ : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; + } } + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1; } - return doubleBits.pack(lo, hi) -} -},{"double-bits":90}],92:[function(require,module,exports){ -'use strict' - -var bnadd = require('big-rat/add') - -module.exports = add - -function add(a, b) { - var n = a.length - var r = new Array(n) - for(var i=0; i 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; + } + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; + } + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } + } + function code(λ, φ) { + var r = smallRadius ? radius : π - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; } } - - return true -} - -function segmentsIntersect(a0, a1, b0, b1) { - var x0 = orient(a0, b0, b1) - var y0 = orient(a1, b0, b1) - if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { - return false - } - - var x1 = orient(b0, a0, a1) - var y1 = orient(b1, a0, a1) - if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { - return false - } - - //Check for degenerate collinear case - if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { - return checkCollinear(a0, a1, b0, b1) - } - - return true -} -},{"robust-orientation":259}],97:[function(require,module,exports){ -"use strict"; "use restrict"; - -module.exports = UnionFind; - -function UnionFind(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; i 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; } - return x; -} - -proto.link = function(x, y) { - var xr = this.find(x) - , yr = this.find(y); - if(xr === yr) { - return; - } - var ranks = this.ranks - , roots = this.roots - , xd = ranks[xr] - , yd = ranks[yr]; - if(xd < yd) { - roots[xr] = yr; - } else if(yd < xd) { - roots[yr] = xr; - } else { - roots[yr] = xr; - ++ranks[xr]; - } -} -},{}],98:[function(require,module,exports){ -(function (Buffer){ -var clone = (function() { -'use strict'; - -/** - * Clones (copies) an Object using deep copying. - * - * This function supports circular references by default, but if you are certain - * there are no circular references in your object, you can save some CPU time - * by calling clone(obj, false). - * - * Caution: if `circular` is false and `parent` contains circular references, - * your program may enter an infinite loop and crash. - * - * @param `parent` - the object to be cloned - * @param `circular` - set to true if the object to be cloned may contain - * circular references. (optional - true by default) - * @param `depth` - set to a number if the object is only to be cloned to - * a particular depth. (optional - defaults to Infinity) - * @param `prototype` - sets the prototype to be used when cloning an object. - * (optional - defaults to parent prototype). -*/ -function clone(parent, circular, depth, prototype) { - var filter; - if (typeof circular === 'object') { - depth = circular.depth; - prototype = circular.prototype; - filter = circular.filter; - circular = circular.circular - } - // maintain two arrays for circular references, where corresponding parents - // and children have the same index - var allParents = []; - var allChildren = []; - - var useBuffer = typeof Buffer != 'undefined'; - - if (typeof circular == 'undefined') - circular = true; - - if (typeof depth == 'undefined') - depth = Infinity; - - // recurse this function so we don't reset allParents and allChildren - function _clone(parent, depth) { - // cloning null always returns null - if (parent === null) - return null; - - if (depth == 0) - return parent; - - var child; - var proto; - if (typeof parent != 'object') { - return parent; - } - - if (clone.__isArray(parent)) { - child = []; - } else if (clone.__isRegExp(parent)) { - child = new RegExp(parent.source, __getRegExpFlags(parent)); - if (parent.lastIndex) child.lastIndex = parent.lastIndex; - } else if (clone.__isDate(parent)) { - child = new Date(parent.getTime()); - } else if (useBuffer && Buffer.isBuffer(parent)) { - child = new Buffer(parent.length); - parent.copy(child); - return child; - } else { - if (typeof prototype == 'undefined') { - proto = Object.getPrototypeOf(parent); - child = Object.create(proto); + var d3_geo_clipExtentMAX = 1e9; + d3.geo.clipExtent = function() { + var x0, y0, x1, y1, stream, clip, clipExtent = { + stream: function(output) { + if (stream) stream.valid = false; + stream = clip(output); + stream.valid = true; + return stream; + }, + extent: function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); + if (stream) stream.valid = false, stream = null; + return clipExtent; } - else { - child = Object.create(prototype); - proto = prototype; + }; + return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + }; + function d3_geo_clipExtent(x0, y0, x1, y1) { + return function(listener) { + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + listener = bufferListener; + segments = []; + polygon = []; + clean = true; + }, + polygonEnd: function() { + listener = listener_; + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { + listener.polygonStart(); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } + listener.polygonEnd(); + } + segments = polygon = ring = null; + } + }; + function insidePolygon(p) { + var wn = 0, n = polygon.length, y = p[1]; + for (var i = 0; i < n; ++i) { + for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { + b = v[j]; + if (a[1] <= y) { + if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; } - } - - if (circular) { - var index = allParents.indexOf(parent); - - if (index != -1) { - return allChildren[index]; + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); + } else { + listener.point(to[0], to[1]); + } } - allParents.push(parent); - allChildren.push(child); - } - - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; } - - if (attrs && attrs.set == null) { - continue; + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); } - child[i] = _clone(parent[i], depth - 1); - } - - return child; - } - - return _clone(parent, depth); -} - -/** - * Simple flat clone using prototype, accepts only objects, usefull for property - * override on FLAT configuration object (no nested props). - * - * USE WITH CAUTION! This may not behave as you wish if you do not know how this - * works. - */ -clone.clonePrototype = function clonePrototype(parent) { - if (parent === null) - return null; - - var c = function () {}; - c.prototype = parent; - return new c(); -}; - -// private utility functions - -function __objToStr(o) { - return Object.prototype.toString.call(o); -}; -clone.__objToStr = __objToStr; - -function __isDate(o) { - return typeof o === 'object' && __objToStr(o) === '[object Date]'; -}; -clone.__isDate = __isDate; - -function __isArray(o) { - return typeof o === 'object' && __objToStr(o) === '[object Array]'; -}; -clone.__isArray = __isArray; - -function __isRegExp(o) { - return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; -}; -clone.__isRegExp = __isRegExp; - -function __getRegExpFlags(re) { - var flags = ''; - if (re.global) flags += 'g'; - if (re.ignoreCase) flags += 'i'; - if (re.multiline) flags += 'm'; - return flags; -}; -clone.__getRegExpFlags = __getRegExpFlags; - -return clone; -})(); - -if (typeof module === 'object' && module.exports) { - module.exports = clone; -} - -}).call(this,require("buffer").Buffer) -},{"buffer":51}],99:[function(require,module,exports){ -module.exports={"jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}],"hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}],"hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}],"cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}],"spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}],"summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}],"autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}],"winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}],"bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}],"copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}],"greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}],"yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}],"greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}],"yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}],"bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}],"rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}],"picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}],"rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}],"portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}],"blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}],"earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}],"electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}]}; - -},{}],100:[function(require,module,exports){ -/* - * Ben Postlethwaite - * January 2013 - * License MIT - */ -'use strict'; - -var at = require('arraytools'); -var clone = require('clone'); -var colorScale = require('./colorScales'); - -module.exports = function (spec) { - - /* - * Default Options - */ - var indicies, rgba, fromrgba, torgba, - nsteps, cmap, colormap, format, - nshades, colors, alpha, index, i, - r = [], - g = [], - b = [], - a = []; - - if ( !at.isPlainObject(spec) ) spec = {}; - - nshades = spec.nshades || 72; - format = spec.format || 'hex'; - - colormap = spec.colormap; - if (!colormap) colormap = 'jet'; - - if (typeof colormap === 'string') { - colormap = colormap.toLowerCase(); - - if (!colorScale[colormap]) { - throw Error(colormap + ' not a supported colorscale'); + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); } - - cmap = clone(colorScale[colormap]); - - } else if (Array.isArray(colormap)) { - cmap = clone(colormap); - - } else { - throw Error('unsupported colormap option', colormap); - } - - if (cmap.length > nshades) { - throw new Error( - colormap+' map requires nshades to be at least size '+cmap.length - ); - } - - if (!Array.isArray(spec.alpha)) { - - if (typeof spec.alpha === 'number') { - alpha = [spec.alpha, spec.alpha]; - + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } } else { - alpha = [1, 1]; + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } } - - } else if (spec.alpha.length !== 2) { - alpha = [1, 1]; - - } else { - alpha = clone(spec.alpha); + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; } - - /* - * map index points from 0->1 to 0 -> n-1 - */ - indicies = cmap.map(function(c) { - return Math.round(c.index * nshades); - }); - - /* - * Add alpha channel to the map - */ - if (alpha[0] < 0) alpha[0] = 0; - if (alpha[1] < 0) alpha[0] = 0; - if (alpha[0] > 1) alpha[0] = 1; - if (alpha[1] > 1) alpha[0] = 1; - - for (i = 0; i < indicies.length; ++i) { - index = cmap[i].index; - rgba = cmap[i].rgb; - - // if user supplies their own map use it - if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue; - rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index; + function compare(a, b) { + return comparePoints(a.x, b.x); } - - /* - * map increasing linear values between indicies to - * linear steps in colorvalues - */ - for (i = 0; i < indicies.length-1; ++i) { - nsteps = indicies[i+1] - indicies[i]; - fromrgba = cmap[i].rgb; - torgba = cmap[i+1].rgb; - r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) ); - g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) ); - b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) ); - a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) ); + function comparePoints(a, b) { + var ca = corner(a, 1), cb = corner(b, 1); + return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; } - - r = r.map( Math.round ); - g = g.map( Math.round ); - b = b.map( Math.round ); - - colors = at.zip(r, g, b, a); - - if (format === 'hex') colors = colors.map( rgb2hex ); - if (format === 'rgbaString') colors = colors.map( rgbaStr ); - - return colors; -}; - - -function rgb2hex (rgba) { - var dig, hex = '#'; - for (var i = 0; i < 3; ++i) { - dig = rgba[i]; - dig = dig.toString(16); - hex += ('00' + dig).substr( dig.length ); + } + function d3_geo_conic(projectAt) { + var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); + p.parallels = function(_) { + if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; + return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); + }; + return p; + } + function d3_geo_conicEqualArea(φ0, φ1) { + var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; + function forward(λ, φ) { + var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; + return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; } - return hex; -} - -function rgbaStr (rgba) { - return 'rgba(' + rgba.join(',') + ')'; -} - -},{"./colorScales":99,"arraytools":49,"clone":98}],101:[function(require,module,exports){ -module.exports = compareCells - -var min = Math.min - -function compareInt(a, b) { - return a - b -} - -function compareCells(a, b) { - var n = a.length - , t = a.length - b.length - if(t) { - return t + forward.invert = function(x, y) { + var ρ0_y = ρ0 - y; + return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; + }; + return forward; } - switch(n) { - case 0: - return 0 - case 1: - return a[0] - b[0] - case 2: - return (a[0]+a[1]-b[0]-b[1]) || - min(a[0],a[1]) - min(b[0],b[1]) - case 3: - var l1 = a[0]+a[1] - , m1 = b[0]+b[1] - t = l1+a[2] - (m1+b[2]) - if(t) { - return t + (d3.geo.conicEqualArea = function() { + return d3_geo_conic(d3_geo_conicEqualArea); + }).raw = d3_geo_conicEqualArea; + d3.geo.albers = function() { + return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); + }; + d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); + var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); + var point, pointStream = { + point: function(x, y) { + point = [ x, y ]; } - var l0 = min(a[0], a[1]) - , m0 = min(b[0], b[1]) - return min(l0, a[2]) - min(m0, b[2]) || - min(l0+a[2], l1) - min(m0+b[2], m1) - case 4: - var aw=a[0], ax=a[1], ay=a[2], az=a[3] - , bw=b[0], bx=b[1], by=b[2], bz=b[3] - return (aw+ax+ay+az)-(bw+bx+by+bz) || - min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) || - min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) - - min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) || - min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) - - min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz) - default: - var as = a.slice().sort(compareInt) - var bs = b.slice().sort(compareInt) - for(var i=0; i= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); } - } - return 0 - } -} - -},{}],102:[function(require,module,exports){ -"use strict" - -var convexHull1d = require('./lib/ch1d') -var convexHull2d = require('./lib/ch2d') -var convexHullnd = require('./lib/chnd') - -module.exports = convexHull - -function convexHull(points) { - var n = points.length - if(n === 0) { - return [] - } else if(n === 1) { - return [[0]] - } - var d = points[0].length - if(d === 0) { - return [] - } else if(d === 1) { - return convexHull1d(points) - } else if(d === 2) { - return convexHull2d(points) - } - return convexHullnd(points, d) -} -},{"./lib/ch1d":103,"./lib/ch2d":104,"./lib/chnd":105}],103:[function(require,module,exports){ -"use strict" - -module.exports = convexHull1d - -function convexHull1d(points) { - var lo = 0 - var hi = 0 - for(var i=1; i points[hi][0]) { - hi = i + }; + function d3_geo_pathAreaRingStart() { + var x00, y00, x0, y0; + d3_geo_pathArea.point = function(x, y) { + d3_geo_pathArea.point = nextPoint; + x00 = x0 = x, y00 = y0 = y; + }; + function nextPoint(x, y) { + d3_geo_pathAreaPolygon += y0 * x - x0 * y; + x0 = x, y0 = y; } + d3_geo_pathArea.lineEnd = function() { + nextPoint(x00, y00); + }; } - if(lo < hi) { - return [[lo], [hi]] - } else if(lo > hi) { - return [[hi], [lo]] - } else { - return [[lo]] - } -} -},{}],104:[function(require,module,exports){ -'use strict' - -module.exports = convexHull2D - -var monotoneHull = require('monotone-convex-hull-2d') - -function convexHull2D(points) { - var hull = monotoneHull(points) - var h = hull.length - if(h <= 2) { - return [] - } - var edges = new Array(h) - var a = hull[h-1] - for(var i=0; i d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; } - return npoints -} - -function invPermute(cells, front) { - var nc = cells.length - var nf = front.length - for(var i=0; i= front[k]) { - x += 1 - } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; } - c[j] = x } + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); } - } - return cells -} - -function convexHullnD(points, d) { - try { - return ich(points, true) - } catch(e) { - //If point set is degenerate, try to find a basis and rerun it - var ah = aff(points) - if(ah.length <= d) { - //No basis, no try - return [] + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; } - var npoints = permute(points, ah) - var nhull = ich(npoints, true) - return invPermute(nhull, ah) - } -} -},{"affine-hull":106,"incremental-convex-hull":235}],106:[function(require,module,exports){ -'use strict' - -module.exports = affineHull - -var orient = require('robust-orientation') - -function linearlyIndependent(points, d) { - var nhull = new Array(d+1) - for(var i=0; i 1 && orient( - points[lower[m-2]], - points[lower[m-1]], - p) <= 0) { - m -= 1 - lower.pop() + function lineEnd() { + stream.point = point; } - lower.push(idx) - - //Insert into upper list - m = upper.length - while(m > 1 && orient( - points[upper[m-2]], - points[upper[m-1]], - p) >= 0) { - m -= 1 - upper.pop() + function lineEndPolygon() { + context.closePath(); } - upper.push(idx) - } - - //Merge lists together - var result = new Array(upper.length + lower.length - 2) - var ptr = 0 - for(var i=0, nl=lower.length; i0; --j) { - result[ptr++] = upper[j] + return stream; } - - //Return result - return result -} -},{"robust-orientation":259}],108:[function(require,module,exports){ -module.exports = { - AFG: "afghan", - ALA: "\\b\\wland", - ALB: "albania", - DZA: "algeria", - ASM: "^(?=.*americ).*samoa", - AND: "andorra", - AGO: "angola", - AIA: "anguill?a", - ATA: "antarctica", - ATG: "antigua", - ARG: "argentin", - ARM: "armenia", - ABW: "^(?!.*bonaire).*\\baruba", - AUS: "australia", - AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp", - AZE: "azerbaijan", - BHS: "bahamas", - BHR: "bahrain", - BGD: "bangladesh|^(?=.*east).*paki?stan", - BRB: "barbados", - BLR: "belarus|byelo", - BEL: "^(?!.*luxem).*belgium", - BLZ: "belize|^(?=.*british).*honduras", - BEN: "benin|dahome", - BMU: "bermuda", - BTN: "bhutan", - BOL: "bolivia", - BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands", - BIH: "herzegovina|bosnia", - BWA: "botswana|bechuana", - BVT: "bouvet", - BRA: "brazil", - IOT: "british.?indian.?ocean", - BRN: "brunei", - BGR: "bulgaria", - BFA: "burkina|\\bfaso|upper.?volta", - BDI: "burundi", - KHM: "cambodia|kampuchea|khmer", - CMR: "cameroon", - CAN: "canada", - CPV: "verde", - CYM: "cayman", - CAF: "\\bcentral.african.republic", - TCD: "\\bchad", - CHL: "\\bchile", - CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china", - CXR: "christmas", - CCK: "\\bcocos|keeling", - COL: "colombia", - COM: "comoro", - COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc", - COG: "^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo", - COK: "\\bcook", - CRI: "costa.?rica", - CIV: "ivoire|ivory", - HRV: "croatia", - CUB: "\\bcuba", - CUW: "^(?!.*bonaire).*\\bcura(c|ç)ao", - CYP: "cyprus", - CZE: "^(?=.*rep).*czech|czechia|bohemia", - CSK: "czechoslovakia", - DNK: "denmark", - DJI: "djibouti", - DMA: "dominica(?!n)", - DOM: "dominican.rep", - ECU: "ecuador", - EGY: "egypt", - SLV: "el.?salvador", - GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea", - ERI: "eritrea", - EST: "estonia", - ETH: "ethiopia|abyssinia", - FLK: "falkland|malvinas", - FRO: "faroe|faeroe", - FJI: "fiji", - FIN: "finland", - FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul", - GUF: "^(?=.*french).*guiana", - PYF: "french.?polynesia|tahiti", - ATF: "french.?southern", - GAB: "gabon", - GMB: "gambia", - GEO: "^(?!.*south).*georgia", - DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany", - DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german", - GHA: "ghana|gold.?coast", - GIB: "gibraltar", - GRC: "greece|hellenic|hellas", - GRL: "greenland", - GRD: "grenada", - GLP: "guadeloupe", - GUM: "\\bguam", - GTM: "guatemala", - GGY: "guernsey", - GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea", - GNB: "bissau|^(?=.*portu).*guinea", - GUY: "guyana|british.?guiana", - HTI: "haiti", - HMD: "heard.*mcdonald", - VAT: "holy.?see|vatican|papal.?st", - HND: "^(?!.*brit).*honduras", - HKG: "hong.?kong", - HUN: "^(?!.*austr).*hungary", - ISL: "iceland", - IND: "india(?!.*ocea)", - IDN: "indonesia", - IRN: "\\biran|persia", - IRQ: "\\biraq|mesopotamia", - IRL: "ireland", - IMN: "^(?=.*isle).*\\bman", - ISR: "israel", - ITA: "italy", - JAM: "jamaica", - JPN: "japan", - JEY: "jersey", - JOR: "jordan", - KAZ: "kazak", - KEN: "kenya|british.?east.?africa|east.?africa.?prot", - KIR: "kiribati", - PRK: "^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk", - KOR: "^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea", - KWT: "kuwait", - KGZ: "kyrgyz|kirghiz", - LAO: "\\blaos?\\b", - LVA: "latvia", - LBN: "lebanon", - LSO: "lesotho|basuto", - LBR: "liberia", - LBY: "libya", - LIE: "liechtenstein", - LTU: "lithuania", - LUX: "^(?!.*belg).*luxem", - MAC: "maca(o|u)", - MKD: "macedonia|fyrom", - MDG: "madagascar|malagasy", - MWI: "malawi|nyasa", - MYS: "malaysia", - MDV: "maldive", - MLI: "\\bmali\\b", - MLT: "\\bmalta", - MHL: "marshall", - MTQ: "martinique", - MRT: "mauritania", - MUS: "mauritius", - MYT: "\\bmayotte", - MEX: "\\bmexic", - FSM: "micronesia", - MDA: "moldov|b(a|e)ssarabia", - MCO: "monaco", - MNG: "mongolia", - MNE: "^(?!.*serbia).*montenegro", - MSR: "montserrat", - MAR: "morocco|\\bmaroc", - MOZ: "mozambique", - MMR: "myanmar|burma", - NAM: "namibia", - NRU: "nauru", - NPL: "nepal", - NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands", - ANT: "^(?=.*\\bant).*(nether|dutch)", - NCL: "new.?caledonia", - NZL: "new.?zealand", - NIC: "nicaragua", - NER: "\\bniger(?!ia)", - NGA: "nigeria", - NIU: "niue", - NFK: "norfolk", - MNP: "mariana", - NOR: "norway", - OMN: "\\boman|trucial", - PAK: "^(?!.*east).*paki?stan", - PLW: "palau", - PSE: "palestin|\\bgaza|west.?bank", - PAN: "panama", - PNG: "papua|new.?guinea", - PRY: "paraguay", - PER: "peru", - PHL: "philippines", - PCN: "pitcairn", - POL: "poland", - PRT: "portugal", - PRI: "puerto.?rico", - QAT: "qatar", - REU: "r(e|é)union", - ROU: "r(o|u|ou)mania", - RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics", - RWA: "rwanda", - BLM: "barth(e|é)lemy", - SHN: "helena", - KNA: "kitts|\\bnevis", - LCA: "\\blucia", - MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)", - SPM: "miquelon", - VCT: "vincent", - WSM: "^(?!.*amer).*samoa", - SMR: "san.?marino", - STP: "\\bs(a|ã)o.?tom(e|é)", - SAU: "\\bsa\\w*.?arabia", - SEN: "senegal", - SRB: "^(?!.*monte).*serbia", - SYC: "seychell", - SLE: "sierra", - SGP: "singapore", - SXM: "^(?!.*martin)(?!.*saba).*maarten", - SVK: "^(?!.*cze).*slovak", - SVN: "slovenia", - SLB: "solomon", - SOM: "somali", - ZAF: "\\bs\\w*.?africa", - SGS: "south.?georgia|sandwich", - SSD: "\\bs\\w*.?sudan", - ESP: "spain", - LKA: "sri.?lanka|ceylon", - SDN: "^(?!.*\\bs(?!u)).*sudan", - SUR: "surinam|dutch.?guiana", - SJM: "svalbard", - SWZ: "swaziland", - SWE: "sweden", - CHE: "switz|swiss", - SYR: "syria", - TWN: "taiwan|taipei|formosa", - TJK: "tajik", - TZA: "tanzania", - THA: "thailand|\\bsiam", - TLS: "^(?=.*leste).*timor|^(?=.*east).*timor", - TGO: "togo", - TKL: "tokelau", - TON: "tonga", - TTO: "trinidad|tobago", - TUN: "tunisia", - TUR: "turkey", - TKM: "turkmen", - TCA: "turks", - TUV: "tuvalu", - UGA: "uganda", - UKR: "ukrain", - ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em", - GBR: "united.?kingdom|britain|^u\\.?k\\.?$", - USA: "united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)", - UMI: "minor.?outlying.?is", - URY: "uruguay", - UZB: "uzbek", - VUT: "vanuatu|new.?hebrides", - VEN: "venezuela", - VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam", - VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin", - VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin", - WLF: "futuna|wallis", - ESH: "western.sahara", - YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen", - YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen", - YUG: "yugoslavia", - ZMB: "zambia|northern.?rhodesia", - EAZ: "zanzibar", - ZWE: "zimbabwe|^(?!.*northern).*rhodesia" -}; - -},{}],109:[function(require,module,exports){ -"use strict" - -var createThunk = require("./lib/thunk.js") - -function Procedure() { - this.argTypes = [] - this.shimArgs = [] - this.arrayArgs = [] - this.arrayBlockIndices = [] - this.scalarArgs = [] - this.offsetArgs = [] - this.offsetArgIndex = [] - this.indexArgs = [] - this.shapeArgs = [] - this.funcName = "" - this.pre = null - this.body = null - this.post = null - this.debug = false -} - -function compileCwise(user_args) { - //Create procedure - var proc = new Procedure() - - //Parse blocks - proc.pre = user_args.pre - proc.body = user_args.body - proc.post = user_args.post - - //Parse arguments - var proc_args = user_args.args.slice(0) - proc.argTypes = proc_args - for(var i=0; i0) { - throw new Error("cwise: pre() block may not reference array args") - } - if(i < proc.post.args.length && proc.post.args[i].count>0) { - throw new Error("cwise: post() block may not reference array args") - } - } else if(arg_type === "scalar") { - proc.scalarArgs.push(i) - proc.shimArgs.push("scalar" + i) - } else if(arg_type === "index") { - proc.indexArgs.push(i) - if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { - throw new Error("cwise: pre() block may not reference array index") - } - if(i < proc.body.args.length && proc.body.args[i].lvalue) { - throw new Error("cwise: body() block may not write to array index") - } - if(i < proc.post.args.length && proc.post.args[i].count > 0) { - throw new Error("cwise: post() block may not reference array index") - } - } else if(arg_type === "shape") { - proc.shapeArgs.push(i) - if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { - throw new Error("cwise: pre() block may not write to array shape") - } - if(i < proc.body.args.length && proc.body.args[i].lvalue) { - throw new Error("cwise: body() block may not write to array shape") - } - if(i < proc.post.args.length && proc.post.args[i].lvalue) { - throw new Error("cwise: post() block may not write to array shape") - } - } else if(typeof arg_type === "object" && arg_type.offset) { - proc.argTypes[i] = "offset" - proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) - proc.offsetArgIndex.push(i) - } else { - throw new Error("cwise: Unknown argument type " + proc_args[i]) - } - } - - //Make sure at least one array argument was specified - if(proc.arrayArgs.length <= 0) { - throw new Error("cwise: No array arguments specified") - } - - //Make sure arguments are correct - if(proc.pre.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in pre() block") - } - if(proc.body.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in body() block") - } - if(proc.post.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in post() block") - } - - //Check debug flag - proc.debug = !!user_args.printCode || !!user_args.debug - - //Retrieve name - proc.funcName = user_args.funcName || "cwise" - - //Read in block size - proc.blockSize = user_args.blockSize || 64 - - return createThunk(proc) -} - -module.exports = compileCwise - -},{"./lib/thunk.js":111}],110:[function(require,module,exports){ -"use strict" - -var uniq = require("uniq") - -// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) -// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. -function innerFill(order, proc, body) { - var dimension = order.length - , nargs = proc.arrayArgs.length - , has_index = proc.indexArgs.length>0 - , code = [] - , vars = [] - , idx=0, pidx=0, i, j - for(i=0; i=0; --i) { // Start at largest stride and work your way inwards - idx = order[i] - code.push(["for(i",i,"=0;i",i," 0) { - code.push(["index[",pidx,"]-=s",pidx].join("")) - } - code.push(["++index[",idx,"]"].join("")) - } - code.push("}") - } - return code.join("\n") -} - -// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. -// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. -// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. -function outerFill(matched, order, proc, body) { - var dimension = order.length - , nargs = proc.arrayArgs.length - , blockSize = proc.blockSize - , has_index = proc.indexArgs.length > 0 - , code = [] - for(var i=0; i0;){"].join("")) // Iterate back to front - code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). - code.push(["s",order[i],"=j",i].join("")) - code.push(["j",i,"=0"].join("")) - code.push(["}else{s",order[i],"=",blockSize].join("")) - code.push(["j",i,"-=",blockSize,"}"].join("")) - if(has_index) { - code.push(["index[",order[i],"]=j",i].join("")) - } - } - for(var i=0; i 0) { - allEqual = allEqual && summary[i] === summary[i-1] - } - } - if(allEqual) { - return summary[0] - } - return summary.join("") -} - -//Generates a cwise operator -function generateCWiseOp(proc, typesig) { - - //Compute dimension - // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. - var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 - var orders = new Array(proc.arrayArgs.length) - var dtypes = new Array(proc.arrayArgs.length) - for(var i=0; i 0) { - vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) - } - if(proc.indexArgs.length > 0) { - // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. - var zeros = new Array(dimension) - for(var i=0; i 3) { - code.push(processBlock(proc.pre, proc, dtypes)) - } - - //Process body - var body = processBlock(proc.body, proc, dtypes) - var matched = countMatches(loopOrders) - if(matched < dimension) { - code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. - } else { - code.push(innerFill(loopOrders[0], proc, body)) - } - - //Inline epilog - if(proc.post.body.length > 3) { - code.push(processBlock(proc.post, proc, dtypes)) - } - - if(proc.debug) { - console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") - } - - var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") - var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) - return f() -} -module.exports = generateCWiseOp - -},{"uniq":279}],111:[function(require,module,exports){ -"use strict" - -// The function below is called when constructing a cwise function object, and does the following: -// A function object is constructed which accepts as argument a compilation function and returns another function. -// It is this other function that is eventually returned by createThunk, and this function is the one that actually -// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. -// The compilation passed to the first function object is used for compiling new functions. -// Once this function object is created, it is called with compile as argument, where the first argument of compile -// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). -// So createThunk roughly works like this: -// function createThunk(proc) { -// var thunk = function(compileBound) { -// var CACHED = {} -// return function(arrays and scalars) { -// if (dtype and order of arrays in CACHED) { -// var func = CACHED[dtype and order of arrays] -// } else { -// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) -// } -// return func(arrays and scalars) -// } -// } -// return thunk(compile.bind1(proc)) -// } - -var compile = require("./compile.js") - -function createThunk(proc) { - var code = ["'use strict'", "var CACHED={}"] - var vars = [] - var thunkName = proc.funcName + "_cwise_thunk" - - //Build thunk - code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) - var typesig = [] - var string_typesig = [] - var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). - Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] - var shapeLengthConditions = [], shapeConditions = [] - // Process array arguments - for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) - shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) - shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") - } - } - // Check for shape equality - if (proc.arrayArgs.length > 1) { - code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") - code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") - code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") - code.push("}") - } - // Process scalar arguments - for(var i=0; i b ? 1 : a >= b ? 0 : NaN; - } - d3.descending = function(a, b) { - return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; - }; - d3.min = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array[i]) != null && a > b) a = b; - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; - } - return a; - }; - d3.max = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array[i]) != null && b > a) a = b; - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; - } - return a; - }; - d3.extent = function(array, f) { - var i = -1, n = array.length, a, b, c; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = array[i]) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } - return [ a, c ]; - }; - function d3_number(x) { - return x === null ? NaN : +x; - } - function d3_numeric(x) { - return !isNaN(x); - } - d3.sum = function(array, f) { - var s = 0, n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = +array[i])) s += a; - } else { - while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; - } - return s; - }; - d3.mean = function(array, f) { - var s = 0, n = array.length, a, i = -1, j = n; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; - } - if (j) return s / j; - }; - d3.quantile = function(values, p) { - var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; - return e ? v + e * (values[h] - v) : v; - }; - d3.median = function(array, f) { - var numbers = [], n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); - } - if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); - }; - d3.variance = function(array, f) { - var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; - if (arguments.length === 1) { - while (++i < n) { - if (d3_numeric(a = d3_number(array[i]))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } else { - while (++i < n) { - if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } - if (j > 1) return s / (j - 1); - }; - d3.deviation = function() { - var v = d3.variance.apply(this, arguments); - return v ? Math.sqrt(v) : v; - }; - function d3_bisector(compare) { - return { - left: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; - } - return lo; - }, - right: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; - } - return lo; - } - }; - } - var d3_bisect = d3_bisector(d3_ascending); - d3.bisectLeft = d3_bisect.left; - d3.bisect = d3.bisectRight = d3_bisect.right; - d3.bisector = function(f) { - return d3_bisector(f.length === 1 ? function(d, x) { - return d3_ascending(f(d), x); - } : f); - }; - d3.shuffle = function(array, i0, i1) { - if ((m = arguments.length) < 3) { - i1 = array.length; - if (m < 2) i0 = 0; - } - var m = i1 - i0, t, i; - while (m) { - i = Math.random() * m-- | 0; - t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; - } - return array; - }; - d3.permute = function(array, indexes) { - var i = indexes.length, permutes = new Array(i); - while (i--) permutes[i] = array[indexes[i]]; - return permutes; - }; - d3.pairs = function(array) { - var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); - while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; - return pairs; - }; - d3.transpose = function(matrix) { - if (!(n = matrix.length)) return []; - for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { - for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { - row[j] = matrix[j][i]; - } - } - return transpose; - }; - function d3_transposeLength(d) { - return d.length; - } - d3.zip = function() { - return d3.transpose(arguments); - }; - d3.keys = function(map) { - var keys = []; - for (var key in map) keys.push(key); - return keys; - }; - d3.values = function(map) { - var values = []; - for (var key in map) values.push(map[key]); - return values; - }; - d3.entries = function(map) { - var entries = []; - for (var key in map) entries.push({ - key: key, - value: map[key] - }); - return entries; - }; - d3.merge = function(arrays) { - var n = arrays.length, m, i = -1, j = 0, merged, array; - while (++i < n) j += arrays[i].length; - merged = new Array(j); - while (--n >= 0) { - array = arrays[n]; - m = array.length; - while (--m >= 0) { - merged[--j] = array[m]; - } - } - return merged; - }; - var abs = Math.abs; - d3.range = function(start, stop, step) { - if (arguments.length < 3) { - step = 1; - if (arguments.length < 2) { - stop = start; - start = 0; - } - } - if ((stop - start) / step === Infinity) throw new Error("infinite range"); - var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; - start *= k, stop *= k, step *= k; - if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); - return range; - }; - function d3_range_integerScale(x) { - var k = 1; - while (x * k % 1) k *= 10; - return k; - } - function d3_class(ctor, properties) { - for (var key in properties) { - Object.defineProperty(ctor.prototype, key, { - value: properties[key], - enumerable: false - }); - } - } - d3.map = function(object, f) { - var map = new d3_Map(); - if (object instanceof d3_Map) { - object.forEach(function(key, value) { - map.set(key, value); - }); - } else if (Array.isArray(object)) { - var i = -1, n = object.length, o; - if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); - } else { - for (var key in object) map.set(key, object[key]); - } - return map; - }; - function d3_Map() { - this._ = Object.create(null); - } - var d3_map_proto = "__proto__", d3_map_zero = "\x00"; - d3_class(d3_Map, { - has: d3_map_has, - get: function(key) { - return this._[d3_map_escape(key)]; - }, - set: function(key, value) { - return this._[d3_map_escape(key)] = value; - }, - remove: d3_map_remove, - keys: d3_map_keys, - values: function() { - var values = []; - for (var key in this._) values.push(this._[key]); - return values; - }, - entries: function() { - var entries = []; - for (var key in this._) entries.push({ - key: d3_map_unescape(key), - value: this._[key] - }); - return entries; - }, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); - } - }); - function d3_map_escape(key) { - return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; - } - function d3_map_unescape(key) { - return (key += "")[0] === d3_map_zero ? key.slice(1) : key; - } - function d3_map_has(key) { - return d3_map_escape(key) in this._; - } - function d3_map_remove(key) { - return (key = d3_map_escape(key)) in this._ && delete this._[key]; - } - function d3_map_keys() { - var keys = []; - for (var key in this._) keys.push(d3_map_unescape(key)); - return keys; - } - function d3_map_size() { - var size = 0; - for (var key in this._) ++size; - return size; - } - function d3_map_empty() { - for (var key in this._) return false; - return true; - } - d3.nest = function() { - var nest = {}, keys = [], sortKeys = [], sortValues, rollup; - function map(mapType, array, depth) { - if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; - var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; - while (++i < n) { - if (values = valuesByKey.get(keyValue = key(object = array[i]))) { - values.push(object); - } else { - valuesByKey.set(keyValue, [ object ]); - } - } - if (mapType) { - object = mapType(); - setter = function(keyValue, values) { - object.set(keyValue, map(mapType, values, depth)); - }; - } else { - object = {}; - setter = function(keyValue, values) { - object[keyValue] = map(mapType, values, depth); - }; - } - valuesByKey.forEach(setter); - return object; - } - function entries(map, depth) { - if (depth >= keys.length) return map; - var array = [], sortKey = sortKeys[depth++]; - map.forEach(function(key, keyMap) { - array.push({ - key: key, - values: entries(keyMap, depth) - }); - }); - return sortKey ? array.sort(function(a, b) { - return sortKey(a.key, b.key); - }) : array; - } - nest.map = function(array, mapType) { - return map(mapType, array, 0); - }; - nest.entries = function(array) { - return entries(map(d3.map, array, 0), 0); - }; - nest.key = function(d) { - keys.push(d); - return nest; - }; - nest.sortKeys = function(order) { - sortKeys[keys.length - 1] = order; - return nest; - }; - nest.sortValues = function(order) { - sortValues = order; - return nest; - }; - nest.rollup = function(f) { - rollup = f; - return nest; - }; - return nest; - }; - d3.set = function(array) { - var set = new d3_Set(); - if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); - return set; - }; - function d3_Set() { - this._ = Object.create(null); - } - d3_class(d3_Set, { - has: d3_map_has, - add: function(key) { - this._[d3_map_escape(key += "")] = true; - return key; - }, - remove: d3_map_remove, - values: d3_map_keys, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key)); - } - }); - d3.behavior = {}; - function d3_identity(d) { - return d; - } - d3.rebind = function(target, source) { - var i = 1, n = arguments.length, method; - while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); - return target; - }; - function d3_rebind(target, source, method) { - return function() { - var value = method.apply(source, arguments); - return value === source ? target : value; - }; - } - function d3_vendorSymbol(object, name) { - if (name in object) return name; - name = name.charAt(0).toUpperCase() + name.slice(1); - for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { - var prefixName = d3_vendorPrefixes[i] + name; - if (prefixName in object) return prefixName; - } - } - var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; - function d3_noop() {} - d3.dispatch = function() { - var dispatch = new d3_dispatch(), i = -1, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - return dispatch; - }; - function d3_dispatch() {} - d3_dispatch.prototype.on = function(type, listener) { - var i = type.indexOf("."), name = ""; - if (i >= 0) { - name = type.slice(i + 1); - type = type.slice(0, i); - } - if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); - if (arguments.length === 2) { - if (listener == null) for (type in this) { - if (this.hasOwnProperty(type)) this[type].on(name, null); - } - return this; + function d3_geo_resample(project) { + var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; + function resample(stream) { + return (maxDepth ? resampleRecursive : resampleNone)(stream); } - }; - function d3_dispatch_event(dispatch) { - var listeners = [], listenerByName = new d3_Map(); - function event() { - var z = listeners, i = -1, n = z.length, l; - while (++i < n) if (l = z[i].on) l.apply(this, arguments); - return dispatch; + function resampleNone(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + }); } - event.on = function(name, listener) { - var l = listenerByName.get(name), i; - if (arguments.length < 2) return l && l.on; - if (l) { - l.on = null; - listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); - listenerByName.remove(name); - } - if (listener) listeners.push(listenerByName.set(name, { - on: listener - })); - return dispatch; - }; - return event; - } - d3.event = null; - function d3_eventPreventDefault() { - d3.event.preventDefault(); - } - function d3_eventSource() { - var e = d3.event, s; - while (s = e.sourceEvent) e = s; - return e; - } - function d3_eventDispatch(target) { - var dispatch = new d3_dispatch(), i = 0, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - dispatch.of = function(thiz, argumentz) { - return function(e1) { - try { - var e0 = e1.sourceEvent = d3.event; - e1.target = target; - d3.event = e1; - dispatch[e1.type].apply(thiz, argumentz); - } finally { - d3.event = e0; + function resampleRecursive(stream) { + var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; + var resample = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + stream.polygonStart(); + resample.lineStart = ringStart; + }, + polygonEnd: function() { + stream.polygonEnd(); + resample.lineStart = lineStart; } }; - }; - return dispatch; - } - d3.requote = function(s) { - return s.replace(d3_requote_re, "\\$&"); - }; - var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; - var d3_subclass = {}.__proto__ ? function(object, prototype) { - object.__proto__ = prototype; - } : function(object, prototype) { - for (var property in prototype) object[property] = prototype[property]; - }; - function d3_selection(groups) { - d3_subclass(groups, d3_selectionPrototype); - return groups; - } - var d3_select = function(s, n) { - return n.querySelector(s); - }, d3_selectAll = function(s, n) { - return n.querySelectorAll(s); - }, d3_selectMatches = function(n, s) { - var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; - d3_selectMatches = function(n, s) { - return d3_selectMatcher.call(n, s); - }; - return d3_selectMatches(n, s); - }; - if (typeof Sizzle === "function") { - d3_select = function(s, n) { - return Sizzle(s, n)[0] || null; - }; - d3_selectAll = Sizzle; - d3_selectMatches = Sizzle.matchesSelector; - } - d3.selection = function() { - return d3.select(d3_document.documentElement); - }; - var d3_selectionPrototype = d3.selection.prototype = []; - d3_selectionPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, group, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(subnode = selector.call(node, node.__data__, i, j)); - if (subnode && "__data__" in node) subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selector(selector) { - return typeof selector === "function" ? selector : function() { - return d3_select(selector, this); - }; - } - d3_selectionPrototype.selectAll = function(selector) { - var subgroups = [], subgroup, node; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); - subgroup.parentNode = node; - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selectorAll(selector) { - return typeof selector === "function" ? selector : function() { - return d3_selectAll(selector, this); - }; - } - var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; - var d3_nsPrefix = { - svg: "http://www.w3.org/2000/svg", - xhtml: d3_nsXhtml, - xlink: "http://www.w3.org/1999/xlink", - xml: "http://www.w3.org/XML/1998/namespace", - xmlns: "http://www.w3.org/2000/xmlns/" - }; - d3.ns = { - prefix: d3_nsPrefix, - qualify: function(name) { - var i = name.indexOf(":"), prefix = name; - if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); - return d3_nsPrefix.hasOwnProperty(prefix) ? { - space: d3_nsPrefix[prefix], - local: name - } : name; - } - }; - d3_selectionPrototype.attr = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(); - name = d3.ns.qualify(name); - return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); - } - for (value in name) this.each(d3_selection_attr(value, name[value])); - return this; - } - return this.each(d3_selection_attr(name, value)); - }; - function d3_selection_attr(name, value) { - name = d3.ns.qualify(name); - function attrNull() { - this.removeAttribute(name); - } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); - } - function attrConstant() { - this.setAttribute(name, value); - } - function attrConstantNS() { - this.setAttributeNS(name.space, name.local, value); - } - function attrFunction() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); - } - function attrFunctionNS() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); - } - return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; - } - function d3_collapse(s) { - return s.trim().replace(/\s+/g, " "); - } - d3_selectionPrototype.classed = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; - if (value = node.classList) { - while (++i < n) if (!value.contains(name[i])) return false; - } else { - value = node.getAttribute("class"); - while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; - } - return true; - } - for (value in name) this.each(d3_selection_classed(value, name[value])); - return this; - } - return this.each(d3_selection_classed(name, value)); - }; - function d3_selection_classedRe(name) { - return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); - } - function d3_selection_classes(name) { - return (name + "").trim().split(/^|\s+/); - } - function d3_selection_classed(name, value) { - name = d3_selection_classes(name).map(d3_selection_classedName); - var n = name.length; - function classedConstant() { - var i = -1; - while (++i < n) name[i](this, value); - } - function classedFunction() { - var i = -1, x = value.apply(this, arguments); - while (++i < n) name[i](this, x); - } - return typeof value === "function" ? classedFunction : classedConstant; - } - function d3_selection_classedName(name) { - var re = d3_selection_classedRe(name); - return function(node, value) { - if (c = node.classList) return value ? c.add(name) : c.remove(name); - var c = node.getAttribute("class") || ""; - if (value) { - re.lastIndex = 0; - if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); - } else { - node.setAttribute("class", d3_collapse(c.replace(re, " "))); - } - }; - } - d3_selectionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); - return this; - } - if (n < 2) { - var node = this.node(); - return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); - } - priority = ""; - } - return this.each(d3_selection_style(name, value, priority)); - }; - function d3_selection_style(name, value, priority) { - function styleNull() { - this.style.removeProperty(name); - } - function styleConstant() { - this.style.setProperty(name, value, priority); - } - function styleFunction() { - var x = value.apply(this, arguments); - if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); - } - return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; - } - d3_selectionPrototype.property = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") return this.node()[name]; - for (value in name) this.each(d3_selection_property(value, name[value])); - return this; - } - return this.each(d3_selection_property(name, value)); - }; - function d3_selection_property(name, value) { - function propertyNull() { - delete this[name]; - } - function propertyConstant() { - this[name] = value; - } - function propertyFunction() { - var x = value.apply(this, arguments); - if (x == null) delete this[name]; else this[name] = x; - } - return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; - } - d3_selectionPrototype.text = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.textContent = v == null ? "" : v; - } : value == null ? function() { - this.textContent = ""; - } : function() { - this.textContent = value; - }) : this.node().textContent; - }; - d3_selectionPrototype.html = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.innerHTML = v == null ? "" : v; - } : value == null ? function() { - this.innerHTML = ""; - } : function() { - this.innerHTML = value; - }) : this.node().innerHTML; - }; - d3_selectionPrototype.append = function(name) { - name = d3_selection_creator(name); - return this.select(function() { - return this.appendChild(name.apply(this, arguments)); - }); - }; - function d3_selection_creator(name) { - function create() { - var document = this.ownerDocument, namespace = this.namespaceURI; - return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); - } - function createNS() { - return this.ownerDocument.createElementNS(name.space, name.local); - } - return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; - } - d3_selectionPrototype.insert = function(name, before) { - name = d3_selection_creator(name); - before = d3_selection_selector(before); - return this.select(function() { - return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); - }); - }; - d3_selectionPrototype.remove = function() { - return this.each(d3_selectionRemove); - }; - function d3_selectionRemove() { - var parent = this.parentNode; - if (parent) parent.removeChild(this); - } - d3_selectionPrototype.data = function(value, key) { - var i = -1, n = this.length, group, node; - if (!arguments.length) { - value = new Array(n = (group = this[0]).length); - while (++i < n) { - if (node = group[i]) { - value[i] = node.__data__; - } - } - return value; - } - function bind(group, groupData) { - var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; - if (key) { - var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; - for (i = -1; ++i < n; ) { - if (node = group[i]) { - if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { - exitNodes[i] = node; - } else { - nodeByKeyValue.set(keyValue, node); - } - keyValues[i] = keyValue; - } - } - for (i = -1; ++i < m; ) { - if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { - enterNodes[i] = d3_selection_dataNode(nodeData); - } else if (node !== true) { - updateNodes[i] = node; - node.__data__ = nodeData; - } - nodeByKeyValue.set(keyValue, true); - } - for (i = -1; ++i < n; ) { - if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { - exitNodes[i] = group[i]; - } - } - } else { - for (i = -1; ++i < n0; ) { - node = group[i]; - nodeData = groupData[i]; - if (node) { - node.__data__ = nodeData; - updateNodes[i] = node; - } else { - enterNodes[i] = d3_selection_dataNode(nodeData); - } - } - for (;i < m; ++i) { - enterNodes[i] = d3_selection_dataNode(groupData[i]); - } - for (;i < n; ++i) { - exitNodes[i] = group[i]; - } + function point(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); } - enterNodes.update = updateNodes; - enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; - enter.push(enterNodes); - update.push(updateNodes); - exit.push(exitNodes); - } - var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); - if (typeof value === "function") { - while (++i < n) { - bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + function lineStart() { + x0 = NaN; + resample.point = linePoint; + stream.lineStart(); } - } else { - while (++i < n) { - bind(group = this[i], value); + function linePoint(λ, φ) { + var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); + resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); + stream.point(x0, y0); } - } - update.enter = function() { - return enter; - }; - update.exit = function() { - return exit; - }; - return update; - }; - function d3_selection_dataNode(data) { - return { - __data__: data - }; - } - d3_selectionPrototype.datum = function(value) { - return arguments.length ? this.property("__data__", value) : this.property("__data__"); - }; - d3_selectionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); - } + function lineEnd() { + resample.point = point; + stream.lineEnd(); } - } - return d3_selection(subgroups); - }; - function d3_selection_filter(selector) { - return function() { - return d3_selectMatches(this, selector); - }; - } - d3_selectionPrototype.order = function() { - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { - if (node = group[i]) { - if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); - next = node; - } + function ringStart() { + lineStart(); + resample.point = ringPoint; + resample.lineEnd = ringEnd; } - } - return this; - }; - d3_selectionPrototype.sort = function(comparator) { - comparator = d3_selection_sortComparator.apply(this, arguments); - for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); - return this.order(); - }; - function d3_selection_sortComparator(comparator) { - if (!arguments.length) comparator = d3_ascending; - return function(a, b) { - return a && b ? comparator(a.__data__, b.__data__) : !a - !b; - }; - } - d3_selectionPrototype.each = function(callback) { - return d3_selection_each(this, function(node, i, j) { - callback.call(node, node.__data__, i, j); - }); - }; - function d3_selection_each(groups, callback) { - for (var j = 0, m = groups.length; j < m; j++) { - for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { - if (node = group[i]) callback(node, i, j); + function ringPoint(λ, φ) { + linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; + resample.point = linePoint; } - } - return groups; - } - d3_selectionPrototype.call = function(callback) { - var args = d3_array(arguments); - callback.apply(args[0] = this, args); - return this; - }; - d3_selectionPrototype.empty = function() { - return !this.node(); - }; - d3_selectionPrototype.node = function() { - for (var j = 0, m = this.length; j < m; j++) { - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - var node = group[i]; - if (node) return node; + function ringEnd() { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); + resample.lineEnd = lineEnd; + lineEnd(); } + return resample; } - return null; - }; - d3_selectionPrototype.size = function() { - var n = 0; - d3_selection_each(this, function() { - ++n; - }); - return n; - }; - function d3_selection_enter(selection) { - d3_subclass(selection, d3_selection_enterPrototype); - return selection; - } - var d3_selection_enterPrototype = []; - d3.selection.enter = d3_selection_enter; - d3.selection.enter.prototype = d3_selection_enterPrototype; - d3_selection_enterPrototype.append = d3_selectionPrototype.append; - d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; - d3_selection_enterPrototype.node = d3_selectionPrototype.node; - d3_selection_enterPrototype.call = d3_selectionPrototype.call; - d3_selection_enterPrototype.size = d3_selectionPrototype.size; - d3_selection_enterPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, upgroup, group, node; - for (var j = -1, m = this.length; ++j < m; ) { - upgroup = (group = this[j]).update; - subgroups.push(subgroup = []); - subgroup.parentNode = group.parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); - subnode.__data__ = node.__data__; - } else { - subgroup.push(null); + function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { + var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; + if (d2 > 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); } } } - return d3_selection(subgroups); - }; - d3_selection_enterPrototype.insert = function(name, before) { - if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); - return d3_selectionPrototype.insert.call(this, name, before); - }; - function d3_selection_enterInsertBefore(enter) { - var i0, j0; - return function(d, i, j) { - var group = enter[j].update, n = group.length, node; - if (j != j0) j0 = j, i0 = 0; - if (i >= i0) i0 = i + 1; - while (!(node = group[i0]) && ++i0 < n) ; - return node; + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; }; + return resample; } - d3.select = function(node) { - var group; - if (typeof node === "string") { - group = [ d3_select(node, d3_document) ]; - group.parentNode = d3_document.documentElement; - } else { - group = [ node ]; - group.parentNode = d3_documentElement(node); - } - return d3_selection([ group ]); - }; - d3.selectAll = function(nodes) { - var group; - if (typeof nodes === "string") { - group = d3_array(d3_selectAll(nodes, d3_document)); - group.parentNode = d3_document.documentElement; - } else { - group = d3_array(nodes); - group.parentNode = null; - } - return d3_selection([ group ]); - }; - d3_selectionPrototype.on = function(type, listener, capture) { - var n = arguments.length; - if (n < 3) { - if (typeof type !== "string") { - if (n < 2) listener = false; - for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); - return this; - } - if (n < 2) return (n = this.node()["__on" + type]) && n._; - capture = false; - } - return this.each(d3_selection_on(type, listener, capture)); - }; - function d3_selection_on(type, listener, capture) { - var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; - if (i > 0) type = type.slice(0, i); - var filter = d3_selection_onFilters.get(type); - if (filter) type = filter, wrap = d3_selection_onFilter; - function onRemove() { - var l = this[name]; - if (l) { - this.removeEventListener(type, l, l.$); - delete this[name]; + d3.geo.path = function() { + var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; + function path(object) { + if (object) { + if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); + if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); + d3.geo.stream(object, cacheStream); } + return contextStream.result(); } - function onAdd() { - var l = wrap(listener, d3_array(arguments)); - onRemove.call(this); - this.addEventListener(type, this[name] = l, l.$ = capture); - l._ = listener; - } - function removeAll() { - var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; - for (var name in this) { - if (match = name.match(re)) { - var l = this[name]; - this.removeEventListener(match[1], l, l.$); - delete this[name]; - } - } + path.area = function(object) { + d3_geo_pathAreaSum = 0; + d3.geo.stream(object, projectStream(d3_geo_pathArea)); + return d3_geo_pathAreaSum; + }; + path.centroid = function(object) { + d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); + return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + }; + path.bounds = function(object) { + d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); + d3.geo.stream(object, projectStream(d3_geo_pathBounds)); + return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + }; + path.projection = function(_) { + if (!arguments.length) return projection; + projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; + return reset(); + }; + path.context = function(_) { + if (!arguments.length) return context; + contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); + if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); + return reset(); + }; + path.pointRadius = function(_) { + if (!arguments.length) return pointRadius; + pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); + return path; + }; + function reset() { + cacheStream = null; + return path; } - return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; - } - var d3_selection_onFilters = d3.map({ - mouseenter: "mouseover", - mouseleave: "mouseout" - }); - if (d3_document) { - d3_selection_onFilters.forEach(function(k) { - if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + return path.projection(d3.geo.albersUsa()).context(null); + }; + function d3_geo_pathProjectStream(project) { + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); }); - } - function d3_selection_onListener(listener, argumentz) { - return function(e) { - var o = d3.event; - d3.event = e; - argumentz[0] = this.__data__; - try { - listener.apply(this, argumentz); - } finally { - d3.event = o; - } + return function(stream) { + return d3_geo_projectionRadians(resample(stream)); }; } - function d3_selection_onFilter(listener, argumentz) { - var l = d3_selection_onListener(listener, argumentz); - return function(e) { - var target = this, related = e.relatedTarget; - if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { - l.call(target, e); + d3.geo.transform = function(methods) { + return { + stream: function(stream) { + var transform = new d3_geo_transform(stream); + for (var k in methods) transform[k] = methods[k]; + return transform; } }; + }; + function d3_geo_transform(stream) { + this.stream = stream; } - var d3_event_dragSelect, d3_event_dragId = 0; - function d3_event_dragSuppress(node) { - var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); - if (d3_event_dragSelect == null) { - d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); - } - if (d3_event_dragSelect) { - var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; - style[d3_event_dragSelect] = "none"; + d3_geo_transform.prototype = { + point: function(x, y) { + this.stream.point(x, y); + }, + sphere: function() { + this.stream.sphere(); + }, + lineStart: function() { + this.stream.lineStart(); + }, + lineEnd: function() { + this.stream.lineEnd(); + }, + polygonStart: function() { + this.stream.polygonStart(); + }, + polygonEnd: function() { + this.stream.polygonEnd(); } - return function(suppressClick) { - w.on(name, null); - if (d3_event_dragSelect) style[d3_event_dragSelect] = select; - if (suppressClick) { - var off = function() { - w.on(click, null); - }; - w.on(click, function() { - d3_eventPreventDefault(); - off(); - }, true); - setTimeout(off, 0); + }; + function d3_geo_transformPoint(stream, point) { + return { + point: point, + sphere: function() { + stream.sphere(); + }, + lineStart: function() { + stream.lineStart(); + }, + lineEnd: function() { + stream.lineEnd(); + }, + polygonStart: function() { + stream.polygonStart(); + }, + polygonEnd: function() { + stream.polygonEnd(); } }; } - d3.mouse = function(container) { - return d3_mousePoint(container, d3_eventSource()); - }; - var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; - function d3_mousePoint(container, e) { - if (e.changedTouches) e = e.changedTouches[0]; - var svg = container.ownerSVGElement || container; - if (svg.createSVGPoint) { - var point = svg.createSVGPoint(); - if (d3_mouse_bug44083 < 0) { - var window = d3_window(container); - if (window.scrollX || window.scrollY) { - svg = d3.select("body").append("svg").style({ - position: "absolute", - top: 0, - left: 0, - margin: 0, - padding: 0, - border: "none" - }, "important"); - var ctm = svg[0][0].getScreenCTM(); - d3_mouse_bug44083 = !(ctm.f || ctm.e); - svg.remove(); - } - } - if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, - point.y = e.clientY; - point = point.matrixTransform(container.getScreenCTM().inverse()); - return [ point.x, point.y ]; - } - var rect = container.getBoundingClientRect(); - return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + d3.geo.projection = d3_geo_projection; + d3.geo.projectionMutator = d3_geo_projectionMutator; + function d3_geo_projection(project) { + return d3_geo_projectionMutator(function() { + return project; + })(); } - d3.touch = function(container, touches, identifier) { - if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; - if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { - if ((touch = touches[i]).identifier === identifier) { - return d3_mousePoint(container, touch); - } + function d3_geo_projectionMutator(projectAt) { + var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { + x = project(x, y); + return [ x[0] * k + δx, δy - x[1] * k ]; + }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; + function projection(point) { + point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); + return [ point[0] * k + δx, δy - point[1] * k ]; } - }; - d3.behavior.drag = function() { - var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); - function drag() { - this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + function invert(point) { + point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); + return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; } - function dragstart(id, position, subject, move, end) { - return function() { - var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); - if (origin) { - dragOffset = origin.apply(that, arguments); - dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; - } else { - dragOffset = [ 0, 0 ]; - } - dispatch({ - type: "dragstart" - }); - function moved() { - var position1 = position(parent, dragId), dx, dy; - if (!position1) return; - dx = position1[0] - position0[0]; - dy = position1[1] - position0[1]; - dragged |= dx | dy; - position0 = position1; - dispatch({ - type: "drag", - x: position1[0] + dragOffset[0], - y: position1[1] + dragOffset[1], - dx: dx, - dy: dy - }); - } - function ended() { - if (!position(parent, dragId)) return; - dragSubject.on(move + dragName, null).on(end + dragName, null); - dragRestore(dragged); - dispatch({ - type: "dragend" - }); - } - }; + projection.stream = function(output) { + if (stream) stream.valid = false; + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); + stream.valid = true; + return stream; + }; + projection.clipAngle = function(_) { + if (!arguments.length) return clipAngle; + preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); + return invalidate(); + }; + projection.clipExtent = function(_) { + if (!arguments.length) return clipExtent; + clipExtent = _; + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; + return invalidate(); + }; + projection.scale = function(_) { + if (!arguments.length) return k; + k = +_; + return reset(); + }; + projection.translate = function(_) { + if (!arguments.length) return [ x, y ]; + x = +_[0]; + y = +_[1]; + return reset(); + }; + projection.center = function(_) { + if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; + λ = _[0] % 360 * d3_radians; + φ = _[1] % 360 * d3_radians; + return reset(); + }; + projection.rotate = function(_) { + if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; + δλ = _[0] % 360 * d3_radians; + δφ = _[1] % 360 * d3_radians; + δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); } - drag.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return drag; + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); }; - return d3.rebind(drag, event, "on"); - }; - function d3_behavior_dragTouchId() { - return d3.event.changedTouches[0].identifier; - } - d3.touches = function(container, touches) { - if (arguments.length < 2) touches = d3_eventSource().touches; - return touches ? d3_array(touches).map(function(touch) { - var point = d3_mousePoint(container, touch); - point.identifier = touch.identifier; - return point; - }) : []; - }; - var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; - function d3_sgn(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; } - function d3_cross2d(a, b, c) { - return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); } - function d3_acos(x) { - return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; } - function d3_asin(x) { - return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + } + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; } - function d3_sinh(x) { - return ((x = Math.exp(x)) - 1 / x) / 2; + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; } - function d3_cosh(x) { - return ((x = Math.exp(x)) + 1 / x) / 2; + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + }; } - function d3_tanh(x) { - return ((x = Math.exp(2 * x)) - 1) / (x + 1); + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; } - function d3_haversin(x) { - return (x = Math.sin(x / 2)) * x; + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; } - var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; - d3.interpolateZoom = function(p0, p1) { - var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; - if (d2 < ε2) { - S = Math.log(w1 / w0) / ρ; - i = function(t) { - return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; - }; - } else { - var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); - S = (r1 - r0) / ρ; - i = function(t) { - var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); - return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] }; } - i.duration = S * 1e3; - return i; + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); }; - d3.behavior.zoom = function() { - var view = { - x: 0, - y: 0, - k: 1 - }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; - if (!d3_behavior_zoomWheel) { - d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); - }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return d3.event.wheelDelta; - }, "mousewheel") : (d3_behavior_zoomDelta = function() { - return -d3.event.detail; - }, "MozMousePixelScroll"); + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * τ; + } else { + from = radius + direction * τ; + to = radius - .5 * step; + } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + } + }; + } + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + } + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; } - function zoom(g) { - g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); } - zoom.event = function(g) { - g.each(function() { - var dispatch = event.of(this, arguments), view1 = view; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.zoom", function() { - view = this.__chart__ || { - x: 0, - y: 0, - k: 1 - }; - zoomstarted(dispatch); - }).tween("zoom:zoom", function() { - var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); - return function(t) { - var l = i(t), k = dx / l[2]; - this.__chart__ = view = { - x: cx - l[0] * k, - y: cy - l[1] * k, - k: k - }; - zoomed(dispatch); - }; - }).each("interrupt.zoom", function() { - zoomended(dispatch); - }).each("end.zoom", function() { - zoomended(dispatch); - }); - } else { - this.__chart__ = view; - zoomstarted(dispatch); - zoomed(dispatch); - zoomended(dispatch); - } + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; }); }; - zoom.translate = function(_) { - if (!arguments.length) return [ view.x, view.y ]; - view = { - x: +_[0], - y: +_[1], - k: view.k + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] }; - rescale(); - return zoom; }; - zoom.scale = function(_) { - if (!arguments.length) return view.k; - view = { - x: view.x, - y: view.y, - k: null - }; - scaleTo(+_); - rescale(); - return zoom; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); }; - zoom.scaleExtent = function(_) { - if (!arguments.length) return scaleExtent; - scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; - return zoom; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); }; - zoom.center = function(_) { - if (!arguments.length) return center; - center = _ && [ +_[0], +_[1] ]; - return zoom; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); }; - zoom.size = function(_) { - if (!arguments.length) return size; - size = _ && [ +_[0], +_[1] ]; - return zoom; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); }; - zoom.duration = function(_) { - if (!arguments.length) return duration; - duration = +_; - return zoom; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; }; - zoom.x = function(z) { - if (!arguments.length) return x1; - x1 = z; - x0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; }; - zoom.y = function(z) { - if (!arguments.length) return y1; - y1 = z; - y0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; }; - function location(p) { - return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; - } - function point(l) { - return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; - } - function scaleTo(s) { - view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); - } - function translateTo(p, l) { - l = point(l); - view.x += p[0] - l[0]; - view.y += p[1] - l[1]; - } - function zoomTo(that, p, l, k) { - that.__chart__ = { - x: view.x, - y: view.y, - k: view.k - }; - scaleTo(Math.pow(2, k)); - translateTo(center0 = p, l); - that = d3.select(that); - if (duration > 0) that = that.transition().duration(duration); - that.call(zoom.event); - } - function rescale() { - if (x1) x1.domain(x0.range().map(function(x) { - return (x - view.x) / view.k; - }).map(x0.invert)); - if (y1) y1.domain(y0.range().map(function(y) { - return (y - view.y) / view.k; - }).map(y0.invert)); - } - function zoomstarted(dispatch) { - if (!zooming++) dispatch({ - type: "zoomstart" + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; }); - } - function zoomed(dispatch) { - rescale(); - dispatch({ - type: "zoom", - scale: view.k, - translate: [ view.x, view.y ] + }; + } + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; }); + }; + } + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; } - function zoomended(dispatch) { - if (!--zooming) dispatch({ - type: "zoomend" - }), center0 = null; + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; + } + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; } - function mousedowned() { - var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); - d3_selection_interrupt.call(that); - zoomstarted(dispatch); - function moved() { - dragged = 1; - translateTo(d3.mouse(that), location0); - zoomed(dispatch); - } - function ended() { - subject.on(mousemove, null).on(mouseup, null); - dragRestore(dragged); - zoomended(dispatch); - } + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; } - function touchstarted() { - var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); - started(); - zoomstarted(dispatch); - subject.on(mousedown, null).on(touchstart, started); - function relocate() { - var touches = d3.touches(that); - scale0 = view.k; - touches.forEach(function(t) { - if (t.identifier in locations0) locations0[t.identifier] = location(t); - }); - return touches; - } - function started() { - var target = d3.event.target; - d3.select(target).on(touchmove, moved).on(touchend, ended); - targets.push(target); - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - locations0[changed[i].identifier] = null; - } - var touches = relocate(), now = Date.now(); - if (touches.length === 1) { - if (now - touchtime < 500) { - var p = touches[0]; - zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); - d3_eventPreventDefault(); - } - touchtime = now; - } else if (touches.length > 1) { - var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; - distance0 = dx * dx + dy * dy; - } - } - function moved() { - var touches = d3.touches(that), p0, l0, p1, l1; - d3_selection_interrupt.call(that); - for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { - p1 = touches[i]; - if (l1 = locations0[p1.identifier]) { - if (l0) break; - p0 = p1, l0 = l1; - } - } - if (l1) { - var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); - p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; - l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; - scaleTo(scale1 * scale0); - } - touchtime = null; - translateTo(p0, l0); - zoomed(dispatch); - } - function ended() { - if (d3.event.touches.length) { - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - delete locations0[changed[i].identifier]; - } - for (var identifier in locations0) { - return void relocate(); - } - } - d3.selectAll(targets).on(zoomName, null); - subject.on(mousedown, mousedowned).on(touchstart, touchstarted); - dragRestore(); - zoomended(dispatch); + azimuthal.invert = function(x, y) { + var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + }; + return azimuthal; + } + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(ρ) { + return 2 * Math.asin(ρ / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(π / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + if (F > 0) { + if (φ < -halfπ + ε) φ = -halfπ + ε; + } else { + if (φ > halfπ - ε) φ = halfπ - ε; } + var ρ = F / Math.pow(t(φ), n); + return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } - function mousewheeled() { - var dispatch = event.of(this, arguments); - if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), - translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); - mousewheelTimer = setTimeout(function() { - mousewheelTimer = null; - zoomended(dispatch); - }, 50); - d3_eventPreventDefault(); - scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); - translateTo(center0, translate0); - zoomed(dispatch); - } - function dblclicked() { - var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; - zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + forward.invert = function(x, y) { + var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; + }; + return forward; + } + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var ρ = G - φ; + return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; } - return d3.rebind(zoom, event, "on"); - }; - var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; - d3.color = d3_color; - function d3_color() {} - d3_color.prototype.toString = function() { - return this.rgb() + ""; - }; - d3.hsl = d3_hsl; - function d3_hsl(h, s, l) { - return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); + forward.invert = function(x, y) { + var ρ0_y = G - y; + return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + }; + return forward; } - var d3_hslPrototype = d3_hsl.prototype = new d3_color(); - d3_hslPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, this.l / k); - }; - d3_hslPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, k * this.l); + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; + } + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; }; - d3_hslPrototype.rgb = function() { - return d3_hsl_rgb(this.h, this.s, this.l); + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = π * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; + } + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(ρ) { + return 2 * Math.atan(ρ); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; + } + d3_geo_transverseMercator.invert = function(x, y) { + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; }; - function d3_hsl_rgb(h, s, l) { - var m1, m2; - h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; - s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; - l = l < 0 ? 0 : l > 1 ? 1 : l; - m2 = l <= .5 ? l * (1 + s) : l + s - l * s; - m1 = 2 * l - m2; - function v(h) { - if (h > 360) h -= 360; else if (h < 0) h += 360; - if (h < 60) return m1 + (m2 - m1) * h / 60; - if (h < 180) return m2; - if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; - return m1; + (d3.geo.transverseMercator = function() { + var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; + projection.center = function(_) { + return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + }; + projection.rotate = function(_) { + return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), + [ _[0], _[1], _[2] - 90 ]); + }; + return rotate([ 0, 0, 90 ]); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; + for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); + return polygon; } - function vv(h) { - return Math.round(v(h) * 255); + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [ 0, 1 ], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; } - return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + return hull.slice(0, hs); } - d3.hcl = d3_hcl; - function d3_hcl(h, c, l) { - return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; } - var d3_hclPrototype = d3_hcl.prototype = new d3_color(); - d3_hclPrototype.brighter = function(k) { - return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; }; - d3_hclPrototype.darker = function(k) { - return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; }; - d3_hclPrototype.rgb = function() { - return d3_hcl_lab(this.h, this.c, this.l).rgb(); + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; }; - function d3_hcl_lab(h, c, l) { - if (isNaN(h)) h = 0; - if (isNaN(c)) c = 0; - return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); } - d3.lab = d3_lab; - function d3_lab(l, a, b) { - return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; } - var d3_lab_K = 18; - var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; - var d3_labPrototype = d3_lab.prototype = new d3_color(); - d3_labPrototype.brighter = function(k) { - return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.darker = function(k) { - return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.rgb = function() { - return d3_lab_rgb(this.l, this.a, this.b); - }; - function d3_lab_rgb(l, a, b) { - var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; - x = d3_lab_xyz(x) * d3_lab_X; - y = d3_lab_xyz(y) * d3_lab_Y; - z = d3_lab_xyz(z) * d3_lab_Z; - return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); } - function d3_lab_hcl(l, a, b) { - return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; } - function d3_lab_xyz(x) { - return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; } - function d3_xyz_lab(x) { - return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); } - function d3_xyz_rgb(r) { - return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); } - d3.rgb = d3_rgb; - function d3_rgb(r, g, b) { - return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); } - function d3_rgbNumber(value) { - return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; } - function d3_rgbString(value) { - return d3_rgbNumber(value) + ""; + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; } - var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); - d3_rgbPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - var r = this.r, g = this.g, b = this.b, i = 30; - if (!r && !g && !b) return new d3_rgb(i, i, i); - if (r && r < i) r = i; - if (g && g < i) g = i; - if (b && b < i) b = i; - return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); - }; - d3_rgbPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_rgb(k * this.r, k * this.g, k * this.b); - }; - d3_rgbPrototype.hsl = function() { - return d3_rgb_hsl(this.r, this.g, this.b); - }; - d3_rgbPrototype.toString = function() { - return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); - }; - function d3_rgb_hex(v) { - return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; } - function d3_rgb_parse(format, rgb, hsl) { - var r = 0, g = 0, b = 0, m1, m2, color; - m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); - if (m1) { - m2 = m1[2].split(","); - switch (m1[1]) { - case "hsl": - { - return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); - } - - case "rgb": - { - return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; } } } - if (color = d3_rgb_names.get(format)) { - return rgb(color.r, color.g, color.b); - } - if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { - if (format.length === 4) { - r = (color & 3840) >> 4; - r = r >> 4 | r; - g = color & 240; - g = g >> 4 | g; - b = color & 15; - b = b << 4 | b; - } else if (format.length === 7) { - r = (color & 16711680) >> 16; - g = (color & 65280) >> 8; - b = color & 255; + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } } } - return rgb(r, g, b); + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; } - function d3_rgb_hsl(r, g, b) { - var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; - if (d) { - s = l < .5 ? d / (max + min) : d / (2 - max - min); - if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; - h *= 60; - } else { - h = NaN; - s = l > 0 && l < 1 ? 0 : h; + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; } - return new d3_hsl(h, s, l); - } - function d3_rgb_lab(r, g, b) { - r = d3_rgb_xyz(r); - g = d3_rgb_xyz(g); - b = d3_rgb_xyz(b); - var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); - return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); - } - function d3_rgb_xyz(r) { - return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); - } - function d3_rgb_parseNumber(c) { - var f = parseFloat(c); - return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; - } - var d3_rgb_names = d3.map({ - aliceblue: 15792383, - antiquewhite: 16444375, - aqua: 65535, - aquamarine: 8388564, - azure: 15794175, - beige: 16119260, - bisque: 16770244, - black: 0, - blanchedalmond: 16772045, - blue: 255, - blueviolet: 9055202, - brown: 10824234, - burlywood: 14596231, - cadetblue: 6266528, - chartreuse: 8388352, - chocolate: 13789470, - coral: 16744272, - cornflowerblue: 6591981, - cornsilk: 16775388, - crimson: 14423100, - cyan: 65535, - darkblue: 139, - darkcyan: 35723, - darkgoldenrod: 12092939, - darkgray: 11119017, - darkgreen: 25600, - darkgrey: 11119017, - darkkhaki: 12433259, - darkmagenta: 9109643, - darkolivegreen: 5597999, - darkorange: 16747520, - darkorchid: 10040012, - darkred: 9109504, - darksalmon: 15308410, - darkseagreen: 9419919, - darkslateblue: 4734347, - darkslategray: 3100495, - darkslategrey: 3100495, - darkturquoise: 52945, - darkviolet: 9699539, - deeppink: 16716947, - deepskyblue: 49151, - dimgray: 6908265, - dimgrey: 6908265, - dodgerblue: 2003199, - firebrick: 11674146, - floralwhite: 16775920, - forestgreen: 2263842, - fuchsia: 16711935, - gainsboro: 14474460, - ghostwhite: 16316671, - gold: 16766720, - goldenrod: 14329120, - gray: 8421504, - green: 32768, - greenyellow: 11403055, - grey: 8421504, - honeydew: 15794160, - hotpink: 16738740, - indianred: 13458524, - indigo: 4915330, - ivory: 16777200, - khaki: 15787660, - lavender: 15132410, - lavenderblush: 16773365, - lawngreen: 8190976, - lemonchiffon: 16775885, - lightblue: 11393254, - lightcoral: 15761536, - lightcyan: 14745599, - lightgoldenrodyellow: 16448210, - lightgray: 13882323, - lightgreen: 9498256, - lightgrey: 13882323, - lightpink: 16758465, - lightsalmon: 16752762, - lightseagreen: 2142890, - lightskyblue: 8900346, - lightslategray: 7833753, - lightslategrey: 7833753, - lightsteelblue: 11584734, - lightyellow: 16777184, - lime: 65280, - limegreen: 3329330, - linen: 16445670, - magenta: 16711935, - maroon: 8388608, - mediumaquamarine: 6737322, - mediumblue: 205, - mediumorchid: 12211667, - mediumpurple: 9662683, - mediumseagreen: 3978097, - mediumslateblue: 8087790, - mediumspringgreen: 64154, - mediumturquoise: 4772300, - mediumvioletred: 13047173, - midnightblue: 1644912, - mintcream: 16121850, - mistyrose: 16770273, - moccasin: 16770229, - navajowhite: 16768685, - navy: 128, - oldlace: 16643558, - olive: 8421376, - olivedrab: 7048739, - orange: 16753920, - orangered: 16729344, - orchid: 14315734, - palegoldenrod: 15657130, - palegreen: 10025880, - paleturquoise: 11529966, - palevioletred: 14381203, - papayawhip: 16773077, - peachpuff: 16767673, - peru: 13468991, - pink: 16761035, - plum: 14524637, - powderblue: 11591910, - purple: 8388736, - rebeccapurple: 6697881, - red: 16711680, - rosybrown: 12357519, - royalblue: 4286945, - saddlebrown: 9127187, - salmon: 16416882, - sandybrown: 16032864, - seagreen: 3050327, - seashell: 16774638, - sienna: 10506797, - silver: 12632256, - skyblue: 8900331, - slateblue: 6970061, - slategray: 7372944, - slategrey: 7372944, - snow: 16775930, - springgreen: 65407, - steelblue: 4620980, - tan: 13808780, - teal: 32896, - thistle: 14204888, - tomato: 16737095, - turquoise: 4251856, - violet: 15631086, - wheat: 16113331, - white: 16777215, - whitesmoke: 16119285, - yellow: 16776960, - yellowgreen: 10145074 - }); - d3_rgb_names.forEach(function(key, value) { - d3_rgb_names.set(key, d3_rgbNumber(value)); - }); - function d3_functor(v) { - return typeof v === "function" ? v : function() { - return v; - }; } - d3.functor = d3_functor; - d3.xhr = d3_xhrType(d3_identity); - function d3_xhrType(response) { - return function(url, mimeType, callback) { - if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, - mimeType = null; - return d3_xhr(url, mimeType, response, callback); - }; + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } } - function d3_xhr(url, mimeType, response, callback) { - var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; - if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); - "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { - request.readyState > 3 && respond(); - }; - function respond() { - var status = request.status, result; - if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { - try { - result = response.call(xhr, request); - } catch (e) { - dispatch.error.call(xhr, e); - return; + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; } - dispatch.load.call(xhr, result); } else { - dispatch.error.call(xhr, request); + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } } } - request.onprogress = function(event) { - var o = d3.event; - d3.event = event; - try { - dispatch.progress.call(xhr, request); - } finally { - d3.event = o; - } - }; - xhr.header = function(name, value) { - name = (name + "").toLowerCase(); - if (arguments.length < 2) return headers[name]; - if (value == null) delete headers[name]; else headers[name] = value + ""; - return xhr; - }; - xhr.mimeType = function(value) { - if (!arguments.length) return mimeType; - mimeType = value == null ? null : value + ""; - return xhr; - }; - xhr.responseType = function(value) { - if (!arguments.length) return responseType; - responseType = value; - return xhr; - }; - xhr.response = function(value) { - response = value; - return xhr; - }; - [ "get", "post" ].forEach(function(method) { - xhr[method] = function() { - return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); - }; - }); - xhr.send = function(method, data, callback) { - if (arguments.length === 2 && typeof data === "function") callback = data, data = null; - request.open(method, url, true); - if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; - if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); - if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); - if (responseType != null) request.responseType = responseType; - if (callback != null) xhr.on("error", callback).on("load", function(request) { - callback(null, request); - }); - dispatch.beforesend.call(xhr, request); - request.send(data == null ? null : data); - return xhr; - }; - xhr.abort = function() { - request.abort(); - return xhr; - }; - d3.rebind(xhr, dispatch, "on"); - return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + edge.a = va; + edge.b = vb; + return true; } - function d3_xhr_fixCallback(callback) { - return callback.length === 1 ? function(error, request) { - callback(error == null ? request : null); - } : callback; + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; } - function d3_xhrHasResponse(request) { - var type = request.responseType; - return type && type !== "text" ? request.response : request.responseText; + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; } - d3.dsv = function(delimiter, mimeType) { - var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); - function dsv(url, row, callback) { - if (arguments.length < 3) callback = row, row = null; - var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); - xhr.row = function(_) { - return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; - }; - return xhr; - } - function response(request) { - return dsv.parse(request.responseText); + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; } - function typedResponse(f) { - return function(request) { - return dsv.parse(request.responseText, f); - }; + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; } - dsv.parse = function(text, f) { - var o; - return dsv.parseRows(text, function(row, i) { - if (o) return o(row, i - 1); - var a = new Function("d", "return {" + row.map(function(name, i) { - return JSON.stringify(name) + ": d[" + i + "]"; - }).join(",") + "}"); - o = f ? function(row, i) { - return f(a(row), i); - } : a; - }); - }; - dsv.parseRows = function(text, f) { - var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; - function token() { - if (I >= N) return EOF; - if (eol) return eol = false, EOL; - var j = I; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); } - I = i + 2; - var c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); } - return text.slice(j + 1, i).replace(/""/g, '"'); - } - while (I < N) { - var c = text.charCodeAt(I++), k = 1; - if (c === 10) eol = true; else if (c === 13) { - eol = true; - if (text.charCodeAt(I) === 10) ++I, ++k; - } else if (c !== delimiterCode) continue; - return text.slice(j, I - k); } - return text.slice(j); + parent = after.U; } - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; } - if (f && (a = f(a, n++)) == null) continue; - rows.push(a); + } else { + red = node.C; + node = next; } - return rows; - }; - dsv.format = function(rows) { - if (Array.isArray(rows[0])) return dsv.formatRows(rows); - var fieldSet = new d3_Set(), fields = []; - rows.forEach(function(row) { - for (var field in row) { - if (!fieldSet.has(field)) { - fields.push(fieldSet.add(field)); + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; } } - }); - return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { - return fields.map(function(field) { - return formatValue(row[field]); - }).join(delimiter); - })).join("\n"); - }; - dsv.formatRows = function(rows) { - return rows.map(formatRow).join("\n"); - }; - function formatRow(row) { - return row.map(formatValue).join(delimiter); - } - function formatValue(text) { - return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; } - return dsv; - }; - d3.csv = d3.dsv(",", "text/csv"); - d3.tsv = d3.dsv(" ", "text/tab-separated-values"); - var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { - setTimeout(callback, 17); }; - d3.timer = function() { - d3_timer.apply(this, arguments); - }; - function d3_timer(callback, delay, then) { - var n = arguments.length; - if (n < 2) delay = 0; - if (n < 3) then = Date.now(); - var time = then + delay, timer = { - c: callback, - t: time, - n: null - }; - if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; - d3_timer_queueTail = timer; - if (!d3_timer_interval) { - d3_timer_timeout = clearTimeout(d3_timer_timeout); - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; } - return timer; + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; } - function d3_timer_step() { - var now = d3_timer_mark(), delay = d3_timer_sweep() - now; - if (delay > 24) { - if (isFinite(delay)) { - clearTimeout(d3_timer_timeout); - d3_timer_timeout = setTimeout(d3_timer_step, delay); - } - d3_timer_interval = 0; + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; } else { - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); + tree._ = q; } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; } - d3.timer.flush = function() { - d3_timer_mark(); - d3_timer_sweep(); - }; - function d3_timer_mark() { - var now = Date.now(), timer = d3_timer_queueHead; - while (timer) { - if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; - timer = timer.n; - } - return now; + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; } - function d3_timer_sweep() { - var t0, t1 = d3_timer_queueHead, time = Infinity; - while (t1) { - if (t1.c) { - if (t1.t < time) time = t1.t; - t1 = (t0 = t1).n; + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); } else { - t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + break; } } - d3_timer_queueTail = t0; - return time; + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; } - function d3_format_precision(x, p) { - return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; } - d3.round = function(x, n) { - return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); - }; - var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); - d3.formatPrefix = function(value, precision) { - var i = 0; - if (value = +value) { - if (value < 0) value *= -1; - if (precision) value = d3.round(value, d3_format_precision(value, precision)); - i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); - i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; } - return d3_formatPrefixes[8 + i / 3]; - }; - function d3_formatPrefix(d, i) { - var k = Math.pow(10, abs(8 - i) * 3); - return { - scale: i > 8 ? function(d) { - return d / k; - } : function(d) { - return d * k; - }, - symbol: d + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); }; - } - function d3_locale_numberFormat(locale) { - var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { - var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; - while (i > 0 && g > 0) { - if (length + g + 1 > width) g = Math.max(1, width - length); - t.push(value.substring(i -= g, i + g)); - if ((length += g + 1) > width) break; - g = locale_grouping[j = (j + 1) % locale_grouping.length]; - } - return t.reverse().join(locale_thousands); - } : d3_identity; - return function(specifier) { - var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; - if (precision) precision = +precision.substring(1); - if (zfill || fill === "0" && align === "=") { - zfill = fill = "0"; - align = "="; - } - switch (type) { - case "n": - comma = true; - type = "g"; - break; - - case "%": - scale = 100; - suffix = "%"; - type = "f"; - break; - - case "p": - scale = 100; - suffix = "%"; - type = "r"; - break; - - case "b": - case "o": - case "x": - case "X": - if (symbol === "#") prefix = "0" + type.toLowerCase(); - - case "c": - exponent = false; - - case "d": - integer = true; - precision = 0; - break; - - case "s": - scale = -1; - type = "r"; - break; - } - if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; - if (type == "r" && !precision) type = "g"; - if (precision != null) { - if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); - } - type = d3_format_types.get(type) || d3_format_typeDefault; - var zcomma = zfill && comma; - return function(value) { - var fullSuffix = suffix; - if (integer && value % 1) return ""; - var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; - if (scale < 0) { - var unit = d3.formatPrefix(value, precision); - value = unit.scale(value); - fullSuffix = unit.symbol + suffix; - } else { - value *= scale; - } - value = type(value, precision); - var i = value.lastIndexOf("."), before, after; - if (i < 0) { - var j = exponent ? value.lastIndexOf("e") : -1; - if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); - } else { - before = value.substring(0, i); - after = locale_decimal + value.substring(i + 1); + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } } - if (!zfill && comma) before = formatGroup(before, Infinity); - var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; - if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); - negative += prefix; - value = before + after; - return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; - }; + }); + return triangles; }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); } - var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; - var d3_format_types = d3.map({ - b: function(x) { - return x.toString(2); - }, - c: function(x) { - return String.fromCharCode(x); - }, - o: function(x) { - return x.toString(8); - }, - x: function(x) { - return x.toString(16); - }, - X: function(x) { - return x.toString(16).toUpperCase(); - }, - g: function(x, p) { - return x.toPrecision(p); - }, - e: function(x, p) { - return x.toExponential(p); - }, - f: function(x, p) { - return x.toFixed(p); - }, - r: function(x, p) { - return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); - } - }); - function d3_format_typeDefault(x) { - return x + ""; - } - var d3_time = d3.time = {}, d3_date = Date; - function d3_date_utc() { - this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); - } - d3_date_utc.prototype = { - getDate: function() { - return this._.getUTCDate(); - }, - getDay: function() { - return this._.getUTCDay(); - }, - getFullYear: function() { - return this._.getUTCFullYear(); - }, - getHours: function() { - return this._.getUTCHours(); - }, - getMilliseconds: function() { - return this._.getUTCMilliseconds(); - }, - getMinutes: function() { - return this._.getUTCMinutes(); - }, - getMonth: function() { - return this._.getUTCMonth(); - }, - getSeconds: function() { - return this._.getUTCSeconds(); - }, - getTime: function() { - return this._.getTime(); - }, - getTimezoneOffset: function() { - return 0; - }, - valueOf: function() { - return this._.valueOf(); - }, - setDate: function() { - d3_time_prototype.setUTCDate.apply(this._, arguments); - }, - setDay: function() { - d3_time_prototype.setUTCDay.apply(this._, arguments); - }, - setFullYear: function() { - d3_time_prototype.setUTCFullYear.apply(this._, arguments); - }, - setHours: function() { - d3_time_prototype.setUTCHours.apply(this._, arguments); - }, - setMilliseconds: function() { - d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); - }, - setMinutes: function() { - d3_time_prototype.setUTCMinutes.apply(this._, arguments); - }, - setMonth: function() { - d3_time_prototype.setUTCMonth.apply(this._, arguments); - }, - setSeconds: function() { - d3_time_prototype.setUTCSeconds.apply(this._, arguments); - }, - setTime: function() { - d3_time_prototype.setTime.apply(this._, arguments); - } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); }; - var d3_time_prototype = Date.prototype; - function d3_time_interval(local, step, number) { - function round(date) { - var d0 = local(date), d1 = offset(d0, 1); - return date - d0 < d1 - date ? d0 : d1; - } - function ceil(date) { - step(date = local(new d3_date(date - 1)), 1); - return date; - } - function offset(date, k) { - step(date = new d3_date(+date), k); - return date; - } - function range(t0, t1, dt) { - var time = ceil(t0), times = []; - if (dt > 1) { - while (time < t1) { - if (!(number(time) % dt)) times.push(new Date(+time)); - step(time, 1); - } - } else { - while (time < t1) times.push(new Date(+time)), step(time, 1); - } - return times; - } - function range_utc(t0, t1, dt) { - try { - d3_date = d3_date_utc; - var utc = new d3_date_utc(); - utc._ = t0; - return range(utc, t1, dt); - } finally { - d3_date = Date; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; } + return quadtree(points); } - local.floor = local; - local.round = round; - local.ceil = ceil; - local.offset = offset; - local.range = range; - var utc = local.utc = d3_time_interval_utc(local); - utc.floor = utc; - utc.round = d3_time_interval_utc(round); - utc.ceil = d3_time_interval_utc(ceil); - utc.offset = d3_time_interval_utc(offset); - utc.range = range_utc; - return local; - } - function d3_time_interval_utc(method) { - return function(date, k) { - try { - d3_date = d3_date_utc; - var utc = new d3_date_utc(); - utc._ = date; - return method(utc, k)._; - } finally { - d3_date = Date; + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } } - }; - } - d3_time.year = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setMonth(0, 1); - return date; - }, function(date, offset) { - date.setFullYear(date.getFullYear() + offset); - }, function(date) { - return date.getFullYear(); - }); - d3_time.years = d3_time.year.range; - d3_time.years.utc = d3_time.year.utc.range; - d3_time.day = d3_time_interval(function(date) { - var day = new d3_date(2e3, 0); - day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); - return day; - }, function(date, offset) { - date.setDate(date.getDate() + offset); - }, function(date) { - return date.getDate() - 1; - }); - d3_time.days = d3_time.day.range; - d3_time.days.utc = d3_time.day.utc.range; - d3_time.dayOfYear = function(date) { - var year = d3_time.year(date); - return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); - }; - [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { - i = 7 - i; - var interval = d3_time[day] = d3_time_interval(function(date) { - (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); - return date; - }, function(date, offset) { - date.setDate(date.getDate() + Math.floor(offset) * 7); - }, function(date) { - var day = d3_time.year(date).getDay(); - return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); - }); - d3_time[day + "s"] = interval.range; - d3_time[day + "s"].utc = interval.utc.range; - d3_time[day + "OfYear"] = function(date) { - var day = d3_time.year(date).getDay(); - return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); - }; - }); - d3_time.week = d3_time.sunday; - d3_time.weeks = d3_time.sunday.range; - d3_time.weeks.utc = d3_time.sunday.utc.range; - d3_time.weekOfYear = d3_time.sundayOfYear; - function d3_locale_timeFormat(locale) { - var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; - function d3_time_format(template) { - var n = template.length; - function format(date) { - var string = [], i = -1, j = 0, c, p, f; - while (++i < n) { - if (template.charCodeAt(i) === 37) { - string.push(template.slice(j, i)); - if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); - if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); - string.push(c); - j = i + 1; + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); } - string.push(template.slice(j, i)); - return string.join(""); } - format.parse = function(string) { - var d = { - y: 1900, - m: 0, - d: 1, - H: 0, - M: 0, - S: 0, - L: 0, - Z: null - }, i = d3_time_parse(d, template, string, 0); - if (i != string.length) return null; - if ("p" in d) d.H = d.H % 12 + d.p * 12; - var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); - if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { - if (!("w" in d)) d.w = "W" in d ? 1 : 0; - date.setFullYear(d.y, 0, 1); - date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); - } else date.setFullYear(d.y, d.m, d.d); - date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); - return localZ ? date._ : date; + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = xm; else x2 = xm; + if (below) y1 = ym; else y2 = ym; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); }; - format.toString = function() { - return template; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); }; - return format; - } - function d3_time_parse(date, template, string, j) { - var c, p, t, i = 0, n = template.length, m = string.length; - while (i < n) { - if (j >= m) return -1; - c = template.charCodeAt(i++); - if (c === 37) { - t = template.charAt(i++); - p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; - if (!p || (j = p(date, string, j)) < 0) return -1; - } else if (c != string.charCodeAt(j++)) { - return -1; + root.find = function(point) { + return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); } - } - return j; + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; } - d3_time_format.utc = function(template) { - var local = d3_time_format(template); - function format(date) { - try { - d3_date = d3_date_utc; - var utc = new d3_date(); - utc._ = date; - return local(utc); - } finally { - d3_date = Date; + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { + var minDistance2 = Infinity, closestPoint; + (function find(node, x1, y1, x2, y2) { + if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; + if (point = node.point) { + var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; + if (distance2 < minDistance2) { + var distance = Math.sqrt(minDistance2 = distance2); + x0 = x - distance, y0 = y - distance; + x3 = x + distance, y3 = y + distance; + closestPoint = point; } } - format.parse = function(string) { - try { - d3_date = d3_date_utc; - var date = local.parse(string); - return date && date._; - } finally { - d3_date = Date; + var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; + for (var i = below << 1 | right, j = i + 4; i < j; ++i) { + if (node = children[i & 3]) switch (i & 3) { + case 0: + find(node, x1, y1, xm, ym); + break; + + case 1: + find(node, xm, y1, x2, ym); + break; + + case 2: + find(node, x1, ym, xm, y2); + break; + + case 3: + find(node, xm, ym, x2, y2); + break; } - }; - format.toString = local.toString; - return format; - }; - d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; - var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); - locale_periods.forEach(function(p, i) { - d3_time_periodLookup.set(p.toLowerCase(), i); - }); - var d3_time_formats = { - a: function(d) { - return locale_shortDays[d.getDay()]; - }, - A: function(d) { - return locale_days[d.getDay()]; - }, - b: function(d) { - return locale_shortMonths[d.getMonth()]; - }, - B: function(d) { - return locale_months[d.getMonth()]; - }, - c: d3_time_format(locale_dateTime), - d: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - e: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - H: function(d, p) { - return d3_time_formatPad(d.getHours(), p, 2); - }, - I: function(d, p) { - return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); - }, - j: function(d, p) { - return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); - }, - L: function(d, p) { - return d3_time_formatPad(d.getMilliseconds(), p, 3); - }, - m: function(d, p) { - return d3_time_formatPad(d.getMonth() + 1, p, 2); - }, - M: function(d, p) { - return d3_time_formatPad(d.getMinutes(), p, 2); - }, - p: function(d) { - return locale_periods[+(d.getHours() >= 12)]; - }, - S: function(d, p) { - return d3_time_formatPad(d.getSeconds(), p, 2); - }, - U: function(d, p) { - return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); - }, - w: function(d) { - return d.getDay(); - }, - W: function(d, p) { - return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); - }, - x: d3_time_format(locale_date), - X: d3_time_format(locale_time), - y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 100, p, 2); - }, - Y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); - }, - Z: d3_time_zone, - "%": function() { - return "%"; } + })(root, x0, y0, x3, y3); + return closestPoint; + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; - var d3_time_parsers = { - a: d3_time_parseWeekdayAbbrev, - A: d3_time_parseWeekday, - b: d3_time_parseMonthAbbrev, - B: d3_time_parseMonth, - c: d3_time_parseLocaleFull, - d: d3_time_parseDay, - e: d3_time_parseDay, - H: d3_time_parseHour24, - I: d3_time_parseHour24, - j: d3_time_parseDayOfYear, - L: d3_time_parseMilliseconds, - m: d3_time_parseMonthNumber, - M: d3_time_parseMinutes, - p: d3_time_parseAmPm, - S: d3_time_parseSeconds, - U: d3_time_parseWeekNumberSunday, - w: d3_time_parseWeekdayNumber, - W: d3_time_parseWeekNumberMonday, - x: d3_time_parseLocaleDate, - X: d3_time_parseLocaleTime, - y: d3_time_parseYear, - Y: d3_time_parseFullYear, - Z: d3_time_parseZone, - "%": d3_time_parseLiteralPercent - }; - function d3_time_parseWeekdayAbbrev(date, string, i) { - d3_time_dayAbbrevRe.lastIndex = 0; - var n = d3_time_dayAbbrevRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseWeekday(date, string, i) { - d3_time_dayRe.lastIndex = 0; - var n = d3_time_dayRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonthAbbrev(date, string, i) { - d3_time_monthAbbrevRe.lastIndex = 0; - var n = d3_time_monthAbbrevRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonth(date, string, i) { - d3_time_monthRe.lastIndex = 0; - var n = d3_time_monthRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseLocaleFull(date, string, i) { - return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } } - function d3_time_parseLocaleDate(date, string, i) { - return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } } - function d3_time_parseLocaleTime(date, string, i) { - return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + a = +a, b = +b; + return function(t) { + return a * (1 - t) + b * t; + }; + } + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; else s[++i] = bm; + } else { + s[++i] = null; + q.push({ + i: i, + x: d3_interpolateNumber(am, bm) + }); + } + bi = d3_interpolate_numberB.lastIndex; } - function d3_time_parseAmPm(date, string, i) { - var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); - return n == null ? -1 : (date.p = n, i); + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; else s[++i] = bs; } - return d3_time_format; - } - var d3_time_formatPads = { - "-": "", - _: " ", - "0": "0" - }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; - function d3_time_formatPad(value, fill, width) { - var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; - return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); - } - function d3_time_formatRe(names) { - return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { + return b(t) + ""; + }) : function() { + return b; + } : (b = q.length, function(t) { + for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }); } - function d3_time_formatLookup(names) { - var map = new d3_Map(), i = -1, n = names.length; - while (++i < n) map.set(names[i].toLowerCase(), i); - return map; + var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; } - function d3_time_parseWeekdayNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 1)); - return n ? (date.w = +n[0], i + n[0].length) : -1; + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; } - function d3_time_parseWeekNumberSunday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.U = +n[0], i + n[0].length) : -1; + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; } - function d3_time_parseWeekNumberMonday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.W = +n[0], i + n[0].length) : -1; + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; } - function d3_time_parseFullYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 4)); - return n ? (date.y = +n[0], i + n[0].length) : -1; + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; } - function d3_time_parseYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + function d3_ease_quad(t) { + return t * t; } - function d3_time_parseZone(date, string, i) { - return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, - i + 5) : -1; + function d3_ease_cubic(t) { + return t * t * t; } - function d3_time_expandYear(d) { - return d + (d > 68 ? 1900 : 2e3); + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); } - function d3_time_parseMonthNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; } - function d3_time_parseDay(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.d = +n[0], i + n[0].length) : -1; + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); } - function d3_time_parseDayOfYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.j = +n[0], i + n[0].length) : -1; + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); } - function d3_time_parseHour24(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.H = +n[0], i + n[0].length) : -1; + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); } - function d3_time_parseMinutes(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.M = +n[0], i + n[0].length) : -1; + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; } - function d3_time_parseSeconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.S = +n[0], i + n[0].length) : -1; + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; } - function d3_time_parseMilliseconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.L = +n[0], i + n[0].length) : -1; + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } - function d3_time_zone(d) { - var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; - return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; } - function d3_time_parseLiteralPercent(date, string, i) { - d3_time_percentRe.lastIndex = 0; - var n = d3_time_percentRe.exec(string.slice(i, i + 1)); - return n ? i + n[0].length : -1; + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; } - function d3_time_formatMulti(formats) { - var n = formats.length, i = -1; - while (++i < n) formats[i][0] = this(formats[i][0]); - return function(date) { - var i = 0, f = formats[i]; - while (!f[1](date)) f = formats[++i]; - return f[0](date); + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; }; } - d3.locale = function(locale) { - return { - numberFormat: d3_locale_numberFormat(locale), - timeFormat: d3_locale_timeFormat(locale) + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); }; - }; - var d3_locale_enUS = d3.locale({ - decimal: ".", - thousands: ",", - grouping: [ 3 ], - currency: [ "$", "" ], - dateTime: "%a %b %e %X %Y", - date: "%m/%d/%Y", - time: "%H:%M:%S", - periods: [ "AM", "PM" ], - days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], - shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], - months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], - shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] - }); - d3.format = d3_locale_enUS.numberFormat; - d3.geo = {}; - function d3_adder() {} - d3_adder.prototype = { - s: 0, - t: 0, - add: function(y) { - d3_adderSum(y, this.t, d3_adderTemp); - d3_adderSum(d3_adderTemp.s, this.s, this); - if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; - }, - reset: function() { - this.s = this.t = 0; - }, - valueOf: function() { - return this.s; - } - }; - var d3_adderTemp = new d3_adder(); - function d3_adderSum(a, b, o) { - var x = o.s = a + b, bv = x - a, av = x - bv; - o.t = a - av + (b - bv); } - d3.geo.stream = function(object, listener) { - if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { - d3_geo_streamObjectType[object.type](object, listener); - } else { - d3_geo_streamGeometry(object, listener); - } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); }; - function d3_geo_streamGeometry(geometry, listener) { - if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { - d3_geo_streamGeometryType[geometry.type](geometry, listener); + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; } - var d3_geo_streamObjectType = { - Feature: function(feature, listener) { - d3_geo_streamGeometry(feature.geometry, listener); - }, - FeatureCollection: function(object, listener) { - var features = object.features, i = -1, n = features.length; - while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); - } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; }; - var d3_geo_streamGeometryType = { - Sphere: function(object, listener) { - listener.sphere(); - }, - Point: function(object, listener) { - object = object.coordinates; - listener.point(object[0], object[1], object[2]); - }, - MultiPoint: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); - }, - LineString: function(object, listener) { - d3_geo_streamLine(object.coordinates, listener, 0); - }, - MultiLineString: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); - }, - Polygon: function(object, listener) { - d3_geo_streamPolygon(object.coordinates, listener); - }, - MultiPolygon: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); - }, - GeometryCollection: function(object, listener) { - var geometries = object.geometries, i = -1, n = geometries.length; - while (++i < n) d3_geo_streamGeometry(geometries[i], listener); + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; } - }; - function d3_geo_streamLine(coordinates, listener, closed) { - var i = -1, n = coordinates.length - closed, coordinate; - listener.lineStart(); - while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); - listener.lineEnd(); + return k; } - function d3_geo_streamPolygon(coordinates, listener) { - var i = -1, n = coordinates.length; - listener.polygonStart(); - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); - listener.polygonEnd(); + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; } - d3.geo.area = function(object) { - d3_geo_areaSum = 0; - d3.geo.stream(object, d3_geo_area); - return d3_geo_areaSum; + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 }; - var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); - var d3_geo_area = { - sphere: function() { - d3_geo_areaSum += 4 * π; - }, - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_areaRingSum.reset(); - d3_geo_area.lineStart = d3_geo_areaRingStart; - }, - polygonEnd: function() { - var area = 2 * d3_geo_areaRingSum; - d3_geo_areaSum += area < 0 ? 4 * π + area : area; - d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + d3.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransformPop(s) { + return s.length ? s.pop() + "," : ""; + } + function d3_interpolateTranslate(ta, tb, s, q) { + if (ta[0] !== tb[0] || ta[1] !== tb[1]) { + var i = s.push("translate(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); } - }; - function d3_geo_areaRingStart() { - var λ00, φ00, λ0, cosφ0, sinφ0; - d3_geo_area.point = function(λ, φ) { - d3_geo_area.point = nextPoint; - λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), - sinφ0 = Math.sin(φ); - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - φ = φ * d3_radians / 2 + π / 4; - var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); - d3_geo_areaRingSum.add(Math.atan2(v, u)); - λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + function d3_interpolateRotate(ra, rb, s, q) { + if (ra !== rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); } - d3_geo_area.lineEnd = function() { - nextPoint(λ00, φ00); - }; } - function d3_geo_cartesian(spherical) { - var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); - return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + function d3_interpolateSkew(wa, wb, s, q) { + if (wa !== wb) { + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + } } - function d3_geo_cartesianDot(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + function d3_interpolateScale(ka, kb, s, q) { + if (ka[0] !== kb[0] || ka[1] !== kb[1]) { + var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] !== 1 || kb[1] !== 1) { + s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + } } - function d3_geo_cartesianCross(a, b) { - return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + function d3_interpolateTransform(a, b) { + var s = [], q = []; + a = d3.transform(a), b = d3.transform(b); + d3_interpolateTranslate(a.translate, b.translate, s, q); + d3_interpolateRotate(a.rotate, b.rotate, s, q); + d3_interpolateSkew(a.skew, b.skew, s, q); + d3_interpolateScale(a.scale, b.scale, s, q); + a = b = null; + return function(t) { + var i = -1, n = q.length, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; } - function d3_geo_cartesianAdd(a, b) { - a[0] += b[0]; - a[1] += b[1]; - a[2] += b[2]; + function d3_uninterpolateNumber(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return (x - a) / b; + }; } - function d3_geo_cartesianScale(vector, k) { - return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + function d3_uninterpolateClamp(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return Math.max(0, Math.min(1, (x - a) / b)); + }; } - function d3_geo_cartesianNormalize(d) { - var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); - d[0] /= l; - d[1] /= l; - d[2] /= l; + d3.layout = {}; + d3.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; } - function d3_geo_spherical(cartesian) { - return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; } - function d3_geo_sphericalEqual(a, b) { - return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; } - d3.geo.bounds = function() { - var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; - var bound = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - bound.point = ringPoint; - bound.lineStart = ringStart; - bound.lineEnd = ringEnd; - dλSum = 0; - d3_geo_area.polygonStart(); - }, - polygonEnd: function() { - d3_geo_area.polygonEnd(); - bound.point = point; - bound.lineStart = lineStart; - bound.lineEnd = lineEnd; - if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; - range[0] = λ0, range[1] = λ1; + d3.layout.chord = function() { + var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d3.range(n)); + k += x; } - }; - function point(λ, φ) { - ranges.push(range = [ λ0 = λ, λ1 = λ ]); - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; - } - function linePoint(λ, φ) { - var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); - if (p0) { - var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); - d3_geo_cartesianNormalize(inflection); - inflection = d3_geo_spherical(inflection); - var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; - if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = inflection[1] * d3_degrees; - if (φi > φ1) φ1 = φi; - } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = -inflection[1] * d3_degrees; - if (φi < φ0) φ0 = φi; - } else { - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i) { + d.sort(function(a, b) { + return sortSubgroups(matrix[i][a], matrix[i][b]); + }); + }); + } + k = (τ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; } - if (antimeridian) { - if (λ < λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; - } - } else { - if (λ1 >= λ0) { - if (λ < λ0) λ0 = λ; - if (λ > λ1) λ1 = λ; - } else { - if (λ > λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; - } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: groupSums[di] + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source: source, + target: target + }); } } - } else { - point(λ, φ); } - p0 = p, λ_ = λ; - } - function lineStart() { - bound.point = linePoint; - } - function lineEnd() { - range[0] = λ0, range[1] = λ1; - bound.point = point; - p0 = null; - } - function ringPoint(λ, φ) { - if (p0) { - var dλ = λ - λ_; - dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; - } else λ__ = λ, φ__ = φ; - d3_geo_area.point(λ, φ); - linePoint(λ, φ); - } - function ringStart() { - d3_geo_area.lineStart(); - } - function ringEnd() { - ringPoint(λ__, φ__); - d3_geo_area.lineEnd(); - if (abs(dλSum) > ε) λ0 = -(λ1 = 180); - range[0] = λ0, range[1] = λ1; - p0 = null; - } - function angle(λ0, λ1) { - return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + if (sortChords) resort(); } - function compareRanges(a, b) { - return a[0] - b[0]; + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); } - function withinRange(x, range) { - return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + chord.matrix = function(x) { + if (!arguments.length) return matrix; + n = (matrix = x) && matrix.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d3.layout.force = function() { + var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad, x1, _, x2) { + if (quad.point !== node) { + var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; + if (dw * dw / theta2 < dn) { + if (dn < chargeDistance2) { + var k = quad.charge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + return true; + } + if (quad.point && dn && dn < chargeDistance2) { + var k = quad.pointCharge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad.charge; + }; } - return function(feature) { - φ1 = λ1 = -(λ0 = φ0 = Infinity); - ranges = []; - d3.geo.stream(feature, bound); - var n = ranges.length; - if (n) { - ranges.sort(compareRanges); - for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { - b = ranges[i]; - if (withinRange(b[0], a) || withinRange(b[1], a)) { - if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; - if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; - } else { - merged.push(a = b); + force.tick = function() { + if ((alpha *= .99) < .005) { + timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); } } - var best = -Infinity, dλ; - for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { - b = merged[i]; - if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; } } - ranges = range = null; - return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + event.tick({ + type: "tick", + alpha: alpha + }); }; - }(); - d3.geo.centroid = function(object) { - d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, d3_geo_centroid); - var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; - if (m < ε2) { - x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; - if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; - m = x * x + y * y + z * z; - if (m < ε2) return [ NaN, NaN ]; - } - return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; - }; - var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; - var d3_geo_centroid = { - sphere: d3_noop, - point: d3_geo_centroidPoint, - lineStart: d3_geo_centroidLineStart, - lineEnd: d3_geo_centroidLineEnd, - polygonStart: function() { - d3_geo_centroid.lineStart = d3_geo_centroidRingStart; - }, - polygonEnd: function() { - d3_geo_centroid.lineStart = d3_geo_centroidLineStart; - } - }; - function d3_geo_centroidPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); - } - function d3_geo_centroidPointXYZ(x, y, z) { - ++d3_geo_centroidW0; - d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; - d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; - d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; - } - function d3_geo_centroidLineStart() { - var x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroid.point = nextPoint; - d3_geo_centroidPointXYZ(x0, y0, z0); + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); - } - } - function d3_geo_centroidLineEnd() { - d3_geo_centroid.point = d3_geo_centroidPoint; - } - function d3_geo_centroidRingStart() { - var λ00, φ00, x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ00 = λ, φ00 = φ; - d3_geo_centroid.point = nextPoint; - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroidPointXYZ(x0, y0, z0); + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.chargeDistance = function(x) { + if (!arguments.length) return Math.sqrt(chargeDistance2); + chargeDistance2 = x * x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return Math.sqrt(theta2); + theta2 = x * x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) { + alpha = x; + } else { + timer.c = null, timer.t = NaN, timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + } + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + timer = d3_timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, l = candidates.length, x; + while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); }; - d3_geo_centroid.lineEnd = function() { - nextPoint(λ00, φ00); - d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; - d3_geo_centroid.point = d3_geo_centroidPoint; + force.resume = function() { + return force.alpha(.1); }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); - d3_geo_centroidX2 += v * cx; - d3_geo_centroidY2 += v * cy; - d3_geo_centroidZ2 += v * cz; - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); } + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; } - function d3_geo_compose(a, b) { - function compose(x, y) { - return x = a(x, y), b(x[0], x[1]); - } - if (a.invert && b.invert) compose.invert = function(x, y) { - return x = b.invert(x, y), x && a.invert(x[0], x[1]); - }; - return compose; + function d3_layout_forceDragend(d) { + d.fixed &= ~6; } - function d3_true() { - return true; + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; } - function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { - var subject = [], clip = []; - segments.forEach(function(segment) { - if ((n = segment.length - 1) <= 0) return; - var n, p0 = segment[0], p1 = segment[n]; - if (d3_geo_sphericalEqual(p0, p1)) { - listener.lineStart(); - for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); - listener.lineEnd(); - return; + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; + } + function d3_layout_forceAccumulate(quad, alpha, charges) { + var cx = 0, cy = 0; + quad.charge = 0; + if (!quad.leaf) { + var nodes = quad.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; } - var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); - a.o = b; - subject.push(a); - clip.push(b); - a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); - b = new d3_geo_clipPolygonIntersection(p1, null, a, true); - a.o = b; - subject.push(a); - clip.push(b); - }); - clip.sort(compare); - d3_geo_clipPolygonLinkCircular(subject); - d3_geo_clipPolygonLinkCircular(clip); - if (!subject.length) return; - for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { - clip[i].e = entry = !entry; } - var start = subject[0], points, point; - while (1) { - var current = start, isSubject = true; - while (current.v) if ((current = current.n) === start) return; - points = current.z; - listener.lineStart(); - do { - current.v = current.o.v = true; - if (current.e) { - if (isSubject) { - for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.n.x, 1, listener); + if (quad.point) { + if (!quad.leaf) { + quad.point.x += Math.random() - .5; + quad.point.y += Math.random() - .5; + } + var k = alpha * charges[quad.point.index]; + quad.charge += quad.pointCharge = k; + cx += k * quad.point.x; + cy += k * quad.point.y; + } + quad.cx = cx / quad.charge; + quad.cy = cy / quad.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; + d3.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; + function hierarchy(root) { + var stack = [ root ], nodes = [], node; + root.depth = 0; + while ((node = stack.pop()) != null) { + nodes.push(node); + if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { + var n, childs, child; + while (--n >= 0) { + stack.push(child = childs[n]); + child.parent = node; + child.depth = node.depth + 1; } - current = current.n; + if (value) node.value = 0; + node.children = childs; } else { - if (isSubject) { - points = current.p.z; - for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.p.x, -1, listener); - } - current = current.p; + if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; + delete node.children; } - current = current.o; - points = current.z; - isSubject = !isSubject; - } while (!current.v); - listener.lineEnd(); + } + d3_layout_hierarchyVisitAfter(root, function(node) { + var childs, parent; + if (sort && (childs = node.children)) childs.sort(sort); + if (value && (parent = node.parent)) parent.value += node.value; + }); + return nodes; } + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + if (value) { + d3_layout_hierarchyVisitBefore(root, function(node) { + if (node.children) node.value = 0; + }); + d3_layout_hierarchyVisitAfter(root, function(node) { + var parent; + if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; + if (parent = node.parent) parent.value += node.value; + }); + } + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; } - function d3_geo_clipPolygonLinkCircular(array) { - if (!(n = array.length)) return; - var n, i = 0, a = array[0], b; - while (++i < n) { - a.n = b = array[i]; - b.p = a; - a = b; + function d3_layout_hierarchyVisitBefore(node, callback) { + var nodes = [ node ]; + while ((node = nodes.pop()) != null) { + callback(node); + if ((children = node.children) && (n = children.length)) { + var n, children; + while (--n >= 0) nodes.push(children[n]); + } } - a.n = b = array[0]; - b.p = a; } - function d3_geo_clipPolygonIntersection(point, points, other, entry) { - this.x = point; - this.z = points; - this.o = other; - this.e = entry; - this.v = false; - this.n = this.p = null; + function d3_layout_hierarchyVisitAfter(node, callback) { + var nodes = [ node ], nodes2 = []; + while ((node = nodes.pop()) != null) { + nodes2.push(node); + if ((children = node.children) && (n = children.length)) { + var i = -1, n, children; + while (++i < n) nodes.push(children[i]); + } + } + while ((node = nodes2.pop()) != null) { + callback(node); + } } - function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { - return function(rotate, listener) { - var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - clip.point = pointRing; - clip.lineStart = ringStart; - clip.lineEnd = ringEnd; - segments = []; - polygon = []; - }, - polygonEnd: function() { - clip.point = point; - clip.lineStart = lineStart; - clip.lineEnd = lineEnd; - segments = d3.merge(segments); - var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); - if (segments.length) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); - } else if (clipStartInside) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (polygonStarted) listener.polygonEnd(), polygonStarted = false; - segments = polygon = null; - }, - sphere: function() { - listener.polygonStart(); - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - listener.polygonEnd(); + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; } - }; - function point(λ, φ) { - var point = rotate(λ, φ); - if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); } - function pointLine(λ, φ) { - var point = rotate(λ, φ); - line.point(point[0], point[1]); + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); } - function lineStart() { - clip.point = pointLine; - line.lineStart(); + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; + function pie(data) { + var n = data.length, values = data.map(function(d, i) { + return +value.call(pie, d, i); + }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + index.forEach(function(i) { + arcs[i] = { + data: data[i], + value: v = values[i], + startAngle: a, + endAngle: a += v * k + pa, + padAngle: p + }; + }); + return arcs; + } + pie.value = function(_) { + if (!arguments.length) return value; + value = _; + return pie; + }; + pie.sort = function(_) { + if (!arguments.length) return sort; + sort = _; + return pie; + }; + pie.startAngle = function(_) { + if (!arguments.length) return startAngle; + startAngle = _; + return pie; + }; + pie.endAngle = function(_) { + if (!arguments.length) return endAngle; + endAngle = _; + return pie; + }; + pie.padAngle = function(_) { + if (!arguments.length) return padAngle; + padAngle = _; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + if (!(n = data.length)) return data; + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var m = series[0].length, n, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } } - function lineEnd() { - clip.point = point; - line.lineEnd(); + return data; + } + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } } - var segments; - var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; - function pointRing(λ, φ) { - ring.push([ λ, φ ]); - var point = rotate(λ, φ); - ringListener.point(point[0], point[1]); + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); } - function ringStart() { - ringListener.lineStart(); - ring = []; + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; } - function ringEnd() { - pointRing(ring[0][0], ring[0][1]); - ringListener.lineEnd(); - var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; - ring.pop(); - polygon.push(ring); - ring = null; - if (!n) return; - if (clean & 1) { - segment = ringSegments[0]; - var n = segment.length - 1, i = -1, point; - if (n > 0) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - while (++i < n) listener.point((point = segment[i])[0], point[1]); - listener.lineEnd(); + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; } - return; + s2 += s3 * data[i][j][1]; } - if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); - segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; } - return clip; - }; - } - function d3_geo_clipSegmentLength1(segment) { - return segment.length > 1; - } - function d3_geo_clipBufferListener() { - var lines = [], line; - return { - lineStart: function() { - lines.push(line = []); - }, - point: function(λ, φ) { - line.push([ λ, φ ]); - }, - lineEnd: d3_noop, - buffer: function() { - var buffer = lines; - lines = []; - line = null; - return buffer; - }, - rejoin: function() { - if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; } - }; + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); } - function d3_geo_clipSort(a, b) { - return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; } - var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); - function d3_geo_clipAntimeridianLine(listener) { - var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; - return { - lineStart: function() { - listener.lineStart(); - clean = 1; - }, - point: function(λ1, φ1) { - var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); - if (abs(dλ - π) < ε) { - listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - listener.point(λ1, φ0); - clean = 0; - } else if (sλ0 !== sλ1 && dλ >= π) { - if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; - if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; - φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - clean = 0; - } - listener.point(λ0 = λ1, φ0 = φ1); - sλ0 = sλ1; - }, - lineEnd: function() { - listener.lineEnd(); - λ0 = φ0 = NaN; - }, - clean: function() { - return 2 - clean; + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; } - }; + } + return j; } - function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { - var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); - return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); } - function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { - var φ; - if (from == null) { - φ = direction * halfπ; - listener.point(-π, φ); - listener.point(0, φ); - listener.point(π, φ); - listener.point(π, 0); - listener.point(π, -φ); - listener.point(0, -φ); - listener.point(-π, -φ); - listener.point(-π, 0); - listener.point(-π, φ); - } else if (abs(from[0] - to[0]) > ε) { - var s = from[0] < to[0] ? π : -π; - φ = direction * s / 2; - listener.point(-s, φ); - listener.point(0, φ); - listener.point(s, φ); - } else { - listener.point(to[0], to[1]); - } + function d3_layout_stackSum(p, d) { + return p + d[1]; } - function d3_geo_pointInPolygon(point, polygon) { - var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; - d3_geo_areaRingSum.reset(); - for (var i = 0, n = polygon.length; i < n; ++i) { - var ring = polygon[i], m = ring.length; - if (!m) continue; - var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; - while (true) { - if (j === m) j = 0; - point = ring[j]; - var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; - d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); - polarAngle += antimeridian ? dλ + sdλ * τ : dλ; - if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { - var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); - d3_geo_cartesianNormalize(arc); - var intersection = d3_geo_cartesianCross(meridianNormal, arc); - d3_geo_cartesianNormalize(intersection); - var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); - if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { - winding += antimeridian ^ dλ >= 0 ? 1 : -1; + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); } } - if (!j++) break; - λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; } + return bins; } - return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } - function d3_geo_clipCircle(radius) { - var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); - return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); - function visible(λ, φ) { - return Math.cos(λ) * Math.cos(φ) > cr; - } - function clipLine(listener) { - var point0, c0, v0, v00, clean; - return { - lineStart: function() { - v00 = v0 = false; - clean = 1; - }, - point: function(λ, φ) { - var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; - if (!point0 && (v00 = v0 = v)) listener.lineStart(); - if (v !== v0) { - point2 = intersect(point0, point1); - if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { - point1[0] += ε; - point1[1] += ε; - v = visible(point1[0], point1[1]); - } - } - if (v !== v0) { - clean = 0; - if (v) { - listener.lineStart(); - point2 = intersect(point1, point0); - listener.point(point2[0], point2[1]); - } else { - point2 = intersect(point0, point1); - listener.point(point2[0], point2[1]); - listener.lineEnd(); - } - point0 = point2; - } else if (notHemisphere && point0 && smallRadius ^ v) { - var t; - if (!(c & c0) && (t = intersect(point1, point0, true))) { - clean = 0; - if (smallRadius) { - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - } else { - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - } - } - } - if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { - listener.point(point1[0], point1[1]); - } - point0 = point1, v0 = v, c0 = c; - }, - lineEnd: function() { - if (v0) listener.lineEnd(); - point0 = null; - }, - clean: function() { - return clean | (v00 && v0) << 1; - } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; }; - } - function intersect(a, b, two) { - var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); - var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; - if (!determinant) return !two && a; - var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); - d3_geo_cartesianAdd(A, B); - var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); - if (t2 < 0) return; - var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); - d3_geo_cartesianAdd(q, A); - q = d3_geo_spherical(q); - if (!two) return q; - var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; - if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; - var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; - if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; - if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { - var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); - d3_geo_cartesianAdd(q1, A); - return [ q, d3_geo_spherical(q1) ]; + root.x = root.y = 0; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r -= dr; + }); } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; } - function code(λ, φ) { - var r = smallRadius ? radius : π - radius, code = 0; - if (λ < -r) code |= 1; else if (λ > r) code |= 2; - if (φ < -r) code |= 4; else if (φ > r) code |= 8; - return code; - } - } - function d3_geom_clipLine(x0, y0, x1, y1) { - return function(line) { - var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; - r = x0 - ax; - if (!dx && r > 0) return; - r /= dx; - if (dx < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dx > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = x1 - ax; - if (!dx && r < 0) return; - r /= dx; - if (dx < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dx > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - r = y0 - ay; - if (!dy && r > 0) return; - r /= dy; - if (dy < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dy > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = y1 - ay; - if (!dy && r < 0) return; - r /= dy; - if (dy < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dy > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - if (t0 > 0) line.a = { - x: ax + t0 * dx, - y: ay + t0 * dy - }; - if (t1 < 1) line.b = { - x: ax + t1 * dx, - y: ay + t1 * dy - }; - return line; + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; }; - } - var d3_geo_clipExtentMAX = 1e9; - d3.geo.clipExtent = function() { - var x0, y0, x1, y1, stream, clip, clipExtent = { - stream: function(output) { - if (stream) stream.valid = false; - stream = clip(output); - stream.valid = true; - return stream; - }, - extent: function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); - if (stream) stream.valid = false, stream = null; - return clipExtent; - } + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; }; - return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); }; - function d3_geo_clipExtent(x0, y0, x1, y1) { - return function(listener) { - var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - listener = bufferListener; - segments = []; - polygon = []; - clean = true; - }, - polygonEnd: function() { - listener = listener_; - segments = d3.merge(segments); - var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; - if (inside || visible) { - listener.polygonStart(); - if (inside) { - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (visible) { - d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); - } - listener.polygonEnd(); - } - segments = polygon = ring = null; - } - }; - function insidePolygon(p) { - var wn = 0, n = polygon.length, y = p[1]; - for (var i = 0; i < n; ++i) { - for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { - b = v[j]; - if (a[1] <= y) { - if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; - } else { - if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; - } - a = b; - } - } - return wn !== 0; - } - function interpolate(from, to, direction, listener) { - var a = 0, a1 = 0; - if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { - do { - listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); - } while ((a = (a + direction + 4) % 4) !== a1); - } else { - listener.point(to[0], to[1]); - } - } - function pointVisible(x, y) { - return x0 <= x && x <= x1 && y0 <= y && y <= y1; - } - function point(x, y) { - if (pointVisible(x, y)) listener.point(x, y); - } - var x__, y__, v__, x_, y_, v_, first, clean; - function lineStart() { - clip.point = linePoint; - if (polygon) polygon.push(ring = []); - first = true; - v_ = false; - x_ = y_ = NaN; - } - function lineEnd() { - if (segments) { - linePoint(x__, y__); - if (v__ && v_) bufferListener.rejoin(); - segments.push(bufferListener.buffer()); - } - clip.point = point; - if (v_) listener.lineEnd(); - } - function linePoint(x, y) { - x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); - y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); - var v = pointVisible(x, y); - if (polygon) ring.push([ x, y ]); - if (first) { - x__ = x, y__ = y, v__ = v; - first = false; - if (v) { - listener.lineStart(); - listener.point(x, y); + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } } - } else { - if (v && v_) listener.point(x, y); else { - var l = { - a: { - x: x_, - y: y_ - }, - b: { - x: x, - y: y - } - }; - if (clipLine(l)) { - if (!v_) { - listener.lineStart(); - listener.point(l.a.x, l.a.y); + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; } - listener.point(l.b.x, l.b.y); - if (!v) listener.lineEnd(); - clean = false; - } else if (v) { - listener.lineStart(); - listener.point(x, y); - clean = false; } } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } } - x_ = x, y_ = y, v_ = v; } - return clip; - }; - function corner(p, direction) { - return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; - } - function compare(a, b) { - return comparePoints(a.x, b.x); } - function comparePoints(a, b) { - var ca = corner(a, 1), cb = corner(b, 1); - return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); } - function d3_geo_conic(projectAt) { - var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); - p.parallels = function(_) { - if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; - return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); - }; - return p; + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; } - function d3_geo_conicEqualArea(φ0, φ1) { - var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; - function forward(λ, φ) { - var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; - return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); } - forward.invert = function(x, y) { - var ρ0_y = ρ0 - y; - return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; - }; - return forward; } - (d3.geo.conicEqualArea = function() { - return d3_geo_conic(d3_geo_conicEqualArea); - }).raw = d3_geo_conicEqualArea; - d3.geo.albers = function() { - return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); - }; - d3.geo.albersUsa = function() { - var lower48 = d3.geo.albers(); - var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); - var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); - var point, pointStream = { - point: function(x, y) { - point = [ x, y ]; + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); + d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; + d3_layout_hierarchyVisitBefore(root1, secondWalk); + if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { + var left = root0, right = root0, bottom = root0; + d3_layout_hierarchyVisitBefore(root0, function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); + d3_layout_hierarchyVisitBefore(root0, function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); } - }, lower48Point, alaskaPoint, hawaiiPoint; - function albersUsa(coordinates) { - var x = coordinates[0], y = coordinates[1]; - point = null; - (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); - return point; + return nodes; } - albersUsa.invert = function(coordinates) { - var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; - return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); - }; - albersUsa.stream = function(stream) { - var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); - return { - point: function(x, y) { - lower48Stream.point(x, y); - alaskaStream.point(x, y); - hawaiiStream.point(x, y); - }, - sphere: function() { - lower48Stream.sphere(); - alaskaStream.sphere(); - hawaiiStream.sphere(); - }, - lineStart: function() { - lower48Stream.lineStart(); - alaskaStream.lineStart(); - hawaiiStream.lineStart(); - }, - lineEnd: function() { - lower48Stream.lineEnd(); - alaskaStream.lineEnd(); - hawaiiStream.lineEnd(); - }, - polygonStart: function() { - lower48Stream.polygonStart(); - alaskaStream.polygonStart(); - hawaiiStream.polygonStart(); - }, - polygonEnd: function() { - lower48Stream.polygonEnd(); - alaskaStream.polygonEnd(); - hawaiiStream.polygonEnd(); + function wrapTree(root0) { + var root1 = { + A: null, + children: [ root0 ] + }, queue = [ root1 ], node1; + while ((node1 = queue.pop()) != null) { + for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { + queue.push((children[i] = child = { + _: children[i], + parent: node1, + children: (child = children[i].children) && child.slice() || [], + A: null, + a: null, + z: 0, + m: 0, + c: 0, + s: 0, + t: null, + i: i + }).a = child); } - }; - }; - albersUsa.precision = function(_) { - if (!arguments.length) return lower48.precision(); - lower48.precision(_); - alaska.precision(_); - hawaii.precision(_); - return albersUsa; - }; - albersUsa.scale = function(_) { - if (!arguments.length) return lower48.scale(); - lower48.scale(_); - alaska.scale(_ * .35); - hawaii.scale(_); - return albersUsa.translate(lower48.translate()); - }; - albersUsa.translate = function(_) { - if (!arguments.length) return lower48.translate(); - var k = lower48.scale(), x = +_[0], y = +_[1]; - lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; - alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - return albersUsa; - }; - return albersUsa.scale(1070); - }; - var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_pathAreaPolygon = 0; - d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; - }, - polygonEnd: function() { - d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; - d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); - } - }; - function d3_geo_pathAreaRingStart() { - var x00, y00, x0, y0; - d3_geo_pathArea.point = function(x, y) { - d3_geo_pathArea.point = nextPoint; - x00 = x0 = x, y00 = y0 = y; - }; - function nextPoint(x, y) { - d3_geo_pathAreaPolygon += y0 * x - x0 * y; - x0 = x, y0 = y; + } + return root1.children[0]; } - d3_geo_pathArea.lineEnd = function() { - nextPoint(x00, y00); - }; - } - var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; - var d3_geo_pathBounds = { - point: d3_geo_pathBoundsPoint, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop - }; - function d3_geo_pathBoundsPoint(x, y) { - if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; - if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; - if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; - if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; - } - function d3_geo_pathBuffer() { - var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointCircle = d3_geo_pathBufferCircle(_); - return stream; - }, - result: function() { - if (buffer.length) { - var result = buffer.join(""); - buffer = []; - return result; + function firstWalk(v) { + var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; + if (children.length) { + d3_layout_treeShift(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; } + } else if (w) { + v.z = w.z + separation(v._, w._); } - }; - function point(x, y) { - buffer.push("M", x, ",", y, pointCircle); - } - function pointLineStart(x, y) { - buffer.push("M", x, ",", y); - stream.point = pointLine; - } - function pointLine(x, y) { - buffer.push("L", x, ",", y); + v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } - function lineEnd() { - stream.point = point; + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; } - function lineEndPolygon() { - buffer.push("Z"); + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !d3_layout_treeRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; } - return stream; - } - function d3_geo_pathBufferCircle(radius) { - return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; - } - var d3_geo_pathCentroid = { - point: d3_geo_pathCentroidPoint, - lineStart: d3_geo_pathCentroidLineStart, - lineEnd: d3_geo_pathCentroidLineEnd, - polygonStart: function() { - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; - }, - polygonEnd: function() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; - d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + function sizeNode(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null ? sizeNode : null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) == null ? null : sizeNode; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); }; - function d3_geo_pathCentroidPoint(x, y) { - d3_geo_centroidX0 += x; - d3_geo_centroidY0 += y; - ++d3_geo_centroidZ0; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; } - function d3_geo_pathCentroidLineStart() { - var x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - } + function d3_layout_treeLeft(v) { + var children = v.children; + return children.length ? children[0] : v.t; } - function d3_geo_pathCentroidLineEnd() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + function d3_layout_treeRight(v) { + var children = v.children, n; + return (n = children.length) ? children[n - 1] : v.t; } - function d3_geo_pathCentroidRingStart() { - var x00, y00, x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - z = y0 * x - x0 * y; - d3_geo_centroidX2 += z * (x0 + x); - d3_geo_centroidY2 += z * (y0 + y); - d3_geo_centroidZ2 += z * 3; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - } - d3_geo_pathCentroid.lineEnd = function() { - nextPoint(x00, y00); - }; + function d3_layout_treeMove(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; } - function d3_geo_pathContext(context) { - var pointRadius = 4.5; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointRadius = _; - return stream; - }, - result: d3_noop - }; - function point(x, y) { - context.moveTo(x + pointRadius, y); - context.arc(x, y, pointRadius, 0, τ); - } - function pointLineStart(x, y) { - context.moveTo(x, y); - stream.point = pointLine; - } - function pointLine(x, y) { - context.lineTo(x, y); - } - function lineEnd() { - stream.point = point; + function d3_layout_treeShift(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); } - function lineEndPolygon() { - context.closePath(); + } + function d3_layout_treeAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; + } + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_hierarchyVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; } - return stream; + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); } - function d3_geo_resample(project) { - var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; - function resample(stream) { - return (maxDepth ? resampleRecursive : resampleNone)(stream); - } - function resampleNone(stream) { - return d3_geo_transformPoint(stream, function(x, y) { - x = project(x, y); - stream.point(x[0], x[1]); - }); + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } } - function resampleRecursive(stream) { - var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; - var resample = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - stream.polygonStart(); - resample.lineStart = ringStart; - }, - polygonEnd: function() { - stream.polygonEnd(); - resample.lineStart = lineStart; + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } } - }; - function point(x, y) { - x = project(x, y); - stream.point(x[0], x[1]); - } - function lineStart() { - x0 = NaN; - resample.point = linePoint; - stream.lineStart(); - } - function linePoint(λ, φ) { - var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); - resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); - stream.point(x0, y0); - } - function lineEnd() { - resample.point = point; - stream.lineEnd(); - } - function ringStart() { - lineStart(); - resample.point = ringPoint; - resample.lineEnd = ringEnd; + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); } - function ringPoint(λ, φ) { - linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; - resample.point = linePoint; + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); } - function ringEnd() { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); - resample.lineEnd = lineEnd; - lineEnd(); + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; } - return resample; + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; } - function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { - var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; - if (d2 > 4 * δ2 && depth--) { - var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; - if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); - stream.point(x2, y2); - resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; + } else { + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; } } - resample.precision = function(_) { - if (!arguments.length) return Math.sqrt(δ2); - maxDepth = (δ2 = _ * _) > 0 && 16; - return resample; - }; - return resample; - } - d3.geo.path = function() { - var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; - function path(object) { - if (object) { - if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); - if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); - d3.geo.stream(object, cacheStream); - } - return contextStream.result(); + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = root.y = 0; + if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; } - path.area = function(object) { - d3_geo_pathAreaSum = 0; - d3.geo.stream(object, projectStream(d3_geo_pathArea)); - return d3_geo_pathAreaSum; + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; }; - path.centroid = function(object) { - d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); - return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; }; - path.bounds = function(object) { - d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); - d3.geo.stream(object, projectStream(d3_geo_pathBounds)); - return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; }; - path.projection = function(_) { - if (!arguments.length) return projection; - projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; - return reset(); + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; }; - path.context = function(_) { - if (!arguments.length) return context; - contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); - if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); - return reset(); + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; }; - path.pointRadius = function(_) { - if (!arguments.length) return pointRadius; - pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); - return path; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; }; - function reset() { - cacheStream = null; - return path; - } - return path.projection(d3.geo.albersUsa()).context(null); + return d3_layout_hierarchyRebind(treemap, hierarchy); }; - function d3_geo_pathProjectStream(project) { - var resample = d3_geo_resample(function(x, y) { - return project([ x * d3_degrees, y * d3_degrees ]); - }); - return function(stream) { - return d3_geo_projectionRadians(resample(stream)); + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy }; } - d3.geo.transform = function(methods) { + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } return { - stream: function(stream) { - var transform = new d3_geo_transform(stream); - for (var k in methods) transform[k] = methods[k]; - return transform; - } + x: x, + y: y, + dx: dx, + dy: dy }; - }; - function d3_geo_transform(stream) { - this.stream = stream; } - d3_geo_transform.prototype = { - point: function(x, y) { - this.stream.point(x, y); - }, - sphere: function() { - this.stream.sphere(); - }, - lineStart: function() { - this.stream.lineStart(); + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; }, - lineEnd: function() { - this.stream.lineEnd(); + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; }, - polygonStart: function() { - this.stream.polygonStart(); + bates: function(m) { + var random = d3.random.irwinHall(m); + return function() { + return random() / m; + }; }, - polygonEnd: function() { - this.stream.polygonEnd(); + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; } }; - function d3_geo_transformPoint(stream, point) { - return { - point: point, - sphere: function() { - stream.sphere(); - }, - lineStart: function() { - stream.lineStart(); - }, - lineEnd: function() { - stream.lineEnd(); - }, - polygonStart: function() { - stream.polygonStart(); + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; + } + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); + } + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; }, - polygonEnd: function() { - stream.polygonEnd(); + ceil: function(x) { + return Math.ceil(x / step) * step; } - }; + } : d3_scale_niceIdentity; } - d3.geo.projection = d3_geo_projection; - d3.geo.projectionMutator = d3_geo_projectionMutator; - function d3_geo_projection(project) { - return d3_geo_projectionMutator(function() { - return project; - })(); + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; } - function d3_geo_projectionMutator(projectAt) { - var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { - x = project(x, y); - return [ x[0] * k + δx, δy - x[1] * k ]; - }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; - function projection(point) { - point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); - return [ point[0] * k + δx, δy - point[1] * k ]; + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; } - function invert(point) { - point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); - return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; + function scale(x) { + return output(x); } - projection.stream = function(output) { - if (stream) stream.valid = false; - stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); - stream.valid = true; - return stream; + scale.invert = function(y) { + return input(y); }; - projection.clipAngle = function(_) { - if (!arguments.length) return clipAngle; - preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); - return invalidate(); + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); }; - projection.clipExtent = function(_) { - if (!arguments.length) return clipExtent; - clipExtent = _; - postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; - return invalidate(); + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); }; - projection.scale = function(_) { - if (!arguments.length) return k; - k = +_; - return reset(); + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); }; - projection.translate = function(_) { - if (!arguments.length) return [ x, y ]; - x = +_[0]; - y = +_[1]; - return reset(); + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); }; - projection.center = function(_) { - if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; - λ = _[0] % 360 * d3_radians; - φ = _[1] % 360 * d3_radians; - return reset(); + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); }; - projection.rotate = function(_) { - if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; - δλ = _[0] % 360 * d3_radians; - δφ = _[1] % 360 * d3_radians; - δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; - return reset(); + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); }; - d3.rebind(projection, projectResample, "precision"); - function reset() { - projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); - var center = project(λ, φ); - δx = x - center[0] * k; - δy = y + center[1] * k; - return invalidate(); - } - function invalidate() { - if (stream) stream.valid = false, stream = null; - return projection; - } - return function() { - project = projectAt.apply(this, arguments); - projection.invert = project.invert && invert; - return reset(); + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); }; + return rescale(); } - function d3_geo_projectionRadians(stream) { - return d3_geo_transformPoint(stream, function(x, y) { - stream.point(x * d3_radians, y * d3_radians); - }); + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } - function d3_geo_equirectangular(λ, φ) { - return [ λ, φ ]; + function d3_scale_linearNice(domain, m) { + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + return domain; } - (d3.geo.equirectangular = function() { - return d3_geo_projection(d3_geo_equirectangular); - }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; - d3.geo.rotation = function(rotate) { - rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); - function forward(coordinates) { - coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - } - forward.invert = function(coordinates) { - coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - }; - return forward; - }; - function d3_geo_identityRotation(λ, φ) { - return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; } - d3_geo_identityRotation.invert = d3_geo_equirectangular; - function d3_geo_rotation(δλ, δφ, δγ) { - return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } - function d3_geo_forwardRotationλ(δλ) { - return function(λ, φ) { - return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; - }; + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + if (format) { + var match = d3_format_re.exec(format); + match.shift(); + if (match[8] === "s") { + var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); + if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); + match[8] = "f"; + format = d3.format(match.join("")); + return function(d) { + return format(prefix.scale(d)) + prefix.symbol; + }; + } + if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); + format = match.join(""); + } else { + format = ",." + d3_scale_linearPrecision(range[2]) + "f"; + } + return d3.format(format); } - function d3_geo_rotationλ(δλ) { - var rotation = d3_geo_forwardRotationλ(δλ); - rotation.invert = d3_geo_forwardRotationλ(-δλ); - return rotation; + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); } - function d3_geo_rotationφγ(δφ, δγ) { - var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); - function rotation(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; - return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + } + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); } - rotation.invert = function(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; - return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); }; - return rotation; - } - d3.geo.circle = function() { - var origin = [ 0, 0 ], angle, precision = 6, interpolate; - function circle() { - var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; - interpolate(null, null, 1, { - point: function(x, y) { - ring.push(x = rotate(x, y)); - x[0] *= d3_degrees, x[1] *= d3_degrees; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); } - }); - return { - type: "Polygon", - coordinates: [ ring ] + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); + } + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(1, base * n / scale.ticks().length); + return function(d) { + var i = d / pow(Math.round(log(d))); + if (i * base < base - .5) i *= base; + return i <= k ? format(d) : ""; }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); } - circle.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return circle; + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); + } + scale.invert = function(x) { + return powb(linear.invert(x)); }; - circle.angle = function(x) { - if (!arguments.length) return angle; - interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); - return circle; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; }; - circle.precision = function(_) { - if (!arguments.length) return precision; - interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); - return circle; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); }; - return circle.angle(90); - }; - function d3_geo_circleInterpolate(radius, precision) { - var cr = Math.cos(radius), sr = Math.sin(radius); - return function(from, to, direction, listener) { - var step = direction * precision; - if (from != null) { - from = d3_geo_circleAngle(cr, from); - to = d3_geo_circleAngle(cr, to); - if (direction > 0 ? from < to : from > to) from += direction * τ; - } else { - from = radius + direction * τ; - to = radius - .5 * step; - } - for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { - listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); - } + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); }; + return d3_scale_linearRebind(scale, linear); } - function d3_geo_circleAngle(cr, point) { - var a = d3_geo_cartesian(point); - a[0] -= cr; - d3_geo_cartesianNormalize(a); - var angle = d3_acos(-a[1]); - return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; } - d3.geo.distance = function(a, b) { - var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; - return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); }; - d3.geo.graticule = function() { - var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; - function graticule() { - return { - type: "MultiLineString", - coordinates: lines() - }; - } - function lines() { - return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { - return abs(x % DX) > ε; - }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { - return abs(y % DY) > ε; - }).map(y)); + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } - graticule.lines = function() { - return lines().map(function(coordinates) { - return { - type: "LineString", - coordinates: coordinates - }; + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; }); + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); }; - graticule.outline = function() { - return { - type: "Polygon", - coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments }; + return scale; }; - graticule.extent = function(_) { - if (!arguments.length) return graticule.minorExtent(); - return graticule.majorExtent(_).minorExtent(_); + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, + 0) : (stop - start) / (domain.length - 1 + padding); + range = steps(start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; }; - graticule.majorExtent = function(_) { - if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; - X0 = +_[0][0], X1 = +_[1][0]; - Y0 = +_[0][1], Y1 = +_[1][1]; - if (X0 > X1) _ = X0, X0 = X1, X1 = _; - if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; - return graticule.precision(precision); + scale.rangeRoundPoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), + 0) : (stop - start) / (domain.length - 1 + padding) | 0; + range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); + rangeBand = 0; + ranger = { + t: "rangeRoundPoints", + a: arguments + }; + return scale; }; - graticule.minorExtent = function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - x0 = +_[0][0], x1 = +_[1][0]; - y0 = +_[0][1], y1 = +_[1][1]; - if (x0 > x1) _ = x0, x0 = x1, x1 = _; - if (y0 > y1) _ = y0, y0 = y1, y1 = _; - return graticule.precision(precision); + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; }; - graticule.step = function(_) { - if (!arguments.length) return graticule.minorStep(); - return graticule.majorStep(_).minorStep(_); + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); + range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; }; - graticule.majorStep = function(_) { - if (!arguments.length) return [ DX, DY ]; - DX = +_[0], DY = +_[1]; - return graticule; + scale.rangeBand = function() { + return rangeBand; }; - graticule.minorStep = function(_) { - if (!arguments.length) return [ dx, dy ]; - dx = +_[0], dy = +_[1]; - return graticule; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); }; - graticule.precision = function(_) { - if (!arguments.length) return precision; - precision = +_; - x = d3_geo_graticuleX(y0, y1, 90); - y = d3_geo_graticuleY(x0, x1, precision); - X = d3_geo_graticuleX(Y0, Y1, 90); - Y = d3_geo_graticuleY(X0, X1, precision); - return graticule; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); }; - return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); }; - function d3_geo_graticuleX(y0, y1, dy) { - var y = d3.range(y0, y1 - ε, dy).concat(y1); - return function(x) { - return y.map(function(y) { - return [ x, y ]; - }); + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); + return rescale(); }; - } - function d3_geo_graticuleY(x0, x1, dx) { - var x = d3.range(x0, x1 - ε, dx).concat(x1); - return function(y) { - return x.map(function(x) { - return [ x, y ]; - }); + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); } - function d3_source(d) { - return d.source; - } - function d3_target(d) { - return d.target; - } - d3.geo.greatArc = function() { - var source = d3_source, source_, target = d3_target, target_; - function greatArc() { - return { - type: "LineString", - coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] - }; + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; } - greatArc.distance = function() { - return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); - }; - greatArc.source = function(_) { - if (!arguments.length) return source; - source = _, source_ = typeof _ === "function" ? null : _; - return greatArc; + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); }; - greatArc.target = function(_) { - if (!arguments.length) return target; - target = _, target_ = typeof _ === "function" ? null : _; - return greatArc; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); }; - greatArc.precision = function() { - return arguments.length ? greatArc : 0; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; }; - return greatArc; - }; - d3.geo.interpolate = function(source, target) { - return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); - }; - function d3_geo_interpolate(x0, y0, x1, y1) { - var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); - var interpolate = d ? function(t) { - var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; - return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; - } : function() { - return [ x0 * d3_degrees, y0 * d3_degrees ]; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); }; - interpolate.distance = d; - return interpolate; + return rescale(); } - d3.geo.length = function(object) { - d3_geo_lengthSum = 0; - d3.geo.stream(object, d3_geo_length); - return d3_geo_lengthSum; - }; - var d3_geo_lengthSum; - var d3_geo_length = { - sphere: d3_noop, - point: d3_noop, - lineStart: d3_geo_lengthLineStart, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); }; - function d3_geo_lengthLineStart() { - var λ0, sinφ0, cosφ0; - d3_geo_length.point = function(λ, φ) { - λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); - d3_geo_length.point = nextPoint; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; }; - d3_geo_length.lineEnd = function() { - d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; }; - function nextPoint(λ, φ) { - var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); - d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); - λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; - } + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; } - function d3_geo_azimuthal(scale, angle) { - function azimuthal(λ, φ) { - var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); - return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; } - azimuthal.invert = function(x, y) { - var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); - return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; }; - return azimuthal; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; } - var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { - return Math.sqrt(2 / (1 + cosλcosφ)); - }, function(ρ) { - return 2 * Math.asin(ρ / 2); - }); - (d3.geo.azimuthalEqualArea = function() { - return d3_geo_projection(d3_geo_azimuthalEqualArea); - }).raw = d3_geo_azimuthalEqualArea; - var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { - var c = Math.acos(cosλcosφ); - return c && c / Math.sin(c); - }, d3_identity); - (d3.geo.azimuthalEquidistant = function() { - return d3_geo_projection(d3_geo_azimuthalEquidistant); - }).raw = d3_geo_azimuthalEquidistant; - function d3_geo_conicConformal(φ0, φ1) { - var cosφ0 = Math.cos(φ0), t = function(φ) { - return Math.tan(π / 4 + φ / 2); - }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; - if (!n) return d3_geo_mercator; - function forward(λ, φ) { - if (F > 0) { - if (φ < -halfπ + ε) φ = -halfπ + ε; + d3.svg = {}; + function d3_zero() { + return 0; + } + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; + function arc() { + var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; + if (r1 < r0) rc = r1, r1 = r0, r0 = rc; + if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; + var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; + if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { + rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); + if (!cw) p1 *= -1; + if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); + if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); + } + if (r1) { + x0 = r1 * Math.cos(a0 + p1); + y0 = r1 * Math.sin(a0 + p1); + x1 = r1 * Math.cos(a1 - p1); + y1 = r1 * Math.sin(a1 - p1); + var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; + if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { + var h1 = (a0 + a1) / 2; + x0 = r1 * Math.cos(h1); + y0 = r1 * Math.sin(h1); + x1 = y1 = null; + } } else { - if (φ > halfπ - ε) φ = halfπ - ε; + x0 = y0 = 0; } - var ρ = F / Math.pow(t(φ), n); - return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; + if (r0) { + x2 = r0 * Math.cos(a1 - p0); + y2 = r0 * Math.sin(a1 - p0); + x3 = r0 * Math.cos(a0 + p0); + y3 = r0 * Math.sin(a0 + p0); + var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; + if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { + var h0 = (a0 + a1) / 2; + x2 = r0 * Math.cos(h0); + y2 = r0 * Math.sin(h0); + x3 = y3 = null; + } + } else { + x2 = y2 = 0; + } + if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var rc1 = rc, rc0 = rc; + if (da < π) { + var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); + rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); + } + if (x1 != null) { + var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); + if (rc === rc1) { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); + } else { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + } else { + path.push("M", x0, ",", y0); + } + if (x3 != null) { + var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); + if (rc === rc0) { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } else { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } + } else { + path.push("L", x2, ",", y2); + } + } else { + path.push("M", x0, ",", y0); + if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); + path.push("L", x2, ",", y2); + if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + } + path.push("Z"); + return path.join(""); } - forward.invert = function(x, y) { - var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); - return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; - }; - return forward; - } - (d3.geo.conicConformal = function() { - return d3_geo_conic(d3_geo_conicConformal); - }).raw = d3_geo_conicConformal; - function d3_geo_conicEquidistant(φ0, φ1) { - var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; - if (abs(n) < ε) return d3_geo_equirectangular; - function forward(λ, φ) { - var ρ = G - φ; - return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; + function circleSegment(r1, cw) { + return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } - forward.invert = function(x, y) { - var ρ0_y = G - y; - return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; }; - return forward; - } - (d3.geo.conicEquidistant = function() { - return d3_geo_conic(d3_geo_conicEquidistant); - }).raw = d3_geo_conicEquidistant; - var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / cosλcosφ; - }, Math.atan); - (d3.geo.gnomonic = function() { - return d3_geo_projection(d3_geo_gnomonic); - }).raw = d3_geo_gnomonic; - function d3_geo_mercator(λ, φ) { - return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; - } - d3_geo_mercator.invert = function(x, y) { - return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; - }; - function d3_geo_mercatorProjection(project) { - var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; - m.scale = function() { - var v = scale.apply(m, arguments); - return v === m ? clipAuto ? m.clipExtent(null) : m : v; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; }; - m.translate = function() { - var v = translate.apply(m, arguments); - return v === m ? clipAuto ? m.clipExtent(null) : m : v; + arc.cornerRadius = function(v) { + if (!arguments.length) return cornerRadius; + cornerRadius = d3_functor(v); + return arc; }; - m.clipExtent = function(_) { - var v = clipExtent.apply(m, arguments); - if (v === m) { - if (clipAuto = _ == null) { - var k = π * scale(), t = translate(); - clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); - } - } else if (clipAuto) { - v = null; - } - return v; + arc.padRadius = function(v) { + if (!arguments.length) return padRadius; + padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); + return arc; }; - return m.clipExtent(null); - } - (d3.geo.mercator = function() { - return d3_geo_mercatorProjection(d3_geo_mercator); - }).raw = d3_geo_mercator; - var d3_geo_orthographic = d3_geo_azimuthal(function() { - return 1; - }, Math.asin); - (d3.geo.orthographic = function() { - return d3_geo_projection(d3_geo_orthographic); - }).raw = d3_geo_orthographic; - var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / (1 + cosλcosφ); - }, function(ρ) { - return 2 * Math.atan(ρ); - }); - (d3.geo.stereographic = function() { - return d3_geo_projection(d3_geo_stereographic); - }).raw = d3_geo_stereographic; - function d3_geo_transverseMercator(λ, φ) { - return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; - } - d3_geo_transverseMercator.invert = function(x, y) { - return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; - }; - (d3.geo.transverseMercator = function() { - var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; - projection.center = function(_) { - return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; }; - projection.rotate = function(_) { - return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), - [ _[0], _[1], _[2] - 90 ]); + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; }; - return rotate([ 0, 0, 90 ]); - }).raw = d3_geo_transverseMercator; - d3.geom = {}; - function d3_geom_pointX(d) { - return d[0]; - } - function d3_geom_pointY(d) { - return d[1]; - } - d3.geom.hull = function(vertices) { - var x = d3_geom_pointX, y = d3_geom_pointY; - if (arguments.length) return hull(vertices); - function hull(data) { - if (data.length < 3) return []; - var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; - for (i = 0; i < n; i++) { - points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); - } - points.sort(d3_geom_hullOrder); - for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); - var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); - var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; - for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); - for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); - return polygon; - } - hull.x = function(_) { - return arguments.length ? (x = _, hull) : x; + arc.padAngle = function(v) { + if (!arguments.length) return padAngle; + padAngle = d3_functor(v); + return arc; }; - hull.y = function(_) { - return arguments.length ? (y = _, hull) : y; + arc.centroid = function() { + var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; + return [ Math.cos(a) * r, Math.sin(a) * r ]; }; - return hull; + return arc; }; - function d3_geom_hullUpper(points) { - var n = points.length, hull = [ 0, 1 ], hs = 2; - for (var i = 2; i < n; i++) { - while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; - hull[hs++] = i; - } - return hull.slice(0, hs); + var d3_svg_arcAuto = "auto"; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; } - function d3_geom_hullOrder(a, b) { - return a[0] - b[0] || a[1] - b[1]; + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; } - d3.geom.polygon = function(coordinates) { - d3_subclass(coordinates, d3_geom_polygonPrototype); - return coordinates; - }; - var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; - d3_geom_polygonPrototype.area = function() { - var i = -1, n = this.length, a, b = this[n - 1], area = 0; - while (++i < n) { - a = b; - b = this[i]; - area += a[1] * b[0] - a[0] * b[1]; - } - return area * .5; - }; - d3_geom_polygonPrototype.centroid = function(k) { - var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; - if (!arguments.length) k = -1 / (6 * this.area()); - while (++i < n) { - a = b; - b = this[i]; - c = a[0] * b[1] - b[0] * a[1]; - x += (a[0] + b[0]) * c; - y += (a[1] + b[1]) * c; - } - return [ x * k, y * k ]; - }; - d3_geom_polygonPrototype.clip = function(subject) { - var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; - while (++i < n) { - input = subject.slice(); - subject.length = 0; - b = this[i]; - c = input[(m = input.length - closed) - 1]; - j = -1; - while (++j < m) { - d = input[j]; - if (d3_geom_polygonInside(d, a, b)) { - if (!d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - subject.push(d); - } else if (d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_arcPadAngle(d) { + return d && d.padAngle; + } + function d3_svg_arcSweep(x0, y0, x1, y1) { + return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + } + function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { + var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; + if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; + return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; } - c = d; } - if (closed) subject.push(subject[0]); - a = b; + if (points.length) segment(); + return segments.length ? segments.join("") : null; } - return subject; + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); }; - function d3_geom_polygonInside(p, a, b) { - return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.length > 1 ? points.join("L") : points + "Z"; } - function d3_geom_polygonIntersect(c, d, a, b) { - var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); - return [ x1 + ua * x21, y1 + ua * y21 ]; + function d3_svg_lineLinearClosed(points) { + return points.join("L") + "Z"; } - function d3_geom_polygonClosed(coordinates) { - var a = coordinates[0], b = coordinates[coordinates.length - 1]; - return !(a[0] - b[0] || a[1] - b[1]); + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); } - var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; - function d3_geom_voronoiBeach() { - d3_geom_voronoiRedBlackNode(this); - this.edge = this.site = this.circle = null; + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); } - function d3_geom_voronoiCreateBeach(site) { - var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); - beach.site = site; - return beach; + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); } - function d3_geom_voronoiDetachBeach(beach) { - d3_geom_voronoiDetachCircle(beach); - d3_geom_voronoiBeaches.remove(beach); - d3_geom_voronoiBeachPool.push(beach); - d3_geom_voronoiRedBlackNode(beach); + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); } - function d3_geom_voronoiRemoveBeach(beach) { - var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { - x: x, - y: y - }, previous = beach.P, next = beach.N, disappearing = [ beach ]; - d3_geom_voronoiDetachBeach(beach); - var lArc = previous; - while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { - previous = lArc.P; - disappearing.unshift(lArc); - d3_geom_voronoiDetachBeach(lArc); - lArc = previous; - } - disappearing.unshift(lArc); - d3_geom_voronoiDetachCircle(lArc); - var rArc = next; - while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { - next = rArc.N; - disappearing.push(rArc); - d3_geom_voronoiDetachBeach(rArc); - rArc = next; + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); } - disappearing.push(rArc); - d3_geom_voronoiDetachCircle(rArc); - var nArcs = disappearing.length, iArc; - for (iArc = 1; iArc < nArcs; ++iArc) { - rArc = disappearing[iArc]; - lArc = disappearing[iArc - 1]; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; } - lArc = disappearing[0]; - rArc = disappearing[nArcs - 1]; - rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - } - function d3_geom_voronoiAddBeach(site) { - var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; - while (node) { - dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; - if (dxl > ε) node = node.L; else { - dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); - if (dxr > ε) { - if (!node.R) { - lArc = node; - break; - } - node = node.R; - } else { - if (dxl > -ε) { - lArc = node.P; - rArc = node; - } else if (dxr > -ε) { - lArc = node; - rArc = node.N; - } else { - lArc = rArc = node; - } - break; - } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; } } - var newArc = d3_geom_voronoiCreateBeach(site); - d3_geom_voronoiBeaches.insert(lArc, newArc); - if (!lArc && !rArc) return; - if (lArc === rArc) { - d3_geom_voronoiDetachCircle(lArc); - rArc = d3_geom_voronoiCreateBeach(lArc.site); - d3_geom_voronoiBeaches.insert(newArc, rArc); - newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - return; - } - if (!rArc) { - newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - return; + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; } - d3_geom_voronoiDetachCircle(lArc); - d3_geom_voronoiDetachCircle(rArc); - var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { - x: (cy * hb - by * hc) / d + ax, - y: (bx * hc - cx * hb) / d + ay - }; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); - newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); - rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); + return path; } - function d3_geom_voronoiLeftBreakPoint(arc, directrix) { - var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; - if (!pby2) return rfocx; - var lArc = arc.P; - if (!lArc) return -Infinity; - site = lArc.site; - var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; - if (!plby2) return lfocx; - var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; - if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; - return (rfocx + lfocx) / 2; + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; } - function d3_geom_voronoiRightBreakPoint(arc, directrix) { - var rArc = arc.N; - if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); - var site = arc.site; - return site.y === directrix ? site.x : Infinity; + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); } - function d3_geom_voronoiCell(site) { - this.site = site; - this.edges = []; + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); } - d3_geom_voronoiCell.prototype.prepare = function() { - var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; - while (iHalfEdge--) { - edge = halfEdges[iHalfEdge].edge; - if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); } - halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); - return halfEdges.length; - }; - function d3_geom_voronoiCloseCells(extent) { - var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; - while (iCell--) { - cell = cells[iCell]; - if (!cell || !cell.prepare()) continue; - halfEdges = cell.edges; - nHalfEdges = halfEdges.length; - iHalfEdge = 0; - while (iHalfEdge < nHalfEdges) { - end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; - start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; - if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { - halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { - x: x0, - y: abs(x2 - x0) < ε ? y2 : y1 - } : abs(y3 - y1) < ε && x1 - x3 > ε ? { - x: abs(y2 - y1) < ε ? x2 : x1, - y: y1 - } : abs(x3 - x1) < ε && y3 - y0 > ε ? { - x: x1, - y: abs(x2 - x1) < ε ? y2 : y0 - } : abs(y3 - y0) < ε && x3 - x0 > ε ? { - x: abs(y2 - y0) < ε ? x2 : x0, - y: y0 - } : null), cell.site, null)); - ++nHalfEdges; - } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); } } + return d3_svg_lineBasis(points); } - function d3_geom_voronoiHalfEdgeOrder(a, b) { - return b.angle - a.angle; + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } - function d3_geom_voronoiCircle() { - d3_geom_voronoiRedBlackNode(this); - this.x = this.y = this.arc = this.site = this.cy = null; + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); } - function d3_geom_voronoiAttachCircle(arc) { - var lArc = arc.P, rArc = arc.N; - if (!lArc || !rArc) return; - var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; - if (lSite === rSite) return; - var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; - var d = 2 * (ax * cy - ay * cx); - if (d >= -ε2) return; - var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; - var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); - circle.arc = arc; - circle.site = cSite; - circle.x = x + bx; - circle.y = cy + Math.sqrt(x * x + y * y); - circle.cy = cy; - arc.circle = circle; - var before = null, node = d3_geom_voronoiCircles._; - while (node) { - if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { - if (node.L) node = node.L; else { - before = node.P; - break; - } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; } else { - if (node.R) node = node.R; else { - before = node; - break; + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; } } } - d3_geom_voronoiCircles.insert(before, circle); - if (!before) d3_geom_voronoiFirstCircle = circle; - } - function d3_geom_voronoiDetachCircle(arc) { - var circle = arc.circle; - if (circle) { - if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; - d3_geom_voronoiCircles.remove(circle); - d3_geom_voronoiCirclePool.push(circle); - d3_geom_voronoiRedBlackNode(circle); - arc.circle = null; + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); } + return tangents; } - function d3_geom_voronoiClipEdges(extent) { - var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; - while (i--) { - e = edges[i]; - if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { - e.a = e.b = null; - edges.splice(i, 1); - } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] - halfπ; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); } + return points; } - function d3_geom_voronoiConnectEdge(edge, extent) { - var vb = edge.b; - if (vb) return true; - var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; - if (ry === ly) { - if (fx < x0 || fx >= x1) return; - if (lx > rx) { - if (!va) va = { - x: fx, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: fx, - y: y1 - }; - } else { - if (!va) va = { - x: fx, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: fx, - y: y0 - }; + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); } - } else { - fm = (lx - rx) / (ry - ly); - fb = fy - fm * fx; - if (fm < -1 || fm > 1) { - if (lx > rx) { - if (!va) va = { - x: (y0 - fb) / fm, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: (y1 - fb) / fm, - y: y1 - }; - } else { - if (!va) va = { - x: (y1 - fb) / fm, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: (y0 - fb) / fm, - y: y0 - }; - } - } else { - if (ly < ry) { - if (!va) va = { - x: x0, - y: fm * x0 + fb - }; else if (va.x >= x1) return; - vb = { - x: x1, - y: fm * x1 + fb - }; - } else { - if (!va) va = { - x: x1, - y: fm * x1 + fb - }; else if (va.x < x0) return; - vb = { - x: x0, - y: fm * x0 + fb - }; + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; } } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; } - edge.a = va; - edge.b = vb; - return true; + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; } - function d3_geom_voronoiEdge(lSite, rSite) { - this.l = lSite; - this.r = rSite; - this.a = this.b = null; + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; + } + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; } - function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, rSite); - d3_geom_voronoiEdges.push(edge); - if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); - if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); - d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); - d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); - return edge; + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; } - function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, null); - edge.a = va; - edge.b = vb; - d3_geom_voronoiEdges.push(edge); - return edge; + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; } - function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { - if (!edge.a && !edge.b) { - edge.a = vertex; - edge.l = lSite; - edge.r = rSite; - } else if (edge.l === rSite) { - edge.b = vertex; - } else { - edge.a = vertex; + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; } - function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { - var va = edge.a, vb = edge.b; - this.edge = edge; - this.site = lSite; - this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + function d3_svg_symbolType() { + return "circle"; } - d3_geom_voronoiHalfEdge.prototype = { - start: function() { - return this.edge.l === this.site ? this.edge.a : this.edge.b; + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; }, - end: function() { - return this.edge.l === this.site ? this.edge.b : this.edge.a; + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + d3_selectionPrototype.transition = function(name) { + var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); + subgroup.push(node); + } } + return d3_transition(subgroups, ns, id); }; - function d3_geom_voronoiRedBlackTree() { - this._ = null; + d3_selectionPrototype.interrupt = function(name) { + return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); + }; + var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); + function d3_selection_interruptNS(ns) { + return function() { + var lock, activeId, active; + if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { + active.timer.c = null; + active.timer.t = NaN; + if (--lock.count) delete lock[activeId]; else delete this[ns]; + lock.active += .5; + active.event && active.event.interrupt.call(this, this.__data__, active.index); + } + }; } - function d3_geom_voronoiRedBlackNode(node) { - node.U = node.C = node.L = node.R = node.P = node.N = null; + function d3_transition(groups, ns, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.namespace = ns; + groups.id = id; + return groups; } - d3_geom_voronoiRedBlackTree.prototype = { - insert: function(after, node) { - var parent, grandpa, uncle; - if (after) { - node.P = after; - node.N = after.N; - if (after.N) after.N.P = node; - after.N = node; - if (after.R) { - after = after.R; - while (after.L) after = after.L; - after.L = node; + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection, name) { + return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, ns, id, node[ns][id]); + subgroup.push(subnode); } else { - after.R = node; + subgroup.push(null); } - parent = after; - } else if (this._) { - after = d3_geom_voronoiRedBlackFirst(this._); - node.P = null; - node.N = after; - after.P = after.L = node; - parent = after; - } else { - node.P = node.N = null; - this._ = node; - parent = null; } - node.L = node.R = null; - node.U = parent; - node.C = true; - after = node; - while (parent && parent.C) { - grandpa = parent.U; - if (parent === grandpa.L) { - uncle = grandpa.R; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.R) { - d3_geom_voronoiRedBlackRotateLeft(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateRight(this, grandpa); - } - } else { - uncle = grandpa.L; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.L) { - d3_geom_voronoiRedBlackRotateRight(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node[ns][id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); + subgroup.push(subnode); } } - parent = after.U; - } - this._.C = false; - }, - remove: function(node) { - if (node.N) node.N.P = node.P; - if (node.P) node.P.N = node.N; - node.N = node.P = null; - var parent = node.U, sibling, left = node.L, right = node.R, next, red; - if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); - if (parent) { - if (parent.L === node) parent.L = next; else parent.R = next; - } else { - this._ = next; } - if (left && right) { - red = next.C; - next.C = node.C; - next.L = left; - left.U = next; - if (next !== right) { - parent = next.U; - next.U = node.U; - node = next.R; - parent.L = node; - next.R = right; - right.U = next; - } else { - next.U = parent; - parent = next; - node = next.R; + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); } - } else { - red = node.C; - node = next; - } - if (node) node.U = parent; - if (red) return; - if (node && node.C) { - node.C = false; - return; } - do { - if (node === this._) break; - if (node === parent.L) { - sibling = parent.R; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - sibling = parent.R; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.R || !sibling.R.C) { - sibling.L.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateRight(this, sibling); - sibling = parent.R; - } - sibling.C = parent.C; - parent.C = sibling.R.C = false; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - node = this._; - break; - } - } else { - sibling = parent.L; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateRight(this, parent); - sibling = parent.L; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.L || !sibling.L.C) { - sibling.R.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, sibling); - sibling = parent.L; - } - sibling.C = parent.C; - parent.C = sibling.L.C = false; - d3_geom_voronoiRedBlackRotateRight(this, parent); - node = this._; - break; - } - } - sibling.C = true; - node = parent; - parent = parent.U; - } while (!node.C); - if (node) node.C = false; } + return d3_transition(subgroups, this.namespace, this.id); + }; + d3_transitionPrototype.tween = function(name, tween) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) return this.node()[ns][id].tween.get(name); + return d3_selection_each(this, tween == null ? function(node) { + node[ns][id].tween.remove(name); + } : function(node) { + node[ns][id].tween.set(name, tween); + }); + }; + function d3_transition_tween(groups, name, value, tween) { + var id = groups.id, ns = groups.namespace; + return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { + node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); + } : (value = tween(value), function(node) { + node[ns][id].tween.set(name, value); + })); + } + d3_transitionPrototype.attr = function(nameNS, value) { + if (arguments.length < 2) { + for (value in nameNS) this.attr(value, nameNS[value]); + return this; + } + var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); }; - function d3_geom_voronoiRedBlackRotateLeft(tree, node) { - var p = node, q = node.R, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; - } else { - tree._ = q; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; } - q.U = parent; - p.U = q; - p.R = q.L; - if (p.R) p.R.U = p; - q.L = p; + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; } - function d3_geom_voronoiRedBlackRotateRight(tree, node) { - var p = node, q = node.L, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; + d3_transitionPrototype.remove = function() { + var ns = this.namespace; + return this.each("end.transition", function() { + var p; + if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node[ns][id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].delay; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node[ns][id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].duration; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node[ns][id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + try { + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node[ns][id]; + type.call(node, node.__data__, i, j); + }); + } finally { + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } } else { - tree._ = q; + d3_selection_each(this, function(node) { + var transition = node[ns][id]; + (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); + }); } - q.U = parent; - p.U = q; - p.L = q.R; - if (p.L) p.L.U = p; - q.R = p; - } - function d3_geom_voronoiRedBlackFirst(node) { - while (node.L) node = node.L; - return node; - } - function d3_geom_voronoi(sites, bbox) { - var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; - d3_geom_voronoiEdges = []; - d3_geom_voronoiCells = new Array(sites.length); - d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); - d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); - while (true) { - circle = d3_geom_voronoiFirstCircle; - if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { - if (site.x !== x0 || site.y !== y0) { - d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); - d3_geom_voronoiAddBeach(site); - x0 = site.x, y0 = site.y; + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition = node[ns][id0]; + d3_transitionNode(node, i, ns, id1, { + time: transition.time, + ease: transition.ease, + delay: transition.delay + transition.duration, + duration: transition.duration + }); } - site = sites.pop(); - } else if (circle) { - d3_geom_voronoiRemoveBeach(circle.arc); - } else { - break; + subgroup.push(node); } } - if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); - var diagram = { - cells: d3_geom_voronoiCells, - edges: d3_geom_voronoiEdges - }; - d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; - return diagram; - } - function d3_geom_voronoiVertexOrder(a, b) { - return b.y - a.y || b.x - a.x; + return d3_transition(subgroups, ns, id1); + }; + function d3_transitionNamespace(name) { + return name == null ? "__transition__" : "__transition_" + name + "__"; } - d3.geom.voronoi = function(points) { - var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; - if (points) return voronoi(points); - function voronoi(data) { - var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; - d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { - var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { - var s = e.start(); - return [ s.x, s.y ]; - }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; - polygon.point = data[i]; - }); - return polygons; + function d3_transitionNode(node, i, ns, id, inherit) { + var lock = node[ns] || (node[ns] = { + active: 0, + count: 0 + }), transition = lock[id], time, timer, duration, ease, tweens; + function schedule(elapsed) { + var delay = transition.delay; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; } - function sites(data) { - return data.map(function(d, i) { - return { - x: Math.round(fx(d, i) / ε) * ε, - y: Math.round(fy(d, i) / ε) * ε, - i: i - }; + function start(elapsed) { + var activeId = lock.active, active = lock[activeId]; + if (active) { + active.timer.c = null; + active.timer.t = NaN; + --lock.count; + delete lock[activeId]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + for (var cancelId in lock) { + if (+cancelId < id) { + var cancel = lock[cancelId]; + cancel.timer.c = null; + cancel.timer.t = NaN; + --lock.count; + delete lock[cancelId]; + } + } + timer.c = tick; + d3_timer(function() { + if (timer.c && tick(elapsed || 1)) { + timer.c = null; + timer.t = NaN; + } + return 1; + }, 0, time); + lock.active = id; + transition.event && transition.event.start.call(node, node.__data__, i); + tweens = []; + transition.tween.forEach(function(key, value) { + if (value = value.call(node, node.__data__, i)) { + tweens.push(value); + } }); + ease = transition.ease; + duration = transition.duration; } - voronoi.links = function(data) { - return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { - return edge.l && edge.r; - }).map(function(edge) { - return { - source: data[edge.l.i], - target: data[edge.r.i] - }; - }); - }; - voronoi.triangles = function(data) { - var triangles = []; - d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { - var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; - while (++j < m) { - e0 = e1; - s0 = s1; - e1 = edges[j].edge; - s1 = e1.l === site ? e1.r : e1.l; - if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { - triangles.push([ data[i], data[s0.i], data[s1.i] ]); - } + function tick(elapsed) { + var t = elapsed / duration, e = ease(t), n = tweens.length; + while (n > 0) { + tweens[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; + } + } + if (!transition) { + time = inherit.time; + timer = d3_timer(schedule, 0, time); + transition = lock[id] = { + tween: new d3_Map(), + time: time, + timer: timer, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + } + } + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; + if (orient === "bottom" || orient === "top") { + tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; + text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); + } else { + tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; + text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); + pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); + } + lineEnter.attr(y2, sign * innerTickSize); + textEnter.attr(y1, sign * tickSpacing); + lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); + textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1, scale0); } + tickEnter.call(tickTransform, scale0, scale1); + tickUpdate.call(tickTransform, scale1, scale1); }); - return triangles; + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; }; - voronoi.x = function(_) { - return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; }; - voronoi.y = function(_) { - return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = d3_array(arguments); + return axis; }; - voronoi.clipExtent = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; - clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; - return voronoi; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; }; - voronoi.size = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; - return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; }; - return voronoi; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; }; - var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; - function d3_geom_voronoiTriangleArea(a, b, c) { - return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); - } - d3.geom.delaunay = function(vertices) { - return d3.geom.voronoi().triangles(vertices); + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 }; - d3.geom.quadtree = function(points, x1, y1, x2, y2) { - var x = d3_geom_pointX, y = d3_geom_pointY, compat; - if (compat = arguments.length) { - x = d3_geom_quadtreeCompatX; - y = d3_geom_quadtreeCompatY; - if (compat === 3) { - y2 = y1; - x2 = x1; - y1 = x1 = 0; - } - return quadtree(points); + function d3_svg_axisX(selection, x0, x1) { + selection.attr("transform", function(d) { + var v0 = x0(d); + return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; + }); + } + function d3_svg_axisY(selection, y0, y1) { + selection.attr("transform", function(d) { + var v0 = y0(d); + return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; + }); + } + d3.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background = g.selectAll(".background").data([ 0 ]); + background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize = g.selectAll(".resize").data(resizes, d3_identity); + resize.exit().remove(); + resize.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); } - function quadtree(data) { - var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; - if (x1 != null) { - x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; + var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d3.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); } else { - x2_ = y2_ = -(x1_ = y1_ = Infinity); - xs = [], ys = []; - n = data.length; - if (compat) for (i = 0; i < n; ++i) { - d = data[i]; - if (d.x < x1_) x1_ = d.x; - if (d.y < y1_) y1_ = d.y; - if (d.x > x2_) x2_ = d.x; - if (d.y > y2_) y2_ = d.y; - xs.push(d.x); - ys.push(d.y); - } else for (i = 0; i < n; ++i) { - var x_ = +fx(d = data[i], i), y_ = +fy(d, i); - if (x_ < x1_) x1_ = x_; - if (y_ < y1_) y1_ = y_; - if (x_ > x2_) x2_ = x_; - if (y_ > y2_) y2_ = y_; - xs.push(x_); - ys.push(y_); + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d3.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d3.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d3.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); } } - var dx = x2_ - x1_, dy = y2_ - y1_; - if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; - function insert(n, d, x, y, x1, y1, x2, y2) { - if (isNaN(x) || isNaN(y)) return; - if (n.leaf) { - var nx = n.x, ny = n.y; - if (nx != null) { - if (abs(nx - x) + abs(ny - y) < .01) { - insertChild(n, d, x, y, x1, y1, x2, y2); - } else { - var nPoint = n.point; - n.x = n.y = n.point = null; - insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); - insertChild(n, d, x, y, x1, y1, x2, y2); - } + function keyup() { + if (d3.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d3.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d3.event.altKey) { + if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale, i) { + var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; } else { - n.x = x, n.y = y, n.point = d; + max = position; } - } else { - insertChild(n, d, x, y, x1, y1, x2, y2); + } + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; + return true; } } - function insertChild(n, d, x, y, x1, y1, x2, y2) { - var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; - n.leaf = false; - n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); - if (right) x1 = xm; else x2 = xm; - if (below) y1 = ym; else y2 = ym; - insert(n, d, x, y, x1, y1, x2, y2); + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d3.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); } - var root = d3_geom_quadtreeNode(); - root.add = function(d) { - insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); - }; - root.visit = function(f) { - d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); - }; - root.find = function(point) { - return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); - }; - i = -1; - if (x1 == null) { - while (++i < n) { - insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); - } - --i; - } else data.forEach(root.add); - xs = ys = data = d = null; - return root; } - quadtree.x = function(_) { - return arguments.length ? (x = _, quadtree) : x; - }; - quadtree.y = function(_) { - return arguments.length ? (y = _, quadtree) : y; - }; - quadtree.extent = function(_) { - if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], - y2 = +_[1][1]; - return quadtree; + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; }; - quadtree.size = function(_) { - if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; - return quadtree; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; }; - return quadtree; - }; - function d3_geom_quadtreeCompatX(d) { - return d.x; - } - function d3_geom_quadtreeCompatY(d) { - return d.y; - } - function d3_geom_quadtreeNode() { - return { - leaf: true, - nodes: [], - point: null, - x: null, - y: null + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; + return brush; }; - } - function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { - if (!f(node, x1, y1, x2, y2)) { - var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; - if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); - if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); - if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); - if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); - } - } - function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { - var minDistance2 = Infinity, closestPoint; - (function find(node, x1, y1, x2, y2) { - if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; - if (point = node.point) { - var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; - if (distance2 < minDistance2) { - var distance = Math.sqrt(minDistance2 = distance2); - x0 = x - distance, y0 = y - distance; - x3 = x + distance, y3 = y + distance; - closestPoint = point; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } } - } - var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; - for (var i = below << 1 | right, j = i + 4; i < j; ++i) { - if (node = children[i & 3]) switch (i & 3) { - case 0: - find(node, x1, y1, xm, ym); - break; - - case 1: - find(node, xm, y1, x2, ym); - break; - - case 2: - find(node, x1, ym, xm, y2); - break; - - case 3: - find(node, xm, ym, x2, y2); - break; + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } } + return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; } - })(root, x0, y0, x3, y3); - return closestPoint; - } - d3.interpolateRgb = d3_interpolateRgb; - function d3_interpolateRgb(a, b) { - a = d3.rgb(a); - b = d3.rgb(b); - var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; - return function(t) { - return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); - }; - } - d3.interpolateObject = d3_interpolateObject; - function d3_interpolateObject(a, b) { - var i = {}, c = {}, k; - for (k in a) { - if (k in b) { - i[k] = d3_interpolate(a[k], b[k]); - } else { - c[k] = a[k]; + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [ x0, x1 ]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; } - } - for (k in b) { - if (!(k in a)) { - c[k] = b[k]; + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [ y0, y1 ]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; } - } - return function(t) { - for (k in i) c[k] = i[k](t); - return c; - }; - } - d3.interpolateNumber = d3_interpolateNumber; - function d3_interpolateNumber(a, b) { - a = +a, b = +b; - return function(t) { - return a * (1 - t) + b * t; + return brush; }; - } - d3.interpolateString = d3_interpolateString; - function d3_interpolateString(a, b) { - var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; - a = a + "", b = b + ""; - while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { - if ((bs = bm.index) > bi) { - bs = b.slice(bi, bs); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - if ((am = am[0]) === (bm = bm[0])) { - if (s[i]) s[i] += bm; else s[++i] = bm; - } else { - s[++i] = null; - q.push({ - i: i, - x: d3_interpolateNumber(am, bm) - }); + brush.clear = function() { + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; } - bi = d3_interpolate_numberB.lastIndex; - } - if (bi < b.length) { - bs = b.slice(bi); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { - return b(t) + ""; - }) : function() { - return b; - } : (b = q.length, function(t) { - for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }); - } - var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); - d3.interpolate = d3_interpolate; - function d3_interpolate(a, b) { - var i = d3.interpolators.length, f; - while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; - return f; - } - d3.interpolators = [ function(a, b) { - var t = typeof b; - return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); - } ]; - d3.interpolateArray = d3_interpolateArray; - function d3_interpolateArray(a, b) { - var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; - for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); - for (;i < na; ++i) c[i] = a[i]; - for (;i < nb; ++i) c[i] = b[i]; - return function(t) { - for (i = 0; i < n0; ++i) c[i] = x[i](t); - return c; + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; }; + return d3.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; + var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; + var d3_time_formatUtc = d3_time_format.utc; + var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); + d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; + function d3_time_formatIsoNative(date) { + return date.toISOString(); } - var d3_ease_default = function() { - return d3_identity; + d3_time_formatIsoNative.parse = function(string) { + var date = new Date(string); + return isNaN(date) ? null : date; }; - var d3_ease = d3.map({ - linear: d3_ease_default, - poly: d3_ease_poly, - quad: function() { - return d3_ease_quad; - }, - cubic: function() { - return d3_ease_cubic; - }, - sin: function() { - return d3_ease_sin; - }, - exp: function() { - return d3_ease_exp; - }, - circle: function() { - return d3_ease_circle; - }, - elastic: d3_ease_elastic, - back: d3_ease_back, - bounce: function() { - return d3_ease_bounce; - } + d3_time_formatIsoNative.toString = d3_time_formatIso.toString; + d3_time.second = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 1e3) * 1e3); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 1e3); + }, function(date) { + return date.getSeconds(); }); - var d3_ease_mode = d3.map({ - "in": d3_identity, - out: d3_ease_reverse, - "in-out": d3_ease_reflect, - "out-in": function(f) { - return d3_ease_reflect(d3_ease_reverse(f)); - } + d3_time.seconds = d3_time.second.range; + d3_time.seconds.utc = d3_time.second.utc.range; + d3_time.minute = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 6e4) * 6e4); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 6e4); + }, function(date) { + return date.getMinutes(); }); - d3.ease = function(name) { - var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; - t = d3_ease.get(t) || d3_ease_default; - m = d3_ease_mode.get(m) || d3_identity; - return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); - }; - function d3_ease_clamp(f) { - return function(t) { - return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + d3_time.minutes = d3_time.minute.range; + d3_time.minutes.utc = d3_time.minute.utc.range; + d3_time.hour = d3_time_interval(function(date) { + var timezone = date.getTimezoneOffset() / 60; + return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 36e5); + }, function(date) { + return date.getHours(); + }); + d3_time.hours = d3_time.hour.range; + d3_time.hours.utc = d3_time.hour.utc.range; + d3_time.month = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setDate(1); + return date; + }, function(date, offset) { + date.setMonth(date.getMonth() + offset); + }, function(date) { + return date.getMonth(); + }); + d3_time.months = d3_time.month.range; + d3_time.months.utc = d3_time.month.utc.range; + function d3_time_scale(linear, methods, format) { + function scale(x) { + return linear(x); + } + scale.invert = function(x) { + return d3_time_scaleDate(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return linear.domain().map(d3_time_scaleDate); + linear.domain(x); + return scale; + }; + function tickMethod(extent, count) { + var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); + return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { + return d / 31536e6; + }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + } + scale.nice = function(interval, skip) { + var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); + if (method) interval = method[0], skip = method[1]; + function skipped(date) { + return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; + } + return scale.domain(d3_scale_nice(domain, skip > 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); }; - } - function d3_ease_reverse(f) { - return function(t) { - return 1 - f(1 - t); + scale.tickFormat = function() { + return format; }; - } - function d3_ease_reflect(f) { - return function(t) { - return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); }; + return d3_scale_linearRebind(scale, linear); } - function d3_ease_quad(t) { - return t * t; + function d3_time_scaleDate(t) { + return new Date(t); } - function d3_ease_cubic(t) { - return t * t * t; + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { + return d.getMilliseconds(); + } ], [ ":%S", function(d) { + return d.getSeconds(); + } ], [ "%I:%M", function(d) { + return d.getMinutes(); + } ], [ "%I %p", function(d) { + return d.getHours(); + } ], [ "%a %d", function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ "%b %d", function(d) { + return d.getDate() != 1; + } ], [ "%B", function(d) { + return d.getMonth(); + } ], [ "%Y", d3_true ] ]); + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { + return d.getUTCMilliseconds(); + } ], [ ":%S", function(d) { + return d.getUTCSeconds(); + } ], [ "%I:%M", function(d) { + return d.getUTCMinutes(); + } ], [ "%I %p", function(d) { + return d.getUTCHours(); + } ], [ "%a %d", function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ "%b %d", function(d) { + return d.getUTCDate() != 1; + } ], [ "%B", function(d) { + return d.getUTCMonth(); + } ], [ "%Y", d3_true ] ]); + d3_time_scaleUtcMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); } - function d3_ease_cubicInOut(t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - var t2 = t * t, t3 = t2 * t; - return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); } - function d3_ease_poly(e) { - return function(t) { - return Math.pow(t, e); - }; + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; +}(); +},{}],83:[function(require,module,exports){ +arguments[4][76][0].apply(exports,arguments) +},{"dup":76,"robust-orientation":1040,"simplicial-complex":86}],84:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],85:[function(require,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],86:[function(require,module,exports){ +arguments[4][79][0].apply(exports,arguments) +},{"bit-twiddle":84,"dup":79,"union-find":85}],87:[function(require,module,exports){ +"use strict" + +function unique_pred(list, compare) { + var ptr = 1 + , len = list.length + , a=list[0], b=list[0] + for(var i=1; i 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; - }; + var lifted = points.map(function(p, i) { + return [ p[0], i ] + }) + lifted.sort(function(a,b) { + return a[0] - b[0] + }) + var cells = new Array(n - 1) + for(var i=1; i 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; - }; + if(includePointAtInfinity) { + cells.push( + [ -1, cells[0][1], ], + [ cells[n-1][1], -1 ]) } - d3.interpolateLab = d3_interpolateLab; - function d3_interpolateLab(a, b) { - a = d3.lab(a); - b = d3.lab(b); - var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; - return function(t) { - return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; - }; + return cells +} + +function triangulate(points, includePointAtInfinity) { + var n = points.length + if(n === 0) { + return [] } - d3.interpolateRound = d3_interpolateRound; - function d3_interpolateRound(a, b) { - b -= a; - return function(t) { - return Math.round(a + b * t); - }; + + var d = points[0].length + if(d < 1) { + return [] } - d3.transform = function(string) { - var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); - return (d3.transform = function(string) { - if (string != null) { - g.setAttribute("transform", string); - var t = g.transform.baseVal.consolidate(); - } - return new d3_transform(t ? t.matrix : d3_transformIdentity); - })(string); - }; - function d3_transform(m) { - var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; - if (r0[0] * r1[1] < r1[0] * r0[1]) { - r0[0] *= -1; - r0[1] *= -1; - kx *= -1; - kz *= -1; + + //Special case: For 1D we can just sort the points + if(d === 1) { + return triangulate1D(n, points, includePointAtInfinity) + } + + //Lift points, sort + var lifted = new Array(n) + var upper = 1.0 + for(var i=0; i= 2) { + return false + } + } + cell[j] = v + } + return true + }) + } else { + hull = hull.filter(function(cell) { + for(var i=0; i<=d; ++i) { + var v = dindex[cell[i]] + if(v < 0) { + return false + } + cell[i] = v + } + return true + }) } - function d3_interpolateTranslate(ta, tb, s, q) { - if (ta[0] !== tb[0] || ta[1] !== tb[1]) { - var i = s.push("translate(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ta[0], tb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ta[1], tb[1]) - }); - } else if (tb[0] || tb[1]) { - s.push("translate(" + tb + ")"); + + if(d & 1) { + for(var i=0; i 180) rb += 360; else if (rb - ra > 180) ra += 360; - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, - x: d3_interpolateNumber(ra, rb) - }); - } else if (rb) { - s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); + + return hull +} +},{"incremental-convex-hull":83,"uniq":87}],89:[function(require,module,exports){ +(function (process,global){ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.2.1 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); } - } - function d3_interpolateSkew(wa, wb, s, q) { - if (wa !== wb) { - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, - x: d3_interpolateNumber(wa, wb) - }); - } else if (wb) { - s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; } - } - function d3_interpolateScale(ka, kb, s, q) { - if (ka[0] !== kb[0] || ka[1] !== kb[1]) { - var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ka[0], kb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ka[1], kb[1]) - }); - } else if (kb[0] !== 1 || kb[1] !== 1) { - s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; } - } - function d3_interpolateTransform(a, b) { - var s = [], q = []; - a = d3.transform(a), b = d3.transform(b); - d3_interpolateTranslate(a.translate, b.translate, s, q); - d3_interpolateRotate(a.rotate, b.rotate, s, q); - d3_interpolateSkew(a.skew, b.skew, s, q); - d3_interpolateScale(a.scale, b.scale, s, q); - a = b = null; - return function(t) { - var i = -1, n = q.length, o; - while (++i < n) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }; - } - function d3_uninterpolateNumber(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return (x - a) / b; - }; - } - function d3_uninterpolateClamp(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return Math.max(0, Math.min(1, (x - a) / b)); - }; - } - d3.layout = {}; - d3.layout.bundle = function() { - return function(links) { - var paths = [], i = -1, n = links.length; - while (++i < n) paths.push(d3_layout_bundlePath(links[i])); - return paths; - }; - }; - function d3_layout_bundlePath(link) { - var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; - while (start !== lca) { - start = start.parent; - points.push(start); + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; } - var k = points.length; - while (end !== lca) { - points.splice(k, 0, end); - end = end.parent; + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; } - return points; - } - function d3_layout_bundleAncestors(node) { - var ancestors = [], parent = node.parent; - while (parent != null) { - ancestors.push(node); - node = parent; - parent = parent.parent; + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; } - ancestors.push(node); - return ancestors; - } - function d3_layout_bundleLeastCommonAncestor(a, b) { - if (a === b) return a; - var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; - while (aNode === bNode) { - sharedNode = aNode; - aNode = aNodes.pop(); - bNode = bNodes.pop(); + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; } - return sharedNode; - } - d3.layout.chord = function() { - var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; - function relayout() { - var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; - chords = []; - groups = []; - k = 0, i = -1; - while (++i < n) { - x = 0, j = -1; - while (++j < n) { - x += matrix[i][j]; - } - groupSums.push(x); - subgroupIndex.push(d3.range(n)); - k += x; + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; } - if (sortGroups) { - groupIndex.sort(function(a, b) { - return sortGroups(groupSums[a], groupSums[b]); - }); + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); } - if (sortSubgroups) { - subgroupIndex.forEach(function(d, i) { - d.sort(function(a, b) { - return sortSubgroups(matrix[i][a], matrix[i][b]); - }); - }); + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + function lib$es6$promise$then$$then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + + if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { + lib$es6$promise$$internal$$makePromise(child); } - k = (τ - padding * n) / k; - x = 0, i = -1; - while (++i < n) { - x0 = x, j = -1; - while (++j < n) { - var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; - subgroups[di + "-" + dj] = { - index: di, - subindex: dj, - startAngle: a0, - endAngle: a1, - value: v - }; - } - groups[di] = { - index: di, - startAngle: x0, - endAngle: x, - value: groupSums[di] - }; - x += padding; + + var state = parent._state; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); } - i = -1; - while (++i < n) { - j = i - 1; - while (++j < n) { - var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; - if (source.value || target.value) { - chords.push(source.value < target.value ? { - source: target, - target: source - } : { - source: source, - target: target - }); - } - } + + return child; + } + var lib$es6$promise$then$$default = lib$es6$promise$then$$then; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; } - if (sortChords) resort(); + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; } - function resort() { - chords.sort(function(a, b) { - return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); - }); + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); } - chord.matrix = function(x) { - if (!arguments.length) return matrix; - n = (matrix = x) && matrix.length; - chords = groups = null; - return chord; - }; - chord.padding = function(x) { - if (!arguments.length) return padding; - padding = x; - chords = groups = null; - return chord; - }; - chord.sortGroups = function(x) { - if (!arguments.length) return sortGroups; - sortGroups = x; - chords = groups = null; - return chord; - }; - chord.sortSubgroups = function(x) { - if (!arguments.length) return sortSubgroups; - sortSubgroups = x; - chords = null; - return chord; - }; - chord.sortChords = function(x) { - if (!arguments.length) return sortChords; - sortChords = x; - if (chords) resort(); - return chord; - }; - chord.chords = function() { - if (!chords) relayout(); - return chords; - }; - chord.groups = function() { - if (!groups) relayout(); - return groups; - }; - return chord; - }; - d3.layout.force = function() { - var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; - function repulse(node) { - return function(quad, x1, _, x2) { - if (quad.point !== node) { - var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; - if (dw * dw / theta2 < dn) { - if (dn < chargeDistance2) { - var k = quad.charge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - return true; - } - if (quad.point && dn && dn < chargeDistance2) { - var k = quad.pointCharge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - } - return !quad.charge; - }; + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); } - force.tick = function() { - if ((alpha *= .99) < .005) { - timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); - return true; - } - var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; - for (i = 0; i < m; ++i) { - o = links[i]; - s = o.source; - t = o.target; - x = t.x - s.x; - y = t.y - s.y; - if (l = x * x + y * y) { - l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; - x *= l; - y *= l; - t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); - t.y -= y * k; - s.x += x * (k = 1 - k); - s.y += y * k; - } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; } - if (k = alpha * gravity) { - x = size[0] / 2; - y = size[1] / 2; - i = -1; - if (k) while (++i < n) { - o = nodes[i]; - o.x += (x - o.x) * k; - o.y += (y - o.y) * k; - } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; } - if (charge) { - d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); - i = -1; - while (++i < n) { - if (!(o = nodes[i]).fixed) { - q.visit(repulse(o)); + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); } - i = -1; - while (++i < n) { - o = nodes[i]; - if (o.fixed) { - o.x = o.px; - o.y = o.py; - } else { - o.x -= (o.px - (o.px = o.x)) * friction; - o.y -= (o.py - (o.py = o.y)) * friction; - } - } - event.tick({ - type: "tick", - alpha: alpha - }); - }; - force.nodes = function(x) { - if (!arguments.length) return nodes; - nodes = x; - return force; - }; - force.links = function(x) { - if (!arguments.length) return links; - links = x; - return force; - }; - force.size = function(x) { - if (!arguments.length) return size; - size = x; - return force; - }; - force.linkDistance = function(x) { - if (!arguments.length) return linkDistance; - linkDistance = typeof x === "function" ? x : +x; - return force; - }; - force.distance = force.linkDistance; - force.linkStrength = function(x) { - if (!arguments.length) return linkStrength; - linkStrength = typeof x === "function" ? x : +x; - return force; - }; - force.friction = function(x) { - if (!arguments.length) return friction; - friction = +x; - return force; - }; - force.charge = function(x) { - if (!arguments.length) return charge; - charge = typeof x === "function" ? x : +x; - return force; - }; - force.chargeDistance = function(x) { - if (!arguments.length) return Math.sqrt(chargeDistance2); - chargeDistance2 = x * x; - return force; - }; - force.gravity = function(x) { - if (!arguments.length) return gravity; - gravity = +x; - return force; - }; - force.theta = function(x) { - if (!arguments.length) return Math.sqrt(theta2); - theta2 = x * x; - return force; - }; - force.alpha = function(x) { - if (!arguments.length) return alpha; - x = +x; - if (alpha) { - if (x > 0) { - alpha = x; + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === lib$es6$promise$then$$default && + constructor.resolve === lib$es6$promise$promise$resolve$$default) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { - timer.c = null, timer.t = NaN, timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); } - } else if (x > 0) { - event.start({ - type: "start", - alpha: alpha = x - }); - timer = d3_timer(force.tick); } - return force; - }; - force.start = function() { - var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; - for (i = 0; i < n; ++i) { - (o = nodes[i]).index = i; - o.weight = 0; + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); } - for (i = 0; i < m; ++i) { - o = links[i]; - if (typeof o.source == "number") o.source = nodes[o.source]; - if (typeof o.target == "number") o.target = nodes[o.target]; - ++o.source.weight; - ++o.target.weight; + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); } - for (i = 0; i < n; ++i) { - o = nodes[i]; - if (isNaN(o.x)) o.x = position("x", w); - if (isNaN(o.y)) o.y = position("y", h); - if (isNaN(o.px)) o.px = o.x; - if (isNaN(o.py)) o.py = o.y; + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); } - distances = []; - if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; - strengths = []; - if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; - charges = []; - if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; - function position(dimension, size) { - if (!neighbors) { - neighbors = new Array(n); - for (j = 0; j < n; ++j) { - neighbors[j] = []; - } - for (j = 0; j < m; ++j) { - var o = links[j]; - neighbors[o.source.index].push(o.target); - neighbors[o.target.index].push(o.source); - } - } - var candidates = neighbors[i], j = -1, l = candidates.length, x; - while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; - return Math.random() * size; + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); } - return force.resume(); - }; - force.resume = function() { - return force.alpha(.1); - }; - force.stop = function() { - return force.alpha(0); - }; - force.drag = function() { - if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); - if (!arguments.length) return drag; - this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); - }; - function dragmove(d) { - d.px = d3.event.x, d.py = d3.event.y; - force.resume(); } - return d3.rebind(force, event, "on"); - }; - function d3_layout_forceDragstart(d) { - d.fixed |= 2; - } - function d3_layout_forceDragend(d) { - d.fixed &= ~6; - } - function d3_layout_forceMouseover(d) { - d.fixed |= 4; - d.px = d.x, d.py = d.y; - } - function d3_layout_forceMouseout(d) { - d.fixed &= ~4; - } - function d3_layout_forceAccumulate(quad, alpha, charges) { - var cx = 0, cy = 0; - quad.charge = 0; - if (!quad.leaf) { - var nodes = quad.nodes, n = nodes.length, i = -1, c; - while (++i < n) { - c = nodes[i]; - if (c == null) continue; - d3_layout_forceAccumulate(c, alpha, charges); - quad.charge += c.charge; - cx += c.charge * c.cx; - cy += c.charge * c.cy; + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } } + + promise._subscribers.length = 0; } - if (quad.point) { - if (!quad.leaf) { - quad.point.x += Math.random() - .5; - quad.point.y += Math.random() - .5; + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; } - var k = alpha * charges[quad.point.index]; - quad.charge += quad.pointCharge = k; - cx += k * quad.point.x; - cy += k * quad.point.y; } - quad.cx = cx / quad.charge; - quad.cy = cy / quad.charge; - } - var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; - d3.layout.hierarchy = function() { - var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; - function hierarchy(root) { - var stack = [ root ], nodes = [], node; - root.depth = 0; - while ((node = stack.pop()) != null) { - nodes.push(node); - if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { - var n, childs, child; - while (--n >= 0) { - stack.push(child = childs[n]); - child.parent = node; - child.depth = node.depth + 1; - } - if (value) node.value = 0; - node.children = childs; + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; } else { - if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; - delete node.children; + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); } - d3_layout_hierarchyVisitAfter(root, function(node) { - var childs, parent; - if (sort && (childs = node.children)) childs.sort(sort); - if (value && (parent = node.parent)) parent.value += node.value; - }); - return nodes; } - hierarchy.sort = function(x) { - if (!arguments.length) return sort; - sort = x; - return hierarchy; - }; - hierarchy.children = function(x) { - if (!arguments.length) return children; - children = x; - return hierarchy; - }; - hierarchy.value = function(x) { - if (!arguments.length) return value; - value = x; - return hierarchy; - }; - hierarchy.revalue = function(root) { - if (value) { - d3_layout_hierarchyVisitBefore(root, function(node) { - if (node.children) node.value = 0; - }); - d3_layout_hierarchyVisitAfter(root, function(node) { - var parent; - if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; - if (parent = node.parent) parent.value += node.value; + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); }); - } - return root; - }; - return hierarchy; - }; - function d3_layout_hierarchyRebind(object, hierarchy) { - d3.rebind(object, hierarchy, "sort", "children", "value"); - object.nodes = object; - object.links = d3_layout_hierarchyLinks; - return object; - } - function d3_layout_hierarchyVisitBefore(node, callback) { - var nodes = [ node ]; - while ((node = nodes.pop()) != null) { - callback(node); - if ((children = node.children) && (n = children.length)) { - var n, children; - while (--n >= 0) nodes.push(children[n]); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); } } - } - function d3_layout_hierarchyVisitAfter(node, callback) { - var nodes = [ node ], nodes2 = []; - while ((node = nodes.pop()) != null) { - nodes2.push(node); - if ((children = node.children) && (n = children.length)) { - var i = -1, n, children; - while (++i < n) nodes.push(children[i]); + + var lib$es6$promise$$internal$$id = 0; + function lib$es6$promise$$internal$$nextId() { + return lib$es6$promise$$internal$$id++; + } + + function lib$es6$promise$$internal$$makePromise(promise) { + promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; + } + + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!lib$es6$promise$utils$$isArray(entries)) { + return new Constructor(function(resolve, reject) { + reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); } } - while ((node = nodes2.pop()) != null) { - callback(node); + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; } - } - function d3_layout_hierarchyChildren(d) { - return d.children; - } - function d3_layout_hierarchyValue(d) { - return d.value; - } - function d3_layout_hierarchySort(a, b) { - return b.value - a.value; - } - function d3_layout_hierarchyLinks(nodes) { - return d3.merge(nodes.map(function(parent) { - return (parent.children || []).map(function(child) { - return { - source: parent, - target: child - }; + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); }); - })); - } - d3.layout.partition = function() { - var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; - function position(node, x, dx, dy) { - var children = node.children; - node.x = x; - node.y = node.depth * dy; - node.dx = dx; - node.dy = dy; - if (children && (n = children.length)) { - var i = -1, n, c, d; - dx = node.value ? dx / node.value : 0; - while (++i < n) { - position(c = children[i], x, d = c.value * dx, dy); - x += d; - } + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); } - } - function depth(node) { - var children = node.children, d = 0; - if (children && (n = children.length)) { - var i = -1, n; - while (++i < n) d = Math.max(d, depth(children[i])); + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); + this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); } - return 1 + d; - } - function partition(d, i) { - var nodes = hierarchy.call(this, d, i); - position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); - return nodes; } - partition.size = function(x) { - if (!arguments.length) return size; - size = x; - return partition; - }; - return d3_layout_hierarchyRebind(partition, hierarchy); - }; - d3.layout.pie = function() { - var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; - function pie(data) { - var n = data.length, values = data.map(function(d, i) { - return +value.call(pie, d, i); - }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; - if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { - return values[j] - values[i]; - } : function(i, j) { - return sort(data[i], data[j]); + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` }); - index.forEach(function(i) { - arcs[i] = { - data: data[i], - value: v = values[i], - startAngle: a, - endAngle: a += v * k + pa, - padAngle: p - }; + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); - return arcs; - } - pie.value = function(_) { - if (!arguments.length) return value; - value = _; - return pie; - }; - pie.sort = function(_) { - if (!arguments.length) return sort; - sort = _; - return pie; - }; - pie.startAngle = function(_) { - if (!arguments.length) return startAngle; - startAngle = _; - return pie; - }; - pie.endAngle = function(_) { - if (!arguments.length) return endAngle; - endAngle = _; - return pie; - }; - pie.padAngle = function(_) { - if (!arguments.length) return padAngle; - padAngle = _; - return pie; - }; - return pie; - }; - var d3_layout_pieSortByValue = {}; - d3.layout.stack = function() { - var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; - function stack(data, index) { - if (!(n = data.length)) return data; - var series = data.map(function(d, i) { - return values.call(stack, d, i); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here }); - var points = series.map(function(d) { - return d.map(function(v, i) { - return [ x.call(stack, v, i), y.call(stack, v, i) ]; - }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available }); - var orders = order.call(stack, points, index); - series = d3.permute(series, orders); - points = d3.permute(points, orders); - var offsets = offset.call(stack, points, index); - var m = series[0].length, n, i, j, o; - for (j = 0; j < m; ++j) { - out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); - for (i = 1; i < n; ++i) { - out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); - } + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure } - return data; - } - stack.values = function(x) { - if (!arguments.length) return values; - values = x; - return stack; - }; - stack.order = function(x) { - if (!arguments.length) return order; - order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; - return stack; - }; - stack.offset = function(x) { - if (!arguments.length) return offset; - offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; - return stack; - }; - stack.x = function(z) { - if (!arguments.length) return x; - x = z; - return stack; - }; - stack.y = function(z) { - if (!arguments.length) return y; - y = z; - return stack; - }; - stack.out = function(z) { - if (!arguments.length) return out; - out = z; - return stack; - }; - return stack; - }; - function d3_layout_stackX(d) { - return d.x; - } - function d3_layout_stackY(d) { - return d.y; - } - function d3_layout_stackOut(d, y0, y) { - d.y0 = y0; - d.y = y; - } - var d3_layout_stackOrders = d3.map({ - "inside-out": function(data) { - var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { - return max[a] - max[b]; - }), top = 0, bottom = 0, tops = [], bottoms = []; - for (i = 0; i < n; ++i) { - j = index[i]; - if (top < bottom) { - top += sums[j]; - tops.push(j); + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure } else { - bottom += sums[j]; - bottoms.push(j); - } - } - return bottoms.reverse().concat(tops); - }, - reverse: function(data) { - return d3.range(data.length).reverse(); - }, - "default": d3_layout_stackOrderDefault - }); - var d3_layout_stackOffsets = d3.map({ - silhouette: function(data) { - var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o > max) max = o; - sums.push(o); - } - for (j = 0; j < m; ++j) { - y0[j] = (max - sums[j]) / 2; - } - return y0; - }, - wiggle: function(data) { - var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; - y0[0] = o = o0 = 0; - for (j = 1; j < m; ++j) { - for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; - for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { - for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { - s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; - } - s2 += s3 * data[i][j][1]; + // success } - y0[j] = o -= s1 ? s2 / s1 * dx : 0; - if (o < o0) o0 = o; - } - for (j = 0; j < m; ++j) y0[j] -= o0; - return y0; - }, - expand: function(data) { - var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure } - for (j = 0; j < m; ++j) y0[j] = 0; - return y0; - }, - zero: d3_layout_stackOffsetZero - }); - function d3_layout_stackOrderDefault(data) { - return d3.range(data.length); - } - function d3_layout_stackOffsetZero(data) { - var j = -1, m = data[0].length, y0 = []; - while (++j < m) y0[j] = 0; - return y0; - } - function d3_layout_stackMaxIndex(array) { - var i = 1, j = 0, v = array[0][1], k, n = array.length; - for (;i < n; ++i) { - if ((k = array[i][1]) > v) { - j = i; - v = k; + ``` + + Errback Example + + ```js + + function foundBooks(books) { + } - } - return j; - } - function d3_layout_stackReduceSum(d) { - return d.reduce(d3_layout_stackSum, 0); - } - function d3_layout_stackSum(p, d) { - return p + d[1]; - } - d3.layout.histogram = function() { - var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; - function histogram(data, i) { - var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; - while (++i < m) { - bin = bins[i] = []; - bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); - bin.y = 0; + + function failure(reason) { + } - if (m > 0) { - i = -1; - while (++i < n) { - x = values[i]; - if (x >= range[0] && x <= range[1]) { - bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; - bin.y += k; - bin.push(data[i]); + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); } + // success } - } - return bins; - } - histogram.value = function(x) { - if (!arguments.length) return valuer; - valuer = x; - return histogram; - }; - histogram.range = function(x) { - if (!arguments.length) return ranger; - ranger = d3_functor(x); - return histogram; - }; - histogram.bins = function(x) { - if (!arguments.length) return binner; - binner = typeof x === "number" ? function(range) { - return d3_layout_histogramBinFixed(range, x); - } : d3_functor(x); - return histogram; - }; - histogram.frequency = function(x) { - if (!arguments.length) return frequency; - frequency = !!x; - return histogram; - }; - return histogram; - }; - function d3_layout_histogramBinSturges(range, values) { - return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); - } - function d3_layout_histogramBinFixed(range, n) { - var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; - while (++x <= n) f[x] = m * x + b; - return f; - } - function d3_layout_histogramRange(values) { - return [ d3.min(values), d3.max(values) ]; - } - d3.layout.pack = function() { - var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; - function pack(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { - return radius; - }; - root.x = root.y = 0; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r = +r(d.value); }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - if (padding) { - var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r += dr; - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r -= dr; - }); - } - d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); - return nodes; - } - pack.size = function(_) { - if (!arguments.length) return size; - size = _; - return pack; - }; - pack.radius = function(_) { - if (!arguments.length) return radius; - radius = _ == null || typeof _ === "function" ? _ : +_; - return pack; - }; - pack.padding = function(_) { - if (!arguments.length) return padding; - padding = +_; - return pack; - }; - return d3_layout_hierarchyRebind(pack, hierarchy); - }; - function d3_layout_packSort(a, b) { - return a.value - b.value; - } - function d3_layout_packInsert(a, b) { - var c = a._pack_next; - a._pack_next = b; - b._pack_prev = a; - b._pack_next = c; - c._pack_prev = b; - } - function d3_layout_packSplice(a, b) { - a._pack_next = b; - b._pack_prev = a; - } - function d3_layout_packIntersects(a, b) { - var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; - return .999 * dr * dr > dx * dx + dy * dy; - } - function d3_layout_packSiblings(node) { - if (!(nodes = node.children) || !(n = nodes.length)) return; - var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; - function bound(node) { - xMin = Math.min(node.x - node.r, xMin); - xMax = Math.max(node.x + node.r, xMax); - yMin = Math.min(node.y - node.r, yMin); - yMax = Math.max(node.y + node.r, yMax); - } - nodes.forEach(d3_layout_packLink); - a = nodes[0]; - a.x = -a.r; - a.y = 0; - bound(a); - if (n > 1) { - b = nodes[1]; - b.x = b.r; - b.y = 0; - bound(b); - if (n > 2) { - c = nodes[2]; - d3_layout_packPlace(a, b, c); - bound(c); - d3_layout_packInsert(a, c); - a._pack_prev = c; - d3_layout_packInsert(c, b); - b = a._pack_next; - for (i = 3; i < n; i++) { - d3_layout_packPlace(a, b, c = nodes[i]); - var isect = 0, s1 = 1, s2 = 1; - for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { - if (d3_layout_packIntersects(j, c)) { - isect = 1; - break; - } - } - if (isect == 1) { - for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { - if (d3_layout_packIntersects(k, c)) { - break; - } - } - } - if (isect) { - if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); - i--; - } else { - d3_layout_packInsert(a, c); - b = c; - bound(c); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: lib$es6$promise$then$$default, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { + lib$es6$promise$$internal$$makePromise(this.promise); + } + + if (lib$es6$promise$utils$$isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); } } + } else { + lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); } } - var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; - for (i = 0; i < n; i++) { - c = nodes[i]; - c.x -= cx; - c.y -= cy; - cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); - } - node.r = cr; - nodes.forEach(d3_layout_packUnlink); - } - function d3_layout_packLink(node) { - node._pack_next = node._pack_prev = node; - } - function d3_layout_packUnlink(node) { - delete node._pack_next; - delete node._pack_prev; - } - function d3_layout_packTransform(node, x, y, k) { - var children = node.children; - node.x = x += k * node.x; - node.y = y += k * node.y; - node.r *= k; - if (children) { - var i = -1, n = children.length; - while (++i < n) d3_layout_packTransform(children[i], x, y, k); - } - } - function d3_layout_packPlace(a, b, c) { - var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; - if (db && (dx || dy)) { - var da = b.r + c.r, dc = dx * dx + dy * dy; - da *= da; - db *= db; - var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); - c.x = a.x + x * dx + y * dy; - c.y = a.y + x * dy - y * dx; - } else { - c.x = a.x + db; - c.y = a.y; + + function lib$es6$promise$enumerator$$validationError() { + return new Error('Array Methods must be provided an Array'); } - } - d3.layout.tree = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; - function tree(d, i) { - var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); - d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; - d3_layout_hierarchyVisitBefore(root1, secondWalk); - if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { - var left = root0, right = root0, bottom = root0; - d3_layout_hierarchyVisitBefore(root0, function(node) { - if (node.x < left.x) left = node; - if (node.x > right.x) right = node; - if (node.depth > bottom.depth) bottom = node; - }); - var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); - d3_layout_hierarchyVisitBefore(root0, function(node) { - node.x = (node.x + tx) * kx; - node.y = node.depth * ky; - }); + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var length = this.length; + var input = this._input; + + for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + this._eachEntry(input[i], i); } - return nodes; - } - function wrapTree(root0) { - var root1 = { - A: null, - children: [ root0 ] - }, queue = [ root1 ], node1; - while ((node1 = queue.pop()) != null) { - for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { - queue.push((children[i] = child = { - _: children[i], - parent: node1, - children: (child = children[i].children) && child.slice() || [], - A: null, - a: null, - z: 0, - m: 0, - c: 0, - s: 0, - t: null, - i: i - }).a = child); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve = c.resolve; + + if (resolve === lib$es6$promise$promise$resolve$$default) { + var then = lib$es6$promise$$internal$$getThen(entry); + + if (then === lib$es6$promise$then$$default && + entry._state !== lib$es6$promise$$internal$$PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === lib$es6$promise$promise$$default) { + var promise = new c(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); } + } else { + this._willSettleAt(resolve(entry), i); } - return root1.children[0]; - } - function firstWalk(v) { - var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; - if (children.length) { - d3_layout_treeShift(v); - var midpoint = (children[0].z + children[children.length - 1].z) / 2; - if (w) { - v.z = w.z + separation(v._, w._); - v.m = v.z - midpoint; + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + this._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); } else { - v.z = midpoint; + this._result[i] = value; } - } else if (w) { - v.z = w.z + separation(v._, w._); } - v.parent.A = apportion(v, w, v.parent.A || siblings[0]); + + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, this._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; } - function secondWalk(v) { - v._.x = v.z + v.parent.m; - v.m += v.parent.m; + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; } - function apportion(v, w, ancestor) { - if (w) { - var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; - while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { - vom = d3_layout_treeLeft(vom); - vop = d3_layout_treeRight(vop); - vop.a = v; - shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); - if (shift > 0) { - d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); - sip += shift; - sop += shift; - } - sim += vim.m; - sip += vip.m; - som += vom.m; - sop += vop.m; - } - if (vim && !d3_layout_treeRight(vop)) { - vop.t = vim; - vop.m += sim - sop; - } - if (vip && !d3_layout_treeLeft(vom)) { - vom.t = vip; - vom.m += sip - som; - ancestor = v; + + lib$es6$promise$polyfill$$default(); +}).call(this); + + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":70}],90:[function(require,module,exports){ +/** + * inspired by is-number + * but significantly simplified and sped up by ignoring number and string constructors + * ie these return false: + * new Number(1) + * new String('1') + */ + +'use strict'; + +/** + * Is this string all whitespace? + * This solution kind of makes my brain hurt, but it's significantly faster + * than !str.trim() or any other solution I could find. + * + * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character + * and verified with: + * + * for(var i = 0; i < 65536; i++) { + * var s = String.fromCharCode(i); + * if(+s===0 && !s.trim()) console.log(i, s); + * } + * + * which counts a couple of these as *not* whitespace, but finds nothing else + * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears + * that there are no whitespace characters above this, and code points above + * this do not map onto white space characters. + */ +function allBlankCharCodes(str){ + var l = str.length, + a; + for(var i = 0; i < l; i++) { + a = str.charCodeAt(i); + if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) && + (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) && + (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) && + (a !== 8288) && (a !== 12288) && (a !== 65279)) { + return false; } - } - return ancestor; } - function sizeNode(node) { - node.x *= size[0]; - node.y = node.depth * size[1]; + return true; +} + +module.exports = function(n) { + var type = typeof n; + if(type === 'string') { + var original = n; + n = +n; + // whitespace strings cast to zero - filter them out + if(n===0 && allBlankCharCodes(original)) return false; } - tree.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return tree; - }; - tree.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null ? sizeNode : null; - return tree; - }; - tree.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) == null ? null : sizeNode; - return tree; - }; - return d3_layout_hierarchyRebind(tree, hierarchy); - }; - function d3_layout_treeSeparation(a, b) { - return a.parent == b.parent ? 1 : 2; + else if(type !== 'number') return false; + + return n - n < 1; +}; + +},{}],91:[function(require,module,exports){ +'use strict' + +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var pool = require('typedarray-pool') +var shaders = require('./lib/shaders') + +module.exports = createError2D + +var WEIGHTS = [ + // x-error bar + [1, 0, 0, 1, 0, 0], + [1, 0, 0, -1, 0, 0], + [-1, 0, 0, -1, 0, 0], + + [-1, 0, 0, -1, 0, 0], + [-1, 0, 0, 1, 0, 0], + [1, 0, 0, 1, 0, 0], + + // x-error right cap + [1, 0, -1, 0, 0, 1], + [1, 0, -1, 0, 0, -1], + [1, 0, 1, 0, 0, -1], + + [1, 0, 1, 0, 0, -1], + [1, 0, 1, 0, 0, 1], + [1, 0, -1, 0, 0, 1], + + // x-error left cap + [-1, 0, -1, 0, 0, 1], + [-1, 0, -1, 0, 0, -1], + [-1, 0, 1, 0, 0, -1], + + [-1, 0, 1, 0, 0, -1], + [-1, 0, 1, 0, 0, 1], + [-1, 0, -1, 0, 0, 1], + + // y-error bar + [0, 1, 1, 0, 0, 0], + [0, 1, -1, 0, 0, 0], + [0, -1, -1, 0, 0, 0], + + [0, -1, -1, 0, 0, 0], + [0, 1, 1, 0, 0, 0], + [0, -1, 1, 0, 0, 0], + + // y-error top cap + [0, 1, 0, -1, 1, 0], + [0, 1, 0, -1, -1, 0], + [0, 1, 0, 1, -1, 0], + + [0, 1, 0, 1, 1, 0], + [0, 1, 0, -1, 1, 0], + [0, 1, 0, 1, -1, 0], + + // y-error bottom cap + [0, -1, 0, -1, 1, 0], + [0, -1, 0, -1, -1, 0], + [0, -1, 0, 1, -1, 0], + + [0, -1, 0, 1, 1, 0], + [0, -1, 0, -1, 1, 0], + [0, -1, 0, 1, -1, 0] +] + +function GLError2D (plot, shader, buffer) { + this.plot = plot + + this.shader = shader + this.buffer = buffer + + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + + this.numPoints = 0 + + this.color = [0, 0, 0, 1] +} + +var proto = GLError2D.prototype + +proto.draw = (function () { + var MATRIX = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + + var PIXEL_SCALE = [1, 1] + + return function () { + var plot = this.plot + var shader = this.shader + var buffer = this.buffer + var bounds = this.bounds + var numPoints = this.numPoints + + if (!numPoints) { + return + } + + var gl = plot.gl + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] + + PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX + PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY + + buffer.bind() + shader.bind() + + shader.uniforms.viewTransform = MATRIX + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.color = this.color + + shader.attributes.position.pointer( + gl.FLOAT, + false, + 16, + 0) + + shader.attributes.pixelOffset.pointer( + gl.FLOAT, + false, + 16, + 8) + + gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length) } - function d3_layout_treeLeft(v) { - var children = v.children; - return children.length ? children[0] : v.t; +})() + +proto.drawPick = function (offset) { return offset } +proto.pick = function (x, y) { + return null +} + +proto.update = function (options) { + options = options || {} + + var i, x, y + + var positions = options.positions || [] + var errors = options.errors || [] + + var lineWidth = 1 + if ('lineWidth' in options) { + lineWidth = +options.lineWidth } - function d3_layout_treeRight(v) { - var children = v.children, n; - return (n = children.length) ? children[n - 1] : v.t; + + var capSize = 5 + if ('capSize' in options) { + capSize = +options.capSize } - function d3_layout_treeMove(wm, wp, shift) { - var change = shift / (wp.i - wm.i); - wp.c -= change; - wp.s += shift; - wm.c += change; - wp.z += shift; - wp.m += shift; + + this.color = (options.color || [0, 0, 0, 1]).slice() + + var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + + var numPoints = this.numPoints = positions.length >> 1 + for (i = 0; i < numPoints; ++i) { + x = positions[i * 2] + y = positions[i * 2 + 1] + + bounds[0] = Math.min(x, bounds[0]) + bounds[1] = Math.min(y, bounds[1]) + bounds[2] = Math.max(x, bounds[2]) + bounds[3] = Math.max(y, bounds[3]) } - function d3_layout_treeShift(v) { - var shift = 0, change = 0, children = v.children, i = children.length, w; - while (--i >= 0) { - w = children[i]; - w.z += shift; - w.m += shift; - shift += w.s + (change += w.c); - } + if (bounds[2] === bounds[0]) { + bounds[2] += 1 } - function d3_layout_treeAncestor(vim, v, ancestor) { - return vim.a.parent === v.parent ? vim.a : ancestor; + if (bounds[3] === bounds[1]) { + bounds[3] += 1 } - d3.layout.cluster = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; - function cluster(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; - d3_layout_hierarchyVisitAfter(root, function(node) { - var children = node.children; - if (children && children.length) { - node.x = d3_layout_clusterX(children); - node.y = d3_layout_clusterY(children); - } else { - node.x = previousNode ? x += separation(node, previousNode) : 0; - node.y = 0; - previousNode = node; - } - }); - var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; - d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { - node.x = (node.x - root.x) * size[0]; - node.y = (root.y - node.y) * size[1]; - } : function(node) { - node.x = (node.x - x0) / (x1 - x0) * size[0]; - node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; - }); - return nodes; + var sx = 1.0 / (bounds[2] - bounds[0]) + var sy = 1.0 / (bounds[3] - bounds[1]) + var tx = bounds[0] + var ty = bounds[1] + + var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4) + var ptr = 0 + for (i = 0; i < numPoints; ++i) { + x = positions[2 * i] + y = positions[2 * i + 1] + var ex0 = errors[4 * i] + var ex1 = errors[4 * i + 1] + var ey0 = errors[4 * i + 2] + var ey1 = errors[4 * i + 3] + + for (var j = 0; j < WEIGHTS.length; ++j) { + var w = WEIGHTS[j] + + var dx = w[0] + var dy = w[1] + + if (dx < 0) { + dx *= ex0 + } else if (dx > 0) { + dx *= ex1 + } + + if (dy < 0) { + dy *= ey0 + } else if (dy > 0) { + dy *= ey1 + } + + bufferData[ptr++] = sx * ((x - tx) + dx) + bufferData[ptr++] = sy * ((y - ty) + dy) + bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4] + bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5] } - cluster.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return cluster; - }; - cluster.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null; - return cluster; - }; - cluster.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) != null; - return cluster; - }; - return d3_layout_hierarchyRebind(cluster, hierarchy); - }; - function d3_layout_clusterY(children) { - return 1 + d3.max(children, function(child) { - return child.y; - }); } - function d3_layout_clusterX(children) { - return children.reduce(function(x, child) { - return x + child.x; - }, 0) / children.length; + this.buffer.update(bufferData) + pool.free(bufferData) +} + +proto.dispose = function () { + this.plot.removeObject(this) + this.shader.dispose() + this.buffer.dispose() +} + +function createError2D (plot, options) { + var shader = createShader(plot.gl, shaders.vertex, shaders.fragment) + var buffer = createBuffer(plot.gl) + + var errorbars = new GLError2D(plot, shader, buffer) + + errorbars.update(options) + + plot.addObject(errorbars) + + return errorbars +} + +},{"./lib/shaders":92,"gl-buffer":93,"gl-shader":94,"typedarray-pool":122}],92:[function(require,module,exports){ + + +module.exports = { + vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n", + fragment: "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" +} + +},{}],93:[function(require,module,exports){ +"use strict" + +var pool = require("typedarray-pool") +var ops = require("ndarray-ops") +var ndarray = require("ndarray") + +var SUPPORTED_TYPES = [ + "uint8", + "uint8_clamped", + "uint16", + "uint32", + "int8", + "int16", + "int32", + "float32" ] + +function GLBuffer(gl, type, handle, length, usage) { + this.gl = gl + this.type = type + this.handle = handle + this.length = length + this.usage = usage +} + +var proto = GLBuffer.prototype + +proto.bind = function() { + this.gl.bindBuffer(this.type, this.handle) +} + +proto.unbind = function() { + this.gl.bindBuffer(this.type, null) +} + +proto.dispose = function() { + this.gl.deleteBuffer(this.handle) +} + +function updateTypeArray(gl, type, len, usage, data, offset) { + var dataLen = data.length * data.BYTES_PER_ELEMENT + if(offset < 0) { + gl.bufferData(type, data, usage) + return dataLen } - function d3_layout_clusterLeft(node) { - var children = node.children; - return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + if(dataLen + offset > len) { + throw new Error("gl-buffer: If resizing buffer, must not specify offset") } - function d3_layout_clusterRight(node) { - var children = node.children, n; - return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + gl.bufferSubData(type, offset, data) + return len +} + +function makeScratchTypeArray(array, dtype) { + var res = pool.malloc(array.length, dtype) + var n = array.length + for(var i=0; i 0) { - row.push(child = remaining[n - 1]); - row.area += child.area; - if (mode !== "squarify" || (score = worst(row, u)) <= best) { - remaining.pop(); - best = score; - } else { - row.area -= row.pop().area; - position(row, u, rect, false); - u = Math.min(rect.dx, rect.dy); - row.length = row.area = 0; - best = Infinity; - } - } - if (row.length) { - position(row, u, rect, true); - row.length = row.area = 0; - } - children.forEach(squarify); - } - } - function stickify(node) { - var children = node.children; - if (children && children.length) { - var rect = pad(node), remaining = children.slice(), child, row = []; - scale(remaining, rect.dx * rect.dy / node.value); - row.area = 0; - while (child = remaining.pop()) { - row.push(child); - row.area += child.area; - if (child.z != null) { - position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); - row.length = row.area = 0; - } - } - children.forEach(stickify); - } + return res +} + +function isPacked(shape, stride) { + var n = 1 + for(var i=stride.length-1; i>=0; --i) { + if(stride[i] !== n) { + return false } - function worst(row, u) { - var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; - while (++i < n) { - if (!(r = row[i].area)) continue; - if (r < rmin) rmin = r; - if (r > rmax) rmax = r; - } - s *= s; - u *= u; - return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + n *= shape[i] + } + return true +} + +proto.update = function(array, offset) { + if(typeof offset !== "number") { + offset = -1 + } + this.bind() + if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray + var dtype = array.dtype + if(SUPPORTED_TYPES.indexOf(dtype) < 0) { + dtype = "float32" } - function position(row, u, rect, flush) { - var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; - if (u == rect.dx) { - if (flush || v > rect.dy) v = rect.dy; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dy = v; - x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); - } - o.z = true; - o.dx += rect.x + rect.dx - x; - rect.y += v; - rect.dy -= v; + if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { + var ext = gl.getExtension('OES_element_index_uint') + if(ext && dtype !== "uint16") { + dtype = "uint32" } else { - if (flush || v > rect.dx) v = rect.dx; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dx = v; - y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); - } - o.z = false; - o.dy += rect.y + rect.dy - y; - rect.x += v; - rect.dx -= v; + dtype = "uint16" } } - function treemap(d) { - var nodes = stickies || hierarchy(d), root = nodes[0]; - root.x = root.y = 0; - if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; - if (stickies) hierarchy.revalue(root); - scale([ root ], root.dx * root.dy / root.value); - (stickies ? stickify : squarify)(root); - if (sticky) stickies = nodes; - return nodes; - } - treemap.size = function(x) { - if (!arguments.length) return size; - size = x; - return treemap; - }; - treemap.padding = function(x) { - if (!arguments.length) return padding; - function padFunction(node) { - var p = x.call(treemap, node, node.depth); - return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + if(dtype === array.dtype && isPacked(array.shape, array.stride)) { + if(array.offset === 0 && array.data.length === array.shape[0]) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) } - function padConstant(node) { - return d3_layout_treemapPad(node, x); + } else { + var tmp = pool.malloc(array.size, dtype) + var ndt = ndarray(tmp, array.shape) + ops.assign(ndt, array) + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) } - var type; - pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], - padConstant) : padConstant; - return treemap; - }; - treemap.round = function(x) { - if (!arguments.length) return round != Number; - round = x ? Math.round : Number; - return treemap; - }; - treemap.sticky = function(x) { - if (!arguments.length) return sticky; - sticky = x; - stickies = null; - return treemap; - }; - treemap.ratio = function(x) { - if (!arguments.length) return ratio; - ratio = x; - return treemap; - }; - treemap.mode = function(x) { - if (!arguments.length) return mode; - mode = x + ""; - return treemap; - }; - return d3_layout_hierarchyRebind(treemap, hierarchy); - }; - function d3_layout_treemapPadNull(node) { - return { - x: node.x, - y: node.y, - dx: node.dx, - dy: node.dy - }; - } - function d3_layout_treemapPad(node, padding) { - var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; - if (dx < 0) { - x += dx / 2; - dx = 0; - } - if (dy < 0) { - y += dy / 2; - dy = 0; - } - return { - x: x, - y: y, - dx: dx, - dy: dy - }; - } - d3.random = { - normal: function(µ, σ) { - var n = arguments.length; - if (n < 2) σ = 1; - if (n < 1) µ = 0; - return function() { - var x, y, r; - do { - x = Math.random() * 2 - 1; - y = Math.random() * 2 - 1; - r = x * x + y * y; - } while (!r || r > 1); - return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); - }; - }, - logNormal: function() { - var random = d3.random.normal.apply(d3, arguments); - return function() { - return Math.exp(random()); - }; - }, - bates: function(m) { - var random = d3.random.irwinHall(m); - return function() { - return random() / m; - }; - }, - irwinHall: function(m) { - return function() { - for (var s = 0, j = 0; j < m; j++) s += Math.random(); - return s; - }; - } - }; - d3.scale = {}; - function d3_scaleExtent(domain) { - var start = domain[0], stop = domain[domain.length - 1]; - return start < stop ? [ start, stop ] : [ stop, start ]; - } - function d3_scaleRange(scale) { - return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); - } - function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { - var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); - return function(x) { - return i(u(x)); - }; - } - function d3_scale_nice(domain, nice) { - var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; - if (x1 < x0) { - dx = i0, i0 = i1, i1 = dx; - dx = x0, x0 = x1, x1 = dx; + pool.free(tmp) } - domain[i0] = nice.floor(x0); - domain[i1] = nice.ceil(x1); - return domain; - } - function d3_scale_niceStep(step) { - return step ? { - floor: function(x) { - return Math.floor(x / step) * step; - }, - ceil: function(x) { - return Math.ceil(x / step) * step; - } - } : d3_scale_niceIdentity; - } - var d3_scale_niceIdentity = { - floor: d3_identity, - ceil: d3_identity - }; - function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { - var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; - if (domain[k] < domain[0]) { - domain = domain.slice().reverse(); - range = range.slice().reverse(); + } else if(Array.isArray(array)) { //Vanilla array + var t + if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { + t = makeScratchTypeArray(array, "uint16") + } else { + t = makeScratchTypeArray(array, "float32") } - while (++j <= k) { - u.push(uninterpolate(domain[j - 1], domain[j])); - i.push(interpolate(range[j - 1], range[j])); + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) } - return function(x) { - var j = d3.bisect(domain, x, 1, k) - 1; - return i[j](u[j](x)); - }; - } - d3.scale.linear = function() { - return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); - }; - function d3_scale_linear(domain, range, interpolate, clamp) { - var output, input; - function rescale() { - var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; - output = linear(domain, range, uninterpolate, interpolate); - input = linear(range, domain, uninterpolate, d3_interpolate); - return scale; + pool.free(t) + } else if(typeof array === "object" && typeof array.length === "number") { //Typed array + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) + } else if(typeof array === "number" || array === undefined) { //Number/default + if(offset >= 0) { + throw new Error("gl-buffer: Cannot specify offset when resizing buffer") } - function scale(x) { - return output(x); + array = array | 0 + if(array <= 0) { + array = 1 } - scale.invert = function(y) { - return input(y); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = x.map(Number); - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.rangeRound = function(x) { - return scale.range(x).interpolate(d3_interpolateRound); - }; - scale.clamp = function(x) { - if (!arguments.length) return clamp; - clamp = x; - return rescale(); - }; - scale.interpolate = function(x) { - if (!arguments.length) return interpolate; - interpolate = x; - return rescale(); - }; - scale.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - scale.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - scale.nice = function(m) { - d3_scale_linearNice(domain, m); - return rescale(); - }; - scale.copy = function() { - return d3_scale_linear(domain, range, interpolate, clamp); - }; - return rescale(); + this.gl.bufferData(this.type, array|0, this.usage) + this.length = array + } else { //Error, case should not happen + throw new Error("gl-buffer: Invalid data type") } - function d3_scale_linearRebind(scale, linear) { - return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); +} + +function createBuffer(gl, data, type, usage) { + type = type || gl.ARRAY_BUFFER + usage = usage || gl.DYNAMIC_DRAW + if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { + throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") } - function d3_scale_linearNice(domain, m) { - d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - return domain; + if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { + throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") } - function d3_scale_linearTickRange(domain, m) { - if (m == null) m = 10; - var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; - if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; - extent[0] = Math.ceil(extent[0] / step) * step; - extent[1] = Math.floor(extent[1] / step) * step + step * .5; - extent[2] = step; - return extent; + var handle = gl.createBuffer() + var result = new GLBuffer(gl, type, handle, 0, usage) + result.update(data) + return result +} + +module.exports = createBuffer + +},{"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":122}],94:[function(require,module,exports){ +'use strict' + +var createUniformWrapper = require('./lib/create-uniforms') +var createAttributeWrapper = require('./lib/create-attributes') +var makeReflect = require('./lib/reflect') +var shaderCache = require('./lib/shader-cache') +var runtime = require('./lib/runtime-reflect') +var GLError = require("./lib/GLError") + +//Shader object +function Shader(gl) { + this.gl = gl + + //Default initialize these to null + this._vref = + this._fref = + this._relink = + this.vertShader = + this.fragShader = + this.program = + this.attributes = + this.uniforms = + this.types = null +} + +var proto = Shader.prototype + +proto.bind = function() { + if(!this.program) { + this._relink() } - function d3_scale_linearTicks(domain, m) { - return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); + this.gl.useProgram(this.program) +} + +proto.dispose = function() { + if(this._fref) { + this._fref.dispose() } - function d3_scale_linearTickFormat(domain, m, format) { - var range = d3_scale_linearTickRange(domain, m); - if (format) { - var match = d3_format_re.exec(format); - match.shift(); - if (match[8] === "s") { - var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); - if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); - match[8] = "f"; - format = d3.format(match.join("")); - return function(d) { - return format(prefix.scale(d)) + prefix.symbol; - }; - } - if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); - format = match.join(""); - } else { - format = ",." + d3_scale_linearPrecision(range[2]) + "f"; - } - return d3.format(format); + if(this._vref) { + this._vref.dispose() } - var d3_scale_linearFormatSignificant = { - s: 1, - g: 1, - p: 1, - r: 1, - e: 1 - }; - function d3_scale_linearPrecision(value) { - return -Math.floor(Math.log(value) / Math.LN10 + .01); + this.attributes = + this.types = + this.vertShader = + this.fragShader = + this.program = + this._relink = + this._fref = + this._vref = null +} + +function compareAttributes(a, b) { + if(a.name < b.name) { + return -1 } - function d3_scale_linearFormatPrecision(type, range) { - var p = d3_scale_linearPrecision(range[2]); - return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + return 1 +} + +//Update export hook for glslify-live +proto.update = function( + vertSource + , fragSource + , uniforms + , attributes) { + + //If only one object passed, assume glslify style output + if(!fragSource || arguments.length === 1) { + var obj = vertSource + vertSource = obj.vertex + fragSource = obj.fragment + uniforms = obj.uniforms + attributes = obj.attributes } - d3.scale.log = function() { - return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); - }; - function d3_scale_log(linear, base, positive, domain) { - function log(x) { - return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); - } - function pow(x) { - return positive ? Math.pow(base, x) : -Math.pow(base, -x); - } - function scale(x) { - return linear(log(x)); + + var wrapper = this + var gl = wrapper.gl + + //Compile vertex and fragment shaders + var pvref = wrapper._vref + wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource) + if(pvref) { + pvref.dispose() + } + wrapper.vertShader = wrapper._vref.shader + var pfref = this._fref + wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource) + if(pfref) { + pfref.dispose() + } + wrapper.fragShader = wrapper._fref.shader + + //If uniforms/attributes is not specified, use RT reflection + if(!uniforms || !attributes) { + + //Create initial test program + var testProgram = gl.createProgram() + gl.attachShader(testProgram, wrapper.fragShader) + gl.attachShader(testProgram, wrapper.vertShader) + gl.linkProgram(testProgram) + if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) { + var errLog = gl.getProgramInfoLog(testProgram) + throw new GLError(errLog, 'Error linking program:' + errLog) } - scale.invert = function(x) { - return pow(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - positive = x[0] >= 0; - linear.domain((domain = x.map(Number)).map(log)); - return scale; - }; - scale.base = function(_) { - if (!arguments.length) return base; - base = +_; - linear.domain(domain.map(log)); - return scale; - }; - scale.nice = function() { - var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); - linear.domain(niced); - domain = niced.map(pow); - return scale; - }; - scale.ticks = function() { - var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; - if (isFinite(j - i)) { - if (positive) { - for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); - ticks.push(pow(i)); + + //Load data from runtime + uniforms = uniforms || runtime.uniforms(gl, testProgram) + attributes = attributes || runtime.attributes(gl, testProgram) + + //Release test program + gl.deleteProgram(testProgram) + } + + //Sort attributes lexicographically + // overrides undefined WebGL behavior for attribute locations + attributes = attributes.slice() + attributes.sort(compareAttributes) + + //Convert attribute types, read out locations + var attributeUnpacked = [] + var attributeNames = [] + var attributeLocations = [] + for(var i=0; i= 0) { + var size = attr.type.charAt(attr.type.length-1)|0 + var locVector = new Array(size) + for(var j=0; j 0; k--) ticks.push(pow(i) * k); + attributeLocations.push(-1) } - for (i = 0; ticks[i] < u; i++) {} - for (j = ticks.length; ticks[j - 1] > v; j--) {} - ticks = ticks.slice(i, j); } - return ticks; - }; - scale.tickFormat = function(n, format) { - if (!arguments.length) return d3_scale_logFormat; - if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); - var k = Math.max(1, base * n / scale.ticks().length); - return function(d) { - var i = d / pow(Math.round(log(d))); - if (i * base < base - .5) i *= base; - return i <= k ? format(d) : ""; - }; - }; - scale.copy = function() { - return d3_scale_log(linear.copy(), base, positive, domain); - }; - return d3_scale_linearRebind(scale, linear); + attributeUnpacked.push({ + name: attr.name, + type: attr.type, + locations: locVector + }) + } else { + attributeUnpacked.push({ + name: attr.name, + type: attr.type, + locations: [ attributeLocations.length ] + }) + attributeNames.push(attr.name) + if(typeof attr.location === 'number') { + attributeLocations.push(attr.location|0) + } else { + attributeLocations.push(-1) + } + } } - var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { - floor: function(x) { - return -Math.ceil(-x); - }, - ceil: function(x) { - return -Math.floor(-x); + + //For all unspecified attributes, assign them lexicographically min attribute + var curLocation = 0 + for(var i=0; i= 0) { + curLocation += 1 + } + attributeLocations[i] = curLocation } - }; - d3.scale.pow = function() { - return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); - }; - function d3_scale_pow(linear, exponent, domain) { - var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); - function scale(x) { - return linear(powp(x)); + } + + //Rebuild program and recompute all uniform locations + var uniformLocations = new Array(uniforms.length) + function relink() { + wrapper.program = shaderCache.program( + gl + , wrapper._vref + , wrapper._fref + , attributeNames + , attributeLocations) + + for(var i=0; i 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; - }; - scale.copy = function() { - return d3_scale_quantile(domain, range); - }; - return rescale(); } - d3.scale.quantize = function() { - return d3_scale_quantize(0, 1, [ 0, 1 ]); - }; - function d3_scale_quantize(x0, x1, range) { - var kx, i; - function scale(x) { - return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + + var scratch = new Array(dimension) + var vertexAttrib = gl['vertexAttrib' + dimension + 'fv'] + + Object.defineProperty(obj, name, { + set: function(x) { + for(var i=0; i= 0) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addVectorAttribute( + gl + , wrapper + , locs[0] + , locations + , d + , obj + , name) + } else if(type.indexOf('mat') >= 0) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addMatrixAttribute( + gl + , wrapper + , locs + , locations + , d + , obj + , name) + } else { + throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type) + } + break } - scale.domain = function(_) { - if (!arguments.length) return domain; - domain = _; - return scale; - }; - scale.range = function(_) { - if (!arguments.length) return range; - range = _; - return scale; - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - return [ domain[y - 1], domain[y] ]; - }; - scale.copy = function() { - return d3_scale_threshold(domain, range); - }; - return scale; } - d3.scale.identity = function() { - return d3_scale_identity([ 0, 1 ]); - }; - function d3_scale_identity(domain) { - function identity(x) { - return +x; - } - identity.invert = identity; - identity.domain = identity.range = function(x) { - if (!arguments.length) return domain; - domain = x.map(identity); - return identity; - }; - identity.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - identity.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - identity.copy = function() { - return d3_scale_identity(domain); - }; - return identity; + return obj +} + +},{"./GLError":95}],97:[function(require,module,exports){ +'use strict' + +var coallesceUniforms = require('./reflect') +var GLError = require("./GLError") + +module.exports = createUniformWrapper + +//Binds a function and returns a value +function identity(x) { + var c = new Function('y', 'return function(){return y}') + return c(x) +} + +function makeVector(length, fill) { + var result = new Array(length) + for(var i=0; i a1 ? 0 : 1; - if (r1 < r0) rc = r1, r1 = r0, r0 = rc; - if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; - var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; - if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { - rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); - if (!cw) p1 *= -1; - if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); - if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); - } - if (r1) { - x0 = r1 * Math.cos(a0 + p1); - y0 = r1 * Math.sin(a0 + p1); - x1 = r1 * Math.cos(a1 - p1); - y1 = r1 * Math.sin(a1 - p1); - var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; - if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { - var h1 = (a0 + a1) / 2; - x0 = r1 * Math.cos(h1); - y0 = r1 * Math.sin(h1); - x1 = y1 = null; + + function makePropSetter(path, index, type) { + switch(type) { + case 'bool': + case 'int': + case 'sampler2D': + case 'samplerCube': + return 'gl.uniform1i(locations[' + index + '],obj' + path + ')' + case 'float': + return 'gl.uniform1f(locations[' + index + '],obj' + path + ')' + default: + var vidx = type.indexOf('vec') + if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type') + } + switch(type.charAt(0)) { + case 'b': + case 'i': + return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' + case 'v': + return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' + default: + throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type) + } + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + } + return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' + } else { + throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) } + break + } + } + + function enumerateIndices(prefix, type) { + if(typeof type !== 'object') { + return [ [prefix, type] ] + } + var indices = [] + for(var id in type) { + var prop = type[id] + var tprefix = prefix + if(parseInt(id) + '' === id) { + tprefix += '[' + id + ']' } else { - x0 = y0 = 0; + tprefix += '.' + id } - if (r0) { - x2 = r0 * Math.cos(a1 - p0); - y2 = r0 * Math.sin(a1 - p0); - x3 = r0 * Math.cos(a0 + p0); - y3 = r0 * Math.sin(a0 + p0); - var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; - if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { - var h0 = (a0 + a1) / 2; - x2 = r0 * Math.cos(h0); - y2 = r0 * Math.sin(h0); - x3 = y3 = null; - } + if(typeof prop === 'object') { + indices.push.apply(indices, enumerateIndices(tprefix, prop)) } else { - x2 = y2 = 0; + indices.push([tprefix, prop]) } - if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { - cr = r0 < r1 ^ cw ? 0 : 1; - var rc1 = rc, rc0 = rc; - if (da < π) { - var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); - rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); - rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); - } - if (x1 != null) { - var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); - if (rc === rc1) { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); - } else { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + return indices + } + + function makeSetter(type) { + var code = [ 'return function updateProperty(obj){' ] + var indices = enumerateIndices('', type) + for(var i=0; i 4) { + throw new GLError('', 'Invalid data type') } - } else { - path.push("M", x0, ",", y0); - } - if (x3 != null) { - var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); - if (rc === rc0) { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); - } else { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + if(type.charAt(0) === 'b') { + return makeVector(d, false) + } + return makeVector(d, 0) + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } + return makeVector(d*d, 0) } else { - path.push("L", x2, ",", y2); + throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) } + break + } + } + + function storeProperty(obj, prop, type) { + if(typeof type === 'object') { + var child = processObject(type) + Object.defineProperty(obj, prop, { + get: identity(child), + set: makeSetter(type), + enumerable: true, + configurable: false + }) + } else { + if(locations[type]) { + Object.defineProperty(obj, prop, { + get: makeGetter(type), + set: makeSetter(type), + enumerable: true, + configurable: false + }) } else { - path.push("M", x0, ",", y0); - if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); - path.push("L", x2, ",", y2); - if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + obj[prop] = defaultValue(uniforms[type].type) } - path.push("Z"); - return path.join(""); - } - function circleSegment(r1, cw) { - return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } - arc.innerRadius = function(v) { - if (!arguments.length) return innerRadius; - innerRadius = d3_functor(v); - return arc; - }; - arc.outerRadius = function(v) { - if (!arguments.length) return outerRadius; - outerRadius = d3_functor(v); - return arc; - }; - arc.cornerRadius = function(v) { - if (!arguments.length) return cornerRadius; - cornerRadius = d3_functor(v); - return arc; - }; - arc.padRadius = function(v) { - if (!arguments.length) return padRadius; - padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); - return arc; - }; - arc.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return arc; - }; - arc.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return arc; - }; - arc.padAngle = function(v) { - if (!arguments.length) return padAngle; - padAngle = d3_functor(v); - return arc; - }; - arc.centroid = function() { - var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; - return [ Math.cos(a) * r, Math.sin(a) * r ]; - }; - return arc; - }; - var d3_svg_arcAuto = "auto"; - function d3_svg_arcInnerRadius(d) { - return d.innerRadius; - } - function d3_svg_arcOuterRadius(d) { - return d.outerRadius; - } - function d3_svg_arcStartAngle(d) { - return d.startAngle; - } - function d3_svg_arcEndAngle(d) { - return d.endAngle; - } - function d3_svg_arcPadAngle(d) { - return d && d.padAngle; - } - function d3_svg_arcSweep(x0, y0, x1, y1) { - return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; - } - function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { - var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; - if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; - return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; } - function d3_svg_line(projection) { - var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; - function line(data) { - var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); - function segment() { - segments.push("M", interpolate(projection(points), tension)); + + function processObject(obj) { + var result + if(Array.isArray(obj)) { + result = new Array(obj.length) + for(var i=0; i 1 ? points.join("L") : points + "Z"; - } - function d3_svg_lineLinearClosed(points) { - return points.join("L") + "Z"; - } - function d3_svg_lineStep(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); - if (n > 1) path.push("H", p[0]); - return path.join(""); - } - function d3_svg_lineStepBefore(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); - return path.join(""); - } - function d3_svg_lineStepAfter(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); - return path.join(""); - } - function d3_svg_lineCardinalOpen(points, tension) { - return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); - } - function d3_svg_lineCardinalClosed(points, tension) { - return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), - points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + return result } - function d3_svg_lineCardinal(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + + //Return data + var coallesced = coallesceUniforms(uniforms, true) + return { + get: identity(processObject(coallesced)), + set: makeSetter(coallesced), + enumerable: true, + configurable: true } - function d3_svg_lineHermite(points, tangents) { - if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { - return d3_svg_lineLinear(points); - } - var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; - if (quad) { - path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; - p0 = points[1]; - pi = 2; - } - if (tangents.length > 1) { - t = tangents[1]; - p = points[pi]; - pi++; - path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - for (var i = 2; i < tangents.length; i++, pi++) { - p = points[pi]; - t = tangents[i]; - path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; +} + +},{"./GLError":95,"./reflect":98}],98:[function(require,module,exports){ +'use strict' + +module.exports = makeReflectTypes + +//Construct type info for reflection. +// +// This iterates over the flattened list of uniform type values and smashes them into a JSON object. +// +// The leaves of the resulting object are either indices or type strings representing primitive glslify types +function makeReflectTypes(uniforms, useIndex) { + var obj = {} + for(var i=0; i 1) { + if(!(x[0] in o)) { + o[x[0]] = [] + } + o = o[x[0]] + for(var k=1; k 1) { + for(var j=0; j 9) { - s = d * 3 / Math.sqrt(s); - m[i] = s * a; - m[i + 1] = s * b; - } + return result +} + +},{}],100:[function(require,module,exports){ +'use strict' + +exports.shader = getShaderReference +exports.program = createProgram + +var GLError = require("./GLError") +var formatCompilerError = require('gl-format-compiler-error'); + +var weakMap = typeof WeakMap === 'undefined' ? require('weakmap-shim') : WeakMap +var CACHE = new weakMap() + +var SHADER_COUNTER = 0 + +function ShaderReference(id, src, type, shader, programs, count, cache) { + this.id = id + this.src = src + this.type = type + this.shader = shader + this.count = count + this.programs = [] + this.cache = cache +} + +ShaderReference.prototype.dispose = function() { + if(--this.count === 0) { + var cache = this.cache + var gl = cache.gl + + //Remove program references + var programs = this.programs + for(var i=0, n=programs.length; i π) + ",1 " + p; + return program +} + +proto.getProgram = function(vref, fref, attribs, locations) { + var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') + var prog = this.programs[token] + if(!prog || !this.gl.isProgram(prog)) { + this.programs[token] = prog = linkProgram( + this.gl, + vref.shader, + fref.shader, + attribs, + locations) + vref.programs.push(token) + fref.programs.push(token) + } + return prog +} + +function getCache(gl) { + var ctxCache = CACHE.get(gl) + if(!ctxCache) { + ctxCache = new ContextCache(gl) + CACHE.set(gl, ctxCache) + } + return ctxCache +} + +function getShaderReference(gl, type, src) { + return getCache(gl).getShaderReference(type, src) +} + +function createProgram(gl, vref, fref, attribs, locations) { + return getCache(gl).getProgram(vref, fref, attribs, locations) +} + +},{"./GLError":95,"gl-format-compiler-error":101,"weakmap-shim":119}],101:[function(require,module,exports){ + +var sprintf = require('sprintf-js').sprintf; +var glConstants = require('gl-constants/lookup'); +var shaderName = require('glsl-shader-name'); +var addLineNumbers = require('add-line-numbers'); + +module.exports = formatCompilerError; + +function formatCompilerError(errLog, src, type) { + "use strict"; + + var name = shaderName(src) || 'of unknown name (see npm glsl-shader-name)'; + + var typeName = 'unknown type'; + if (type !== undefined) { + typeName = type === glConstants.FRAGMENT_SHADER ? 'fragment' : 'vertex' } - function curve(r0, p0, r1, p1) { - return "Q 0,0 " + p1; + + var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name); + var shortForm = sprintf("%s%s", longForm, errLog); + + var errorStrings = errLog.split('\n'); + var errors = {}; + + for (var i = 0; i < errorStrings.length; i++) { + var errorString = errorStrings[i]; + if (errorString === '') continue; + var lineNo = parseInt(errorString.split(':')[2]); + if (isNaN(lineNo)) { + throw new Error(sprintf('Could not parse error: %s', errorString)); + } + errors[lineNo] = errorString; } - chord.radius = function(v) { - if (!arguments.length) return radius; - radius = d3_functor(v); - return chord; - }; - chord.source = function(v) { - if (!arguments.length) return source; - source = d3_functor(v); - return chord; - }; - chord.target = function(v) { - if (!arguments.length) return target; - target = d3_functor(v); - return chord; - }; - chord.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return chord; - }; - chord.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return chord; - }; - return chord; - }; - function d3_svg_chordRadius(d) { - return d.radius; - } - d3.svg.diagonal = function() { - var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; - function diagonal(d, i) { - var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { - x: p0.x, - y: m - }, { - x: p3.x, - y: m - }, p3 ]; - p = p.map(projection); - return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + + var lines = addLineNumbers(src).split('\n'); + + for (var i = 0; i < lines.length; i++) { + if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue; + var line = lines[i]; + longForm += line + '\n'; + if (errors[i+1]) { + var e = errors[i+1]; + e = e.substr(e.split(':', 3).join(':').length + 1).trim(); + longForm += sprintf('^^^ %s\n\n', e); + } } - diagonal.source = function(x) { - if (!arguments.length) return source; - source = d3_functor(x); - return diagonal; - }; - diagonal.target = function(x) { - if (!arguments.length) return target; - target = d3_functor(x); - return diagonal; - }; - diagonal.projection = function(x) { - if (!arguments.length) return projection; - projection = x; - return diagonal; + + return { + long: longForm.trim(), + short: shortForm.trim() }; - return diagonal; - }; - function d3_svg_diagonalProjection(d) { - return [ d.x, d.y ]; +} + + +},{"add-line-numbers":102,"gl-constants/lookup":106,"glsl-shader-name":107,"sprintf-js":116}],102:[function(require,module,exports){ +var padLeft = require('pad-left') + +module.exports = addLineNumbers +function addLineNumbers (string, start, delim) { + start = typeof start === 'number' ? start : 1 + delim = delim || ': ' + + var lines = string.split(/\r?\n/) + var totalDigits = String(lines.length + start - 1).length + return lines.map(function (line, i) { + var c = i + start + var digits = String(c).length + var prefix = padLeft(c, totalDigits - digits) + return prefix + delim + line + }).join('\n') +} + +},{"pad-left":103}],103:[function(require,module,exports){ +/*! + * pad-left + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT license. + */ + +'use strict'; + +var repeat = require('repeat-string'); + +module.exports = function padLeft(str, num, ch) { + ch = typeof ch !== 'undefined' ? (ch + '') : ' '; + return repeat(ch, num) + str; +}; +},{"repeat-string":104}],104:[function(require,module,exports){ +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +'use strict'; + +/** + * Results cache + */ + +var res = ''; +var cache; + +/** + * Expose `repeat` + */ + +module.exports = repeat; + +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ + +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('repeat-string expects a string.'); } - d3.svg.diagonal.radial = function() { - var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; - diagonal.projection = function(x) { - return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; - }; - return diagonal; - }; - function d3_svg_diagonalRadialProjection(projection) { - return function() { - var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; - return [ r * Math.cos(a), r * Math.sin(a) ]; - }; + + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; + + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; } - d3.svg.symbol = function() { - var type = d3_svg_symbolType, size = d3_svg_symbolSize; - function symbol(d, i) { - return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + + while (max > res.length && num > 0) { + if (num & 1) { + res += str; } - symbol.type = function(x) { - if (!arguments.length) return type; - type = d3_functor(x); - return symbol; - }; - symbol.size = function(x) { - if (!arguments.length) return size; - size = d3_functor(x); - return symbol; - }; - return symbol; - }; - function d3_svg_symbolSize() { - return 64; - } - function d3_svg_symbolType() { - return "circle"; + + num >>= 1; + if (!num) break; + str += str; } - function d3_svg_symbolCircle(size) { - var r = Math.sqrt(size / π); - return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + + return res.substr(0, max); +} + + +},{}],105:[function(require,module,exports){ +module.exports = { + 0: 'NONE', + 1: 'ONE', + 2: 'LINE_LOOP', + 3: 'LINE_STRIP', + 4: 'TRIANGLES', + 5: 'TRIANGLE_STRIP', + 6: 'TRIANGLE_FAN', + 256: 'DEPTH_BUFFER_BIT', + 512: 'NEVER', + 513: 'LESS', + 514: 'EQUAL', + 515: 'LEQUAL', + 516: 'GREATER', + 517: 'NOTEQUAL', + 518: 'GEQUAL', + 519: 'ALWAYS', + 768: 'SRC_COLOR', + 769: 'ONE_MINUS_SRC_COLOR', + 770: 'SRC_ALPHA', + 771: 'ONE_MINUS_SRC_ALPHA', + 772: 'DST_ALPHA', + 773: 'ONE_MINUS_DST_ALPHA', + 774: 'DST_COLOR', + 775: 'ONE_MINUS_DST_COLOR', + 776: 'SRC_ALPHA_SATURATE', + 1024: 'STENCIL_BUFFER_BIT', + 1028: 'FRONT', + 1029: 'BACK', + 1032: 'FRONT_AND_BACK', + 1280: 'INVALID_ENUM', + 1281: 'INVALID_VALUE', + 1282: 'INVALID_OPERATION', + 1285: 'OUT_OF_MEMORY', + 1286: 'INVALID_FRAMEBUFFER_OPERATION', + 2304: 'CW', + 2305: 'CCW', + 2849: 'LINE_WIDTH', + 2884: 'CULL_FACE', + 2885: 'CULL_FACE_MODE', + 2886: 'FRONT_FACE', + 2928: 'DEPTH_RANGE', + 2929: 'DEPTH_TEST', + 2930: 'DEPTH_WRITEMASK', + 2931: 'DEPTH_CLEAR_VALUE', + 2932: 'DEPTH_FUNC', + 2960: 'STENCIL_TEST', + 2961: 'STENCIL_CLEAR_VALUE', + 2962: 'STENCIL_FUNC', + 2963: 'STENCIL_VALUE_MASK', + 2964: 'STENCIL_FAIL', + 2965: 'STENCIL_PASS_DEPTH_FAIL', + 2966: 'STENCIL_PASS_DEPTH_PASS', + 2967: 'STENCIL_REF', + 2968: 'STENCIL_WRITEMASK', + 2978: 'VIEWPORT', + 3024: 'DITHER', + 3042: 'BLEND', + 3088: 'SCISSOR_BOX', + 3089: 'SCISSOR_TEST', + 3106: 'COLOR_CLEAR_VALUE', + 3107: 'COLOR_WRITEMASK', + 3317: 'UNPACK_ALIGNMENT', + 3333: 'PACK_ALIGNMENT', + 3379: 'MAX_TEXTURE_SIZE', + 3386: 'MAX_VIEWPORT_DIMS', + 3408: 'SUBPIXEL_BITS', + 3410: 'RED_BITS', + 3411: 'GREEN_BITS', + 3412: 'BLUE_BITS', + 3413: 'ALPHA_BITS', + 3414: 'DEPTH_BITS', + 3415: 'STENCIL_BITS', + 3553: 'TEXTURE_2D', + 4352: 'DONT_CARE', + 4353: 'FASTEST', + 4354: 'NICEST', + 5120: 'BYTE', + 5121: 'UNSIGNED_BYTE', + 5122: 'SHORT', + 5123: 'UNSIGNED_SHORT', + 5124: 'INT', + 5125: 'UNSIGNED_INT', + 5126: 'FLOAT', + 5386: 'INVERT', + 5890: 'TEXTURE', + 6401: 'STENCIL_INDEX', + 6402: 'DEPTH_COMPONENT', + 6406: 'ALPHA', + 6407: 'RGB', + 6408: 'RGBA', + 6409: 'LUMINANCE', + 6410: 'LUMINANCE_ALPHA', + 7680: 'KEEP', + 7681: 'REPLACE', + 7682: 'INCR', + 7683: 'DECR', + 7936: 'VENDOR', + 7937: 'RENDERER', + 7938: 'VERSION', + 9728: 'NEAREST', + 9729: 'LINEAR', + 9984: 'NEAREST_MIPMAP_NEAREST', + 9985: 'LINEAR_MIPMAP_NEAREST', + 9986: 'NEAREST_MIPMAP_LINEAR', + 9987: 'LINEAR_MIPMAP_LINEAR', + 10240: 'TEXTURE_MAG_FILTER', + 10241: 'TEXTURE_MIN_FILTER', + 10242: 'TEXTURE_WRAP_S', + 10243: 'TEXTURE_WRAP_T', + 10497: 'REPEAT', + 10752: 'POLYGON_OFFSET_UNITS', + 16384: 'COLOR_BUFFER_BIT', + 32769: 'CONSTANT_COLOR', + 32770: 'ONE_MINUS_CONSTANT_COLOR', + 32771: 'CONSTANT_ALPHA', + 32772: 'ONE_MINUS_CONSTANT_ALPHA', + 32773: 'BLEND_COLOR', + 32774: 'FUNC_ADD', + 32777: 'BLEND_EQUATION_RGB', + 32778: 'FUNC_SUBTRACT', + 32779: 'FUNC_REVERSE_SUBTRACT', + 32819: 'UNSIGNED_SHORT_4_4_4_4', + 32820: 'UNSIGNED_SHORT_5_5_5_1', + 32823: 'POLYGON_OFFSET_FILL', + 32824: 'POLYGON_OFFSET_FACTOR', + 32854: 'RGBA4', + 32855: 'RGB5_A1', + 32873: 'TEXTURE_BINDING_2D', + 32926: 'SAMPLE_ALPHA_TO_COVERAGE', + 32928: 'SAMPLE_COVERAGE', + 32936: 'SAMPLE_BUFFERS', + 32937: 'SAMPLES', + 32938: 'SAMPLE_COVERAGE_VALUE', + 32939: 'SAMPLE_COVERAGE_INVERT', + 32968: 'BLEND_DST_RGB', + 32969: 'BLEND_SRC_RGB', + 32970: 'BLEND_DST_ALPHA', + 32971: 'BLEND_SRC_ALPHA', + 33071: 'CLAMP_TO_EDGE', + 33170: 'GENERATE_MIPMAP_HINT', + 33189: 'DEPTH_COMPONENT16', + 33306: 'DEPTH_STENCIL_ATTACHMENT', + 33635: 'UNSIGNED_SHORT_5_6_5', + 33648: 'MIRRORED_REPEAT', + 33901: 'ALIASED_POINT_SIZE_RANGE', + 33902: 'ALIASED_LINE_WIDTH_RANGE', + 33984: 'TEXTURE0', + 33985: 'TEXTURE1', + 33986: 'TEXTURE2', + 33987: 'TEXTURE3', + 33988: 'TEXTURE4', + 33989: 'TEXTURE5', + 33990: 'TEXTURE6', + 33991: 'TEXTURE7', + 33992: 'TEXTURE8', + 33993: 'TEXTURE9', + 33994: 'TEXTURE10', + 33995: 'TEXTURE11', + 33996: 'TEXTURE12', + 33997: 'TEXTURE13', + 33998: 'TEXTURE14', + 33999: 'TEXTURE15', + 34000: 'TEXTURE16', + 34001: 'TEXTURE17', + 34002: 'TEXTURE18', + 34003: 'TEXTURE19', + 34004: 'TEXTURE20', + 34005: 'TEXTURE21', + 34006: 'TEXTURE22', + 34007: 'TEXTURE23', + 34008: 'TEXTURE24', + 34009: 'TEXTURE25', + 34010: 'TEXTURE26', + 34011: 'TEXTURE27', + 34012: 'TEXTURE28', + 34013: 'TEXTURE29', + 34014: 'TEXTURE30', + 34015: 'TEXTURE31', + 34016: 'ACTIVE_TEXTURE', + 34024: 'MAX_RENDERBUFFER_SIZE', + 34041: 'DEPTH_STENCIL', + 34055: 'INCR_WRAP', + 34056: 'DECR_WRAP', + 34067: 'TEXTURE_CUBE_MAP', + 34068: 'TEXTURE_BINDING_CUBE_MAP', + 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', + 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', + 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', + 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', + 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', + 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', + 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', + 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', + 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', + 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', + 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', + 34342: 'CURRENT_VERTEX_ATTRIB', + 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', + 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', + 34467: 'COMPRESSED_TEXTURE_FORMATS', + 34660: 'BUFFER_SIZE', + 34661: 'BUFFER_USAGE', + 34816: 'STENCIL_BACK_FUNC', + 34817: 'STENCIL_BACK_FAIL', + 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', + 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', + 34877: 'BLEND_EQUATION_ALPHA', + 34921: 'MAX_VERTEX_ATTRIBS', + 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', + 34930: 'MAX_TEXTURE_IMAGE_UNITS', + 34962: 'ARRAY_BUFFER', + 34963: 'ELEMENT_ARRAY_BUFFER', + 34964: 'ARRAY_BUFFER_BINDING', + 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', + 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', + 35040: 'STREAM_DRAW', + 35044: 'STATIC_DRAW', + 35048: 'DYNAMIC_DRAW', + 35632: 'FRAGMENT_SHADER', + 35633: 'VERTEX_SHADER', + 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', + 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', + 35663: 'SHADER_TYPE', + 35664: 'FLOAT_VEC2', + 35665: 'FLOAT_VEC3', + 35666: 'FLOAT_VEC4', + 35667: 'INT_VEC2', + 35668: 'INT_VEC3', + 35669: 'INT_VEC4', + 35670: 'BOOL', + 35671: 'BOOL_VEC2', + 35672: 'BOOL_VEC3', + 35673: 'BOOL_VEC4', + 35674: 'FLOAT_MAT2', + 35675: 'FLOAT_MAT3', + 35676: 'FLOAT_MAT4', + 35678: 'SAMPLER_2D', + 35680: 'SAMPLER_CUBE', + 35712: 'DELETE_STATUS', + 35713: 'COMPILE_STATUS', + 35714: 'LINK_STATUS', + 35715: 'VALIDATE_STATUS', + 35716: 'INFO_LOG_LENGTH', + 35717: 'ATTACHED_SHADERS', + 35718: 'ACTIVE_UNIFORMS', + 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', + 35720: 'SHADER_SOURCE_LENGTH', + 35721: 'ACTIVE_ATTRIBUTES', + 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', + 35724: 'SHADING_LANGUAGE_VERSION', + 35725: 'CURRENT_PROGRAM', + 36003: 'STENCIL_BACK_REF', + 36004: 'STENCIL_BACK_VALUE_MASK', + 36005: 'STENCIL_BACK_WRITEMASK', + 36006: 'FRAMEBUFFER_BINDING', + 36007: 'RENDERBUFFER_BINDING', + 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', + 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', + 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', + 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', + 36053: 'FRAMEBUFFER_COMPLETE', + 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', + 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', + 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', + 36061: 'FRAMEBUFFER_UNSUPPORTED', + 36064: 'COLOR_ATTACHMENT0', + 36096: 'DEPTH_ATTACHMENT', + 36128: 'STENCIL_ATTACHMENT', + 36160: 'FRAMEBUFFER', + 36161: 'RENDERBUFFER', + 36162: 'RENDERBUFFER_WIDTH', + 36163: 'RENDERBUFFER_HEIGHT', + 36164: 'RENDERBUFFER_INTERNAL_FORMAT', + 36168: 'STENCIL_INDEX8', + 36176: 'RENDERBUFFER_RED_SIZE', + 36177: 'RENDERBUFFER_GREEN_SIZE', + 36178: 'RENDERBUFFER_BLUE_SIZE', + 36179: 'RENDERBUFFER_ALPHA_SIZE', + 36180: 'RENDERBUFFER_DEPTH_SIZE', + 36181: 'RENDERBUFFER_STENCIL_SIZE', + 36194: 'RGB565', + 36336: 'LOW_FLOAT', + 36337: 'MEDIUM_FLOAT', + 36338: 'HIGH_FLOAT', + 36339: 'LOW_INT', + 36340: 'MEDIUM_INT', + 36341: 'HIGH_INT', + 36346: 'SHADER_COMPILER', + 36347: 'MAX_VERTEX_UNIFORM_VECTORS', + 36348: 'MAX_VARYING_VECTORS', + 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', + 37440: 'UNPACK_FLIP_Y_WEBGL', + 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', + 37442: 'CONTEXT_LOST_WEBGL', + 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', + 37444: 'BROWSER_DEFAULT_WEBGL' +} + +},{}],106:[function(require,module,exports){ +var gl10 = require('./1.0/numbers') + +module.exports = function lookupConstant (number) { + return gl10[number] +} + +},{"./1.0/numbers":105}],107:[function(require,module,exports){ +var tokenize = require('glsl-tokenizer') +var atob = require('atob-lite') + +module.exports = getName + +function getName(src) { + var tokens = Array.isArray(src) + ? src + : tokenize(src) + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i] + if (token.type !== 'preprocessor') continue + var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) + if (!match) continue + if (!match[2]) continue + + var b64 = match[1] + var name = match[2] + + return (b64 ? atob(name) : name).trim() } - var d3_svg_symbols = d3.map({ - circle: d3_svg_symbolCircle, - cross: function(size) { - var r = Math.sqrt(size / 5) / 2; - return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; - }, - diamond: function(size) { - var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; - return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; - }, - square: function(size) { - var r = Math.sqrt(size) / 2; - return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; - }, - "triangle-down": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; - }, - "triangle-up": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; - } - }); - d3.svg.symbolTypes = d3_svg_symbols.keys(); - var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); - d3_selectionPrototype.transition = function(name) { - var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { - time: Date.now(), - ease: d3_ease_cubicInOut, - delay: 0, - duration: 250 - }; - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); - subgroup.push(node); - } - } - return d3_transition(subgroups, ns, id); - }; - d3_selectionPrototype.interrupt = function(name) { - return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); - }; - var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); - function d3_selection_interruptNS(ns) { - return function() { - var lock, activeId, active; - if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { - active.timer.c = null; - active.timer.t = NaN; - if (--lock.count) delete lock[activeId]; else delete this[ns]; - lock.active += .5; - active.event && active.event.interrupt.call(this, this.__data__, active.index); - } - }; +} + +},{"atob-lite":108,"glsl-tokenizer":115}],108:[function(require,module,exports){ +module.exports = function _atob(str) { + return atob(str) +} + +},{}],109:[function(require,module,exports){ +module.exports = tokenize + +var literals100 = require('./lib/literals') + , operators = require('./lib/operators') + , builtins100 = require('./lib/builtins') + , literals300es = require('./lib/literals-300es') + , builtins300es = require('./lib/builtins-300es') + +var NORMAL = 999 // <-- never emitted + , TOKEN = 9999 // <-- never emitted + , BLOCK_COMMENT = 0 + , LINE_COMMENT = 1 + , PREPROCESSOR = 2 + , OPERATOR = 3 + , INTEGER = 4 + , FLOAT = 5 + , IDENT = 6 + , BUILTIN = 7 + , KEYWORD = 8 + , WHITESPACE = 9 + , EOF = 10 + , HEX = 11 + +var map = [ + 'block-comment' + , 'line-comment' + , 'preprocessor' + , 'operator' + , 'integer' + , 'float' + , 'ident' + , 'builtin' + , 'keyword' + , 'whitespace' + , 'eof' + , 'integer' +] + +function tokenize(opt) { + var i = 0 + , total = 0 + , mode = NORMAL + , c + , last + , content = [] + , tokens = [] + , token_idx = 0 + , token_offs = 0 + , line = 1 + , col = 0 + , start = 0 + , isnum = false + , isoperator = false + , input = '' + , len + + opt = opt || {} + var allBuiltins = builtins100 + var allLiterals = literals100 + if (opt.version === '300 es') { + allBuiltins = builtins300es + allLiterals = literals300es } - function d3_transition(groups, ns, id) { - d3_subclass(groups, d3_transitionPrototype); - groups.namespace = ns; - groups.id = id; - return groups; + + return function(data) { + tokens = [] + if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data) + return end() } - var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; - d3_transitionPrototype.call = d3_selectionPrototype.call; - d3_transitionPrototype.empty = d3_selectionPrototype.empty; - d3_transitionPrototype.node = d3_selectionPrototype.node; - d3_transitionPrototype.size = d3_selectionPrototype.size; - d3.transition = function(selection, name) { - return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); - }; - d3.transition.prototype = d3_transitionPrototype; - d3_transitionPrototype.select = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { - if ("__data__" in node) subnode.__data__ = node.__data__; - d3_transitionNode(subnode, i, ns, id, node[ns][id]); - subgroup.push(subnode); - } else { - subgroup.push(null); - } - } + + function token(data) { + if (data.length) { + tokens.push({ + type: map[mode] + , data: data + , position: start + , line: line + , column: col + }) } - return d3_transition(subgroups, ns, id); - }; - d3_transitionPrototype.selectAll = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - transition = node[ns][id]; - subnodes = selector.call(node, node.__data__, i, j); - subgroups.push(subgroup = []); - for (var k = -1, o = subnodes.length; ++k < o; ) { - if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); - subgroup.push(subnode); - } - } + } + + function write(chunk) { + i = 0 + input += chunk + len = input.length + + var last + + while(c = input[i], i < len) { + last = i + + switch(mode) { + case BLOCK_COMMENT: i = block_comment(); break + case LINE_COMMENT: i = line_comment(); break + case PREPROCESSOR: i = preprocessor(); break + case OPERATOR: i = operator(); break + case INTEGER: i = integer(); break + case HEX: i = hex(); break + case FLOAT: i = decimal(); break + case TOKEN: i = readtoken(); break + case WHITESPACE: i = whitespace(); break + case NORMAL: i = normal(); break } - } - return d3_transition(subgroups, ns, id); - }; - d3_transitionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); + + if(last !== i) { + switch(input[last]) { + case '\n': col = 0; ++line; break + default: ++col; break } } } - return d3_transition(subgroups, this.namespace, this.id); - }; - d3_transitionPrototype.tween = function(name, tween) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) return this.node()[ns][id].tween.get(name); - return d3_selection_each(this, tween == null ? function(node) { - node[ns][id].tween.remove(name); - } : function(node) { - node[ns][id].tween.set(name, tween); - }); - }; - function d3_transition_tween(groups, name, value, tween) { - var id = groups.id, ns = groups.namespace; - return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { - node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); - } : (value = tween(value), function(node) { - node[ns][id].tween.set(name, value); - })); + + total += i + input = input.slice(i) + return tokens } - d3_transitionPrototype.attr = function(nameNS, value) { - if (arguments.length < 2) { - for (value in nameNS) this.attr(value, nameNS[value]); - return this; + + function end(chunk) { + if(content.length) { + token(content.join('')) } - var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); - function attrNull() { - this.removeAttribute(name); + + mode = EOF + token('(eof)') + return tokens + } + + function normal() { + content = content.length ? [] : content + + if(last === '/' && c === '*') { + start = total + i - 1 + mode = BLOCK_COMMENT + last = c + return i + 1 } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); + + if(last === '/' && c === '/') { + start = total + i - 1 + mode = LINE_COMMENT + last = c + return i + 1 } - function attrTween(b) { - return b == null ? attrNull : (b += "", function() { - var a = this.getAttribute(name), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttribute(name, i(t)); - }); - }); + + if(c === '#') { + mode = PREPROCESSOR + start = total + i + return i } - function attrTweenNS(b) { - return b == null ? attrNullNS : (b += "", function() { - var a = this.getAttributeNS(name.space, name.local), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttributeNS(name.space, name.local, i(t)); - }); - }); + + if(/\s/.test(c)) { + mode = WHITESPACE + start = total + i + return i } - return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.attrTween = function(nameNS, tween) { - var name = d3.ns.qualify(nameNS); - function attrTween(d, i) { - var f = tween.call(this, d, i, this.getAttribute(name)); - return f && function(t) { - this.setAttribute(name, f(t)); - }; + + isnum = /\d/.test(c) + isoperator = /[^\w_]/.test(c) + + start = total + i + mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN + return i + } + + function whitespace() { + if(/[^\s]/g.test(c)) { + token(content.join('')) + mode = NORMAL + return i } - function attrTweenNS(d, i) { - var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); - return f && function(t) { - this.setAttributeNS(name.space, name.local, f(t)); - }; + content.push(c) + last = c + return i + 1 + } + + function preprocessor() { + if((c === '\r' || c === '\n') && last !== '\\') { + token(content.join('')) + mode = NORMAL + return i } - return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.style(priority, name[priority], value); - return this; - } - priority = ""; + content.push(c) + last = c + return i + 1 + } + + function line_comment() { + return preprocessor() + } + + function block_comment() { + if(c === '/' && last === '*') { + content.push(c) + token(content.join('')) + mode = NORMAL + return i + 1 } - function styleNull() { - this.style.removeProperty(name); + + content.push(c) + last = c + return i + 1 + } + + function operator() { + if(last === '.' && /\d/.test(c)) { + mode = FLOAT + return i } - function styleString(b) { - return b == null ? styleNull : (b += "", function() { - var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; - return a !== b && (i = d3_interpolate(a, b), function(t) { - this.style.setProperty(name, i(t), priority); - }); - }); + + if(last === '/' && c === '*') { + mode = BLOCK_COMMENT + return i } - return d3_transition_tween(this, "style." + name, value, styleString); - }; - d3_transitionPrototype.styleTween = function(name, tween, priority) { - if (arguments.length < 3) priority = ""; - function styleTween(d, i) { - var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); - return f && function(t) { - this.style.setProperty(name, f(t), priority); - }; + + if(last === '/' && c === '/') { + mode = LINE_COMMENT + return i } - return this.tween("style." + name, styleTween); - }; - d3_transitionPrototype.text = function(value) { - return d3_transition_tween(this, "text", value, d3_transition_text); - }; - function d3_transition_text(b) { - if (b == null) b = ""; - return function() { - this.textContent = b; - }; - } - d3_transitionPrototype.remove = function() { - var ns = this.namespace; - return this.each("end.transition", function() { - var p; - if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); - }); - }; - d3_transitionPrototype.ease = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].ease; - if (typeof value !== "function") value = d3.ease.apply(d3, arguments); - return d3_selection_each(this, function(node) { - node[ns][id].ease = value; - }); - }; - d3_transitionPrototype.delay = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].delay; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node[ns][id].delay = +value.call(node, node.__data__, i, j); - } : (value = +value, function(node) { - node[ns][id].delay = value; - })); - }; - d3_transitionPrototype.duration = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].duration; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); - } : (value = Math.max(1, value), function(node) { - node[ns][id].duration = value; - })); - }; - d3_transitionPrototype.each = function(type, listener) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) { - var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; - try { - d3_transitionInheritId = id; - d3_selection_each(this, function(node, i, j) { - d3_transitionInherit = node[ns][id]; - type.call(node, node.__data__, i, j); - }); - } finally { - d3_transitionInherit = inherit; - d3_transitionInheritId = inheritId; - } - } else { - d3_selection_each(this, function(node) { - var transition = node[ns][id]; - (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); - }); + + if(c === '.' && content.length) { + while(determine_operator(content)); + + mode = FLOAT + return i } - return this; - }; - d3_transitionPrototype.transition = function() { - var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if (node = group[i]) { - transition = node[ns][id0]; - d3_transitionNode(node, i, ns, id1, { - time: transition.time, - ease: transition.ease, - delay: transition.delay + transition.duration, - duration: transition.duration - }); - } - subgroup.push(node); + + if(c === ';' || c === ')' || c === '(') { + if(content.length) while(determine_operator(content)); + token(c) + mode = NORMAL + return i + 1 + } + + var is_composite_operator = content.length === 2 && c !== '=' + if(/[\w_\d\s]/.test(c) || is_composite_operator) { + while(determine_operator(content)); + mode = NORMAL + return i + } + + content.push(c) + last = c + return i + 1 + } + + function determine_operator(buf) { + var j = 0 + , idx + , res + + do { + idx = operators.indexOf(buf.slice(0, buf.length + j).join('')) + res = operators[idx] + + if(idx === -1) { + if(j-- + buf.length > 0) continue + res = buf.slice(0, 1).join('') } + + token(res) + + start += res.length + content = content.slice(res.length) + return content.length + } while(1) + } + + function hex() { + if(/[^a-fA-F0-9]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i } - return d3_transition(subgroups, ns, id1); - }; - function d3_transitionNamespace(name) { - return name == null ? "__transition__" : "__transition_" + name + "__"; + + content.push(c) + last = c + return i + 1 } - function d3_transitionNode(node, i, ns, id, inherit) { - var lock = node[ns] || (node[ns] = { - active: 0, - count: 0 - }), transition = lock[id], time, timer, duration, ease, tweens; - function schedule(elapsed) { - var delay = transition.delay; - timer.t = delay + time; - if (delay <= elapsed) return start(elapsed - delay); - timer.c = start; + + function integer() { + if(c === '.') { + content.push(c) + mode = FLOAT + last = c + return i + 1 } - function start(elapsed) { - var activeId = lock.active, active = lock[activeId]; - if (active) { - active.timer.c = null; - active.timer.t = NaN; - --lock.count; - delete lock[activeId]; - active.event && active.event.interrupt.call(node, node.__data__, active.index); - } - for (var cancelId in lock) { - if (+cancelId < id) { - var cancel = lock[cancelId]; - cancel.timer.c = null; - cancel.timer.t = NaN; - --lock.count; - delete lock[cancelId]; - } - } - timer.c = tick; - d3_timer(function() { - if (timer.c && tick(elapsed || 1)) { - timer.c = null; - timer.t = NaN; - } - return 1; - }, 0, time); - lock.active = id; - transition.event && transition.event.start.call(node, node.__data__, i); - tweens = []; - transition.tween.forEach(function(key, value) { - if (value = value.call(node, node.__data__, i)) { - tweens.push(value); - } - }); - ease = transition.ease; - duration = transition.duration; + + if(/[eE]/.test(c)) { + content.push(c) + mode = FLOAT + last = c + return i + 1 + } + + if(c === 'x' && content.length === 1 && content[0] === '0') { + mode = HEX + content.push(c) + last = c + return i + 1 + } + + if(/[^\d]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i + } + + content.push(c) + last = c + return i + 1 + } + + function decimal() { + if(c === 'f') { + content.push(c) + last = c + i += 1 } - function tick(elapsed) { - var t = elapsed / duration, e = ease(t), n = tweens.length; - while (n > 0) { - tweens[--n].call(node, e); - } - if (t >= 1) { - transition.event && transition.event.end.call(node, node.__data__, i); - if (--lock.count) delete lock[id]; else delete node[ns]; - return 1; + + if(/[eE]/.test(c)) { + content.push(c) + last = c + return i + 1 + } + + if (c === '-' && /[eE]/.test(last)) { + content.push(c) + last = c + return i + 1 + } + + if(/[^\d]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i + } + + content.push(c) + last = c + return i + 1 + } + + function readtoken() { + if(/[^\d\w_]/.test(c)) { + var contentstr = content.join('') + if(allLiterals.indexOf(contentstr) > -1) { + mode = KEYWORD + } else if(allBuiltins.indexOf(contentstr) > -1) { + mode = BUILTIN + } else { + mode = IDENT } + token(content.join('')) + mode = NORMAL + return i } - if (!transition) { - time = inherit.time; - timer = d3_timer(schedule, 0, time); - transition = lock[id] = { - tween: new d3_Map(), - time: time, - timer: timer, - delay: inherit.delay, - duration: inherit.duration, - ease: inherit.ease, - index: i - }; - inherit = null; - ++lock.count; + content.push(c) + last = c + return i + 1 + } +} + +},{"./lib/builtins":111,"./lib/builtins-300es":110,"./lib/literals":113,"./lib/literals-300es":112,"./lib/operators":114}],110:[function(require,module,exports){ +// 300es builtins/reserved words that were previously valid in v100 +var v100 = require('./builtins') + +// The texture2D|Cube functions have been removed +// And the gl_ features are updated +v100 = v100.slice().filter(function (b) { + return !/^(gl\_|texture)/.test(b) +}) + +module.exports = v100.concat([ + // the updated gl_ constants + 'gl_VertexID' + , 'gl_InstanceID' + , 'gl_Position' + , 'gl_PointSize' + , 'gl_FragCoord' + , 'gl_FrontFacing' + , 'gl_FragDepth' + , 'gl_PointCoord' + , 'gl_MaxVertexAttribs' + , 'gl_MaxVertexUniformVectors' + , 'gl_MaxVertexOutputVectors' + , 'gl_MaxFragmentInputVectors' + , 'gl_MaxVertexTextureImageUnits' + , 'gl_MaxCombinedTextureImageUnits' + , 'gl_MaxTextureImageUnits' + , 'gl_MaxFragmentUniformVectors' + , 'gl_MaxDrawBuffers' + , 'gl_MinProgramTexelOffset' + , 'gl_MaxProgramTexelOffset' + , 'gl_DepthRangeParameters' + , 'gl_DepthRange' + + // other builtins + , 'trunc' + , 'round' + , 'roundEven' + , 'isnan' + , 'isinf' + , 'floatBitsToInt' + , 'floatBitsToUint' + , 'intBitsToFloat' + , 'uintBitsToFloat' + , 'packSnorm2x16' + , 'unpackSnorm2x16' + , 'packUnorm2x16' + , 'unpackUnorm2x16' + , 'packHalf2x16' + , 'unpackHalf2x16' + , 'outerProduct' + , 'transpose' + , 'determinant' + , 'inverse' + , 'texture' + , 'textureSize' + , 'textureProj' + , 'textureLod' + , 'textureOffset' + , 'texelFetch' + , 'texelFetchOffset' + , 'textureProjOffset' + , 'textureLodOffset' + , 'textureProjLod' + , 'textureProjLodOffset' + , 'textureGrad' + , 'textureGradOffset' + , 'textureProjGrad' + , 'textureProjGradOffset' +]) + +},{"./builtins":111}],111:[function(require,module,exports){ +module.exports = [ + // Keep this list sorted + 'abs' + , 'acos' + , 'all' + , 'any' + , 'asin' + , 'atan' + , 'ceil' + , 'clamp' + , 'cos' + , 'cross' + , 'dFdx' + , 'dFdy' + , 'degrees' + , 'distance' + , 'dot' + , 'equal' + , 'exp' + , 'exp2' + , 'faceforward' + , 'floor' + , 'fract' + , 'gl_BackColor' + , 'gl_BackLightModelProduct' + , 'gl_BackLightProduct' + , 'gl_BackMaterial' + , 'gl_BackSecondaryColor' + , 'gl_ClipPlane' + , 'gl_ClipVertex' + , 'gl_Color' + , 'gl_DepthRange' + , 'gl_DepthRangeParameters' + , 'gl_EyePlaneQ' + , 'gl_EyePlaneR' + , 'gl_EyePlaneS' + , 'gl_EyePlaneT' + , 'gl_Fog' + , 'gl_FogCoord' + , 'gl_FogFragCoord' + , 'gl_FogParameters' + , 'gl_FragColor' + , 'gl_FragCoord' + , 'gl_FragData' + , 'gl_FragDepth' + , 'gl_FragDepthEXT' + , 'gl_FrontColor' + , 'gl_FrontFacing' + , 'gl_FrontLightModelProduct' + , 'gl_FrontLightProduct' + , 'gl_FrontMaterial' + , 'gl_FrontSecondaryColor' + , 'gl_LightModel' + , 'gl_LightModelParameters' + , 'gl_LightModelProducts' + , 'gl_LightProducts' + , 'gl_LightSource' + , 'gl_LightSourceParameters' + , 'gl_MaterialParameters' + , 'gl_MaxClipPlanes' + , 'gl_MaxCombinedTextureImageUnits' + , 'gl_MaxDrawBuffers' + , 'gl_MaxFragmentUniformComponents' + , 'gl_MaxLights' + , 'gl_MaxTextureCoords' + , 'gl_MaxTextureImageUnits' + , 'gl_MaxTextureUnits' + , 'gl_MaxVaryingFloats' + , 'gl_MaxVertexAttribs' + , 'gl_MaxVertexTextureImageUnits' + , 'gl_MaxVertexUniformComponents' + , 'gl_ModelViewMatrix' + , 'gl_ModelViewMatrixInverse' + , 'gl_ModelViewMatrixInverseTranspose' + , 'gl_ModelViewMatrixTranspose' + , 'gl_ModelViewProjectionMatrix' + , 'gl_ModelViewProjectionMatrixInverse' + , 'gl_ModelViewProjectionMatrixInverseTranspose' + , 'gl_ModelViewProjectionMatrixTranspose' + , 'gl_MultiTexCoord0' + , 'gl_MultiTexCoord1' + , 'gl_MultiTexCoord2' + , 'gl_MultiTexCoord3' + , 'gl_MultiTexCoord4' + , 'gl_MultiTexCoord5' + , 'gl_MultiTexCoord6' + , 'gl_MultiTexCoord7' + , 'gl_Normal' + , 'gl_NormalMatrix' + , 'gl_NormalScale' + , 'gl_ObjectPlaneQ' + , 'gl_ObjectPlaneR' + , 'gl_ObjectPlaneS' + , 'gl_ObjectPlaneT' + , 'gl_Point' + , 'gl_PointCoord' + , 'gl_PointParameters' + , 'gl_PointSize' + , 'gl_Position' + , 'gl_ProjectionMatrix' + , 'gl_ProjectionMatrixInverse' + , 'gl_ProjectionMatrixInverseTranspose' + , 'gl_ProjectionMatrixTranspose' + , 'gl_SecondaryColor' + , 'gl_TexCoord' + , 'gl_TextureEnvColor' + , 'gl_TextureMatrix' + , 'gl_TextureMatrixInverse' + , 'gl_TextureMatrixInverseTranspose' + , 'gl_TextureMatrixTranspose' + , 'gl_Vertex' + , 'greaterThan' + , 'greaterThanEqual' + , 'inversesqrt' + , 'length' + , 'lessThan' + , 'lessThanEqual' + , 'log' + , 'log2' + , 'matrixCompMult' + , 'max' + , 'min' + , 'mix' + , 'mod' + , 'normalize' + , 'not' + , 'notEqual' + , 'pow' + , 'radians' + , 'reflect' + , 'refract' + , 'sign' + , 'sin' + , 'smoothstep' + , 'sqrt' + , 'step' + , 'tan' + , 'texture2D' + , 'texture2DLod' + , 'texture2DProj' + , 'texture2DProjLod' + , 'textureCube' + , 'textureCubeLod' + , 'texture2DLodEXT' + , 'texture2DProjLodEXT' + , 'textureCubeLodEXT' + , 'texture2DGradEXT' + , 'texture2DProjGradEXT' + , 'textureCubeGradEXT' +] + +},{}],112:[function(require,module,exports){ +var v100 = require('./literals') + +module.exports = v100.slice().concat([ + 'layout' + , 'centroid' + , 'smooth' + , 'case' + , 'mat2x2' + , 'mat2x3' + , 'mat2x4' + , 'mat3x2' + , 'mat3x3' + , 'mat3x4' + , 'mat4x2' + , 'mat4x3' + , 'mat4x4' + , 'uint' + , 'uvec2' + , 'uvec3' + , 'uvec4' + , 'samplerCubeShadow' + , 'sampler2DArray' + , 'sampler2DArrayShadow' + , 'isampler2D' + , 'isampler3D' + , 'isamplerCube' + , 'isampler2DArray' + , 'usampler2D' + , 'usampler3D' + , 'usamplerCube' + , 'usampler2DArray' + , 'coherent' + , 'restrict' + , 'readonly' + , 'writeonly' + , 'resource' + , 'atomic_uint' + , 'noperspective' + , 'patch' + , 'sample' + , 'subroutine' + , 'common' + , 'partition' + , 'active' + , 'filter' + , 'image1D' + , 'image2D' + , 'image3D' + , 'imageCube' + , 'iimage1D' + , 'iimage2D' + , 'iimage3D' + , 'iimageCube' + , 'uimage1D' + , 'uimage2D' + , 'uimage3D' + , 'uimageCube' + , 'image1DArray' + , 'image2DArray' + , 'iimage1DArray' + , 'iimage2DArray' + , 'uimage1DArray' + , 'uimage2DArray' + , 'image1DShadow' + , 'image2DShadow' + , 'image1DArrayShadow' + , 'image2DArrayShadow' + , 'imageBuffer' + , 'iimageBuffer' + , 'uimageBuffer' + , 'sampler1DArray' + , 'sampler1DArrayShadow' + , 'isampler1D' + , 'isampler1DArray' + , 'usampler1D' + , 'usampler1DArray' + , 'isampler2DRect' + , 'usampler2DRect' + , 'samplerBuffer' + , 'isamplerBuffer' + , 'usamplerBuffer' + , 'sampler2DMS' + , 'isampler2DMS' + , 'usampler2DMS' + , 'sampler2DMSArray' + , 'isampler2DMSArray' + , 'usampler2DMSArray' +]) + +},{"./literals":113}],113:[function(require,module,exports){ +module.exports = [ + // current + 'precision' + , 'highp' + , 'mediump' + , 'lowp' + , 'attribute' + , 'const' + , 'uniform' + , 'varying' + , 'break' + , 'continue' + , 'do' + , 'for' + , 'while' + , 'if' + , 'else' + , 'in' + , 'out' + , 'inout' + , 'float' + , 'int' + , 'void' + , 'bool' + , 'true' + , 'false' + , 'discard' + , 'return' + , 'mat2' + , 'mat3' + , 'mat4' + , 'vec2' + , 'vec3' + , 'vec4' + , 'ivec2' + , 'ivec3' + , 'ivec4' + , 'bvec2' + , 'bvec3' + , 'bvec4' + , 'sampler1D' + , 'sampler2D' + , 'sampler3D' + , 'samplerCube' + , 'sampler1DShadow' + , 'sampler2DShadow' + , 'struct' + + // future + , 'asm' + , 'class' + , 'union' + , 'enum' + , 'typedef' + , 'template' + , 'this' + , 'packed' + , 'goto' + , 'switch' + , 'default' + , 'inline' + , 'noinline' + , 'volatile' + , 'public' + , 'static' + , 'extern' + , 'external' + , 'interface' + , 'long' + , 'short' + , 'double' + , 'half' + , 'fixed' + , 'unsigned' + , 'input' + , 'output' + , 'hvec2' + , 'hvec3' + , 'hvec4' + , 'dvec2' + , 'dvec3' + , 'dvec4' + , 'fvec2' + , 'fvec3' + , 'fvec4' + , 'sampler2DRect' + , 'sampler3DRect' + , 'sampler2DRectShadow' + , 'sizeof' + , 'cast' + , 'namespace' + , 'using' +] + +},{}],114:[function(require,module,exports){ +module.exports = [ + '<<=' + , '>>=' + , '++' + , '--' + , '<<' + , '>>' + , '<=' + , '>=' + , '==' + , '!=' + , '&&' + , '||' + , '+=' + , '-=' + , '*=' + , '/=' + , '%=' + , '&=' + , '^^' + , '^=' + , '|=' + , '(' + , ')' + , '[' + , ']' + , '.' + , '!' + , '~' + , '*' + , '/' + , '%' + , '+' + , '-' + , '<' + , '>' + , '&' + , '^' + , '|' + , '?' + , ':' + , '=' + , ',' + , ';' + , '{' + , '}' +] + +},{}],115:[function(require,module,exports){ +var tokenize = require('./index') + +module.exports = tokenizeString + +function tokenizeString(str, opt) { + var generator = tokenize(opt) + var tokens = [] + + tokens = tokens.concat(generator(str)) + tokens = tokens.concat(generator(null)) + + return tokens +} + +},{"./index":109}],116:[function(require,module,exports){ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[diefg]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ } - } - d3.svg.axis = function() { - var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; - function axis(g) { - g.each(function() { - var g = d3.select(this); - var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); - var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; - var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), - d3.transition(path)); - tickEnter.append("line"); - tickEnter.append("text"); - var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; - if (orient === "bottom" || orient === "top") { - tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; - text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); - } else { - tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; - text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); - pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); - } - lineEnter.attr(y2, sign * innerTickSize); - textEnter.attr(y1, sign * tickSpacing); - lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); - textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); - if (scale1.rangeBand) { - var x = scale1, dx = x.rangeBand() / 2; - scale0 = scale1 = function(d) { - return x(d) + dx; - }; - } else if (scale0.rangeBand) { - scale0 = scale1; - } else { - tickExit.call(tickTransform, scale1, scale0); + + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) } - tickEnter.call(tickTransform, scale0, scale1); - tickUpdate.call(tickTransform, scale1, scale1); - }); + return sprintf.format.call(null, cache[key], arguments) } - axis.scale = function(x) { - if (!arguments.length) return scale; - scale = x; - return axis; - }; - axis.orient = function(x) { - if (!arguments.length) return orient; - orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; - return axis; - }; - axis.ticks = function() { - if (!arguments.length) return tickArguments_; - tickArguments_ = d3_array(arguments); - return axis; - }; - axis.tickValues = function(x) { - if (!arguments.length) return tickValues; - tickValues = x; - return axis; - }; - axis.tickFormat = function(x) { - if (!arguments.length) return tickFormat_; - tickFormat_ = x; - return axis; - }; - axis.tickSize = function(x) { - var n = arguments.length; - if (!n) return innerTickSize; - innerTickSize = +x; - outerTickSize = +arguments[n - 1]; - return axis; - }; - axis.innerTickSize = function(x) { - if (!arguments.length) return innerTickSize; - innerTickSize = +x; - return axis; - }; - axis.outerTickSize = function(x) { - if (!arguments.length) return outerTickSize; - outerTickSize = +x; - return axis; - }; - axis.tickPadding = function(x) { - if (!arguments.length) return tickPadding; - tickPadding = +x; - return axis; - }; - axis.tickSubdivide = function() { - return arguments.length && axis; - }; - return axis; - }; - var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { - top: 1, - right: 1, - bottom: 1, - left: 1 - }; - function d3_svg_axisX(selection, x0, x1) { - selection.attr("transform", function(d) { - var v0 = x0(d); - return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; - }); - } - function d3_svg_axisY(selection, y0, y1) { - selection.attr("transform", function(d) { - var v0 = y0(d); - return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; - }); - } - d3.svg.brush = function() { - var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; - function brush(g) { - g.each(function() { - var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); - var background = g.selectAll(".background").data([ 0 ]); - background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); - g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); - var resize = g.selectAll(".resize").data(resizes, d3_identity); - resize.exit().remove(); - resize.enter().append("g").attr("class", function(d) { - return "resize " + d; - }).style("cursor", function(d) { - return d3_svg_brushCursor[d]; - }).append("rect").attr("x", function(d) { - return /[ew]$/.test(d) ? -3 : null; - }).attr("y", function(d) { - return /^[ns]/.test(d) ? -3 : null; - }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); - resize.style("display", brush.empty() ? "none" : null); - var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; - if (x) { - range = d3_scaleRange(x); - backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); - redrawX(gUpdate); - } - if (y) { - range = d3_scaleRange(y); - backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); - redrawY(gUpdate); + + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "j": + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "g": + arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output[output.length] = arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } } - redraw(gUpdate); - }); + return output.join("") } - brush.event = function(g) { - g.each(function() { - var event_ = event.of(this, arguments), extent1 = { - x: xExtent, - y: yExtent, - i: xExtentDomain, - j: yExtentDomain - }, extent0 = this.__chart__ || extent1; - this.__chart__ = extent1; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.brush", function() { - xExtentDomain = extent0.i; - yExtentDomain = extent0.j; - xExtent = extent0.x; - yExtent = extent0.y; - event_({ - type: "brushstart" - }); - }).tween("brush:brush", function() { - var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); - xExtentDomain = yExtentDomain = null; - return function(t) { - xExtent = extent1.x = xi(t); - yExtent = extent1.y = yi(t); - event_({ - type: "brush", - mode: "resize" - }); - }; - }).each("end.brush", function() { - xExtentDomain = extent1.i; - yExtentDomain = extent1.j; - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); - }); - } else { - event_({ - type: "brushstart" - }); - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); + + sprintf.cache = {} + + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) } - }); - }; - function redraw(g) { - g.selectAll(".resize").attr("transform", function(d) { - return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; - }); + return parse_tree } - function redrawX(g) { - g.select(".extent").attr("x", xExtent[0]); - g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) } - function redrawY(g) { - g.select(".extent").attr("y", yExtent[0]); - g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() } - function brushstart() { - var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; - var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); - if (d3.event.changedTouches) { - w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); - } else { - w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); - } - g.interrupt().selectAll("*").interrupt(); - if (dragging) { - origin[0] = xExtent[0] - origin[0]; - origin[1] = yExtent[0] - origin[1]; - } else if (resizing) { - var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); - offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; - origin[0] = xExtent[ex]; - origin[1] = yExtent[ey]; - } else if (d3.event.altKey) center = origin.slice(); - g.style("pointer-events", "none").selectAll(".resize").style("display", null); - d3.select("body").style("cursor", eventTarget.style("cursor")); - event_({ - type: "brushstart" - }); - brushmove(); - function keydown() { - if (d3.event.keyCode == 32) { - if (!dragging) { - center = null; - origin[0] -= xExtent[1]; - origin[1] -= yExtent[1]; - dragging = 2; - } - d3_eventPreventDefault(); - } - } - function keyup() { - if (d3.event.keyCode == 32 && dragging == 2) { - origin[0] += xExtent[1]; - origin[1] += yExtent[1]; - dragging = 0; - d3_eventPreventDefault(); - } - } - function brushmove() { - var point = d3.mouse(target), moved = false; - if (offset) { - point[0] += offset[0]; - point[1] += offset[1]; - } - if (!dragging) { - if (d3.event.altKey) { - if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; - origin[0] = xExtent[+(point[0] < center[0])]; - origin[1] = yExtent[+(point[1] < center[1])]; - } else center = null; - } - if (resizingX && move1(point, x, 0)) { - redrawX(g); - moved = true; - } - if (resizingY && move1(point, y, 1)) { - redrawY(g); - moved = true; - } - if (moved) { - redraw(g); - event_({ - type: "brush", - mode: dragging ? "move" : "resize" - }); - } - } - function move1(point, scale, i) { - var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; - if (dragging) { - r0 -= position; - r1 -= size + position; - } - min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; - if (dragging) { - max = (min += position) + size; - } else { - if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); - if (position < min) { - max = min; - min = position; - } else { - max = position; - } - } - if (extent[0] != min || extent[1] != max) { - if (i) yExtentDomain = null; else xExtentDomain = null; - extent[0] = min; - extent[1] = max; - return true; - } - } - function brushend() { - brushmove(); - g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); - d3.select("body").style("cursor", null); - w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); - dragRestore(); - event_({ - type: "brushend" - }); - } + + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf } - brush.x = function(z) { - if (!arguments.length) return x; - x = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.y = function(z) { - if (!arguments.length) return y; - y = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.clamp = function(z) { - if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; - if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; - return brush; - }; - brush.extent = function(z) { - var x0, x1, y0, y1, t; - if (!arguments.length) { - if (x) { - if (xExtentDomain) { - x0 = xExtentDomain[0], x1 = xExtentDomain[1]; - } else { - x0 = xExtent[0], x1 = xExtent[1]; - if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf + + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) } - if (y) { - if (yExtentDomain) { - y0 = yExtentDomain[0], y1 = yExtentDomain[1]; - } else { - y0 = yExtent[0], y1 = yExtent[1]; - if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - } + } +})(typeof window === "undefined" ? this : window); + +},{}],117:[function(require,module,exports){ +var hiddenStore = require('./hidden-store.js'); + +module.exports = createStore; + +function createStore() { + var key = {}; + + return function (obj) { + if ((typeof obj !== 'object' || obj === null) && + typeof obj !== 'function' + ) { + throw new Error('Weakmap-shim: Key must be object') } - return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; - } - if (x) { - x0 = z[0], x1 = z[1]; - if (y) x0 = x0[0], x1 = x1[0]; - xExtentDomain = [ x0, x1 ]; - if (x.invert) x0 = x(x0), x1 = x(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; - } - if (y) { - y0 = z[0], y1 = z[1]; - if (x) y0 = y0[1], y1 = y1[1]; - yExtentDomain = [ y0, y1 ]; - if (y.invert) y0 = y(y0), y1 = y(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; - } - return brush; - }; - brush.clear = function() { - if (!brush.empty()) { - xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; - xExtentDomain = yExtentDomain = null; - } - return brush; - }; - brush.empty = function() { - return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + + var store = obj.valueOf(key); + return store && store.identity === key ? + store : hiddenStore(obj, key); }; - return d3.rebind(brush, event, "on"); - }; - var d3_svg_brushCursor = { - n: "ns-resize", - e: "ew-resize", - s: "ns-resize", - w: "ew-resize", - nw: "nwse-resize", - ne: "nesw-resize", - se: "nwse-resize", - sw: "nesw-resize" - }; - var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; - var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; - var d3_time_formatUtc = d3_time_format.utc; - var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); - d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; - function d3_time_formatIsoNative(date) { - return date.toISOString(); +} + +},{"./hidden-store.js":118}],118:[function(require,module,exports){ +module.exports = hiddenStore; + +function hiddenStore(obj, key) { + var store = { identity: key }; + var valueOf = obj.valueOf; + + Object.defineProperty(obj, "valueOf", { + value: function (value) { + return value !== key ? + valueOf.apply(this, arguments) : store; + }, + writable: true + }); + + return store; +} + +},{}],119:[function(require,module,exports){ +// Original - @Gozola. +// https://gist.github.com/Gozala/1269991 +// This is a reimplemented version (with a few bug fixes). + +var createStore = require('./create-store.js'); + +module.exports = weakMap; + +function weakMap() { + var privates = createStore(); + + return { + 'get': function (key, fallback) { + var store = privates(key) + return store.hasOwnProperty('value') ? + store.value : fallback + }, + 'set': function (key, value) { + privates(key).value = value; + }, + 'has': function(key) { + return 'value' in privates(key); + }, + 'delete': function (key) { + return delete privates(key).value; + } + } +} + +},{"./create-store.js":117}],120:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],121:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],122:[function(require,module,exports){ +(function (global,Buffer){ +'use strict' + +var bits = require('bit-twiddle') +var dup = require('dup') + +//Legacy pool support +if(!global.__TYPEDARRAY_POOL) { + global.__TYPEDARRAY_POOL = { + UINT8 : dup([32, 0]) + , UINT16 : dup([32, 0]) + , UINT32 : dup([32, 0]) + , INT8 : dup([32, 0]) + , INT16 : dup([32, 0]) + , INT32 : dup([32, 0]) + , FLOAT : dup([32, 0]) + , DOUBLE : dup([32, 0]) + , DATA : dup([32, 0]) + , UINT8C : dup([32, 0]) + , BUFFER : dup([32, 0]) } - d3_time_formatIsoNative.parse = function(string) { - var date = new Date(string); - return isNaN(date) ? null : date; - }; - d3_time_formatIsoNative.toString = d3_time_formatIso.toString; - d3_time.second = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 1e3) * 1e3); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 1e3); - }, function(date) { - return date.getSeconds(); - }); - d3_time.seconds = d3_time.second.range; - d3_time.seconds.utc = d3_time.second.utc.range; - d3_time.minute = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 6e4) * 6e4); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 6e4); - }, function(date) { - return date.getMinutes(); - }); - d3_time.minutes = d3_time.minute.range; - d3_time.minutes.utc = d3_time.minute.utc.range; - d3_time.hour = d3_time_interval(function(date) { - var timezone = date.getTimezoneOffset() / 60; - return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 36e5); - }, function(date) { - return date.getHours(); - }); - d3_time.hours = d3_time.hour.range; - d3_time.hours.utc = d3_time.hour.utc.range; - d3_time.month = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setDate(1); - return date; - }, function(date, offset) { - date.setMonth(date.getMonth() + offset); - }, function(date) { - return date.getMonth(); - }); - d3_time.months = d3_time.month.range; - d3_time.months.utc = d3_time.month.utc.range; - function d3_time_scale(linear, methods, format) { - function scale(x) { - return linear(x); +} + +var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' +var POOL = global.__TYPEDARRAY_POOL + +//Upgrade pool +if(!POOL.UINT8C) { + POOL.UINT8C = dup([32, 0]) +} +if(!POOL.BUFFER) { + POOL.BUFFER = dup([32, 0]) +} + +//New technique: Only allocate from ArrayBufferView and Buffer +var DATA = POOL.DATA + , BUFFER = POOL.BUFFER + +exports.free = function free(array) { + if(Buffer.isBuffer(array)) { + BUFFER[bits.log2(array.length)].push(array) + } else { + if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { + array = array.buffer } - scale.invert = function(x) { - return d3_time_scaleDate(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return linear.domain().map(d3_time_scaleDate); - linear.domain(x); - return scale; - }; - function tickMethod(extent, count) { - var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); - return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { - return d / 31536e6; - }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + if(!array) { + return } - scale.nice = function(interval, skip) { - var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); - if (method) interval = method[0], skip = method[1]; - function skipped(date) { - return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; - } - return scale.domain(d3_scale_nice(domain, skip > 1 ? { - floor: function(date) { - while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); - return date; - }, - ceil: function(date) { - while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); - return date; - } - } : interval)); - }; - scale.ticks = function(interval, skip) { - var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { - range: interval - }, skip ]; - if (method) interval = method[0], skip = method[1]; - return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); - }; - scale.tickFormat = function() { - return format; - }; - scale.copy = function() { - return d3_time_scale(linear.copy(), methods, format); - }; - return d3_scale_linearRebind(scale, linear); + var n = array.length || array.byteLength + var log_n = bits.log2(n)|0 + DATA[log_n].push(array) } - function d3_time_scaleDate(t) { - return new Date(t); +} + +function freeArrayBuffer(buffer) { + if(!buffer) { + return } - var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; - var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; - var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { - return d.getMilliseconds(); - } ], [ ":%S", function(d) { - return d.getSeconds(); - } ], [ "%I:%M", function(d) { - return d.getMinutes(); - } ], [ "%I %p", function(d) { - return d.getHours(); - } ], [ "%a %d", function(d) { - return d.getDay() && d.getDate() != 1; - } ], [ "%b %d", function(d) { - return d.getDate() != 1; - } ], [ "%B", function(d) { - return d.getMonth(); - } ], [ "%Y", d3_true ] ]); - var d3_time_scaleMilliseconds = { - range: function(start, stop, step) { - return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); - }, - floor: d3_identity, - ceil: d3_identity - }; - d3_time_scaleLocalMethods.year = d3_time.year; - d3_time.scale = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); - }; - var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { - return [ m[0].utc, m[1] ]; - }); - var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { - return d.getUTCMilliseconds(); - } ], [ ":%S", function(d) { - return d.getUTCSeconds(); - } ], [ "%I:%M", function(d) { - return d.getUTCMinutes(); - } ], [ "%I %p", function(d) { - return d.getUTCHours(); - } ], [ "%a %d", function(d) { - return d.getUTCDay() && d.getUTCDate() != 1; - } ], [ "%b %d", function(d) { - return d.getUTCDate() != 1; - } ], [ "%B", function(d) { - return d.getUTCMonth(); - } ], [ "%Y", d3_true ] ]); - d3_time_scaleUtcMethods.year = d3_time.year.utc; - d3_time.scale.utc = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); - }; - d3.text = d3_xhrType(function(request) { - return request.responseText; - }); - d3.json = function(url, callback) { - return d3_xhr(url, "application/json", d3_json, callback); - }; - function d3_json(request) { - return JSON.parse(request.responseText); + var n = buffer.length || buffer.byteLength + var log_n = bits.log2(n) + DATA[log_n].push(buffer) +} + +function freeTypedArray(array) { + freeArrayBuffer(array.buffer) +} + +exports.freeUint8 = +exports.freeUint16 = +exports.freeUint32 = +exports.freeInt8 = +exports.freeInt16 = +exports.freeInt32 = +exports.freeFloat32 = +exports.freeFloat = +exports.freeFloat64 = +exports.freeDouble = +exports.freeUint8Clamped = +exports.freeDataView = freeTypedArray + +exports.freeArrayBuffer = freeArrayBuffer + +exports.freeBuffer = function freeBuffer(array) { + BUFFER[bits.log2(array.length)].push(array) +} + +exports.malloc = function malloc(n, dtype) { + if(dtype === undefined || dtype === 'arraybuffer') { + return mallocArrayBuffer(n) + } else { + switch(dtype) { + case 'uint8': + return mallocUint8(n) + case 'uint16': + return mallocUint16(n) + case 'uint32': + return mallocUint32(n) + case 'int8': + return mallocInt8(n) + case 'int16': + return mallocInt16(n) + case 'int32': + return mallocInt32(n) + case 'float': + case 'float32': + return mallocFloat(n) + case 'double': + case 'float64': + return mallocDouble(n) + case 'uint8_clamped': + return mallocUint8Clamped(n) + case 'buffer': + return mallocBuffer(n) + case 'data': + case 'dataview': + return mallocDataView(n) + + default: + return null + } } - d3.html = function(url, callback) { - return d3_xhr(url, "text/html", d3_html, callback); - }; - function d3_html(request) { - var range = d3_document.createRange(); - range.selectNode(d3_document.body); - return range.createContextualFragment(request.responseText); + return null +} + +function mallocArrayBuffer(n) { + var n = bits.nextPow2(n) + var log_n = bits.log2(n) + var d = DATA[log_n] + if(d.length > 0) { + return d.pop() + } + return new ArrayBuffer(n) +} +exports.mallocArrayBuffer = mallocArrayBuffer + +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocUint8 = mallocUint8 + +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocUint16 = mallocUint16 + +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocUint32 = mallocUint32 + +function mallocInt8(n) { + return new Int8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocInt8 = mallocInt8 + +function mallocInt16(n) { + return new Int16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocInt16 = mallocInt16 + +function mallocInt32(n) { + return new Int32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocInt32 = mallocInt32 + +function mallocFloat(n) { + return new Float32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocFloat32 = exports.mallocFloat = mallocFloat + +function mallocDouble(n) { + return new Float64Array(mallocArrayBuffer(8*n), 0, n) +} +exports.mallocFloat64 = exports.mallocDouble = mallocDouble + +function mallocUint8Clamped(n) { + if(hasUint8C) { + return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) + } else { + return mallocUint8(n) + } +} +exports.mallocUint8Clamped = mallocUint8Clamped + +function mallocDataView(n) { + return new DataView(mallocArrayBuffer(n), 0, n) +} +exports.mallocDataView = mallocDataView + +function mallocBuffer(n) { + n = bits.nextPow2(n) + var log_n = bits.log2(n) + var cache = BUFFER[log_n] + if(cache.length > 0) { + return cache.pop() } - d3.xml = d3_xhrType(function(request) { - return request.responseXML; - }); - if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; -}(); -},{}],114:[function(require,module,exports){ -"use strict" + return new Buffer(n) +} +exports.mallocBuffer = mallocBuffer -var ch = require("incremental-convex-hull") -var uniq = require("uniq") +exports.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"bit-twiddle":120,"buffer":65,"dup":121}],123:[function(require,module,exports){ +'use strict' -module.exports = triangulate +module.exports = createErrorBars -function LiftedPoint(p, i) { - this.point = p - this.index = i +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders/index') + +var IDENTITY = [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] + +function ErrorBars(gl, buffer, vao, shader) { + this.gl = gl + this.shader = shader + this.buffer = buffer + this.vao = vao + this.pixelRatio = 1 + this.bounds = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]] + this.clipBounds = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]] + this.lineWidth = [1,1,1] + this.capSize = [10,10,10] + this.lineCount = [0,0,0] + this.lineOffset = [0,0,0] + this.opacity = 1 } -function compareLifted(a, b) { - var ap = a.point - var bp = b.point - var d = ap.length - for(var i=0; i= 1 } -function triangulate1D(n, points, includePointAtInfinity) { - if(n === 1) { - if(includePointAtInfinity) { - return [ [-1, 0] ] - } else { - return [] - } - } - var lifted = points.map(function(p, i) { - return [ p[0], i ] - }) - lifted.sort(function(a,b) { - return a[0] - b[0] - }) - var cells = new Array(n - 1) - for(var i=1; i= 2) { - return false + if(position && error) { + + var verts = [] + var n = position.length + var vertexCount = 0 + this.bounds = [[ Infinity, Infinity, Infinity], + [-Infinity,-Infinity,-Infinity]] + this.lineCount = [0,0,0] + + //Build geometry for lines + for(var j=0; j<3; ++j) { + this.lineOffset[j] = vertexCount + +i_loop: + for(var i=0; i 0) { + var x = p.slice() + x[j] += e[1][j] + verts.push(p[0], p[1], p[2], + c[0], c[1], c[2], c[3], + 0, 0, 0, + x[0], x[1], x[2], + c[0], c[1], c[2], c[3], + 0, 0, 0) + updateBounds(this.bounds, x) + vertexCount += 2 + emitFace(verts, x, c, j) + } } - return true - }) + this.lineCount[j] = vertexCount - this.lineOffset[j] + } + this.buffer.update(verts) + } +} + +proto.dispose = function() { + this.shader.dispose() + this.buffer.dispose() + this.vao.dispose() +} + +function createErrorBars(options) { + var gl = options.gl + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 0, + stride: 40 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 4, + offset: 12, + stride: 40 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 28, + stride: 40 + } + ]) + + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.color.location = 1 + shader.attributes.offset.location = 2 + + var result = new ErrorBars(gl, buffer, vao, shader) + result.update(options) + return result +} + +},{"./shaders/index":158,"gl-buffer":124,"gl-vao":157}],124:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":127}],125:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],126:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],127:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":125,"buffer":65,"dup":122}],128:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":129,"./lib/create-attributes":130,"./lib/create-uniforms":131,"./lib/reflect":132,"./lib/runtime-reflect":133,"./lib/shader-cache":134,"dup":94}],129:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],130:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":129,"dup":96}],131:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":129,"./reflect":132,"dup":97}],132:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],133:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],134:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":129,"dup":100,"gl-format-compiler-error":135,"weakmap-shim":153}],135:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":136,"dup":101,"gl-constants/lookup":140,"glsl-shader-name":141,"sprintf-js":150}],136:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":137}],137:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":138}],138:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],139:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],140:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":139,"dup":106}],141:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":142,"dup":107,"glsl-tokenizer":149}],142:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],143:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":145,"./lib/builtins-300es":144,"./lib/literals":147,"./lib/literals-300es":146,"./lib/operators":148,"dup":109}],144:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":145,"dup":110}],145:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],146:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":147,"dup":112}],147:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],148:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],149:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":143,"dup":115}],150:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],151:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":152,"dup":117}],152:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],153:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":151,"dup":119}],154:[function(require,module,exports){ +"use strict" + +function doBind(gl, elements, attributes) { + if(elements) { + elements.bind() } else { - hull = hull.filter(function(cell) { - for(var i=0; i<=d; ++i) { - var v = dindex[cell[i]] - if(v < 0) { - return false + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) + } + var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0 + if(attributes) { + if(attributes.length > nattribs) { + throw new Error("gl-vao: Too many vertex attributes") + } + for(var i=0; i 0) { - return dupe_number(count|0, value) - } - break - case "object": - if(typeof (count.length) === "number") { - return dupe_array(count, value, 0) - } - break - } - return [] +function createVAONative(gl, ext) { + return new VAONative(gl, ext, ext.createVertexArrayOES()) } -module.exports = dupe -},{}],116:[function(require,module,exports){ -(function (process,global){ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 3.1.2 - */ +module.exports = createVAONative +},{"./do-bind.js":154}],157:[function(require,module,exports){ +"use strict" -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } +var createVAONative = require("./lib/vao-native.js") +var createVAOEmulated = require("./lib/vao-emulated.js") - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } +function createVAO(gl, attributes, elements, elementsType) { + var ext = gl.getExtension('OES_vertex_array_object') + var vao + if(ext) { + vao = createVAONative(gl, ext) + } else { + vao = createVAOEmulated(gl) + } + vao.update(attributes, elements, elementsType) + return vao +} - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } +module.exports = createVAO - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } +},{"./lib/vao-emulated.js":155,"./lib/vao-native.js":156}],158:[function(require,module,exports){ +'use strict' - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$vertxNext; - var lib$es6$promise$asap$$customSchedulerFn; - var lib$es6$promise$asap$$asap = function asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (lib$es6$promise$asap$$customSchedulerFn) { - lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); - } else { - lib$es6$promise$asap$$scheduleFlush(); - } - } - } +var createShader = require('gl-shader') - function lib$es6$promise$asap$$setScheduler(scheduleFn) { - lib$es6$promise$asap$$customSchedulerFn = scheduleFn; - } +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}" - function lib$es6$promise$asap$$setAsap(asapFn) { - lib$es6$promise$asap$$asap = asapFn; - } +module.exports = function(gl) { + return createShader(gl, vertSrc, fragSrc, null, [ + {name: 'position', type: 'vec3'}, + {name: 'offset', type: 'vec3'}, + {name: 'color', type: 'vec4'} + ]) +} - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; +},{"gl-shader":128}],159:[function(require,module,exports){ - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - // node - function lib$es6$promise$asap$$useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(lib$es6$promise$asap$$flush); - }; - } +exports.lineVertex = "precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n vec2 dir = (matrix * vec3(d, 0)).xy;\n vec3 base = matrix * vec3(a, 1);\n vec2 n = 0.5 * width *\n normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n vec2 tangent = normalize(screenShape.xy * dir);\n if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n direction = -tangent;\n } else {\n direction = tangent;\n }\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n" +exports.lineFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n" +exports.mitreVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 p;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n vec3 pp = matrix * vec3(p, 1);\n gl_Position = vec4(pp.xy, 0, pp.z);\n gl_PointSize = radius;\n}\n" +exports.mitreFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n discard;\n }\n gl_FragColor = vec4(color.rgb, color.a);\n}\n" +exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 n = width *\n normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n pickA = pick0;\n pickB = pick1;\n}\n" +exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n vec4 fragId = vec4(pickA.xyz, 0.0);\n if(pickB.w > pickA.w) {\n fragId.xyz = pickB.xyz;\n }\n\n fragId += pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n gl_FragColor = fragId / 255.0;\n}\n" +exports.fillVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 p = base.xy / base.z;\n if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n if(dot(p, projectAxis) < projectValue) {\n p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n }\n }\n gl_Position = vec4(p, depth, 1);\n}\n" +exports.fillFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } +},{}],160:[function(require,module,exports){ +'use strict' - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); +module.exports = createLinePlot - return function() { - node.data = (iterations = ++iterations % 2); - }; - } +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var createTexture = require('gl-texture2d') +var ndarray = require('ndarray') +var pool = require('typedarray-pool') - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } +var SHADERS = require('./lib/shaders') - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } +function GLLine2D( + plot, + dashPattern, + lineBuffer, + pickBuffer, + lineShader, + mitreShader, + fillShader, + pickShader) { - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; + this.plot = plot + this.dashPattern = dashPattern + this.lineBuffer = lineBuffer + this.pickBuffer = pickBuffer + this.lineShader = lineShader + this.mitreShader = mitreShader + this.fillShader = fillShader + this.pickShader = pickShader + this.usingDashes = false - callback(arg); + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } + this.width = 1 + this.color = [0,0,1,1] - lib$es6$promise$asap$$len = 0; - } + //Fill to axes + this.fill = [false, false, false, false] + this.fillColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - function lib$es6$promise$asap$$attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } + this.data = null + this.numPoints = 0 + this.vertCount = 0 - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - function lib$es6$promise$then$$then(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; + this.pickOffset = 0 - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } + this.lodBuffer = [] +} - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; +var proto = GLLine2D.prototype - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$asap(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } +proto.draw = (function() { +var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] +var SCREEN_SHAPE = [0,0] +var PX_AXIS = [1,0] +var NX_AXIS = [-1,0] +var PY_AXIS = [0,1] +var NY_AXIS = [0,-1] +return function() { + var plot = this.plot + var color = this.color + var width = this.width + var numPoints = this.numPoints + var bounds = this.bounds + var count = this.vertCount - return child; - } - var lib$es6$promise$then$$default = lib$es6$promise$then$$then; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; + if(!count) { + return + } - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } + var gl = plot.gl + var viewBox = plot.viewBox + var dataBox = plot.dataBox + var pixelRatio = plot.pixelRatio - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] - function lib$es6$promise$$internal$$noop() {} + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; + SCREEN_SHAPE[0] = screenX + SCREEN_SHAPE[1] = screenY - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + var buffer = this.lineBuffer + buffer.bind() - function lib$es6$promise$$internal$$selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } + var fill = this.fill - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } + if(fill[0] || fill[1] || fill[2] || fill[3]) { - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } + var fillShader = this.fillShader + fillShader.bind() - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } + var fillUniforms = fillShader.uniforms + fillUniforms.matrix = MATRIX + fillUniforms.depth = plot.nextDepthValue() - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$asap(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; + var fillAttributes = fillShader.attributes + fillAttributes.a.pointer(gl.FLOAT, false, 16, 0) + fillAttributes.d.pointer(gl.FLOAT, false, 16, 8) - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); + gl.depthMask(true) + gl.enable(gl.DEPTH_TEST) - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); + var fillColor = this.fillColor + if(fill[0]) { + fillUniforms.color = fillColor[0] + fillUniforms.projectAxis = NX_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } + if(fill[1]) { + fillUniforms.color = fillColor[1] + fillUniforms.projectAxis = NY_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { - if (maybeThenable.constructor === promise.constructor && - then === lib$es6$promise$then$$default && - constructor.resolve === lib$es6$promise$promise$resolve$$default) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } + if(fill[2]) { + fillUniforms.color = fillColor[2] + fillUniforms.projectAxis = PX_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } + if(fill[3]) { + fillUniforms.color = fillColor[3] + fillUniforms.projectAxis = PY_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } + gl.depthMask(false) + gl.disable(gl.DEPTH_TEST) + } - lib$es6$promise$$internal$$publish(promise); - } + var shader = this.lineShader + shader.bind() - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + var uniforms = shader.uniforms + uniforms.matrix = MATRIX + uniforms.color = color + uniforms.width = width * pixelRatio + uniforms.screenShape = SCREEN_SHAPE + uniforms.dashPattern = this.dashPattern.bind() + uniforms.dashLength = this.dashLength * pixelRatio - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; + var attributes = shader.attributes + attributes.a.pointer(gl.FLOAT, false, 16, 0) + attributes.d.pointer(gl.FLOAT, false, 16, 8) - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); - } - } + gl.drawArrays(gl.TRIANGLES, 0, count) - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; + //Draw mitres + if(width > 2 && !this.usingDashes) { + var mshader = this.mitreShader + mshader.bind() - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); - } + var muniforms = mshader.uniforms + muniforms.matrix = MATRIX + muniforms.color = color + muniforms.screenShape = SCREEN_SHAPE + muniforms.radius = width * pixelRatio - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; + mshader.attributes.p.pointer(gl.FLOAT, false, 48, 0) + gl.drawArrays(gl.POINTS, 0, (count/3)|0) + } +} +})() - parent._onerror = null; +proto.drawPick = (function() { + var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] + var SCREEN_SHAPE = [0,0] + var PICK_OFFSET = [0,0,0,0] + return function(pickOffset) { + var plot = this.plot + var shader = this.pickShader + var buffer = this.lineBuffer + var pickBuffer= this.pickBuffer + var width = this.width + var numPoints = this.numPoints + var bounds = this.bounds + var count = this.vertCount + + var gl = plot.gl + var viewBox = plot.viewBox + var dataBox = plot.dataBox + var pixelRatio = plot.pickPixelRatio + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + this.pickOffset = pickOffset - if (length === 0 && parent._state) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); - } + if(!count) { + return pickOffset + numPoints } - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - if (subscribers.length === 0) { return; } + SCREEN_SHAPE[0] = screenX + SCREEN_SHAPE[1] = screenY - var child, callback, detail = promise._result; + PICK_OFFSET[0] = pickOffset & 0xff + PICK_OFFSET[1] = (pickOffset>>>8) & 0xff + PICK_OFFSET[2] = (pickOffset>>>16) & 0xff + PICK_OFFSET[3] = pickOffset>>>24 - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; + shader.bind() - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } + var uniforms = shader.uniforms + uniforms.matrix = MATRIX + uniforms.width = width * pixelRatio + uniforms.pickOffset = PICK_OFFSET + uniforms.screenShape = SCREEN_SHAPE - promise._subscribers.length = 0; - } + var attributes = shader.attributes - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } + buffer.bind() + attributes.a.pointer(gl.FLOAT, false, 16, 0) + attributes.d.pointer(gl.FLOAT, false, 16, 8) - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + pickBuffer.bind() + attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0) + attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4) - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } + gl.drawArrays(gl.TRIANGLES, 0, count) - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; + return pickOffset + numPoints + } +})() - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.numPoints + if(value < pickOffset || value >= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var points = this.data + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] + } +} - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } +function deepCopy(arr) { + return arr.map(function(x) { + return x.slice() + }) +} - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } +proto.update = function(options) { + options = options || {} - } else { - value = detail; - succeeded = true; - } + var gl = this.plot.gl - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } + var connectGaps = !!options.connectGaps - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } + this.color = (options.color || [0,0,1,1]).slice() + this.width = +(options.width || 1) - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; + this.fill = (options.fill || [false,false,false,false]).slice() + this.fillColor = deepCopy(options.fillColor || [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]]) - var promise = new Constructor(lib$es6$promise$$internal$$noop); + var dashes = options.dashes || [1] + var dashLength = 0 + for(var i=0; i 1 - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } + this.dashPattern = createTexture(gl, + ndarray(dashData, [dashLength, 1, 4], [1, 0, 0])) + this.dashPattern.minFilter = gl.NEAREST + this.dashPattern.magFilter = gl.NEAREST + this.dashLength = dashLength + pool.free(dashData) - var length = entries.length; + var data = options.positions + this.data = data - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } + var bounds = this.bounds + bounds[0] = bounds[1] = Infinity + bounds[2] = bounds[3] = -Infinity - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } + var numPoints = this.numPoints = data.length>>>1 + if(numPoints === 0) { + return + } - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } + for(var i=0; i 1) { + var id = --ptr + var ax = data[2*ptr] + var ay = data[2*ptr+1] - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. + var next = id-1 + var bx = data[2*next] + var by = data[2*next+1] - A promise can be in one of three states: pending, fulfilled, or rejected. + if (isNaN(ax) || isNaN(ay) || isNaN(bx) || isNaN(by)) { + continue + } - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. + count += 1 - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. + ax = (ax - bounds[0]) / (bounds[2] - bounds[0]) + ay = (ay - bounds[1]) / (bounds[3] - bounds[1]) + bx = (bx - bounds[0]) / (bounds[2] - bounds[0]) + by = (by - bounds[1]) / (bounds[3] - bounds[1]) - Basic Usage: - ------------ + var dx = bx - ax + var dy = by - ay - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); + var akey0 = id | (1<<24) + var akey1 = (id-1) + var bkey0 = id + var bkey1 = (id-1) | (1<<24) - // on failure - reject(reason); - }); + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 - Advanced Usage: - --------------- + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 + } - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } + this.vertCount = 6 * count + this.lineBuffer.update(lineData.subarray(lineDataPtr)) + this.pickBuffer.update(pickData.subarray(pickDataPtr)) - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + pool.free(lineData) + pool.free(pickData) +} - Unlike callbacks, promises are great composable primitives. +proto.dispose = function() { + this.plot.removeObject(this) + this.lineBuffer.dispose() + this.pickBuffer.dispose() + this.lineShader.dispose() + this.mitreShader.dispose() + this.fillShader.dispose() + this.pickShader.dispose() + this.dashPattern.dispose() +} - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON +function createLinePlot(plot, options) { + var gl = plot.gl + var lineBuffer = createBuffer(gl) + var pickBuffer = createBuffer(gl) + var dashPattern = createTexture(gl, [1,1]) + var lineShader = createShader(gl, SHADERS.lineVertex, SHADERS.lineFragment) + var mitreShader = createShader(gl, SHADERS.mitreVertex, SHADERS.mitreFragment) + var fillShader = createShader(gl, SHADERS.fillVertex, SHADERS.fillFragment) + var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) + var linePlot = new GLLine2D( + plot, + dashPattern, + lineBuffer, + pickBuffer, + lineShader, + mitreShader, + fillShader, + pickShader) + plot.addObject(linePlot) + linePlot.update(options) + return linePlot +} - return values; - }); - ``` +},{"./lib/shaders":159,"gl-buffer":161,"gl-shader":162,"gl-texture2d":188,"ndarray":1031,"typedarray-pool":191}],161:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":191}],162:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":163,"./lib/create-attributes":164,"./lib/create-uniforms":165,"./lib/reflect":166,"./lib/runtime-reflect":167,"./lib/shader-cache":168,"dup":94}],163:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],164:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":163,"dup":96}],165:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":163,"./reflect":166,"dup":97}],166:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],167:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],168:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":163,"dup":100,"gl-format-compiler-error":169,"weakmap-shim":187}],169:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":170,"dup":101,"gl-constants/lookup":174,"glsl-shader-name":175,"sprintf-js":184}],170:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":171}],171:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":172}],172:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],173:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],174:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":173,"dup":106}],175:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":176,"dup":107,"glsl-tokenizer":183}],176:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],177:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":179,"./lib/builtins-300es":178,"./lib/literals":181,"./lib/literals-300es":180,"./lib/operators":182,"dup":109}],178:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":179,"dup":110}],179:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],180:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":181,"dup":112}],181:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],182:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],183:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":177,"dup":115}],184:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],185:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":186,"dup":117}],186:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],187:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":185,"dup":119}],188:[function(require,module,exports){ +'use strict' - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; +var ndarray = require('ndarray') +var ops = require('ndarray-ops') +var pool = require('typedarray-pool') - if (lib$es6$promise$$internal$$noop !== resolver) { - typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); - this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); - } - } +module.exports = createTexture2D - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; - lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; - lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; +var linearTypes = null +var filterTypes = null +var wrapTypes = null - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, +function lazyInitLinearTypes(gl) { + linearTypes = [ + gl.LINEAR, + gl.NEAREST_MIPMAP_LINEAR, + gl.LINEAR_MIPMAP_NEAREST, + gl.LINEAR_MIPMAP_NEAREST + ] + filterTypes = [ + gl.NEAREST, + gl.LINEAR, + gl.NEAREST_MIPMAP_NEAREST, + gl.NEAREST_MIPMAP_LINEAR, + gl.LINEAR_MIPMAP_NEAREST, + gl.LINEAR_MIPMAP_LINEAR + ] + wrapTypes = [ + gl.REPEAT, + gl.CLAMP_TO_EDGE, + gl.MIRRORED_REPEAT + ] +} - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. +var convertFloatToUint8 = function(out, inp) { + ops.muls(out, inp, 255.0) +} - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` +function reshapeTexture(tex, w, h) { + var gl = tex.gl + var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(w < 0 || w > maxSize || h < 0 || h > maxSize) { + throw new Error('gl-texture2d: Invalid texture size') + } + tex._shape = [w, h] + tex.bind() + gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) + tex._mipLevels = [0] + return tex +} - Chaining - -------- +function Texture2D(gl, handle, width, height, format, type) { + this.gl = gl + this.handle = handle + this.format = format + this.type = type + this._shape = [width, height] + this._mipLevels = [0] + this._magFilter = gl.NEAREST + this._minFilter = gl.NEAREST + this._wrapS = gl.CLAMP_TO_EDGE + this._wrapT = gl.CLAMP_TO_EDGE + this._anisoSamples = 1 + + var parent = this + var wrapVector = [this._wrapS, this._wrapT] + Object.defineProperties(wrapVector, [ + { + get: function() { + return parent._wrapS + }, + set: function(v) { + return parent.wrapS = v + } + }, + { + get: function() { + return parent._wrapT + }, + set: function(v) { + return parent.wrapT = v + } + } + ]) + this._wrapVector = wrapVector - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. + var shapeVector = [this._shape[0], this._shape[1]] + Object.defineProperties(shapeVector, [ + { + get: function() { + return parent._shape[0] + }, + set: function(v) { + return parent.width = v + } + }, + { + get: function() { + return parent._shape[1] + }, + set: function(v) { + return parent.height = v + } + } + ]) + this._shapeVector = shapeVector +} - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); +var proto = Texture2D.prototype - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. +Object.defineProperties(proto, { + minFilter: { + get: function() { + return this._minFilter + }, + set: function(v) { + this.bind() + var gl = this.gl + if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { + if(!gl.getExtension('OES_texture_float_linear')) { + v = gl.NEAREST + } + } + if(filterTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown filter mode ' + v) + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v) + return this._minFilter = v + } + }, + magFilter: { + get: function() { + return this._magFilter + }, + set: function(v) { + this.bind() + var gl = this.gl + if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { + if(!gl.getExtension('OES_texture_float_linear')) { + v = gl.NEAREST + } + } + if(filterTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown filter mode ' + v) + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) + return this._magFilter = v + } + }, + mipSamples: { + get: function() { + return this._anisoSamples + }, + set: function(i) { + var psamples = this._anisoSamples + this._anisoSamples = Math.max(i, 1)|0 + if(psamples !== this._anisoSamples) { + var ext = gl.getExtension('EXT_texture_filter_anisotropic') + if(ext) { + this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) + } + } + return this._anisoSamples + } + }, + wrapS: { + get: function() { + return this._wrapS + }, + set: function(v) { + this.bind() + if(wrapTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v) + return this._wrapS = v + } + }, + wrapT: { + get: function() { + return this._wrapT + }, + set: function(v) { + this.bind() + if(wrapTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v) + return this._wrapT = v + } + }, + wrap: { + get: function() { + return this._wrapVector + }, + set: function(v) { + if(!Array.isArray(v)) { + v = [v,v] + } + if(v.length !== 2) { + throw new Error('gl-texture2d: Must specify wrap mode for rows and columns') + } + for(var i=0; i<2; ++i) { + if(wrapTypes.indexOf(v[i]) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + } + this._wrapS = v[0] + this._wrapT = v[1] - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` + var gl = this.gl + this.bind() + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT) - Assimilation - ------------ + return v + } + }, + shape: { + get: function() { + return this._shapeVector + }, + set: function(x) { + if(!Array.isArray(x)) { + x = [x|0,x|0] + } else { + if(x.length !== 2) { + throw new Error('gl-texture2d: Invalid texture shape') + } + } + reshapeTexture(this, x[0]|0, x[1]|0) + return [x[0]|0, x[1]|0] + } + }, + width: { + get: function() { + return this._shape[0] + }, + set: function(w) { + w = w|0 + reshapeTexture(this, w, this._shape[1]) + return w + } + }, + height: { + get: function() { + return this._shape[1] + }, + set: function(h) { + h = h|0 + reshapeTexture(this, this._shape[0], h) + return h + } + } +}) - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. +proto.bind = function(unit) { + var gl = this.gl + if(unit !== undefined) { + gl.activeTexture(gl.TEXTURE0 + (unit|0)) + } + gl.bindTexture(gl.TEXTURE_2D, this.handle) + if(unit !== undefined) { + return (unit|0) + } + return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0 +} - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` +proto.dispose = function() { + this.gl.deleteTexture(this.handle) +} - If the assimliated promise rejects, then the downstream promise will also reject. +proto.generateMipmap = function() { + this.bind() + this.gl.generateMipmap(this.gl.TEXTURE_2D) - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` + //Update mip levels + var l = Math.min(this._shape[0], this._shape[1]) + for(var i=0; l>0; ++i, l>>>=1) { + if(this._mipLevels.indexOf(i) < 0) { + this._mipLevels.push(i) + } + } +} - Simple Example - -------------- +proto.setPixels = function(data, x_off, y_off, mip_level) { + var gl = this.gl + this.bind() + if(Array.isArray(x_off)) { + mip_level = y_off + y_off = x_off[1]|0 + x_off = x_off[0]|0 + } else { + x_off = x_off || 0 + y_off = y_off || 0 + } + mip_level = mip_level || 0 + if(data instanceof HTMLCanvasElement || + data instanceof ImageData || + data instanceof HTMLImageElement || + data instanceof HTMLVideoElement) { + var needsMip = this._mipLevels.indexOf(mip_level) < 0 + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data) + this._mipLevels.push(mip_level) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data) + } + } else if(data.shape && data.stride && data.data) { + if(data.shape.length < 2 || + x_off + data.shape[1] > this._shape[1]>>>mip_level || + y_off + data.shape[0] > this._shape[0]>>>mip_level || + x_off < 0 || + y_off < 0) { + throw new Error('gl-texture2d: Texture dimensions are out of bounds') + } + texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data) + } else { + throw new Error('gl-texture2d: Unsupported data type') + } +} - Synchronous Example - ```javascript - var result; +function isPacked(shape, stride) { + if(shape.length === 3) { + return (stride[2] === 1) && + (stride[1] === shape[0]*shape[2]) && + (stride[0] === shape[2]) + } + return (stride[0] === 1) && + (stride[1] === shape[0]) +} - try { - result = findResult(); - // success - } catch(reason) { - // failure +function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) { + var dtype = array.dtype + var shape = array.shape.slice() + if(shape.length < 2 || shape.length > 3) { + throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') + } + var type = 0, format = 0 + var packed = isPacked(shape, array.stride.slice()) + if(dtype === 'float32') { + type = gl.FLOAT + } else if(dtype === 'float64') { + type = gl.FLOAT + packed = false + dtype = 'float32' + } else if(dtype === 'uint8') { + type = gl.UNSIGNED_BYTE + } else { + type = gl.UNSIGNED_BYTE + packed = false + dtype = 'uint8' + } + var channels = 1 + if(shape.length === 2) { + format = gl.LUMINANCE + shape = [shape[0], shape[1], 1] + array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + } else if(shape.length === 3) { + if(shape[2] === 1) { + format = gl.ALPHA + } else if(shape[2] === 2) { + format = gl.LUMINANCE_ALPHA + } else if(shape[2] === 3) { + format = gl.RGB + } else if(shape[2] === 4) { + format = gl.RGBA + } else { + throw new Error('gl-texture2d: Invalid shape for pixel coords') + } + channels = shape[2] + } else { + throw new Error('gl-texture2d: Invalid shape for texture') + } + //For 1-channel textures allow conversion between formats + if((format === gl.LUMINANCE || format === gl.ALPHA) && + (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { + format = cformat + } + if(format !== cformat) { + throw new Error('gl-texture2d: Incompatible texture format for setPixels') + } + var size = array.size + var needsMip = mipLevels.indexOf(mip_level) < 0 + if(needsMip) { + mipLevels.push(mip_level) + } + if(type === ctype && packed) { + //Array data types are compatible, can directly copy into texture + if(array.offset === 0 && array.data.length === size) { + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) } - ``` + } else { + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + } + } + } else { + //Need to do type conversion to pack data into buffer + var pack_buffer + if(ctype === gl.FLOAT) { + pack_buffer = pool.mallocFloat32(size) + } else { + pack_buffer = pool.mallocUint8(size) + } + var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) + if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { + convertFloatToUint8(pack_view, array) + } else { + ops.assign(pack_view, array) + } + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) + } + if(ctype === gl.FLOAT) { + pool.freeFloat32(pack_buffer) + } else { + pool.freeUint8(pack_buffer) + } + } +} - Errback Example +function initTexture(gl) { + var tex = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, tex) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + return tex +} - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` +function createTextureShape(gl, width, height, format, type) { + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { + throw new Error('gl-texture2d: Invalid texture shape') + } + if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { + throw new Error('gl-texture2d: Floating point textures not supported on this platform') + } + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) + return new Texture2D(gl, tex, width, height, format, type) +} - Promise Example; +function createTextureDOM(gl, element, format, type) { + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element) + return new Texture2D(gl, tex, element.width|0, element.height|0, format, type) +} - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` +//Creates a texture from an ndarray +function createTextureArray(gl, array) { + var dtype = array.dtype + var shape = array.shape.slice() + var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { + throw new Error('gl-texture2d: Invalid texture size') + } + var packed = isPacked(shape, array.stride.slice()) + var type = 0 + if(dtype === 'float32') { + type = gl.FLOAT + } else if(dtype === 'float64') { + type = gl.FLOAT + packed = false + dtype = 'float32' + } else if(dtype === 'uint8') { + type = gl.UNSIGNED_BYTE + } else { + type = gl.UNSIGNED_BYTE + packed = false + dtype = 'uint8' + } + var format = 0 + if(shape.length === 2) { + format = gl.LUMINANCE + shape = [shape[0], shape[1], 1] + array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + } else if(shape.length === 3) { + if(shape[2] === 1) { + format = gl.ALPHA + } else if(shape[2] === 2) { + format = gl.LUMINANCE_ALPHA + } else if(shape[2] === 3) { + format = gl.RGB + } else if(shape[2] === 4) { + format = gl.RGBA + } else { + throw new Error('gl-texture2d: Invalid shape for pixel coords') + } + } else { + throw new Error('gl-texture2d: Invalid shape for texture') + } + if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { + type = gl.UNSIGNED_BYTE + packed = false + } + var buffer, buf_store + var size = array.size + if(!packed) { + var stride = [shape[2], shape[2]*shape[0], 1] + buf_store = pool.malloc(size, dtype) + var buf_array = ndarray(buf_store, shape, stride, 0) + if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { + convertFloatToUint8(buf_array, array) + } else { + ops.assign(buf_array, array) + } + buffer = buf_store.subarray(0, size) + } else if (array.offset === 0 && array.data.length === size) { + buffer = array.data + } else { + buffer = array.data.subarray(array.offset, array.offset + size) + } + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) + if(!packed) { + pool.free(buf_store) + } + return new Texture2D(gl, tex, shape[0], shape[1], format, type) +} - Advanced Example - -------------- +function createTexture2D(gl) { + if(arguments.length <= 1) { + throw new Error('gl-texture2d: Missing arguments for texture2d constructor') + } + if(!linearTypes) { + lazyInitLinearTypes(gl) + } + if(typeof arguments[1] === 'number') { + return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) + } + if(Array.isArray(arguments[1])) { + return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) + } + if(typeof arguments[1] === 'object') { + var obj = arguments[1] + if(obj instanceof HTMLCanvasElement || + obj instanceof HTMLImageElement || + obj instanceof HTMLVideoElement || + obj instanceof ImageData) { + return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) + } else if(obj.shape && obj.data && obj.stride) { + return createTextureArray(gl, obj) + } + } + throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') +} - Synchronous Example +},{"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":191}],189:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],190:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],191:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":189,"buffer":65,"dup":122}],192:[function(require,module,exports){ - ```javascript - var author, books; +var createShader = require('gl-shader') - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n" +var forwardFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n" +var pickFrag = "precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}" - Errback Example +var ATTRIBUTES = [ + {name: 'position', type: 'vec3'}, + {name: 'nextPosition', type: 'vec3'}, + {name: 'arcLength', type: 'float'}, + {name: 'lineWidth', type: 'float'}, + {name: 'color', type: 'vec4'} +] - ```js +exports.createShader = function(gl) { + return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES) +} - function foundBooks(books) { +exports.createPickShader = function(gl) { + return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES) +} - } +},{"gl-shader":199}],193:[function(require,module,exports){ +'use strict' - function failure(reason) { +module.exports = createLinePlot - } +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createTexture = require('gl-texture2d') +var unpackFloat = require('glsl-read-float') +var bsearch = require('binary-search-bounds') +var ndarray = require('ndarray') +var shaders = require('./lib/shaders') - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` +var createShader = shaders.createShader +var createPickShader = shaders.createPickShader - Promise Example; +var identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1] - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` +function distance (a, b) { + var s = 0.0 + for (var i = 0; i < 3; ++i) { + var d = a[i] - b[i] + s += d * d + } + return Math.sqrt(s) +} - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: lib$es6$promise$then$$default, +function filterClipBounds (bounds) { + var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]] + for (var i = 0; i < 3; ++i) { + result[0][i] = Math.max(bounds[0][i], result[0][i]) + result[1][i] = Math.min(bounds[1][i], result[1][i]) + } + return result +} - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. +function PickResult (tau, position, index, dataCoordinate) { + this.arcLength = tau + this.position = position + this.index = index + this.dataCoordinate = dataCoordinate +} - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } +function LinePlot (gl, shader, pickShader, buffer, vao, texture) { + this.gl = gl + this.shader = shader + this.pickShader = pickShader + this.buffer = buffer + this.vao = vao + this.clipBounds = [ + [ -Infinity, -Infinity, -Infinity ], + [ Infinity, Infinity, Infinity ]] + this.points = [] + this.arcLength = [] + this.vertexCount = 0 + this.bounds = [[0, 0, 0], [0, 0, 0]] + this.pickId = 0 + this.lineWidth = 1 + this.texture = texture + this.dashScale = 1 + this.opacity = 1 + this.dirty = true + this.pixelRatio = 1 +} - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } +var proto = LinePlot.prototype - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` +proto.isTransparent = function () { + return this.opacity < 1 +} - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(lib$es6$promise$$internal$$noop); +proto.isOpaque = function () { + return this.opacity >= 1 +} - if (Array.isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; +proto.pickSlots = 1 - this._result = new Array(this.length); +proto.setPickBase = function (id) { + this.pickId = id +} - if (this.length === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(); - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); - } - } - } else { - lib$es6$promise$$internal$$reject(this.promise, this._validationError()); - } - } +proto.drawTransparent = proto.draw = function (camera) { + var gl = this.gl + var shader = this.shader + var vao = this.vao + shader.bind() + shader.uniforms = { + model: camera.model || identity, + view: camera.view || identity, + projection: camera.projection || identity, + clipBounds: filterClipBounds(this.clipBounds), + dashTexture: this.texture.bind(), + dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], + opacity: this.opacity, + screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], + pixelRatio: this.pixelRatio + } + vao.bind() + vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) +} - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; +proto.drawPick = function (camera) { + var gl = this.gl + var shader = this.pickShader + var vao = this.vao + shader.bind() + shader.uniforms = { + model: camera.model || identity, + view: camera.view || identity, + projection: camera.projection || identity, + pickId: this.pickId, + clipBounds: filterClipBounds(this.clipBounds), + screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], + pixelRatio: this.pixelRatio + } + vao.bind() + vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) +} - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var length = this.length; - var input = this._input; +proto.update = function (options) { + var i, j - for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - this._eachEntry(input[i], i); - } - }; + this.dirty = true - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var c = this._instanceConstructor; - var resolve = c.resolve; + var connectGaps = !!options.connectGaps - if (resolve === lib$es6$promise$promise$resolve$$default) { - var then = lib$es6$promise$$internal$$getThen(entry); + if ('dashScale' in options) { + this.dashScale = options.dashScale + } + if ('opacity' in options) { + this.opacity = +options.opacity + } - if (then === lib$es6$promise$then$$default && - entry._state !== lib$es6$promise$$internal$$PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === lib$es6$promise$promise$$default) { - var promise = new c(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); - } - } else { - this._willSettleAt(resolve(entry), i); - } - }; + var positions = options.position || options.positions + if (!positions) { + return + } - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var promise = this.promise; + // Default color + var colors = options.color || options.colors || [0, 0, 0, 1] - if (promise._state === lib$es6$promise$$internal$$PENDING) { - this._remaining--; + var lineWidth = options.lineWidth || 1 - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - this._result[i] = value; - } - } + // Recalculate buffer data + var buffer = [] + var arcLengthArray = [] + var pointArray = [] + var arcLength = 0.0 + var vertexCount = 0 + var bounds = [ + [ Infinity, Infinity, Infinity ], + [ -Infinity, -Infinity, -Infinity ]] + var hadGap = false - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, this._result); - } - }; + fill_loop: + for (i = 1; i < positions.length; ++i) { + var a = positions[i - 1] + var b = positions[i] - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; + arcLengthArray.push(arcLength) + pointArray.push(a.slice()) - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; + for (j = 0; j < 3; ++j) { + if (isNaN(a[j]) || isNaN(b[j]) || + !isFinite(a[j]) || !isFinite(b[j])) { - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); + if (!connectGaps && buffer.length > 0) { + for (var k = 0; k < 24; ++k) { + buffer.push(buffer[buffer.length - 12]) } - } - - var P = local.Promise; + vertexCount += 2 + hadGap = true + } - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; + continue fill_loop } - - local.Promise = lib$es6$promise$promise$$default; + bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]) + bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]) } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + var acolor, bcolor + if (Array.isArray(colors[0])) { + acolor = colors[i - 1] + bcolor = colors[i] + } else { + acolor = bcolor = colors } - - lib$es6$promise$polyfill$$default(); -}).call(this); - - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":56}],117:[function(require,module,exports){ -/** - * inspired by is-number - * but significantly simplified and sped up by ignoring number and string constructors - * ie these return false: - * new Number(1) - * new String('1') - */ - -'use strict'; - -/** - * Is this string all whitespace? - * This solution kind of makes my brain hurt, but it's significantly faster - * than !str.trim() or any other solution I could find. - * - * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character - * and verified with: - * - * for(var i = 0; i < 65536; i++) { - * var s = String.fromCharCode(i); - * if(+s===0 && !s.trim()) console.log(i, s); - * } - * - * which counts a couple of these as *not* whitespace, but finds nothing else - * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears - * that there are no whitespace characters above this, and code points above - * this do not map onto white space characters. - */ -function allBlankCharCodes(str){ - var l = str.length, - a; - for(var i = 0; i < l; i++) { - a = str.charCodeAt(i); - if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) && - (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) && - (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) && - (a !== 8288) && (a !== 12288) && (a !== 65279)) { - return false; - } + if (acolor.length === 3) { + acolor = [acolor[0], acolor[1], acolor[2], 1] } - return true; -} - -module.exports = function(n) { - var type = typeof n; - if(type === 'string') { - var original = n; - n = +n; - // whitespace strings cast to zero - filter them out - if(n===0 && allBlankCharCodes(original)) return false; + if (bcolor.length === 3) { + bcolor = [bcolor[0], bcolor[1], bcolor[2], 1] } - else if(type !== 'number') return false; - return n - n < 1; -}; - -},{}],118:[function(require,module,exports){ -"use strict" - -var pool = require("typedarray-pool") -var ops = require("ndarray-ops") -var ndarray = require("ndarray") + var w0 + if (Array.isArray(lineWidth)) { + w0 = lineWidth[i - 1] + } else { + w0 = lineWidth + } -var SUPPORTED_TYPES = [ - "uint8", - "uint8_clamped", - "uint16", - "uint32", - "int8", - "int16", - "int32", - "float32" ] + var t0 = arcLength + arcLength += distance(a, b) -function GLBuffer(gl, type, handle, length, usage) { - this.gl = gl - this.type = type - this.handle = handle - this.length = length - this.usage = usage -} + if (hadGap) { + for (j = 0; j < 2; ++j) { + buffer.push( + a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3]) + } + vertexCount += 2 + hadGap = false + } -var proto = GLBuffer.prototype + buffer.push( + a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3], + a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3], + b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3], + b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3]) -proto.bind = function() { - this.gl.bindBuffer(this.type, this.handle) -} + vertexCount += 4 + } + this.buffer.update(buffer) -proto.unbind = function() { - this.gl.bindBuffer(this.type, null) -} + arcLengthArray.push(arcLength) + pointArray.push(positions[positions.length - 1].slice()) -proto.dispose = function() { - this.gl.deleteBuffer(this.handle) -} + this.bounds = bounds -function updateTypeArray(gl, type, len, usage, data, offset) { - var dataLen = data.length * data.BYTES_PER_ELEMENT - if(offset < 0) { - gl.bufferData(type, data, usage) - return dataLen - } - if(dataLen + offset > len) { - throw new Error("gl-buffer: If resizing buffer, must not specify offset") - } - gl.bufferSubData(type, offset, data) - return len -} + this.vertexCount = vertexCount -function makeScratchTypeArray(array, dtype) { - var res = pool.malloc(array.length, dtype) - var n = array.length - for(var i=0; i=0; --i) { - if(stride[i] !== n) { - return false - } - n *= shape[i] - } - return true -} + if ('dashes' in options) { + var dashArray = options.dashes -proto.update = function(array, offset) { - if(typeof offset !== "number") { - offset = -1 - } - this.bind() - if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray - var dtype = array.dtype - if(SUPPORTED_TYPES.indexOf(dtype) < 0) { - dtype = "float32" - } - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - var ext = gl.getExtension('OES_element_index_uint') - if(ext && dtype !== "uint16") { - dtype = "uint32" - } else { - dtype = "uint16" - } + // Calculate prefix sum + var prefixSum = dashArray.slice() + prefixSum.unshift(0) + for (i = 1; i < prefixSum.length; ++i) { + prefixSum[i] = prefixSum[i - 1] + prefixSum[i] } - if(dtype === array.dtype && isPacked(array.shape, array.stride)) { - if(array.offset === 0 && array.data.length === array.shape[0]) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) + + var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]) + for (i = 0; i < 256; ++i) { + for (j = 0; j < 4; ++j) { + dashTexture.set(i, 0, j, 0) } - } else { - var tmp = pool.malloc(array.size, dtype) - var ndt = ndarray(tmp, array.shape) - ops.assign(ndt, array) - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) + if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { + dashTexture.set(i, 0, 0, 0) } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) + dashTexture.set(i, 0, 0, 255) } - pool.free(tmp) - } - } else if(Array.isArray(array)) { //Vanilla array - var t - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - t = makeScratchTypeArray(array, "uint16") - } else { - t = makeScratchTypeArray(array, "float32") - } - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) - } - pool.free(t) - } else if(typeof array === "object" && typeof array.length === "number") { //Typed array - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) - } else if(typeof array === "number" || array === undefined) { //Number/default - if(offset >= 0) { - throw new Error("gl-buffer: Cannot specify offset when resizing buffer") - } - array = array | 0 - if(array <= 0) { - array = 1 } - this.gl.bufferData(this.type, array|0, this.usage) - this.length = array - } else { //Error, case should not happen - throw new Error("gl-buffer: Invalid data type") + + this.texture.setPixels(dashTexture) } } -function createBuffer(gl, data, type, usage) { - type = type || gl.ARRAY_BUFFER - usage = usage || gl.DYNAMIC_DRAW - if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { - throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") +proto.dispose = function () { + this.shader.dispose() + this.vao.dispose() + this.buffer.dispose() +} + +proto.pick = function (selection) { + if (!selection) { + return null } - if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { - throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") + if (selection.id !== this.pickId) { + return null } - var handle = gl.createBuffer() - var result = new GLBuffer(gl, type, handle, 0, usage) - result.update(data) - return result + var tau = unpackFloat( + selection.value[0], + selection.value[1], + selection.value[2], + 0) + var index = bsearch.le(this.arcLength, tau) + if (index < 0) { + return null + } + if (index === this.arcLength.length - 1) { + return new PickResult( + this.arcLength[this.arcLength.length - 1], + this.points[this.points.length - 1].slice(), + index) + } + var a = this.points[index] + var b = this.points[Math.min(index + 1, this.points.length - 1)] + var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]) + var ti = 1.0 - t + var x = [0, 0, 0] + for (var i = 0; i < 3; ++i) { + x[i] = ti * a[i] + t * b[i] + } + var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1) + return new PickResult( + tau, + x, + dataIndex, + this.points[dataIndex]) } -module.exports = createBuffer +function createLinePlot (options) { + var gl = options.gl || (options.scene && options.scene.gl) -},{"ndarray":253,"ndarray-ops":252,"typedarray-pool":278}],119:[function(require,module,exports){ -'use strict' + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.nextPosition.location = 1 + shader.attributes.arcLength.location = 2 + shader.attributes.lineWidth.location = 3 + shader.attributes.color.location = 4 -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var pool = require('typedarray-pool') -var shaders = require('./lib/shaders') + var pickShader = createPickShader(gl) + pickShader.attributes.position.location = 0 + pickShader.attributes.nextPosition.location = 1 + pickShader.attributes.arcLength.location = 2 + pickShader.attributes.lineWidth.location = 3 + pickShader.attributes.color.location = 4 -module.exports = createError2D + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + 'buffer': buffer, + 'size': 3, + 'offset': 0, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 3, + 'offset': 12, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 1, + 'offset': 24, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 1, + 'offset': 28, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 4, + 'offset': 32, + 'stride': 48 + } + ]) -var WEIGHTS = [ - // x-error bar - [1, 0, 0, 1, 0, 0], - [1, 0, 0, -1, 0, 0], - [-1, 0, 0, -1, 0, 0], + // Create texture for dash pattern + var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) + for (var i = 0; i < 256 * 4; ++i) { + defaultTexture.data[i] = 255 + } + var texture = createTexture(gl, defaultTexture) + texture.wrap = gl.REPEAT - [-1, 0, 0, -1, 0, 0], - [-1, 0, 0, 1, 0, 0], - [1, 0, 0, 1, 0, 0], + var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) + linePlot.update(options) + return linePlot +} - // x-error right cap - [1, 0, -1, 0, 0, 1], - [1, 0, -1, 0, 0, -1], - [1, 0, 1, 0, 0, -1], +},{"./lib/shaders":192,"binary-search-bounds":194,"gl-buffer":195,"gl-texture2d":228,"gl-vao":232,"glsl-read-float":233,"ndarray":1031}],194:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],195:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":198}],196:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],197:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],198:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":196,"buffer":65,"dup":122}],199:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":200,"./lib/create-attributes":201,"./lib/create-uniforms":202,"./lib/reflect":203,"./lib/runtime-reflect":204,"./lib/shader-cache":205,"dup":94}],200:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],201:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":200,"dup":96}],202:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":200,"./reflect":203,"dup":97}],203:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],204:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],205:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":200,"dup":100,"gl-format-compiler-error":206,"weakmap-shim":224}],206:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":207,"dup":101,"gl-constants/lookup":211,"glsl-shader-name":212,"sprintf-js":221}],207:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":208}],208:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":209}],209:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],210:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],211:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":210,"dup":106}],212:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":213,"dup":107,"glsl-tokenizer":220}],213:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],214:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":216,"./lib/builtins-300es":215,"./lib/literals":218,"./lib/literals-300es":217,"./lib/operators":219,"dup":109}],215:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":216,"dup":110}],216:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],217:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":218,"dup":112}],218:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],219:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],220:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":214,"dup":115}],221:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],222:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":223,"dup":117}],223:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],224:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":222,"dup":119}],225:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],226:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],227:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":225,"buffer":65,"dup":122}],228:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":227}],229:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],230:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":229,"dup":155}],231:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":229,"dup":156}],232:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":230,"./lib/vao-native.js":231,"dup":157}],233:[function(require,module,exports){ +module.exports = decodeFloat - [1, 0, 1, 0, 0, -1], - [1, 0, 1, 0, 0, 1], - [1, 0, -1, 0, 0, 1], +var UINT8_VIEW = new Uint8Array(4) +var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) - // x-error left cap - [-1, 0, -1, 0, 0, 1], - [-1, 0, -1, 0, 0, -1], - [-1, 0, 1, 0, 0, -1], +function decodeFloat(x, y, z, w) { + UINT8_VIEW[0] = w + UINT8_VIEW[1] = z + UINT8_VIEW[2] = y + UINT8_VIEW[3] = x + return FLOAT_VIEW[0] +} - [-1, 0, 1, 0, 0, -1], - [-1, 0, 1, 0, 0, 1], - [-1, 0, -1, 0, 0, 1], +},{}],234:[function(require,module,exports){ +module.exports = clone; - // y-error bar - [0, 1, 1, 0, 0, 0], - [0, 1, -1, 0, 0, 0], - [0, -1, -1, 0, 0, 0], +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {mat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ +function clone(a) { + var out = new Float32Array(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; +},{}],235:[function(require,module,exports){ +module.exports = create; - [0, -1, -1, 0, 0, 0], - [0, 1, 1, 0, 0, 0], - [0, -1, 1, 0, 0, 0], +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ +function create() { + var out = new Float32Array(16); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; +},{}],236:[function(require,module,exports){ +module.exports = determinant; - // y-error top cap - [0, 1, 0, -1, 1, 0], - [0, 1, 0, -1, -1, 0], - [0, 1, 0, 1, -1, 0], +/** + * Calculates the determinant of a mat4 + * + * @param {mat4} a the source matrix + * @returns {Number} determinant of a + */ +function determinant(a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - [0, 1, 0, 1, 1, 0], - [0, 1, 0, -1, 1, 0], - [0, 1, 0, 1, -1, 0], + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32; - // y-error bottom cap - [0, -1, 0, -1, 1, 0], - [0, -1, 0, -1, -1, 0], - [0, -1, 0, 1, -1, 0], + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +}; +},{}],237:[function(require,module,exports){ +module.exports = fromQuat; - [0, -1, 0, 1, 1, 0], - [0, -1, 0, -1, 1, 0], - [0, -1, 0, 1, -1, 0] -] +/** + * Creates a matrix from a quaternion rotation. + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @returns {mat4} out + */ +function fromQuat(out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, -function GLError2D (plot, shader, buffer) { - this.plot = plot + xx = x * x2, + yx = y * x2, + yy = y * y2, + zx = z * x2, + zy = z * y2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; - this.shader = shader - this.buffer = buffer + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; - this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; - this.numPoints = 0 + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; - this.color = [0, 0, 0, 1] -} + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; -var proto = GLError2D.prototype + return out; +}; +},{}],238:[function(require,module,exports){ +module.exports = fromRotationTranslation; -proto.draw = (function () { - var MATRIX = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {vec3} v Translation vector + * @returns {mat4} out + */ +function fromRotationTranslation(out, q, v) { + // Quaternion math + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + xy = x * y2, + xz = x * z2, + yy = y * y2, + yz = y * z2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + + return out; +}; +},{}],239:[function(require,module,exports){ +module.exports = identity; + +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ +function identity(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; +},{}],240:[function(require,module,exports){ +module.exports = invert; + +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - var PIXEL_SCALE = [1, 1] + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, - return function () { - var plot = this.plot - var shader = this.shader - var buffer = this.buffer - var bounds = this.bounds - var numPoints = this.numPoints + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - if (!numPoints) { - return + if (!det) { + return null; } + det = 1.0 / det; - var gl = plot.gl - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + return out; +}; +},{}],241:[function(require,module,exports){ +var identity = require('./identity'); - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] +module.exports = lookAt; - PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX - PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {vec3} eye Position of the viewer + * @param {vec3} center Point the viewer is looking at + * @param {vec3} up vec3 pointing up + * @returns {mat4} out + */ +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, + eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2], + centerx = center[0], + centery = center[1], + centerz = center[2]; - buffer.bind() - shader.bind() + if (Math.abs(eyex - centerx) < 0.000001 && + Math.abs(eyey - centery) < 0.000001 && + Math.abs(eyez - centerz) < 0.000001) { + return identity(out); + } - shader.uniforms.viewTransform = MATRIX - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.color = this.color + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; - shader.attributes.position.pointer( - gl.FLOAT, - false, - 16, - 0) + len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len; + z1 *= len; + z2 *= len; - shader.attributes.pixelOffset.pointer( - gl.FLOAT, - false, - 16, - 8) + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } - gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length) - } -})() + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; -proto.drawPick = function (offset) { return offset } -proto.pick = function (x, y) { - return null -} + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } -proto.update = function (options) { - options = options || {} + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; - var i, x, y + return out; +}; +},{"./identity":239}],242:[function(require,module,exports){ +module.exports = multiply; - var positions = options.positions || [] - var errors = options.errors || [] +/** + * Multiplies two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +function multiply(out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - var lineWidth = 1 - if ('lineWidth' in options) { - lineWidth = +options.lineWidth - } + // Cache only the current line of the second matrix + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - var capSize = 5 - if ('capSize' in options) { - capSize = +options.capSize - } + b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; + out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - this.color = (options.color || [0, 0, 0, 1]).slice() + b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; + out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; + out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + return out; +}; +},{}],243:[function(require,module,exports){ +module.exports = perspective; - var numPoints = this.numPoints = positions.length >> 1 - for (i = 0; i < numPoints; ++i) { - x = positions[i * 2] - y = positions[i * 2 + 1] +/** + * Generates a perspective projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +function perspective(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf = 1 / (near - far); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = (2 * far * near) * nf; + out[15] = 0; + return out; +}; +},{}],244:[function(require,module,exports){ +module.exports = rotate; - bounds[0] = Math.min(x, bounds[0]) - bounds[1] = Math.min(y, bounds[1]) - bounds[2] = Math.max(x, bounds[2]) - bounds[3] = Math.max(y, bounds[3]) - } - if (bounds[2] === bounds[0]) { - bounds[2] += 1 - } - if (bounds[3] === bounds[1]) { - bounds[3] += 1 - } - var sx = 1.0 / (bounds[2] - bounds[0]) - var sy = 1.0 / (bounds[3] - bounds[1]) - var tx = bounds[0] - var ty = bounds[1] +/** + * Rotates a mat4 by the given angle + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ +function rotate(out, a, rad, axis) { + var x = axis[0], y = axis[1], z = axis[2], + len = Math.sqrt(x * x + y * y + z * z), + s, c, t, + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + b00, b01, b02, + b10, b11, b12, + b20, b21, b22; - var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4) - var ptr = 0 - for (i = 0; i < numPoints; ++i) { - x = positions[2 * i] - y = positions[2 * i + 1] - var ex0 = errors[4 * i] - var ex1 = errors[4 * i + 1] - var ey0 = errors[4 * i + 2] - var ey1 = errors[4 * i + 3] + if (Math.abs(len) < 0.000001) { return null; } + + len = 1 / len; + x *= len; + y *= len; + z *= len; - for (var j = 0; j < WEIGHTS.length; ++j) { - var w = WEIGHTS[j] + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; - var dx = w[0] - var dy = w[1] + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; - if (dx < 0) { - dx *= ex0 - } else if (dx > 0) { - dx *= ex1 - } + // Construct the elements of the rotation matrix + b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; + b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; + b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; - if (dy < 0) { - dy *= ey0 - } else if (dy > 0) { - dy *= ey1 - } + // Perform rotation-specific matrix multiplication + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; - bufferData[ptr++] = sx * ((x - tx) + dx) - bufferData[ptr++] = sy * ((y - ty) + dy) - bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4] - bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5] + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; } - } - this.buffer.update(bufferData) - pool.free(bufferData) -} - -proto.dispose = function () { - this.plot.removeObject(this) - this.shader.dispose() - this.buffer.dispose() -} - -function createError2D (plot, options) { - var shader = createShader(plot.gl, shaders.vertex, shaders.fragment) - var buffer = createBuffer(plot.gl) + return out; +}; +},{}],245:[function(require,module,exports){ +module.exports = rotateX; - var errorbars = new GLError2D(plot, shader, buffer) +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +function rotateX(out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; - errorbars.update(options) + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } - plot.addObject(errorbars) + // Perform axis-specific matrix multiplication + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +}; +},{}],246:[function(require,module,exports){ +module.exports = rotateY; - return errorbars -} +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +function rotateY(out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; -},{"./lib/shaders":120,"gl-buffer":118,"gl-shader":197,"typedarray-pool":278}],120:[function(require,module,exports){ + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + // Perform axis-specific matrix multiplication + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +}; +},{}],247:[function(require,module,exports){ +module.exports = rotateZ; -module.exports = { - vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n", - fragment: "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" -} +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +function rotateZ(out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; -},{}],121:[function(require,module,exports){ -'use strict' + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } -module.exports = createErrorBars + // Perform axis-specific matrix multiplication + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +}; +},{}],248:[function(require,module,exports){ +module.exports = scale; -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders/index') +/** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {vec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ +function scale(out, a, v) { + var x = v[0], y = v[1], z = v[2]; -var IDENTITY = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; +},{}],249:[function(require,module,exports){ +module.exports = translate; -function ErrorBars(gl, buffer, vao, shader) { - this.gl = gl - this.shader = shader - this.buffer = buffer - this.vao = vao - this.pixelRatio = 1 - this.bounds = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]] - this.clipBounds = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]] - this.lineWidth = [1,1,1] - this.capSize = [10,10,10] - this.lineCount = [0,0,0] - this.lineOffset = [0,0,0] - this.opacity = 1 -} +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to translate + * @param {vec3} v vector to translate by + * @returns {mat4} out + */ +function translate(out, a, v) { + var x = v[0], y = v[1], z = v[2], + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23; -var proto = ErrorBars.prototype + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; -proto.isOpaque = function() { - return this.opacity >= 1 -} + out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; + out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; + out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; -proto.isTransparent = function() { - return this.opacity < 1 -} + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } -proto.drawTransparent = proto.draw = function(cameraParams) { - var gl = this.gl - var uniforms = this.shader.uniforms + return out; +}; +},{}],250:[function(require,module,exports){ +module.exports = transpose; - this.shader.bind() - var view = uniforms.view = cameraParams.view || IDENTITY - var projection = uniforms.projection = cameraParams.projection || IDENTITY - uniforms.model = cameraParams.model || IDENTITY - uniforms.clipBounds = this.clipBounds - uniforms.opacity = this.opacity +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +function transpose(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], a02 = a[2], a03 = a[3], + a12 = a[6], a13 = a[7], + a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +}; +},{}],251:[function(require,module,exports){ +'use strict' - var cx = view[12] - var cy = view[13] - var cz = view[14] - var cw = view[15] - var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight +var barycentric = require('barycentric') +var closestPointToTriangle = require('polytope-closest-point/lib/closest_point_2d.js') +module.exports = closestPointToPickLocation - this.vao.bind() - for(var i=0; i<3; ++i) { - gl.lineWidth(this.lineWidth[i]) - uniforms.capSize = this.capSize[i] * pixelScaleF - gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i]) +function xformMatrix(m, v) { + var out = [0,0,0,0] + for(var i=0; i<4; ++i) { + for(var j=0; j<4; ++j) { + out[j] += m[4*i + j] * v[i] + } } - this.vao.unbind() + return out } -function updateBounds(bounds, point) { +function projectVertex(v, model, view, projection, resolution) { + var p = xformMatrix(projection, + xformMatrix(view, + xformMatrix(model, [v[0], v[1], v[2], 1]))) for(var i=0; i<3; ++i) { - bounds[0][i] = Math.min(bounds[0][i], point[i]) - bounds[1][i] = Math.max(bounds[1][i], point[i]) + p[i] /= p[3] } + return [ 0.5 * resolution[0] * (1.0+p[0]), 0.5 * resolution[1] * (1.0-p[1]) ] } -var FACE_TABLE = (function(){ - var table = new Array(3) - for(var d=0; d<3; ++d) { - var row = [] - for(var j=1; j<=2; ++j) { - for(var s=-1; s<=1; s+=2) { - var u = (j+d) % 3 - var y = [0,0,0] - y[u] = s - row.push(y) - } +function barycentricCoord(simplex, point) { + if(simplex.length === 2) { + var d0 = 0.0 + var d1 = 0.0 + for(var i=0; i<2; ++i) { + d0 += Math.pow(point[i] - simplex[0][i], 2) + d1 += Math.pow(point[i] - simplex[1][i], 2) } - table[d] = row - } - return table -})() - - -function emitFace(verts, x, c, d) { - var offsets = FACE_TABLE[d] - for(var i=0; i 0) { - var x = p.slice() - x[j] += e[1][j] - verts.push(p[0], p[1], p[2], - c[0], c[1], c[2], c[3], - 0, 0, 0, - x[0], x[1], x[2], - c[0], c[1], c[2], c[3], - 0, 0, 0) - updateBounds(this.bounds, x) - vertexCount += 2 + emitFace(verts, x, c, j) - } - } - this.lineCount[j] = vertexCount - this.lineOffset[j] + var weights = barycentricCoord(simplex2D, pixelCoord) + var s = 0.0 + for(var i=0; i<3; ++i) { + if(weights[i] < -0.001 || + weights[i] > 1.0001) { + return null } - this.buffer.update(verts) + s += weights[i] } + if(Math.abs(s - 1.0) > 0.001) { + return null + } + return [closestIndex, interpolate(simplex, weights), weights] } +},{"barycentric":254,"polytope-closest-point/lib/closest_point_2d.js":298}],252:[function(require,module,exports){ -proto.dispose = function() { - this.shader.dispose() - this.buffer.dispose() - this.vao.dispose() -} - -function createErrorBars(options) { - var gl = options.gl - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 0, - stride: 40 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 4, - offset: 12, - stride: 40 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 28, - stride: 40 - } - ]) - - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.color.location = 1 - shader.attributes.offset.location = 2 - - var result = new ErrorBars(gl, buffer, vao, shader) - result.update(options) - return result -} - -},{"./shaders/index":122,"gl-buffer":118,"gl-vao":226}],122:[function(require,module,exports){ -'use strict' - - -var createShader = require('gl-shader') -var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}" -var fragSrc = "precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}" +var triVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}" +var triFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}" +var edgeVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}" +var edgeFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" +var pointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}" +var pointFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" +var pickVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}" +var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}" +var pickPointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}" +var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}" +var contourFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n" -module.exports = function(gl) { - return createShader(gl, vertSrc, fragSrc, null, [ +exports.meshShader = { + vertex: triVertSrc, + fragment: triFragSrc, + attributes: [ {name: 'position', type: 'vec3'}, - {name: 'offset', type: 'vec3'}, - {name: 'color', type: 'vec4'} - ]) -} - -},{"gl-shader":197}],123:[function(require,module,exports){ -'use strict' - -var createTexture = require('gl-texture2d') - -module.exports = createFBO - -var colorAttachmentArrays = null -var FRAMEBUFFER_UNSUPPORTED -var FRAMEBUFFER_INCOMPLETE_ATTACHMENT -var FRAMEBUFFER_INCOMPLETE_DIMENSIONS -var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT - -function saveFBOState(gl) { - var fbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) - var rbo = gl.getParameter(gl.RENDERBUFFER_BINDING) - var tex = gl.getParameter(gl.TEXTURE_BINDING_2D) - return [fbo, rbo, tex] + {name: 'normal', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'} + ] } - -function restoreFBOState(gl, data) { - gl.bindFramebuffer(gl.FRAMEBUFFER, data[0]) - gl.bindRenderbuffer(gl.RENDERBUFFER, data[1]) - gl.bindTexture(gl.TEXTURE_2D, data[2]) +exports.wireShader = { + vertex: edgeVertSrc, + fragment: edgeFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'} + ] } - -function lazyInitColorAttachments(gl, ext) { - var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL) - colorAttachmentArrays = new Array(maxColorAttachments + 1) - for(var i=0; i<=maxColorAttachments; ++i) { - var x = new Array(maxColorAttachments) - for(var j=0; j 1) { - ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]) - } +var identityMatrix = [ + 1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] - //Allocate depth/stencil buffers - var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture') - if(WEBGL_depth_texture) { - if(useStencil) { - fbo.depth = initTexture(gl, width, height, - WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, - gl.DEPTH_STENCIL, - gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo.depth = initTexture(gl, width, height, - gl.UNSIGNED_SHORT, - gl.DEPTH_COMPONENT, - gl.DEPTH_ATTACHMENT) - } - } else { - if(useDepth && useStencil) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT) - } else if(useStencil) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT) - } - } +function SimplicialMesh(gl + , texture + , triShader + , lineShader + , pointShader + , pickShader + , pointPickShader + , contourShader + , trianglePositions + , triangleIds + , triangleColors + , triangleUVs + , triangleNormals + , triangleVAO + , edgePositions + , edgeIds + , edgeColors + , edgeUVs + , edgeVAO + , pointPositions + , pointIds + , pointColors + , pointUVs + , pointSizes + , pointVAO + , contourPositions + , contourVAO) { - //Check frame buffer state - var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) - if(status !== gl.FRAMEBUFFER_COMPLETE) { + this.gl = gl + this.cells = [] + this.positions = [] + this.intensity = [] + this.texture = texture + this.dirty = true - //Release all partially allocated resources - fbo._destroyed = true + this.triShader = triShader + this.lineShader = lineShader + this.pointShader = pointShader + this.pickShader = pickShader + this.pointPickShader = pointPickShader + this.contourShader = contourShader - //Release all resources - gl.bindFramebuffer(gl.FRAMEBUFFER, null) - gl.deleteFramebuffer(fbo.handle) - fbo.handle = null - if(fbo.depth) { - fbo.depth.dispose() - fbo.depth = null - } - if(fbo._depth_rb) { - gl.deleteRenderbuffer(fbo._depth_rb) - fbo._depth_rb = null - } - for(var i=0; i= 1 } -var proto = Framebuffer.prototype +proto.isTransparent = function() { + return this.opacity < 1 +} -function reshapeFBO(fbo, w, h) { - //If fbo is invalid, just skip this - if(fbo._destroyed) { - throw new Error('gl-fbo: Can\'t resize destroyed FBO') - } +proto.pickSlots = 1 - //Don't resize if no change in shape - if( (fbo._shape[0] === w) && - (fbo._shape[1] === h) ) { - return - } +proto.setPickBase = function(id) { + this.pickId = id +} - var gl = fbo.gl +function genColormap(param) { + var colors = colormap({ + colormap: param + , nshades: 256 + , format: 'rgba' + }) - //Check parameter ranges - var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) - if( w < 0 || w > maxFBOSize || - h < 0 || h > maxFBOSize) { - throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions') + var result = new Uint8Array(256*4) + for(var i=0; i<256; ++i) { + var c = colors[i] + for(var j=0; j<3; ++j) { + result[4*i+j] = c[j] + } + result[4*i+3] = c[3]*255 } - //Update shape - fbo._shape[0] = w - fbo._shape[1] = h - - //Save framebuffer state - var state = saveFBOState(gl) + return ndarray(result, [256,256,4], [4,0,1]) +} - //Resize framebuffer attachments - for(var i=0; i maxFBOSize || height < 0 || height > maxFBOSize) { - throw new Error('gl-fbo: Parameters are too large for FBO') + if('opacity' in params) { + this.opacity = params.opacity } - - //Handle each option type - options = options || {} - - //Figure out number of color buffers to use - var numColors = 1 - if('color' in options) { - numColors = Math.max(options.color|0, 0) - if(numColors < 0) { - throw new Error('gl-fbo: Must specify a nonnegative number of colors') - } - if(numColors > 1) { - //Check if multiple render targets supported - if(!WEBGL_draw_buffers) { - throw new Error('gl-fbo: Multiple draw buffer extension not supported') - } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) { - throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers') - } - } + if('ambient' in params) { + this.ambientLight = params.ambient + } + if('diffuse' in params) { + this.diffuseLight = params.diffuse + } + if('specular' in params) { + this.specularLight = params.specular } - - //Determine whether to use floating point textures - var colorType = gl.UNSIGNED_BYTE - var OES_texture_float = gl.getExtension('OES_texture_float') - if(options.float && numColors > 0) { - if(!OES_texture_float) { - throw new Error('gl-fbo: Context does not support floating point textures') - } - colorType = gl.FLOAT - } else if(options.preferFloat && numColors > 0) { - if(OES_texture_float) { - colorType = gl.FLOAT - } + if('roughness' in params) { + this.roughness = params.roughness } - - //Check if we should use depth buffer - var useDepth = true - if('depth' in options) { - useDepth = !!options.depth + if('fresnel' in params) { + this.fresnel = params.fresnel } - //Check if we should use a stencil buffer - var useStencil = false - if('stencil' in options) { - useStencil = !!options.stencil + if(params.texture) { + this.texture.dispose() + this.texture = createTexture(gl, params.texture) + } else if (params.colormap) { + this.texture.shape = [256,256] + this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR + this.texture.magFilter = gl.LINEAR + this.texture.setPixels(genColormap(params.colormap)) + this.texture.generateMipmap() } - return new Framebuffer( - gl, - width, - height, - colorType, - numColors, - useDepth, - useStencil, - WEBGL_draw_buffers) -} + var cells = params.cells + var positions = params.positions -},{"gl-texture2d":222}],124:[function(require,module,exports){ + if(!positions || !cells) { + return + } + var tPos = [] + var tCol = [] + var tNor = [] + var tUVs = [] + var tIds = [] -exports.lineVertex = "precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n vec2 dir = (matrix * vec3(d, 0)).xy;\n vec3 base = matrix * vec3(a, 1);\n vec2 n = 0.5 * width *\n normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n vec2 tangent = normalize(screenShape.xy * dir);\n if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n direction = -tangent;\n } else {\n direction = tangent;\n }\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n" -exports.lineFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n" -exports.mitreVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 p;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n vec3 pp = matrix * vec3(p, 1);\n gl_Position = vec4(pp.xy, 0, pp.z);\n gl_PointSize = radius;\n}\n" -exports.mitreFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n discard;\n }\n gl_FragColor = vec4(color.rgb, color.a);\n}\n" -exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 n = width *\n normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n pickA = pick0;\n pickB = pick1;\n}\n" -exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n vec4 fragId = vec4(pickA.xyz, 0.0);\n if(pickB.w > pickA.w) {\n fragId.xyz = pickB.xyz;\n }\n\n fragId += pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n gl_FragColor = fragId / 255.0;\n}\n" -exports.fillVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 p = base.xy / base.z;\n if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n if(dot(p, projectAxis) < projectValue) {\n p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n }\n }\n gl_Position = vec4(p, depth, 1);\n}\n" -exports.fillFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" + var ePos = [] + var eCol = [] + var eUVs = [] + var eIds = [] -},{}],125:[function(require,module,exports){ -'use strict' + var pPos = [] + var pCol = [] + var pUVs = [] + var pSiz = [] + var pIds = [] -module.exports = createLinePlot + //Save geometry data for picking calculations + this.cells = cells + this.positions = positions -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var createTexture = require('gl-texture2d') -var ndarray = require('ndarray') -var pool = require('typedarray-pool') + //Compute normals + var vertexNormals = params.vertexNormals + var cellNormals = params.cellNormals + var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon + var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon + if(params.useFacetNormals && !cellNormals) { + cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon) + } + if(!cellNormals && !vertexNormals) { + vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon) + } -var SHADERS = require('./lib/shaders') + //Compute colors + var vertexColors = params.vertexColors + var cellColors = params.cellColors + var meshColor = params.meshColor || [1,1,1,1] -function GLLine2D( - plot, - dashPattern, - lineBuffer, - pickBuffer, - lineShader, - mitreShader, - fillShader, - pickShader) { + //UVs + var vertexUVs = params.vertexUVs + var vertexIntensity = params.vertexIntensity + var cellUVs = params.cellUVs + var cellIntensity = params.cellIntensity - this.plot = plot - this.dashPattern = dashPattern - this.lineBuffer = lineBuffer - this.pickBuffer = pickBuffer - this.lineShader = lineShader - this.mitreShader = mitreShader - this.fillShader = fillShader - this.pickShader = pickShader - this.usingDashes = false + var intensityLo = Infinity + var intensityHi = -Infinity + if(!vertexUVs && !cellUVs) { + if(vertexIntensity) { + for(var i=0; i 2 && !this.usingDashes) { - var mshader = this.mitreShader - mshader.bind() + this.pointPositions.update(pPos) + this.pointColors.update(pCol) + this.pointUVs.update(pUVs) + this.pointSizes.update(pSiz) + this.pointIds.update(new Uint32Array(pIds)) - var muniforms = mshader.uniforms - muniforms.matrix = MATRIX - muniforms.color = color - muniforms.screenShape = SCREEN_SHAPE - muniforms.radius = width * pixelRatio + this.edgePositions.update(ePos) + this.edgeColors.update(eCol) + this.edgeUVs.update(eUVs) + this.edgeIds.update(new Uint32Array(eIds)) - mshader.attributes.p.pointer(gl.FLOAT, false, 48, 0) - gl.drawArrays(gl.POINTS, 0, (count/3)|0) - } + this.trianglePositions.update(tPos) + this.triangleColors.update(tCol) + this.triangleUVs.update(tUVs) + this.triangleNormals.update(tNor) + this.triangleIds.update(new Uint32Array(tIds)) } -})() - -proto.drawPick = (function() { - var MATRIX = [1, 0, 0, - 0, 1, 0, - 0, 0, 1] - var SCREEN_SHAPE = [0,0] - var PICK_OFFSET = [0,0,0,0] - return function(pickOffset) { - var plot = this.plot - var shader = this.pickShader - var buffer = this.lineBuffer - var pickBuffer= this.pickBuffer - var width = this.width - var numPoints = this.numPoints - var bounds = this.bounds - var count = this.vertCount - - var gl = plot.gl - var viewBox = plot.viewBox - var dataBox = plot.dataBox - var pixelRatio = plot.pickPixelRatio - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] - this.pickOffset = pickOffset +proto.drawTransparent = proto.draw = function(params) { + params = params || {} + var gl = this.gl + var model = params.model || identityMatrix + var view = params.view || identityMatrix + var projection = params.projection || identityMatrix - if(!count) { - return pickOffset + numPoints - } + var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]] + for(var i=0; i<3; ++i) { + clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]) + clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]) + } - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + var uniforms = { + model: model, + view: view, + projection: projection, - SCREEN_SHAPE[0] = screenX - SCREEN_SHAPE[1] = screenY + clipBounds: clipBounds, - PICK_OFFSET[0] = pickOffset & 0xff - PICK_OFFSET[1] = (pickOffset>>>8) & 0xff - PICK_OFFSET[2] = (pickOffset>>>16) & 0xff - PICK_OFFSET[3] = pickOffset>>>24 + kambient: this.ambientLight, + kdiffuse: this.diffuseLight, + kspecular: this.specularLight, + roughness: this.roughness, + fresnel: this.fresnel, - shader.bind() + eyePosition: [0,0,0], + lightPosition: [0,0,0], - var uniforms = shader.uniforms - uniforms.matrix = MATRIX - uniforms.width = width * pixelRatio - uniforms.pickOffset = PICK_OFFSET - uniforms.screenShape = SCREEN_SHAPE + opacity: this.opacity, - var attributes = shader.attributes + contourColor: this.contourColor, - buffer.bind() - attributes.a.pointer(gl.FLOAT, false, 16, 0) - attributes.d.pointer(gl.FLOAT, false, 16, 8) + texture: 0 + } - pickBuffer.bind() - attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0) - attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4) + this.texture.bind(0) - gl.drawArrays(gl.TRIANGLES, 0, count) + var invCameraMatrix = new Array(16) + multiply(invCameraMatrix, uniforms.view, uniforms.model) + multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) + invert(invCameraMatrix, invCameraMatrix) - return pickOffset + numPoints + for(var i=0; i<3; ++i) { + uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15] } -})() -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.numPoints - if(value < pickOffset || value >= pickOffset + pointCount) { - return null + var w = invCameraMatrix[15] + for(var i=0; i<3; ++i) { + w += this.lightPosition[i] * invCameraMatrix[4*i+3] } - var pointId = value - pickOffset - var points = this.data - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + for(var i=0; i<3; ++i) { + var s = invCameraMatrix[12+i] + for(var j=0; j<3; ++j) { + s += invCameraMatrix[4*j+i] * this.lightPosition[j] + } + uniforms.lightPosition[i] = s / w } -} - -function deepCopy(arr) { - return arr.map(function(x) { - return x.slice() - }) -} -proto.update = function(options) { - options = options || {} + if(this.triangleCount > 0) { + var shader = this.triShader + shader.bind() + shader.uniforms = uniforms - var gl = this.plot.gl + this.triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) + this.triangleVAO.unbind() + } - var connectGaps = !!options.connectGaps + if(this.edgeCount > 0 && this.lineWidth > 0) { + var shader = this.lineShader + shader.bind() + shader.uniforms = uniforms - this.color = (options.color || [0,0,1,1]).slice() - this.width = +(options.width || 1) + this.edgeVAO.bind() + gl.lineWidth(this.lineWidth) + gl.drawArrays(gl.LINES, 0, this.edgeCount*2) + this.edgeVAO.unbind() + } - this.fill = (options.fill || [false,false,false,false]).slice() - this.fillColor = deepCopy(options.fillColor || [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]]) + if(this.pointCount > 0) { + var shader = this.pointShader + shader.bind() + shader.uniforms = uniforms - var dashes = options.dashes || [1] - var dashLength = 0 - for(var i=0; i 0 && this.contourLineWidth > 0) { + var shader = this.contourShader + shader.bind() + shader.uniforms = uniforms + + this.contourVAO.bind() + gl.drawArrays(gl.LINES, 0, this.contourCount) + this.contourVAO.unbind() } - this.dashPattern.dispose() - this.usingDashes = dashes.length > 1 +} - this.dashPattern = createTexture(gl, - ndarray(dashData, [dashLength, 1, 4], [1, 0, 0])) - this.dashPattern.minFilter = gl.NEAREST - this.dashPattern.magFilter = gl.NEAREST - this.dashLength = dashLength - pool.free(dashData) +proto.drawPick = function(params) { + params = params || {} - var data = options.positions - this.data = data + var gl = this.gl - var bounds = this.bounds - bounds[0] = bounds[1] = Infinity - bounds[2] = bounds[3] = -Infinity + var model = params.model || identityMatrix + var view = params.view || identityMatrix + var projection = params.projection || identityMatrix - var numPoints = this.numPoints = data.length>>>1 - if(numPoints === 0) { - return + var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]] + for(var i=0; i<3; ++i) { + clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]) + clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]) } - for(var i=0; i 0) { + this.triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) + this.triangleVAO.unbind() } - //Generate line data - var lineData = pool.mallocFloat32(24*(numPoints-1)) - var pickData = pool.mallocUint32(12*(numPoints-1)) - var lineDataPtr = lineData.length - var pickDataPtr = pickData.length - var ptr = numPoints + if(this.edgeCount > 0) { + this.edgeVAO.bind() + gl.lineWidth(this.lineWidth) + gl.drawArrays(gl.LINES, 0, this.edgeCount*2) + this.edgeVAO.unbind() + } - var count = 0 + if(this.pointCount > 0) { + var shader = this.pointPickShader + shader.bind() + shader.uniforms = uniforms - while(ptr > 1) { - var id = --ptr - var ax = data[2*ptr] - var ay = data[2*ptr+1] + this.pointVAO.bind() + gl.drawArrays(gl.POINTS, 0, this.pointCount) + this.pointVAO.unbind() + } +} - var next = id-1 - var bx = data[2*next] - var by = data[2*next+1] - if (isNaN(ax) || isNaN(ay) || isNaN(bx) || isNaN(by)) { - continue - } +proto.pick = function(pickData) { + if(!pickData) { + return null + } + if(pickData.id !== this.pickId) { + return null + } - count += 1 + var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2] + var cell = this.cells[cellId] + var positions = this.positions - ax = (ax - bounds[0]) / (bounds[2] - bounds[0]) - ay = (ay - bounds[1]) / (bounds[3] - bounds[1]) + var simplex = new Array(cell.length) + for(var i=0; i= 1 -} +module.exports = createSimplicialMesh -proto.pickSlots = 1 +},{"./lib/closest-point":251,"./lib/shaders":252,"colormap":263,"gl-buffer":265,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-shader":266,"gl-texture2d":292,"gl-vao":296,"ndarray":1031,"normals":297,"simplicial-complex-contour":299,"typedarray-pool":306}],254:[function(require,module,exports){ +'use strict' -proto.setPickBase = function (id) { - this.pickId = id -} +module.exports = barycentric -proto.drawTransparent = proto.draw = function (camera) { - var gl = this.gl - var shader = this.shader - var vao = this.vao - shader.bind() - shader.uniforms = { - model: camera.model || identity, - view: camera.view || identity, - projection: camera.projection || identity, - clipBounds: filterClipBounds(this.clipBounds), - dashTexture: this.texture.bind(), - dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], - opacity: this.opacity, - screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], - pixelRatio: this.pixelRatio - } - vao.bind() - vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) -} +var solve = require('robust-linear-solve') -proto.drawPick = function (camera) { - var gl = this.gl - var shader = this.pickShader - var vao = this.vao - shader.bind() - shader.uniforms = { - model: camera.model || identity, - view: camera.view || identity, - projection: camera.projection || identity, - pickId: this.pickId, - clipBounds: filterClipBounds(this.clipBounds), - screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], - pixelRatio: this.pixelRatio +function reduce(x) { + var r = 0 + for(var i=0; i 0) { - for (var k = 0; k < 24; ++k) { - buffer.push(buffer[buffer.length - 12]) - } - vertexCount += 2 - hadGap = true - } + "hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}], - continue fill_loop - } - bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]) - bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]) - } + "hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}], - var acolor, bcolor - if (Array.isArray(colors[0])) { - acolor = colors[i - 1] - bcolor = colors[i] - } else { - acolor = bcolor = colors - } - if (acolor.length === 3) { - acolor = [acolor[0], acolor[1], acolor[2], 1] - } - if (bcolor.length === 3) { - bcolor = [bcolor[0], bcolor[1], bcolor[2], 1] - } + "cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}], - var w0 - if (Array.isArray(lineWidth)) { - w0 = lineWidth[i - 1] - } else { - w0 = lineWidth - } + "spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}], - var t0 = arcLength - arcLength += distance(a, b) + "summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}], - if (hadGap) { - for (j = 0; j < 2; ++j) { - buffer.push( - a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3]) - } - vertexCount += 2 - hadGap = false - } + "autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}], - buffer.push( - a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3], - a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3], - b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3], - b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3]) + "winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}], - vertexCount += 4 - } - this.buffer.update(buffer) + "bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}], - arcLengthArray.push(arcLength) - pointArray.push(positions[positions.length - 1].slice()) + "copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}], - this.bounds = bounds + "greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}], - this.vertexCount = vertexCount + "yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}], - this.points = pointArray - this.arcLength = arcLengthArray + "greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}], - if ('dashes' in options) { - var dashArray = options.dashes + "yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}], - // Calculate prefix sum - var prefixSum = dashArray.slice() - prefixSum.unshift(0) - for (i = 1; i < prefixSum.length; ++i) { - prefixSum[i] = prefixSum[i - 1] + prefixSum[i] - } + "bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}], - var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]) - for (i = 0; i < 256; ++i) { - for (j = 0; j < 4; ++j) { - dashTexture.set(i, 0, j, 0) - } - if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { - dashTexture.set(i, 0, 0, 0) - } else { - dashTexture.set(i, 0, 0, 255) - } - } + "rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}], - this.texture.setPixels(dashTexture) - } -} + "picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}], -proto.dispose = function () { - this.shader.dispose() - this.vao.dispose() - this.buffer.dispose() -} + "rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}], -proto.pick = function (selection) { - if (!selection) { - return null - } - if (selection.id !== this.pickId) { - return null - } - var tau = unpackFloat( - selection.value[0], - selection.value[1], - selection.value[2], - 0) - var index = bsearch.le(this.arcLength, tau) - if (index < 0) { - return null - } - if (index === this.arcLength.length - 1) { - return new PickResult( - this.arcLength[this.arcLength.length - 1], - this.points[this.points.length - 1].slice(), - index) - } - var a = this.points[index] - var b = this.points[Math.min(index + 1, this.points.length - 1)] - var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]) - var ti = 1.0 - t - var x = [0, 0, 0] - for (var i = 0; i < 3; ++i) { - x[i] = ti * a[i] + t * b[i] - } - var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1) - return new PickResult( - tau, - x, - dataIndex, - this.points[dataIndex]) -} + "portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}], -function createLinePlot (options) { - var gl = options.gl || (options.scene && options.scene.gl) + "blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}], - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.nextPosition.location = 1 - shader.attributes.arcLength.location = 2 - shader.attributes.lineWidth.location = 3 - shader.attributes.color.location = 4 + "earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}], - var pickShader = createPickShader(gl) - pickShader.attributes.position.location = 0 - pickShader.attributes.nextPosition.location = 1 - pickShader.attributes.arcLength.location = 2 - pickShader.attributes.lineWidth.location = 3 - pickShader.attributes.color.location = 4 + "electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - 'buffer': buffer, - 'size': 3, - 'offset': 0, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 3, - 'offset': 12, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 1, - 'offset': 24, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 1, - 'offset': 28, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 4, - 'offset': 32, - 'stride': 48 - } - ]) + "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}], - // Create texture for dash pattern - var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) - for (var i = 0; i < 256 * 4; ++i) { - defaultTexture.data[i] = 255 - } - var texture = createTexture(gl, defaultTexture) - texture.wrap = gl.REPEAT + "viridis": [{"index":0,"rgb":[68,1,84]},{"index":0.13,"rgb":[71,44,122]},{"index":0.25,"rgb":[59,81,139]},{"index":0.38,"rgb":[44,113,142]},{"index":0.5,"rgb":[33,144,141]},{"index":0.63,"rgb":[39,173,129]},{"index":0.75,"rgb":[92,200,99]},{"index":0.88,"rgb":[170,220,50]},{"index":1,"rgb":[253,231,37]}], - var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) - linePlot.update(options) - return linePlot -} + "inferno": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[31,12,72]},{"index":0.25,"rgb":[85,15,109]},{"index":0.38,"rgb":[136,34,106]},{"index":0.5,"rgb":[186,54,85]},{"index":0.63,"rgb":[227,89,51]},{"index":0.75,"rgb":[249,140,10]},{"index":0.88,"rgb":[249,201,50]},{"index":1,"rgb":[252,255,164]}], -},{"./lib/shaders":126,"binary-search-bounds":128,"gl-buffer":118,"gl-texture2d":222,"gl-vao":226,"glsl-read-float":129,"ndarray":253}],128:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],129:[function(require,module,exports){ -module.exports = decodeFloat + "magma": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[28,16,68]},{"index":0.25,"rgb":[79,18,123]},{"index":0.38,"rgb":[129,37,129]},{"index":0.5,"rgb":[181,54,122]},{"index":0.63,"rgb":[229,80,100]},{"index":0.75,"rgb":[251,135,97]},{"index":0.88,"rgb":[254,194,135]},{"index":1,"rgb":[252,253,191]}], -var UINT8_VIEW = new Uint8Array(4) -var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) + "plasma": [{"index":0,"rgb":[13,8,135]},{"index":0.13,"rgb":[75,3,161]},{"index":0.25,"rgb":[125,3,168]},{"index":0.38,"rgb":[168,34,150]},{"index":0.5,"rgb":[203,70,121]},{"index":0.63,"rgb":[229,107,93]},{"index":0.75,"rgb":[248,148,65]},{"index":0.88,"rgb":[253,195,40]},{"index":1,"rgb":[240,249,33]}], -function decodeFloat(x, y, z, w) { - UINT8_VIEW[0] = w - UINT8_VIEW[1] = z - UINT8_VIEW[2] = y - UINT8_VIEW[3] = x - return FLOAT_VIEW[0] -} + "warm": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[172,0,187]},{"index":0.25,"rgb":[219,0,170]},{"index":0.38,"rgb":[255,0,130]},{"index":0.5,"rgb":[255,63,74]},{"index":0.63,"rgb":[255,123,0]},{"index":0.75,"rgb":[234,176,0]},{"index":0.88,"rgb":[190,228,0]},{"index":1,"rgb":[147,255,0]}], -},{}],130:[function(require,module,exports){ -module.exports = invert + "cool": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[116,0,218]},{"index":0.25,"rgb":[98,74,237]},{"index":0.38,"rgb":[68,146,231]},{"index":0.5,"rgb":[0,204,197]},{"index":0.63,"rgb":[0,247,146]},{"index":0.75,"rgb":[0,255,88]},{"index":0.88,"rgb":[40,255,8]},{"index":1,"rgb":[147,255,0]}], -/** - * Inverts a mat3 - * - * @alias mat3.invert - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2] - var a10 = a[3], a11 = a[4], a12 = a[5] - var a20 = a[6], a21 = a[7], a22 = a[8] + "rainbow-soft": [{"index":0,"rgb":[125,0,179]},{"index":0.1,"rgb":[199,0,180]},{"index":0.2,"rgb":[255,0,121]},{"index":0.3,"rgb":[255,108,0]},{"index":0.4,"rgb":[222,194,0]},{"index":0.5,"rgb":[150,255,0]},{"index":0.6,"rgb":[0,255,55]},{"index":0.7,"rgb":[0,246,150]},{"index":0.8,"rgb":[50,167,222]},{"index":0.9,"rgb":[103,51,235]},{"index":1,"rgb":[124,0,186]}], - var b01 = a22 * a11 - a12 * a21 - var b11 = -a22 * a10 + a12 * a20 - var b21 = a21 * a10 - a11 * a20 + "bathymetry": [{"index":0,"rgb":[40,26,44]},{"index":0.13,"rgb":[59,49,90]},{"index":0.25,"rgb":[64,76,139]},{"index":0.38,"rgb":[63,110,151]},{"index":0.5,"rgb":[72,142,158]},{"index":0.63,"rgb":[85,174,163]},{"index":0.75,"rgb":[120,206,163]},{"index":0.88,"rgb":[187,230,172]},{"index":1,"rgb":[253,254,204]}], - // Calculate the determinant - var det = a00 * b01 + a01 * b11 + a02 * b21 + "cdom": [{"index":0,"rgb":[47,15,62]},{"index":0.13,"rgb":[87,23,86]},{"index":0.25,"rgb":[130,28,99]},{"index":0.38,"rgb":[171,41,96]},{"index":0.5,"rgb":[206,67,86]},{"index":0.63,"rgb":[230,106,84]},{"index":0.75,"rgb":[242,149,103]},{"index":0.88,"rgb":[249,193,135]},{"index":1,"rgb":[254,237,176]}], - if (!det) return null - det = 1.0 / det + "chlorophyll": [{"index":0,"rgb":[18,36,20]},{"index":0.13,"rgb":[25,63,41]},{"index":0.25,"rgb":[24,91,59]},{"index":0.38,"rgb":[13,119,72]},{"index":0.5,"rgb":[18,148,80]},{"index":0.63,"rgb":[80,173,89]},{"index":0.75,"rgb":[132,196,122]},{"index":0.88,"rgb":[175,221,162]},{"index":1,"rgb":[215,249,208]}], - out[0] = b01 * det - out[1] = (-a22 * a01 + a02 * a21) * det - out[2] = (a12 * a01 - a02 * a11) * det - out[3] = b11 * det - out[4] = (a22 * a00 - a02 * a20) * det - out[5] = (-a12 * a00 + a02 * a10) * det - out[6] = b21 * det - out[7] = (-a21 * a00 + a01 * a20) * det - out[8] = (a11 * a00 - a01 * a10) * det + "density": [{"index":0,"rgb":[54,14,36]},{"index":0.13,"rgb":[89,23,80]},{"index":0.25,"rgb":[110,45,132]},{"index":0.38,"rgb":[120,77,178]},{"index":0.5,"rgb":[120,113,213]},{"index":0.63,"rgb":[115,151,228]},{"index":0.75,"rgb":[134,185,227]},{"index":0.88,"rgb":[177,214,227]},{"index":1,"rgb":[230,241,241]}], - return out -} + "freesurface-blue": [{"index":0,"rgb":[30,4,110]},{"index":0.13,"rgb":[47,14,176]},{"index":0.25,"rgb":[41,45,236]},{"index":0.38,"rgb":[25,99,212]},{"index":0.5,"rgb":[68,131,200]},{"index":0.63,"rgb":[114,156,197]},{"index":0.75,"rgb":[157,181,203]},{"index":0.88,"rgb":[200,208,216]},{"index":1,"rgb":[241,237,236]}], -},{}],131:[function(require,module,exports){ -module.exports = clone; + "freesurface-red": [{"index":0,"rgb":[60,9,18]},{"index":0.13,"rgb":[100,17,27]},{"index":0.25,"rgb":[142,20,29]},{"index":0.38,"rgb":[177,43,27]},{"index":0.5,"rgb":[192,87,63]},{"index":0.63,"rgb":[205,125,105]},{"index":0.75,"rgb":[216,162,148]},{"index":0.88,"rgb":[227,199,193]},{"index":1,"rgb":[241,237,236]}], -/** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param {mat4} a matrix to clone - * @returns {mat4} a new 4x4 matrix - */ -function clone(a) { - var out = new Float32Array(16); - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -}; -},{}],132:[function(require,module,exports){ -module.exports = create; + "oxygen": [{"index":0,"rgb":[64,5,5]},{"index":0.13,"rgb":[106,6,15]},{"index":0.25,"rgb":[144,26,7]},{"index":0.38,"rgb":[168,64,3]},{"index":0.5,"rgb":[188,100,4]},{"index":0.63,"rgb":[206,136,11]},{"index":0.75,"rgb":[220,174,25]},{"index":0.88,"rgb":[231,215,44]},{"index":1,"rgb":[248,254,105]}], -/** - * Creates a new identity mat4 - * - * @returns {mat4} a new 4x4 matrix - */ -function create() { - var out = new Float32Array(16); - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -}; -},{}],133:[function(require,module,exports){ -module.exports = determinant; + "par": [{"index":0,"rgb":[51,20,24]},{"index":0.13,"rgb":[90,32,35]},{"index":0.25,"rgb":[129,44,34]},{"index":0.38,"rgb":[159,68,25]},{"index":0.5,"rgb":[182,99,19]},{"index":0.63,"rgb":[199,134,22]},{"index":0.75,"rgb":[212,171,35]},{"index":0.88,"rgb":[221,210,54]},{"index":1,"rgb":[225,253,75]}], -/** - * Calculates the determinant of a mat4 - * - * @param {mat4} a the source matrix - * @returns {Number} determinant of a - */ -function determinant(a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + "phase": [{"index":0,"rgb":[145,105,18]},{"index":0.13,"rgb":[184,71,38]},{"index":0.25,"rgb":[186,58,115]},{"index":0.38,"rgb":[160,71,185]},{"index":0.5,"rgb":[110,97,218]},{"index":0.63,"rgb":[50,123,164]},{"index":0.75,"rgb":[31,131,110]},{"index":0.88,"rgb":[77,129,34]},{"index":1,"rgb":[145,105,18]}], - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32; + "salinity": [{"index":0,"rgb":[42,24,108]},{"index":0.13,"rgb":[33,50,162]},{"index":0.25,"rgb":[15,90,145]},{"index":0.38,"rgb":[40,118,137]},{"index":0.5,"rgb":[59,146,135]},{"index":0.63,"rgb":[79,175,126]},{"index":0.75,"rgb":[120,203,104]},{"index":0.88,"rgb":[193,221,100]},{"index":1,"rgb":[253,239,154]}], - // Calculate the determinant - return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + "temperature": [{"index":0,"rgb":[4,35,51]},{"index":0.13,"rgb":[23,51,122]},{"index":0.25,"rgb":[85,59,157]},{"index":0.38,"rgb":[129,79,143]},{"index":0.5,"rgb":[175,95,130]},{"index":0.63,"rgb":[222,112,101]},{"index":0.75,"rgb":[249,146,66]},{"index":0.88,"rgb":[249,196,65]},{"index":1,"rgb":[232,250,91]}], + + "turbidity": [{"index":0,"rgb":[34,31,27]},{"index":0.13,"rgb":[65,50,41]},{"index":0.25,"rgb":[98,69,52]},{"index":0.38,"rgb":[131,89,57]},{"index":0.5,"rgb":[161,112,59]},{"index":0.63,"rgb":[185,140,66]},{"index":0.75,"rgb":[202,174,88]},{"index":0.88,"rgb":[216,209,126]},{"index":1,"rgb":[233,246,171]}], + + "velocity-blue": [{"index":0,"rgb":[17,32,64]},{"index":0.13,"rgb":[35,52,116]},{"index":0.25,"rgb":[29,81,156]},{"index":0.38,"rgb":[31,113,162]},{"index":0.5,"rgb":[50,144,169]},{"index":0.63,"rgb":[87,173,176]},{"index":0.75,"rgb":[149,196,189]},{"index":0.88,"rgb":[203,221,211]},{"index":1,"rgb":[254,251,230]}], + + "velocity-green": [{"index":0,"rgb":[23,35,19]},{"index":0.13,"rgb":[24,64,38]},{"index":0.25,"rgb":[11,95,45]},{"index":0.38,"rgb":[39,123,35]},{"index":0.5,"rgb":[95,146,12]},{"index":0.63,"rgb":[152,165,18]},{"index":0.75,"rgb":[201,186,69]},{"index":0.88,"rgb":[233,216,137]},{"index":1,"rgb":[255,253,205]}], + + "cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}] }; -},{}],134:[function(require,module,exports){ -module.exports = fromQuat; -/** - * Creates a matrix from a quaternion rotation. - * - * @param {mat4} out mat4 receiving operation result - * @param {quat4} q Rotation quaternion - * @returns {mat4} out +},{}],263:[function(require,module,exports){ +/* + * Ben Postlethwaite + * January 2013 + * License MIT */ -function fromQuat(out, q) { - var x = q[0], y = q[1], z = q[2], w = q[3], - x2 = x + x, - y2 = y + y, - z2 = z + z, +'use strict'; - xx = x * x2, - yx = y * x2, - yy = y * y2, - zx = z * x2, - zy = z * y2, - zz = z * z2, - wx = w * x2, - wy = w * y2, - wz = w * z2; +var at = require('arraytools'); +var clone = require('clone'); +var colorScale = require('./colorScales'); - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; +module.exports = createColormap; - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; +function createColormap (spec) { + /* + * Default Options + */ + var indicies, rgba, fromrgba, torgba, + nsteps, cmap, colormap, format, + nshades, colors, alpha, index, i, + r = [], + g = [], + b = [], + a = []; - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + if ( !at.isPlainObject(spec) ) spec = {}; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + nshades = spec.nshades || 72; + format = spec.format || 'hex'; - return out; -}; -},{}],135:[function(require,module,exports){ -module.exports = fromRotationTranslation; + colormap = spec.colormap; + if (!colormap) colormap = 'jet'; -/** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat4} q Rotation quaternion - * @param {vec3} v Translation vector - * @returns {mat4} out - */ -function fromRotationTranslation(out, q, v) { - // Quaternion math - var x = q[0], y = q[1], z = q[2], w = q[3], - x2 = x + x, - y2 = y + y, - z2 = z + z, + if (typeof colormap === 'string') { + colormap = colormap.toLowerCase(); - xx = x * x2, - xy = x * y2, - xz = x * z2, - yy = y * y2, - yz = y * z2, - zz = z * z2, - wx = w * x2, - wy = w * y2, - wz = w * z2; + if (!colorScale[colormap]) { + throw Error(colormap + ' not a supported colorscale'); + } - out[0] = 1 - (yy + zz); - out[1] = xy + wz; - out[2] = xz - wy; - out[3] = 0; - out[4] = xy - wz; - out[5] = 1 - (xx + zz); - out[6] = yz + wx; - out[7] = 0; - out[8] = xz + wy; - out[9] = yz - wx; - out[10] = 1 - (xx + yy); - out[11] = 0; - out[12] = v[0]; - out[13] = v[1]; - out[14] = v[2]; - out[15] = 1; - - return out; -}; -},{}],136:[function(require,module,exports){ -module.exports = identity; + cmap = clone(colorScale[colormap]); -/** - * Set a mat4 to the identity matrix - * - * @param {mat4} out the receiving matrix - * @returns {mat4} out - */ -function identity(out) { - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -}; -},{}],137:[function(require,module,exports){ -module.exports = invert; + } else if (Array.isArray(colormap)) { + cmap = clone(colormap); -/** - * Inverts a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + } else { + throw Error('unsupported colormap option', colormap); + } - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32, + if (cmap.length > nshades) { + throw new Error( + colormap+' map requires nshades to be at least size '+cmap.length + ); + } - // Calculate the determinant - det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + if (!Array.isArray(spec.alpha)) { - if (!det) { - return null; + if (typeof spec.alpha === 'number') { + alpha = [spec.alpha, spec.alpha]; + + } else { + alpha = [1, 1]; + } + + } else if (spec.alpha.length !== 2) { + alpha = [1, 1]; + + } else { + alpha = clone(spec.alpha); } - det = 1.0 / det; - out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + /* + * map index points from 0->1 to 0 -> n-1 + */ + indicies = cmap.map(function(c) { + return Math.round(c.index * nshades); + }); - return out; + /* + * Add alpha channel to the map + */ + if (alpha[0] < 0) alpha[0] = 0; + if (alpha[1] < 0) alpha[0] = 0; + if (alpha[0] > 1) alpha[0] = 1; + if (alpha[1] > 1) alpha[0] = 1; + + for (i = 0; i < indicies.length; ++i) { + index = cmap[i].index; + rgba = cmap[i].rgb; + + // if user supplies their own map use it + if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue; + rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index; + } + + /* + * map increasing linear values between indicies to + * linear steps in colorvalues + */ + for (i = 0; i < indicies.length-1; ++i) { + nsteps = indicies[i+1] - indicies[i]; + fromrgba = cmap[i].rgb; + torgba = cmap[i+1].rgb; + r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) ); + g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) ); + b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) ); + a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) ); + } + + r = r.map( Math.round ); + g = g.map( Math.round ); + b = b.map( Math.round ); + + colors = at.zip(r, g, b, a); + + if (format === 'hex') colors = colors.map( rgb2hex ); + if (format === 'rgbaString') colors = colors.map( rgbaStr ); + + return colors; }; -},{}],138:[function(require,module,exports){ -var identity = require('./identity'); -module.exports = lookAt; + +function rgb2hex (rgba) { + var dig, hex = '#'; + for (var i = 0; i < 3; ++i) { + dig = rgba[i]; + dig = dig.toString(16); + hex += ('00' + dig).substr( dig.length ); + } + return hex; +} + +function rgbaStr (rgba) { + return 'rgba(' + rgba.join(',') + ')'; +} + +},{"./colorScales":262,"arraytools":64,"clone":264}],264:[function(require,module,exports){ +(function (Buffer){ +var clone = (function() { +'use strict'; /** - * Generates a look-at matrix with the given eye position, focal point, and up axis + * Clones (copies) an Object using deep copying. * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {vec3} eye Position of the viewer - * @param {vec3} center Point the viewer is looking at - * @param {vec3} up vec3 pointing up - * @returns {mat4} out - */ -function lookAt(out, eye, center, up) { - var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, - eyex = eye[0], - eyey = eye[1], - eyez = eye[2], - upx = up[0], - upy = up[1], - upz = up[2], - centerx = center[0], - centery = center[1], - centerz = center[2]; + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). +*/ +function clone(parent, circular, depth, prototype) { + var filter; + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + filter = circular.filter; + circular = circular.circular + } + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; - if (Math.abs(eyex - centerx) < 0.000001 && - Math.abs(eyey - centery) < 0.000001 && - Math.abs(eyez - centerz) < 0.000001) { - return identity(out); - } + var useBuffer = typeof Buffer != 'undefined'; - z0 = eyex - centerx; - z1 = eyey - centery; - z2 = eyez - centerz; + if (typeof circular == 'undefined') + circular = true; - len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); - z0 *= len; - z1 *= len; - z2 *= len; + if (typeof depth == 'undefined') + depth = Infinity; - x0 = upy * z2 - upz * z1; - x1 = upz * z0 - upx * z2; - x2 = upx * z1 - upy * z0; - len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); - if (!len) { - x0 = 0; - x1 = 0; - x2 = 0; + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth == 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; + } + + if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + child = new Buffer(parent.length); + parent.copy(child); + return child; } else { - len = 1 / len; - x0 *= len; - x1 *= len; - x2 *= len; + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } } - y0 = z1 * x2 - z2 * x1; - y1 = z2 * x0 - z0 * x2; - y2 = z0 * x1 - z1 * x0; + if (circular) { + var index = allParents.indexOf(parent); - len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); - if (!len) { - y0 = 0; - y1 = 0; - y2 = 0; - } else { - len = 1 / len; - y0 *= len; - y1 *= len; - y2 *= len; + if (index != -1) { + return allChildren[index]; + } + allParents.push(parent); + allChildren.push(child); } - out[0] = x0; - out[1] = y0; - out[2] = z0; - out[3] = 0; - out[4] = x1; - out[5] = y1; - out[6] = z1; - out[7] = 0; - out[8] = x2; - out[9] = y2; - out[10] = z2; - out[11] = 0; - out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); - out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); - out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); - out[15] = 1; + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); + } - return out; -}; -},{"./identity":136}],139:[function(require,module,exports){ -module.exports = multiply; + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + return child; + } + + return _clone(parent, depth); +} /** - * Multiplies two mat4's + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. */ -function multiply(out, a, b) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; +clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); +}; + +// private utility functions + +function __objToStr(o) { + return Object.prototype.toString.call(o); +}; +clone.__objToStr = __objToStr; + +function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; +}; +clone.__isDate = __isDate; + +function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; +}; +clone.__isArray = __isArray; + +function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; +}; +clone.__isRegExp = __isRegExp; + +function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; +}; +clone.__getRegExpFlags = __getRegExpFlags; - // Cache only the current line of the second matrix - var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; +return clone; +})(); - b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; - out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; +if (typeof module === 'object' && module.exports) { + module.exports = clone; +} - b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; - out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; +}).call(this,require("buffer").Buffer) +},{"buffer":65}],265:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":306}],266:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":267,"./lib/create-attributes":268,"./lib/create-uniforms":269,"./lib/reflect":270,"./lib/runtime-reflect":271,"./lib/shader-cache":272,"dup":94}],267:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],268:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":267,"dup":96}],269:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":267,"./reflect":270,"dup":97}],270:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],271:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],272:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":267,"dup":100,"gl-format-compiler-error":273,"weakmap-shim":291}],273:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":274,"dup":101,"gl-constants/lookup":278,"glsl-shader-name":279,"sprintf-js":288}],274:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":275}],275:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":276}],276:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],277:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],278:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":277,"dup":106}],279:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":280,"dup":107,"glsl-tokenizer":287}],280:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],281:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":283,"./lib/builtins-300es":282,"./lib/literals":285,"./lib/literals-300es":284,"./lib/operators":286,"dup":109}],282:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":283,"dup":110}],283:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],284:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":285,"dup":112}],285:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],286:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],287:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":281,"dup":115}],288:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],289:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":290,"dup":117}],290:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],291:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":289,"dup":119}],292:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":306}],293:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],294:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":293,"dup":155}],295:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":293,"dup":156}],296:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":294,"./lib/vao-native.js":295,"dup":157}],297:[function(require,module,exports){ +var DEFAULT_NORMALS_EPSILON = 1e-6; +var DEFAULT_FACE_EPSILON = 1e-6; - b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; - out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - return out; -}; -},{}],140:[function(require,module,exports){ -module.exports = perspective; +//Estimate the vertex normals of a mesh +exports.vertexNormals = function(faces, positions, specifiedEpsilon) { -/** - * Generates a perspective projection matrix with the given bounds - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {number} fovy Vertical field of view in radians - * @param {number} aspect Aspect ratio. typically viewport width/height - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ -function perspective(out, fovy, aspect, near, far) { - var f = 1.0 / Math.tan(fovy / 2), - nf = 1 / (near - far); - out[0] = f / aspect; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = f; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = (far + near) * nf; - out[11] = -1; - out[12] = 0; - out[13] = 0; - out[14] = (2 * far * near) * nf; - out[15] = 0; - return out; -}; -},{}],141:[function(require,module,exports){ -module.exports = rotate; + var N = positions.length; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon; -/** - * Rotates a mat4 by the given angle - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ -function rotate(out, a, rad, axis) { - var x = axis[0], y = axis[1], z = axis[2], - len = Math.sqrt(x * x + y * y + z * z), - s, c, t, - a00, a01, a02, a03, - a10, a11, a12, a13, - a20, a21, a22, a23, - b00, b01, b02, - b10, b11, b12, - b20, b21, b22; + //Initialize normal array + for(var i=0; i epsilon) { + var norm = normals[c]; + var w = 1.0 / Math.sqrt(m01 * m21); + for(var k=0; k<3; ++k) { + var u = (k+1)%3; + var v = (k+2)%3; + norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); + } + } + } + } - if (a !== out) { // If the source and destination differ, copy the unchanged last row - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + //Scale all normals to unit length + for(var i=0; i epsilon) { + var w = 1.0 / Math.sqrt(m); + for(var k=0; k<3; ++k) { + norm[k] *= w; + } + } else { + for(var k=0; k<3; ++k) { + norm[k] = 0.0; + } + } + } -/** - * Rotates a matrix by the given angle around the X axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateX(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a10 = a[4], - a11 = a[5], - a12 = a[6], - a13 = a[7], - a20 = a[8], - a21 = a[9], - a22 = a[10], - a23 = a[11]; + //Return the resulting set of patches + return normals; +} - if (a !== out) { // If the source and destination differ, copy the unchanged rows - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - } +//Compute face normals of a mesh +exports.faceNormals = function(faces, positions, specifiedEpsilon) { - // Perform axis-specific matrix multiplication - out[4] = a10 * c + a20 * s; - out[5] = a11 * c + a21 * s; - out[6] = a12 * c + a22 * s; - out[7] = a13 * c + a23 * s; - out[8] = a20 * c - a10 * s; - out[9] = a21 * c - a11 * s; - out[10] = a22 * c - a12 * s; - out[11] = a23 * c - a13 * s; - return out; -}; -},{}],143:[function(require,module,exports){ -module.exports = rotateY; + var N = faces.length; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon; -/** - * Rotates a matrix by the given angle around the Y axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateY(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a[0], - a01 = a[1], - a02 = a[2], - a03 = a[3], - a20 = a[8], - a21 = a[9], - a22 = a[10], - a23 = a[11]; + for(var i=0; i epsilon) { + l = 1.0 / Math.sqrt(l); + } else { + l = 0.0; + } + for(var j=0; j<3; ++j) { + n[j] *= l; + } + normals[i] = n; + } + return normals; +} -/** - * Rotates a matrix by the given angle around the Z axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateZ(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a[0], - a01 = a[1], - a02 = a[2], - a03 = a[3], - a10 = a[4], - a11 = a[5], - a12 = a[6], - a13 = a[7]; - if (a !== out) { // If the source and destination differ, copy the unchanged last row - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + +},{}],298:[function(require,module,exports){ +//Optimized version for triangle closest point +// Based on Eberly's WildMagick codes +// http://www.geometrictools.com/LibMathematics/Distance/Distance.html +"use strict"; + +var diff = new Float64Array(4); +var edge0 = new Float64Array(4); +var edge1 = new Float64Array(4); + +function closestPoint2d(V0, V1, V2, point, result) { + //Reallocate buffers if necessary + if(diff.length < point.length) { + diff = new Float64Array(point.length); + edge0 = new Float64Array(point.length); + edge1 = new Float64Array(point.length); + } + //Compute edges + for(var i=0; i= a00) { + s = 1.0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } else { + s = 0; + if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else if (-b1 >= a11) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else { // region 3 + s = 0; + if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else if (-b1 >= a11) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else if (t < 0) { // region 5 + t = 0; + if (b0 >= 0) { + s = 0; + sqrDistance = c; + } else if (-b0 >= a00) { + s = 1; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } else { // region 0 + // minimum at interior point + var invDet = 1.0 / det; + s *= invDet; + t *= invDet; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + var tmp0, tmp1, numer, denom; + + if (s < 0) { // region 2 + tmp0 = a01 + b0; + tmp1 = a11 + b1; + if (tmp1 > tmp0) { + numer = tmp1 - tmp0; + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + s = 1; + t = 0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = numer/denom; + t = 1 - s; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + s = 0; + if (tmp1 <= 0) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else if (t < 0) { // region 6 + tmp0 = a01 + b1; + tmp1 = a00 + b0; + if (tmp1 > tmp0) { + numer = tmp1 - tmp0; + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + t = 1; + s = 0; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = numer/denom; + s = 1 - t; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + t = 0; + if (tmp1 <= 0) { + s = 1; + sqrDistance = a00 + 2.0*b0 + c; + } else if (b0 >= 0) { + s = 0; + sqrDistance = c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } + } else { // region 1 + numer = a11 + b1 - a01 - b0; + if (numer <= 0) { + s = 0; + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + s = 1; + t = 0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = numer/denom; + t = 1 - s; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } } + } + var u = 1.0 - s - t; + for(var i=0; i 1.0001) { - return null + //Count number of cells + var numCells = cells.length + if(numCells === 0 || d < 1) { + return { + cells: [], + vertexIds: [], + vertexWeights: [] } - s += weights[i] - } - if(Math.abs(s - 1.0) > 0.001) { - return null } - return [closestIndex, interpolate(simplex, weights), weights] -} -},{"barycentric":151,"polytope-closest-point/lib/closest_point_2d.js":153}],149:[function(require,module,exports){ - -var triVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}" -var triFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}" -var edgeVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}" -var edgeFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" -var pointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}" -var pointFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" -var pickVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}" -var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}" -var pickPointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}" -var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}" -var contourFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n" + //Read in vertex signs + var vertexSigns = getSigns(values, +level) -exports.meshShader = { - vertex: triVertSrc, - fragment: triFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'normal', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'} - ] -} -exports.wireShader = { - vertex: edgeVertSrc, - fragment: edgeFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'} - ] -} -exports.pointShader = { - vertex: pointVertSrc, - fragment: pointFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'}, - {name: 'pointSize', type: 'float'} - ] -} -exports.pickShader = { - vertex: pickVertSrc, - fragment: pickFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'id', type: 'vec4'} - ] -} -exports.pointPickShader = { - vertex: pickPointVertSrc, - fragment: pickFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'pointSize', type: 'float'}, - {name: 'id', type: 'vec4'} - ] -} -exports.contourShader = { - vertex: contourVertSrc, - fragment: contourFragSrc, - attributes: [ - {name: 'position', type: 'vec3'} - ] -} + //First get 1-skeleton, find all crossings + var edges = getEdges(cells, d) + var weights = getCrossingWeights(edges, values, vertexSigns, +level) -},{}],150:[function(require,module,exports){ -'use strict' + //Build vertex cascade to speed up binary search + var vcascade = getCascade(edges, values.length|0) -var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small -var DEFAULT_FACE_NORMALS_EPSILON = 1e-6; + //Then construct cells + var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns) -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createTexture = require('gl-texture2d') -var normals = require('normals') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var ndarray = require('ndarray') -var colormap = require('colormap') -var getContour = require('simplicial-complex-contour') -var pool = require('typedarray-pool') -var shaders = require('./lib/shaders') -var closestPoint = require('./lib/closest-point') + //Unpack data into pretty format + var uedges = unpackEdges(edges) + var uweights = [].slice.call(weights.data, 0, weights.shape[0]) -var meshShader = shaders.meshShader -var wireShader = shaders.wireShader -var pointShader = shaders.pointShader -var pickShader = shaders.pickShader -var pointPickShader = shaders.pointPickShader -var contourShader = shaders.contourShader + //Release data + pool.free(vertexSigns) + pool.free(edges.data) + pool.free(weights.data) + pool.free(vcascade) + + return { + cells: faces, + vertexIds: uedges, + vertexWeights: uweights + } +} +},{"./lib/codegen":300,"ndarray":1031,"ndarray-sort":303,"typedarray-pool":306}],300:[function(require,module,exports){ +'use strict' -var identityMatrix = [ - 1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] +module.exports = getPolygonizer -function SimplicialMesh(gl - , texture - , triShader - , lineShader - , pointShader - , pickShader - , pointPickShader - , contourShader - , trianglePositions - , triangleIds - , triangleColors - , triangleUVs - , triangleNormals - , triangleVAO - , edgePositions - , edgeIds - , edgeColors - , edgeUVs - , edgeVAO - , pointPositions - , pointIds - , pointColors - , pointUVs - , pointSizes - , pointVAO - , contourPositions - , contourVAO) { +var pool = require('typedarray-pool') +var createMSTable = require('marching-simplex-table') - this.gl = gl - this.cells = [] - this.positions = [] - this.intensity = [] - this.texture = texture - this.dirty = true +var CACHE = {} - this.triShader = triShader - this.lineShader = lineShader - this.pointShader = pointShader - this.pickShader = pickShader - this.pointPickShader = pointPickShader - this.contourShader = contourShader +function createCellPolygonizer(d) { + var maxCellSize = 0 + var tables = new Array(d+1) + tables[0] = [ [] ] + for(var i=1; i<=d; ++i) { + var tab = tables[i] = createMSTable(i) + for(var j=0; j>1,v=E[2*m+1];', + 'if(v===b){return m}', + 'if(b 0) { + code.push(',') + } + code.push('[') + for(var j=0; j 0) { + code.push(',') + } + code.push('B(C,E,c[', f[0], '],c[', f[1], '])') + } + code.push(']') + } + code.push(');') + } - this.pointPositions = pointPositions - this.pointColors = pointColors - this.pointUVs = pointUVs - this.pointSizes = pointSizes - this.pointIds = pointIds - this.pointVAO = pointVAO - this.pointCount = 0 + for(var i=d+1; i>1; --i) { + if(i < d+1) { + code.push('else ') + } + code.push('if(l===', i, '){') - this.contourLineWidth = 1 - this.contourPositions = contourPositions - this.contourVAO = contourVAO - this.contourCount = 0 - this.contourColor = [0,0,0] - this.contourEnable = true + //Generate mask + var maskStr = [] + for(var j=0; j= 1 -} +var chull = require('convex-hull') -proto.isTransparent = function() { - return this.opacity < 1 +function constructVertex(d, a, b) { + var x = new Array(d) + for(var i=0; i 1) { + var scratch_shape = [] + for(var i=1; i 1) { + + //Copy data into scratch + code.push("dptr=0;sptr=ptr") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"left){", + "dptr=0", + "sptr=cptr-s0") + for(var i=1; ib){break __l}"].join("")) + for(var i=order.length-1; i>=1; --i) { + code.push( + "sptr+=e"+i, + "dptr+=f"+i, + "}") + } + + //Copy data back + code.push("dptr=cptr;sptr=cptr-s0") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"left)&&("+dataRead("cptr-s0")+">scratch)){", + dataWrite("cptr", dataRead("cptr-s0")), + "cptr-=s0", + "}", + dataWrite("cptr", "scratch")) + } + + //Close outer loop body + code.push("}") + if(order.length > 1 && allocator) { + code.push("free(scratch)") + } + code.push("} return " + funcName) + + //Compile and link function + if(allocator) { + var result = new Function("malloc", "free", code.join("\n")) + return result(allocator[0], allocator[1]) + } else { + var result = new Function(code.join("\n")) + return result() } - return result } -proto.highlight = function(selection) { - if(!selection || !this.contourEnable) { - this.contourCount = 0 - return +function createQuickSort(order, dtype, insertionSort) { + var code = [ "'use strict'" ] + var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("") + var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length)) + var allocator = getMallocFree(dtype) + var labelCounter=0 + + code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) + + var vars = [ + "sixth=((right-left+1)/6)|0", + "index1=left+sixth", + "index5=right-sixth", + "index3=(left+right)>>1", + "index2=index3-sixth", + "index4=index3+sixth", + "el1=index1", + "el2=index2", + "el3=index3", + "el4=index4", + "el5=index5", + "less=left+1", + "great=right-1", + "pivots_are_equal=true", + "tmp", + "tmp0", + "x", + "y", + "z", + "k", + "ptr0", + "ptr1", + "ptr2", + "comp_pivot1=0", + "comp_pivot2=0", + "comp=0" + ] + + if(order.length > 1) { + var ele_size = [] + for(var i=1; i=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j," 1) { + for(var i=0; i1) { + code.push("ptr_shift+=d"+j) + } else { + code.push("ptr0+=d"+j) } + code.push("}") } } - this.contourCount = (ptr / 3)|0 - this.contourPositions.update(result.subarray(0, ptr)) - pool.free(result) -} - -proto.update = function(params) { - params = params || {} - var gl = this.gl - - this.dirty = true - - if('contourEnable' in params) { - this.contourEnable = params.contourEnable + + function lexicoLoop(label, ptrs, usePivot, body) { + if(ptrs.length === 1) { + code.push("ptr0="+toPointer(ptrs[0])) + } else { + for(var i=0; i 1) { + for(var i=0; i=1; --i) { + if(usePivot) { + code.push("pivot_ptr+=f"+i) + } + if(ptrs.length > 1) { + code.push("ptr_shift+=e"+i) + } else { + code.push("ptr0+=e"+i) + } + code.push("}") + } } - if('contourColor' in params) { - this.contourColor = params.contourColor + + function cleanUp() { + if(order.length > 1 && allocator) { + code.push("free(pivot1)", "free(pivot2)") + } } - if('lineWidth' in params) { - this.lineWidth = params.lineWidth + + function compareSwap(a_id, b_id) { + var a = "el"+a_id + var b = "el"+b_id + if(order.length > 1) { + var lbl = "__l" + (++labelCounter) + lexicoLoop(lbl, [a, b], false, [ + "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n", + "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n", + "if(comp<0){break ", lbl, "}" + ].join("")) + } else { + code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join("")) + } } - if('lightPosition' in params) { - this.lightPosition = params.lightPosition + + compareSwap(1, 2) + compareSwap(4, 5) + compareSwap(1, 3) + compareSwap(2, 3) + compareSwap(1, 4) + compareSwap(3, 4) + compareSwap(2, 5) + compareSwap(2, 3) + compareSwap(4, 5) + + if(order.length > 1) { + cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [ + "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n", + "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n", + "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n", + "x=",dataRead("ptr0"),"\n", + "y=",dataRead("ptr2"),"\n", + "z=",dataRead("ptr4"),"\n", + dataWrite("ptr5", "x"),"\n", + dataWrite("ptr6", "y"),"\n", + dataWrite("ptr7", "z") + ].join("")) + } else { + code.push([ + "pivot1=", dataRead(toPointer("el2")), "\n", + "pivot2=", dataRead(toPointer("el4")), "\n", + "pivots_are_equal=pivot1===pivot2\n", + "x=", dataRead(toPointer("el1")), "\n", + "y=", dataRead(toPointer("el3")), "\n", + "z=", dataRead(toPointer("el5")), "\n", + dataWrite(toPointer("index1"), "x"), "\n", + dataWrite(toPointer("index3"), "y"), "\n", + dataWrite(toPointer("index5"), "z") + ].join("")) } - if('opacity' in params) { - this.opacity = params.opacity + + + function moveElement(dst, src) { + if(order.length > 1) { + cacheLoop([dst, src], false, + dataWrite("ptr0", dataRead("ptr1")) + ) + } else { + code.push(dataWrite(toPointer(dst), dataRead(toPointer(src)))) + } } - if('ambient' in params) { - this.ambientLight = params.ambient + + moveElement("index2", "left") + moveElement("index4", "right") + + function comparePivot(result, ptr, n) { + if(order.length > 1) { + var lbl = "__l" + (++labelCounter) + lexicoLoop(lbl, [ptr], true, [ + result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n", + "if(",result,"!==0){break ", lbl, "}" + ].join("")) + } else { + code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join("")) + } } - if('diffuse' in params) { - this.diffuseLight = params.diffuse + + function swapElements(a, b) { + if(order.length > 1) { + cacheLoop([a,b],false,[ + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", "tmp") + ].join("")) + } else { + code.push([ + "ptr0=",toPointer(a),"\n", + "ptr1=",toPointer(b),"\n", + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", "tmp") + ].join("")) + } } - if('specular' in params) { - this.specularLight = params.specular + + function tripleSwap(k, less, great) { + if(order.length > 1) { + cacheLoop([k,less,great], false, [ + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", dataRead("ptr2")),"\n", + dataWrite("ptr2", "tmp") + ].join("")) + code.push("++"+less, "--"+great) + } else { + code.push([ + "ptr0=",toPointer(k),"\n", + "ptr1=",toPointer(less),"\n", + "ptr2=",toPointer(great),"\n", + "++",less,"\n", + "--",great,"\n", + "tmp=", dataRead("ptr0"), "\n", + dataWrite("ptr0", dataRead("ptr1")), "\n", + dataWrite("ptr1", dataRead("ptr2")), "\n", + dataWrite("ptr2", "tmp") + ].join("")) + } } - if('roughness' in params) { - this.roughness = params.roughness + + function swapAndDecrement(k, great) { + swapElements(k, great) + code.push("--"+great) } - if('fresnel' in params) { - this.fresnel = params.fresnel + + code.push("if(pivots_are_equal){") + //Pivots are equal case + code.push("for(k=less;k<=great;++k){") + comparePivot("comp", "k", 1) + code.push("if(comp===0){continue}") + code.push("if(comp<0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + code.push("while(true){") + comparePivot("comp", "great", 1) + code.push("if(comp>0){") + code.push("great--") + code.push("}else if(comp<0){") + tripleSwap("k", "less", "great") + code.push("break") + code.push("}else{") + swapAndDecrement("k", "great") + code.push("break") + code.push("}") + code.push("}") + code.push("}") + code.push("}") + code.push("}else{") + //Pivots not equal case + code.push("for(k=less;k<=great;++k){") + comparePivot("comp_pivot1", "k", 1) + code.push("if(comp_pivot1<0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + comparePivot("comp_pivot2", "k", 2) + code.push("if(comp_pivot2>0){") + code.push("while(true){") + comparePivot("comp", "great", 2) + code.push("if(comp>0){") + code.push("if(--great1) { + cacheLoop([mem_dest, pivot_dest], true, [ + dataWrite("ptr0", dataRead("ptr1")), "\n", + dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join("")) + ].join("")) + } else { + code.push( + dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))), + dataWrite(toPointer(pivot_dest), "pivot"+pivot)) + } } + + storePivot("left", "(less-1)", 1) + storePivot("right", "(great+1)", 2) - if(params.texture) { - this.texture.dispose() - this.texture = createTexture(gl, params.texture) - } else if (params.colormap) { - this.texture.shape = [256,256] - this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR - this.texture.magFilter = gl.LINEAR - this.texture.setPixels(genColormap(params.colormap)) - this.texture.generateMipmap() + //Recursive sort call + function doSort(left, right) { + code.push([ + "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n", + "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", + "}else{\n", + funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", + "}" + ].join("")) } - - var cells = params.cells - var positions = params.positions - - if(!positions || !cells) { - return + doSort("left", "(less-2)") + doSort("(great+2)", "right") + + //If pivots are equal, then early out + code.push("if(pivots_are_equal){") + cleanUp() + code.push("return") + code.push("}") + + function walkPointer(ptr, pivot, body) { + if(order.length > 1) { + code.push(["__l",++labelCounter,":while(true){"].join("")) + cacheLoop([ptr], true, [ + "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}" + ].join("")) + code.push(body, "}") + } else { + code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join("")) + } } + + //Check bounds + code.push("if(lessindex5){") + + walkPointer("less", 1, "++less") + walkPointer("great", 2, "--great") + + code.push("for(k=less;k<=great;++k){") + comparePivot("comp_pivot1", "k", 1) + code.push("if(comp_pivot1===0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + comparePivot("comp_pivot2", "k", 2) + code.push("if(comp_pivot2===0){") + code.push("while(true){") + comparePivot("comp", "great", 2) + code.push("if(comp===0){") + code.push("if(--great 1 && allocator) { + var compiled = new Function("insertionSort", "malloc", "free", code.join("\n")) + return compiled(insertionSort, allocator[0], allocator[1]) + } + var compiled = new Function("insertionSort", code.join("\n")) + return compiled(insertionSort) +} - var tPos = [] - var tCol = [] - var tNor = [] - var tUVs = [] - var tIds = [] - - var ePos = [] - var eCol = [] - var eUVs = [] - var eIds = [] - - var pPos = [] - var pCol = [] - var pUVs = [] - var pSiz = [] - var pIds = [] - - //Save geometry data for picking calculations - this.cells = cells - this.positions = positions - - //Compute normals - var vertexNormals = params.vertexNormals - var cellNormals = params.cellNormals - var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon - var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon - if(params.useFacetNormals && !cellNormals) { - cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon) +function compileSort(order, dtype) { + var code = ["'use strict'"] + var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("") + var funcArgs = [ "array" ] + + code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) + + //Unpack local variables from array + var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"] + for(var i=0; i 0) { + vars.push(["d",j,"=s",j,"-d",p,"*n",p].join("")) + } else { + vars.push(["d",j,"=s",j].join("")) } - } else { - for(var i=0; i 0) { + vars.push(["e",k,"=s",k,"-e",q,"*n",q, + ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join("")) + } else { + vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join("")) } + q = k } } + + //Declare local variables + code.push("var " + vars.join(",")) + + //Create arguments for subroutine + var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length)) + + //Call main sorting routine + code.push([ + "if(n0<=",INSERTION_SORT_THRESHOLD,"){", + "insertionSort(", sortArgs.join(","), ")}else{", + "quickSort(", sortArgs.join(","), + ")}" + ].join("")) + + //Return + code.push("}return " + funcName) + + //Link everything together + var result = new Function("insertionSort", "quickSort", code.join("\n")) + var insertionSort = createInsertionSort(order, dtype) + var quickSort = createQuickSort(order, dtype, insertionSort) + return result(insertionSort, quickSort) +} - if(vertexIntensity) { - this.intensity = vertexIntensity - } else if(cellIntensity) { - this.intensity = unpackIntensity(cells, positions.length, cellIntensity) - } else { - this.intensity = takeZComponent(positions) - } - - //Point size - var pointSizes = params.pointSizes - var meshPointSize = params.pointSize || 1.0 +module.exports = compileSort +},{"typedarray-pool":306}],303:[function(require,module,exports){ +"use strict" - //Update bounds - this.bounds = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]] - for(var i=0; i 0) { - var shader = this.triShader - shader.bind() - shader.uniforms = uniforms + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight - this.triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) - this.triangleVAO.unbind() - } + if(xCount) { + uniforms.color = tickMarkColor[0] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } - if(this.edgeCount > 0 && this.lineWidth > 0) { - var shader = this.lineShader - shader.bind() - shader.uniforms = uniforms + SCR_OFFSET[0] = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0 + SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkLength[3] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkWidth[3] * pixelRatio / screenHeight - this.edgeVAO.bind() - gl.lineWidth(this.lineWidth) - gl.drawArrays(gl.LINES, 0, this.edgeCount*2) - this.edgeVAO.unbind() - } + if(yCount) { + uniforms.color = tickMarkColor[3] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = Y_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, yOffset, yCount) + } - if(this.pointCount > 0) { - var shader = this.pointShader - shader.bind() - shader.uniforms = uniforms + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[2] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[2] * pixelRatio / screenHeight - this.pointVAO.bind() - gl.drawArrays(gl.POINTS, 0, this.pointCount) - this.pointVAO.unbind() + if(xCount) { + uniforms.color = tickMarkColor[2] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } } +})() - if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) { - var shader = this.contourShader - shader.bind() - shader.uniforms = uniforms - - this.contourVAO.bind() - gl.drawArrays(gl.LINES, 0, this.contourCount) - this.contourVAO.unbind() - } -} +proto.update = (function() { + var OFFSET_X = [1, 1, -1, -1, 1, -1] + var OFFSET_Y = [1, -1, 1, 1, -1, -1] -proto.drawPick = function(params) { - params = params || {} + return function(options) { + var ticks = options.ticks + var bounds = options.bounds + var data = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length)) - var gl = this.gl + var zeroLineEnable = this.plot.zeroLineEnable - var model = params.model || identityMatrix - var view = params.view || identityMatrix - var projection = params.projection || identityMatrix + var ptr = 0 + var gridTicks = [[], []] + for(var dim=0; dim<2; ++dim) { + var localTicks = gridTicks[dim] + var axisTicks = ticks[dim] + var lo = bounds[dim] + var hi = bounds[dim+2] + for(var i=0; i 0) { - this.triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) - this.triangleVAO.unbind() - } +module.exports = createLines - if(this.edgeCount > 0) { - this.edgeVAO.bind() - gl.lineWidth(this.lineWidth) - gl.drawArrays(gl.LINES, 0, this.edgeCount*2) - this.edgeVAO.unbind() - } +var createBuffer = require('gl-buffer') +var createShader = require('gl-shader') - if(this.pointCount > 0) { - var shader = this.pointPickShader - shader.bind() - shader.uniforms = uniforms +var shaders = require('./shaders') - this.pointVAO.bind() - gl.drawArrays(gl.POINTS, 0, this.pointCount) - this.pointVAO.unbind() - } +function Lines(plot, vbo, shader) { + this.plot = plot + this.vbo = vbo + this.shader = shader } +var proto = Lines.prototype -proto.pick = function(pickData) { - if(!pickData) { - return null - } - if(pickData.id !== this.pickId) { - return null - } +proto.bind = function() { + var shader = this.shader + this.vbo.bind() + this.shader.bind() + shader.attributes.coord.pointer() + shader.uniforms.screenBox = this.plot.screenBox +} - var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2] - var cell = this.cells[cellId] - var positions = this.positions +proto.drawLine = (function() { + var start = [0,0] + var end = [0,0] + return function(startX, startY, endX, endY, width, color) { + var plot = this.plot + var shader = this.shader + var gl = plot.gl - var simplex = new Array(cell.length) - for(var i=0; i tickOffset[start]) { + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = textColor[axis] + shader.uniforms.angle = textAngle[axis] + gl.drawArrays( + gl.TRIANGLES, + tickOffset[start], + tickOffset[end] - tickOffset[start]) + } + } + if(labelEnable[axis] && labelCount) { + SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis] + shader.uniforms.dataAxis = ZERO_2 + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = labelColor[axis] + shader.uniforms.angle = labelAngle[axis] + gl.drawArrays( + gl.TRIANGLES, + labelOffset, + labelCount) } - ]) - var edgePositions = createBuffer(gl) - var edgeColors = createBuffer(gl) - var edgeUVs = createBuffer(gl) - var edgeIds = createBuffer(gl) - var edgeVAO = createVAO(gl, [ - { buffer: edgePositions, - type: gl.FLOAT, - size: 3 - }, - { buffer: edgeIds, - type: gl.UNSIGNED_BYTE, - size: 4, - normalized: true - }, - { buffer: edgeColors, - type: gl.FLOAT, - size: 4 - }, - { buffer: edgeUVs, - type: gl.FLOAT, - size: 2 + SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0 + if(tickEnable[axis+2]) { + SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2] + if(start < end && tickOffset[end] > tickOffset[start]) { + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = textColor[axis+2] + shader.uniforms.angle = textAngle[axis+2] + gl.drawArrays( + gl.TRIANGLES, + tickOffset[start], + tickOffset[end] - tickOffset[start]) + } + } + if(labelEnable[axis+2] && labelCount) { + SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2] + shader.uniforms.dataAxis = ZERO_2 + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = labelColor[axis+2] + shader.uniforms.angle = labelAngle[axis+2] + gl.drawArrays( + gl.TRIANGLES, + labelOffset, + labelCount) } - ]) - var pointPositions = createBuffer(gl) - var pointColors = createBuffer(gl) - var pointUVs = createBuffer(gl) - var pointSizes = createBuffer(gl) - var pointIds = createBuffer(gl) - var pointVAO = createVAO(gl, [ - { buffer: pointPositions, - type: gl.FLOAT, - size: 3 - }, - { buffer: pointIds, - type: gl.UNSIGNED_BYTE, - size: 4, - normalized: true - }, - { buffer: pointColors, - type: gl.FLOAT, - size: 4 - }, - { buffer: pointUVs, - type: gl.FLOAT, - size: 2 - }, - { buffer: pointSizes, - type: gl.FLOAT, - size: 1 + } +})() + +proto.drawTitle = (function() { + var DATA_AXIS = [0,0] + var SCREEN_OFFSET = [0,0] + + return function() { + var plot = this.plot + var shader = this.shader + var gl = plot.gl + var screenBox = plot.screenBox + var titleCenter = plot.titleCenter + var titleAngle = plot.titleAngle + var titleColor = plot.titleColor + var titleCenter = plot.titleCenter + var pixelRatio = plot.pixelRatio + + if(!this.titleCount) { + return } - ]) - var contourPositions = createBuffer(gl) - var contourVAO = createVAO(gl, [ - { buffer: contourPositions, - type: gl.FLOAT, - size: 3 - }]) + for(var i=0; i<2; ++i) { + SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) / + (screenBox[2+i] - screenBox[i]) - 1 + } - var mesh = new SimplicialMesh(gl - , meshTexture - , triShader - , lineShader - , pointShader - , pickShader - , pointPickShader - , contourShader - , trianglePositions - , triangleIds - , triangleColors - , triangleUVs - , triangleNormals - , triangleVAO - , edgePositions - , edgeIds - , edgeColors - , edgeUVs - , edgeVAO - , pointPositions - , pointIds - , pointColors - , pointUVs - , pointSizes - , pointVAO - , contourPositions - , contourVAO) + shader.bind() + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.angle = titleAngle + shader.uniforms.color = titleColor - mesh.update(params) + gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount) + } +})() - return mesh -} +proto.bind = (function() { + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var TEXT_SCALE = [0,0] -module.exports = createSimplicialMesh + return function() { + var plot = this.plot + var shader = this.shader + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var screenBox = plot.screenBox + var viewBox = plot.viewBox -},{"./lib/closest-point":148,"./lib/shaders":149,"colormap":100,"gl-buffer":118,"gl-mat4/invert":137,"gl-mat4/multiply":139,"gl-shader":197,"gl-texture2d":222,"gl-vao":226,"ndarray":253,"normals":152,"simplicial-complex-contour":154,"typedarray-pool":278}],151:[function(require,module,exports){ -'use strict' + shader.bind() -module.exports = barycentric + //Set up coordinate scaling uniforms + for(var i=0; i<2; ++i) { -var solve = require('robust-linear-solve') + var lo = bounds[i] + var hi = bounds[i+2] + var boundScale = hi - lo + var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) + var dataWidth = (dataBox[i+2] - dataBox[i]) -function reduce(x) { - var r = 0 - for(var i=0; i epsilon) { - var norm = normals[c]; - var w = 1.0 / Math.sqrt(m01 * m21); - for(var k=0; k<3; ++k) { - var u = (k+1)%3; - var v = (k+2)%3; - norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); - } - } + offsets.push(Math.floor(vertices.length/3)) + tickX.push(x) } - } - //Scale all normals to unit length - for(var i=0; i epsilon) { - var w = 1.0 / Math.sqrt(m); - for(var k=0; k<3; ++k) { - norm[k] *= w; - } - } else { - for(var k=0; k<3; ++k) { - norm[k] = 0.0; - } - } + this.tickOffset[dimension] = offsets + this.tickX[dimension] = tickX } - //Return the resulting set of patches - return normals; -} - -//Compute face normals of a mesh -exports.faceNormals = function(faces, positions, specifiedEpsilon) { - - var N = faces.length; - var normals = new Array(N); - var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon; + //Add labels + for(var dimension=0; dimension<2; ++dimension) { + this.labelOffset[dimension] = Math.floor(vertices.length/3) - for(var i=0; i epsilon) { - l = 1.0 / Math.sqrt(l); - } else { - l = 0.0; - } - for(var j=0; j<3; ++j) { - n[j] *= l; - } - normals[i] = n; + //Add title + this.titleOffset = Math.floor(vertices.length/3) + var data = getText(options.titleFont, options.title).data + var scale = options.titleSize + for(var i=0; i= a00) { - s = 1.0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } else { - s = 0; - if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else if (-b1 >= a11) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else { // region 3 - s = 0; - if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else if (-b1 >= a11) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else if (t < 0) { // region 5 - t = 0; - if (b0 >= 0) { - s = 0; - sqrDistance = c; - } else if (-b0 >= a00) { - s = 1; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } else { // region 0 - // minimum at interior point - var invDet = 1.0 / det; - s *= invDet; - t *= invDet; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c; +function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) { + var code = [ + "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", +earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), +";while(l<=h){\ +var m=(l+h)>>>1,x=a[m]"] + if(earlyOut) { + if(predicate.indexOf("c") < 0) { + code.push(";if(x===y){return m}else if(x<=y){") + } else { + code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") } } else { - var tmp0, tmp1, numer, denom; - - if (s < 0) { // region 2 - tmp0 = a01 + b0; - tmp1 = a11 + b1; - if (tmp1 > tmp0) { - numer = tmp1 - tmp0; - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - s = 1; - t = 0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = numer/denom; - t = 1 - s; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - s = 0; - if (tmp1 <= 0) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else if (t < 0) { // region 6 - tmp0 = a01 + b1; - tmp1 = a00 + b0; - if (tmp1 > tmp0) { - numer = tmp1 - tmp0; - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - t = 1; - s = 0; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = numer/denom; - s = 1 - t; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - t = 0; - if (tmp1 <= 0) { - s = 1; - sqrDistance = a00 + 2.0*b0 + c; - } else if (b0 >= 0) { - s = 0; - sqrDistance = c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } - } else { // region 1 - numer = a11 + b1 - a01 - b0; - if (numer <= 0) { - s = 0; - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - s = 1; - t = 0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = numer/denom; - t = 1 - s; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } - } + code.push(";if(", predicate, "){i=m;") } - var u = 1.0 - s - t; - for(var i=0; i=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) } -module.exports = closestPoint2d; +},{}],313:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":316}],314:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],315:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],316:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":314,"buffer":65,"dup":122}],317:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],318:[function(require,module,exports){ +module.exports = require("cwise-compiler") +},{"cwise-compiler":319}],319:[function(require,module,exports){ +"use strict" + +var createThunk = require("./lib/thunk.js") + +function Procedure() { + this.argTypes = [] + this.shimArgs = [] + this.arrayArgs = [] + this.arrayBlockIndices = [] + this.scalarArgs = [] + this.offsetArgs = [] + this.offsetArgIndex = [] + this.indexArgs = [] + this.shapeArgs = [] + this.funcName = "" + this.pre = null + this.body = null + this.post = null + this.debug = false +} + +function compileCwise(user_args) { + //Create procedure + var proc = new Procedure() + + //Parse blocks + proc.pre = user_args.pre + proc.body = user_args.body + proc.post = user_args.post + + //Parse arguments + var proc_args = user_args.args.slice(0) + proc.argTypes = proc_args + for(var i=0; i0) { + throw new Error("cwise: pre() block may not reference array args") + } + if(i < proc.post.args.length && proc.post.args[i].count>0) { + throw new Error("cwise: post() block may not reference array args") + } + } else if(arg_type === "scalar") { + proc.scalarArgs.push(i) + proc.shimArgs.push("scalar" + i) + } else if(arg_type === "index") { + proc.indexArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { + throw new Error("cwise: pre() block may not reference array index") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array index") + } + if(i < proc.post.args.length && proc.post.args[i].count > 0) { + throw new Error("cwise: post() block may not reference array index") + } + } else if(arg_type === "shape") { + proc.shapeArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { + throw new Error("cwise: pre() block may not write to array shape") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array shape") + } + if(i < proc.post.args.length && proc.post.args[i].lvalue) { + throw new Error("cwise: post() block may not write to array shape") + } + } else if(typeof arg_type === "object" && arg_type.offset) { + proc.argTypes[i] = "offset" + proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) + proc.offsetArgIndex.push(i) + } else { + throw new Error("cwise: Unknown argument type " + proc_args[i]) + } + } + + //Make sure at least one array argument was specified + if(proc.arrayArgs.length <= 0) { + throw new Error("cwise: No array arguments specified") + } + + //Make sure arguments are correct + if(proc.pre.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in pre() block") + } + if(proc.body.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in body() block") + } + if(proc.post.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in post() block") + } + + //Check debug flag + proc.debug = !!user_args.printCode || !!user_args.debug + + //Retrieve name + proc.funcName = user_args.funcName || "cwise" + + //Read in block size + proc.blockSize = user_args.blockSize || 64 + + return createThunk(proc) +} + +module.exports = compileCwise + +},{"./lib/thunk.js":321}],320:[function(require,module,exports){ +"use strict" + +var uniq = require("uniq") + +// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) +// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. +function innerFill(order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , has_index = proc.indexArgs.length>0 + , code = [] + , vars = [] + , idx=0, pidx=0, i, j + for(i=0; i=0; --i) { // Start at largest stride and work your way inwards + idx = order[i] + code.push(["for(i",i,"=0;i",i," 0) { + code.push(["index[",pidx,"]-=s",pidx].join("")) + } + code.push(["++index[",idx,"]"].join("")) + } + code.push("}") + } + return code.join("\n") +} + +// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. +// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. +// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. +function outerFill(matched, order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , blockSize = proc.blockSize + , has_index = proc.indexArgs.length > 0 + , code = [] + for(var i=0; i0;){"].join("")) // Iterate back to front + code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). + code.push(["s",order[i],"=j",i].join("")) + code.push(["j",i,"=0"].join("")) + code.push(["}else{s",order[i],"=",blockSize].join("")) + code.push(["j",i,"-=",blockSize,"}"].join("")) + if(has_index) { + code.push(["index[",order[i],"]=j",i].join("")) + } + } + for(var i=0; i 0) { + allEqual = allEqual && summary[i] === summary[i-1] + } + } + if(allEqual) { + return summary[0] + } + return summary.join("") +} + +//Generates a cwise operator +function generateCWiseOp(proc, typesig) { + + //Compute dimension + // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. + var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 + var orders = new Array(proc.arrayArgs.length) + var dtypes = new Array(proc.arrayArgs.length) + for(var i=0; i 0) { + vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) + } + if(proc.indexArgs.length > 0) { + // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. + var zeros = new Array(dimension) + for(var i=0; i 3) { + code.push(processBlock(proc.pre, proc, dtypes)) + } + + //Process body + var body = processBlock(proc.body, proc, dtypes) + var matched = countMatches(loopOrders) + if(matched < dimension) { + code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. + } else { + code.push(innerFill(loopOrders[0], proc, body)) + } + + //Inline epilog + if(proc.post.body.length > 3) { + code.push(processBlock(proc.post, proc, dtypes)) + } + + if(proc.debug) { + console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") + } + + var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") + var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) + return f() +} +module.exports = generateCWiseOp -},{}],154:[function(require,module,exports){ -'use strict' +},{"uniq":322}],321:[function(require,module,exports){ +"use strict" + +// The function below is called when constructing a cwise function object, and does the following: +// A function object is constructed which accepts as argument a compilation function and returns another function. +// It is this other function that is eventually returned by createThunk, and this function is the one that actually +// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. +// The compilation passed to the first function object is used for compiling new functions. +// Once this function object is created, it is called with compile as argument, where the first argument of compile +// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). +// So createThunk roughly works like this: +// function createThunk(proc) { +// var thunk = function(compileBound) { +// var CACHED = {} +// return function(arrays and scalars) { +// if (dtype and order of arrays in CACHED) { +// var func = CACHED[dtype and order of arrays] +// } else { +// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) +// } +// return func(arrays and scalars) +// } +// } +// return thunk(compile.bind1(proc)) +// } + +var compile = require("./compile.js") + +function createThunk(proc) { + var code = ["'use strict'", "var CACHED={}"] + var vars = [] + var thunkName = proc.funcName + "_cwise_thunk" + + //Build thunk + code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) + var typesig = [] + var string_typesig = [] + var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). + Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] + var shapeLengthConditions = [], shapeConditions = [] + // Process array arguments + for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) + shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) + shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") + } + } + // Check for shape equality + if (proc.arrayArgs.length > 1) { + code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") + code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") + code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") + code.push("}") + } + // Process scalar arguments + for(var i=0; i 1) { + ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]) } - //Read in vertex signs - var vertexSigns = getSigns(values, +level) + //Allocate depth/stencil buffers + var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture') + if(WEBGL_depth_texture) { + if(useStencil) { + fbo.depth = initTexture(gl, width, height, + WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, + gl.DEPTH_STENCIL, + gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo.depth = initTexture(gl, width, height, + gl.UNSIGNED_SHORT, + gl.DEPTH_COMPONENT, + gl.DEPTH_ATTACHMENT) + } + } else { + if(useDepth && useStencil) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT) + } else if(useStencil) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT) + } + } - //First get 1-skeleton, find all crossings - var edges = getEdges(cells, d) - var weights = getCrossingWeights(edges, values, vertexSigns, +level) + //Check frame buffer state + var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) + if(status !== gl.FRAMEBUFFER_COMPLETE) { - //Build vertex cascade to speed up binary search - var vcascade = getCascade(edges, values.length|0) + //Release all partially allocated resources + fbo._destroyed = true - //Then construct cells - var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns) + //Release all resources + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.deleteFramebuffer(fbo.handle) + fbo.handle = null + if(fbo.depth) { + fbo.depth.dispose() + fbo.depth = null + } + if(fbo._depth_rb) { + gl.deleteRenderbuffer(fbo._depth_rb) + fbo._depth_rb = null + } + for(var i=0; i>1,v=E[2*m+1];', - 'if(v===b){return m}', - 'if(b 0) { - code.push(',') + //Shape vector for resizing + var parent = this + var shapeVector = [width|0, height|0] + Object.defineProperties(shapeVector, { + 0: { + get: function() { + return parent._shape[0] + }, + set: function(w) { + return parent.width = w } - code.push('[') - for(var j=0; j 0) { - code.push(',') - } - code.push('B(C,E,c[', f[0], '],c[', f[1], '])') + }, + 1: { + get: function() { + return parent._shape[1] + }, + set: function(h) { + return parent.height = h } - code.push(']') } - code.push(');') - } + }) + this._shapeVector = shapeVector - for(var i=d+1; i>1; --i) { - if(i < d+1) { - code.push('else ') - } - code.push('if(l===', i, '){') + //Initialize all attachments + rebuildFBO(this) +} - //Generate mask - var maskStr = [] - for(var j=0; j maxFBOSize || + h < 0 || h > maxFBOSize) { + throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions') } - return alg -} -},{"marching-simplex-table":156,"typedarray-pool":278}],156:[function(require,module,exports){ -'use strict' -module.exports = createTable + //Update shape + fbo._shape[0] = w + fbo._shape[1] = h -var chull = require('convex-hull') + //Save framebuffer state + var state = saveFBOState(gl) -function constructVertex(d, a, b) { - var x = new Array(d) - for(var i=0; i 1) { - var scratch_shape = [] - for(var i=1; i 1) { - - //Copy data into scratch - code.push("dptr=0;sptr=ptr") - for(var i=order.length-1; i>=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"left){", - "dptr=0", - "sptr=cptr-s0") - for(var i=1; ib){break __l}"].join("")) - for(var i=order.length-1; i>=1; --i) { - code.push( - "sptr+=e"+i, - "dptr+=f"+i, - "}") - } - - //Copy data back - code.push("dptr=cptr;sptr=cptr-s0") - for(var i=order.length-1; i>=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j," maxFBOSize || height < 0 || height > maxFBOSize) { + throw new Error('gl-fbo: Parameters are too large for FBO') + } + + //Handle each option type + options = options || {} + + //Figure out number of color buffers to use + var numColors = 1 + if('color' in options) { + numColors = Math.max(options.color|0, 0) + if(numColors < 0) { + throw new Error('gl-fbo: Must specify a nonnegative number of colors') } - code.push(dataWrite("dptr", "scratch[sptr++]")) - for(var i=0; i 1) { + //Check if multiple render targets supported + if(!WEBGL_draw_buffers) { + throw new Error('gl-fbo: Multiple draw buffer extension not supported') + } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) { + throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers') } - code.push("dptr+=d"+j,"}") } - } else { - code.push("scratch=" + dataRead("ptr"), - "while((j-->left)&&("+dataRead("cptr-s0")+">scratch)){", - dataWrite("cptr", dataRead("cptr-s0")), - "cptr-=s0", - "}", - dataWrite("cptr", "scratch")) - } - - //Close outer loop body - code.push("}") - if(order.length > 1 && allocator) { - code.push("free(scratch)") } - code.push("} return " + funcName) - - //Compile and link function - if(allocator) { - var result = new Function("malloc", "free", code.join("\n")) - return result(allocator[0], allocator[1]) - } else { - var result = new Function(code.join("\n")) - return result() - } -} -function createQuickSort(order, dtype, insertionSort) { - var code = [ "'use strict'" ] - var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("") - var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length)) - var allocator = getMallocFree(dtype) - var labelCounter=0 - - code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) - - var vars = [ - "sixth=((right-left+1)/6)|0", - "index1=left+sixth", - "index5=right-sixth", - "index3=(left+right)>>1", - "index2=index3-sixth", - "index4=index3+sixth", - "el1=index1", - "el2=index2", - "el3=index3", - "el4=index4", - "el5=index5", - "less=left+1", - "great=right-1", - "pivots_are_equal=true", - "tmp", - "tmp0", - "x", - "y", - "z", - "k", - "ptr0", - "ptr1", - "ptr2", - "comp_pivot1=0", - "comp_pivot2=0", - "comp=0" - ] - - if(order.length > 1) { - var ele_size = [] - for(var i=1; i 0) { + if(!OES_texture_float) { + throw new Error('gl-fbo: Context does not support floating point textures') } - vars.push( - "ptr3", - "ptr4", - "ptr5", - "ptr6", - "ptr7", - "pivot_ptr", - "ptr_shift", - "elementSize="+ele_size.join("*")) - if(allocator) { - vars.push("pivot1=malloc(elementSize)", - "pivot2=malloc(elementSize)") - } else { - vars.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)") + colorType = gl.FLOAT + } else if(options.preferFloat && numColors > 0) { + if(OES_texture_float) { + colorType = gl.FLOAT } - } else { - vars.push("pivot1", "pivot2") } - - //Initialize local variables - code.push("var " + vars.join(",")) - - function toPointer(v) { - return ["(offset+",v,"*s0)"].join("") + + //Check if we should use depth buffer + var useDepth = true + if('depth' in options) { + useDepth = !!options.depth } - - function dataRead(ptr) { - if(dtype === "generic") { - return ["data.get(", ptr, ")"].join("") - } - return ["data[",ptr,"]"].join("") + + //Check if we should use a stencil buffer + var useStencil = false + if('stencil' in options) { + useStencil = !!options.stencil } - - function dataWrite(ptr, v) { - if(dtype === "generic") { - return ["data.set(", ptr, ",", v, ")"].join("") + + return new Framebuffer( + gl, + width, + height, + colorType, + numColors, + useDepth, + useStencil, + WEBGL_draw_buffers) +} + +},{"gl-texture2d":324}],324:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":326}],325:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],326:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":317,"buffer":65,"dup":122}],327:[function(require,module,exports){ +'use strict' + +module.exports = createSelectBuffer + +var createFBO = require('gl-fbo') +var pool = require('typedarray-pool') +var ndarray = require('ndarray') + +var nextPow2 = require('bit-twiddle').nextPow2 + +var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_4_arg0_||255>_inline_4_arg1_||255>_inline_4_arg2_||255>_inline_4_arg3_){var _inline_4_l=_inline_4_arg4_-_inline_4_arg6_[0],_inline_4_a=_inline_4_arg5_-_inline_4_arg6_[1],_inline_4_f=_inline_4_l*_inline_4_l+_inline_4_a*_inline_4_a;_inline_4_f=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j," 1) { - for(var i=0; i1) { - code.push("ptr_shift+=d"+j) - } else { - code.push("ptr0+=d"+j) + this.fbo.shape = v + var c = this.fbo.shape[0] + var r = this.fbo.shape[1] + if(r*c*4 > this.buffer.length) { + pool.free(this.buffer) + var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) + for(var i=0; i 1) { - for(var i=0; i=1; --i) { - if(usePivot) { - code.push("pivot_ptr+=f"+i) - } - if(ptrs.length > 1) { - code.push("ptr_shift+=e"+i) - } else { - code.push("ptr0+=e"+i) - } - code.push("}") - } +}) + +proto.begin = function() { + var gl = this.gl + var shape = this.shape + if(!gl) { + return + } + + this.fbo.bind() + gl.clearColor(1,1,1,1) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) +} + +proto.end = function() { + var gl = this.gl + if(!gl) { + return + } + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + if(!this._readTimeout) { + clearTimeout(this._readTimeout) + } + this._readTimeout = setTimeout(this._readCallback, 1) +} + +proto.query = function(x, y, radius) { + if(!this.gl) { + return null } - - function cleanUp() { - if(order.length > 1 && allocator) { - code.push("free(pivot1)", "free(pivot2)") - } + + var shape = this.fbo.shape.slice() + + x = x|0 + y = y|0 + if(typeof radius !== 'number') { + radius = 1.0 } - - function compareSwap(a_id, b_id) { - var a = "el"+a_id - var b = "el"+b_id - if(order.length > 1) { - var lbl = "__l" + (++labelCounter) - lexicoLoop(lbl, [a, b], false, [ - "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n", - "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n", - "if(comp<0){break ", lbl, "}" - ].join("")) - } else { - code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join("")) - } + + var x0 = Math.min(Math.max(x - radius, 0), shape[0])|0 + var x1 = Math.min(Math.max(x + radius, 0), shape[0])|0 + var y0 = Math.min(Math.max(y - radius, 0), shape[1])|0 + var y1 = Math.min(Math.max(y + radius, 0), shape[1])|0 + + if(x1 <= x0 || y1 <= y0) { + return null } - - compareSwap(1, 2) - compareSwap(4, 5) - compareSwap(1, 3) - compareSwap(2, 3) - compareSwap(1, 4) - compareSwap(3, 4) - compareSwap(2, 5) - compareSwap(2, 3) - compareSwap(4, 5) - - if(order.length > 1) { - cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [ - "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n", - "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n", - "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n", - "x=",dataRead("ptr0"),"\n", - "y=",dataRead("ptr2"),"\n", - "z=",dataRead("ptr4"),"\n", - dataWrite("ptr5", "x"),"\n", - dataWrite("ptr6", "y"),"\n", - dataWrite("ptr7", "z") - ].join("")) - } else { - code.push([ - "pivot1=", dataRead(toPointer("el2")), "\n", - "pivot2=", dataRead(toPointer("el4")), "\n", - "pivots_are_equal=pivot1===pivot2\n", - "x=", dataRead(toPointer("el1")), "\n", - "y=", dataRead(toPointer("el3")), "\n", - "z=", dataRead(toPointer("el5")), "\n", - dataWrite(toPointer("index1"), "x"), "\n", - dataWrite(toPointer("index3"), "y"), "\n", - dataWrite(toPointer("index5"), "z") - ].join("")) + + var dims = [x1-x0,y1-y0] + var region = ndarray( + this.buffer, + [dims[0], dims[1], 4], + [4, shape[0]*4, 1], + 4*(x0 + shape[0]*y0)); + + var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius) + var dx = closest[0] + var dy = closest[1] + if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) { + return null } - - function moveElement(dst, src) { - if(order.length > 1) { - cacheLoop([dst, src], false, - dataWrite("ptr0", dataRead("ptr1")) - ) - } else { - code.push(dataWrite(toPointer(dst), dataRead(toPointer(src)))) - } + var c0 = region.get(dx, dy, 0) + var c1 = region.get(dx, dy, 1) + var c2 = region.get(dx, dy, 2) + var c3 = region.get(dx, dy, 3) + + return new SelectResult( + (dx + x0)|0, + (dy + y0)|0, + c0, + [c1, c2, c3], + Math.sqrt(closest[2])) +} + +proto.dispose = function() { + if(!this.gl) { + return } - - moveElement("index2", "left") - moveElement("index4", "right") - - function comparePivot(result, ptr, n) { - if(order.length > 1) { - var lbl = "__l" + (++labelCounter) - lexicoLoop(lbl, [ptr], true, [ - result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n", - "if(",result,"!==0){break ", lbl, "}" - ].join("")) - } else { - code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join("")) - } + this.fbo.dispose() + pool.free(this.buffer) + this.gl = null + if(this._readTimeout) { + clearTimeout(this._readTimeout) } - - function swapElements(a, b) { - if(order.length > 1) { - cacheLoop([a,b],false,[ - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", "tmp") - ].join("")) - } else { - code.push([ - "ptr0=",toPointer(a),"\n", - "ptr1=",toPointer(b),"\n", - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", "tmp") - ].join("")) - } +} + +function createSelectBuffer(gl, shape) { + var fbo = createFBO(gl, shape) + var buffer = pool.mallocUint8(shape[0]*shape[1]*4) + return new SelectBuffer(gl, fbo, buffer) +} + +},{"bit-twiddle":317,"cwise/lib/wrapper":318,"gl-fbo":323,"ndarray":1031,"typedarray-pool":326}],328:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":329,"./lib/create-attributes":330,"./lib/create-uniforms":331,"./lib/reflect":332,"./lib/runtime-reflect":333,"./lib/shader-cache":334,"dup":94}],329:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],330:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":329,"dup":96}],331:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":329,"./reflect":332,"dup":97}],332:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],333:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],334:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":329,"dup":100,"gl-format-compiler-error":335,"weakmap-shim":353}],335:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":336,"dup":101,"gl-constants/lookup":340,"glsl-shader-name":341,"sprintf-js":350}],336:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":337}],337:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":338}],338:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],339:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],340:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":339,"dup":106}],341:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":342,"dup":107,"glsl-tokenizer":349}],342:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],343:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":345,"./lib/builtins-300es":344,"./lib/literals":347,"./lib/literals-300es":346,"./lib/operators":348,"dup":109}],344:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":345,"dup":110}],345:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],346:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":347,"dup":112}],347:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],348:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],349:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":343,"dup":115}],350:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],351:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":352,"dup":117}],352:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],353:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":351,"dup":119}],354:[function(require,module,exports){ +"use strict" + +module.exports = createText + +var vectorizeText = require("./lib/vtext") +var defaultCanvas = null +var defaultContext = null + +if(typeof document !== 'undefined') { + defaultCanvas = document.createElement('canvas') + defaultCanvas.width = 8192 + defaultCanvas.height = 1024 + defaultContext = defaultCanvas.getContext("2d") +} + +function createText(str, options) { + if((typeof options !== "object") || (options === null)) { + options = {} } - - function tripleSwap(k, less, great) { - if(order.length > 1) { - cacheLoop([k,less,great], false, [ - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", dataRead("ptr2")),"\n", - dataWrite("ptr2", "tmp") - ].join("")) - code.push("++"+less, "--"+great) - } else { - code.push([ - "ptr0=",toPointer(k),"\n", - "ptr1=",toPointer(less),"\n", - "ptr2=",toPointer(great),"\n", - "++",less,"\n", - "--",great,"\n", - "tmp=", dataRead("ptr0"), "\n", - dataWrite("ptr0", dataRead("ptr1")), "\n", - dataWrite("ptr1", dataRead("ptr2")), "\n", - dataWrite("ptr2", "tmp") - ].join("")) + return vectorizeText( + str, + options.canvas || defaultCanvas, + options.context || defaultContext, + options) +} + +},{"./lib/vtext":355}],355:[function(require,module,exports){ +"use strict" + +module.exports = vectorizeText +module.exports.processPixels = processPixels + +var surfaceNets = require('surface-nets') +var ndarray = require('ndarray') +var simplify = require('simplify-planar-graph') +var cleanPSLG = require('clean-pslg') +var cdt2d = require('cdt2d') +var toPolygonCrappy = require('planar-graph-to-polyline') + +function transformPositions(positions, options, size) { + var align = options.textAlign || "start" + var baseline = options.textBaseline || "alphabetic" + + var lo = [1<<30, 1<<30] + var hi = [0,0] + var n = positions.length + for(var i=0; i0){") - code.push("great--") - code.push("}else if(comp<0){") - tripleSwap("k", "less", "great") - code.push("break") - code.push("}else{") - swapAndDecrement("k", "great") - code.push("break") - code.push("}") - code.push("}") - code.push("}") - code.push("}") - code.push("}else{") - //Pivots not equal case - code.push("for(k=less;k<=great;++k){") - comparePivot("comp_pivot1", "k", 1) - code.push("if(comp_pivot1<0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - comparePivot("comp_pivot2", "k", 2) - code.push("if(comp_pivot2>0){") - code.push("while(true){") - comparePivot("comp", "great", 2) - code.push("if(comp>0){") - code.push("if(--great1) { - cacheLoop([mem_dest, pivot_dest], true, [ - dataWrite("ptr0", dataRead("ptr1")), "\n", - dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join("")) - ].join("")) - } else { - code.push( - dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))), - dataWrite(toPointer(pivot_dest), "pivot"+pivot)) - } + + var yShift = 0 + switch(baseline) { + case "hanging": + case "top": + yShift = -lo[1] + break + + case "middle": + yShift = -0.5 * (lo[1] + hi[1]) + break + + case "alphabetic": + case "ideographic": + yShift = -3 * size + break + + case "bottom": + yShift = -hi[1] + break + + default: + throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'") } - - storePivot("left", "(less-1)", 1) - storePivot("right", "(great+1)", 2) - //Recursive sort call - function doSort(left, right) { - code.push([ - "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n", - "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", - "}else{\n", - funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", - "}" - ].join("")) + var scale = 1.0 / size + if("lineHeight" in options) { + scale *= +options.lineHeight + } else if("width" in options) { + scale = options.width / (hi[0] - lo[0]) + } else if("height" in options) { + scale = options.height / (hi[1] - lo[1]) } - doSort("left", "(less-2)") - doSort("(great+2)", "right") - - //If pivots are equal, then early out - code.push("if(pivots_are_equal){") - cleanUp() - code.push("return") - code.push("}") - - function walkPointer(ptr, pivot, body) { - if(order.length > 1) { - code.push(["__l",++labelCounter,":while(true){"].join("")) - cacheLoop([ptr], true, [ - "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}" - ].join("")) - code.push(body, "}") - } else { - code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join("")) - } + + return positions.map(function(p) { + return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ] + }) +} + +function getPixels(canvas, context, str, size) { + var width = Math.ceil(context.measureText(str).width + 2*size)|0 + if(width > 8192) { + throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") } - - //Check bounds - code.push("if(lessindex5){") - - walkPointer("less", 1, "++less") - walkPointer("great", 2, "--great") - - code.push("for(k=less;k<=great;++k){") - comparePivot("comp_pivot1", "k", 1) - code.push("if(comp_pivot1===0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - comparePivot("comp_pivot2", "k", 2) - code.push("if(comp_pivot2===0){") - code.push("while(true){") - comparePivot("comp", "great", 2) - code.push("if(comp===0){") - code.push("if(--great 1 && allocator) { - var compiled = new Function("insertionSort", "malloc", "free", code.join("\n")) - return compiled(insertionSort, allocator[0], allocator[1]) + var height = 3 * size + if(canvas.height < height) { + canvas.height = height + } + + context.fillStyle = "#000" + context.fillRect(0, 0, canvas.width, canvas.height) + + context.fillStyle = "#fff" + context.fillText(str, size, 2*size) + + //Cut pixels from image + var pixelData = context.getImageData(0, 0, width, height) + var pixels = ndarray(pixelData.data, [height, width, 4]) + + return pixels.pick(-1,-1,0).transpose(1,0) +} + +function getContour(pixels, doSimplify) { + var contour = surfaceNets(pixels, 128) + if(doSimplify) { + return simplify(contour.cells, contour.positions, 0.25) + } + return { + edges: contour.cells, + positions: contour.positions + } +} + +function processPixelsImpl(pixels, options, size, simplify) { + //Extract contour + var contour = getContour(pixels, simplify) + + //Apply warp to positions + var positions = transformPositions(contour.positions, options, size) + var edges = contour.edges + var flip = "ccw" === options.orientation + + //Clean up the PSLG, resolve self intersections, etc. + cleanPSLG(positions, edges) + + //If triangulate flag passed, triangulate the result + if(options.polygons || options.polygon || options.polyline) { + var result = toPolygonCrappy(edges, positions) + var nresult = new Array(result.length) + for(var i=0; i 0) { - vars.push(["d",j,"=s",j,"-d",p,"*n",p].join("")) - } else { - vars.push(["d",j,"=s",j].join("")) - } - p = j - } - var k = order.length-1-i - if(k !== 0) { - if(q > 0) { - vars.push(["e",k,"=s",k,"-e",q,"*n",q, - ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join("")) - } else { - vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join("")) - } - q = k - } + return { + edges: [], + positions: [] } - - //Declare local variables - code.push("var " + vars.join(",")) - - //Create arguments for subroutine - var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length)) - - //Call main sorting routine - code.push([ - "if(n0<=",INSERTION_SORT_THRESHOLD,"){", - "insertionSort(", sortArgs.join(","), ")}else{", - "quickSort(", sortArgs.join(","), - ")}" - ].join("")) - - //Return - code.push("}return " + funcName) - - //Link everything together - var result = new Function("insertionSort", "quickSort", code.join("\n")) - var insertionSort = createInsertionSort(order, dtype) - var quickSort = createQuickSort(order, dtype, insertionSort) - return result(insertionSort, quickSort) } -module.exports = compileSort -},{"typedarray-pool":278}],158:[function(require,module,exports){ -"use strict" +function vectorizeText(str, canvas, context, options) { + var size = options.size || 64 + var family = options.font || "normal" -var compile = require("./lib/compile_sort.js") -var CACHE = {} + context.font = size + "px " + family + context.textAlign = "start" + context.textBaseline = "alphabetic" + context.direction = "ltr" -function sort(array) { - var order = array.order - var dtype = array.dtype - var typeSig = [order, dtype ] - var typeName = typeSig.join(":") - var compiled = CACHE[typeName] - if(!compiled) { - CACHE[typeName] = compiled = compile(order, dtype) - } - compiled(array) - return array + var pixels = getPixels(canvas, context, str, size) + + return processPixels(pixels, options, size) } -module.exports = sort -},{"./lib/compile_sort.js":157}],159:[function(require,module,exports){ +},{"cdt2d":356,"clean-pslg":367,"ndarray":1031,"planar-graph-to-polyline":424,"simplify-planar-graph":428,"surface-nets":450}],356:[function(require,module,exports){ 'use strict' -module.exports = createBoxes +var monotoneTriangulate = require('./lib/monotone') +var makeIndex = require('./lib/triangulation') +var delaunayFlip = require('./lib/delaunay') +var filterTriangulation = require('./lib/filter') -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') +module.exports = cdt2d -var shaders = require('./shaders') +function canonicalizeEdge(e) { + return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] +} -function Boxes(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader +function compareEdge(a, b) { + return a[0]-b[0] || a[1]-b[1] } -var proto = Boxes.prototype +function canonicalizeEdges(edges) { + return edges.map(canonicalizeEdge).sort(compareEdge) +} -proto.bind = function() { - var shader = this.shader - this.vbo.bind() - this.shader.bind() - shader.attributes.coord.pointer() - shader.uniforms.screenBox = this.plot.screenBox +function getDefault(options, property, dflt) { + if(property in options) { + return options[property] + } + return dflt } -proto.drawBox = (function() { - var lo = [0,0] - var hi = [0,0] - return function(loX, loY, hiX, hiY, color) { - var plot = this.plot - var shader = this.shader - var gl = plot.gl +function cdt2d(points, edges, options) { - lo[0] = loX - lo[1] = loY - hi[0] = hiX - hi[1] = hiY + if(!Array.isArray(edges)) { + options = edges || {} + edges = [] + } else { + options = options || {} + edges = edges || [] + } - shader.uniforms.lo = lo - shader.uniforms.hi = hi - shader.uniforms.color = color + //Parse out options + var delaunay = !!getDefault(options, 'delaunay', true) + var interior = !!getDefault(options, 'interior', true) + var exterior = !!getDefault(options, 'exterior', true) + var infinity = !!getDefault(options, 'infinity', false) - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) + //Handle trivial case + if((!interior && !exterior) || points.length === 0) { + return [] } -}()) -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() -} + //Construct initial triangulation + var cells = monotoneTriangulate(points, edges) -function createBoxes(plot) { - var gl = plot.gl - var vbo = createBuffer(gl, [ - 0,0, - 0,1, - 1,0, - 1,1]) - var shader = createShader(gl, shaders.boxVert, shaders.lineFrag) - return new Boxes(plot, vbo, shader) + //If delaunay refinement needed, then improve quality by edge flipping + if(delaunay || interior !== exterior || infinity) { + + //Index all of the cells to support fast neighborhood queries + var triangulation = makeIndex(points.length, canonicalizeEdges(edges)) + for(var i=0; i 0) { + var b = stack.pop() + var a = stack.pop() - for(var i=0; i<2; ++i) { - var lo = bounds[i] - var hi = bounds[i+2] - var boundScale = hi - lo - var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) - var dataWidth = (dataBox[i+2] - dataBox[i]) - DATA_SCALE[i] = 2.0 * boundScale / dataWidth - DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth + //Find opposite pairs + var x = -1, y = -1 + var star = stars[a] + for(var i=1; i= 0) { + continue + } - shader.bind() - vbo.bind() + //Flip the edge + triangulation.flip(a, b) - shader.attributes.dataCoord.pointer() + //Test flipping neighboring edges + testFlip(points, triangulation, stack, x, a, y) + testFlip(points, triangulation, stack, a, y, x) + testFlip(points, triangulation, stack, y, b, x) + testFlip(points, triangulation, stack, b, x, y) + } +} - var uniforms = shader.uniforms - uniforms.dataShift = DATA_SHIFT - uniforms.dataScale = DATA_SCALE +},{"binary-search-bounds":312,"robust-in-sphere":361}],358:[function(require,module,exports){ +'use strict' - var tickMarkLength = plot.tickMarkLength - var tickMarkWidth = plot.tickMarkWidth - var tickMarkColor = plot.tickMarkColor +var bsearch = require('binary-search-bounds') - var xTicksOffset = 0 - var yTicksOffset = ticks[0].length * 6 +module.exports = classifyFaces - var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xEnd = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xOffset = xTicksOffset + 6 * xStart - var xCount = 6 * Math.max(0, xEnd - xStart) +function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) { + this.cells = cells + this.neighbor = neighbor + this.flags = flags + this.constraint = constraint + this.active = active + this.next = next + this.boundary = boundary +} - var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yEnd = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yOffset = yTicksOffset + 6 * yStart - var yCount = 6 * Math.max(0, yEnd - yStart) +var proto = FaceIndex.prototype - SCR_OFFSET[0] = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0 - SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkLength[1] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkWidth[1] * pixelRatio / screenHeight +function compareCell(a, b) { + return a[0] - b[0] || + a[1] - b[1] || + a[2] - b[2] +} - if(yCount) { - uniforms.color = tickMarkColor[1] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = Y_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, yOffset, yCount) +proto.locate = (function() { + var key = [0,0,0] + return function(a, b, c) { + var x = a, y = b, z = c + if(b < c) { + if(b < a) { + x = b + y = c + z = a + } + } else if(c < a) { + x = c + y = a + z = b } + if(x < 0) { + return -1 + } + key[0] = x + key[1] = y + key[2] = z + return bsearch.eq(this.cells, key, compareCell) + } +})() - SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 - SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight - - if(xCount) { - uniforms.color = tickMarkColor[0] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = X_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, xOffset, xCount) +function indexCells(triangulation, infinity) { + //First get cells and canonicalize + var cells = triangulation.cells() + var nc = cells.length + for(var i=0; i 0 || next.length > 0) { + while(active.length > 0) { + var t = active.pop() + if(flags[t] === -side) { + continue + } + flags[t] = side + var c = cells[t] + for(var j=0; j<3; ++j) { + var f = neighbor[3*t+j] + if(f >= 0 && flags[f] === 0) { + if(constraint[3*t+j]) { + next.push(f) + } else { + active.push(f) + flags[f] = side + } } } } - this.ticks = gridTicks - this.vbo.update(data) + //Swap arrays and loop + var tmp = next + next = active + active = tmp + next.length = 0 + side = -side } -})() - -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() - this.tickShader.dispose() -} -function createGrid(plot) { - var gl = plot.gl - var vbo = createBuffer(gl) - var shader = createShader(gl, shaders.gridVert, shaders.gridFrag) - var tickShader = createShader(gl, shaders.tickVert, shaders.gridFrag) - var grid = new Grid(plot, vbo, shader, tickShader) - return grid + var result = filterCells(cells, flags, target) + if(infinity) { + return result.concat(index.boundary) + } + return result } -},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197}],161:[function(require,module,exports){ +},{"binary-search-bounds":312}],359:[function(require,module,exports){ 'use strict' -module.exports = createLines +var bsearch = require('binary-search-bounds') +var orient = require('robust-orientation')[3] -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') +var EVENT_POINT = 0 +var EVENT_END = 1 +var EVENT_START = 2 -var shaders = require('./shaders') +module.exports = monotoneTriangulate -function Lines(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader +//A partial convex hull fragment, made of two unimonotone polygons +function PartialHull(a, b, idx, lowerIds, upperIds) { + this.a = a + this.b = b + this.idx = idx + this.lowerIds = lowerIds + this.upperIds = upperIds } -var proto = Lines.prototype - -proto.bind = function() { - var shader = this.shader - this.vbo.bind() - this.shader.bind() - shader.attributes.coord.pointer() - shader.uniforms.screenBox = this.plot.screenBox +//An event in the sweep line procedure +function Event(a, b, type, idx) { + this.a = a + this.b = b + this.type = type + this.idx = idx } -proto.drawLine = (function() { - var start = [0,0] - var end = [0,0] - return function(startX, startY, endX, endY, width, color) { - var plot = this.plot - var shader = this.shader - var gl = plot.gl - - start[0] = startX - start[1] = startY - end[0] = endX - end[1] = endY - - shader.uniforms.start = start - shader.uniforms.end = end - shader.uniforms.width = width * plot.pixelRatio - shader.uniforms.color = color - - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) +//This is used to compare events for the sweep line procedure +// Points are: +// 1. sorted lexicographically +// 2. sorted by type (point < end < start) +// 3. segments sorted by winding order +// 4. sorted by index +function compareEvent(a, b) { + var d = + (a.a[0] - b.a[0]) || + (a.a[1] - b.a[1]) || + (a.type - b.type) + if(d) { return d } + if(a.type !== EVENT_POINT) { + d = orient(a.a, a.b, b.b) + if(d) { return d } } -}()) - -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() + return a.idx - b.idx } -function createLines(plot) { - var gl = plot.gl - var vbo = createBuffer(gl, [ - -1,-1, - -1,1, - 1,-1, - 1,1]) - var shader = createShader(gl, shaders.lineVert, shaders.lineFrag) - var lines = new Lines(plot, vbo, shader) - return lines +function testPoint(hull, p) { + return orient(hull.a, hull.b, p) } -},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],162:[function(require,module,exports){ -'use strict' - - +function addPoint(cells, hulls, points, p, idx) { + var lo = bsearch.lt(hulls, p, testPoint) + var hi = bsearch.gt(hulls, p, testPoint) + for(var i=lo; i 1 && orient( + points[lowerIds[m-2]], + points[lowerIds[m-1]], + p) > 0) { + cells.push( + [lowerIds[m-1], + lowerIds[m-2], + idx]) + m -= 1 + } + lowerIds.length = m + lowerIds.push(idx) -module.exports = { - lineVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n", - lineFrag: FRAGMENT, - textVert: "#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n", - textFrag: FRAGMENT, - gridVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n", - gridFrag: FRAGMENT, - boxVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n", - tickVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n" + //Insert p into upper hull + var upperIds = hull.upperIds + var m = upperIds.length + while(m > 1 && orient( + points[upperIds[m-2]], + points[upperIds[m-1]], + p) < 0) { + cells.push( + [upperIds[m-2], + upperIds[m-1], + idx]) + m -= 1 + } + upperIds.length = m + upperIds.push(idx) + } } -},{}],163:[function(require,module,exports){ -'use strict' - -module.exports = createTextElements - -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') -var getText = require('text-cache') -var bsearch = require('binary-search-bounds') -var shaders = require('./shaders') - -function TextElements(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader - this.tickOffset = [[],[]] - this.tickX = [[],[]] - this.labelOffset = [0,0] - this.labelCount = [0,0] +function findSplit(hull, edge) { + var d + if(hull.a[0] < edge.a[0]) { + d = orient(hull.a, hull.b, edge.a) + } else { + d = orient(edge.b, edge.a, hull.a) + } + if(d) { return d } + if(edge.b[0] < hull.b[0]) { + d = orient(hull.a, hull.b, edge.b) + } else { + d = orient(edge.b, edge.a, hull.b) + } + return d || hull.idx - edge.idx } -var proto = TextElements.prototype - -proto.drawTicks = (function() { - var DATA_AXIS = [0,0] - var SCREEN_OFFSET = [0,0] - var ZERO_2 = [0,0] +function splitHulls(hulls, points, event) { + var splitIdx = bsearch.le(hulls, event, findSplit) + var hull = hulls[splitIdx] + var upperIds = hull.upperIds + var x = upperIds[upperIds.length-1] + hull.upperIds = [x] + hulls.splice(splitIdx+1, 0, + new PartialHull(event.a, event.b, event.idx, [x], upperIds)) +} - return function(axis) { - var plot = this.plot - var shader = this.shader - var tickX = this.tickX[axis] - var tickOffset = this.tickOffset[axis] - var gl = plot.gl - var viewBox = plot.viewBox - var dataBox = plot.dataBox - var screenBox = plot.screenBox - var pixelRatio = plot.pixelRatio - var tickEnable = plot.tickEnable - var tickPad = plot.tickPad - var textColor = plot.tickColor - var textAngle = plot.tickAngle - var tickLength = plot.tickMarkLength - var labelEnable = plot.labelEnable - var labelPad = plot.labelPad - var labelColor = plot.labelColor - var labelAngle = plot.labelAngle - var labelOffset = this.labelOffset[axis] - var labelCount = this.labelCount[axis] +function mergeHulls(hulls, points, event) { + //Swap pointers for merge search + var tmp = event.a + event.a = event.b + event.b = tmp + var mergeIdx = bsearch.eq(hulls, event, findSplit) + var upper = hulls[mergeIdx] + var lower = hulls[mergeIdx-1] + lower.upperIds = upper.upperIds + hulls.splice(mergeIdx, 1) +} - var start = bsearch.lt(tickX, dataBox[axis]) - var end = bsearch.le(tickX, dataBox[axis+2]) - DATA_AXIS[0] = DATA_AXIS[1] = 0 - DATA_AXIS[axis] = 1 +function monotoneTriangulate(points, edges) { - SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0 + var numPoints = points.length + var numEdges = edges.length - var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1] + var events = [] - SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0 - if(tickEnable[axis]) { - SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis] - if(start < end && tickOffset[end] > tickOffset[start]) { - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = textColor[axis] - shader.uniforms.angle = textAngle[axis] - gl.drawArrays( - gl.TRIANGLES, - tickOffset[start], - tickOffset[end] - tickOffset[start]) - } - } - if(labelEnable[axis] && labelCount) { - SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis] - shader.uniforms.dataAxis = ZERO_2 - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = labelColor[axis] - shader.uniforms.angle = labelAngle[axis] - gl.drawArrays( - gl.TRIANGLES, - labelOffset, - labelCount) - } + //Create point events + for(var i=0; i tickOffset[start]) { - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = textColor[axis+2] - shader.uniforms.angle = textAngle[axis+2] - gl.drawArrays( - gl.TRIANGLES, - tickOffset[start], - tickOffset[end] - tickOffset[start]) - } - } - if(labelEnable[axis+2] && labelCount) { - SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2] - shader.uniforms.dataAxis = ZERO_2 - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = labelColor[axis+2] - shader.uniforms.angle = labelAngle[axis+2] - gl.drawArrays( - gl.TRIANGLES, - labelOffset, - labelCount) + //Create edge events + for(var i=0; i b[0]) { + events.push( + new Event(b, a, EVENT_START, i), + new Event(a, b, EVENT_END, i)) } - } -})() - -proto.drawTitle = (function() { - var DATA_AXIS = [0,0] - var SCREEN_OFFSET = [0,0] - return function() { - var plot = this.plot - var shader = this.shader - var gl = plot.gl - var screenBox = plot.screenBox - var titleCenter = plot.titleCenter - var titleAngle = plot.titleAngle - var titleColor = plot.titleColor - var titleCenter = plot.titleCenter - var pixelRatio = plot.pixelRatio + //Sort events + events.sort(compareEvent) - if(!this.titleCount) { - return - } + //Initialize hull + var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52) + var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ] - for(var i=0; i<2; ++i) { - SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) / - (screenBox[2+i] - screenBox[i]) - 1 + //Process events in order + var cells = [] + for(var i=0, numEvents=events.length; i= 0 } })() -proto.update = function(options) { - var vertices = [] - var axesTicks = options.ticks - var bounds = options.bounds +proto.removeTriangle = function(i, j, k) { + var stars = this.stars + removePair(stars[i], j, k) + removePair(stars[j], k, i) + removePair(stars[k], i, j) +} - for(var dimension=0; dimension<2; ++dimension) { - var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity] +proto.addTriangle = function(i, j, k) { + var stars = this.stars + stars[i].push(j, k) + stars[j].push(k, i) + stars[k].push(i, j) +} - //Copy vertices over to buffer - var ticks = axesTicks[dimension] - for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") + } } -},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197,"text-cache":273}],164:[function(require,module,exports){ -arguments[4][62][0].apply(exports,arguments) -},{"dup":62}],165:[function(require,module,exports){ -'use strict' +function makeProduct(a, b) { + if(a.charAt(0) === "m") { + if(b.charAt(0) === "w") { + var toks = a.split("[") + return ["w", b.substr(1), "m", toks[0].substr(1)].join("") + } else { + return ["prod(", a, ",", b, ")"].join("") + } + } else { + return makeProduct(b, a) + } +} -module.exports = createGLPlot2D +function sign(s) { + if(s & 1 !== 0) { + return "-" + } + return "" +} -var createPick = require('gl-select-static') +function determinant(m) { + if(m.length === 2) { + return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] + } else { + var expr = [] + for(var i=0; i= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } + } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } + } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + } + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g +} +},{}],365:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],366:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56}],367:[function(require,module,exports){ +'use strict' - //Drawing parameters - this.grid = null - this.text = null - this.line = null - this.box = null - this.objects = [] - this.overlays = [] +module.exports = cleanPSLG - this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] +var UnionFind = require('union-find') +var boxIntersect = require('box-intersect') +var compareCell = require('compare-cell') +var segseg = require('robust-segment-intersect') +var rat = require('big-rat') +var ratCmp = require('big-rat/cmp') +var ratToFloat = require('big-rat/to-float') +var ratVec = require('rat-vec') +var nextafter = require('nextafter') - this.dirty = false - this.pickDirty = false - this.pickDelay = 120 - this.pickRadius = 10 - this._pickTimeout = null - this._drawPick = this.drawPick.bind(this) +var solveIntersection = require('./lib/rat-seg-intersect') - this._depthCounter = 0 +//Bounds on a rational number when rounded to a float +function boundRat(r) { + var f = ratToFloat(r) + var cmp = ratCmp(rat(f), r) + if(cmp < 0) { + return [f, nextafter(f, Infinity)] + } else if(cmp > 0) { + return [nextafter(f, -Infinity), f] + } else { + return [f, f] + } } -var proto = GLPlot2D.prototype - -proto.setDirty = function() { - this.dirty = this.pickDirty = true +//Convert a list of edges in a pslg to bounding boxes +function boundEdges(points, edges) { + var bounds = new Array(edges.length) + for(var i=0; i= floatPoints.length) { + return ratPoints[idx-floatPoints.length] + } + var p = floatPoints[idx] + return [ rat(p[0]), rat(p[1]) ] } - this.dirty = false + junctions.sort(function(a, b) { + if(a[0] !== b[0]) { + return a[0] - b[0] + } + var u = getPoint(a[1]) + var v = getPoint(b[1]) + return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1]) + }) - gl.bindFramebuffer(gl.FRAMEBUFFER, null) + //Split edges along junctions + for(var i=junctions.length-1; i>=0; --i) { + var junction = junctions[i] + var e = junction[0] - //Turn on scissor - gl.enable(gl.SCISSOR_TEST) + var edge = edges[e] + var s = edge[0] + var t = edge[1] - //Turn off depth buffer - gl.disable(gl.DEPTH_TEST) - gl.depthFunc(gl.LESS) - gl.depthMask(false) + //Check if edge is not lexicographically sorted + var a = floatPoints[s] + var b = floatPoints[t] + if(((a[0] - b[0]) || (a[1] - b[1])) < 0) { + var tmp = s + s = t + t = tmp + } - //Configure premultiplied alpha blending - gl.enable(gl.BLEND) - gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + //Split leading edge + edge[0] = s + var last = edge[1] = junction[1] - //Draw border - gl.scissor( - screenBox[0], - screenBox[1], - screenBox[2]-screenBox[0], - screenBox[3]-screenBox[1]) - var borderColor = this.borderColor - gl.clearColor( - borderColor[0]*borderColor[3], - borderColor[1]*borderColor[3], - borderColor[2]*borderColor[3], - borderColor[3]) - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) + //If we are grouping edges by color, remember to track data + var color + if(useColor) { + color = edge[2] + } - //Draw center pane - gl.scissor( - viewPixels[0], - viewPixels[1], - viewPixels[2]-viewPixels[0], - viewPixels[3]-viewPixels[1]) - gl.viewport( - viewPixels[0], - viewPixels[1], - viewPixels[2]-viewPixels[0], - viewPixels[3]-viewPixels[1]) - var backgroundColor = this.backgroundColor - gl.clearColor( - backgroundColor[0]*backgroundColor[3], - backgroundColor[1]*backgroundColor[3], - backgroundColor[2]*backgroundColor[3], - backgroundColor[3]) - gl.clear(gl.COLOR_BUFFER_BIT) + //Split other edges + while(i > 0 && junctions[i-1][0] === e) { + var junction = junctions[--i] + var next = junction[1] + if(useColor) { + edges.push([last, next, color]) + } else { + edges.push([last, next]) + } + last = next + } - //Draw grid - grid.draw() + //Add final edge + if(useColor) { + edges.push([last, t, color]) + } else { + edges.push([last, t]) + } + } - //Draw zero lines separately - var zeroLineEnable = this.zeroLineEnable - var zeroLineColor = this.zeroLineColor - var zeroLineWidth = this.zeroLineWidth - if(zeroLineEnable[0] || zeroLineEnable[1]) { - line.bind() - for(var i=0; i<2; ++i) { - if(!zeroLineEnable[i] || - !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) { - continue - } + //Return constructed rational points + return ratPoints +} - var zeroIntercept = screenBox[i] - - dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) +//Merge overlapping points +function dedupPoints(floatPoints, ratPoints, floatBounds) { + var numPoints = floatPoints.length + ratPoints.length + var uf = new UnionFind(numPoints) - if(i === 0) { - line.drawLine( - zeroIntercept, screenBox[1], zeroIntercept, screenBox[3], - zeroLineWidth[i], - zeroLineColor[i]) - } else { - line.drawLine( - screenBox[0], zeroIntercept, screenBox[2], zeroIntercept, - zeroLineWidth[i], - zeroLineColor[i]) - } - } + //Compute rational bounds + var bounds = floatBounds + for(var i=0; i b[2]) { + return 1 } - if(borderLineEnable[3]) { - line.drawLine( - viewPixels[2], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio, - viewPixels[2], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio, - borderLineWidth[3], borderLineColor[3]) + return 0 +} + +//Remove duplicate edge labels +function dedupEdges(edges, labels, useColor) { + if(edges.length === 0) { + return } - if(borderLineEnable[2]) { - line.drawLine( - viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[3], - viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[3], - borderLineWidth[2], borderLineColor[2]) + if(labels) { + for(var i=0; i 0 || tjunctions.length > 0) } - pickBuffer.end() + // More iterations necessary + return true } -})() - -proto.pick = (function() { -return function(x, y) { - var pixelRatio = this.pixelRatio - var pickPixelRatio = this.pickPixelRatio - var viewBox = this.viewBox - var scrX = Math.round((x - viewBox[0] / pixelRatio) * pickPixelRatio)|0 - var scrY = Math.round((y - viewBox[1] / pixelRatio) * pickPixelRatio)|0 +//Main loop, runs PSLG clean up until completion +function cleanPSLG(points, edges, colors) { + var modified = false - var pickResult = this.pickBuffer.query(scrX, scrY, this.pickRadius) - if(!pickResult) { - return null + //If using colors, augment edges with color data + var prevEdges + if(colors) { + prevEdges = edges + var augEdges = new Array(edges.length) + for(var i=0; i=0; --i) { - this.objects[i].dispose() + var shift = 0 + var a, b + if(isBN(numer)) { + a = numer.clone() + } else if(typeof numer === 'string') { + a = str2bn(numer) + } else if(numer === 0) { + return [num2bn(0), num2bn(1)] + } else if(numer === Math.floor(numer)) { + a = num2bn(numer) + } else { + while(numer !== Math.floor(numer)) { + numer = numer * Math.pow(2, 256) + shift -= 256 + } + a = num2bn(numer) } - this.objects.length = 0 - for(var i=this.overlays.length-1; i>=0; --i) { - this.overlays[i].dispose() + if(isRat(denom)) { + a.mul(denom[1]) + b = denom[0].clone() + } else if(isBN(denom)) { + b = denom.clone() + } else if(typeof denom === 'string') { + b = str2bn(denom) + } else if(!denom) { + b = num2bn(1) + } else if(denom === Math.floor(denom)) { + b = num2bn(denom) + } else { + while(denom !== Math.floor(denom)) { + denom = denom * Math.pow(2, 256) + shift += 256 + } + b = num2bn(denom) } - this.overlays.length = 0 - - this.gl = null -} - -proto.addObject = function(object) { - if(this.objects.indexOf(object) < 0) { - this.objects.push(object) - this.setDirty() + if(shift > 0) { + a = a.shln(shift) + } else if(shift < 0) { + b = b.shln(-shift) } + return rationalize(a, b) } -proto.removeObject = function(object) { - var objects = this.objects - for(var i=0; i 20) { + return 52 } + return h + 32 +} - var view = createView({ - center: options.center || [0,0,0], - up: options.up || [0,1,0], - eye: options.eye || [0,0,10], - mode: options.mode || 'orbit', - distanceLimits: limits - }) +},{"bit-twiddle":382,"double-bits":384}],377:[function(require,module,exports){ +'use strict' - var pmatrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] - var distance = 0.0 - var width = element.clientWidth - var height = element.clientHeight +var BN = require('bn.js') - var camera = { - view: view, - element: element, - delay: options.delay || 16, - rotateSpeed: options.rotateSpeed || 1, - zoomSpeed: options.zoomSpeed || 1, - translateSpeed: options.translateSpeed || 1, - flipX: !!options.flipX, - flipY: !!options.flipY, - modes: view.modes, - tick: function() { - var t = now() - var delay = this.delay - view.idle(t-delay) - view.flush(t-(100+delay*2)) - var ctime = t - 2 * delay - view.recalcMatrix(ctime) - var allEqual = true - var matrix = view.computedMatrix - for(var i=0; i<16; ++i) { - allEqual = allEqual && (pmatrix[i] === matrix[i]) - pmatrix[i] = matrix[i] - } - var sizeChanged = - element.clientWidth === width && - element.clientHeight === height - width = element.clientWidth - height = element.clientHeight - if(allEqual) { - return !sizeChanged - } - distance = Math.exp(view.computedRadius[0]) - return true - }, - lookAt: function(center, eye, up) { - view.lookAt(view.lastT(), center, eye, up) - }, - rotate: function(pitch, yaw, roll) { - view.rotate(view.lastT(), pitch, yaw, roll) - }, - pan: function(dx, dy, dz) { - view.pan(view.lastT(), dx, dy, dz) - }, - translate: function(dx, dy, dz) { - view.translate(view.lastT(), dx, dy, dz) - } - } +module.exports = isBN - Object.defineProperties(camera, { - matrix: { - get: function() { - return view.computedMatrix - }, - set: function(mat) { - view.setMatrix(view.lastT(), mat) - return view.computedMatrix - }, - enumerable: true - }, - mode: { - get: function() { - return view.getMode() - }, - set: function(mode) { - view.setMode(mode) - return view.getMode() - }, - enumerable: true - }, - center: { - get: function() { - return view.computedCenter - }, - set: function(ncenter) { - view.lookAt(view.lastT(), ncenter) - return view.computedCenter - }, - enumerable: true - }, - eye: { - get: function() { - return view.computedEye - }, - set: function(neye) { - view.lookAt(view.lastT(), null, neye) - return view.computedEye - }, - enumerable: true - }, - up: { - get: function() { - return view.computedUp - }, - set: function(nup) { - view.lookAt(view.lastT(), null, null, nup) - return view.computedUp - }, - enumerable: true - }, - distance: { - get: function() { - return distance - }, - set: function(d) { - view.setDistance(view.lastT(), d) - return d - }, - enumerable: true - }, - distanceLimits: { - get: function() { - return view.getDistanceLimits(limits) - }, - set: function(v) { - view.setDistanceLimits(v) - return v - }, - enumerable: true - } - }) - - element.addEventListener('contextmenu', function(ev) { - ev.preventDefault() - return false - }) +//Test if x is a bignumber +//FIXME: obviously this is the wrong way to do it +function isBN(x) { + return x && typeof x === 'object' && Boolean(x.words) +} - var lastX = 0, lastY = 0 - mouseChange(element, function(buttons, x, y, mods) { - var scale = 1.0 / element.clientHeight - var dx = scale * (x - lastX) - var dy = scale * (y - lastY) +},{"bn.js":383}],378:[function(require,module,exports){ +'use strict' - var flipX = camera.flipX ? 1 : -1 - var flipY = camera.flipY ? 1 : -1 +var BN = require('bn.js') +var db = require('double-bits') - var drot = Math.PI * camera.rotateSpeed +module.exports = num2bn - var t = now() +function num2bn(x) { + var e = db.exponent(x) + if(e < 52) { + return new BN(x) + } else { + return (new BN(x * Math.pow(2, 52-e))).shln(e-52) + } +} - if(buttons & 1) { - if(mods.shift) { - view.rotate(t, 0, 0, -dx * drot) - } else { - view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0) - } - } else if(buttons & 2) { - view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0) - } else if(buttons & 4) { - var kzoom = camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 50.0 - view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) - } +},{"bn.js":383,"double-bits":384}],379:[function(require,module,exports){ +'use strict' - lastX = x - lastY = y - }) +var num2bn = require('./num-to-bn') +var sign = require('./bn-sign') - mouseWheel(element, function(dx, dy, dz) { - var flipX = camera.flipX ? 1 : -1 - var flipY = camera.flipY ? 1 : -1 - var t = now() - if(Math.abs(dx) > Math.abs(dy)) { - view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) - } else { - var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0 - view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) - } - }, true) +module.exports = rationalize - return camera +function rationalize(numer, denom) { + var snumer = sign(numer) + var sdenom = sign(denom) + if(snumer === 0) { + return [num2bn(0), num2bn(1)] + } + if(sdenom === 0) { + return [num2bn(0), num2bn(0)] + } + if(sdenom < 0) { + numer = numer.neg() + denom = denom.neg() + } + var d = numer.gcd(denom) + if(d.cmpn(1)) { + return [ numer.div(d), denom.div(d) ] + } + return [ numer, denom ] } -},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],168:[function(require,module,exports){ -// Copyright (C) 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/** - * @fileoverview Install a leaky WeakMap emulation on platforms that - * don't provide a built-in one. - * - *

Assumes that an ES5 platform where, if {@code WeakMap} is - * already present, then it conforms to the anticipated ES6 - * specification. To run this file on an ES5 or almost ES5 - * implementation where the {@code WeakMap} specification does not - * quite conform, run repairES5.js first. - * - *

Even though WeakMapModule is not global, the linter thinks it - * is, which is why it is in the overrides list below. - * - *

NOTE: Before using this WeakMap emulation in a non-SES - * environment, see the note below about hiddenRecord. - * - * @author Mark S. Miller - * @requires crypto, ArrayBuffer, Uint8Array, navigator, console - * @overrides WeakMap, ses, Proxy - * @overrides WeakMapModule - */ +},{"./bn-sign":374,"./num-to-bn":378}],380:[function(require,module,exports){ +'use strict' -/** - * This {@code WeakMap} emulation is observably equivalent to the - * ES-Harmony WeakMap, but with leakier garbage collection properties. - * - *

As with true WeakMaps, in this emulation, a key does not - * retain maps indexed by that key and (crucially) a map does not - * retain the keys it indexes. A map by itself also does not retain - * the values associated with that map. - * - *

However, the values associated with a key in some map are - * retained so long as that key is retained and those associations are - * not overridden. For example, when used to support membranes, all - * values exported from a given membrane will live for the lifetime - * they would have had in the absence of an interposed membrane. Even - * when the membrane is revoked, all objects that would have been - * reachable in the absence of revocation will still be reachable, as - * far as the GC can tell, even though they will no longer be relevant - * to ongoing computation. - * - *

The API implemented here is approximately the API as implemented - * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, - * rather than the offially approved proposal page. TODO(erights): - * upgrade the ecmascript WeakMap proposal page to explain this API - * change and present to EcmaScript committee for their approval. - * - *

The first difference between the emulation here and that in - * FF6.0a1 is the presence of non enumerable {@code get___, has___, - * set___, and delete___} methods on WeakMap instances to represent - * what would be the hidden internal properties of a primitive - * implementation. Whereas the FF6.0a1 WeakMap.prototype methods - * require their {@code this} to be a genuine WeakMap instance (i.e., - * an object of {@code [[Class]]} "WeakMap}), since there is nothing - * unforgeable about the pseudo-internal method names used here, - * nothing prevents these emulated prototype methods from being - * applied to non-WeakMaps with pseudo-internal methods of the same - * names. - * - *

Another difference is that our emulated {@code - * WeakMap.prototype} is not itself a WeakMap. A problem with the - * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap - * providing ambient mutability and an ambient communications - * channel. Thus, if a WeakMap is already present and has this - * problem, repairES5.js wraps it in a safe wrappper in order to - * prevent access to this channel. (See - * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). - */ +var BN = require('bn.js') -/** - * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is - * absent, install an approximate emulation. - * - *

If WeakMap is present but cannot store some objects, use our approximate - * emulation as a wrapper. - * - *

If this is almost a secureable ES5 platform, then WeakMap.js - * should be run after repairES5.js. - * - *

See {@code WeakMap} for documentation of the garbage collection - * properties of this WeakMap emulation. - */ -(function WeakMapModule() { - "use strict"; +module.exports = str2BN - if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { - // already too broken, so give up - return; +function str2BN(x) { + return new BN(x) +} + +},{"bn.js":383}],381:[function(require,module,exports){ +'use strict' + +var rationalize = require('./lib/rationalize') + +module.exports = mul + +function mul(a, b) { + return rationalize(a[0].mul(b[0]), a[1].mul(b[1])) +} + +},{"./lib/rationalize":379}],382:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],383:[function(require,module,exports){ +(function (module, exports) { + +'use strict'; + +// Utils + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +// Could use `inherits` module, but don't want to move from single file +// architecture yet. +function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; +} + +// BN + +function BN(number, base, endian) { + // May be `new BN(bn)` ? + if (number !== null && + typeof number === 'object' && + Array.isArray(number.words)) { + return number; } - /** - * In some cases (current Firefox), we must make a choice betweeen a - * WeakMap which is capable of using all varieties of host objects as - * keys and one which is capable of safely using proxies as keys. See - * comments below about HostWeakMap and DoubleWeakMap for details. - * - * This function (which is a global, not exposed to guests) marks a - * WeakMap as permitted to do what is necessary to index all host - * objects, at the cost of making it unsafe for proxies. - * - * Do not apply this function to anything which is not a genuine - * fresh WeakMap. - */ - function weakMapPermitHostObjects(map) { - // identity of function used as a secret -- good enough and cheap - if (map.permitHostObjects___) { - map.permitHostObjects___(weakMapPermitHostObjects); - } + this.sign = false; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (base === 'le' || base === 'be') { + endian = base; + base = 10; } - if (typeof ses !== 'undefined') { - ses.weakMapPermitHostObjects = weakMapPermitHostObjects; + + if (number !== null) + this._init(number || 0, base || 10, endian || 'be'); +} +if (typeof module === 'object') + module.exports = BN; +else + exports.BN = BN; + +BN.BN = BN; +BN.wordSize = 26; + +BN.prototype._init = function init(number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } else if (typeof number === 'object') { + return this._initArray(number, base, endian); } + if (base === 'hex') + base = 16; + assert(base === (base | 0) && base >= 2 && base <= 36); - // IE 11 has no Proxy but has a broken WeakMap such that we need to patch - // it using DoubleWeakMap; this flag tells DoubleWeakMap so. - var doubleWeakMapCheckSilentFailure = false; + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') + start++; - // Check if there is already a good-enough WeakMap implementation, and if so - // exit without replacing it. - if (typeof WeakMap === 'function') { - var HostWeakMap = WeakMap; - // There is a WeakMap -- is it good enough? - if (typeof navigator !== 'undefined' && - /Firefox/.test(navigator.userAgent)) { - // We're now *assuming not*, because as of this writing (2013-05-06) - // Firefox's WeakMaps have a miscellany of objects they won't accept, and - // we don't want to make an exhaustive list, and testing for just one - // will be a problem if that one is fixed alone (as they did for Event). + if (base === 16) + this._parseHex(number, start); + else + this._parseBase(number, base, start); - // If there is a platform that we *can* reliably test on, here's how to - // do it: - // var problematic = ... ; - // var testHostMap = new HostWeakMap(); - // try { - // testHostMap.set(problematic, 1); // Firefox 20 will throw here - // if (testHostMap.get(problematic) === 1) { - // return; - // } - // } catch (e) {} + if (number[0] === '-') + this.sign = true; - } else { - // IE 11 bug: WeakMaps silently fail to store frozen objects. - var testMap = new HostWeakMap(); - var testObject = Object.freeze({}); - testMap.set(testObject, 1); - if (testMap.get(testObject) !== 1) { - doubleWeakMapCheckSilentFailure = true; - // Fall through to installing our WeakMap. - } else { - module.exports = WeakMap; - return; - } - } - } + this.strip(); - var hop = Object.prototype.hasOwnProperty; - var gopn = Object.getOwnPropertyNames; - var defProp = Object.defineProperty; - var isExtensible = Object.isExtensible; + if (endian !== 'le') + return; - /** - * Security depends on HIDDEN_NAME being both unguessable and - * undiscoverable by untrusted code. - * - *

Given the known weaknesses of Math.random() on existing - * browsers, it does not generate unguessability we can be confident - * of. - * - *

It is the monkey patching logic in this file that is intended - * to ensure undiscoverability. The basic idea is that there are - * three fundamental means of discovering properties of an object: - * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), - * as well as some proposed ES6 extensions that appear on our - * whitelist. The first two only discover enumerable properties, and - * we only use HIDDEN_NAME to name a non-enumerable property, so the - * only remaining threat should be getOwnPropertyNames and some - * proposed ES6 extensions that appear on our whitelist. We monkey - * patch them to remove HIDDEN_NAME from the list of properties they - * returns. - * - *

TODO(erights): On a platform with built-in Proxies, proxies - * could be used to trap and thereby discover the HIDDEN_NAME, so we - * need to monkey patch Proxy.create, Proxy.createFunction, etc, in - * order to wrap the provided handler with the real handler which - * filters out all traps using HIDDEN_NAME. - * - *

TODO(erights): Revisit Mike Stay's suggestion that we use an - * encapsulated function at a not-necessarily-secret name, which - * uses the Stiegler shared-state rights amplification pattern to - * reveal the associated value only to the WeakMap in which this key - * is associated with that value. Since only the key retains the - * function, the function can also remember the key without causing - * leakage of the key, so this doesn't violate our general gc - * goals. In addition, because the name need not be a guarded - * secret, we could efficiently handle cross-frame frozen keys. - */ - var HIDDEN_NAME_PREFIX = 'weakmap:'; - var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; + this._initArray(this.toArray(), base, endian); +}; - if (typeof crypto !== 'undefined' && - typeof crypto.getRandomValues === 'function' && - typeof ArrayBuffer === 'function' && - typeof Uint8Array === 'function') { - var ab = new ArrayBuffer(25); - var u8s = new Uint8Array(ab); - crypto.getRandomValues(u8s); - HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + - Array.prototype.map.call(u8s, function(u8) { - return (u8 % 36).toString(36); - }).join('') + '___'; +BN.prototype._initNumber = function _initNumber(number, base, endian) { + if (number < 0) { + this.sign = true; + number = -number; } - - function isNotHiddenName(name) { - return !( - name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && - name.substr(name.length - 3) === '___'); + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; } - /** - * Monkey patch getOwnPropertyNames to avoid revealing the - * HIDDEN_NAME. - * - *

The ES5.1 spec requires each name to appear only once, but as - * of this writing, this requirement is controversial for ES6, so we - * made this code robust against this case. If the resulting extra - * search turns out to be expensive, we can probably relax this once - * ES6 is adequately supported on all major browsers, iff no browser - * versions we support at that time have relaxed this constraint - * without providing built-in ES6 WeakMaps. - */ - defProp(Object, 'getOwnPropertyNames', { - value: function fakeGetOwnPropertyNames(obj) { - return gopn(obj).filter(isNotHiddenName); - } - }); + if (endian !== 'le') + return; - /** - * getPropertyNames is not in ES5 but it is proposed for ES6 and - * does appear in our whitelist, so we need to clean it too. - */ - if ('getPropertyNames' in Object) { - var originalGetPropertyNames = Object.getPropertyNames; - defProp(Object, 'getPropertyNames', { - value: function fakeGetPropertyNames(obj) { - return originalGetPropertyNames(obj).filter(isNotHiddenName); - } - }); + // Reverse the bytes + this._initArray(this.toArray(), base, endian); +}; + +BN.prototype._initArray = function _initArray(number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; } - /** - *

To treat objects as identity-keys with reasonable efficiency - * on ES5 by itself (i.e., without any object-keyed collections), we - * need to add a hidden property to such key objects when we - * can. This raises several issues: - *

    - *
  • Arranging to add this property to objects before we lose the - * chance, and - *
  • Hiding the existence of this new property from most - * JavaScript code. - *
  • Preventing certification theft, where one object is - * created falsely claiming to be the key of an association - * actually keyed by another object. - *
  • Preventing value theft, where untrusted code with - * access to a key object but not a weak map nevertheless - * obtains access to the value associated with that key in that - * weak map. - *
- * We do so by - *
    - *
  • Making the name of the hidden property unguessable, so "[]" - * indexing, which we cannot intercept, cannot be used to access - * a property without knowing the name. - *
  • Making the hidden property non-enumerable, so we need not - * worry about for-in loops or {@code Object.keys}, - *
  • monkey patching those reflective methods that would - * prevent extensions, to add this hidden property first, - *
  • monkey patching those methods that would reveal this - * hidden property. - *
- * Unfortunately, because of same-origin iframes, we cannot reliably - * add this hidden property before an object becomes - * non-extensible. Instead, if we encounter a non-extensible object - * without a hidden record that we can detect (whether or not it has - * a hidden record stored under a name secret to us), then we just - * use the key object itself to represent its identity in a brute - * force leaky map stored in the weak map, losing all the advantages - * of weakness for these. - */ - function getHiddenRecord(key) { - if (key !== Object(key)) { - throw new TypeError('Not an object: ' + key); + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + var off = 0; + if (endian === 'be') { + for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { + var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } } - var hiddenRecord = key[HIDDEN_NAME]; - if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } - if (!isExtensible(key)) { - // Weak map must brute force, as explained in doc-comment above. - return void 0; + } else if (endian === 'le') { + for (var i = 0, j = 0; i < number.length; i += 3) { + var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } } + } + return this.strip(); +}; - // The hiddenRecord and the key point directly at each other, via - // the "key" and HIDDEN_NAME properties respectively. The key - // field is for quickly verifying that this hidden record is an - // own property, not a hidden record from up the prototype chain. - // - // NOTE: Because this WeakMap emulation is meant only for systems like - // SES where Object.prototype is frozen without any numeric - // properties, it is ok to use an object literal for the hiddenRecord. - // This has two advantages: - // * It is much faster in a performance critical place - // * It avoids relying on Object.create(null), which had been - // problematic on Chrome 28.0.1480.0. See - // https://code.google.com/p/google-caja/issues/detail?id=1687 - hiddenRecord = { key: key }; - - // When using this WeakMap emulation on platforms where - // Object.prototype might not be frozen and Object.create(null) is - // reliable, use the following two commented out lines instead. - // hiddenRecord = Object.create(null); - // hiddenRecord.key = key; +function parseHex(str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; - // Please contact us if you need this to work on platforms where - // Object.prototype might not be frozen and - // Object.create(null) might not be reliable. + r <<= 4; - try { - defProp(key, HIDDEN_NAME, { - value: hiddenRecord, - writable: false, - enumerable: false, - configurable: false - }); - return hiddenRecord; - } catch (error) { - // Under some circumstances, isExtensible seems to misreport whether - // the HIDDEN_NAME can be defined. - // The circumstances have not been isolated, but at least affect - // Node.js v0.10.26 on TravisCI / Linux, but not the same version of - // Node.js on OS X. - return void 0; - } - } + // 'a' - 'f' + if (c >= 49 && c <= 54) + r |= c - 49 + 0xa; - /** - * Monkey patch operations that would make their argument - * non-extensible. - * - *

The monkey patched versions throw a TypeError if their - * argument is not an object, so it should only be done to functions - * that should throw a TypeError anyway if their argument is not an - * object. - */ - (function(){ - var oldFreeze = Object.freeze; - defProp(Object, 'freeze', { - value: function identifyingFreeze(obj) { - getHiddenRecord(obj); - return oldFreeze(obj); - } - }); - var oldSeal = Object.seal; - defProp(Object, 'seal', { - value: function identifyingSeal(obj) { - getHiddenRecord(obj); - return oldSeal(obj); - } - }); - var oldPreventExtensions = Object.preventExtensions; - defProp(Object, 'preventExtensions', { - value: function identifyingPreventExtensions(obj) { - getHiddenRecord(obj); - return oldPreventExtensions(obj); - } - }); - })(); + // 'A' - 'F' + else if (c >= 17 && c <= 22) + r |= c - 17 + 0xa; - function constFunc(func) { - func.prototype = null; - return Object.freeze(func); + // '0' - '9' + else + r |= c & 0xf; } + return r; +} - var calledAsFunctionWarningDone = false; - function calledAsFunctionWarning() { - // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() - // but we used to permit it and do it ourselves, so warn only. - if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { - calledAsFunctionWarningDone = true; - console.warn('WeakMap should be invoked as new WeakMap(), not ' + - 'WeakMap(). This will be an error in the future.'); +BN.prototype._parseHex = function _parseHex(number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Scan 24-bit chunks and add them to the number + var off = 0; + for (var i = number.length - 6, j = 0; i >= start; i -= 6) { + var w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; } } + if (i + 6 !== start) { + var w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); +}; - var nextId = 0; +function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; - var OurWeakMap = function() { - if (!(this instanceof OurWeakMap)) { // approximate test for new ...() - calledAsFunctionWarning(); - } + r *= mul; - // We are currently (12/25/2012) never encountering any prematurely - // non-extensible keys. - var keys = []; // brute force for prematurely non-extensible keys. - var values = []; // brute force for corresponding values. - var id = nextId++; + // 'a' + if (c >= 49) + r += c - 49 + 0xa; - function get___(key, opt_default) { - var index; - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - return id in hiddenRecord ? hiddenRecord[id] : opt_default; - } else { - index = keys.indexOf(key); - return index >= 0 ? values[index] : opt_default; - } - } + // 'A' + else if (c >= 17) + r += c - 17 + 0xa; - function has___(key) { - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - return id in hiddenRecord; - } else { - return keys.indexOf(key) >= 0; - } - } + // '0' - '9' + else + r += c; + } + return r; +} - function set___(key, value) { - var index; - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - hiddenRecord[id] = value; - } else { - index = keys.indexOf(key); - if (index >= 0) { - values[index] = value; - } else { - // Since some browsers preemptively terminate slow turns but - // then continue computing with presumably corrupted heap - // state, we here defensively get keys.length first and then - // use it to update both the values and keys arrays, keeping - // them in sync. - index = keys.length; - values[index] = value; - // If we crash here, values will be one longer than keys. - keys[index] = key; - } - } - return this; - } +BN.prototype._parseBase = function _parseBase(number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - function delete___(key) { - var hiddenRecord = getHiddenRecord(key); - var index, lastIndex; - if (hiddenRecord) { - return id in hiddenRecord && delete hiddenRecord[id]; - } else { - index = keys.indexOf(key); - if (index < 0) { - return false; - } - // Since some browsers preemptively terminate slow turns but - // then continue computing with potentially corrupted heap - // state, we here defensively get keys.length first and then use - // it to update both the keys and the values array, keeping - // them in sync. We update the two with an order of assignments, - // such that any prefix of these assignments will preserve the - // key/value correspondence, either before or after the delete. - // Note that this needs to work correctly when index === lastIndex. - lastIndex = keys.length - 1; - keys[index] = void 0; - // If we crash here, there's a void 0 in the keys array, but - // no operation will cause a "keys.indexOf(void 0)", since - // getHiddenRecord(void 0) will always throw an error first. - values[index] = values[lastIndex]; - // If we crash here, values[index] cannot be found here, - // because keys[index] is void 0. - keys[index] = keys[lastIndex]; - // If index === lastIndex and we crash here, then keys[index] - // is still void 0, since the aliasing killed the previous key. - keys.length = lastIndex; - // If we crash here, keys will be one shorter than values. - values.length = lastIndex; - return true; - } - } + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) + limbLen++; + limbLen--; + limbPow = (limbPow / base) | 0; - return Object.create(OurWeakMap.prototype, { - get___: { value: constFunc(get___) }, - has___: { value: constFunc(has___) }, - set___: { value: constFunc(set___) }, - delete___: { value: constFunc(delete___) } - }); - }; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - OurWeakMap.prototype = Object.create(Object.prototype, { - get: { - /** - * Return the value most recently associated with key, or - * opt_default if none. - */ - value: function get(key, opt_default) { - return this.get___(key, opt_default); - }, - writable: true, - configurable: true - }, + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - has: { - /** - * Is there a value associated with key in this WeakMap? - */ - value: function has(key) { - return this.has___(key); - }, - writable: true, - configurable: true - }, + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) + this.words[0] += word; + else + this._iaddn(word); + } - set: { - /** - * Associate value with key in this WeakMap, overwriting any - * previous association if present. - */ - value: function set(key, value) { - return this.set___(key, value); - }, - writable: true, - configurable: true - }, + if (mod !== 0) { + var pow = 1; + var word = parseBase(number, i, number.length, base); - 'delete': { - /** - * Remove any association for key in this WeakMap, returning - * whether there was one. - * - *

Note that the boolean return here does not work like the - * {@code delete} operator. The {@code delete} operator returns - * whether the deletion succeeds at bringing about a state in - * which the deleted property is absent. The {@code delete} - * operator therefore returns true if the property was already - * absent, whereas this {@code delete} method returns false if - * the association was already absent. - */ - value: function remove(key) { - return this.delete___(key); - }, - writable: true, - configurable: true - } - }); + for (var i = 0; i < mod; i++) + pow *= base; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) + this.words[0] += word; + else + this._iaddn(word); + } +}; - if (typeof HostWeakMap === 'function') { - (function() { - // If we got here, then the platform has a WeakMap but we are concerned - // that it may refuse to store some key types. Therefore, make a map - // implementation which makes use of both as possible. +BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + dest.words[i] = this.words[i]; + dest.length = this.length; + dest.sign = this.sign; + dest.red = this.red; +}; - // In this mode we are always using double maps, so we are not proxy-safe. - // This combination does not occur in any known browser, but we had best - // be safe. - if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { - Proxy = undefined; - } +BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; +}; - function DoubleWeakMap() { - if (!(this instanceof OurWeakMap)) { // approximate test for new ...() - calledAsFunctionWarning(); - } +// Remove leading `0` from `this` +BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) + this.length--; + return this._normSign(); +}; - // Preferable, truly weak map. - var hmap = new HostWeakMap(); +BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) + this.sign = false; + return this; +}; - // Our hidden-property-based pseudo-weak-map. Lazily initialized in the - // 'set' implementation; thus we can avoid performing extra lookups if - // we know all entries actually stored are entered in 'hmap'. - var omap = undefined; +BN.prototype.inspect = function inspect() { + return (this.red ? ''; +}; - // Hidden-property maps are not compatible with proxies because proxies - // can observe the hidden name and either accidentally expose it or fail - // to allow the hidden property to be set. Therefore, we do not allow - // arbitrary WeakMaps to switch to using hidden properties, but only - // those which need the ability, and unprivileged code is not allowed - // to set the flag. - // - // (Except in doubleWeakMapCheckSilentFailure mode in which case we - // disable proxies.) - var enableSwitching = false; +/* - function dget(key, opt_default) { - if (omap) { - return hmap.has(key) ? hmap.get(key) - : omap.get___(key, opt_default); - } else { - return hmap.get(key, opt_default); - } - } +var zeros = []; +var groupSizes = []; +var groupBases = []; - function dhas(key) { - return hmap.has(key) || (omap ? omap.has___(key) : false); - } +var s = ''; +var i = -1; +while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; +} +groupSizes[0] = 0; +groupSizes[1] = 0; +groupBases[0] = 0; +groupBases[1] = 0; +var base = 2 - 1; +while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; +} - var dset; - if (doubleWeakMapCheckSilentFailure) { - dset = function(key, value) { - hmap.set(key, value); - if (!hmap.has(key)) { - if (!omap) { omap = new OurWeakMap(); } - omap.set(key, value); - } - return this; - }; - } else { - dset = function(key, value) { - if (enableSwitching) { - try { - hmap.set(key, value); - } catch (e) { - if (!omap) { omap = new OurWeakMap(); } - omap.set___(key, value); - } - } else { - hmap.set(key, value); - } - return this; - }; - } +*/ - function ddelete(key) { - var result = !!hmap['delete'](key); - if (omap) { return omap.delete___(key) || result; } - return result; - } +var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' +]; - return Object.create(OurWeakMap.prototype, { - get___: { value: constFunc(dget) }, - has___: { value: constFunc(dhas) }, - set___: { value: constFunc(dset) }, - delete___: { value: constFunc(ddelete) }, - permitHostObjects___: { value: constFunc(function(token) { - if (token === weakMapPermitHostObjects) { - enableSwitching = true; - } else { - throw new Error('bogus call to permitHostObjects___'); - } - })} - }); - } - DoubleWeakMap.prototype = OurWeakMap.prototype; - module.exports = DoubleWeakMap; +var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 +]; - // define .constructor to hide OurWeakMap ctor - Object.defineProperty(WeakMap.prototype, 'constructor', { - value: WeakMap, - enumerable: false, // as default .constructor is - configurable: true, - writable: true - }); - })(); - } else { - // There is no host WeakMap, so we must use the emulation. +var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 +]; - // Emulated WeakMaps are incompatible with native proxies (because proxies - // can observe the hidden name), so we must disable Proxy usage (in - // ArrayLike and Domado, currently). - if (typeof Proxy !== 'undefined') { - Proxy = undefined; +BN.prototype.toString = function toString(base, padding) { + base = base || 10; + if (base === 16 || base === 'hex') { + var out = ''; + var off = 0; + var padding = padding | 0 || 1; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) + out = zeros[6 - word.length] + word + out; + else + out = word + out; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } } + if (carry !== 0) + out = carry.toString(16) + out; + while (out.length % padding !== 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + var out = ''; + var c = this.clone(); + c.sign = false; + while (c.cmpn(0) !== 0) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); - module.exports = OurWeakMap; + if (c.cmpn(0) !== 0) + out = zeros[groupSize - r.length] + r + out; + else + out = r + out; + } + if (this.cmpn(0) === 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else { + assert(false, 'Base should be between 2 and 36'); } -})(); +}; -},{}],169:[function(require,module,exports){ -'use strict' +BN.prototype.toJSON = function toJSON() { + return this.toString(16); +}; -var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') +BN.prototype.toArray = function toArray(endian) { + this.strip(); + var res = new Array(this.byteLength()); + res[0] = 0; -var TriangleCache = new weakMap() + var q = this.clone(); + if (endian !== 'le') { + // Assume big-endian + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); -function createABigTriangle(gl) { + res[res.length - i - 1] = b; + } + } else { + // Assume little-endian + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); - var triangleVAO = TriangleCache.get(gl) - if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) { - var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) - triangleVAO = createVAO(gl, [ - { buffer: buf, - type: gl.FLOAT, - size: 2 - } - ]) - triangleVAO._triangleBuffer = buf - TriangleCache.set(gl, triangleVAO) + res[i] = b; + } } - triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, 3) - triangleVAO.unbind() -} - -module.exports = createABigTriangle - -},{"gl-buffer":118,"gl-vao":226,"weak-map":168}],170:[function(require,module,exports){ -'use strict' - -module.exports = createAxes - -var createText = require('./lib/text.js') -var createLines = require('./lib/lines.js') -var createBackground = require('./lib/background.js') -var getCubeProperties = require('./lib/cube.js') -var Ticks = require('./lib/ticks.js') -var identity = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]) + return res; +}; -function copyVec3(a, b) { - a[0] = b[0] - a[1] = b[1] - a[2] = b[2] - return a +if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; +} else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; } -function Axes(gl) { - this.gl = gl - - this.pixelRatio = 1 - - this.bounds = [ [-10, -10, -10], - [ 10, 10, 10] ] - this.ticks = [ [], [], [] ] - this.autoTicks = true - this.tickSpacing = [ 1, 1, 1 ] - - this.tickEnable = [ true, true, true ] - this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ] - this.tickSize = [ 12, 12, 12 ] - this.tickAngle = [ 0, 0, 0 ] - this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.tickPad = [ 10, 10, 10 ] +BN.prototype._zeroBits = function _zeroBits(w) { + // Short-cut + if (w === 0) + return 26; - this.lastCubeProps = { - cubeEdges: [0,0,0], - axis: [0,0,0] + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) + r++; + return r; +}; - this.labels = [ 'x', 'y', 'z' ] - this.labelEnable = [ true, true, true ] - this.labelFont = 'sans-serif' - this.labelSize = [ 20, 20, 20 ] - this.labelAngle = [ 0, 0, 0 ] - this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.labelPad = [ 10, 10, 10 ] - - this.lineEnable = [ true, true, true ] - this.lineMirror = [ false, false, false ] - this.lineWidth = [ 1, 1, 1 ] - this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - - this.lineTickEnable = [ true, true, true ] - this.lineTickMirror = [ false, false, false ] - this.lineTickLength = [ 0, 0, 0 ] - this.lineTickWidth = [ 1, 1, 1 ] - this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - - this.gridEnable = [ true, true, true ] - this.gridWidth = [ 1, 1, 1 ] - this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - - this.zeroEnable = [ true, true, true ] - this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.zeroLineWidth = [ 2, 2, 2 ] - - this.backgroundEnable = [ false, false, false ] - this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5], - [0.8, 0.8, 0.8, 0.5], - [0.8, 0.8, 0.8, 0.5] ] +// Return number of used bits in a BN +BN.prototype.bitLength = function bitLength() { + var hi = 0; + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; +}; - this._firstInit = true - this._text = null - this._lines = null - this._background = createBackground(gl) -} +// Number of trailing zero bits +BN.prototype.zeroBits = function zeroBits() { + if (this.cmpn(0) === 0) + return 0; -var proto = Axes.prototype + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) + break; + } + return r; +}; -proto.update = function(options) { - options = options || {} +BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); +}; - //Option parsing helper functions - function parseOption(nest, cons, name) { - if(name in options) { - var opt = options[name] - var prev = this[name] - var next - if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : - Array.isArray(opt) ) { - this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] - } else { - this[name] = next = [ cons(opt), cons(opt), cons(opt) ] - } - for(var i=0; i<3; ++i) { - if(next[i] !== prev[i]) { - return true - } - } - } - return false - } +// Return negative clone of `this` +BN.prototype.neg = function neg() { + if (this.cmpn(0) === 0) + return this.clone(); - var NUMBER = parseOption.bind(this, false, Number) - var BOOLEAN = parseOption.bind(this, false, Boolean) - var STRING = parseOption.bind(this, false, String) - var COLOR = parseOption.bind(this, true, function(v) { - if(Array.isArray(v)) { - if(v.length === 3) { - return [ +v[0], +v[1], +v[2], 1.0 ] - } else if(v.length === 4) { - return [ +v[0], +v[1], +v[2], +v[3] ] - } - } - return [ 0, 0, 0, 1 ] - }) + var r = this.clone(); + r.sign = !this.sign; + return r; +}; - //Tick marks and bounds - var nextTicks - var ticksUpdate = false - var boundsChanged = false - if('bounds' in options) { - var bounds = options.bounds -i_loop: - for(var i=0; i<2; ++i) { - for(var j=0; j<3; ++j) { - if(bounds[i][j] !== this.bounds[i][j]) { - boundsChanged = true - } - this.bounds[i][j] = bounds[i][j] - } - } - } - if('ticks' in options) { - nextTicks = options.ticks - ticksUpdate = true - this.autoTicks = false - for(var i=0; i<3; ++i) { - this.tickSpacing[i] = 0.0 - } - } else if(NUMBER('tickSpacing')) { - this.autoTicks = true - boundsChanged = true - } - if(this._firstInit) { - if(!('ticks' in options || 'tickSpacing' in options)) { - this.autoTicks = true - } +// Or `num` with `this` in-place +BN.prototype.ior = function ior(num) { + this.sign = this.sign || num.sign; - //Force tick recomputation on first update - boundsChanged = true - ticksUpdate = true - this._firstInit = false - } + while (this.length < num.length) + this.words[this.length++] = 0; - if(boundsChanged && this.autoTicks) { - nextTicks = Ticks.create(this.bounds, this.tickSpacing) - ticksUpdate = true - } + for (var i = 0; i < num.length; i++) + this.words[i] = this.words[i] | num.words[i]; - //Compare next ticks to previous ticks, only update if needed - if(ticksUpdate) { - for(var i=0; i<3; ++i) { - nextTicks[i].sort(function(a,b) { - return a.x-b.x - }) - } - if(Ticks.equal(nextTicks, this.ticks)) { - ticksUpdate = false - } else { - this.ticks = nextTicks - } - } + return this.strip(); +}; - //Parse tick properties - BOOLEAN('tickEnable') - if(STRING('tickFont')) { - ticksUpdate = true //If font changes, must rebuild vbo - } - NUMBER('tickSize') - NUMBER('tickAngle') - NUMBER('tickPad') - COLOR('tickColor') - //Axis labels - var labelUpdate = STRING('labels') - if(STRING('labelFont')) { - labelUpdate = true - } - BOOLEAN('labelEnable') - NUMBER('labelSize') - NUMBER('labelPad') - COLOR('labelColor') +// Or `num` with `this` +BN.prototype.or = function or(num) { + if (this.length > num.length) + return this.clone().ior(num); + else + return num.clone().ior(this); +}; - //Axis lines - BOOLEAN('lineEnable') - BOOLEAN('lineMirror') - NUMBER('lineWidth') - COLOR('lineColor') - //Axis line ticks - BOOLEAN('lineTickEnable') - BOOLEAN('lineTickMirror') - NUMBER('lineTickLength') - NUMBER('lineTickWidth') - COLOR('lineTickColor') +// And `num` with `this` in-place +BN.prototype.iand = function iand(num) { + this.sign = this.sign && num.sign; - //Grid lines - BOOLEAN('gridEnable') - NUMBER('gridWidth') - COLOR('gridColor') + // b = min-length(num, this) + var b; + if (this.length > num.length) + b = num; + else + b = this; - //Zero line - BOOLEAN('zeroEnable') - COLOR('zeroLineColor') - NUMBER('zeroLineWidth') + for (var i = 0; i < b.length; i++) + this.words[i] = this.words[i] & num.words[i]; - //Background - BOOLEAN('backgroundEnable') - COLOR('backgroundColor') + this.length = b.length; - //Update text if necessary - if(!this._text) { - this._text = createText( - this.gl, - this.bounds, - this.labels, - this.labelFont, - this.ticks, - this.tickFont) - } else if(this._text && (labelUpdate || ticksUpdate)) { - this._text.update( - this.bounds, - this.labels, - this.labelFont, - this.ticks, - this.tickFont) - } + return this.strip(); +}; - //Update lines if necessary - if(this._lines && ticksUpdate) { - this._lines.dispose() - this._lines = null - } - if(!this._lines) { - this._lines = createLines(this.gl, this.bounds, this.ticks) - } -} -function OffsetInfo() { - this.primalOffset = [0,0,0] - this.primalMinor = [0,0,0] - this.mirrorOffset = [0,0,0] - this.mirrorMinor = [0,0,0] -} +// And `num` with `this` +BN.prototype.and = function and(num) { + if (this.length > num.length) + return this.clone().iand(num); + else + return num.clone().iand(this); +}; -var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ] -function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) { - var primalOffset = result.primalOffset - var primalMinor = result.primalMinor - var dualOffset = result.mirrorOffset - var dualMinor = result.mirrorMinor - var e = cubeEdges[i] +// Xor `num` with `this` in-place +BN.prototype.ixor = function ixor(num) { + this.sign = this.sign || num.sign; - //Calculate offsets - for(var j=0; j<3; ++j) { - if(i === j) { - continue - } - var a = primalOffset, - b = dualOffset, - c = primalMinor, - d = dualMinor - if(e & (1< 0) { - c[j] = -1 - d[j] = 0 - } else { - c[j] = 0 - d[j] = +1 - } + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } -} -var CUBE_ENABLE = [0,0,0] -var DEFAULT_PARAMS = { - model: identity, - view: identity, - projection: identity -} + for (var i = 0; i < b.length; i++) + this.words[i] = a.words[i] ^ b.words[i]; -proto.isOpaque = function() { - return true -} + if (this !== a) + for (; i < a.length; i++) + this.words[i] = a.words[i]; -proto.isTransparent = function() { - return false -} + this.length = a.length; -proto.drawTransparent = function(params) {} + return this.strip(); +}; -var PRIMAL_MINOR = [0,0,0] -var MIRROR_MINOR = [0,0,0] -var PRIMAL_OFFSET = [0,0,0] +// Xor `num` with `this` +BN.prototype.xor = function xor(num) { + if (this.length > num.length) + return this.clone().ixor(num); + else + return num.clone().ixor(this); +}; -proto.draw = function(params) { - params = params || DEFAULT_PARAMS - var gl = this.gl +// Set `bit` of `this` +BN.prototype.setn = function setn(bit, val) { + assert(typeof bit === 'number' && bit >= 0); - //Geometry for camera and axes - var model = params.model || identity - var view = params.view || identity - var projection = params.projection || identity - var bounds = this.bounds + var off = (bit / 26) | 0; + var wbit = bit % 26; - //Unpack axis info - var cubeParams = getCubeProperties(model, view, projection, bounds) - var cubeEdges = cubeParams.cubeEdges - var cubeAxis = cubeParams.axis + while (this.length <= off) + this.words[this.length++] = 0; - var cx = view[12] - var cy = view[13] - var cz = view[14] - var cw = view[15] + if (val) + this.words[off] = this.words[off] | (1 << wbit); + else + this.words[off] = this.words[off] & ~(1 << wbit); - var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight + return this.strip(); +}; - for(var i=0; i<3; ++i) { - this.lastCubeProps.cubeEdges[i] = cubeEdges[i] - this.lastCubeProps.axis[i] = cubeAxis[i] + +// Add `num` to `this` in-place +BN.prototype.iadd = function iadd(num) { + // negative + positive + if (this.sign && !num.sign) { + this.sign = false; + var r = this.isub(num); + this.sign = !this.sign; + return this._normSign(); + + // positive + negative + } else if (!this.sign && num.sign) { + num.sign = false; + var r = this.isub(num); + num.sign = true; + return r._normSign(); } - //Compute axis info - var lineOffset = LINE_OFFSET - for(var i=0; i<3; ++i) { - computeLineOffset( - LINE_OFFSET[i], - i, - this.bounds, - cubeEdges, - cubeAxis) + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - //Set up state parameters - var gl = this.gl + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] + b.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - //Draw background first - var cubeEnable = CUBE_ENABLE - for(var i=0; i<3; ++i) { - if(this.backgroundEnable[i]) { - cubeEnable[i] = cubeAxis[i] - } else { - cubeEnable[i] = 0 - } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) + this.words[i] = a.words[i]; } - this._background.draw( - model, - view, - projection, - bounds, - cubeEnable, - this.backgroundColor) + return this; +}; - //Draw lines - this._lines.bind( - model, - view, - projection, - this) +// Add `num` to `this` +BN.prototype.add = function add(num) { + if (num.sign && !this.sign) { + num.sign = false; + var res = this.sub(num); + num.sign = true; + return res; + } else if (!num.sign && this.sign) { + this.sign = false; + var res = num.sub(this); + this.sign = true; + return res; + } - //First draw grid lines and zero lines - for(var i=0; i<3; ++i) { - var x = [0,0,0] - if(cubeAxis[i] > 0) { - x[i] = bounds[1][i] - } else { - x[i] = bounds[0][i] - } + if (this.length > num.length) + return this.clone().iadd(num); + else + return num.clone().iadd(this); +}; - //Draw grid lines - for(var j=0; j<2; ++j) { - var u = (i + 1 + j) % 3 - var v = (i + 1 + (j^1)) % 3 - if(this.gridEnable[u]) { - this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio) - } - } +// Subtract `num` from `this` in-place +BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.sign) { + num.sign = false; + var r = this.iadd(num); + num.sign = true; + return r._normSign(); - //Draw zero lines (need to do this AFTER all grid lines are drawn) - for(var j=0; j<2; ++j) { - var u = (i + 1 + j) % 3 - var v = (i + 1 + (j^1)) % 3 - if(this.zeroEnable[v]) { - //Check if zero line in bounds - if(bounds[0][v] <= 0 && bounds[1][v] >= 0) { - this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio) - } - } - } + // -this - num = -(this + num) + } else if (this.sign) { + this.sign = false; + this.iadd(num); + this.sign = true; + return this._normSign(); } - //Then draw axis lines and tick marks - for(var i=0; i<3; ++i) { + // At this point both numbers are positive + var cmp = this.cmp(num); - //Draw axis lines - if(this.lineEnable[i]) { - this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) - } - if(this.lineMirror[i]) { - this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) - } + // Optimization - zeroify + if (cmp === 0) { + this.sign = false; + this.length = 1; + this.words[0] = 0; + return this; + } - //Compute minor axes - var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor) - var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor) - var tickLength = this.lineTickLength - var op = 0 - for(var j=0; j<3; ++j) { - var scaleFactor = pixelScaleF / model[5*j] - primalMinor[j] *= tickLength[j] * scaleFactor - mirrorMinor[j] *= tickLength[j] * scaleFactor - } + // a > b + var a; + var b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - //Draw axis line ticks - if(this.lineTickEnable[i]) { - this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) - } - if(this.lineTickMirror[i]) { - this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) - } + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] - b.words[i] + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; } - //Draw text sprites - this._text.bind( - model, - view, - projection, - this.pixelRatio) + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) + for (; i < a.length; i++) + this.words[i] = a.words[i]; + this.length = Math.max(this.length, i); - for(var i=0; i<3; ++i) { + if (a !== this) + this.sign = true; - var minor = lineOffset[i].primalMinor - var offset = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset) + return this.strip(); +}; - for(var j=0; j<3; ++j) { - if(this.lineTickEnable[i]) { - offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0) / model[5*j] +// Subtract `num` from `this` +BN.prototype.sub = function sub(num) { + return this.clone().isub(num); +}; + +/* +// NOTE: This could be potentionally used to generate loop-less multiplications +function _genCombMulTo(alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + + 'mask = 0x3ffffff, shift = 0x4000000;', + 'out.length = ' + len + ';' + ]; + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + for (var j = minJ; j <= maxJ; j++) { + var i = k - j; + var mul = 'a[' + i + '] * b[' + j + ']'; + + if (j === minJ) { + src.push('w = ' + mul + ' + c;'); + src.push('c = (w / shift) | 0;'); + } else { + src.push('w += ' + mul + ';'); + src.push('c += (w / shift) | 0;'); } + src.push('w &= mask;'); } + src.push('o[' + k + '] = w;'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); - //Draw tick text - if(this.tickEnable[i]) { + return src.join('\n'); +} +*/ - //Add tick padding - for(var j=0; j<3; ++j) { - offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j] - } +BN.prototype._smallMulTo = function _smallMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; - //Draw axis - this._text.drawTicks( - i, - this.tickSize[i], - this.tickAngle[i], - offset, - this.tickColor[i]) + var carry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; } + out.words[k] = rword; + carry = ncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } - //Draw labels - if(this.labelEnable[i]) { + return out.strip(); +}; - //Add label padding - for(var j=0; j<3; ++j) { - offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j] - } - offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]) +BN.prototype._bigMulTo = function _bigMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; - //Draw axis - this._text.drawLabel( - i, - this.labelSize[i], - this.labelAngle[i], - offset, - this.labelColor[i]) + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; } -} -proto.dispose = function() { - this._text.dispose() - this._lines.dispose() - this._background.dispose() - this._lines = null - this._text = null - this._background = null - this.gl = null -} + return out.strip(); +}; -function createAxes(gl, options) { - var axes = new Axes(gl) - axes.update(options) - return axes -} +BN.prototype.mulTo = function mulTo(num, out) { + var res; + if (this.length + num.length < 63) + res = this._smallMulTo(num, out); + else + res = this._bigMulTo(num, out); + return res; +}; -},{"./lib/background.js":171,"./lib/cube.js":172,"./lib/lines.js":173,"./lib/text.js":175,"./lib/ticks.js":176}],171:[function(require,module,exports){ -'use strict' +// Multiply `this` by `num` +BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); +}; -module.exports = createBackgroundCube +// In-place Multiplication +BN.prototype.imul = function imul(num) { + if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { + this.words[0] = 0; + this.length = 1; + return this; + } -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders').bg + var tlen = this.length; + var nlen = num.length; -function BackgroundCube(gl, buffer, vao, shader) { - this.gl = gl - this.buffer = buffer - this.vao = vao - this.shader = shader -} + this.sign = num.sign !== this.sign; + this.length = this.length + num.length; + this.words[this.length - 1] = 0; -var proto = BackgroundCube.prototype + for (var k = this.length - 2; k >= 0; k--) { + // Sum all words with the same `i + j = k` and accumulate `carry`, + // note that carry could be >= 0x3ffffff + var carry = 0; + var rword = 0; + var maxJ = Math.min(k, nlen - 1); + for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i]; + var b = num.words[j]; + var r = a * b; -proto.draw = function(model, view, projection, bounds, enable, colors) { - var needsBG = false - for(var i=0; i<3; ++i) { - needsBG = needsBG || enable[i] + var lo = r & 0x3ffffff; + carry += (r / 0x4000000) | 0; + lo += rword; + rword = lo & 0x3ffffff; + carry += lo >>> 26; + } + this.words[k] = rword; + this.words[k + 1] += carry; + carry = 0; + } + + // Propagate overflows + var carry = 0; + for (var i = 1; i < this.length; i++) { + var w = this.words[i] + carry; + this.words[i] = w & 0x3ffffff; + carry = w >>> 26; + } + + return this.strip(); +}; + +BN.prototype.imuln = function imuln(num) { + assert(typeof num === 'number'); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i] * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; } - if(!needsBG) { - return + + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - var gl = this.gl + return this; +}; - gl.enable(gl.POLYGON_OFFSET_FILL) - gl.polygonOffset(1, 2) +BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); +}; - this.shader.bind() - this.shader.uniforms = { - model: model, - view: view, - projection: projection, - bounds: bounds, - enable: enable, - colors: colors - } - this.vao.bind() - this.vao.draw(this.gl.TRIANGLES, 36) +// `this` * `this` +BN.prototype.sqr = function sqr() { + return this.mul(this); +}; - gl.disable(gl.POLYGON_OFFSET_FILL) -} +// `this` * `this` in-place +BN.prototype.isqr = function isqr() { + return this.mul(this); +}; -proto.dispose = function() { - this.vao.dispose() - this.buffer.dispose() - this.shader.dispose() -} +// Shift-left in-place +BN.prototype.ishln = function ishln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); -function createBackgroundCube(gl) { - //Create cube vertices - var vertices = [] - var indices = [] - var ptr = 0 - for(var d=0; d<3; ++d) { - var u = (d+1) % 3 - var v = (d+2) % 3 - var x = [0,0,0] - var c = [0,0,0] - for(var s=-1; s<=1; s+=2) { - indices.push(ptr, ptr+2, ptr+1, - ptr+1, ptr+2, ptr+3) - x[d] = s - c[d] = s - for(var i=-1; i<=1; i+=2) { - x[u] = i - for(var j=-1; j<=1; j+=2) { - x[v] = j - vertices.push(x[0], x[1], x[2], - c[0], c[1], c[2]) - ptr += 1 - } - } - //Swap u and v - var tt = u - u = v - v = tt + if (r !== 0) { + var carry = 0; + for (var i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + if (carry) { + this.words[i] = carry; + this.length++; } } - //Allocate buffer and vertex array - var buffer = createBuffer(gl, new Float32Array(vertices)) - var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) - var vao = createVAO(gl, [ - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 0, - stride: 24 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 12, - stride: 24 - } - ], elements) - - //Create shader object - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.normal.location = 1 - - return new BackgroundCube(gl, buffer, vao, shader) -} + if (s !== 0) { + for (var i = this.length - 1; i >= 0; i--) + this.words[i + s] = this.words[i]; + for (var i = 0; i < s; i++) + this.words[i] = 0; + this.length += s; + } -},{"./shaders":174,"gl-buffer":118,"gl-vao":226}],172:[function(require,module,exports){ -"use strict" + return this.strip(); +}; -module.exports = getCubeEdges +// Shift-right in-place +// NOTE: `hint` is a lowest bit before trailing zeroes +// NOTE: if `extended` is present - it will be filled with destroyed bits +BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) + h = (hint - (hint % 26)) / 26; + else + h = 0; -var bits = require('bit-twiddle') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var splitPoly = require('split-polygon') -var orient = require('robust-orientation') + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; -var mvp = new Array(16) -var imvp = new Array(16) -var pCubeVerts = new Array(8) -var cubeVerts = new Array(8) -var x = new Array(3) -var zero3 = [0,0,0] + h -= s; + h = Math.max(0, h); -;(function() { - for(var i=0; i<8; ++i) { - pCubeVerts[i] =[1,1,1,1] - cubeVerts[i] = [1,1,1] + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) + maskedWords.words[i] = this.words[i]; + maskedWords.length = s; } -})() + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (var i = 0; i < this.length; i++) + this.words[i] = this.words[i + s]; + } else { + this.words[0] = 0; + this.length = 1; + } -function transformHg(result, x, mat) { - for(var i=0; i<4; ++i) { - result[i] = mat[12+i] - for(var j=0; j<3; ++j) { - result[i] += x[j]*mat[4*j+i] - } + var carry = 0; + for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i]; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; } -} -var FRUSTUM_PLANES = [ - [ 0, 0, 1, 0, 0], - [ 0, 0,-1, 1, 0], - [ 0,-1, 0, 1, 0], - [ 0, 1, 0, 1, 0], - [-1, 0, 0, 1, 0], - [ 1, 0, 0, 1, 0] -] + // Push carried bits as a mask + if (maskedWords && carry !== 0) + maskedWords.words[maskedWords.length++] = carry; -function polygonArea(p) { - for(var i=0; i= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + return false; } - return area -} + // Check bit and return + var w = this.words[s]; -var CUBE_EDGES = [1,1,1] -var CUBE_AXIS = [0,0,0] -var CUBE_RESULT = { - cubeEdges: CUBE_EDGES, - axis: CUBE_AXIS -} + return !!(w & q); +}; -function getCubeEdges(model, view, projection, bounds) { +// Return only lowers bits of number (in-place) +BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; - //Concatenate matrices - multiply(mvp, view, model) - multiply(mvp, projection, mvp) - - //First project cube vertices - var ptr = 0 - for(var i=0; i<2; ++i) { - x[2] = bounds[i][2] - for(var j=0; j<2; ++j) { - x[1] = bounds[j][1] - for(var k=0; k<2; ++k) { - x[0] = bounds[k][0] - transformHg(pCubeVerts[ptr], x, mvp) - ptr += 1 - } - } - } + assert(!this.sign, 'imaskn works only with positive numbers'); - //Classify camera against cube faces - var closest = -1 + if (r !== 0) + s++; + this.length = Math.min(s, this.length); - for(var i=0; i<8; ++i) { - var w = pCubeVerts[i][3] - for(var l=0; l<3; ++l) { - cubeVerts[i][l] = pCubeVerts[i][l] / w - } - if(w < 0) { - if(closest < 0) { - closest = i - } else if(cubeVerts[i][2] < cubeVerts[closest][2]) { - closest = i - } - } + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; } - if(closest < 0) { - closest = 0 - for(var d=0; d<3; ++d) { - var u = (d+2) % 3 - var v = (d+1) % 3 - var o0 = -1 - var o1 = -1 - for(var s=0; s<2; ++s) { - var f0 = (s< o0) { - closest |= 1< o0) { - closest |= 1< cubeVerts[i][1]) { - bottom = i - } - } +// Add plain number `num` to `this` +BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.isubn(-num); - //Find left/right neighbors of bottom vertex - var left = -1 - for(var i=0; i<3; ++i) { - var idx = bottom ^ (1< cubeVerts[right][0]) { - right = idx + // Possible sign change + if (this.sign) { + if (this.length === 1 && this.words[0] < num) { + this.words[0] = num - this.words[0]; + this.sign = false; + return this; } - } - //Determine edge axis coordinates - var cubeEdges = CUBE_EDGES - cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0 - cubeEdges[bits.log2(left^bottom)] = bottom&left - cubeEdges[bits.log2(bottom^right)] = bottom&right - var top = right ^ 7 - if(top === closest || top === farthest) { - top = left ^ 7 - cubeEdges[bits.log2(right^top)] = top&right - } else { - cubeEdges[bits.log2(left^top)] = top&left + this.sign = false; + this.isubn(num); + this.sign = true; + return this; } - //Determine visible faces - var axis = CUBE_AXIS - var cutCorner = closest - for(var d=0; d<3; ++d) { - if(cutCorner & (1<= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) + this.words[i + 1] = 1; + else + this.words[i + 1]++; } + this.length = Math.max(this.length, i + 1); - //Return result - return CUBE_RESULT -} -},{"bit-twiddle":50,"gl-mat4/invert":137,"gl-mat4/multiply":139,"robust-orientation":259,"split-polygon":178}],173:[function(require,module,exports){ -'use strict' + return this; +}; -module.exports = createLines +// Subtract plain number `num` from `this` +BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.iaddn(-num); -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders').line + if (this.sign) { + this.sign = false; + this.iaddn(num); + this.sign = true; + return this; + } -var MAJOR_AXIS = [0,0,0] -var MINOR_AXIS = [0,0,0] -var SCREEN_AXIS = [0,0,0] -var OFFSET_VEC = [0,0,0] -var SHAPE = [1,1] + this.words[0] -= num; -function zeroVec(a) { - a[0] = a[1] = a[2] = 0 - return a -} + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } -function copyVec(a,b) { - a[0] = b[0] - a[1] = b[1] - a[2] = b[2] - return a -} + return this.strip(); +}; -function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) { - this.gl = gl - this.vertBuffer = vertBuffer - this.vao = vao - this.shader = shader - this.tickCount = tickCount - this.tickOffset = tickOffset - this.gridCount = gridCount - this.gridOffset = gridOffset -} +BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); +}; -var proto = Lines.prototype +BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); +}; -proto.bind = function(model, view, projection) { - this.shader.bind() - this.shader.uniforms.model = model - this.shader.uniforms.view = view - this.shader.uniforms.projection = projection +BN.prototype.iabs = function iabs() { + this.sign = false; + + return this; +}; - SHAPE[0] = this.gl.drawingBufferWidth - SHAPE[1] = this.gl.drawingBufferHeight +BN.prototype.abs = function abs() { + return this.clone().iabs(); +}; - this.shader.uniforms.screenShape = SHAPE - this.vao.bind() -} +BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + // Bigger storage is needed + var len = num.length + shift; + var i; + if (this.words.length < len) { + var t = new Array(len); + for (var i = 0; i < this.length; i++) + t[i] = this.words[i]; + this.words = t; + } else { + i = this.length; + } -proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) { - var minorAxis = zeroVec(MINOR_AXIS) - this.shader.uniforms.majorAxis = MINOR_AXIS + // Zeroify rest + this.length = Math.max(this.length, len); + for (; i < this.length; i++) + this.words[i] = 0; - minorAxis[j] = bounds[1][j] - bounds[0][j] - this.shader.uniforms.minorAxis = minorAxis + var carry = 0; + for (var i = 0; i < num.length; i++) { + var w = this.words[i + shift] + carry; + var right = num.words[i] * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + var w = this.words[i + shift] + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } - var noffset = copyVec(OFFSET_VEC, offset) - noffset[j] += bounds[0][j] - this.shader.uniforms.offset = noffset + if (carry === 0) + return this.strip(); - this.shader.uniforms.lineWidth = lineWidth + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (var i = 0; i < this.length; i++) { + var w = -this.words[i] + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.sign = true; - this.shader.uniforms.color = color + return this.strip(); +}; - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[(j+2)%3] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.vao.draw(this.gl.TRIANGLES, 6) +BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[(j+1)%3] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.vao.draw(this.gl.TRIANGLES, 6) -} + var a = this.clone(); + var b = num; -proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) { - if(!this.tickCount[j]) { - return + // Normalize + var bhi = b.words[b.length - 1]; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.shln(shift); + a.ishln(shift); + bhi = b.words[b.length - 1]; } - var majorAxis = zeroVec(MAJOR_AXIS) - majorAxis[j] = 1 - this.shader.uniforms.majorAxis = majorAxis - this.shader.uniforms.offset = offset - this.shader.uniforms.minorAxis = minorAxis - this.shader.uniforms.color = color - this.shader.uniforms.lineWidth = lineWidth - - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[j] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j]) -} + // Initialize quotient + var m = a.length - b.length; + var q; + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) + q.words[i] = 0; + } -proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) { - if(!this.gridCount[i]) { - return + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (!diff.sign) { + a = diff; + if (q) + q.words[m] = 1; } - var minorAxis = zeroVec(MINOR_AXIS) - minorAxis[j] = bounds[1][j] - bounds[0][j] - this.shader.uniforms.minorAxis = minorAxis + for (var j = m - 1; j >= 0; j--) { + var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1]; - var noffset = copyVec(OFFSET_VEC, offset) - noffset[j] += bounds[0][j] - this.shader.uniforms.offset = noffset + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); - var majorAxis = zeroVec(MAJOR_AXIS) - majorAxis[i] = 1 - this.shader.uniforms.majorAxis = majorAxis + a._ishlnsubmul(b, qj, j); + while (a.sign) { + qj--; + a.sign = false; + a._ishlnsubmul(b, 1, j); + if (a.cmpn(0) !== 0) + a.sign = !a.sign; + } + if (q) + q.words[j] = qj; + } + if (q) + q.strip(); + a.strip(); - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[i] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.shader.uniforms.lineWidth = lineWidth + // Denormalize + if (mode !== 'div' && shift !== 0) + a.ishrn(shift); + return { div: q ? q : null, mod: a }; +}; - this.shader.uniforms.color = color - this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i]) -} +BN.prototype.divmod = function divmod(num, mode) { + assert(num.cmpn(0) !== 0); -proto.drawZero = function(j, i, bounds, offset, color, lineWidth) { - var minorAxis = zeroVec(MINOR_AXIS) - this.shader.uniforms.majorAxis = minorAxis + if (this.sign && !num.sign) { + var res = this.neg().divmod(num, mode); + var div; + var mod; + if (mode !== 'mod') + div = res.div.neg(); + if (mode !== 'div') + mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); + return { + div: div, + mod: mod + }; + } else if (!this.sign && num.sign) { + var res = this.divmod(num.neg(), mode); + var div; + if (mode !== 'mod') + div = res.div.neg(); + return { div: div, mod: res.mod }; + } else if (this.sign && num.sign) { + return this.neg().divmod(num.neg(), mode); + } - minorAxis[j] = bounds[1][j] - bounds[0][j] - this.shader.uniforms.minorAxis = minorAxis + // Both numbers are positive at this point - var noffset = copyVec(OFFSET_VEC, offset) - noffset[j] += bounds[0][j] - this.shader.uniforms.offset = noffset + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) + return { div: new BN(0), mod: this }; - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[i] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.shader.uniforms.lineWidth = lineWidth + // Very short reduction + if (num.length === 1) { + if (mode === 'div') + return { div: this.divn(num.words[0]), mod: null }; + else if (mode === 'mod') + return { div: null, mod: new BN(this.modn(num.words[0])) }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } - this.shader.uniforms.color = color - this.vao.draw(this.gl.TRIANGLES, 6) -} + return this._wordDiv(num, mode); +}; -proto.dispose = function() { - this.vao.dispose() - this.vertBuffer.dispose() - this.shader.dispose() -} +// Find `this` / `num` +BN.prototype.div = function div(num) { + return this.divmod(num, 'div').div; +}; -function createLines(gl, bounds, ticks) { - var vertices = [] - var tickOffset = [0,0,0] - var tickCount = [0,0,0] +// Find `this` % `num` +BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod').mod; +}; - //Create grid lines for each axis/direction - var gridOffset = [0,0,0] - var gridCount = [0,0,0] +// Find Round(`this` / `num`) +BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); - //Add zero line - vertices.push( - 0,0,1, 0,1,1, 0,0,-1, - 0,0,-1, 0,1,1, 0,1,-1) + // Fast case - exact division + if (dm.mod.cmpn(0) === 0) + return dm.div; - for(var i=0; i<3; ++i) { - //Axis tick marks - var start = ((vertices.length / 3)|0) - for(var j=0; j= 0; i--) + acc = (p * acc + this.words[i]) % num; -var lineVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n" -var lineFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" -exports.line = function(gl) { - return createShader(gl, lineVert, lineFrag, null, [ - {name: 'position', type: 'vec3'} - ]) -} + return acc; +}; -var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}" -var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" -exports.text = function(gl) { - return createShader(gl, textVert, textFrag, null, [ - {name: 'position', type: 'vec3'} - ]) -} +// In-place division by number +BN.prototype.idivn = function idivn(num) { + assert(num <= 0x3ffffff); -var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}" -var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}" -exports.bg = function(gl) { - return createShader(gl, bgVert, bgFrag, null, [ - {name: 'position', type: 'vec3'}, - {name: 'normal', type: 'vec3'} - ]) -} + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = this.words[i] + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } -},{"gl-shader":197}],175:[function(require,module,exports){ -(function (process){ -"use strict" + return this.strip(); +}; -module.exports = createTextSprites +BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); +}; -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var vectorizeText = require('vectorize-text') -var createShader = require('./shaders').text +BN.prototype.egcd = function egcd(p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); -var globals = window || process.global || {} -var __TEXT_CACHE = globals.__TEXT_CACHE || {} -globals.__TEXT_CACHE = {} + var x = this; + var y = p.clone(); -//Vertex buffer format for text is: -// -/// [x,y,z] = Spatial coordinate -// + if (x.sign) + x = x.mod(p); + else + x = x.clone(); -var VERTEX_SIZE = 3 -var VERTEX_STRIDE = VERTEX_SIZE * 4 + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); -function TextSprites( - gl, - shader, - buffer, - vao) { - this.gl = gl - this.shader = shader - this.buffer = buffer - this.vao = vao - this.tickOffset = - this.tickCount = - this.labelOffset = - this.labelCount = null -} + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); -var proto = TextSprites.prototype + var g = 0; -//Bind textures for rendering -var SHAPE = [0,0] -proto.bind = function(model, view, projection, pixelScale) { - this.vao.bind() - this.shader.bind() - var uniforms = this.shader.uniforms - uniforms.model = model - uniforms.view = view - uniforms.projection = projection - uniforms.pixelScale = pixelScale - SHAPE[0] = this.gl.drawingBufferWidth - SHAPE[1] = this.gl.drawingBufferHeight - this.shader.uniforms.resolution = SHAPE -} + while (x.isEven() && y.isEven()) { + x.ishrn(1); + y.ishrn(1); + ++g; + } -proto.update = function(bounds, labels, labelFont, ticks, tickFont) { - var gl = this.gl - var data = [] + var yp = y.clone(); + var xp = x.clone(); - function addItem(t, text, font, size) { - var fontcache = __TEXT_CACHE[font] - if(!fontcache) { - fontcache = __TEXT_CACHE[font] = {} - } - var mesh = fontcache[text] - if(!mesh) { - mesh = fontcache[text] = tryVectorizeText(text, { - triangles: true, - font: font, - textAlign: 'center', - textBaseline: 'middle' - }) + while (x.cmpn(0) !== 0) { + while (x.isEven()) { + x.ishrn(1); + if (A.isEven() && B.isEven()) { + A.ishrn(1); + B.ishrn(1); + } else { + A.iadd(yp).ishrn(1); + B.isub(xp).ishrn(1); + } } - var scale = (size || 12) / 12 - var positions = mesh.positions - var cells = mesh.cells - var lo = [ Infinity, Infinity] - var hi = [-Infinity,-Infinity] - for(var i=0, nc=cells.length; i=0; --j) { - var p = positions[c[j]] - data.push(scale*p[0], -scale*p[1], t) + + while (y.isEven()) { + y.ishrn(1); + if (C.isEven() && D.isEven()) { + C.ishrn(1); + D.ishrn(1); + } else { + C.iadd(yp).ishrn(1); + D.isub(xp).ishrn(1); } } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } } - //Generate sprites for all 3 axes, store data in texture atlases - var tickOffset = [0,0,0] - var tickCount = [0,0,0] - var labelOffset = [0,0,0] - var labelCount = [0,0,0] - for(var d=0; d<3; ++d) { + return { + a: C, + b: D, + gcd: y.ishln(g) + }; +}; - //Generate label - labelOffset[d] = (data.length/VERTEX_SIZE)|0 - addItem(0.5*(bounds[0][d]+bounds[1][d]), labels[d], labelFont) - labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d] +// This is reduced incarnation of the binary EEA +// above, designated to invert members of the +// _prime_ fields F(p) at a maximal speed +BN.prototype._invmp = function _invmp(p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); - //Generate sprites for tick marks - tickOffset[d] = (data.length/VERTEX_SIZE)|0 - for(var i=0; i 0 && b.cmpn(1) > 0) { + while (a.isEven()) { + a.ishrn(1); + if (x1.isEven()) + x1.ishrn(1); + else + x1.iadd(delta).ishrn(1); + } + while (b.isEven()) { + b.ishrn(1); + if (x2.isEven()) + x2.ishrn(1); + else + x2.iadd(delta).ishrn(1); + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); } - tickCount[d] = ((data.length/VERTEX_SIZE)|0) - tickOffset[d] } + if (a.cmpn(1) === 0) + return x1; + else + return x2; +}; - this.buffer.update(data) - this.tickOffset = tickOffset - this.tickCount = tickCount - this.labelOffset = labelOffset - this.labelCount = labelCount -} - -//Draws the tick marks for an axis -var AXIS = [0,0,0] -proto.drawTicks = function(d, scale, angle, offset, color) { - if(!this.tickCount[d]) { - return - } +BN.prototype.gcd = function gcd(num) { + if (this.cmpn(0) === 0) + return num.clone(); + if (num.cmpn(0) === 0) + return this.clone(); - var v = AXIS - v[0] = v[1] = v[2] = 0 - v[d] = 1 - this.shader.uniforms.axis = v - this.shader.uniforms.color = color - this.shader.uniforms.angle = angle - this.shader.uniforms.scale = scale - this.shader.uniforms.offset = offset - this.vao.draw(this.gl.TRIANGLES, this.tickCount[d], this.tickOffset[d]) -} + var a = this.clone(); + var b = num.clone(); + a.sign = false; + b.sign = false; -//Draws the text label for an axis -var ZERO = [0,0,0] -proto.drawLabel = function(d, scale, angle, offset, color) { - if(!this.labelCount[d]) { - return + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.ishrn(1); + b.ishrn(1); } - this.shader.uniforms.axis = ZERO - this.shader.uniforms.color = color - this.shader.uniforms.angle = angle - this.shader.uniforms.scale = scale - this.shader.uniforms.offset = offset - this.vao.draw(this.gl.TRIANGLES, this.labelCount[d], this.labelOffset[d]) -} -//Releases all resources attached to this object -proto.dispose = function() { - this.shader.dispose() - this.vao.dispose() - this.buffer.dispose() -} + do { + while (a.isEven()) + a.ishrn(1); + while (b.isEven()) + b.ishrn(1); -function tryVectorizeText(text, options) { - try { - return vectorizeText(text, options) - } catch(e) { - console.warn('error vectorizing text:', e) - return { - cells: [], - positions: [] + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; } - } -} - -function createTextSprites( - gl, - bounds, - labels, - labelFont, - ticks, - tickFont) { - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { "buffer": buffer, - "size": 3 - } - ]) + a.isub(b); + } while (true); - var shader = createShader(gl) - shader.attributes.position.location = 0 + return b.ishln(shift); +}; - var result = new TextSprites( - gl, - shader, - buffer, - vao) +// Invert number in the field F(num) +BN.prototype.invm = function invm(num) { + return this.egcd(num).a.mod(num); +}; - result.update(bounds, labels, labelFont, ticks, tickFont) +BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; +}; - return result -} +BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; +}; -}).call(this,require('_process')) -},{"./shaders":174,"_process":56,"gl-buffer":118,"gl-vao":226,"vectorize-text":280}],176:[function(require,module,exports){ -'use strict' +// And first word and num +BN.prototype.andln = function andln(num) { + return this.words[0] & num; +}; -exports.create = defaultTicks -exports.equal = ticksEqual +// Increment at the bit position in-line +BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; -function prettyPrint(spacing, i) { - var stepStr = spacing + "" - var u = stepStr.indexOf(".") - var sigFigs = 0 - if(u >= 0) { - sigFigs = stepStr.length - u - 1 - } - var shift = Math.pow(10, sigFigs) - var x = Math.round(spacing * i * shift) - var xstr = x + "" - if(xstr.indexOf("e") >= 0) { - return xstr + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + for (var i = this.length; i < s + 1; i++) + this.words[i] = 0; + this.words[s] |= q; + this.length = s + 1; + return this; } - var xi = x / shift, xf = x % shift - if(x < 0) { - xi = -Math.ceil(xi)|0 - xf = (-xf)|0 - } else { - xi = Math.floor(xi)|0 - xf = xf|0 + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i]; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; } - var xis = "" + xi - if(x < 0) { - xis = "-" + xis + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - if(sigFigs) { - var xs = "" + xf - while(xs.length < sigFigs) { - xs = "0" + xs - } - return xis + "." + xs + return this; +}; + +BN.prototype.cmpn = function cmpn(num) { + var sign = num < 0; + if (sign) + num = -num; + + if (this.sign && !sign) + return -1; + else if (!this.sign && sign) + return 1; + + num &= 0x3ffffff; + this.strip(); + + var res; + if (this.length > 1) { + res = 1; } else { - return xis + var w = this.words[0]; + res = w === num ? 0 : w < num ? -1 : 1; } -} + if (this.sign) + res = -res; + return res; +}; -function defaultTicks(bounds, tickSpacing) { - var array = [] - for(var d=0; d<3; ++d) { - var ticks = [] - var m = 0.5*(bounds[0][d]+bounds[1][d]) - for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) { - ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) - } - for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) { - ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) - } - array.push(ticks) - } - return array -} +// Compare two numbers and return: +// 1 - if `this` > `num` +// 0 - if `this` == `num` +// -1 - if `this` < `num` +BN.prototype.cmp = function cmp(num) { + if (this.sign && !num.sign) + return -1; + else if (!this.sign && num.sign) + return 1; -function ticksEqual(ticksA, ticksB) { - for(var i=0; i<3; ++i) { - if(ticksA[i].length !== ticksB[i].length) { - return false - } - for(var j=0; j num.length) + return 1; + else if (this.length < num.length) + return -1; -function extractPlanes(M, zNear, zFar) { - var z = zNear || 0.0 - var zf = zFar || 1.0 - return [ - [ M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3] ], - [ M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3] ], - [ M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7] ], - [ M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7] ], - [ z*M[12] + M[8], z*M[13] + M[9], z*M[14] + M[10], z*M[15] + M[11] ], - [ zf*M[12] - M[8], zf*M[13] - M[9], zf*M[14] - M[10], zf*M[15] - M[11] ] - ] -} -},{}],178:[function(require,module,exports){ -"use strict" + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i]; + var b = num.words[i]; -var robustDot = require("robust-dot-product") -var robustSum = require("robust-sum") + if (a === b) + continue; + if (a < b) + res = -1; + else if (a > b) + res = 1; + break; + } + return res; +}; -module.exports = splitPolygon -module.exports.positive = positive -module.exports.negative = negative +// +// A reduce context, could be using montgomery or something better, depending +// on the `m` itself. +// +BN.red = function red(num) { + return new Red(num); +}; -function planeT(p, plane) { - var r = robustSum(robustDot(p, plane), [plane[plane.length-1]]) - return r[r.length-1] -} +BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(!this.sign, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); +}; +BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); +}; -//Can't do this exactly and emit a floating point result -function lerpW(a, wa, b, wb) { - var d = wb - wa - var t = -wa / d - if(t < 0.0) { - t = 0.0 - } else if(t > 1.0) { - t = 1.0 - } - var ti = 1.0 - t - var n = a.length - var r = new Array(n) - for(var i=0; i 0) || (a > 0 && b < 0)) { - var p = lerpW(s, b, t, a) - pos.push(p) - neg.push(p.slice()) - } - if(b < 0) { - neg.push(t.slice()) - } else if(b > 0) { - pos.push(t.slice()) - } else { - pos.push(t.slice()) - neg.push(t.slice()) - } - a = b - } - return { positive: pos, negative: neg } -} +BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); +}; -function positive(points, plane) { - var pos = [] - var a = planeT(points[points.length-1], plane) - for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { - pos.push(lerpW(s, b, t, a)) - } - if(b >= 0) { - pos.push(t.slice()) - } - a = b - } - return pos -} +BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); +}; -function negative(points, plane) { - var neg = [] - var a = planeT(points[points.length-1], plane) - for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { - neg.push(lerpW(s, b, t, a)) - } - if(b <= 0) { - neg.push(t.slice()) - } - a = b - } - return neg -} -},{"robust-dot-product":179,"robust-sum":262}],179:[function(require,module,exports){ -"use strict" +BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); +}; -var twoProduct = require("two-product") -var robustSum = require("robust-sum") +BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); +}; -module.exports = robustDotProduct +BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); +}; -function robustDotProduct(a, b) { - var r = twoProduct(a[0], b[0]) - for(var i=1; i this.n); - //Calculate the following properties for each axis: - // - // * lo - start of visible range for each axis in tick coordinates - // * hi - end of visible range for each axis in tick coordinates - // * ticksPerPixel - pixel density of tick marks for the axis - // - var ranges = RANGES - for(var i=0; i<3; ++i) { - ranges[i].lo = Infinity - ranges[i].hi = -Infinity - ranges[i].pixelsPerDataUnit = Infinity + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); } - //Compute frustum planes, intersect with box - var frustum = getPlanes(m4transpose(mvp, mvp)) - m4transpose(mvp, mvp) - - //Loop over vertices of viewable box - for(var d=0; d<3; ++d) { - var u = (d+1)%3 - var v = (d+2)%3 - var x = SCRATCH_X -i_loop: - for(var i=0; i<2; ++i) { - var poly = [] - - if((axis[d] < 0) === !!i) { - continue - } + return r; +}; - x[d] = bounds[i][d] - for(var j=0; j<2; ++j) { - x[u] = bounds[j^i][u] - for(var k=0; k<2; ++k) { - x[v] = bounds[k^j^i][v] - poly.push(x.slice()) - } - } - for(var j=0; j>> 22); + prev = next; + } + input.words[i - 10] = prev >>> 22; + input.length -= 9; +}; -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders/index') +K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; -module.exports = createSpikes + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var hi; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i]; + hi = w * 0x40; + lo += w * 0x3d1; + hi += (lo / 0x4000000) | 0; + lo &= 0x3ffffff; -var identity = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] + num.words[i] = lo; -function AxisSpikes(gl, buffer, vao, shader) { - this.gl = gl - this.buffer = buffer - this.vao = vao - this.shader = shader - this.pixelRatio = 1 - this.bounds = [[-1000,-1000,-1000], [1000,1000,1000]] - this.position = [0,0,0] - this.lineWidth = [2,2,2] - this.colors = [[0,0,0,1], [0,0,0,1], [0,0,0,1]] - this.enabled = [true,true,true] - this.drawSides = [true,true,true] - this.axes = null -} + lo = hi; + } -var proto = AxisSpikes.prototype + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) + num.length--; + } + return num; +}; -var OUTER_FACE = [0,0,0] -var INNER_FACE = [0,0,0] +function P224() { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); +} +inherits(P224, MPrime); -var SHAPE = [0,0] +function P192() { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +} +inherits(P192, MPrime); -proto.isTransparent = function() { - return false +function P25519() { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } +inherits(P25519, MPrime); -proto.drawTransparent = function(camera) {} +P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = num.words[i] * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; -proto.draw = function(camera) { - var gl = this.gl - var vao = this.vao - var shader = this.shader + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) + num.words[num.length++] = carry; + return num; +}; - vao.bind() - shader.bind() +// Exported mostly for testing purposes, use plain name instead +BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) + return primes[name]; - var model = camera.model || identity - var view = camera.view || identity - var projection = camera.projection || identity + var prime; + if (name === 'k256') + prime = new K256(); + else if (name === 'p224') + prime = new P224(); + else if (name === 'p192') + prime = new P192(); + else if (name === 'p25519') + prime = new P25519(); + else + throw new Error('Unknown prime ' + name); + primes[name] = prime; - var axis - if(this.axes) { - axis = this.axes.lastCubeProps.axis - } + return prime; +}; - var outerFace = OUTER_FACE - var innerFace = INNER_FACE - for(var i=0; i<3; ++i) { - if(axis && axis[i] < 0) { - outerFace[i] = this.bounds[0][i] - innerFace[i] = this.bounds[1][i] - } else { - outerFace[i] = this.bounds[1][i] - innerFace[i] = this.bounds[0][i] - } +// +// Base reduction engine +// +function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; } +} - SHAPE[0] = gl.drawingBufferWidth - SHAPE[1] = gl.drawingBufferHeight +Red.prototype._verify1 = function _verify1(a) { + assert(!a.sign, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); +}; - shader.uniforms.model = model - shader.uniforms.view = view - shader.uniforms.projection = projection - shader.uniforms.coordinates = [this.position, outerFace, innerFace] - shader.uniforms.colors = this.colors - shader.uniforms.screenShape = SHAPE +Red.prototype._verify2 = function _verify2(a, b) { + assert(!a.sign && !b.sign, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); +}; - for(var i=0; i<3; ++i) { - shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio - if(this.enabled[i]) { - vao.draw(gl.TRIANGLES, 6, 6*i) - if(this.drawSides[i]) { - vao.draw(gl.TRIANGLES, 12, 18+12*i) - } - } - } +Red.prototype.imod = function imod(a) { + if (this.prime) + return this.prime.ireduce(a)._forceRed(this); + return a.mod(this.m)._forceRed(this); +}; - vao.unbind() -} +Red.prototype.neg = function neg(a) { + var r = a.clone(); + r.sign = !r.sign; + return r.iadd(this.m)._forceRed(this); +}; -proto.update = function(options) { - if(!options) { - return - } - if("bounds" in options) { - this.bounds = options.bounds - } - if("position" in options) { - this.position = options.position - } - if("lineWidth" in options) { - this.lineWidth = options.lineWidth - } - if("colors" in options) { - this.colors = options.colors - } - if("enabled" in options) { - this.enabled = options.enabled - } - if("drawSides" in options) { - this.drawSides = options.drawSides - } -} +Red.prototype.add = function add(a, b) { + this._verify2(a, b); -proto.dispose = function() { - this.vao.dispose() - this.buffer.dispose() - this.shader.dispose() -} + var res = a.add(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res._forceRed(this); +}; +Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res; +}; -function createSpikes(gl, options) { - //Create buffers - var data = [ ] +Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); - function line(x,y,z,i,l,h) { - var row = [x,y,z, 0,0,0, 1] - row[i+3] = 1 - row[i] = l - data.push.apply(data, row) - row[6] = -1 - data.push.apply(data, row) - row[i] = h - data.push.apply(data, row) - data.push.apply(data, row) - row[6] = 1 - data.push.apply(data, row) - row[i] = l - data.push.apply(data, row) - } + var res = a.sub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res._forceRed(this); +}; - line(0,0,0, 0, 0, 1) - line(0,0,0, 1, 0, 1) - line(0,0,0, 2, 0, 1) +Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); - line(1,0,0, 1, -1,1) - line(1,0,0, 2, -1,1) + var res = a.isub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res; +}; - line(0,1,0, 0, -1,1) - line(0,1,0, 2, -1,1) +Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.shln(num)); +}; - line(0,0,1, 0, -1,1) - line(0,0,1, 1, -1,1) +Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); +}; - var buffer = createBuffer(gl, data) - var vao = createVAO(gl, [{ - type: gl.FLOAT, - buffer: buffer, - size: 3, - offset: 0, - stride: 28 - }, { - type: gl.FLOAT, - buffer: buffer, - size: 3, - offset: 12, - stride: 28 - }, { - type: gl.FLOAT, - buffer: buffer, - size: 1, - offset: 24, - stride: 28 - }]) +Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); +}; - //Create shader - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.color.location = 1 - shader.attributes.weight.location = 2 +Red.prototype.isqr = function isqr(a) { + return this.imul(a, a); +}; - //Create spike object - var spikes = new AxisSpikes(gl, buffer, vao, shader) +Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); +}; - //Set parameters - spikes.update(options) +Red.prototype.sqrt = function sqrt(a) { + if (a.cmpn(0) === 0) + return a.clone(); - //Return resulting object - return spikes -} + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); -},{"./shaders/index":181,"gl-buffer":118,"gl-vao":226}],183:[function(require,module,exports){ -'use strict' + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).ishrn(2); + var r = this.pow(a, pow); + return r; + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (q.cmpn(0) !== 0 && q.andln(1) === 0) { + s++; + q.ishrn(1); + } + assert(q.cmpn(0) !== 0); -module.exports = createScene + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); -var createCamera = require('3d-view-controls') -var createAxes = require('gl-axes3d') -var axesRanges = require('gl-axes3d/properties') -var createSpikes = require('gl-spikes3d') -var createSelect = require('gl-select-static') -var createFBO = require('gl-fbo') -var drawTriangle = require('a-big-triangle') -var mouseChange = require('mouse-change') -var perspective = require('gl-mat4/perspective') -var createShader = require('./lib/shader') + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).ishrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) + z.redIAdd(nOne); -function MouseSelect() { - this.mouse = [-1,-1] - this.screen = null - this.distance = Infinity - this.index = null - this.dataCoordinate = null - this.dataPosition = null - this.object = null - this.data = null -} + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).ishrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) + tmp = tmp.redSqr(); + assert(i < m); + var b = this.pow(c, new BN(1).ishln(m - i - 1)); -function getContext(canvas, options) { - var gl = null - try { - gl = canvas.getContext('webgl', options) - if(!gl) { - gl = canvas.getContext('experimental-webgl', options) - } - } catch(e) { - return null + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; } - return gl -} -function roundUpPow10(x) { - var y = Math.round(Math.log(Math.abs(x)) / Math.log(10)) - if(y < 0) { - var base = Math.round(Math.pow(10, -y)) - return Math.ceil(x*base) / base - } else if(y > 0) { - var base = Math.round(Math.pow(10, y)) - return Math.ceil(x/base) * base - } - return Math.ceil(x) -} + return r; +}; -function defaultBool(x) { - if(typeof x === 'boolean') { - return x +Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.sign) { + inv.sign = false; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); } - return true -} +}; -function createScene(options) { - options = options || {} +Red.prototype.pow = function pow(a, num) { + var w = []; - var stopped = false + if (num.cmpn(0) === 0) + return new BN(1); - var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio) + var q = num.clone(); - var canvas = options.canvas - if(!canvas) { - canvas = document.createElement('canvas') - if(options.container) { - var container = options.container - container.appendChild(canvas) - } else { - document.body.appendChild(canvas) - } + while (q.cmpn(0) !== 0) { + w.push(q.andln(1)); + q.ishrn(1); } - var gl = options.gl - if(!gl) { - gl = getContext(canvas, - options.glOptions || { - premultipliedAlpha: true, - antialias: true - }) - } - if(!gl) { - throw new Error('webgl not supported') + // Skip leading zeroes + var res = a; + for (var i = 0; i < w.length; i++, res = this.sqr(res)) + if (w[i] !== 0) + break; + + if (++i < w.length) { + for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { + if (w[i] === 0) + continue; + res = this.mul(res, q); + } } - //Initial bounds - var bounds = options.bounds || [[-10,-10,-10], [10,10,10]] + return res; +}; - //Create selection - var selection = new MouseSelect() +Red.prototype.convertTo = function convertTo(num) { + var r = num.mod(this.m); + if (r === num) + return r.clone(); + else + return r; +}; - //Accumulation buffer - var accumBuffer = createFBO(gl, - [gl.drawingBufferWidth, gl.drawingBufferHeight], { - preferFloat: true - }) +Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; +}; - var accumShader = createShader(gl) +// +// Montgomery method engine +// - //Create a camera - var cameraOptions = options.camera || { - eye: [2,0,0], - center: [0,0,0], - up: [0,1,0], - zoomMin: 0.1, - zoomMax: 100, - mode: 'turntable' - } +BN.mont = function mont(num) { + return new Mont(num); +}; - //Create axes - var axesOptions = options.axes || {} - var axes = createAxes(gl, axesOptions) - axes.enable = !axesOptions.disable +function Mont(m) { + Red.call(this, m); - //Create spikes - var spikeOptions = options.spikes || {} - var spikes = createSpikes(gl, spikeOptions) + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) + this.shift += 26 - (this.shift % 26); + this.r = new BN(1).ishln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - //Object list is empty initially - var objects = [] - var pickBufferIds = [] - var pickBufferCount = [] - var pickBuffers = [] + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv.sign = true; + this.minv = this.minv.mod(this.r); +} +inherits(Mont, Red); - //Dirty flag, skip redraw if scene static - var dirty = true - var pickDirty = true +Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.shln(this.shift)); +}; - var projection = new Array(16) - var model = new Array(16) +Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; +}; - var cameraParams = { - view: null, - projection: projection, - model: model +Mont.prototype.imul = function imul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { + a.words[0] = 0; + a.length = 1; + return a; } - var pickDirty = true + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); - var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ] + return res._forceRed(this); +}; - //Create scene object - var scene = { - gl: gl, - contextLost: false, - pixelRatio: options.pixelRatio || parseFloat(window.devicePixelRatio), - canvas: canvas, - selection: selection, - camera: createCamera(canvas, cameraOptions), - axes: axes, - axesPixels: null, - spikes: spikes, - bounds: bounds, - objects: objects, - shape: viewShape, - aspect: options.aspectRatio || [1,1,1], - pickRadius: options.pickRadius || 10, - zNear: options.zNear || 0.01, - zFar: options.zFar || 1000, - fovy: options.fovy || Math.PI/4, - clearColor: options.clearColor || [0,0,0,0], - autoResize: defaultBool(options.autoResize), - autoBounds: defaultBool(options.autoBounds), - autoScale: !!options.autoScale, - autoCenter: defaultBool(options.autoCenter), - clipToBounds: defaultBool(options.clipToBounds), - snapToData: !!options.snapToData, - onselect: options.onselect || null, - onrender: options.onrender || null, - onclick: options.onclick || null, - cameraParams: cameraParams, - oncontextloss: null, - mouseListener: null - } +Mont.prototype.mul = function mul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) + return new BN(0)._forceRed(this); - var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ] + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); - function resizeListener() { - if(stopped) { - return + return res._forceRed(this); +}; + +Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); +}; + +})(typeof module === 'undefined' || module, this); + +},{}],384:[function(require,module,exports){ +(function (Buffer){ +var hasTypedArrays = false +if(typeof Float64Array !== "undefined") { + var DOUBLE_VIEW = new Float64Array(1) + , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) + DOUBLE_VIEW[0] = 1.0 + hasTypedArrays = true + if(UINT_VIEW[1] === 0x3ff00000) { + //Use little endian + module.exports = function doubleBitsLE(n) { + DOUBLE_VIEW[0] = n + return [ UINT_VIEW[0], UINT_VIEW[1] ] } - if(!scene.autoResize) { - return + function toDoubleLE(lo, hi) { + UINT_VIEW[0] = lo + UINT_VIEW[1] = hi + return DOUBLE_VIEW[0] } - var parent = canvas.parentNode - var width = 1 - var height = 1 - if(parent && parent !== document.body) { - width = parent.clientWidth - height = parent.clientHeight - } else { - width = window.innerWidth - height = window.innerHeight + module.exports.pack = toDoubleLE + function lowUintLE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[0] } - var nextWidth = Math.ceil(width * scene.pixelRatio)|0 - var nextHeight = Math.ceil(height * scene.pixelRatio)|0 - if(nextWidth !== canvas.width || nextHeight !== canvas.height) { - canvas.width = nextWidth - canvas.height = nextHeight - var style = canvas.style - style.position = style.position || 'absolute' - style.left = '0px' - style.top = '0px' - style.width = width + 'px' - style.height = height + 'px' - dirty = true + module.exports.lo = lowUintLE + function highUintLE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[1] } - } - if(scene.autoResize) { - resizeListener() - } - window.addEventListener('resize', resizeListener) - - function reallocPickIds() { - var numObjs = objects.length - var numPick = pickBuffers.length - for(var i=0; i 0 && pickBufferCount[numPick-1] === 0) { - pickBufferCount.pop() - pickBuffers.pop().dispose() + module.exports.pack = toDoubleBE + function lowUintBE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[1] } - } - - scene.update = function(options) { - if(stopped) { - return + module.exports.lo = lowUintBE + function highUintBE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[0] } - options = options || {} - dirty = true - pickDirty = true + module.exports.hi = highUintBE + } else { + hasTypedArrays = false } - - scene.add = function(obj) { - if(stopped) { - return - } - obj.axes = axes - objects.push(obj) - pickBufferIds.push(-1) - dirty = true - pickDirty = true - reallocPickIds() +} +if(!hasTypedArrays) { + var buffer = new Buffer(8) + module.exports = function doubleBits(n) { + buffer.writeDoubleLE(n, 0, true) + return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] } - - scene.remove = function(obj) { - if(stopped) { - return - } - var idx = objects.indexOf(obj) - if(idx < 0) { - return - } - objects.splice(idx, 1) - pickBufferIds.pop() - dirty = true - pickDirty = true - reallocPickIds() + function toDouble(lo, hi) { + buffer.writeUInt32LE(lo, 0, true) + buffer.writeUInt32LE(hi, 4, true) + return buffer.readDoubleLE(0, true) + } + module.exports.pack = toDouble + function lowUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(0, true) + } + module.exports.lo = lowUint + function highUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(4, true) } + module.exports.hi = highUint +} - scene.dispose = function() { - if(stopped) { - return - } +module.exports.sign = function(n) { + return module.exports.hi(n) >>> 31 +} - stopped = true +module.exports.exponent = function(n) { + var b = module.exports.hi(n) + return ((b<<1) >>> 21) - 1023 +} - window.removeEventListener('resize', resizeListener) - canvas.removeEventListener('webglcontextlost', checkContextLoss) - scene.mouseListener.enabled = false +module.exports.fraction = function(n) { + var lo = module.exports.lo(n) + var hi = module.exports.hi(n) + var b = hi & ((1<<20) - 1) + if(hi & 0x7ff00000) { + b += (1<<20) + } + return [lo, b] +} - if(scene.contextLost) { - return - } +module.exports.denormalized = function(n) { + var hi = module.exports.hi(n) + return !(hi & 0x7ff00000) +} +}).call(this,require("buffer").Buffer) +},{"buffer":65}],385:[function(require,module,exports){ +'use strict' - //Destroy objects - axes.dispose() - spikes.dispose() - for(var i=0; i selection.distance) { - continue - } - for(var j=0; j>>1 + if(d <= 0) { + return + } - //Tick camera - var cameraMoved = scene.camera.tick() - cameraParams.view = scene.camera.matrix - dirty = dirty || cameraMoved - pickDirty = pickDirty || cameraMoved + var retval - //Set pixel ratio - axes.pixelRatio = scene.pixelRatio - spikes.pixelRatio = scene.pixelRatio + //Convert red boxes + var redList = pool.mallocDouble(2*d*n) + var redIds = pool.mallocInt32(n) + n = convertBoxes(red, d, redList, redIds) - //Check if any objects changed, recalculate bounds - var numObjs = objects.length - var lo = nBounds[0] - var hi = nBounds[1] - lo[0] = lo[1] = lo[2] = Infinity - hi[0] = hi[1] = hi[2] = -Infinity - for(var i=0; i 0) { + if(d === 1 && full) { + //Special case: 1d complete + sweep.init(n) + retval = sweep.sweepComplete( + d, visit, + 0, n, redList, redIds, + 0, n, redList, redIds) + } else { - //Set the axes properties for each object - obj.pixelRatio = scene.pixelRatio - obj.axes = scene.axes + //Convert blue boxes + var blueList = pool.mallocDouble(2*d*m) + var blueIds = pool.mallocInt32(m) + m = convertBoxes(blue, d, blueList, blueIds) - dirty = dirty || !!obj.dirty - pickDirty = pickDirty || !!obj.dirty - var obb = obj.bounds - if(obb) { - var olo = obb[0] - var ohi = obb[1] - for(var j=0; j<3; ++j) { - lo[j] = Math.min(lo[j], olo[j]) - hi[j] = Math.max(hi[j], ohi[j]) - } - } - } + if(m > 0) { + sweep.init(n+m) - //Recalculate bounds - var bounds = scene.bounds - if(scene.autoBounds) { - for(var j=0; j<3; ++j) { - if(hi[j] < lo[j]) { - lo[j] = -1 - hi[j] = 1 + if(d === 1) { + //Special case: 1d bipartite + retval = sweep.sweepBipartite( + d, visit, + 0, n, redList, redIds, + 0, m, blueList, blueIds) } else { - if(lo[j] === hi[j]) { - lo[j] -= 1 - hi[j] += 1 - } - var padding = 0.05 * (hi[j] - lo[j]) - lo[j] = lo[j] - padding - hi[j] = hi[j] + padding + //General case: d>1 + retval = boxIntersectIter( + d, visit, full, + n, redList, redIds, + m, blueList, blueIds) } - bounds[0][j] = lo[j] - bounds[1][j] = hi[j] - } - } - - var boundsChanged = false - for(var j=0; j<3; ++j) { - boundsChanged = boundsChanged || - (prevBounds[0][j] !== bounds[0][j]) || - (prevBounds[1][j] !== bounds[1][j]) - prevBounds[0][j] = bounds[0][j] - prevBounds[1][j] = bounds[1][j] - } - if(boundsChanged) { - var tickSpacing = [0,0,0] - for(var i=0; i<3; ++i) { - tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0) - } - if(axes.autoTicks) { - axes.update({ - bounds: bounds, - tickSpacing: tickSpacing - }) - } else { - axes.update({ - bounds: bounds - }) + pool.free(blueList) + pool.free(blueIds) } } - //Recalculate bounds - pickDirty = pickDirty || boundsChanged - dirty = dirty || boundsChanged - - //Get scene - var width = gl.drawingBufferWidth - var height = gl.drawingBufferHeight - viewShape[0] = width - viewShape[1] = height - pickShape[0] = Math.max(width/scene.pixelRatio, 1)|0 - pickShape[1] = Math.max(height/scene.pixelRatio, 1)|0 - - //Compute camera parameters - perspective(projection, - scene.fovy, - width/height, - scene.zNear, - scene.zFar) + pool.free(redList) + pool.free(redIds) + } - //Compute model matrix - for(var i=0; i<16; ++i) { - model[i] = 0 - } - model[15] = 1 + return retval +} - var maxS = 0 - for(var i=0; i<3; ++i) { - maxS = Math.max(maxS, bounds[1][i] - bounds[0][i]) - } - for(var i=0; i<3; ++i) { - if(scene.autoScale) { - model[5*i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i]) - } else { - model[5*i] = 1 / maxS - } - if(scene.autoCenter) { - model[12+i] = -model[5*i] * 0.5 * (bounds[0][i] + bounds[1][i]) - } - } +var RESULT - //Apply axes/clip bounds - for(var i=0; i' + + BLUE_END + '-' + BLUE_START + '){') + if(full) { + invoke(true, false) + code.push('}else{') + invoke(false, false) + } else { + code.push('if(' + FLIP + '){') + invoke(true, true) + code.push('}else{') + invoke(true, false) + code.push('}}else{if(' + FLIP + '){') + invoke(false, true) + code.push('}else{') + invoke(false, false) + code.push('}') + } + code.push('}}return ' + funcName) -module.exports = { - vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", - fragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n", - pickVertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", - pickFragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n" + var codeStr = prefix.join('') + code.join('') + var proc = new Function(codeStr) + return proc() } -},{}],185:[function(require,module,exports){ + +exports.partial = bruteForcePlanner(false) +exports.full = bruteForcePlanner(true) +},{}],390:[function(require,module,exports){ 'use strict' -module.exports = createFancyScatter2D +module.exports = boxIntersectIter -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var textCache = require('text-cache') var pool = require('typedarray-pool') -var vectorizeText = require('vectorize-text') -var shaders = require('./lib/shaders') - -var BOUNDARIES = {} - -function getBoundary(glyph) { - if(glyph in BOUNDARIES) { - return BOUNDARIES[glyph] - } +var bits = require('bit-twiddle') +var bruteForce = require('./brute') +var bruteForcePartial = bruteForce.partial +var bruteForceFull = bruteForce.full +var sweep = require('./sweep') +var findMedian = require('./median') +var genPartition = require('./partition') - var polys = vectorizeText(glyph, { - polygons: true, - font: 'sans-serif', - textAlign: 'left', - textBaseline: 'alphabetic' - }) +//Twiddle parameters +var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search +var SCAN_CUTOFF = (1<<22) //Cut off for two way scan +var SCAN_COMPLETE_CUTOFF = (1<<22) - var coords = [] - var normals = [] +//Partition functions +var partitionInteriorContainsInterval = genPartition( + '!(lo>=p0)&&!(p1>=hi)', + ['p0', 'p1']) - polys.forEach(function(loops) { - loops.forEach(function(loop) { - for(var i=0; i 0) { + top -= 1 - proto.drawPick = function(offset) { - var plot = this.plot - var shader = this.pickShader - var numVertices = this.numVertices + var iptr = top * IFRAME_SIZE + var axis = BOX_ISTACK[iptr] + var redStart = BOX_ISTACK[iptr+1] + var redEnd = BOX_ISTACK[iptr+2] + var blueStart = BOX_ISTACK[iptr+3] + var blueEnd = BOX_ISTACK[iptr+4] + var state = BOX_ISTACK[iptr+5] - var gl = plot.gl + var dptr = top * DFRAME_SIZE + var lo = BOX_DSTACK[dptr] + var hi = BOX_DSTACK[dptr+1] - this.pickOffset = offset + //Unpack state info + var flip = (state & 1) + var full = !!(state & 16) - if(!numVertices) { - return offset + //Unpack indices + var red = xBoxes + var redIndex = xIndex + var blue = yBoxes + var blueIndex = yIndex + if(flip) { + red = yBoxes + redIndex = yIndex + blue = xBoxes + blueIndex = xIndex } - for(var i=0; i<4; ++i) { - PICK_OFFSET[i] = ((offset>>(i*8)) & 0xff) + if(state & 2) { + redEnd = partitionStartLessThan( + d, axis, + redStart, redEnd, red, redIndex, + hi) + if(redStart >= redEnd) { + continue + } + } + if(state & 4) { + redStart = partitionEndLessThanEqual( + d, axis, + redStart, redEnd, red, redIndex, + lo) + if(redStart >= redEnd) { + continue + } + } + + var redCount = redEnd - redStart + var blueCount = blueEnd - blueStart + + if(full) { + if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { + retval = sweep.scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } + } else { + if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { + //If input small, then use brute force + retval = bruteForcePartial( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } else if(d * redCount * blueCount < SCAN_CUTOFF) { + //If input medium sized, then use sweep and prune + retval = sweep.scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } } + + //First, find all red intervals whose interior contains (lo,hi) + var red0 = partitionInteriorContainsInterval( + d, axis, + redStart, redEnd, red, redIndex, + lo, hi) - calcScales.call(this) - - shader.bind() + //Lower dimensional case + if(redStart < red0) { - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.viewTransform = MATRIX - shader.uniforms.pickOffset = PICK_OFFSET + if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { + //Special case for small inputs: use brute force + retval = bruteForceFull( + d, axis+1, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } else if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blueStart, blueEnd, blue, blueIndex, + redStart, red0, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + } + if(retval !== void 0) { + return retval + } + } else { + iterPush(top++, + axis+1, + redStart, red0, + blueStart, blueEnd, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blueStart, blueEnd, + redStart, red0, + flip^1, + -Infinity, Infinity) + } + } - this.positionBuffer.bind() - shader.attributes.position.pointer() + //Divide and conquer phase + if(red0 < redEnd) { - this.offsetBuffer.bind() - shader.attributes.offset.pointer() + //Cut blue into 3 parts: + // + // Points < mid point + // Points = mid point + // Points > mid point + // + var blue0 = findMedian( + d, axis, + blueStart, blueEnd, blue, blueIndex) + var mid = blue[elemSize * blue0 + axis] + var blue1 = partitionStartEqual( + d, axis, + blue0, blueEnd, blue, blueIndex, + mid) - this.idBuffer.bind() - shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false) + //Right case + if(blue1 < blueEnd) { + iterPush(top++, + axis, + red0, redEnd, + blue1, blueEnd, + (flip|4) + (full ? 16 : 0), + mid, hi) + } - gl.drawArrays(gl.TRIANGLES, 0, numVertices) + //Left case + if(blueStart < blue0) { + iterPush(top++, + axis, + red0, redEnd, + blueStart, blue0, + (flip|2) + (full ? 16 : 0), + lo, mid) + } - return offset + this.numPoints - } -})() + //Center case (the hard part) + if(blue0 + 1 === blue1) { + //Optimization: Range with exactly 1 point, use a brute force scan + if(full) { + retval = onePointFull( + d, axis, visit, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) + } else { + retval = onePointPartial( + d, axis, visit, flip, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) + } + if(retval !== void 0) { + return retval + } + } else if(blue0 < blue1) { + var red1 + if(full) { + //If full intersection, need to handle special case + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + if(red0 < red1) { + var redX = partitionStartEqual( + d, axis, + red0, red1, red, redIndex, + mid) + if(axis === d-2) { + //Degenerate sweep intersection: + // [red0, redX] with [blue0, blue1] + if(red0 < redX) { + retval = sweep.sweepComplete( + d, visit, + red0, redX, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.numPoints - if(value < pickOffset || value >= pickOffset + pointCount) { - return null - } - var pointId = value - pickOffset - var points = this.points - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + //Normal sweep intersection: + // [redX, red1] with [blue0, blue1] + if(redX < red1) { + retval = sweep.sweepBipartite( + d, visit, + redX, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } + } else { + if(red0 < redX) { + iterPush(top++, + axis+1, + red0, redX, + blue0, blue1, + 16, + -Infinity, Infinity) + } + if(redX < red1) { + iterPush(top++, + axis+1, + redX, red1, + blue0, blue1, + 0, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + redX, red1, + 1, + -Infinity, Infinity) + } + } + } + } else { + if(flip) { + red1 = partitionContainsPointProper( + d, axis, + red0, redEnd, red, redIndex, + mid) + } else { + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + } + if(red0 < red1) { + if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blue0, blue1, blue, blueIndex, + red0, red1, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + red0, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + } + } else { + iterPush(top++, + axis+1, + red0, red1, + blue0, blue1, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + red0, red1, + flip^1, + -Infinity, Infinity) + } + } + } + } + } } } +},{"./brute":389,"./median":391,"./partition":392,"./sweep":394,"bit-twiddle":395,"typedarray-pool":397}],391:[function(require,module,exports){ +'use strict' -proto.update = function(options) { - options = options || {} +module.exports = findMedian - var positions = options.positions || [] - var colors = options.colors || [] - var glyphs = options.glyphs || [] - var sizes = options.sizes || [] - var borderWidths = options.borderWidths || [] - var borderColors = options.borderColors || [] +var genPartition = require('./partition') - this.points = positions +var partitionStartLessThan = genPartition('lo> 1 - for(var j=0; j<2; ++j) { - bounds[j] = Math.min(bounds[j], positions[2*i+j]) - bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j]) +var PARTITION_THRESHOLD = 8 //Cut off for using insertion sort in findMedian + +//Base case for median finding: Use insertion sort +function insertionSort(d, axis, start, end, boxes, ids) { + var elemSize = 2 * d + var boxPtr = elemSize * (start+1) + axis + for(var i=start+1; istart && boxes[ptr+axis] > x; + --j, ptr-=elemSize) { + //Swap + var aPtr = ptr + var bPtr = ptr+elemSize + for(var k=0; k>> 1) + var elemSize = 2*d + var pivot = mid + var value = boxes[elemSize*mid+axis] + + while(lo < hi) { + if(hi - lo < PARTITION_THRESHOLD) { + insertionSort(d, axis, lo, hi, boxes, ids) + value = boxes[elemSize*mid+axis] + break + } + + //Select pivot using median-of-3 + var count = hi - lo + var pivot0 = (Math.random()*count+lo)|0 + var value0 = boxes[elemSize*pivot0 + axis] + var pivot1 = (Math.random()*count+lo)|0 + var value1 = boxes[elemSize*pivot1 + axis] + var pivot2 = (Math.random()*count+lo)|0 + var value2 = boxes[elemSize*pivot2 + axis] + if(value0 <= value1) { + if(value2 >= value1) { + pivot = pivot1 + value = value1 + } else if(value0 >= value2) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } + } else { + if(value1 >= value2) { + pivot = pivot1 + value = value1 + } else if(value2 >= value0) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } + } - ptr += 1 + //Swap pivot to end of array + var aPtr = elemSize * (hi-1) + var bPtr = elemSize * pivot + for(var i=0; i= 0) { + reads.push('lo=e[k+n]') + } + if(predicate.indexOf('hi') >= 0) { + reads.push('hi=e[k+o]') + } + fargs.push( + code.replace('_', reads.join()) + .replace('$', predicate)) + return Function.apply(void 0, fargs) } +},{}],393:[function(require,module,exports){ +'use strict'; -},{"./lib/shaders":184,"gl-buffer":118,"gl-shader":197,"text-cache":273,"typedarray-pool":278,"vectorize-text":280}],186:[function(require,module,exports){ - - -exports.pointVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute float weight;\n\nuniform mat3 matrix;\nuniform float pointSize, useWeight;\n\nvarying float fragWeight;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n fragWeight = mix(1.0, weight, useWeight);\n}\n" -exports.pointFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\n\nvarying float fragWeight;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, fragWeight);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n" -exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n" -exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n" - -},{}],187:[function(require,module,exports){ -arguments[4][62][0].apply(exports,arguments) -},{"dup":62}],188:[function(require,module,exports){ -'use strict' +//This code is extracted from ndarray-sort +//It is inlined here as a temporary workaround -module.exports = sortLevels +module.exports = wrapper; var INSERT_SORT_CUTOFF = 32 -function sortLevels(data_levels, data_points, data_ids, data_weights, n0) { +function wrapper(data, n0) { if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) + insertionSort(0, n0 - 1, data); } else { - quickSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) + quickSort(0, n0 - 1, data); } } -function insertionSort(left, right, data_levels, data_points, data_ids, data_weights) { +function insertionSort(left, right, data) { + var ptr = 2*(left+1) for(var i=left+1; i<=right; ++i) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - + var a = data[ptr++] + var b = data[ptr++] var j = i - while(j > left) { - var b_level = data_levels[j-1] - var b_x = data_points[2*(j-1)] - if(((b_level - a_level) || (a_x - b_x)) >= 0) { + var jptr = ptr-2 + while(j-- > left) { + var x = data[jptr-2] + var y = data[jptr-1] + if(x < a) { + break + } else if(x === a && y < b) { break } - data_levels[j] = b_level - data_points[2*j] = b_x - data_points[2*j+1] = data_points[2*j-1] - data_ids[j] = data_ids[j-1] - data_weights[j] = data_weights[j-1] - j -= 1 + data[jptr] = x + data[jptr+1] = y + jptr -= 2 } - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight + data[jptr] = a + data[jptr+1] = b } } -function swap(i, j, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight +function swap(i, j, data) { + i *= 2 + j *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = x + data[j+1] = y } -function move(i, j, data_levels, data_points, data_ids, data_weights) { - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] +function move(i, j, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[i+1] = data[j+1] } -function rotate(i, j, k, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = data_levels[k] - data_points[2*j] = data_points[2*k] - data_points[2*j+1] = data_points[2*k+1] - data_ids[j] = data_ids[k] - data_weights[j] = data_weights[k] - - data_levels[k] = a_level - data_points[2*k] = a_x - data_points[2*k+1] = a_y - data_ids[k] = a_id - data_weights[k] = a_weight +function rotate(i, j, k, data) { + i *= 2 + j *= 2 + k *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = data[k] + data[j+1] = data[k+1] + data[k] = x + data[k+1] = y } -function shufflePivot( - i, j, - a_level, a_x, a_y, a_id, a_weight, - data_levels, data_points, data_ids, data_weights) { - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight +function shufflePivot(i, j, px, py, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[j] = px + data[i+1] = data[j+1] + data[j+1] = py } -function compare(i, j, data_levels, data_points, data_ids) { - return ((data_levels[i] - data_levels[j]) || - (data_points[2*j] - data_points[2*i]) || - (data_ids[i] - data_ids[j])) < 0 +function compare(i, j, data) { + i *= 2 + j *= 2 + var x = data[i], + y = data[j] + if(x < y) { + return false + } else if(x === y) { + return data[i+1] > data[j+1] + } + return true } -function comparePivot(i, level, x, y, id, data_levels, data_points, data_ids) { - return ((level - data_levels[i]) || - (data_points[2*i] - x) || - (id - data_ids[i])) < 0 +function comparePivot(i, y, b, data) { + i *= 2 + var x = data[i] + if(x < y) { + return true + } else if(x === y) { + return data[i+1] < b + } + return false } -function quickSort(left, right, data_levels, data_points, data_ids, data_weights) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, +function quickSort(left, right, data) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, tmp = 0 - if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) { + if(compare(el1, el2, data)) { tmp = el1 el1 = el2 el2 = tmp } - if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + if(compare(el4, el5, data)) { tmp = el4 el4 = el5 el5 = tmp } - if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) { + if(compare(el1, el3, data)) { tmp = el1 el1 = el3 el3 = tmp } - if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + if(compare(el2, el3, data)) { tmp = el2 el2 = el3 el3 = tmp } - if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) { + if(compare(el1, el4, data)) { tmp = el1 el1 = el4 el4 = tmp } - if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) { + if(compare(el3, el4, data)) { tmp = el3 el3 = el4 el4 = tmp } - if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) { + if(compare(el2, el5, data)) { tmp = el2 el2 = el5 el5 = tmp } - if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + if(compare(el2, el3, data)) { tmp = el2 el2 = el3 el3 = tmp } - if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + if(compare(el4, el5, data)) { tmp = el4 el4 = el5 el5 = tmp } - var pivot1_level = data_levels[el2] - var pivot1_x = data_points[2*el2] - var pivot1_y = data_points[2*el2+1] - var pivot1_id = data_ids[el2] - var pivot1_weight = data_weights[el2] + var pivot1X = data[2*el2] + var pivot1Y = data[2*el2+1] + var pivot2X = data[2*el4] + var pivot2Y = data[2*el4+1] - var pivot2_level = data_levels[el4] - var pivot2_x = data_points[2*el4] - var pivot2_y = data_points[2*el4+1] - var pivot2_id = data_ids[el4] - var pivot2_weight = data_weights[el4] + var ptr0 = 2 * el1; + var ptr2 = 2 * el3; + var ptr4 = 2 * el5; + var ptr5 = 2 * index1; + var ptr6 = 2 * index3; + var ptr7 = 2 * index5; + for (var i1 = 0; i1 < 2; ++i1) { + var x = data[ptr0+i1]; + var y = data[ptr2+i1]; + var z = data[ptr4+i1]; + data[ptr5+i1] = x; + data[ptr6+i1] = y; + data[ptr7+i1] = z; + } - var ptr0 = el1 - var ptr2 = el3 - var ptr4 = el5 - var ptr5 = index1 - var ptr6 = index3 - var ptr7 = index5 + move(index2, left, data) + move(index4, right, data) + for (var k = less; k <= great; ++k) { + if (comparePivot(k, pivot1X, pivot1Y, data)) { + if (k !== less) { + swap(k, less, data) + } + ++less; + } else { + if (!comparePivot(k, pivot2X, pivot2Y, data)) { + while (true) { + if (!comparePivot(great, pivot2X, pivot2Y, data)) { + if (--great < k) { + break; + } + continue; + } else { + if (comparePivot(great, pivot1X, pivot1Y, data)) { + rotate(k, less, great, data) + ++less; + --great; + } else { + swap(k, great, data) + --great; + } + break; + } + } + } + } + } + shufflePivot(left, less-1, pivot1X, pivot1Y, data) + shufflePivot(right, great+1, pivot2X, pivot2Y, data) + if (less - 2 - left <= INSERT_SORT_CUTOFF) { + insertionSort(left, less - 2, data); + } else { + quickSort(left, less - 2, data); + } + if (right - (great + 2) <= INSERT_SORT_CUTOFF) { + insertionSort(great + 2, right, data); + } else { + quickSort(great + 2, right, data); + } + if (great - less <= INSERT_SORT_CUTOFF) { + insertionSort(less, great, data); + } else { + quickSort(less, great, data); + } +} +},{}],394:[function(require,module,exports){ +'use strict' - var level_x = data_levels[ptr0] - var level_y = data_levels[ptr2] - var level_z = data_levels[ptr4] - data_levels[ptr5] = level_x - data_levels[ptr6] = level_y - data_levels[ptr7] = level_z +module.exports = { + init: sqInit, + sweepBipartite: sweepBipartite, + sweepComplete: sweepComplete, + scanBipartite: scanBipartite, + scanComplete: scanComplete +} - for (var i1 = 0; i1 < 2; ++i1) { - var x = data_points[2*ptr0+i1] - var y = data_points[2*ptr2+i1] - var z = data_points[2*ptr4+i1] - data_points[2*ptr5+i1] = x - data_points[2*ptr6+i1] = y - data_points[2*ptr7+i1] = z +var pool = require('typedarray-pool') +var bits = require('bit-twiddle') +var isort = require('./sort') + +//Flag for blue +var BLUE_FLAG = (1<<28) + +//1D sweep event queue stuff (use pool to save space) +var INIT_CAPACITY = 1024 +var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) + +//Reserves memory for the 1D sweep data structures +function sqInit(count) { + var rcount = bits.nextPow2(count) + if(RED_SWEEP_QUEUE.length < rcount) { + pool.free(RED_SWEEP_QUEUE) + RED_SWEEP_QUEUE = pool.mallocInt32(rcount) + } + if(RED_SWEEP_INDEX.length < rcount) { + pool.free(RED_SWEEP_INDEX) + RED_SWEEP_INDEX = pool.mallocInt32(rcount) + } + if(BLUE_SWEEP_QUEUE.length < rcount) { + pool.free(BLUE_SWEEP_QUEUE) + BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) + } + if(BLUE_SWEEP_INDEX.length < rcount) { + pool.free(BLUE_SWEEP_INDEX) + BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) + } + if(COMMON_SWEEP_QUEUE.length < rcount) { + pool.free(COMMON_SWEEP_QUEUE) + COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) + } + if(COMMON_SWEEP_INDEX.length < rcount) { + pool.free(COMMON_SWEEP_INDEX) + COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) + } + var eventLength = 8 * rcount + if(SWEEP_EVENTS.length < eventLength) { + pool.free(SWEEP_EVENTS) + SWEEP_EVENTS = pool.mallocDouble(eventLength) } +} - var id_x = data_ids[ptr0] - var id_y = data_ids[ptr2] - var id_z = data_ids[ptr4] - data_ids[ptr5] = id_x - data_ids[ptr6] = id_y - data_ids[ptr7] = id_z +//Remove an item from the active queue in O(1) +function sqPop(queue, index, count, item) { + var idx = index[item] + var top = queue[count-1] + queue[idx] = top + index[top] = idx +} - var weight_x = data_weights[ptr0] - var weight_y = data_weights[ptr2] - var weight_z = data_weights[ptr4] - data_weights[ptr5] = weight_x - data_weights[ptr6] = weight_y - data_weights[ptr7] = weight_z +//Insert an item into the active queue in O(1) +function sqPush(queue, index, count, item) { + queue[count] = item + index[item] = count +} + +//Recursion base case: use 1D sweep algorithm +function sweepBipartite( + d, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + //store events as pairs [coordinate, idx] + // + // red create: -(idx+1) + // red destroy: idx + // blue create: -(idx+BLUE_FLAG) + // blue destroy: idx+BLUE_FLAG + // + var ptr = 0 + var elemSize = 2*d + var istart = d-1 + var iend = elemSize-1 + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + for(var i=0; i= BLUE_FLAG) { + //blue destroy event + e = (e-BLUE_FLAG)|0 + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) + } else if(e >= 0) { + //red destroy event + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) + } else if(e <= -BLUE_FLAG) { + //blue create event + e = (-e-BLUE_FLAG)|0 + for(var j=0; jright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + var commonActive = 0 + for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { + color = 2 + i += 1 + } + + if(e < 0) { + //Create event + var id = -(e>>1) - 1 - move(index2, left, data_levels, data_points, data_ids, data_weights) - move(index4, right, data_levels, data_points, data_ids, data_weights) - for (var k = less; k <= great; ++k) { - if (comparePivot(k, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - if (k !== less) { - swap(k, less, data_levels, data_points, data_ids, data_weights) + //Intersect with common + for(var j=0; j>1) - 1 + if(color === 0) { + //Red + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) + } else if(color === 1) { + //Blue + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) + } else if(color === 2) { + //Both + sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) + } } } - shufflePivot(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) - shufflePivot(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) - if (less - 2 - left <= INSERT_SORT_CUTOFF) { - insertionSort(left, less - 2, data_levels, data_points, data_ids, data_weights) +} + +//Sweep and prune/scanline algorithm: +// Scan along axis, detect intersections +// Brute force all boxes along axis +function scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = axis + var iend = axis+d + + var redShift = 1 + var blueShift = 1 + if(flip) { + blueShift = BLUE_FLAG } else { - quickSort(left, less - 2, data_levels, data_points, data_ids, data_weights) + redShift = BLUE_FLAG } - if (right - (great + 2) <= INSERT_SORT_CUTOFF) { - insertionSort(great + 2, right, data_levels, data_points, data_ids, data_weights) - } else { - quickSort(great + 2, right, data_levels, data_points, data_ids, data_weights) + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + isRed = !flip + idx -= BLUE_FLAG + } else { + isRed = !!flip + idx -= 1 + } + if(isRed) { + sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) + } else { + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] -var pool = require('typedarray-pool') +red_loop: + for(var j=0; j>> 1 - if(n < 1) { - return [] - } +function scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { - var lox = Infinity, loy = Infinity - var hix = -Infinity, hiy = -Infinity - for(var i=0; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG + } else { + idx -= 1 + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx - bounds = bounds || [0,0,0,0] + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] - bounds[0] = lox - bounds[1] = loy - bounds[2] = hix - bounds[3] = hiy +red_loop: + for(var j=0; j= Math.max(0.9 * count, 32)) { - var mid = (end + start)>>>1 - snapRec(nx, ny, diam_2, offset, mid, level+1) - offset = mid + } + } else { + var idx = e - BLUE_FLAG + for(var j=redActive-1; j>=0; --j) { + if(RED_SWEEP_QUEUE[j] === idx) { + for(var k=j+1; k=0; --ptr) { - points[2*ptr] = (points[2*ptr] - lox) * scaleX - points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY +var doubleBits = require("double-bits") - var level = levels[ptr] - if(level === lastLevel) { - continue - } +var SMALLEST_DENORM = Math.pow(2, -1074) +var UINT_MAX = (-1)>>>0 - lod.push(new SnapInterval( - diam * Math.pow(0.5, level), - ptr+1, - prevOffset - (ptr+1) - )) - prevOffset = ptr+1 +module.exports = nextafter - lastLevel = level +function nextafter(x, y) { + if(isNaN(x) || isNaN(y)) { + return NaN } - - lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) - pool.free(levels) - - return lod + if(x === y) { + return x + } + if(x === 0) { + if(y < 0) { + return -SMALLEST_DENORM + } else { + return SMALLEST_DENORM + } + } + var hi = doubleBits.hi(x) + var lo = doubleBits.lo(x) + if((y > x) === (x > 0)) { + if(lo === UINT_MAX) { + hi += 1 + lo = 0 + } else { + lo += 1 + } + } else { + if(lo === 0) { + lo = UINT_MAX + hi -= 1 + } else { + lo -= 1 + } + } + return doubleBits.pack(lo, hi) } - -},{"./lib/sort":188,"typedarray-pool":278}],190:[function(require,module,exports){ +},{"double-bits":400}],400:[function(require,module,exports){ +arguments[4][384][0].apply(exports,arguments) +},{"buffer":65,"dup":384}],401:[function(require,module,exports){ 'use strict' -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var bsearch = require('binary-search-bounds') -var snapPoints = require('snap-points-2d') - -var pool = require('typedarray-pool') - -var SHADERS = require('./lib/shader') - -module.exports = createScatter2D - -function Scatter2D(plot, offsetBuffer, pickBuffer, weightBuffer, shader, pickShader) { - this.plot = plot - this.offsetBuffer = offsetBuffer - this.pickBuffer = pickBuffer - this.weightBuffer = weightBuffer - this.shader = shader - this.pickShader = pickShader - this.scales = [] - this.size = 12.0 - this.borderSize = 1.0 - this.pointCount = 0 - this.color = [1,0,0,1] - this.borderColor = [0,0,0,1] - this.bounds = [Infinity,Infinity,-Infinity,-Infinity] - this.pickOffset = 0 - this.points = null - this.xCoords = null -} +var bnadd = require('big-rat/add') -var proto = Scatter2D.prototype +module.exports = add -proto.dispose = function() { - this.shader.dispose() - this.pickShader.dispose() - this.offsetBuffer.dispose() - this.pickBuffer.dispose() - if(this.xCoords) { - pool.free(this.xCoords) +function add(a, b) { + var n = a.length + var r = new Array(n) + for(var i=0; i>>1) - packed.set(data) - var packedW = pool.mallocFloat32(data.length) - this.points = data - this.scales = snapPoints(packed, packedId, packedW, this.bounds) - this.offsetBuffer.update(packed) - this.pickBuffer.update(packedId) - this.weightBuffer.update(packedW) - var xCoords = pool.mallocFloat32(data.length>>>1) - for(var i=0,j=0; i>> 1 - this.pickOffset = 0 + return result } -proto.drawPick = (function() { - var MATRIX = [1,0,0, - 0,1,0, - 0,0,1] - var PICK_VEC4 = [0,0,0,0] -return function(pickOffset) { - var plot = this.plot - var shader = this.pickShader - var scales = this.scales - var offsetBuffer = this.offsetBuffer - var pickBuffer = this.pickBuffer - var bounds = this.bounds - var size = this.size - var borderSize = this.borderSize - var gl = plot.gl - var pixelRatio = plot.pickPixelRatio - var viewBox = plot.viewBox - var dataBox = plot.dataBox +},{"big-rat":372}],403:[function(require,module,exports){ +'use strict' + +var rat = require('big-rat') +var mul = require('big-rat/mul') - if(this.pointCount === 0) { - return pickOffset +module.exports = muls + +function muls(a, x) { + var s = rat(x) + var n = a.length + var r = new Array(n) + for(var i=0; i>8) & 0xff) - PICK_VEC4[2] = ((pickOffset>>16) & 0xff) - PICK_VEC4[3] = ((pickOffset>>24) & 0xff) +},{"big-rat/sub":386}],405:[function(require,module,exports){ +"use strict" - shader.bind() - shader.uniforms.matrix = MATRIX - shader.uniforms.color = this.color - shader.uniforms.borderColor = this.borderColor - shader.uniforms.pointSize = pixelRatio * (size + borderSize) - shader.uniforms.pickOffset = PICK_VEC4 +module.exports = segmentsIntersect - if(this.borderSize === 0) { - shader.uniforms.centerFraction = 2.0; - } else { - shader.uniforms.centerFraction = size / (size + borderSize + 1.25) - } +var orient = require("robust-orientation")[3] - offsetBuffer.bind() - shader.attributes.position.pointer() - pickBuffer.bind() - shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE) +function checkCollinear(a0, a1, b0, b1) { - var xCoords = this.xCoords - var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX - var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX + for(var d=0; d<2; ++d) { + var x0 = a0[d] + var y0 = a1[d] + var l0 = Math.min(x0, y0) + var h0 = Math.max(x0, y0) - for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { - var lod = scales[scaleNum] - if(lod.pixelSize < pixelSize && scaleNum > 1) { - continue + var x1 = b0[d] + var y1 = b1[d] + var l1 = Math.min(x1, y1) + var h1 = Math.max(x1, y1) + + if(h1 < l0 || h0 < l1) { + return false } + } - var intervalStart = lod.offset - var intervalEnd = lod.count + intervalStart + return true +} - var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) - var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 +function segmentsIntersect(a0, a1, b0, b1) { + var x0 = orient(a0, b0, b1) + var y0 = orient(a1, b0, b1) + if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { + return false + } - if(endOffset > startOffset) { - gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) - } + var x1 = orient(b0, a0, a1) + var y1 = orient(b1, a0, a1) + if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { + return false } - return pickOffset + this.pointCount + //Check for degenerate collinear case + if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { + return checkCollinear(a0, a1, b0, b1) + } + + return true } -})() +},{"robust-orientation":1040}],406:[function(require,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],407:[function(require,module,exports){ +'use strict' -proto.draw = (function() { - var MATRIX = [1, 0, 0, - 0, 1, 0, - 0, 0, 1] +module.exports = trimLeaves - return function() { - var plot = this.plot - var shader = this.shader - var scales = this.scales - var offsetBuffer = this.offsetBuffer - var bounds = this.bounds - var size = this.size - var borderSize = this.borderSize - var gl = plot.gl - var pixelRatio = plot.pixelRatio - var viewBox = plot.viewBox - var dataBox = plot.dataBox +var e2a = require('edges-to-adjacency-list') - if(this.pointCount === 0) { - return +function trimLeaves(edges, positions) { + var adj = e2a(edges, positions.length) + var live = new Array(positions.length) + var nbhd = new Array(positions.length) + + var dead = [] + for(var i=0; i 0) { + var v = dead.pop() + live[v] = false + var n = adj[v] + for(var i=0; i= 0; --scaleNum) { - var lod = scales[scaleNum] - if(lod.pixelSize < pixelSize && scaleNum > 1) { - continue - } + var cycles = [] - var intervalStart = lod.offset - var intervalEnd = lod.count + intervalStart + //Add isolated vertices as trivial case + for(var i=0; i startOffset) { - gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + //Find next vertex and cut edge + function next(a, b, noCut) { + var nextCell, nextVertex, nextDir + for(var i=0; i<2; ++i) { + if(adj[i][b].length > 0) { + nextCell = adj[i][b][0] + nextDir = i + break } + } + nextVertex = nextCell[nextDir^1] - if(firstLevel) { - firstLevel = false - shader.uniforms.useWeight = 0 + for(var dir=0; dir<2; ++dir) { + var nbhd = adj[dir][b] + for(var k=0; k 0) { + nextCell = e + nextVertex = p + nextDir = dir + } } } + if(noCut) { + return nextVertex + } + if(nextCell) { + cut(nextCell, nextDir) + } + return nextVertex } -})() -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.pointCount - if(value < pickOffset || value >= pickOffset + pointCount) { - return null + function extractCycle(v, dir) { + var e0 = adj[dir][v][0] + var cycle = [v] + cut(e0, dir) + var u = e0[dir^1] + var d0 = dir + while(true) { + while(u !== v) { + cycle.push(u) + u = next(cycle[cycle.length-2], u, false) + } + if(adj[0][v].length + adj[1][v].length === 0) { + break + } + var a = cycle[cycle.length-1] + var b = v + var c = cycle[1] + var d = next(a, b, true) + if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) { + break + } + cycle.push(v) + u = next(a, b) + } + return cycle } - var pointId = value - pickOffset - var points = this.points - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + + function shouldGlue(pcycle, ncycle) { + return (ncycle[1] === ncycle[ncycle.length-1]) + } + + for(var i=0; i 0) { + var ni = adj[0][i].length + var ncycle = extractCycle(i,j) + if(shouldGlue(pcycle, ncycle)) { + //Glue together trivial cycles + pcycle.push.apply(pcycle, ncycle) + } else { + if(pcycle.length > 0) { + cycles.push(pcycle) + } + pcycle = ncycle + } + } + if(pcycle.length > 0) { + cycles.push(pcycle) + } + } } + + //Combine paths and loops together + return cycles } +},{"compare-angle":410}],410:[function(require,module,exports){ +"use strict" -function createScatter2D(plot, options) { - var gl = plot.gl - var buffer = createBuffer(gl) - var pickBuffer = createBuffer(gl) - var weightBuffer = createBuffer(gl) - var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment) - var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) +module.exports = compareAngle - var result = new Scatter2D( - plot, buffer, pickBuffer, weightBuffer, shader, pickShader) - result.update(options) +var orient = require("robust-orientation") +var sgn = require("signum") +var twoSum = require("two-sum") +var robustProduct = require("robust-product") +var robustSum = require("robust-sum") - //Register with plot - plot.addObject(result) +function testInterior(a, b, c) { + var x0 = twoSum(a[0], -b[0]) + var y0 = twoSum(a[1], -b[1]) + var x1 = twoSum(c[0], -b[0]) + var y1 = twoSum(c[1], -b[1]) - return result + var d = robustSum( + robustProduct(x0, x1), + robustProduct(y0, y1)) + + return d[d.length-1] >= 0 } -},{"./lib/shader":186,"binary-search-bounds":187,"gl-buffer":118,"gl-shader":197,"snap-points-2d":189,"typedarray-pool":278}],191:[function(require,module,exports){ +function compareAngle(a, b, c, d) { + var bcd = orient(b, c, d) + if(bcd === 0) { + //Handle degenerate cases + var sabc = sgn(orient(a, b, c)) + var sabd = sgn(orient(a, b, d)) + if(sabc === sabd) { + if(sabc === 0) { + var ic = testInterior(a, b, c) + var id = testInterior(a, b, d) + if(ic === id) { + return 0 + } else if(ic) { + return 1 + } else { + return -1 + } + } + return 0 + } else if(sabd === 0) { + if(sabc > 0) { + return -1 + } else if(testInterior(a, b, d)) { + return -1 + } else { + return 1 + } + } else if(sabc === 0) { + if(sabd > 0) { + return 1 + } else if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } + } + return sgn(sabd - sabc) + } + var abc = orient(a, b, c) + if(abc > 0) { + if(bcd > 0 && orient(a, b, d) > 0) { + return 1 + } + return -1 + } else if(abc < 0) { + if(bcd > 0 || orient(a, b, d) > 0) { + return 1 + } + return -1 + } else { + var abd = orient(a, b, d) + if(abd > 0) { + return 1 + } else { + if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } + } + } +} +},{"robust-orientation":1040,"robust-product":412,"robust-sum":421,"signum":413,"two-sum":414}],411:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54,"two-product":422,"two-sum":414}],412:[function(require,module,exports){ "use strict" -var vectorizeText = require("vectorize-text") - -module.exports = getGlyph +var robustSum = require("robust-sum") +var robustScale = require("robust-scale") -var GLYPH_CACHE = {} +module.exports = robustProduct -function getGlyph(symbol, font) { - var fontCache = GLYPH_CACHE[font] - if(!fontCache) { - fontCache = GLYPH_CACHE[font] = {} +function robustProduct(a, b) { + if(a.length === 1) { + return robustScale(b, a[0]) } - if(symbol in fontCache) { - return fontCache[symbol] + if(b.length === 1) { + return robustScale(a, b[0]) } - - //Get line and triangle meshes for glyph - var lineSymbol = vectorizeText(symbol, { - textAlign: "center", - textBaseline: "middle", - lineHeight: 1.0, - font: font - }) - var triSymbol = vectorizeText(symbol, { - triangles: true, - textAlign: "center", - textBaseline: "middle", - lineHeight: 1.0, - font: font - }) - - //Calculate bounding box - var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]] - for(var i=0; i 0) { return 1 } + return 0.0 +} +},{}],414:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"dup":53}],415:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],416:[function(require,module,exports){ +"use strict" -var ATTRIBUTES = [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'glyph', type: 'vec2'}, - {name: 'id', type: 'vec4'} -] +var bounds = require("binary-search-bounds") -var perspective = { - vertex: perspectiveVertSrc, - fragment: drawFragSrc, - attributes: ATTRIBUTES - }, - ortho = { - vertex: orthographicVertSrc, - fragment: drawFragSrc, - attributes: ATTRIBUTES - }, - project = { - vertex: projectionVertSrc, - fragment: drawFragSrc, - attributes: ATTRIBUTES - }, - pickPerspective = { - vertex: perspectiveVertSrc, - fragment: pickFragSrc, - attributes: ATTRIBUTES - }, - pickOrtho = { - vertex: orthographicVertSrc, - fragment: pickFragSrc, - attributes: ATTRIBUTES - }, - pickProject = { - vertex: projectionVertSrc, - fragment: pickFragSrc, - attributes: ATTRIBUTES - } +var NOT_FOUND = 0 +var SUCCESS = 1 +var EMPTY = 2 -function createShader(gl, src) { - var shader = createShaderWrapper(gl, src) - var attr = shader.attributes - attr.position.location = 0 - attr.color.location = 1 - attr.glyph.location = 2 - attr.id.location = 3 - return shader -} +module.exports = createWrapper -exports.createPerspective = function(gl) { - return createShader(gl, perspective) -} -exports.createOrtho = function(gl) { - return createShader(gl, ortho) -} -exports.createProject = function(gl) { - return createShader(gl, project) -} -exports.createPickPerspective = function(gl) { - return createShader(gl, pickPerspective) -} -exports.createPickOrtho = function(gl) { - return createShader(gl, pickOrtho) -} -exports.createPickProject = function(gl) { - return createShader(gl, pickProject) +function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { + this.mid = mid + this.left = left + this.right = right + this.leftPoints = leftPoints + this.rightPoints = rightPoints + this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length } -},{"gl-shader":197}],193:[function(require,module,exports){ -'use strict' - -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var pool = require('typedarray-pool') -var mat4mult = require('gl-mat4/multiply') -var shaders = require('./lib/shaders') -var getGlyph = require('./lib/glyphs') +var proto = IntervalTreeNode.prototype -var IDENTITY = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] +function copy(a, b) { + a.mid = b.mid + a.left = b.left + a.right = b.right + a.leftPoints = b.leftPoints + a.rightPoints = b.rightPoints + a.count = b.count +} -module.exports = createPointCloud +function rebuild(node, intervals) { + var ntree = createIntervalTree(intervals) + node.mid = ntree.mid + node.left = ntree.left + node.right = ntree.right + node.leftPoints = ntree.leftPoints + node.rightPoints = ntree.rightPoints + node.count = ntree.count +} -function transformMat4(x, m) { - var x0 = x[0] - var x1 = x[1] - var x2 = x[2] - var x3 = x[3] - x[0] = m[0] * x0 + m[4] * x1 + m[8] * x2 + m[12] * x3 - x[1] = m[1] * x0 + m[5] * x1 + m[9] * x2 + m[13] * x3 - x[2] = m[2] * x0 + m[6] * x1 + m[10] * x2 + m[14] * x3 - x[3] = m[3] * x0 + m[7] * x1 + m[11] * x2 + m[15] * x3 - return x +function rebuildWithInterval(node, interval) { + var intervals = node.intervals([]) + intervals.push(interval) + rebuild(node, intervals) } -function project(p, v, m, x) { - transformMat4(x, x, m) - transformMat4(x, x, v) - return transformMat4(x, x, p) +function rebuildWithoutInterval(node, interval) { + var intervals = node.intervals([]) + var idx = intervals.indexOf(interval) + if(idx < 0) { + return NOT_FOUND + } + intervals.splice(idx, 1) + rebuild(node, intervals) + return SUCCESS } -function clampVec(v) { - var result = new Array(3) - for(var i=0; i<3; ++i) { - result[i] = Math.min(Math.max(v[i], -1e8), 1e8) +proto.intervals = function(result) { + result.push.apply(result, this.leftPoints) + if(this.left) { + this.left.intervals(result) + } + if(this.right) { + this.right.intervals(result) } return result } -function ScatterPlotPickResult(index, position) { - this.index = index - this.dataCoordinate = this.position = position +proto.insert = function(interval) { + var weight = this.count - this.leftPoints.length + this.count += 1 + if(interval[1] < this.mid) { + if(this.left) { + if(4*(this.left.count+1) > 3*(weight+1)) { + rebuildWithInterval(this, interval) + } else { + this.left.insert(interval) + } + } else { + this.left = createIntervalTree([interval]) + } + } else if(interval[0] > this.mid) { + if(this.right) { + if(4*(this.right.count+1) > 3*(weight+1)) { + rebuildWithInterval(this, interval) + } else { + this.right.insert(interval) + } + } else { + this.right = createIntervalTree([interval]) + } + } else { + var l = bounds.ge(this.leftPoints, interval, compareBegin) + var r = bounds.ge(this.rightPoints, interval, compareEnd) + this.leftPoints.splice(l, 0, interval) + this.rightPoints.splice(r, 0, interval) + } } -function PointCloud( - gl, - shader, - orthoShader, - projectShader, - pointBuffer, - colorBuffer, - glyphBuffer, - idBuffer, - vao, - pickPerspectiveShader, - pickOrthoShader, - pickProjectShader) { +proto.remove = function(interval) { + var weight = this.count - this.leftPoints + if(interval[1] < this.mid) { + if(!this.left) { + return NOT_FOUND + } + var rw = this.right ? this.right.count : 0 + if(4 * rw > 3 * (weight-1)) { + return rebuildWithoutInterval(this, interval) + } + var r = this.left.remove(interval) + if(r === EMPTY) { + this.left = null + this.count -= 1 + return SUCCESS + } else if(r === SUCCESS) { + this.count -= 1 + } + return r + } else if(interval[0] > this.mid) { + if(!this.right) { + return NOT_FOUND + } + var lw = this.left ? this.left.count : 0 + if(4 * lw > 3 * (weight-1)) { + return rebuildWithoutInterval(this, interval) + } + var r = this.right.remove(interval) + if(r === EMPTY) { + this.right = null + this.count -= 1 + return SUCCESS + } else if(r === SUCCESS) { + this.count -= 1 + } + return r + } else { + if(this.count === 1) { + if(this.leftPoints[0] === interval) { + return EMPTY + } else { + return NOT_FOUND + } + } + if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { + if(this.left && this.right) { + var p = this + var n = this.left + while(n.right) { + p = n + n = n.right + } + if(p === this) { + n.right = this.right + } else { + var l = this.left + var r = this.right + p.count -= n.count + p.right = n.left + n.left = l + n.right = r + } + copy(this, n) + this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length + } else if(this.left) { + copy(this, this.left) + } else { + copy(this, this.right) + } + return SUCCESS + } + for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { + var r = cb(arr[i]) + if(r) { return r } + } +} - this.shader = shader - this.orthoShader = orthoShader - this.projectShader = projectShader +function reportRange(arr, cb) { + for(var i=0; i this.mid) { + if(this.right) { + var r = this.right.queryPoint(x, cb) + if(r) { return r } + } + return reportRightRange(this.rightPoints, x, cb) + } else { + return reportRange(this.leftPoints, cb) + } +} - this.opacity = 1.0 +proto.queryInterval = function(lo, hi, cb) { + if(lo < this.mid && this.left) { + var r = this.left.queryInterval(lo, hi, cb) + if(r) { return r } + } + if(hi > this.mid && this.right) { + var r = this.right.queryInterval(lo, hi, cb) + if(r) { return r } + } + if(hi < this.mid) { + return reportLeftRange(this.leftPoints, hi, cb) + } else if(lo > this.mid) { + return reportRightRange(this.rightPoints, lo, cb) + } else { + return reportRange(this.leftPoints, cb) + } +} - this.lineWidth = 0 - this.projectScale = [2.0/3.0, 2.0/3.0, 2.0/3.0] - this.projectOpacity = [1,1,1] +function compareNumbers(a, b) { + return a - b +} - this.pickId = 0 - this.pickPerspectiveShader = pickPerspectiveShader - this.pickOrthoShader = pickOrthoShader - this.pickProjectShader = pickProjectShader - this.points = [] +function compareBegin(a, b) { + var d = a[0] - b[0] + if(d) { return d } + return a[1] - b[1] +} - this._selectResult = new ScatterPlotPickResult(0, [0,0,0]) +function compareEnd(a, b) { + var d = a[1] - b[1] + if(d) { return d } + return a[0] - b[0] +} - this.useOrtho = true - this.bounds = [[ Infinity,Infinity,Infinity], - [-Infinity,-Infinity,-Infinity]] +function createIntervalTree(intervals) { + if(intervals.length === 0) { + return null + } + var pts = [] + for(var i=0; i>1] - this.highlightId = [1,1,1,1] - this.highlightScale = 2 + var leftIntervals = [] + var rightIntervals = [] + var centerIntervals = [] + for(var i=0; i= 1) { - return true - } - for(var i=0; i<3; ++i) { - if(this.axesProject[i] && this.projectOpacity[i] >= 1) { - return true +tproto.remove = function(interval) { + if(this.root) { + var r = this.root.remove(interval) + if(r === EMPTY) { + this.root = null } + return r !== NOT_FOUND } return false } -var VIEW_SHAPE = [0,0] -var U_VEC = [0,0,0] -var V_VEC = [0,0,0] -var MU_VEC = [0,0,0,1] -var MV_VEC = [0,0,0,1] -var SCRATCH_MATRIX = IDENTITY.slice() -var SCRATCH_VEC = [0,0,0] -var CLIP_BOUNDS = [[0,0,0], [0,0,0]] - -function zeroVec(a) { - a[0] = a[1] = a[2] = 0 - return a -} - -function augment(hg, af) { - hg[0] = af[0] - hg[1] = af[1] - hg[2] = af[2] - hg[3] = 1 - return hg -} - -function setComponent(out, v, i, x) { - out[0] = v[0] - out[1] = v[1] - out[2] = v[2] - out[i] = x - return out +tproto.queryPoint = function(p, cb) { + if(this.root) { + return this.root.queryPoint(p, cb) + } } -function getClipBounds(bounds) { - var result = CLIP_BOUNDS - for(var i=0; i<2; ++i) { - for(var j=0; j<3; ++j) { - result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8) - } +tproto.queryInterval = function(lo, hi, cb) { + if(lo <= hi && this.root) { + return this.root.queryInterval(lo, hi, cb) } - return result } -function drawProject(shader, points, camera, transparent, forceDraw) { - var axesProject = points.axesProject - - var gl = points.gl - var uniforms = shader.uniforms - var model = camera.model || IDENTITY - var view = camera.view || IDENTITY - var projection = camera.projection || IDENTITY - var bounds = points.axesBounds - var clipBounds = getClipBounds(points.clipBounds) +Object.defineProperty(tproto, "count", { + get: function() { + if(this.root) { + return this.root.count + } + return 0 + } +}) - var cubeAxis - if(points.axes) { - cubeAxis = points.axes.lastCubeProps.axis - } else { - cubeAxis = [1,1,1] +Object.defineProperty(tproto, "intervals", { + get: function() { + if(this.root) { + return this.root.intervals([]) + } + return [] } +}) - VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth - VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight +function createWrapper(intervals) { + if(!intervals || intervals.length === 0) { + return new IntervalTree(null) + } + return new IntervalTree(createIntervalTree(intervals)) +} - shader.bind() - uniforms.view = view - uniforms.projection = projection - uniforms.screenSize = VIEW_SHAPE - uniforms.highlightId = points.highlightId - uniforms.highlightScale = points.highlightScale - uniforms.clipBounds = clipBounds - uniforms.pickGroup = points.pickId / 255.0 - uniforms.pixelRatio = points.pixelRatio +},{"binary-search-bounds":415}],417:[function(require,module,exports){ +"use strict" - for(var i=0; i<3; ++i) { - if(!axesProject[i]) { - continue - } - if((points.projectOpacity[i] < 1) !== transparent) { - continue - } +module.exports = orderSegments - uniforms.scale = points.projectScale[i] - uniforms.opacity = points.projectOpacity[i] +var orient = require("robust-orientation") - //Project model matrix - var pmodel = SCRATCH_MATRIX - for(var j=0; j<16; ++j) { - pmodel[j] = 0 - } - for(var j=0; j<4; ++j) { - pmodel[5*j] = 1 +function horizontalOrder(a, b) { + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + var alo = Math.min(a[0][1], a[1][1]) + var ahi = Math.max(a[0][1], a[1][1]) + var blo = Math.min(b[0][1], b[1][1]) + var bhi = Math.max(b[0][1], b[1][1]) + if(ahi < blo) { + return ahi - blo } - pmodel[5*i] = 0 - if(cubeAxis[i] < 0) { - pmodel[12+i] = bounds[0][i] - } else { - pmodel[12+i] = bounds[1][i] + if(alo > bhi) { + return alo - bhi } - mat4mult(pmodel, model, pmodel) - uniforms.model = pmodel - - //Compute initial axes - var u = (i+1)%3 - var v = (i+2)%3 - var du = zeroVec(U_VEC) - var dv = zeroVec(V_VEC) - du[u] = 1 - dv[v] = 1 + return ahi - bhi + } + var al, ar + if(a[0][1] < a[1][1]) { + al = a[0] + ar = a[1] + } else { + al = a[1] + ar = a[0] + } + var d = orient(br, bl, al) + if(d) { + return d + } + d = orient(br, bl, ar) + if(d) { + return d + } + return ar - br +} - //Align orientation relative to viewer - var mdu = project(projection, view, model, augment(MU_VEC, du)) - var mdv = project(projection, view, model, augment(MV_VEC, dv)) - if(Math.abs(mdu[1]) > Math.abs(mdv[1])) { - var tmp = mdu - mdu = mdv - mdv = tmp - tmp = du - du = dv - dv = tmp - var t = u - u = v - v = t - } - if(mdu[0] < 0) { - du[u] = -1 +function orderSegments(b, a) { + var al, ar + if(a[0][0] < a[1][0]) { + al = a[0] + ar = a[1] + } else if(a[0][0] > a[1][0]) { + al = a[1] + ar = a[0] + } else { + return horizontalOrder(a, b) + } + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + return -horizontalOrder(b, a) + } + var d1 = orient(al, ar, br) + var d2 = orient(al, ar, bl) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } - if(mdv[1] > 0) { - dv[v] = -1 + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } - var su = 0.0 - var sv = 0.0 - for(var j=0; j<4; ++j) { - su += Math.pow(model[4*u+j], 2) - sv += Math.pow(model[4*v+j], 2) + } else if(d2) { + return d2 + } + d1 = orient(br, bl, ar) + d2 = orient(br, bl, al) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } - du[u] /= Math.sqrt(su) - dv[v] /= Math.sqrt(sv) - uniforms.axes[0] = du - uniforms.axes[1] = dv - - //Update fragment clip bounds - uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8) - uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8) - - //Draw interior - points.vao.draw(gl.TRIANGLES, points.vertexCount) - - //Draw edges - if(points.lineWidth > 0) { - gl.lineWidth(points.lineWidth) - points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } + } else if(d2) { + return d2 } + return ar[0] - br[0] } +},{"robust-orientation":1040}],418:[function(require,module,exports){ +"use strict" +module.exports = createRBTree -var NEG_INFINITY3 = [-1e8, -1e8, -1e8] -var POS_INFINITY3 = [1e8, 1e8, 1e8] -var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] - -function drawFull(shader, pshader, points, camera, transparent, forceDraw) { - var gl = points.gl - - points.vao.bind() +var RED = 0 +var BLACK = 1 - if(transparent === (points.opacity < 1) || forceDraw) { - shader.bind() - var uniforms = shader.uniforms +function RBNode(color, key, value, left, right, count) { + this._color = color + this.key = key + this.value = value + this.left = left + this.right = right + this._count = count +} - uniforms.model = camera.model || IDENTITY - uniforms.view = camera.view || IDENTITY - uniforms.projection = camera.projection || IDENTITY +function cloneNode(node) { + return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) +} - VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth - VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight - uniforms.screenSize = VIEW_SHAPE +function repaint(color, node) { + return new RBNode(color, node.key, node.value, node.left, node.right, node._count) +} - uniforms.highlightId = points.highlightId - uniforms.highlightScale = points.highlightScale +function recount(node) { + node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) +} - uniforms.fragClipBounds = CLIP_GROUP - uniforms.clipBounds = points.axes.bounds +function RedBlackTree(compare, root) { + this._compare = compare + this.root = root +} - uniforms.opacity = points.opacity - uniforms.pickGroup = points.pickId / 255.0 +var proto = RedBlackTree.prototype - uniforms.pixelRatio = points.pixelRatio +Object.defineProperty(proto, "keys", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(k) + }) + return result + } +}) - //Draw interior - points.vao.draw(gl.TRIANGLES, points.vertexCount) +Object.defineProperty(proto, "values", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(v) + }) + return result + } +}) - //Draw edges - if(points.lineWidth > 0) { - gl.lineWidth(points.lineWidth) - points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) +//Returns the number of nodes in the tree +Object.defineProperty(proto, "length", { + get: function() { + if(this.root) { + return this.root._count } + return 0 } +}) - drawProject(pshader, points, camera, transparent, forceDraw) - - points.vao.unbind() -} - -proto.draw = function(camera) { - var shader = this.useOrtho ? this.orthoShader : this.shader - drawFull(shader, this.projectShader, this, camera, false, false) +//Insert a new item into the tree +proto.insert = function(key, value) { + var cmp = this._compare + //Find point to insert new node at + var n = this.root + var n_stack = [] + var d_stack = [] + while(n) { + var d = cmp(key, n.key) + n_stack.push(n) + d_stack.push(d) + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + //Rebuild path to leaf node + n_stack.push(new RBNode(RED, key, value, null, null, 1)) + for(var s=n_stack.length-2; s>=0; --s) { + var n = n_stack[s] + if(d_stack[s] <= 0) { + n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) + } else { + n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) + } + } + //Rebalance tree using rotations + //console.log("start insert", key, d_stack) + for(var s=n_stack.length-1; s>1; --s) { + var p = n_stack[s-1] + var n = n_stack[s] + if(p._color === BLACK || n._color === BLACK) { + break + } + var pp = n_stack[s-2] + if(pp.left === p) { + if(p.left === n) { + var y = pp.right + if(y && y._color === RED) { + //console.log("LLr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LLb") + pp._color = RED + pp.left = p.right + p._color = BLACK + p.right = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = p + } else { + ppp.right = p + } + } + break + } + } else { + var y = pp.right + if(y && y._color === RED) { + //console.log("LRr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LRb") + p.right = n.left + pp._color = RED + pp.left = n.right + n._color = BLACK + n.left = p + n.right = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = n + } else { + ppp.right = n + } + } + break + } + } + } else { + if(p.right === n) { + var y = pp.left + if(y && y._color === RED) { + //console.log("RRr", y.key) + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RRb") + pp._color = RED + pp.right = p.left + p._color = BLACK + p.left = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = p + } else { + ppp.left = p + } + } + break + } + } else { + var y = pp.left + if(y && y._color === RED) { + //console.log("RLr") + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RLb") + p.left = n.right + pp._color = RED + pp.right = n.left + n._color = BLACK + n.right = p + n.left = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = n + } else { + ppp.left = n + } + } + break + } + } + } + } + //Return new tree + n_stack[0]._color = BLACK + return new RedBlackTree(cmp, n_stack[0]) } -proto.drawTransparent = function(camera) { - var shader = this.useOrtho ? this.orthoShader : this.shader - drawFull(shader, this.projectShader, this, camera, true, false) -} -proto.drawPick = function(camera) { - var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader - drawFull(shader, this.pickProjectShader, this, camera, false, true) +//Visit all nodes inorder +function doVisitFull(visit, node) { + if(node.left) { + var v = doVisitFull(visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + if(node.right) { + return doVisitFull(visit, node.right) + } } -proto.pick = function(selected) { - if(!selected) { - return null - } - if(selected.id !== this.pickId) { - return null +//Visit half nodes in order +function doVisitHalf(lo, compare, visit, node) { + var l = compare(lo, node.key) + if(l <= 0) { + if(node.left) { + var v = doVisitHalf(lo, compare, visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } } - var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) - if(x >= this.pointCount || x < 0) { - return null + if(node.right) { + return doVisitHalf(lo, compare, visit, node.right) } +} - //Unpack result - var coord = this.points[x] - var result = this._selectResult - result.index = x - for(var i=0; i<3; ++i) { - result.position[i] = result.dataCoordinate[i] = coord[i] +//Visit all nodes within a range +function doVisit(lo, hi, compare, visit, node) { + var l = compare(lo, node.key) + var h = compare(hi, node.key) + var v + if(l <= 0) { + if(node.left) { + v = doVisit(lo, hi, compare, visit, node.left) + if(v) { return v } + } + if(h > 0) { + v = visit(node.key, node.value) + if(v) { return v } + } + } + if(h > 0 && node.right) { + return doVisit(lo, hi, compare, visit, node.right) } - return result } -proto.highlight = function(selection) { - if(!selection) { - this.highlightId = [1,1,1,1] - } else { - var pointId = selection.index - var a0 = pointId &0xff - var a1 = (pointId>>8) &0xff - var a2 = (pointId>>16)&0xff - this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0] + +proto.forEach = function rbTreeForEach(visit, lo, hi) { + if(!this.root) { + return } -} + switch(arguments.length) { + case 1: + return doVisitFull(visit, this.root) + break -proto.update = function(options) { + case 2: + return doVisitHalf(lo, this._compare, visit, this.root) + break - options = options || {} + case 3: + if(this._compare(lo, hi) >= 0) { + return + } + return doVisit(lo, hi, this._compare, visit, this.root) + break + } +} - if('perspective' in options) { - this.useOrtho = !options.perspective +//First item in list +Object.defineProperty(proto, "begin", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.left + } + return new RedBlackTreeIterator(this, stack) } - if('orthographic' in options) { - this.useOrtho = !!options.orthographic +}) + +//Last item in list +Object.defineProperty(proto, "end", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.right + } + return new RedBlackTreeIterator(this, stack) } - if('lineWidth' in options) { - this.lineWidth = options.lineWidth +}) + +//Find the ith item in the tree +proto.at = function(idx) { + if(idx < 0) { + return new RedBlackTreeIterator(this, []) } - if('project' in options) { - if(Array.isArray(options.project)) { - this.axesProject = options.project + var n = this.root + var stack = [] + while(true) { + stack.push(n) + if(n.left) { + if(idx < n.left._count) { + n = n.left + continue + } + idx -= n.left._count + } + if(!idx) { + return new RedBlackTreeIterator(this, stack) + } + idx -= 1 + if(n.right) { + if(idx >= n.right._count) { + break + } + n = n.right } else { - var v = !!options.project - this.axesProject = [v,v,v] + break } } - if('projectScale' in options) { - if(Array.isArray(options.projectScale)) { - this.projectScale = options.projectScale.slice() + return new RedBlackTreeIterator(this, []) +} + +proto.ge = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d <= 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left } else { - var s = +options.projectScale - this.projectScale = [s,s,s] + n = n.right } } - if('projectOpacity' in options) { - if(Array.isArray(options.projectOpacity)) { - this.projectOpacity = options.projectOpacity.slice() + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} + +proto.gt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d < 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left } else { - var s = +options.projectOpacity - this.projectOpacity = [s,s,s] + n = n.right } } - if('opacity' in options) { - this.opacity = options.opacity - } - - //Set dirty flag - this.dirty = true + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - //Create new buffers - var points = options.position - if(!points) { - return +proto.lt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d > 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - //Text font - var font = options.font || 'normal' - var alignment = options.alignment || [0,0] - - //Bounds - var lowerBound = [ Infinity, Infinity, Infinity] - var upperBound = [-Infinity,-Infinity,-Infinity] - - //Unpack options - var glyphs = options.glyph - var colors = options.color - var sizes = options.size - var angles = options.angle - var lineColors = options.lineColor - - //Picking geometry - var pickCounter = 0 +proto.le = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d >= 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - //First do pass to compute buffer sizes - var triVertexCount = 0 - var lineVertexCount = 0 +//Finds the item with key if it exists +proto.find = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d === 0) { + return new RedBlackTreeIterator(this, stack) + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + return new RedBlackTreeIterator(this, []) +} - //Count number of points and buffer size - var numPoints = points.length +//Removes item with key from tree +proto.remove = function(key) { + var iter = this.find(key) + if(iter) { + return iter.remove() + } + return this +} -count_loop: - for(var i=0; i 0 + } +}) - var triOffset = 0 - var lineOffset = triVertexCount - var color = [0,0,0,1] - var lineColor = [0,0,0,1] +//Node of the iterator +Object.defineProperty(iproto, "node", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1] + } + return null + }, + enumerable: true +}) - var isColorArray = Array.isArray(colors) && Array.isArray(colors[0]) - var isLineColorArray = Array.isArray(lineColors) && Array.isArray(lineColors[0]) +//Makes a copy of an iterator +iproto.clone = function() { + return new RedBlackTreeIterator(this.tree, this._stack.slice()) +} -fill_loop: - for(var i=0; i=0; --i) { + n = stack[i] + if(i === 0) { + n._color = BLACK + return } - - var glyphData - if(Array.isArray(glyphs)) { - glyphData = getGlyph(glyphs[i], font) - } else if(glyphs) { - glyphData = getGlyph(glyphs, font) + //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) + p = stack[i-1] + if(p.left === n) { + //console.log("left child") + s = p.right + if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.right = cloneNode(s) + z = s.right = cloneNode(s.right) + p.right = s.left + s.left = p + s.right = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + return + } else if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red") + s = p.right = cloneNode(s) + z = s.left = cloneNode(s.left) + p.right = z.left + s.left = z.right + z.left = p + z.right = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = z + } else { + pp.right = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent", p.right.value) + p._color = BLACK + p.right = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent", p.right.value) + p.right = repaint(RED, s) + continue + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.right = s.left + s.left = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } } else { - glyphData = getGlyph('●', font) - } - var glyphMesh = glyphData[0] - var glyphLines = glyphData[1] - var glyphBounds = glyphData[2] - - - //Get color - if(Array.isArray(colors)) { - var c - if(isColorArray) { - c = colors[i] + //console.log("right child") + s = p.left + if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red", p.value, p._color) + s = p.left = cloneNode(s) + z = s.left = cloneNode(s.left) + p.left = s.right + s.right = p + s.left = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + return + } else if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.left = cloneNode(s) + z = s.right = cloneNode(s.right) + p.left = z.right + s.right = z.left + z.right = p + z.left = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = z + } else { + pp.left = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent") + p._color = BLACK + p.left = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent") + p.left = repaint(RED, s) + continue + } } else { - c = colors - } - if(c.length === 3) { - for(var j=0; j<3; ++j) { - color[j] = c[j] + //console.log("case 3: red sibling") + s = cloneNode(s) + p.left = s.right + s.right = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } } - color[3] = 1 - } else if(c.length === 4) { - for(var j=0; j<4; ++j) { - color[j] = c[j] + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) } + i = i+2 } - } else { - color[0] = color[1] = color[2] = 0 - color[3] = 1 } + } +} - //Get lineColor - if(Array.isArray(lineColors)) { - var c - if(isLineColorArray) { - c = lineColors[i] - } else { - c = lineColors - } - if(c.length === 3) { - for(var j=0; j<3; ++j) { - lineColor[j] = c[j] - } - lineColor[j] = 1 - } else if(c.length === 4) { - for(var j=0; j<4; ++j) { - lineColor[j] = c[j] - } - } +//Removes item at iterator from tree +iproto.remove = function() { + var stack = this._stack + if(stack.length === 0) { + return this.tree + } + //First copy path to node + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + var n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) } else { - lineColor[0] = lineColor[1] = lineColor[2] = 0 - lineColor[3] = 1 + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } + } - var size = 0.5 - if(Array.isArray(sizes)) { - size = +sizes[i] - } else if(sizes) { - size = +sizes - } else if(this.useOrtho) { - size = 12 + //Get node + n = cstack[cstack.length-1] + //console.log("start remove: ", n.value) + + //If not leaf, then swap with previous node + if(n.left && n.right) { + //console.log("moving to leaf") + + //First walk to previous leaf + var split = cstack.length + n = n.left + while(n.right) { + cstack.push(n) + n = n.right } + //Copy path to leaf + var v = cstack[split-1] + cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) + cstack[split-1].key = n.key + cstack[split-1].value = n.value - var angle = 0 - if(Array.isArray(angles)) { - angle = +angles[i] - } else if(angles) { - angle = +angles + //Fix up stack + for(var i=cstack.length-2; i>=split; --i) { + n = cstack[i] + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } + cstack[split-1].left = cstack[split] + } + //console.log("stack=", cstack.map(function(v) { return v.value })) - //Loop through markers and append to buffers - var cos = Math.cos(angle) - var sin = Math.sin(angle) + //Remove leaf node + n = cstack[cstack.length-1] + if(n._color === RED) { + //Easy case: removing red leaf + //console.log("RED leaf") + var p = cstack[cstack.length-2] + if(p.left === n) { + p.left = null + } else if(p.right === n) { + p.right = null + } + cstack.pop() + for(var i=0; i 0) { + return this._stack[this._stack.length-1].key } + return + }, + enumerable: true +}) - //Calculate text offset - if(alignment[0] < 0) { - textOffset[0] = alignment[0] * (1+glyphBounds[1][0]) - } else if(alignment[0] > 0) { - textOffset[0] = -alignment[0] * (1+glyphBounds[0][0]) +//Returns value +Object.defineProperty(iproto, "value", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1].value } + return + }, + enumerable: true +}) - //Write out inner marker - var cells = glyphMesh.cells - var verts = glyphMesh.positions - for(var j=0; j=0; --s) { + if(stack[s+1] === stack[s].right) { + ++idx + if(stack[s].left) { + idx += stack[s].left._count } - idArray[lineOffset] = pickCounter - var p = verts[cell[k]] - glyphArray[2*lineOffset] = size * (cos*p[0] - sin*p[1] + textOffset[0]) - glyphArray[2*lineOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1]) - lineOffset += 1 } } + return idx + }, + enumerable: true +}) - //Increment pickCounter - pickCounter += 1 +//Advances iterator to next element in list +iproto.next = function() { + var stack = this._stack + if(stack.length === 0) { + return } - - - //Update vertex counts - this.vertexCount = triVertexCount - this.lineVertexCount = lineVertexCount - - //Update buffers - this.pointBuffer.update(positionArray) - this.colorBuffer.update(colorArray) - this.glyphBuffer.update(glyphArray) - this.idBuffer.update(new Uint32Array(idArray)) - - pool.free(positionArray) - pool.free(colorArray) - pool.free(glyphArray) - pool.free(idArray) - - //Update bounds - this.bounds = [lowerBound, upperBound] - - //Save points - this.points = points - - //Save number of points - this.pointCount = points.length -} - -proto.dispose = function() { - //Shaders - this.shader.dispose() - this.orthoShader.dispose() - this.pickPerspectiveShader.dispose() - this.pickOrthoShader.dispose() - - //Vertex array - this.vao.dispose() - - //Buffers - this.pointBuffer.dispose() - this.colorBuffer.dispose() - this.glyphBuffer.dispose() - this.idBuffer.dispose() -} - -function createPointCloud(options) { - var gl = options.gl - - var shader = shaders.createPerspective(gl) - var orthoShader = shaders.createOrtho(gl) - var projectShader = shaders.createProject(gl) - var pickPerspectiveShader = shaders.createPickPerspective(gl) - var pickOrthoShader = shaders.createPickOrtho(gl) - var pickProjectShader = shaders.createPickProject(gl) - - var pointBuffer = createBuffer(gl) - var colorBuffer = createBuffer(gl) - var glyphBuffer = createBuffer(gl) - var idBuffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - buffer: pointBuffer, - size: 3, - type: gl.FLOAT - }, - { - buffer: colorBuffer, - size: 4, - type: gl.FLOAT - }, - { - buffer: glyphBuffer, - size: 2, - type: gl.FLOAT - }, - { - buffer: idBuffer, - size: 4, - type: gl.UNSIGNED_BYTE, - normalized: true + var n = stack[stack.length-1] + if(n.right) { + n = n.right + while(n) { + stack.push(n) + n = n.left } - ]) - - var pointCloud = new PointCloud( - gl, - shader, - orthoShader, - projectShader, - pointBuffer, - colorBuffer, - glyphBuffer, - idBuffer, - vao, - pickPerspectiveShader, - pickOrthoShader, - pickProjectShader) - - pointCloud.update(options) - - return pointCloud + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].right === n) { + n = stack[stack.length-1] + stack.pop() + } + } } -},{"./lib/glyphs":191,"./lib/shaders":192,"gl-buffer":118,"gl-mat4/multiply":139,"gl-vao":226,"typedarray-pool":278}],194:[function(require,module,exports){ -'use strict' - - - -exports.boxVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n" -exports.boxFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n" - -},{}],195:[function(require,module,exports){ -'use strict' - -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') - -var SHADERS = require('./lib/shaders') - -module.exports = createSelectBox - -function SelectBox(plot, boxBuffer, boxShader) { - this.plot = plot - this.boxBuffer = boxBuffer - this.boxShader = boxShader - - this.enabled = true - - this.selectBox = [Infinity,Infinity,-Infinity,-Infinity] +//Checks if iterator is at end of tree +Object.defineProperty(iproto, "hasNext", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].right) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].left === stack[s]) { + return true + } + } + return false + } +}) - this.borderColor = [0,0,0,1] - this.innerFill = false - this.innerColor = [0,0,0,0.25] - this.outerFill = true - this.outerColor = [0,0,0,0.5] - this.borderWidth = 10 +//Update value +iproto.update = function(value) { + var stack = this._stack + if(stack.length === 0) { + throw new Error("Can't update empty node!") + } + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + } + return new RedBlackTree(this.tree._compare, cstack[0]) } -var proto = SelectBox.prototype - -proto.draw = function() { - if(!this.enabled) { +//Moves iterator backward one element +iproto.prev = function() { + var stack = this._stack + if(stack.length === 0) { return } - - var plot = this.plot - var selectBox = this.selectBox - var lineWidth = this.borderWidth - - var innerFill = this.innerFill - var innerColor = this.innerColor - var outerFill = this.outerFill - var outerColor = this.outerColor - var borderColor = this.borderColor - - var boxes = plot.box - var screenBox = plot.screenBox - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - - //Map select box into pixel coordinates - var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] - var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] - var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] - var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] - - loX = Math.max(loX, viewBox[0]) - loY = Math.max(loY, viewBox[1]) - hiX = Math.min(hiX, viewBox[2]) - hiY = Math.min(hiY, viewBox[3]) - - if(hiX < loX || hiY < loY) { - return + var n = stack[stack.length-1] + if(n.left) { + n = n.left + while(n) { + stack.push(n) + n = n.right + } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].left === n) { + n = stack[stack.length-1] + stack.pop() + } } +} - boxes.bind() - - //Draw box - var screenWidth = screenBox[2] - screenBox[0] - var screenHeight = screenBox[3] - screenBox[1] - - if(this.outerFill) { - boxes.drawBox(0, 0, screenWidth, loY, outerColor) - boxes.drawBox(0, loY, loX, hiY, outerColor) - boxes.drawBox(0, hiY, screenWidth, screenHeight, outerColor) - boxes.drawBox(hiX, loY, screenWidth, hiY, outerColor) +//Checks if iterator is at start of tree +Object.defineProperty(iproto, "hasPrev", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].left) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].right === stack[s]) { + return true + } + } + return false } +}) - if(this.innerFill) { - boxes.drawBox(loX, loY, hiX, hiY, innerColor) +//Default comparison function +function defaultCompare(a, b) { + if(a < b) { + return -1 } - - //Draw border - if(lineWidth > 0) { - - //Draw border - var w = lineWidth * pixelRatio - boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) - boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) - boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) - boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) + if(a > b) { + return 1 } + return 0 } -proto.update = function(options) { - options = options || {} - - this.innerFill = !!options.innerFill - this.outerFill = !!options.outerFill - this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() - this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() - this.borderColor = (options.borderColor || [0,0,0,1]).slice() - this.borderWidth = options.borderWidth || 0 - this.selectBox = (options.selectBox || this.selectBox).slice() -} - -proto.dispose = function() { - this.boxBuffer.dispose() - this.boxShader.dispose() - this.plot.removeOverlay(this) -} - -function createSelectBox(plot, options) { - var gl = plot.gl - var buffer = createBuffer(gl, [ - 0, 0, - 0, 1, - 1, 0, - 1, 1 ]) - var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment) - var selectBox = new SelectBox(plot, buffer, shader) - selectBox.update(options) - plot.addOverlay(selectBox) - return selectBox +//Build a tree +function createRBTree(compare) { + return new RedBlackTree(compare || defaultCompare, null) } +},{}],419:[function(require,module,exports){ +"use strict" -},{"./lib/shaders":194,"gl-buffer":118,"gl-shader":197}],196:[function(require,module,exports){ -'use strict' - -module.exports = createSelectBuffer +module.exports = createSlabDecomposition -var createFBO = require('gl-fbo') -var pool = require('typedarray-pool') -var ndarray = require('ndarray') +var bounds = require("binary-search-bounds") +var createRBTree = require("functional-red-black-tree") +var orient = require("robust-orientation") +var orderSegments = require("./lib/order-segments") -var nextPow2 = require('bit-twiddle').nextPow2 +function SlabDecomposition(slabs, coordinates, horizontal) { + this.slabs = slabs + this.coordinates = coordinates + this.horizontal = horizontal +} -var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_31_arg0_||255>_inline_31_arg1_||255>_inline_31_arg2_||255>_inline_31_arg3_){var _inline_31_l=_inline_31_arg4_-_inline_31_arg6_[0],_inline_31_a=_inline_31_arg5_-_inline_31_arg6_[1],_inline_31_f=_inline_31_l*_inline_31_l+_inline_31_a*_inline_31_a;_inline_31_f 0) { + if(p[0] !== seg[1][0]) { + lastNode = root + root = root.right + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } + } else { + if(p[0] !== seg[1][0]) { + return root + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } } - fbo.bind() - gl.readPixels(0,0,fbo.shape[0],fbo.shape[1],gl.RGBA,gl.UNSIGNED_BYTE,self.buffer) - self._readTimeout = null } + return lastNode } -var proto = SelectBuffer.prototype - -Object.defineProperty(proto, 'shape', { - get: function() { - if(!this.gl) { - return [0,0] +proto.castUp = function(p) { + var bucket = bounds.le(this.coordinates, p[0]) + if(bucket < 0) { + return -1 + } + var root = this.slabs[bucket] + var hitNode = searchBucket(this.slabs[bucket], p) + var lastHit = -1 + if(hitNode) { + lastHit = hitNode.value + } + //Edge case: need to handle horizontal segments (sucks) + if(this.coordinates[bucket] === p[0]) { + var lastSegment = null + if(hitNode) { + lastSegment = hitNode.key } - return this.fbo.shape.slice() - }, - set: function(v) { - if(!this.gl) { - return + if(bucket > 0) { + var otherHitNode = searchBucket(this.slabs[bucket-1], p) + if(otherHitNode) { + if(lastSegment) { + if(orderSegments(otherHitNode.key, lastSegment) > 0) { + lastSegment = otherHitNode.key + lastHit = otherHitNode.value + } + } else { + lastHit = otherHitNode.value + lastSegment = otherHitNode.key + } + } } - this.fbo.shape = v - var c = this.fbo.shape[0] - var r = this.fbo.shape[1] - if(r*c*4 > this.buffer.length) { - pool.free(this.buffer) - var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) - for(var i=0; i 0) { + var hbucket = bounds.ge(horiz, p[1], compareHorizontal) + if(hbucket < horiz.length) { + var e = horiz[hbucket] + if(p[1] === e.y) { + if(e.closed) { + return e.index + } else { + while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { + hbucket = hbucket+1 + e = horiz[hbucket] + if(e.closed) { + return e.index + } + } + if(e.y === p[1] && !e.start) { + hbucket = hbucket+1 + if(hbucket >= horiz.length) { + return lastHit + } + e = horiz[hbucket] + } + } + } + //Check if e is above/below last segment + if(e.start) { + if(lastSegment) { + var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) + if(lastSegment[0][0] > lastSegment[1][0]) { + o = -o + } + if(o > 0) { + lastHit = e.index + } + } else { + lastHit = e.index + } + } else if(e.y !== p[1]) { + lastHit = e.index + } } } - return v } -}) + return lastHit +} -proto.begin = function() { - var gl = this.gl - var shape = this.shape - if(!gl) { - return - } +function IntervalSegment(y, index, start, closed) { + this.y = y + this.index = index + this.start = start + this.closed = closed +} - this.fbo.bind() - gl.clearColor(1,1,1,1) - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) +function Event(x, segment, create, index) { + this.x = x + this.segment = segment + this.create = create + this.index = index } -proto.end = function() { - var gl = this.gl - if(!gl) { - return + +function createSlabDecomposition(segments) { + var numSegments = segments.length + var numEvents = 2 * numSegments + var events = new Array(numEvents) + for(var i=0; i 0 && coordinates[bucket] === p[0]) { + root = slabs[bucket-1] + } else { + return 1 + } + } + var lastOrientation = 1 + while(root) { + var s = root.key + var o = orient(p, s[0], s[1]) + if(s[0][0] < s[1][0]) { + if(o < 0) { + root = root.left + } else if(o > 0) { + lastOrientation = -1 + root = root.right + } else { + return 0 + } + } else { + if(o > 0) { + root = root.left + } else if(o < 0) { + lastOrientation = 1 + root = root.right + } else { + return 0 + } + } + } + return lastOrientation + } +} - return new SelectResult( - (dx + x0)|0, - (dy + y0)|0, - c0, - [c1, c2, c3], - Math.sqrt(closest[2])) +function classifyEmpty(p) { + return 1 } -proto.dispose = function() { - if(!this.gl) { - return - } - this.fbo.dispose() - pool.free(this.buffer) - this.gl = null - if(this._readTimeout) { - clearTimeout(this._readTimeout) +function createClassifyVertical(testVertical) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return 1 } } -function createSelectBuffer(gl, shape) { - var fbo = createFBO(gl, shape) - var buffer = pool.mallocUint8(shape[0]*shape[1]*4) - return new SelectBuffer(gl, fbo, buffer) +function createClassifyPointDegen(testVertical, testNormal) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return testNormal(p) + } } -},{"bit-twiddle":50,"cwise/lib/wrapper":112,"gl-fbo":123,"ndarray":253,"typedarray-pool":278}],197:[function(require,module,exports){ -'use strict' - -var createUniformWrapper = require('./lib/create-uniforms') -var createAttributeWrapper = require('./lib/create-attributes') -var makeReflect = require('./lib/reflect') -var shaderCache = require('./lib/shader-cache') -var runtime = require('./lib/runtime-reflect') -var GLError = require("./lib/GLError") +function preprocessPolygon(loops) { + //Compute number of loops + var numLoops = loops.length -//Shader object -function Shader(gl) { - this.gl = gl + //Unpack segments + var segments = [] + var vsegments = [] + var ptr = 0 + for(var i=0; i 0 } - //Sort attributes lexicographically - // overrides undefined WebGL behavior for attribute locations - attributes = attributes.slice() - attributes.sort(compareAttributes) + //Extract all clockwise faces + faces = faces.filter(ccw) - //Convert attribute types, read out locations - var attributeUnpacked = [] - var attributeNames = [] - var attributeLocations = [] - for(var i=0; i= 0) { - var size = attr.type.charAt(attr.type.length-1)|0 - var locVector = new Array(size) - for(var j=0; j= 0) { - curLocation += 1 + containment.sort(function(a,b) { + return b[0] - a[0] + }) + for(var i=0; i 0) { + var top = toVisit.pop() + var nbhd = fadj[top] + uniq(nbhd, function(a,b) { + return a-b + }) + var nnbhr = nbhd.length + var p = parity[top] + var polyline + if(p === 0) { + var c = faces[top] + polyline = [c] + } + for(var i=0; i= 0) { + continue + } + parity[f] = p^1 + toVisit.push(f) + if(p === 0) { + var c = faces[f] + if(!sharedBoundary(c)) { + c.reverse() + polyline.push(c) + } + } + } + if(p === 0) { + result.push(polyline) + } + } - //Generate uniform wrappers - Object.defineProperty(wrapper, 'uniforms', createUniformWrapper( - gl - , wrapper - , uniforms - , uniformLocations)) + return result } +},{"./lib/trim-leaves":407,"edges-to-adjacency-list":408,"planar-dual":409,"point-in-big-polygon":420,"robust-sum":421,"two-product":422,"uniq":423}],425:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],426:[function(require,module,exports){ +"use strict"; "use restrict"; -//Compiles and links a shader program with the given attribute and vertex list -function createShader( - gl - , vertSource - , fragSource - , uniforms - , attributes) { +module.exports = UnionFind; - var shader = new Shader(gl) +function UnionFind(count) { + this.roots = new Array(count); + this.ranks = new Array(count); + + for(var i=0; i> 1 + } + return (i >> 1) - 1 + } -Object.defineProperty(proto, 'location', { - get: function() { - return this._locations[this._index] + //Bubble element i down the heap + function heapDown(i) { + var w = heapWeight(i) + while(true) { + var tw = w + var left = 2*i + 1 + var right = 2*(i + 1) + var next = i + if(left < heapCount) { + var lw = heapWeight(left) + if(lw < tw) { + next = left + tw = lw + } + } + if(right < heapCount) { + var rw = heapWeight(right) + if(rw < tw) { + next = right + } + } + if(next === i) { + return i + } + heapSwap(i, next) + i = next + } } - , set: function(v) { - if(v !== this._locations[this._index]) { - this._locations[this._index] = v|0 - this._wrapper.program = null + + //Bubbles element i up the heap + function heapUp(i) { + var w = heapWeight(i) + while(i > 0) { + var parent = heapParent(i) + if(parent >= 0) { + var pw = heapWeight(parent) + if(w < pw) { + heapSwap(i, parent) + i = parent + continue + } + } + return i } - return v|0 } -}) -//Adds a vector attribute to obj -function addVectorAttribute( - gl - , wrapper - , index - , locations - , dimension - , obj - , name) { + //Pop minimum element + function heapPop() { + if(heapCount > 0) { + var head = heap[0] + heapSwap(0, heapCount-1) + heapCount -= 1 + heapDown(0) + return head + } + return -1 + } - //Construct constant function - var constFuncArgs = [ 'gl', 'v' ] - var varNames = [] - for(var i=0; i= 0) { + inv[t] = s + } + if(outv[s] >= 0) { + outv[s] = t + } - //Create accessor - Object.defineProperty(obj, name, { - set: function(x) { - gl.disableVertexAttribArray(locations[index]) - constFunc(gl, locations[index], x) - return x + //Update weights on s and t + if(index[s] >= 0) { + heapUpdate(index[s], computeWeight(s)) } - , get: function() { - return attr + if(index[t] >= 0) { + heapUpdate(index[t], computeWeight(t)) } - , enumerable: true - }) -} + } -function addMatrixAttribute( - gl - , wrapper - , index - , locations - , dimension - , obj - , name) { + //Initialize weights and heap + var heap = [] + var index = new Array(n) + for(var i=0; i>1; i>=0; --i) { + heapDown(i) + } + + //Kill vertices + while(true) { + var hmin = heapPop() + if((hmin < 0) || (weights[hmin] > minArea)) { + break + } + kill(hmin) + } - var parts = new Array(dimension) - var attrs = new Array(dimension) - for(var i=0; i= 0 && tout >= 0 && tin !== tout) { + var cin = index[tin] + var cout = index[tout] + if(cin !== cout) { + ncells.push([ cin, cout ]) } - return x - } - , get: function() { - return parts } - , enumerable: true }) -} -//Create shims for attributes -function createAttributeWrapper( - gl - , wrapper - , attributes - , locations) { + //Normalize result + sc.unique(sc.normalize(ncells)) - var obj = {} - for(var i=0, n=attributes.length; i= 0) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addVectorAttribute( - gl - , wrapper - , locs[0] - , locations - , d - , obj - , name) - } else if(type.indexOf('mat') >= 0) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addMatrixAttribute( - gl - , wrapper - , locs - , locations - , d - , obj - , name) - } else { - throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type) - } - break +//Helper macros +function array(i) { + return "a" + i +} +function data(i) { + return "d" + i +} +function cube(i,bitmask) { + return "c" + i + "_" + bitmask +} +function shape(i) { + return "s" + i +} +function stride(i,j) { + return "t" + i + "_" + j +} +function offset(i) { + return "o" + i +} +function scalar(i) { + return "x" + i +} +function pointer(i) { + return "p" + i +} +function delta(i,bitmask) { + return "d" + i + "_" + bitmask +} +function index(i) { + return "i" + i +} +function step(i,j) { + return "u" + i + "_" + j +} +function pcube(bitmask) { + return "b" + bitmask +} +function qcube(bitmask) { + return "y" + bitmask +} +function pdelta(bitmask) { + return "e" + bitmask +} +function vert(i) { + return "v" + i +} +var VERTEX_IDS = "V" +var PHASES = "P" +var VERTEX_COUNT = "N" +var POOL_SIZE = "Q" +var POINTER = "X" +var TEMPORARY = "T" + +function permBitmask(dimension, mask, order) { + var r = 0 + for(var i=0; i 0) { + stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) + } + vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + } + } + //Create index variables + for(var i=0; i=0; --i) { + sizeVariable.push(shape(order[i])) + } + //Previous phases and vertex_ids + vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", + PHASES + "=mallocUint32(" + POOL_SIZE + ")", + VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", + POINTER + "=0") + //Create cube variables for phases + vars.push(pcube(0) + "=0") + for(var j=1; j<(1< 4) { - throw new GLError('', 'Invalid data type') - } - switch(type.charAt(0)) { - case 'b': - case 'i': - return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' - case 'v': - return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' - default: - throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type) - } - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) - } - return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' - } else { - throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) - } - break + function forLoopEnd(i) { + for(var j=0; j=0; --i) { + forLoopBegin(i, 0) } - var indices = [] - for(var id in type) { - var prop = type[id] - var tprefix = prefix - if(parseInt(id) + '' === id) { - tprefix += '[' + id + ']' + var phaseFuncArgs = [] + for(var i=0; i 4) { - throw new GLError('', 'Invalid data type') - } - if(type.charAt(0) === 'b') { - return makeVector(d, false) - } - return makeVector(d, 0) - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + //Generate vertex + code.push("vertex(", vertexArgs.join(), ");", + vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;") + + //Check for face crossings + var base = (1<0; k=(k-1)&subset) { + faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") + } + faceArgs.push(vert(0)) + for(var k=0; k0){", + index(order[i]), "=1;") + createLoop(i-1, mask|(1< 0") + } + if(typeof args.vertex !== "function") { + error("Must specify vertex creation function") + } + if(typeof args.cell !== "function") { + error("Must specify cell creation function") + } + if(typeof args.phase !== "function") { + error("Must specify phase function") + } + var getters = args.getters || [] + var typesig = new Array(arrays) + for(var i=0; i= 0) { + typesig[i] = true + } else { + typesig[i] = false + } } + return compileSurfaceProcedure( + args.vertex, + args.cell, + args.phase, + scalars, + order, + typesig) } +},{"typedarray-pool":432}],430:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],431:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],432:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":430,"buffer":65,"dup":122}],433:[function(require,module,exports){ +// transliterated from the python snippet here: +// http://en.wikipedia.org/wiki/Lanczos_approximation -},{"./GLError":198,"./reflect":201}],201:[function(require,module,exports){ -'use strict' +var g = 7; +var p = [ + 0.99999999999980993, + 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 +]; -module.exports = makeReflectTypes +var g_ln = 607/128; +var p_ln = [ + 0.99999999999999709182, + 57.156235665862923517, + -59.597960355475491248, + 14.136097974741747174, + -0.49191381609762019978, + 0.33994649984811888699e-4, + 0.46523628927048575665e-4, + -0.98374475304879564677e-4, + 0.15808870322491248884e-3, + -0.21026444172410488319e-3, + 0.21743961811521264320e-3, + -0.16431810653676389022e-3, + 0.84418223983852743293e-4, + -0.26190838401581408670e-4, + 0.36899182659531622704e-5 +]; -//Construct type info for reflection. -// -// This iterates over the flattened list of uniform type values and smashes them into a JSON object. -// -// The leaves of the resulting object are either indices or type strings representing primitive glslify types -function makeReflectTypes(uniforms, useIndex) { - var obj = {} - for(var i=0; i 1) { - if(!(x[0] in o)) { - o[x[0]] = [] +// Spouge approximation (suitable for large arguments) +function lngamma(z) { + + if(z < 0) return Number('0/0'); + var x = p_ln[0]; + for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); + var t = z + g_ln + 0.5; + return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); +} + +module.exports = function gamma (z) { + if (z < 0.5) { + return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); + } + else if(z > 100) return Math.exp(lngamma(z)); + else { + z -= 1; + var x = p[0]; + for (var i = 1; i < g + 2; i++) { + x += p[i] / (z + i); } - o = o[x[0]] - for(var k=1; k0; --i) { + t = pinv[i] + s = p[i] + p[i] = p[t] + p[t] = s + pinv[i] = pinv[s] + pinv[s] = t + r = (r + s) * i + } + pool.freeUint32(pinv) + pool.freeUint32(p) + return r } -function runtimeUniforms(gl, program) { - var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS) - var result = [] - for(var i=0; i 1) { - for(var j=0; j0; --i) { + s = (r / nf)|0 + r = (r - s * nf)|0 + nf = (nf / i)|0 + t = p[i]|0 + p[i] = p[s]|0 + p[s] = t|0 + } + return p } -function runtimeAttributes(gl, program) { - var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES) - var result = [] - for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", + "args": [{ + "name": "_inline_1_arg0_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg1_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg2_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg3_", + "lvalue": false, + "rvalue": true, + "count": 2 + }, { + "name": "_inline_1_arg4_", + "lvalue": false, + "rvalue": true, + "count": 1 + }], + "thisVars": [], + "localVars": ["_inline_1_da", "_inline_1_db"] + }, + funcName: 'zeroCrossings' +}) -ShaderReference.prototype.dispose = function() { - if(--this.count === 0) { - var cache = this.cache - var gl = cache.gl +},{"cwise-compiler":445}],445:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./lib/thunk.js":447,"dup":319}],446:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320,"uniq":448}],447:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"./compile.js":446,"dup":321}],448:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],449:[function(require,module,exports){ +"use strict" - //Remove program references - var programs = this.programs - for(var i=0, n=programs.length; i c)|0 },") + if(dtype === "generic") { + code.push("getters:[0],") } - return shader -} -proto.getShaderReference = function(type, src) { - var gl = this.gl - var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0] - var shader = shaders[src] - if(!shader || !gl.isShader(shader.shader)) { - var shaderObj = compileShader(gl, type, src) - shader = shaders[src] = new ShaderReference( - SHADER_COUNTER++, - src, - type, - shaderObj, - [], - 1, - this) + //Generate vertex function + var cubeArgs = [] + var extraArgs = [] + for(var i=0; i>>7){") } - return shader -} - -function linkProgram(gl, vshader, fshader, attribs, locations) { - var program = gl.createProgram() - gl.attachShader(program, vshader) - gl.attachShader(program, fshader) - for(var i=0; i 128) { + if((i%128)===0) { + if(extraFuncs.length > 0) { + currentFunc.push("}}") + } + var efName = "vExtra" + extraFuncs.length + code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") + currentFunc = [ + "function ", efName, "(m,", extraArgs.join(), "){switch(m){" + ] + extraFuncs.push(currentFunc) + } + } + currentFunc.push("case ", (i&0x7f), ":") + var crossings = new Array(dimension) + var denoms = new Array(dimension) + var crossingCount = new Array(dimension) + var bias = new Array(dimension) + var totalCrossings = 0 + for(var j=0; j j) { + continue + } + if(!(i&(1< 0) { + cStr = "+" + crossingCount[k] + "*c" + } + var weight = 0.5 * (crossings[k].length / totalCrossings) + var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) + vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") + + } + } + currentFunc.push("a.push([", vertexStr.join(), "]);", + "break;") } - gl.linkProgram(program) - if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { - var errLog = gl.getProgramInfoLog(program) - throw new GLError(errLog, 'Error linking program: ' + errLog) + code.push("}},") + if(extraFuncs.length > 0) { + currentFunc.push("}}") } - return program -} -proto.getProgram = function(vref, fref, attribs, locations) { - var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') - var prog = this.programs[token] - if(!prog || !this.gl.isProgram(prog)) { - this.programs[token] = prog = linkProgram( - this.gl, - vref.shader, - fref.shader, - attribs, - locations) - vref.programs.push(token) - fref.programs.push(token) + //Create face function + var faceArgs = [] + for(var i=0; i<(1<<(dimension-1)); ++i) { + faceArgs.push("v" + i) } - return prog -} + faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c") + code.push("cell:function cellFunc(", faceArgs.join(), "){") -function getCache(gl) { - var ctxCache = CACHE.get(gl) - if(!ctxCache) { - ctxCache = new ContextCache(gl) - CACHE.set(gl, ctxCache) + var facets = triangulateCube(dimension-1) + code.push("if(p0){b.push(", + facets.map(function(f) { + return "[" + f.map(function(v) { + return "v" + v + }) + "]" + }).join(), ")}else{b.push(", + facets.map(function(f) { + var e = f.slice() + e.reverse() + return "[" + e.map(function(v) { + return "v" + v + }) + "]" + }).join(), + ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";") + + for(var i=0; i0) { + shapeX += 0.02 + } + } - var errorStrings = errLog.split('\n'); - var errors = {}; + var data = new Float32Array(bufferSize) + var ptr = 0 + var xOffset = -0.5 * shapeX + for(var i=0; i - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ + this.gridLineEnable = [true,true] + this.gridLineWidth = [1,1] + this.gridLineColor = [[0,0,0,1], + [0,0,0,1]] -'use strict'; + this.pixelRatio = 1 -var repeat = require('repeat-string'); + this.tickMarkLength = [0,0,0,0] + this.tickMarkWidth = [0,0,0,0] + this.tickMarkColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -module.exports = function padLeft(str, num, ch) { - ch = typeof ch !== 'undefined' ? (ch + '') : ' '; - return repeat(ch, num) + str; -}; -},{"repeat-string":254}],207:[function(require,module,exports){ -module.exports = { - 0: 'NONE', - 1: 'ONE', - 2: 'LINE_LOOP', - 3: 'LINE_STRIP', - 4: 'TRIANGLES', - 5: 'TRIANGLE_STRIP', - 6: 'TRIANGLE_FAN', - 256: 'DEPTH_BUFFER_BIT', - 512: 'NEVER', - 513: 'LESS', - 514: 'EQUAL', - 515: 'LEQUAL', - 516: 'GREATER', - 517: 'NOTEQUAL', - 518: 'GEQUAL', - 519: 'ALWAYS', - 768: 'SRC_COLOR', - 769: 'ONE_MINUS_SRC_COLOR', - 770: 'SRC_ALPHA', - 771: 'ONE_MINUS_SRC_ALPHA', - 772: 'DST_ALPHA', - 773: 'ONE_MINUS_DST_ALPHA', - 774: 'DST_COLOR', - 775: 'ONE_MINUS_DST_COLOR', - 776: 'SRC_ALPHA_SATURATE', - 1024: 'STENCIL_BUFFER_BIT', - 1028: 'FRONT', - 1029: 'BACK', - 1032: 'FRONT_AND_BACK', - 1280: 'INVALID_ENUM', - 1281: 'INVALID_VALUE', - 1282: 'INVALID_OPERATION', - 1285: 'OUT_OF_MEMORY', - 1286: 'INVALID_FRAMEBUFFER_OPERATION', - 2304: 'CW', - 2305: 'CCW', - 2849: 'LINE_WIDTH', - 2884: 'CULL_FACE', - 2885: 'CULL_FACE_MODE', - 2886: 'FRONT_FACE', - 2928: 'DEPTH_RANGE', - 2929: 'DEPTH_TEST', - 2930: 'DEPTH_WRITEMASK', - 2931: 'DEPTH_CLEAR_VALUE', - 2932: 'DEPTH_FUNC', - 2960: 'STENCIL_TEST', - 2961: 'STENCIL_CLEAR_VALUE', - 2962: 'STENCIL_FUNC', - 2963: 'STENCIL_VALUE_MASK', - 2964: 'STENCIL_FAIL', - 2965: 'STENCIL_PASS_DEPTH_FAIL', - 2966: 'STENCIL_PASS_DEPTH_PASS', - 2967: 'STENCIL_REF', - 2968: 'STENCIL_WRITEMASK', - 2978: 'VIEWPORT', - 3024: 'DITHER', - 3042: 'BLEND', - 3088: 'SCISSOR_BOX', - 3089: 'SCISSOR_TEST', - 3106: 'COLOR_CLEAR_VALUE', - 3107: 'COLOR_WRITEMASK', - 3317: 'UNPACK_ALIGNMENT', - 3333: 'PACK_ALIGNMENT', - 3379: 'MAX_TEXTURE_SIZE', - 3386: 'MAX_VIEWPORT_DIMS', - 3408: 'SUBPIXEL_BITS', - 3410: 'RED_BITS', - 3411: 'GREEN_BITS', - 3412: 'BLUE_BITS', - 3413: 'ALPHA_BITS', - 3414: 'DEPTH_BITS', - 3415: 'STENCIL_BITS', - 3553: 'TEXTURE_2D', - 4352: 'DONT_CARE', - 4353: 'FASTEST', - 4354: 'NICEST', - 5120: 'BYTE', - 5121: 'UNSIGNED_BYTE', - 5122: 'SHORT', - 5123: 'UNSIGNED_SHORT', - 5124: 'INT', - 5125: 'UNSIGNED_INT', - 5126: 'FLOAT', - 5386: 'INVERT', - 5890: 'TEXTURE', - 6401: 'STENCIL_INDEX', - 6402: 'DEPTH_COMPONENT', - 6406: 'ALPHA', - 6407: 'RGB', - 6408: 'RGBA', - 6409: 'LUMINANCE', - 6410: 'LUMINANCE_ALPHA', - 7680: 'KEEP', - 7681: 'REPLACE', - 7682: 'INCR', - 7683: 'DECR', - 7936: 'VENDOR', - 7937: 'RENDERER', - 7938: 'VERSION', - 9728: 'NEAREST', - 9729: 'LINEAR', - 9984: 'NEAREST_MIPMAP_NEAREST', - 9985: 'LINEAR_MIPMAP_NEAREST', - 9986: 'NEAREST_MIPMAP_LINEAR', - 9987: 'LINEAR_MIPMAP_LINEAR', - 10240: 'TEXTURE_MAG_FILTER', - 10241: 'TEXTURE_MIN_FILTER', - 10242: 'TEXTURE_WRAP_S', - 10243: 'TEXTURE_WRAP_T', - 10497: 'REPEAT', - 10752: 'POLYGON_OFFSET_UNITS', - 16384: 'COLOR_BUFFER_BIT', - 32769: 'CONSTANT_COLOR', - 32770: 'ONE_MINUS_CONSTANT_COLOR', - 32771: 'CONSTANT_ALPHA', - 32772: 'ONE_MINUS_CONSTANT_ALPHA', - 32773: 'BLEND_COLOR', - 32774: 'FUNC_ADD', - 32777: 'BLEND_EQUATION_RGB', - 32778: 'FUNC_SUBTRACT', - 32779: 'FUNC_REVERSE_SUBTRACT', - 32819: 'UNSIGNED_SHORT_4_4_4_4', - 32820: 'UNSIGNED_SHORT_5_5_5_1', - 32823: 'POLYGON_OFFSET_FILL', - 32824: 'POLYGON_OFFSET_FACTOR', - 32854: 'RGBA4', - 32855: 'RGB5_A1', - 32873: 'TEXTURE_BINDING_2D', - 32926: 'SAMPLE_ALPHA_TO_COVERAGE', - 32928: 'SAMPLE_COVERAGE', - 32936: 'SAMPLE_BUFFERS', - 32937: 'SAMPLES', - 32938: 'SAMPLE_COVERAGE_VALUE', - 32939: 'SAMPLE_COVERAGE_INVERT', - 32968: 'BLEND_DST_RGB', - 32969: 'BLEND_SRC_RGB', - 32970: 'BLEND_DST_ALPHA', - 32971: 'BLEND_SRC_ALPHA', - 33071: 'CLAMP_TO_EDGE', - 33170: 'GENERATE_MIPMAP_HINT', - 33189: 'DEPTH_COMPONENT16', - 33306: 'DEPTH_STENCIL_ATTACHMENT', - 33635: 'UNSIGNED_SHORT_5_6_5', - 33648: 'MIRRORED_REPEAT', - 33901: 'ALIASED_POINT_SIZE_RANGE', - 33902: 'ALIASED_LINE_WIDTH_RANGE', - 33984: 'TEXTURE0', - 33985: 'TEXTURE1', - 33986: 'TEXTURE2', - 33987: 'TEXTURE3', - 33988: 'TEXTURE4', - 33989: 'TEXTURE5', - 33990: 'TEXTURE6', - 33991: 'TEXTURE7', - 33992: 'TEXTURE8', - 33993: 'TEXTURE9', - 33994: 'TEXTURE10', - 33995: 'TEXTURE11', - 33996: 'TEXTURE12', - 33997: 'TEXTURE13', - 33998: 'TEXTURE14', - 33999: 'TEXTURE15', - 34000: 'TEXTURE16', - 34001: 'TEXTURE17', - 34002: 'TEXTURE18', - 34003: 'TEXTURE19', - 34004: 'TEXTURE20', - 34005: 'TEXTURE21', - 34006: 'TEXTURE22', - 34007: 'TEXTURE23', - 34008: 'TEXTURE24', - 34009: 'TEXTURE25', - 34010: 'TEXTURE26', - 34011: 'TEXTURE27', - 34012: 'TEXTURE28', - 34013: 'TEXTURE29', - 34014: 'TEXTURE30', - 34015: 'TEXTURE31', - 34016: 'ACTIVE_TEXTURE', - 34024: 'MAX_RENDERBUFFER_SIZE', - 34041: 'DEPTH_STENCIL', - 34055: 'INCR_WRAP', - 34056: 'DECR_WRAP', - 34067: 'TEXTURE_CUBE_MAP', - 34068: 'TEXTURE_BINDING_CUBE_MAP', - 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', - 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', - 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', - 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', - 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', - 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', - 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', - 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', - 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', - 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', - 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', - 34342: 'CURRENT_VERTEX_ATTRIB', - 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', - 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', - 34467: 'COMPRESSED_TEXTURE_FORMATS', - 34660: 'BUFFER_SIZE', - 34661: 'BUFFER_USAGE', - 34816: 'STENCIL_BACK_FUNC', - 34817: 'STENCIL_BACK_FAIL', - 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', - 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', - 34877: 'BLEND_EQUATION_ALPHA', - 34921: 'MAX_VERTEX_ATTRIBS', - 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', - 34930: 'MAX_TEXTURE_IMAGE_UNITS', - 34962: 'ARRAY_BUFFER', - 34963: 'ELEMENT_ARRAY_BUFFER', - 34964: 'ARRAY_BUFFER_BINDING', - 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', - 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', - 35040: 'STREAM_DRAW', - 35044: 'STATIC_DRAW', - 35048: 'DYNAMIC_DRAW', - 35632: 'FRAGMENT_SHADER', - 35633: 'VERTEX_SHADER', - 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', - 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', - 35663: 'SHADER_TYPE', - 35664: 'FLOAT_VEC2', - 35665: 'FLOAT_VEC3', - 35666: 'FLOAT_VEC4', - 35667: 'INT_VEC2', - 35668: 'INT_VEC3', - 35669: 'INT_VEC4', - 35670: 'BOOL', - 35671: 'BOOL_VEC2', - 35672: 'BOOL_VEC3', - 35673: 'BOOL_VEC4', - 35674: 'FLOAT_MAT2', - 35675: 'FLOAT_MAT3', - 35676: 'FLOAT_MAT4', - 35678: 'SAMPLER_2D', - 35680: 'SAMPLER_CUBE', - 35712: 'DELETE_STATUS', - 35713: 'COMPILE_STATUS', - 35714: 'LINK_STATUS', - 35715: 'VALIDATE_STATUS', - 35716: 'INFO_LOG_LENGTH', - 35717: 'ATTACHED_SHADERS', - 35718: 'ACTIVE_UNIFORMS', - 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', - 35720: 'SHADER_SOURCE_LENGTH', - 35721: 'ACTIVE_ATTRIBUTES', - 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', - 35724: 'SHADING_LANGUAGE_VERSION', - 35725: 'CURRENT_PROGRAM', - 36003: 'STENCIL_BACK_REF', - 36004: 'STENCIL_BACK_VALUE_MASK', - 36005: 'STENCIL_BACK_WRITEMASK', - 36006: 'FRAMEBUFFER_BINDING', - 36007: 'RENDERBUFFER_BINDING', - 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', - 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', - 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', - 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', - 36053: 'FRAMEBUFFER_COMPLETE', - 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', - 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', - 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', - 36061: 'FRAMEBUFFER_UNSUPPORTED', - 36064: 'COLOR_ATTACHMENT0', - 36096: 'DEPTH_ATTACHMENT', - 36128: 'STENCIL_ATTACHMENT', - 36160: 'FRAMEBUFFER', - 36161: 'RENDERBUFFER', - 36162: 'RENDERBUFFER_WIDTH', - 36163: 'RENDERBUFFER_HEIGHT', - 36164: 'RENDERBUFFER_INTERNAL_FORMAT', - 36168: 'STENCIL_INDEX8', - 36176: 'RENDERBUFFER_RED_SIZE', - 36177: 'RENDERBUFFER_GREEN_SIZE', - 36178: 'RENDERBUFFER_BLUE_SIZE', - 36179: 'RENDERBUFFER_ALPHA_SIZE', - 36180: 'RENDERBUFFER_DEPTH_SIZE', - 36181: 'RENDERBUFFER_STENCIL_SIZE', - 36194: 'RGB565', - 36336: 'LOW_FLOAT', - 36337: 'MEDIUM_FLOAT', - 36338: 'HIGH_FLOAT', - 36339: 'LOW_INT', - 36340: 'MEDIUM_INT', - 36341: 'HIGH_INT', - 36346: 'SHADER_COMPILER', - 36347: 'MAX_VERTEX_UNIFORM_VECTORS', - 36348: 'MAX_VARYING_VECTORS', - 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', - 37440: 'UNPACK_FLIP_Y_WEBGL', - 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', - 37442: 'CONTEXT_LOST_WEBGL', - 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', - 37444: 'BROWSER_DEFAULT_WEBGL' -} + this.tickPad = [15,15,15,15] + this.tickAngle = [0,0,0,0] + this.tickEnable = [true,true,true,true] + this.tickColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -},{}],208:[function(require,module,exports){ -var gl10 = require('./1.0/numbers') + this.labelPad = [15,15,15,15] + this.labelAngle = [0,Math.PI/2,0,3.0*Math.PI/2] + this.labelEnable = [true,true,true,true] + this.labelColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -module.exports = function lookupConstant (number) { - return gl10[number] -} + this.titleCenter = [0,0] + this.titleEnable = true + this.titleAngle = 0 + this.titleColor = [0,0,0,1] -},{"./1.0/numbers":207}],209:[function(require,module,exports){ -var tokenize = require('glsl-tokenizer') -var atob = require('atob-lite') + this.borderColor = [0,0,0,0] + this.backgroundColor = [0,0,0,0] -module.exports = getName + this.zeroLineEnable = [true, true] + this.zeroLineWidth = [4, 4] + this.zeroLineColor = [[0, 0, 0, 1],[0, 0, 0, 1]] -function getName(src) { - var tokens = Array.isArray(src) - ? src - : tokenize(src) + this.borderLineEnable = [true,true,true,true] + this.borderLineWidth = [2,2,2,2] + this.borderLineColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i] - if (token.type !== 'preprocessor') continue - var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) - if (!match) continue - if (!match[2]) continue + //Drawing parameters + this.grid = null + this.text = null + this.line = null + this.box = null + this.objects = [] + this.overlays = [] - var b64 = match[1] - var name = match[2] + this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] - return (b64 ? atob(name) : name).trim() - } -} + this.dirty = false + this.pickDirty = false + this.pickDelay = 120 + this.pickRadius = 10 + this._pickTimeout = null + this._drawPick = this.drawPick.bind(this) -},{"atob-lite":210,"glsl-tokenizer":234}],210:[function(require,module,exports){ -module.exports = function _atob(str) { - return atob(str) + this._depthCounter = 0 } -},{}],211:[function(require,module,exports){ -(function(window) { - var re = { - not_string: /[^s]/, - number: /[diefg]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[\+\-]/ - } - - function sprintf() { - var key = arguments[0], cache = sprintf.cache - if (!(cache[key] && cache.hasOwnProperty(key))) { - cache[key] = sprintf.parse(key) - } - return sprintf.format.call(null, cache[key], arguments) - } +var proto = GLPlot2D.prototype - sprintf.format = function(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]) - if (node_type === "string") { - output[output.length] = parse_tree[i] - } - else if (node_type === "array") { - match = parse_tree[i] // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor] - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) - } - arg = arg[match[2][k]] - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } +proto.setDirty = function() { + this.dirty = this.pickDirty = true +} - if (get_type(arg) == "function") { - arg = arg() - } +proto.setOverlayDirty = function() { + this.dirty = true +} - if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { - throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) - } +proto.nextDepthValue = function() { + return (this._depthCounter++) / 65536.0 +} - if (re.number.test(match[8])) { - is_positive = arg >= 0 - } +function lerp(a, b, t) { + var s = 0.5 * (t + 1.0) + return Math.floor((1.0-s)*a + s*b)|0 +} - switch (match[8]) { - case "b": - arg = arg.toString(2) - break - case "c": - arg = String.fromCharCode(arg) - break - case "d": - case "i": - arg = parseInt(arg, 10) - break - case "j": - arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) - break - case "e": - arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() - break - case "f": - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) - break - case "g": - arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) - break - case "o": - arg = arg.toString(8) - break - case "s": - arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) - break - case "u": - arg = arg >>> 0 - break - case "x": - arg = arg.toString(16) - break - case "X": - arg = arg.toString(16).toUpperCase() - break - } - if (re.json.test(match[8])) { - output[output.length] = arg - } - else { - if (re.number.test(match[8]) && (!is_positive || match[3])) { - sign = is_positive ? "+" : "-" - arg = arg.toString().replace(re.sign, "") - } - else { - sign = "" - } - pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " - pad_length = match[6] - (sign + arg).length - pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" - output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) - } - } - } - return output.join("") - } +proto.draw = (function() { +var TICK_MARK_BOX = [0,0,0,0] +return function() { + var gl = this.gl + var screenBox = this.screenBox + var viewPixels = this.viewBox + var dataBox = this.dataBox + var pixelRatio = this.pixelRatio + var grid = this.grid + var line = this.line + var text = this.text + var objects = this.objects - sprintf.cache = {} + this._depthCounter = 0 - sprintf.parse = function(fmt) { - var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = match[0] - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = "%" - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - } - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") - } - parse_tree[parse_tree.length] = match - } - else { - throw new SyntaxError("[sprintf] unexpected placeholder") - } - _fmt = _fmt.substring(match[0].length) - } - return parse_tree + if(this.pickDirty) { + if(this._pickTimeout) { + clearTimeout(this._pickTimeout) } + this.pickDirty = false + this._pickTimeout = setTimeout(this._drawPick, this.pickDelay) + } - var vsprintf = function(fmt, argv, _argv) { - _argv = (argv || []).slice(0) - _argv.splice(0, 0, fmt) - return sprintf.apply(null, _argv) - } + if(!this.dirty) { + return + } + this.dirty = false - /** - * helpers - */ - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() - } + gl.bindFramebuffer(gl.FRAMEBUFFER, null) - function str_repeat(input, multiplier) { - return Array(multiplier + 1).join(input) - } + //Turn on scissor + gl.enable(gl.SCISSOR_TEST) - /** - * export to either browser or node.js - */ - if (typeof exports !== "undefined") { - exports.sprintf = sprintf - exports.vsprintf = vsprintf - } - else { - window.sprintf = sprintf - window.vsprintf = vsprintf + //Turn off depth buffer + gl.disable(gl.DEPTH_TEST) + gl.depthFunc(gl.LESS) + gl.depthMask(false) - if (typeof define === "function" && define.amd) { - define(function() { - return { - sprintf: sprintf, - vsprintf: vsprintf - } - }) - } - } -})(typeof window === "undefined" ? this : window); + //Configure premultiplied alpha blending + gl.enable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); -},{}],212:[function(require,module,exports){ -var hiddenStore = require('./hidden-store.js'); + //Draw border + gl.scissor( + screenBox[0], + screenBox[1], + screenBox[2]-screenBox[0], + screenBox[3]-screenBox[1]) + var borderColor = this.borderColor + gl.clearColor( + borderColor[0]*borderColor[3], + borderColor[1]*borderColor[3], + borderColor[2]*borderColor[3], + borderColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) -module.exports = createStore; + //Draw center pane + gl.scissor( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + gl.viewport( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + var backgroundColor = this.backgroundColor + gl.clearColor( + backgroundColor[0]*backgroundColor[3], + backgroundColor[1]*backgroundColor[3], + backgroundColor[2]*backgroundColor[3], + backgroundColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT) -function createStore() { - var key = {}; + //Draw grid + grid.draw() - return function (obj) { - if ((typeof obj !== 'object' || obj === null) && - typeof obj !== 'function' - ) { - throw new Error('Weakmap-shim: Key must be object') - } + //Draw zero lines separately + var zeroLineEnable = this.zeroLineEnable + var zeroLineColor = this.zeroLineColor + var zeroLineWidth = this.zeroLineWidth + if(zeroLineEnable[0] || zeroLineEnable[1]) { + line.bind() + for(var i=0; i<2; ++i) { + if(!zeroLineEnable[i] || + !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) { + continue + } - var store = obj.valueOf(key); - return store && store.identity === key ? - store : hiddenStore(obj, key); - }; -} + var zeroIntercept = screenBox[i] - + dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) -},{"./hidden-store.js":213}],213:[function(require,module,exports){ -module.exports = hiddenStore; + if(i === 0) { + line.drawLine( + zeroIntercept, screenBox[1], zeroIntercept, screenBox[3], + zeroLineWidth[i], + zeroLineColor[i]) + } else { + line.drawLine( + screenBox[0], zeroIntercept, screenBox[2], zeroIntercept, + zeroLineWidth[i], + zeroLineColor[i]) + } + } + } -function hiddenStore(obj, key) { - var store = { identity: key }; - var valueOf = obj.valueOf; + //Draw traces + for(var i=0; i= 0) { - pickStr.push('0') - } else if(facet.indexOf(-(i+1)) >= 0) { - pickStr.push('s['+i+']-1') - } else { - pickStr.push('-1') - loStr.push('1') - hiStr.push('s['+i+']-2') - } - } - var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')' - if(loStr.length === 0) { - boundStr = '' - } - - if(cod > 0) { - code.push('if(1') - for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { - continue - } - code.push('&&s[', i, ']>2') - } - code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) - for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { - continue - } - code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr) - } - code.push(');') - } + var gl = this.gl - for(var i=0; i1){dst.set(', - pickStr.join(), ',', bnd, ',0.5*(src.get(', - cPickStr.join(), ')-src.get(', - dPickStr.join(), ')))}else{dst.set(', - pickStr.join(), ',', bnd, ',0)};') - } else { - code.push('if(s[', bnd, ']>1){diff(', outStr, - ',src.pick(', cPickStr.join(), ')', boundStr, - ',src.pick(', dPickStr.join(), ')', boundStr, - ');}else{zero(', outStr, ');};') - } - break + var pixelRatio = this.pixelRatio + this.pickPixelRatio = Math.max(pixelRatio, 1) - case 'mirror': - if(cod === 0) { - code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') - } else { - code.push('zero(', outStr, ');') - } - break + this.setScreenBox(options.screenBox || + [0, 0, gl.drawingBufferWidth/pixelRatio, gl.drawingBufferHeight/pixelRatio]) - case 'wrap': - var aPickStr = pickStr.slice() - var bPickStr = pickStr.slice() - if(facet[i] < 0) { - aPickStr[bnd] = 's[' + bnd + ']-2' - bPickStr[bnd] = '0' - - } else { - aPickStr[bnd] = 's[' + bnd + ']-1' - bPickStr[bnd] = '1' - } - if(cod === 0) { - code.push('if(s[', bnd, ']>2){dst.set(', - pickStr.join(), ',', bnd, ',0.5*(src.get(', - aPickStr.join(), ')-src.get(', - bPickStr.join(), ')))}else{dst.set(', - pickStr.join(), ',', bnd, ',0)};') - } else { - code.push('if(s[', bnd, ']>2){diff(', outStr, - ',src.pick(', aPickStr.join(), ')', boundStr, - ',src.pick(', bPickStr.join(), ')', boundStr, - ');}else{zero(', outStr, ');};') - } - break + var screenBox = this.screenBox + this.setViewBox(options.viewBox || + [0.125*(this.screenBox[2]-this.screenBox[0])/pixelRatio, + 0.125*(this.screenBox[3]-this.screenBox[1])/pixelRatio, + 0.875*(this.screenBox[2]-this.screenBox[0])/pixelRatio, + 0.875*(this.screenBox[3]-this.screenBox[1])/pixelRatio]) - default: - throw new Error('ndarray-gradient: Invalid boundary condition') - } - } + var viewBox = this.viewBox + var aspectRatio = (viewBox[2] - viewBox[0]) / (viewBox[3] - viewBox[1]) + this.setDataBox(options.dataBox || [-10, -10/aspectRatio, 10, 10/aspectRatio]) - if(cod > 0) { - code.push('};') - } - } + this.borderColor = (options.borderColor || [0,0,0,0]).slice() + this.backgroundColor = (options.backgroundColor || [0,0,0,0]).slice() - //Enumerate ridges, facets, etc. of hypercube - for(var i=0; i<(1<=0; --i) { + this.objects[i].dispose() + } + this.objects.length = 0 + for(var i=this.overlays.length-1; i>=0; --i) { + this.overlays[i].dispose() + } + this.overlays.length = 0 -var IDENTITY = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 ] + this.gl = null +} -var QUAD = [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - [1, 0], - [0, 1] -] +proto.addObject = function(object) { + if(this.objects.indexOf(object) < 0) { + this.objects.push(object) + this.setDirty() + } +} -var PERMUTATIONS = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0] -] +proto.removeObject = function(object) { + var objects = this.objects + for(var i=0; i Math.abs(dy)) { + view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) + } else { + var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0 + view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) + } + }, true) - this.dirty = true + return camera } +},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],455:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":458}],456:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],457:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],458:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":456,"buffer":65,"dup":122}],459:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],460:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":459,"dup":155}],461:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":459,"dup":156}],462:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":460,"./lib/vao-native.js":461,"dup":157}],463:[function(require,module,exports){ +// Copyright (C) 2011 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. -var proto = SurfacePlot.prototype +/** + * @fileoverview Install a leaky WeakMap emulation on platforms that + * don't provide a built-in one. + * + *

Assumes that an ES5 platform where, if {@code WeakMap} is + * already present, then it conforms to the anticipated ES6 + * specification. To run this file on an ES5 or almost ES5 + * implementation where the {@code WeakMap} specification does not + * quite conform, run repairES5.js first. + * + *

Even though WeakMapModule is not global, the linter thinks it + * is, which is why it is in the overrides list below. + * + *

NOTE: Before using this WeakMap emulation in a non-SES + * environment, see the note below about hiddenRecord. + * + * @author Mark S. Miller + * @requires crypto, ArrayBuffer, Uint8Array, navigator, console + * @overrides WeakMap, ses, Proxy + * @overrides WeakMapModule + */ + +/** + * This {@code WeakMap} emulation is observably equivalent to the + * ES-Harmony WeakMap, but with leakier garbage collection properties. + * + *

As with true WeakMaps, in this emulation, a key does not + * retain maps indexed by that key and (crucially) a map does not + * retain the keys it indexes. A map by itself also does not retain + * the values associated with that map. + * + *

However, the values associated with a key in some map are + * retained so long as that key is retained and those associations are + * not overridden. For example, when used to support membranes, all + * values exported from a given membrane will live for the lifetime + * they would have had in the absence of an interposed membrane. Even + * when the membrane is revoked, all objects that would have been + * reachable in the absence of revocation will still be reachable, as + * far as the GC can tell, even though they will no longer be relevant + * to ongoing computation. + * + *

The API implemented here is approximately the API as implemented + * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, + * rather than the offially approved proposal page. TODO(erights): + * upgrade the ecmascript WeakMap proposal page to explain this API + * change and present to EcmaScript committee for their approval. + * + *

The first difference between the emulation here and that in + * FF6.0a1 is the presence of non enumerable {@code get___, has___, + * set___, and delete___} methods on WeakMap instances to represent + * what would be the hidden internal properties of a primitive + * implementation. Whereas the FF6.0a1 WeakMap.prototype methods + * require their {@code this} to be a genuine WeakMap instance (i.e., + * an object of {@code [[Class]]} "WeakMap}), since there is nothing + * unforgeable about the pseudo-internal method names used here, + * nothing prevents these emulated prototype methods from being + * applied to non-WeakMaps with pseudo-internal methods of the same + * names. + * + *

Another difference is that our emulated {@code + * WeakMap.prototype} is not itself a WeakMap. A problem with the + * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap + * providing ambient mutability and an ambient communications + * channel. Thus, if a WeakMap is already present and has this + * problem, repairES5.js wraps it in a safe wrappper in order to + * prevent access to this channel. (See + * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). + */ -proto.isTransparent = function () { - return this.opacity < 1 -} +/** + * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is + * absent, install an approximate emulation. + * + *

If WeakMap is present but cannot store some objects, use our approximate + * emulation as a wrapper. + * + *

If this is almost a secureable ES5 platform, then WeakMap.js + * should be run after repairES5.js. + * + *

See {@code WeakMap} for documentation of the garbage collection + * properties of this WeakMap emulation. + */ +(function WeakMapModule() { + "use strict"; -proto.isOpaque = function () { - if (this.opacity >= 1) { - return true + if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { + // already too broken, so give up + return; } - for (var i = 0; i < 3; ++i) { - if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) { - return true + + /** + * In some cases (current Firefox), we must make a choice betweeen a + * WeakMap which is capable of using all varieties of host objects as + * keys and one which is capable of safely using proxies as keys. See + * comments below about HostWeakMap and DoubleWeakMap for details. + * + * This function (which is a global, not exposed to guests) marks a + * WeakMap as permitted to do what is necessary to index all host + * objects, at the cost of making it unsafe for proxies. + * + * Do not apply this function to anything which is not a genuine + * fresh WeakMap. + */ + function weakMapPermitHostObjects(map) { + // identity of function used as a secret -- good enough and cheap + if (map.permitHostObjects___) { + map.permitHostObjects___(weakMapPermitHostObjects); } } - return false -} + if (typeof ses !== 'undefined') { + ses.weakMapPermitHostObjects = weakMapPermitHostObjects; + } -proto.pickSlots = 1 + // IE 11 has no Proxy but has a broken WeakMap such that we need to patch + // it using DoubleWeakMap; this flag tells DoubleWeakMap so. + var doubleWeakMapCheckSilentFailure = false; -proto.setPickBase = function (id) { - this.pickId = id -} + // Check if there is already a good-enough WeakMap implementation, and if so + // exit without replacing it. + if (typeof WeakMap === 'function') { + var HostWeakMap = WeakMap; + // There is a WeakMap -- is it good enough? + if (typeof navigator !== 'undefined' && + /Firefox/.test(navigator.userAgent)) { + // We're now *assuming not*, because as of this writing (2013-05-06) + // Firefox's WeakMaps have a miscellany of objects they won't accept, and + // we don't want to make an exhaustive list, and testing for just one + // will be a problem if that one is fixed alone (as they did for Event). -var ZERO_VEC = [0, 0, 0] + // If there is a platform that we *can* reliably test on, here's how to + // do it: + // var problematic = ... ; + // var testHostMap = new HostWeakMap(); + // try { + // testHostMap.set(problematic, 1); // Firefox 20 will throw here + // if (testHostMap.get(problematic) === 1) { + // return; + // } + // } catch (e) {} -var PROJECT_DATA = { - showSurface: false, - showContour: false, - projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()], - clipBounds: [ - [[0, 0, 0], [0, 0, 0]], - [[0, 0, 0], [0, 0, 0]], - [[0, 0, 0], [0, 0, 0]]] -} + } else { + // IE 11 bug: WeakMaps silently fail to store frozen objects. + var testMap = new HostWeakMap(); + var testObject = Object.freeze({}); + testMap.set(testObject, 1); + if (testMap.get(testObject) !== 1) { + doubleWeakMapCheckSilentFailure = true; + // Fall through to installing our WeakMap. + } else { + module.exports = WeakMap; + return; + } + } + } -function computeProjectionData (camera, obj) { - var i, j, k + var hop = Object.prototype.hasOwnProperty; + var gopn = Object.getOwnPropertyNames; + var defProp = Object.defineProperty; + var isExtensible = Object.isExtensible; - // Compute cube properties - var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC + /** + * Security depends on HIDDEN_NAME being both unguessable and + * undiscoverable by untrusted code. + * + *

Given the known weaknesses of Math.random() on existing + * browsers, it does not generate unguessability we can be confident + * of. + * + *

It is the monkey patching logic in this file that is intended + * to ensure undiscoverability. The basic idea is that there are + * three fundamental means of discovering properties of an object: + * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), + * as well as some proposed ES6 extensions that appear on our + * whitelist. The first two only discover enumerable properties, and + * we only use HIDDEN_NAME to name a non-enumerable property, so the + * only remaining threat should be getOwnPropertyNames and some + * proposed ES6 extensions that appear on our whitelist. We monkey + * patch them to remove HIDDEN_NAME from the list of properties they + * returns. + * + *

TODO(erights): On a platform with built-in Proxies, proxies + * could be used to trap and thereby discover the HIDDEN_NAME, so we + * need to monkey patch Proxy.create, Proxy.createFunction, etc, in + * order to wrap the provided handler with the real handler which + * filters out all traps using HIDDEN_NAME. + * + *

TODO(erights): Revisit Mike Stay's suggestion that we use an + * encapsulated function at a not-necessarily-secret name, which + * uses the Stiegler shared-state rights amplification pattern to + * reveal the associated value only to the WeakMap in which this key + * is associated with that value. Since only the key retains the + * function, the function can also remember the key without causing + * leakage of the key, so this doesn't violate our general gc + * goals. In addition, because the name need not be a guarded + * secret, we could efficiently handle cross-frame frozen keys. + */ + var HIDDEN_NAME_PREFIX = 'weakmap:'; + var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; - var showSurface = obj.showSurface - var showContour = obj.showContour + if (typeof crypto !== 'undefined' && + typeof crypto.getRandomValues === 'function' && + typeof ArrayBuffer === 'function' && + typeof Uint8Array === 'function') { + var ab = new ArrayBuffer(25); + var u8s = new Uint8Array(ab); + crypto.getRandomValues(u8s); + HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + + Array.prototype.map.call(u8s, function(u8) { + return (u8 % 36).toString(36); + }).join('') + '___'; + } - for (i = 0; i < 3; ++i) { - showSurface = showSurface || obj.surfaceProject[i] - for (j = 0; j < 3; ++j) { - showContour = showContour || obj.contourProject[i][j] - } + function isNotHiddenName(name) { + return !( + name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && + name.substr(name.length - 3) === '___'); } - for (i = 0; i < 3; ++i) { - // Construct projection onto axis - var axisSquish = PROJECT_DATA.projections[i] - for (j = 0; j < 16; ++j) { - axisSquish[j] = 0 - } - for (j = 0; j < 4; ++j) { - axisSquish[5 * j] = 1 + /** + * Monkey patch getOwnPropertyNames to avoid revealing the + * HIDDEN_NAME. + * + *

The ES5.1 spec requires each name to appear only once, but as + * of this writing, this requirement is controversial for ES6, so we + * made this code robust against this case. If the resulting extra + * search turns out to be expensive, we can probably relax this once + * ES6 is adequately supported on all major browsers, iff no browser + * versions we support at that time have relaxed this constraint + * without providing built-in ES6 WeakMaps. + */ + defProp(Object, 'getOwnPropertyNames', { + value: function fakeGetOwnPropertyNames(obj) { + return gopn(obj).filter(isNotHiddenName); } - axisSquish[5 * i] = 0 - axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] - multiply(axisSquish, camera.model, axisSquish) + }); - var nclipBounds = PROJECT_DATA.clipBounds[i] - for (k = 0; k < 2; ++k) { - for (j = 0; j < 3; ++j) { - nclipBounds[k][j] = camera.clipBounds[k][j] + /** + * getPropertyNames is not in ES5 but it is proposed for ES6 and + * does appear in our whitelist, so we need to clean it too. + */ + if ('getPropertyNames' in Object) { + var originalGetPropertyNames = Object.getPropertyNames; + defProp(Object, 'getPropertyNames', { + value: function fakeGetPropertyNames(obj) { + return originalGetPropertyNames(obj).filter(isNotHiddenName); } - } - nclipBounds[0][i] = -1e8 - nclipBounds[1][i] = 1e8 + }); } - PROJECT_DATA.showSurface = showSurface - PROJECT_DATA.showContour = showContour - - return PROJECT_DATA -} - -var UNIFORMS = { - model: IDENTITY, - view: IDENTITY, - projection: IDENTITY, - inverseModel: IDENTITY.slice(), - lowerBound: [0, 0, 0], - upperBound: [0, 0, 0], - colorMap: 0, - clipBounds: [[0, 0, 0], [0, 0, 0]], - height: 0.0, - contourTint: 0, - contourColor: [0, 0, 0, 1], - permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], - zOffset: -1e-4, - kambient: 1, - kdiffuse: 1, - kspecular: 1, - lightPosition: [1000, 1000, 1000], - eyePosition: [0, 0, 0], - roughness: 1, - fresnel: 1, - opacity: 1 -} + /** + *

To treat objects as identity-keys with reasonable efficiency + * on ES5 by itself (i.e., without any object-keyed collections), we + * need to add a hidden property to such key objects when we + * can. This raises several issues: + *

    + *
  • Arranging to add this property to objects before we lose the + * chance, and + *
  • Hiding the existence of this new property from most + * JavaScript code. + *
  • Preventing certification theft, where one object is + * created falsely claiming to be the key of an association + * actually keyed by another object. + *
  • Preventing value theft, where untrusted code with + * access to a key object but not a weak map nevertheless + * obtains access to the value associated with that key in that + * weak map. + *
+ * We do so by + *
    + *
  • Making the name of the hidden property unguessable, so "[]" + * indexing, which we cannot intercept, cannot be used to access + * a property without knowing the name. + *
  • Making the hidden property non-enumerable, so we need not + * worry about for-in loops or {@code Object.keys}, + *
  • monkey patching those reflective methods that would + * prevent extensions, to add this hidden property first, + *
  • monkey patching those methods that would reveal this + * hidden property. + *
+ * Unfortunately, because of same-origin iframes, we cannot reliably + * add this hidden property before an object becomes + * non-extensible. Instead, if we encounter a non-extensible object + * without a hidden record that we can detect (whether or not it has + * a hidden record stored under a name secret to us), then we just + * use the key object itself to represent its identity in a brute + * force leaky map stored in the weak map, losing all the advantages + * of weakness for these. + */ + function getHiddenRecord(key) { + if (key !== Object(key)) { + throw new TypeError('Not an object: ' + key); + } + var hiddenRecord = key[HIDDEN_NAME]; + if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } + if (!isExtensible(key)) { + // Weak map must brute force, as explained in doc-comment above. + return void 0; + } -var MATRIX_INVERSE = IDENTITY.slice() -var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] + // The hiddenRecord and the key point directly at each other, via + // the "key" and HIDDEN_NAME properties respectively. The key + // field is for quickly verifying that this hidden record is an + // own property, not a hidden record from up the prototype chain. + // + // NOTE: Because this WeakMap emulation is meant only for systems like + // SES where Object.prototype is frozen without any numeric + // properties, it is ok to use an object literal for the hiddenRecord. + // This has two advantages: + // * It is much faster in a performance critical place + // * It avoids relying on Object.create(null), which had been + // problematic on Chrome 28.0.1480.0. See + // https://code.google.com/p/google-caja/issues/detail?id=1687 + hiddenRecord = { key: key }; -function drawCore (params, transparent) { - params = params || {} - var gl = this.gl + // When using this WeakMap emulation on platforms where + // Object.prototype might not be frozen and Object.create(null) is + // reliable, use the following two commented out lines instead. + // hiddenRecord = Object.create(null); + // hiddenRecord.key = key; - gl.disable(gl.CULL_FACE) + // Please contact us if you need this to work on platforms where + // Object.prototype might not be frozen and + // Object.create(null) might not be reliable. - this._colorMap.bind(0) + try { + defProp(key, HIDDEN_NAME, { + value: hiddenRecord, + writable: false, + enumerable: false, + configurable: false + }); + return hiddenRecord; + } catch (error) { + // Under some circumstances, isExtensible seems to misreport whether + // the HIDDEN_NAME can be defined. + // The circumstances have not been isolated, but at least affect + // Node.js v0.10.26 on TravisCI / Linux, but not the same version of + // Node.js on OS X. + return void 0; + } + } - var uniforms = UNIFORMS - uniforms.model = params.model || IDENTITY - uniforms.view = params.view || IDENTITY - uniforms.projection = params.projection || IDENTITY - uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] - uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] - uniforms.contourColor = this.contourColor[0] + /** + * Monkey patch operations that would make their argument + * non-extensible. + * + *

The monkey patched versions throw a TypeError if their + * argument is not an object, so it should only be done to functions + * that should throw a TypeError anyway if their argument is not an + * object. + */ + (function(){ + var oldFreeze = Object.freeze; + defProp(Object, 'freeze', { + value: function identifyingFreeze(obj) { + getHiddenRecord(obj); + return oldFreeze(obj); + } + }); + var oldSeal = Object.seal; + defProp(Object, 'seal', { + value: function identifyingSeal(obj) { + getHiddenRecord(obj); + return oldSeal(obj); + } + }); + var oldPreventExtensions = Object.preventExtensions; + defProp(Object, 'preventExtensions', { + value: function identifyingPreventExtensions(obj) { + getHiddenRecord(obj); + return oldPreventExtensions(obj); + } + }); + })(); - uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model) + function constFunc(func) { + func.prototype = null; + return Object.freeze(func); + } - for (var i = 0; i < 2; ++i) { - var clipClamped = uniforms.clipBounds[i] - for (var j = 0; j < 3; ++j) { - clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) + var calledAsFunctionWarningDone = false; + function calledAsFunctionWarning() { + // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() + // but we used to permit it and do it ourselves, so warn only. + if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { + calledAsFunctionWarningDone = true; + console.warn('WeakMap should be invoked as new WeakMap(), not ' + + 'WeakMap(). This will be an error in the future.'); } } - uniforms.kambient = this.ambientLight - uniforms.kdiffuse = this.diffuseLight - uniforms.kspecular = this.specularLight + var nextId = 0; - uniforms.roughness = this.roughness - uniforms.fresnel = this.fresnel - uniforms.opacity = this.opacity + var OurWeakMap = function() { + if (!(this instanceof OurWeakMap)) { // approximate test for new ...() + calledAsFunctionWarning(); + } - uniforms.height = 0.0 - uniforms.permutation = DEFAULT_PERM + // We are currently (12/25/2012) never encountering any prematurely + // non-extensible keys. + var keys = []; // brute force for prematurely non-extensible keys. + var values = []; // brute force for corresponding values. + var id = nextId++; - // Compute camera matrix inverse - var invCameraMatrix = MATRIX_INVERSE - multiply(invCameraMatrix, uniforms.view, uniforms.model) - multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) - invert(invCameraMatrix, invCameraMatrix) + function get___(key, opt_default) { + var index; + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + return id in hiddenRecord ? hiddenRecord[id] : opt_default; + } else { + index = keys.indexOf(key); + return index >= 0 ? values[index] : opt_default; + } + } - for (i = 0; i < 3; ++i) { - uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15] - } + function has___(key) { + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + return id in hiddenRecord; + } else { + return keys.indexOf(key) >= 0; + } + } - var w = invCameraMatrix[15] - for (i = 0; i < 3; ++i) { - w += this.lightPosition[i] * invCameraMatrix[4 * i + 3] - } - for (i = 0; i < 3; ++i) { - var s = invCameraMatrix[12 + i] - for (j = 0; j < 3; ++j) { - s += invCameraMatrix[4 * j + i] * this.lightPosition[j] + function set___(key, value) { + var index; + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + hiddenRecord[id] = value; + } else { + index = keys.indexOf(key); + if (index >= 0) { + values[index] = value; + } else { + // Since some browsers preemptively terminate slow turns but + // then continue computing with presumably corrupted heap + // state, we here defensively get keys.length first and then + // use it to update both the values and keys arrays, keeping + // them in sync. + index = keys.length; + values[index] = value; + // If we crash here, values will be one longer than keys. + keys[index] = key; + } + } + return this; + } + + function delete___(key) { + var hiddenRecord = getHiddenRecord(key); + var index, lastIndex; + if (hiddenRecord) { + return id in hiddenRecord && delete hiddenRecord[id]; + } else { + index = keys.indexOf(key); + if (index < 0) { + return false; + } + // Since some browsers preemptively terminate slow turns but + // then continue computing with potentially corrupted heap + // state, we here defensively get keys.length first and then use + // it to update both the keys and the values array, keeping + // them in sync. We update the two with an order of assignments, + // such that any prefix of these assignments will preserve the + // key/value correspondence, either before or after the delete. + // Note that this needs to work correctly when index === lastIndex. + lastIndex = keys.length - 1; + keys[index] = void 0; + // If we crash here, there's a void 0 in the keys array, but + // no operation will cause a "keys.indexOf(void 0)", since + // getHiddenRecord(void 0) will always throw an error first. + values[index] = values[lastIndex]; + // If we crash here, values[index] cannot be found here, + // because keys[index] is void 0. + keys[index] = keys[lastIndex]; + // If index === lastIndex and we crash here, then keys[index] + // is still void 0, since the aliasing killed the previous key. + keys.length = lastIndex; + // If we crash here, keys will be one shorter than values. + values.length = lastIndex; + return true; + } } - uniforms.lightPosition[i] = s / w - } - var projectData = computeProjectionData(uniforms, this) + return Object.create(OurWeakMap.prototype, { + get___: { value: constFunc(get___) }, + has___: { value: constFunc(has___) }, + set___: { value: constFunc(set___) }, + delete___: { value: constFunc(delete___) } + }); + }; - if (projectData.showSurface && (transparent === (this.opacity < 1))) { - // Set up uniforms - this._shader.bind() - this._shader.uniforms = uniforms + OurWeakMap.prototype = Object.create(Object.prototype, { + get: { + /** + * Return the value most recently associated with key, or + * opt_default if none. + */ + value: function get(key, opt_default) { + return this.get___(key, opt_default); + }, + writable: true, + configurable: true + }, - // Draw it - this._vao.bind() + has: { + /** + * Is there a value associated with key in this WeakMap? + */ + value: function has(key) { + return this.has___(key); + }, + writable: true, + configurable: true + }, - if (this.showSurface && this._vertexCount) { - this._vao.draw(gl.TRIANGLES, this._vertexCount) - } + set: { + /** + * Associate value with key in this WeakMap, overwriting any + * previous association if present. + */ + value: function set(key, value) { + return this.set___(key, value); + }, + writable: true, + configurable: true + }, - // Draw projections of surface - for (i = 0; i < 3; ++i) { - if (!this.surfaceProject[i] || !this.vertexCount) { - continue - } - this._shader.uniforms.model = projectData.projections[i] - this._shader.uniforms.clipBounds = projectData.clipBounds[i] - this._vao.draw(gl.TRIANGLES, this._vertexCount) + 'delete': { + /** + * Remove any association for key in this WeakMap, returning + * whether there was one. + * + *

Note that the boolean return here does not work like the + * {@code delete} operator. The {@code delete} operator returns + * whether the deletion succeeds at bringing about a state in + * which the deleted property is absent. The {@code delete} + * operator therefore returns true if the property was already + * absent, whereas this {@code delete} method returns false if + * the association was already absent. + */ + value: function remove(key) { + return this.delete___(key); + }, + writable: true, + configurable: true } + }); - this._vao.unbind() - } + if (typeof HostWeakMap === 'function') { + (function() { + // If we got here, then the platform has a WeakMap but we are concerned + // that it may refuse to store some key types. Therefore, make a map + // implementation which makes use of both as possible. - if (projectData.showContour && !transparent) { - var shader = this._contourShader + // In this mode we are always using double maps, so we are not proxy-safe. + // This combination does not occur in any known browser, but we had best + // be safe. + if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { + Proxy = undefined; + } - // Don't apply lighting to contours - uniforms.kambient = 1.0 - uniforms.kdiffuse = 0.0 - uniforms.kspecular = 0.0 - uniforms.opacity = 1.0 + function DoubleWeakMap() { + if (!(this instanceof OurWeakMap)) { // approximate test for new ...() + calledAsFunctionWarning(); + } - shader.bind() - shader.uniforms = uniforms + // Preferable, truly weak map. + var hmap = new HostWeakMap(); - // Draw contour lines - var vao = this._contourVAO - vao.bind() + // Our hidden-property-based pseudo-weak-map. Lazily initialized in the + // 'set' implementation; thus we can avoid performing extra lookups if + // we know all entries actually stored are entered in 'hmap'. + var omap = undefined; - // Draw contour levels - for (i = 0; i < 3; ++i) { - shader.uniforms.permutation = PERMUTATIONS[i] - gl.lineWidth(this.contourWidth[i]) + // Hidden-property maps are not compatible with proxies because proxies + // can observe the hidden name and either accidentally expose it or fail + // to allow the hidden property to be set. Therefore, we do not allow + // arbitrary WeakMaps to switch to using hidden properties, but only + // those which need the ability, and unprivileged code is not allowed + // to set the flag. + // + // (Except in doubleWeakMapCheckSilentFailure mode in which case we + // disable proxies.) + var enableSwitching = false; - for (j = 0; j < this.contourLevels[i].length; ++j) { - if (!this._contourCounts[i][j]) { - continue - } - if (j === this.highlightLevel[i]) { - shader.uniforms.contourColor = this.highlightColor[i] - shader.uniforms.contourTint = this.highlightTint[i] - } else if (j === 0 || (j - 1) === this.highlightLevel[i]) { - shader.uniforms.contourColor = this.contourColor[i] - shader.uniforms.contourTint = this.contourTint[i] + function dget(key, opt_default) { + if (omap) { + return hmap.has(key) ? hmap.get(key) + : omap.get___(key, opt_default); + } else { + return hmap.get(key, opt_default); + } } - shader.uniforms.height = this.contourLevels[i][j] - vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j]) - } - } - // Draw projections of surface - for (i = 0; i < 3; ++i) { - shader.uniforms.model = projectData.projections[i] - shader.uniforms.clipBounds = projectData.clipBounds[i] - for (j = 0; j < 3; ++j) { - if (!this.contourProject[i][j]) { - continue + function dhas(key) { + return hmap.has(key) || (omap ? omap.has___(key) : false); } - shader.uniforms.permutation = PERMUTATIONS[j] - gl.lineWidth(this.contourWidth[j]) - for (var k = 0; k < this.contourLevels[j].length; ++k) { - if (k === this.highlightLevel[j]) { - shader.uniforms.contourColor = this.highlightColor[j] - shader.uniforms.contourTint = this.highlightTint[j] - } else if (k === 0 || (k - 1) === this.highlightLevel[j]) { - shader.uniforms.contourColor = this.contourColor[j] - shader.uniforms.contourTint = this.contourTint[j] - } - shader.uniforms.height = this.contourLevels[j][k] - vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) + + var dset; + if (doubleWeakMapCheckSilentFailure) { + dset = function(key, value) { + hmap.set(key, value); + if (!hmap.has(key)) { + if (!omap) { omap = new OurWeakMap(); } + omap.set(key, value); + } + return this; + }; + } else { + dset = function(key, value) { + if (enableSwitching) { + try { + hmap.set(key, value); + } catch (e) { + if (!omap) { omap = new OurWeakMap(); } + omap.set___(key, value); + } + } else { + hmap.set(key, value); + } + return this; + }; } - } - } - // Draw dynamic contours - vao = this._dynamicVAO - vao.bind() + function ddelete(key) { + var result = !!hmap['delete'](key); + if (omap) { return omap.delete___(key) || result; } + return result; + } - // Draw contour levels - for (i = 0; i < 3; ++i) { - if (this._dynamicCounts[i] === 0) { - continue + return Object.create(OurWeakMap.prototype, { + get___: { value: constFunc(dget) }, + has___: { value: constFunc(dhas) }, + set___: { value: constFunc(dset) }, + delete___: { value: constFunc(ddelete) }, + permitHostObjects___: { value: constFunc(function(token) { + if (token === weakMapPermitHostObjects) { + enableSwitching = true; + } else { + throw new Error('bogus call to permitHostObjects___'); + } + })} + }); } + DoubleWeakMap.prototype = OurWeakMap.prototype; + module.exports = DoubleWeakMap; - shader.uniforms.model = uniforms.model - shader.uniforms.clipBounds = uniforms.clipBounds - shader.uniforms.permutation = PERMUTATIONS[i] - gl.lineWidth(this.dynamicWidth[i]) - - shader.uniforms.contourColor = this.dynamicColor[i] - shader.uniforms.contourTint = this.dynamicTint[i] - shader.uniforms.height = this.dynamicLevel[i] - vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - - for (j = 0; j < 3; ++j) { - if (!this.contourProject[j][i]) { - continue - } + // define .constructor to hide OurWeakMap ctor + Object.defineProperty(WeakMap.prototype, 'constructor', { + value: WeakMap, + enumerable: false, // as default .constructor is + configurable: true, + writable: true + }); + })(); + } else { + // There is no host WeakMap, so we must use the emulation. - shader.uniforms.model = projectData.projections[j] - shader.uniforms.clipBounds = projectData.clipBounds[j] - vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - } + // Emulated WeakMaps are incompatible with native proxies (because proxies + // can observe the hidden name), so we must disable Proxy usage (in + // ArrayLike and Domado, currently). + if (typeof Proxy !== 'undefined') { + Proxy = undefined; } - vao.unbind() + module.exports = OurWeakMap; } -} - -proto.draw = function (params) { - return drawCore.call(this, params, false) -} +})(); -proto.drawTransparent = function (params) { - return drawCore.call(this, params, true) -} +},{}],464:[function(require,module,exports){ +'use strict' -var PICK_UNIFORMS = { - model: IDENTITY, - view: IDENTITY, - projection: IDENTITY, - inverseModel: IDENTITY, - clipBounds: [[0, 0, 0], [0, 0, 0]], - height: 0.0, - shape: [0, 0], - pickId: 0, - lowerBound: [0, 0, 0], - upperBound: [0, 0, 0], - zOffset: 0.0, - permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], - lightPosition: [0, 0, 0], - eyePosition: [0, 0, 0] -} +var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') -proto.drawPick = function (params) { - params = params || {} - var gl = this.gl - gl.disable(gl.CULL_FACE) +var TriangleCache = new weakMap() - var uniforms = PICK_UNIFORMS - uniforms.model = params.model || IDENTITY - uniforms.view = params.view || IDENTITY - uniforms.projection = params.projection || IDENTITY - uniforms.shape = this._field[2].shape - uniforms.pickId = this.pickId / 255.0 - uniforms.lowerBound = this.bounds[0] - uniforms.upperBound = this.bounds[1] - uniforms.permutation = DEFAULT_PERM +function createABigTriangle(gl) { - for (var i = 0; i < 2; ++i) { - var clipClamped = uniforms.clipBounds[i] - for (var j = 0; j < 3; ++j) { - clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) - } + var triangleVAO = TriangleCache.get(gl) + if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) { + var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) + triangleVAO = createVAO(gl, [ + { buffer: buf, + type: gl.FLOAT, + size: 2 + } + ]) + triangleVAO._triangleBuffer = buf + TriangleCache.set(gl, triangleVAO) } + triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, 3) + triangleVAO.unbind() +} - var projectData = computeProjectionData(uniforms, this) +module.exports = createABigTriangle - if (projectData.showSurface) { - // Set up uniforms - this._pickShader.bind() - this._pickShader.uniforms = uniforms +},{"gl-buffer":455,"gl-vao":462,"weak-map":463}],465:[function(require,module,exports){ +'use strict' - // Draw it - this._vao.bind() - this._vao.draw(gl.TRIANGLES, this._vertexCount) +module.exports = createAxes - // Draw projections of surface - for (i = 0; i < 3; ++i) { - if (!this.surfaceProject[i]) { - continue - } - this._pickShader.uniforms.model = projectData.projections[i] - this._pickShader.uniforms.clipBounds = projectData.clipBounds[i] - this._vao.draw(gl.TRIANGLES, this._vertexCount) - } +var createText = require('./lib/text.js') +var createLines = require('./lib/lines.js') +var createBackground = require('./lib/background.js') +var getCubeProperties = require('./lib/cube.js') +var Ticks = require('./lib/ticks.js') - this._vao.unbind() - } +var identity = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]) - if (projectData.showContour) { - var shader = this._contourPickShader +function copyVec3(a, b) { + a[0] = b[0] + a[1] = b[1] + a[2] = b[2] + return a +} - shader.bind() - shader.uniforms = uniforms +function Axes(gl) { + this.gl = gl - var vao = this._contourVAO - vao.bind() + this.pixelRatio = 1 - for (j = 0; j < 3; ++j) { - gl.lineWidth(this.contourWidth[j]) - shader.uniforms.permutation = PERMUTATIONS[j] - for (i = 0; i < this.contourLevels[j].length; ++i) { - if (this._contourCounts[j][i]) { - shader.uniforms.height = this.contourLevels[j][i] - vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i]) - } - } - } + this.bounds = [ [-10, -10, -10], + [ 10, 10, 10] ] + this.ticks = [ [], [], [] ] + this.autoTicks = true + this.tickSpacing = [ 1, 1, 1 ] - // Draw projections of surface - for (i = 0; i < 3; ++i) { - shader.uniforms.model = projectData.projections[i] - shader.uniforms.clipBounds = projectData.clipBounds[i] + this.tickEnable = [ true, true, true ] + this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ] + this.tickSize = [ 12, 12, 12 ] + this.tickAngle = [ 0, 0, 0 ] + this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.tickPad = [ 10, 10, 10 ] - for (j = 0; j < 3; ++j) { - if (!this.contourProject[i][j]) { - continue - } + this.lastCubeProps = { + cubeEdges: [0,0,0], + axis: [0,0,0] + } - shader.uniforms.permutation = PERMUTATIONS[j] - gl.lineWidth(this.contourWidth[j]) - for (var k = 0; k < this.contourLevels[j].length; ++k) { - if (this._contourCounts[j][k]) { - shader.uniforms.height = this.contourLevels[j][k] - vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) - } - } - } - } + this.labels = [ 'x', 'y', 'z' ] + this.labelEnable = [ true, true, true ] + this.labelFont = 'sans-serif' + this.labelSize = [ 20, 20, 20 ] + this.labelAngle = [ 0, 0, 0 ] + this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.labelPad = [ 10, 10, 10 ] - vao.unbind() - } -} + this.lineEnable = [ true, true, true ] + this.lineMirror = [ false, false, false ] + this.lineWidth = [ 1, 1, 1 ] + this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] -proto.pick = function (selection) { - if (!selection) { - return null - } + this.lineTickEnable = [ true, true, true ] + this.lineTickMirror = [ false, false, false ] + this.lineTickLength = [ 0, 0, 0 ] + this.lineTickWidth = [ 1, 1, 1 ] + this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - if (selection.id !== this.pickId) { - return null - } + this.gridEnable = [ true, true, true ] + this.gridWidth = [ 1, 1, 1 ] + this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - var shape = this._field[2].shape + this.zeroEnable = [ true, true, true ] + this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.zeroLineWidth = [ 2, 2, 2 ] - var result = this._pickResult + this.backgroundEnable = [ false, false, false ] + this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5], + [0.8, 0.8, 0.8, 0.5], + [0.8, 0.8, 0.8, 0.5] ] - // Compute uv coordinate - var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0 - var ix = Math.floor(x) - var fx = x - ix + this._firstInit = true + this._text = null + this._lines = null + this._background = createBackground(gl) +} - var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0 - var iy = Math.floor(y) - var fy = y - iy +var proto = Axes.prototype - ix += 1 - iy += 1 +proto.update = function(options) { + options = options || {} - // Compute xyz coordinate - var pos = result.position - pos[0] = pos[1] = pos[2] = 0 - for (var dx = 0; dx < 2; ++dx) { - var s = dx ? fx : 1.0 - fx - for (var dy = 0; dy < 2; ++dy) { - var t = dy ? fy : 1.0 - fy + //Option parsing helper functions + function parseOption(nest, cons, name) { + if(name in options) { + var opt = options[name] + var prev = this[name] + var next + if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : + Array.isArray(opt) ) { + this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] + } else { + this[name] = next = [ cons(opt), cons(opt), cons(opt) ] + } + for(var i=0; i<3; ++i) { + if(next[i] !== prev[i]) { + return true + } + } + } + return false + } - var r = ix + dx - var c = iy + dy - var w = s * t + var NUMBER = parseOption.bind(this, false, Number) + var BOOLEAN = parseOption.bind(this, false, Boolean) + var STRING = parseOption.bind(this, false, String) + var COLOR = parseOption.bind(this, true, function(v) { + if(Array.isArray(v)) { + if(v.length === 3) { + return [ +v[0], +v[1], +v[2], 1.0 ] + } else if(v.length === 4) { + return [ +v[0], +v[1], +v[2], +v[3] ] + } + } + return [ 0, 0, 0, 1 ] + }) - for (var i = 0; i < 3; ++i) { - pos[i] += this._field[i].get(r, c) * w + //Tick marks and bounds + var nextTicks + var ticksUpdate = false + var boundsChanged = false + if('bounds' in options) { + var bounds = options.bounds +i_loop: + for(var i=0; i<2; ++i) { + for(var j=0; j<3; ++j) { + if(bounds[i][j] !== this.bounds[i][j]) { + boundsChanged = true + } + this.bounds[i][j] = bounds[i][j] } } } - - // Find closest level - var levelIndex = this._pickResult.level - for (var j = 0; j < 3; ++j) { - levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j]) - if (levelIndex[j] < 0) { - if (this.contourLevels[j].length > 0) { - levelIndex[j] = 0 - } - } else if (levelIndex[j] < this.contourLevels[j].length - 1) { - var a = this.contourLevels[j][levelIndex[j]] - var b = this.contourLevels[j][levelIndex[j] + 1] - if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) { - levelIndex[j] += 1 - } + if('ticks' in options) { + nextTicks = options.ticks + ticksUpdate = true + this.autoTicks = false + for(var i=0; i<3; ++i) { + this.tickSpacing[i] = 0.0 } + } else if(NUMBER('tickSpacing')) { + this.autoTicks = true + boundsChanged = true } - result.index[0] = fx < 0.5 ? ix : (ix + 1) - result.index[1] = fy < 0.5 ? iy : (iy + 1) - - result.uv[0] = x / shape[0] - result.uv[1] = y / shape[1] + if(this._firstInit) { + if(!('ticks' in options || 'tickSpacing' in options)) { + this.autoTicks = true + } - for (i = 0; i < 3; ++i) { - result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]) + //Force tick recomputation on first update + boundsChanged = true + ticksUpdate = true + this._firstInit = false } - return result -} - -function padField (nfield, field) { - var shape = field.shape.slice() - var nshape = nfield.shape.slice() - - // Center - ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) - - // Edges - ops.assign(nfield.lo(1).hi(shape[0], 1), - field.hi(shape[0], 1)) - ops.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), - field.lo(0, shape[1] - 1).hi(shape[0], 1)) - ops.assign(nfield.lo(0, 1).hi(1, shape[1]), - field.hi(1)) - ops.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), - field.lo(shape[0] - 1)) - // Corners - nfield.set(0, 0, field.get(0, 0)) - nfield.set(0, nshape[1] - 1, field.get(0, shape[1] - 1)) - nfield.set(nshape[0] - 1, 0, field.get(shape[0] - 1, 0)) - nfield.set(nshape[0] - 1, nshape[1] - 1, field.get(shape[0] - 1, shape[1] - 1)) -} - -function handleArray (param, ctor) { - if (Array.isArray(param)) { - return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ] + if(boundsChanged && this.autoTicks) { + nextTicks = Ticks.create(this.bounds, this.tickSpacing) + ticksUpdate = true } - return [ ctor(param), ctor(param), ctor(param) ] -} -function toColor (x) { - if (Array.isArray(x)) { - if (x.length === 3) { - return [x[0], x[1], x[2], 1] + //Compare next ticks to previous ticks, only update if needed + if(ticksUpdate) { + for(var i=0; i<3; ++i) { + nextTicks[i].sort(function(a,b) { + return a.x-b.x + }) } - return [x[0], x[1], x[2], x[3]] - } - return [0, 0, 0, 1] -} - -function handleColor (param) { - if (Array.isArray(param)) { - if (Array.isArray(param)) { - return [ - toColor(param[0]), - toColor(param[1]), - toColor(param[2]) ] + if(Ticks.equal(nextTicks, this.ticks)) { + ticksUpdate = false } else { - var c = toColor(param) - return [ - c.slice(), - c.slice(), - c.slice() ] + this.ticks = nextTicks } } -} - -proto.update = function (params) { - params = params || {} - - this.dirty = true - if ('contourWidth' in params) { - this.contourWidth = handleArray(params.contourWidth, Number) - } - if ('showContour' in params) { - this.showContour = handleArray(params.showContour, Boolean) - } - if ('showSurface' in params) { - this.showSurface = !!params.showSurface - } - if ('contourTint' in params) { - this.contourTint = handleArray(params.contourTint, Boolean) - } - if ('contourColor' in params) { - this.contourColor = handleColor(params.contourColor) - } - if ('contourProject' in params) { - this.contourProject = handleArray(params.contourProject, function (x) { - return handleArray(x, Boolean) - }) - } - if ('surfaceProject' in params) { - this.surfaceProject = params.surfaceProject - } - if ('dynamicColor' in params) { - this.dynamicColor = handleColor(params.dynamicColor) - } - if ('dynamicTint' in params) { - this.dynamicTint = handleArray(params.dynamicTint, Number) - } - if ('dynamicWidth' in params) { - this.dynamicWidth = handleArray(params.dynamicWidth, Number) - } - if ('opacity' in params) { - this.opacity = params.opacity + //Parse tick properties + BOOLEAN('tickEnable') + if(STRING('tickFont')) { + ticksUpdate = true //If font changes, must rebuild vbo } - if ('colorBounds' in params) { - this.colorBounds = params.colorBounds + NUMBER('tickSize') + NUMBER('tickAngle') + NUMBER('tickPad') + COLOR('tickColor') + + //Axis labels + var labelUpdate = STRING('labels') + if(STRING('labelFont')) { + labelUpdate = true } + BOOLEAN('labelEnable') + NUMBER('labelSize') + NUMBER('labelPad') + COLOR('labelColor') - var field = params.field || (params.coords && params.coords[2]) || null - var levelsChanged = false + //Axis lines + BOOLEAN('lineEnable') + BOOLEAN('lineMirror') + NUMBER('lineWidth') + COLOR('lineColor') - if (!field) { - if (this._field[2].shape[0] || this._field[2].shape[2]) { - field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2) - } else { - field = this._field[2].hi(0, 0) - } - } + //Axis line ticks + BOOLEAN('lineTickEnable') + BOOLEAN('lineTickMirror') + NUMBER('lineTickLength') + NUMBER('lineTickWidth') + COLOR('lineTickColor') - // Update field - if ('field' in params || 'coords' in params) { - var fsize = (field.shape[0] + 2) * (field.shape[1] + 2) + //Grid lines + BOOLEAN('gridEnable') + NUMBER('gridWidth') + COLOR('gridColor') - // Resize if necessary - if (fsize > this._field[2].data.length) { - pool.freeFloat(this._field[2].data) - this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize)) - } + //Zero line + BOOLEAN('zeroEnable') + COLOR('zeroLineColor') + NUMBER('zeroLineWidth') - // Pad field - this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) - padField(this._field[2], field) + //Background + BOOLEAN('backgroundEnable') + COLOR('backgroundColor') - // Save shape of field - this.shape = field.shape.slice() - var shape = this.shape + //Update text if necessary + if(!this._text) { + this._text = createText( + this.gl, + this.bounds, + this.labels, + this.labelFont, + this.ticks, + this.tickFont) + } else if(this._text && (labelUpdate || ticksUpdate)) { + this._text.update( + this.bounds, + this.labels, + this.labelFont, + this.ticks, + this.tickFont) + } - // Resize coordinate fields if necessary - for (var i = 0; i < 2; ++i) { - if (this._field[2].size > this._field[i].data.length) { - pool.freeFloat(this._field[i].data) - this._field[i].data = pool.mallocFloat(this._field[2].size) - } - this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]) - } + //Update lines if necessary + if(this._lines && ticksUpdate) { + this._lines.dispose() + this._lines = null + } + if(!this._lines) { + this._lines = createLines(this.gl, this.bounds, this.ticks) + } +} - // Generate x/y coordinates - if (params.coords) { - var coords = params.coords - if (!Array.isArray(coords) || coords.length !== 3) { - throw new Error('gl-surface: invalid coordinates for x/y') - } - for (i = 0; i < 2; ++i) { - var coord = coords[i] - for (j = 0; j < 2; ++j) { - if (coord.shape[j] !== shape[j]) { - throw new Error('gl-surface: coords have incorrect shape') - } - } - padField(this._field[i], coord) - } - } else if (params.ticks) { - var ticks = params.ticks - if (!Array.isArray(ticks) || ticks.length !== 2) { - throw new Error('gl-surface: invalid ticks') - } - for (i = 0; i < 2; ++i) { - var tick = ticks[i] - if (Array.isArray(tick) || tick.length) { - tick = ndarray(tick) - } - if (tick.shape[0] !== shape[i]) { - throw new Error('gl-surface: invalid tick length') - } - // Make a copy view of the tick array - var tick2 = ndarray(tick.data, shape) - tick2.stride[i] = tick.stride[0] - tick2.stride[i ^ 1] = 0 +function OffsetInfo() { + this.primalOffset = [0,0,0] + this.primalMinor = [0,0,0] + this.mirrorOffset = [0,0,0] + this.mirrorMinor = [0,0,0] +} - // Fill in field array - padField(this._field[i], tick2) - } - } else { - for (i = 0; i < 2; ++i) { - var offset = [0, 0] - offset[i] = 1 - this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) - } - this._field[0].set(0, 0, 0) - for (var j = 0; j < shape[0]; ++j) { - this._field[0].set(j + 1, 0, j) - } - this._field[0].set(shape[0] + 1, 0, shape[0] - 1) - this._field[1].set(0, 0, 0) - for (j = 0; j < shape[1]; ++j) { - this._field[1].set(0, j + 1, j) - } - this._field[1].set(0, shape[1] + 1, shape[1] - 1) - } +var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ] - // Save shape - var fields = this._field +function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) { + var primalOffset = result.primalOffset + var primalMinor = result.primalMinor + var dualOffset = result.mirrorOffset + var dualMinor = result.mirrorMinor + var e = cubeEdges[i] - // Compute surface normals - var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) - for (i = 0; i < 3; ++i) { - gradient(dfields.pick(i), fields[i], 'mirror') + //Calculate offsets + for(var j=0; j<3; ++j) { + if(i === j) { + continue } - var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) - for (i = 0; i < shape[0] + 2; ++i) { - for (j = 0; j < shape[1] + 2; ++j) { - var dxdu = dfields.get(0, i, j, 0) - var dxdv = dfields.get(0, i, j, 1) - var dydu = dfields.get(1, i, j, 0) - var dydv = dfields.get(1, i, j, 1) - var dzdu = dfields.get(2, i, j, 0) - var dzdv = dfields.get(2, i, j, 1) + var a = primalOffset, + b = dualOffset, + c = primalMinor, + d = dualMinor + if(e & (1< 0) { + c[j] = -1 + d[j] = 0 + } else { + c[j] = 0 + d[j] = +1 + } + } +} - var nx = dydu * dzdv - dydv * dzdu - var ny = dzdu * dxdv - dzdv * dxdu - var nz = dxdu * dydv - dxdv * dydu +var CUBE_ENABLE = [0,0,0] +var DEFAULT_PARAMS = { + model: identity, + view: identity, + projection: identity +} - var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) - if (nl < 1e-8) { - nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz)) - if (nl < 1e-8) { - nz = 1.0 - ny = nx = 0.0 - nl = 1.0 - } else { - nl = 1.0 / nl - } - } else { - nl = 1.0 / Math.sqrt(nl) - } +proto.isOpaque = function() { + return true +} - normals.set(i, j, 0, nx * nl) - normals.set(i, j, 1, ny * nl) - normals.set(i, j, 2, nz * nl) - } - } - pool.free(dfields.data) +proto.isTransparent = function() { + return false +} - // Initialize surface - var lo = [ Infinity, Infinity, Infinity ] - var hi = [ -Infinity, -Infinity, -Infinity ] - var lo_intensity = Infinity - var hi_intensity = -Infinity - var count = (shape[0] - 1) * (shape[1] - 1) * 6 - var tverts = pool.mallocFloat(bits.nextPow2(10 * count)) - var tptr = 0 - var vertexCount = 0 - for (i = 0; i < shape[0] - 1; ++i) { - j_loop: - for (j = 0; j < shape[1] - 1; ++j) { - // Test for NaNs - for (var dx = 0; dx < 2; ++dx) { - for (var dy = 0; dy < 2; ++dy) { - for (var k = 0; k < 3; ++k) { - var f = this._field[k].get(1 + i + dx, 1 + j + dy) - if (isNaN(f) || !isFinite(f)) { - continue j_loop - } - } - } - } - for (k = 0; k < 6; ++k) { - var r = i + QUAD[k][0] - var c = j + QUAD[k][1] +proto.drawTransparent = function(params) {} - var tx = this._field[0].get(r + 1, c + 1) - var ty = this._field[1].get(r + 1, c + 1) - f = this._field[2].get(r + 1, c + 1) - var vf = f - nx = normals.get(r + 1, c + 1, 0) - ny = normals.get(r + 1, c + 1, 1) - nz = normals.get(r + 1, c + 1, 2) - if (params.intensity) { - vf = params.intensity.get(r, c) - } +var PRIMAL_MINOR = [0,0,0] +var MIRROR_MINOR = [0,0,0] +var PRIMAL_OFFSET = [0,0,0] - tverts[tptr++] = r - tverts[tptr++] = c - tverts[tptr++] = tx - tverts[tptr++] = ty - tverts[tptr++] = f - tverts[tptr++] = 0 - tverts[tptr++] = vf - tverts[tptr++] = nx - tverts[tptr++] = ny - tverts[tptr++] = nz +proto.draw = function(params) { + params = params || DEFAULT_PARAMS - lo[0] = Math.min(lo[0], tx) - lo[1] = Math.min(lo[1], ty) - lo[2] = Math.min(lo[2], f) - lo_intensity = Math.min(lo_intensity, vf) + var gl = this.gl - hi[0] = Math.max(hi[0], tx) - hi[1] = Math.max(hi[1], ty) - hi[2] = Math.max(hi[2], f) - hi_intensity = Math.max(hi_intensity, vf) + //Geometry for camera and axes + var model = params.model || identity + var view = params.view || identity + var projection = params.projection || identity + var bounds = this.bounds - vertexCount += 1 - } - } - } + //Unpack axis info + var cubeParams = getCubeProperties(model, view, projection, bounds) + var cubeEdges = cubeParams.cubeEdges + var cubeAxis = cubeParams.axis - if (params.intensityBounds) { - lo_intensity = +params.intensityBounds[0] - hi_intensity = +params.intensityBounds[1] - } + var cx = view[12] + var cy = view[13] + var cz = view[14] + var cw = view[15] - // Scale all vertex intensities - for (i = 6; i < tptr; i += 10) { - tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity) - } + var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight - this._vertexCount = vertexCount - this._coordinateBuffer.update(tverts.subarray(0, tptr)) - pool.freeFloat(tverts) - pool.free(normals.data) + for(var i=0; i<3; ++i) { + this.lastCubeProps.cubeEdges[i] = cubeEdges[i] + this.lastCubeProps.axis[i] = cubeAxis[i] + } - // Update bounds - this.bounds = [lo, hi] + //Compute axis info + var lineOffset = LINE_OFFSET + for(var i=0; i<3; ++i) { + computeLineOffset( + LINE_OFFSET[i], + i, + this.bounds, + cubeEdges, + cubeAxis) + } - // Save intensity - this.intensity = params.intensity || this._field[2] + //Set up state parameters + var gl = this.gl - if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) { - levelsChanged = true + //Draw background first + var cubeEnable = CUBE_ENABLE + for(var i=0; i<3; ++i) { + if(this.backgroundEnable[i]) { + cubeEnable[i] = cubeAxis[i] + } else { + cubeEnable[i] = 0 } - - // Save intensity bound - this.intensityBounds = [lo_intensity, hi_intensity] } - // Update level crossings - if ('levels' in params) { - var levels = params.levels - if (!Array.isArray(levels[0])) { - levels = [ [], [], levels ] + this._background.draw( + model, + view, + projection, + bounds, + cubeEnable, + this.backgroundColor) + + //Draw lines + this._lines.bind( + model, + view, + projection, + this) + + //First draw grid lines and zero lines + for(var i=0; i<3; ++i) { + var x = [0,0,0] + if(cubeAxis[i] > 0) { + x[i] = bounds[1][i] } else { - levels = levels.slice() - } - for (i = 0; i < 3; ++i) { - levels[i] = levels[i].slice() - levels.sort(function (a, b) { - return a - b - }) + x[i] = bounds[0][i] } - change_test: - for (i = 0; i < 3; ++i) { - if (levels[i].length !== this.contourLevels[i].length) { - levelsChanged = true - break + + //Draw grid lines + for(var j=0; j<2; ++j) { + var u = (i + 1 + j) % 3 + var v = (i + 1 + (j^1)) % 3 + if(this.gridEnable[u]) { + this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio) } - for (j = 0; j < levels[i].length; ++j) { - if (levels[i][j] !== this.contourLevels[i][j]) { - levelsChanged = true - break change_test + } + + //Draw zero lines (need to do this AFTER all grid lines are drawn) + for(var j=0; j<2; ++j) { + var u = (i + 1 + j) % 3 + var v = (i + 1 + (j^1)) % 3 + if(this.zeroEnable[v]) { + //Check if zero line in bounds + if(bounds[0][v] <= 0 && bounds[1][v] >= 0) { + this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio) } } } - this.contourLevels = levels } - if (levelsChanged) { - fields = this._field - shape = this.shape - - // Update contour lines - var contourVerts = [] - - for (var dim = 0; dim < 3; ++dim) { - levels = this.contourLevels[dim] - var levelOffsets = [] - var levelCounts = [] + //Then draw axis lines and tick marks + for(var i=0; i<3; ++i) { - var parts = [0, 0, 0] + //Draw axis lines + if(this.lineEnable[i]) { + this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) + } + if(this.lineMirror[i]) { + this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) + } - for (i = 0; i < levels.length; ++i) { - var graph = surfaceNets(this._field[dim], levels[i]) - levelOffsets.push((contourVerts.length / 5) | 0) - vertexCount = 0 + //Compute minor axes + var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor) + var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor) + var tickLength = this.lineTickLength + var op = 0 + for(var j=0; j<3; ++j) { + var scaleFactor = pixelScaleF / model[5*j] + primalMinor[j] *= tickLength[j] * scaleFactor + mirrorMinor[j] *= tickLength[j] * scaleFactor + } - edge_loop: - for (j = 0; j < graph.cells.length; ++j) { - var e = graph.cells[j] - for (k = 0; k < 2; ++k) { - var p = graph.positions[e[k]] + //Draw axis line ticks + if(this.lineTickEnable[i]) { + this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) + } + if(this.lineTickMirror[i]) { + this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) + } + } - var x = p[0] - var ix = Math.floor(x) | 0 - var fx = x - ix + //Draw text sprites + this._text.bind( + model, + view, + projection, + this.pixelRatio) - var y = p[1] - var iy = Math.floor(y) | 0 - var fy = y - iy + for(var i=0; i<3; ++i) { - var hole = false - dd_loop: - for (var dd = 0; dd < 3; ++dd) { - parts[dd] = 0.0 - var iu = (dim + dd + 1) % 3 - for (dx = 0; dx < 2; ++dx) { - var s = dx ? fx : 1.0 - fx - r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0 - for (dy = 0; dy < 2; ++dy) { - var t = dy ? fy : 1.0 - fy - c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0 + var minor = lineOffset[i].primalMinor + var offset = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset) - if (dd < 2) { - f = this._field[iu].get(r, c) - } else { - f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]) - } - if (!isFinite(f) || isNaN(f)) { - hole = true - break dd_loop - } + for(var j=0; j<3; ++j) { + if(this.lineTickEnable[i]) { + offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0) / model[5*j] + } + } - var w = s * t - parts[dd] += w * f - } - } - } + //Draw tick text + if(this.tickEnable[i]) { - if (!hole) { - contourVerts.push(parts[0], parts[1], p[0], p[1], parts[2]) - vertexCount += 1 - } else { - if (k > 0) { - // If we already added first edge, pop off verts - for (var l = 0; l < 5; ++l) { - contourVerts.pop() - } - vertexCount -= 1 - } - continue edge_loop - } - } - } - levelCounts.push(vertexCount) + //Add tick padding + for(var j=0; j<3; ++j) { + offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j] } - // Store results - this._contourOffsets[dim] = levelOffsets - this._contourCounts[dim] = levelCounts - } - - var floatBuffer = pool.mallocFloat(contourVerts.length) - for (i = 0; i < contourVerts.length; ++i) { - floatBuffer[i] = contourVerts[i] + //Draw axis + this._text.drawTicks( + i, + this.tickSize[i], + this.tickAngle[i], + offset, + this.tickColor[i]) } - this._contourBuffer.update(floatBuffer) - pool.freeFloat(floatBuffer) - } - - if (params.colormap) { - this._colorMap.setPixels(genColormap(params.colormap)) - } -} -proto.dispose = function () { - this._shader.dispose() - this._vao.dispose() - this._coordinateBuffer.dispose() - this._colorMap.dispose() - this._contourBuffer.dispose() - this._contourVAO.dispose() - this._contourShader.dispose() - this._contourPickShader.dispose() - this._dynamicBuffer.dispose() - this._dynamicVAO.dispose() - for (var i = 0; i < 3; ++i) { - pool.freeFloat(this._field[i].data) - } -} + //Draw labels + if(this.labelEnable[i]) { -proto.highlight = function (selection) { - if (!selection) { - this._dynamicCounts = [0, 0, 0] - this.dyanamicLevel = [NaN, NaN, NaN] - this.highlightLevel = [-1, -1, -1] - return - } + //Add label padding + for(var j=0; j<3; ++j) { + offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j] + } + offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]) - for (var i = 0; i < 3; ++i) { - if (this.enableHighlight[i]) { - this.highlightLevel[i] = selection.level[i] - } else { - this.highlightLevel[i] = -1 + //Draw axis + this._text.drawLabel( + i, + this.labelSize[i], + this.labelAngle[i], + offset, + this.labelColor[i]) } } +} - var levels - if (this.snapToData) { - levels = selection.dataCoordinate - } else { - levels = selection.position - } - if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) && - (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) && - (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) { - return - } - - var vertexCount = 0 - var shape = this.shape - var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1]) +proto.dispose = function() { + this._text.dispose() + this._lines.dispose() + this._background.dispose() + this._lines = null + this._text = null + this._background = null + this.gl = null +} - for (var d = 0; d < 3; ++d) { - if (!this.enableDynamic[d]) { - this.dynamicLevel[d] = NaN - this._dynamicCounts[d] = 0 - continue - } +function createAxes(gl, options) { + var axes = new Axes(gl) + axes.update(options) + return axes +} - this.dynamicLevel[d] = levels[d] +},{"./lib/background.js":466,"./lib/cube.js":467,"./lib/lines.js":468,"./lib/text.js":470,"./lib/ticks.js":471}],466:[function(require,module,exports){ +'use strict' - var u = (d + 1) % 3 - var v = (d + 2) % 3 +module.exports = createBackgroundCube - var f = this._field[d] - var g = this._field[u] - var h = this._field[v] - var intensity = this.intensity +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders').bg - var graph = surfaceNets(f, levels[d]) - var edges = graph.cells - var positions = graph.positions +function BackgroundCube(gl, buffer, vao, shader) { + this.gl = gl + this.buffer = buffer + this.vao = vao + this.shader = shader +} - this._dynamicOffsets[d] = vertexCount +var proto = BackgroundCube.prototype - for (i = 0; i < edges.length; ++i) { - var e = edges[i] - for (var j = 0; j < 2; ++j) { - var p = positions[e[j]] +proto.draw = function(model, view, projection, bounds, enable, colors) { + var needsBG = false + for(var i=0; i<3; ++i) { + needsBG = needsBG || enable[i] + } + if(!needsBG) { + return + } - var x = +p[0] - var ix = x | 0 - var jx = Math.min(ix + 1, shape[0]) | 0 - var fx = x - ix - var hx = 1.0 - fx + var gl = this.gl - var y = +p[1] - var iy = y | 0 - var jy = Math.min(iy + 1, shape[1]) | 0 - var fy = y - iy - var hy = 1.0 - fy + gl.enable(gl.POLYGON_OFFSET_FILL) + gl.polygonOffset(1, 2) - var w00 = hx * hy - var w01 = hx * fy - var w10 = fx * hy - var w11 = fx * fy + this.shader.bind() + this.shader.uniforms = { + model: model, + view: view, + projection: projection, + bounds: bounds, + enable: enable, + colors: colors + } + this.vao.bind() + this.vao.draw(this.gl.TRIANGLES, 36) - var cu = w00 * g.get(ix, iy) + - w01 * g.get(ix, jy) + - w10 * g.get(jx, iy) + - w11 * g.get(jx, jy) + gl.disable(gl.POLYGON_OFFSET_FILL) +} - var cv = w00 * h.get(ix, iy) + - w01 * h.get(ix, jy) + - w10 * h.get(jx, iy) + - w11 * h.get(jx, jy) +proto.dispose = function() { + this.vao.dispose() + this.buffer.dispose() + this.shader.dispose() +} - if (isNaN(cu) || isNaN(cv)) { - if (j) { - vertexCount -= 1 - } - break +function createBackgroundCube(gl) { + //Create cube vertices + var vertices = [] + var indices = [] + var ptr = 0 + for(var d=0; d<3; ++d) { + var u = (d+1) % 3 + var v = (d+2) % 3 + var x = [0,0,0] + var c = [0,0,0] + for(var s=-1; s<=1; s+=2) { + indices.push(ptr, ptr+2, ptr+1, + ptr+1, ptr+2, ptr+3) + x[d] = s + c[d] = s + for(var i=-1; i<=1; i+=2) { + x[u] = i + for(var j=-1; j<=1; j+=2) { + x[v] = j + vertices.push(x[0], x[1], x[2], + c[0], c[1], c[2]) + ptr += 1 } - - scratchBuffer[2 * vertexCount + 0] = cu - scratchBuffer[2 * vertexCount + 1] = cv - - vertexCount += 1 } + //Swap u and v + var tt = u + u = v + v = tt } - - this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d] } - this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) - pool.freeFloat(scratchBuffer) -} + //Allocate buffer and vertex array + var buffer = createBuffer(gl, new Float32Array(vertices)) + var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) + var vao = createVAO(gl, [ + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 0, + stride: 24 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 12, + stride: 24 + } + ], elements) -function createSurfacePlot (params) { - var gl = params.gl + //Create shader object var shader = createShader(gl) - var pickShader = createPickShader(gl) - var contourShader = createContourShader(gl) - var contourPickShader = createPickContourShader(gl) + shader.attributes.position.location = 0 + shader.attributes.normal.location = 1 - var coordinateBuffer = createBuffer(gl) - var vao = createVAO(gl, [ - { buffer: coordinateBuffer, - size: 4, - stride: SURFACE_VERTEX_SIZE, - offset: 0 - }, - { buffer: coordinateBuffer, - size: 3, - stride: SURFACE_VERTEX_SIZE, - offset: 16 - }, - { - buffer: coordinateBuffer, - size: 3, - stride: SURFACE_VERTEX_SIZE, - offset: 28 - } - ]) + return new BackgroundCube(gl, buffer, vao, shader) +} - var contourBuffer = createBuffer(gl) - var contourVAO = createVAO(gl, [ - { - buffer: contourBuffer, - size: 4, - stride: 20, - offset: 0 - }, - { - buffer: contourBuffer, - size: 1, - stride: 20, - offset: 16 - } - ]) +},{"./shaders":469,"gl-buffer":475,"gl-vao":480}],467:[function(require,module,exports){ +"use strict" - var dynamicBuffer = createBuffer(gl) - var dynamicVAO = createVAO(gl, [ - { - buffer: dynamicBuffer, - size: 2, - type: gl.FLOAT - }]) +module.exports = getCubeEdges - var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) - cmap.minFilter = gl.LINEAR - cmap.magFilter = gl.LINEAR +var bits = require('bit-twiddle') +var multiply = require('gl-mat4/multiply') +var invert = require('gl-mat4/invert') +var splitPoly = require('split-polygon') +var orient = require('robust-orientation') - var surface = new SurfacePlot( - gl, - [0, 0], - [[0, 0, 0], [0, 0, 0]], - shader, - pickShader, - coordinateBuffer, - vao, - cmap, - contourShader, - contourPickShader, - contourBuffer, - contourVAO, - dynamicBuffer, - dynamicVAO) +var mvp = new Array(16) +var imvp = new Array(16) +var pCubeVerts = new Array(8) +var cubeVerts = new Array(8) +var x = new Array(3) +var zero3 = [0,0,0] - var nparams = { - levels: [[], [], []] +;(function() { + for(var i=0; i<8; ++i) { + pCubeVerts[i] =[1,1,1,1] + cubeVerts[i] = [1,1,1] } - for (var id in params) { - nparams[id] = params[id] +})() + + +function transformHg(result, x, mat) { + for(var i=0; i<4; ++i) { + result[i] = mat[12+i] + for(var j=0; j<3; ++j) { + result[i] += x[j]*mat[4*j+i] + } } - nparams.colormap = nparams.colormap || 'jet' +} - surface.update(nparams) +var FRUSTUM_PLANES = [ + [ 0, 0, 1, 0, 0], + [ 0, 0,-1, 1, 0], + [ 0,-1, 0, 1, 0], + [ 0, 1, 0, 1, 0], + [-1, 0, 0, 1, 0], + [ 1, 0, 0, 1, 0] +] - return surface -} +function polygonArea(p) { + for(var i=0; i maxSize || h < 0 || h > maxSize) { - throw new Error('gl-texture2d: Invalid texture size') - } - tex._shape = [w, h] - tex.bind() - gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) - tex._mipLevels = [0] - return tex +var CUBE_EDGES = [1,1,1] +var CUBE_AXIS = [0,0,0] +var CUBE_RESULT = { + cubeEdges: CUBE_EDGES, + axis: CUBE_AXIS } -function Texture2D(gl, handle, width, height, format, type) { - this.gl = gl - this.handle = handle - this.format = format - this.type = type - this._shape = [width, height] - this._mipLevels = [0] - this._magFilter = gl.NEAREST - this._minFilter = gl.NEAREST - this._wrapS = gl.CLAMP_TO_EDGE - this._wrapT = gl.CLAMP_TO_EDGE - this._anisoSamples = 1 +function getCubeEdges(model, view, projection, bounds) { - var parent = this - var wrapVector = [this._wrapS, this._wrapT] - Object.defineProperties(wrapVector, [ - { - get: function() { - return parent._wrapS - }, - set: function(v) { - return parent.wrapS = v - } - }, - { - get: function() { - return parent._wrapT - }, - set: function(v) { - return parent.wrapT = v + //Concatenate matrices + multiply(mvp, view, model) + multiply(mvp, projection, mvp) + + //First project cube vertices + var ptr = 0 + for(var i=0; i<2; ++i) { + x[2] = bounds[i][2] + for(var j=0; j<2; ++j) { + x[1] = bounds[j][1] + for(var k=0; k<2; ++k) { + x[0] = bounds[k][0] + transformHg(pCubeVerts[ptr], x, mvp) + ptr += 1 } } - ]) - this._wrapVector = wrapVector + } - var shapeVector = [this._shape[0], this._shape[1]] - Object.defineProperties(shapeVector, [ - { - get: function() { - return parent._shape[0] - }, - set: function(v) { - return parent.width = v - } - }, - { - get: function() { - return parent._shape[1] - }, - set: function(v) { - return parent.height = v - } - } - ]) - this._shapeVector = shapeVector -} + //Classify camera against cube faces + var closest = -1 -var proto = Texture2D.prototype + for(var i=0; i<8; ++i) { + var w = pCubeVerts[i][3] + for(var l=0; l<3; ++l) { + cubeVerts[i][l] = pCubeVerts[i][l] / w + } + if(w < 0) { + if(closest < 0) { + closest = i + } else if(cubeVerts[i][2] < cubeVerts[closest][2]) { + closest = i + } + } + } -Object.defineProperties(proto, { - minFilter: { - get: function() { - return this._minFilter - }, - set: function(v) { - this.bind() - var gl = this.gl - if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { - if(!gl.getExtension('OES_texture_float_linear')) { - v = gl.NEAREST + if(closest < 0) { + closest = 0 + for(var d=0; d<3; ++d) { + var u = (d+2) % 3 + var v = (d+1) % 3 + var o0 = -1 + var o1 = -1 + for(var s=0; s<2; ++s) { + var f0 = (s<= 0) { - if(!gl.getExtension('OES_texture_float_linear')) { - v = gl.NEAREST + if(s) { + o0 = 1 + } else { + o1 = 1 } } - if(filterTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown filter mode ' + v) - } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) - return this._magFilter = v - } - }, - mipSamples: { - get: function() { - return this._anisoSamples - }, - set: function(i) { - var psamples = this._anisoSamples - this._anisoSamples = Math.max(i, 1)|0 - if(psamples !== this._anisoSamples) { - var ext = gl.getExtension('EXT_texture_filter_anisotropic') - if(ext) { - this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) + if(o0 < 0 || o1 < 0) { + if(o1 > o0) { + closest |= 1< o0) { + closest |= 1< cubeVerts[i][1]) { + bottom = i } - }, - width: { - get: function() { - return this._shape[0] - }, - set: function(w) { - w = w|0 - reshapeTexture(this, w, this._shape[1]) - return w + } + + //Find left/right neighbors of bottom vertex + var left = -1 + for(var i=0; i<3; ++i) { + var idx = bottom ^ (1< cubeVerts[right][0]) { + right = idx } } -}) -proto.bind = function(unit) { - var gl = this.gl - if(unit !== undefined) { - gl.activeTexture(gl.TEXTURE0 + (unit|0)) + //Determine edge axis coordinates + var cubeEdges = CUBE_EDGES + cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0 + cubeEdges[bits.log2(left^bottom)] = bottom&left + cubeEdges[bits.log2(bottom^right)] = bottom&right + var top = right ^ 7 + if(top === closest || top === farthest) { + top = left ^ 7 + cubeEdges[bits.log2(right^top)] = top&right + } else { + cubeEdges[bits.log2(left^top)] = top&left } - gl.bindTexture(gl.TEXTURE_2D, this.handle) - if(unit !== undefined) { - return (unit|0) + + //Determine visible faces + var axis = CUBE_AXIS + var cutCorner = closest + for(var d=0; d<3; ++d) { + if(cutCorner & (1<0; ++i, l>>>=1) { - if(this._mipLevels.indexOf(i) < 0) { - this._mipLevels.push(i) - } - } -} + //Create grid lines for each axis/direction + var gridOffset = [0,0,0] + var gridCount = [0,0,0] -proto.setPixels = function(data, x_off, y_off, mip_level) { - var gl = this.gl - this.bind() - if(Array.isArray(x_off)) { - mip_level = y_off - y_off = x_off[1]|0 - x_off = x_off[0]|0 - } else { - x_off = x_off || 0 - y_off = y_off || 0 - } - mip_level = mip_level || 0 - if(data instanceof HTMLCanvasElement || - data instanceof ImageData || - data instanceof HTMLImageElement || - data instanceof HTMLVideoElement) { - var needsMip = this._mipLevels.indexOf(mip_level) < 0 - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data) - this._mipLevels.push(mip_level) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data) + //Add zero line + vertices.push( + 0,0,1, 0,1,1, 0,0,-1, + 0,0,-1, 0,1,1, 0,1,-1) + + for(var i=0; i<3; ++i) { + //Axis tick marks + var start = ((vertices.length / 3)|0) + for(var j=0; j this._shape[1]>>>mip_level || - y_off + data.shape[0] > this._shape[0]>>>mip_level || - x_off < 0 || - y_off < 0) { - throw new Error('gl-texture2d: Texture dimensions are out of bounds') + var end = ((vertices.length / 3)|0) + tickOffset[i] = start + tickCount[i] = end - start + + //Grid lines + var start = ((vertices.length / 3)|0) + for(var k=0; k 3) { - throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') - } - var type = 0, format = 0 - var packed = isPacked(shape, array.stride.slice()) - if(dtype === 'float32') { - type = gl.FLOAT - } else if(dtype === 'float64') { - type = gl.FLOAT - packed = false - dtype = 'float32' - } else if(dtype === 'uint8') { - type = gl.UNSIGNED_BYTE - } else { - type = gl.UNSIGNED_BYTE - packed = false - dtype = 'uint8' - } - var channels = 1 - if(shape.length === 2) { - format = gl.LUMINANCE - shape = [shape[0], shape[1], 1] - array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) - } else if(shape.length === 3) { - if(shape[2] === 1) { - format = gl.ALPHA - } else if(shape[2] === 2) { - format = gl.LUMINANCE_ALPHA - } else if(shape[2] === 3) { - format = gl.RGB - } else if(shape[2] === 4) { - format = gl.RGBA - } else { - throw new Error('gl-texture2d: Invalid shape for pixel coords') - } - channels = shape[2] - } else { - throw new Error('gl-texture2d: Invalid shape for texture') - } - //For 1-channel textures allow conversion between formats - if((format === gl.LUMINANCE || format === gl.ALPHA) && - (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { - format = cformat - } - if(format !== cformat) { - throw new Error('gl-texture2d: Incompatible texture format for setPixels') - } - var size = array.size - var needsMip = mipLevels.indexOf(mip_level) < 0 - if(needsMip) { - mipLevels.push(mip_level) - } - if(type === ctype && packed) { - //Array data types are compatible, can directly copy into texture - if(array.offset === 0 && array.data.length === size) { - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) - } - } else { - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) - } - } - } else { - //Need to do type conversion to pack data into buffer - var pack_buffer - if(ctype === gl.FLOAT) { - pack_buffer = pool.mallocFloat32(size) - } else { - pack_buffer = pool.mallocUint8(size) - } - var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) - if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { - convertFloatToUint8(pack_view, array) - } else { - ops.assign(pack_view, array) - } - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) - } - if(ctype === gl.FLOAT) { - pool.freeFloat32(pack_buffer) - } else { - pool.freeUint8(pack_buffer) - } - } +var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}" +var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" +exports.text = function(gl) { + return createShader(gl, textVert, textFrag, null, [ + {name: 'position', type: 'vec3'} + ]) } -function initTexture(gl) { - var tex = gl.createTexture() - gl.bindTexture(gl.TEXTURE_2D, tex) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) - return tex +var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}" +var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}" +exports.bg = function(gl) { + return createShader(gl, bgVert, bgFrag, null, [ + {name: 'position', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) } -function createTextureShape(gl, width, height, format, type) { - var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { - throw new Error('gl-texture2d: Invalid texture shape') - } - if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { - throw new Error('gl-texture2d: Floating point textures not supported on this platform') - } - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) - return new Texture2D(gl, tex, width, height, format, type) +},{"gl-shader":590}],470:[function(require,module,exports){ +(function (process){ +"use strict" + +module.exports = createTextSprites + +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var vectorizeText = require('vectorize-text') +var createShader = require('./shaders').text + +var globals = window || process.global || {} +var __TEXT_CACHE = globals.__TEXT_CACHE || {} +globals.__TEXT_CACHE = {} + +//Vertex buffer format for text is: +// +/// [x,y,z] = Spatial coordinate +// + +var VERTEX_SIZE = 3 +var VERTEX_STRIDE = VERTEX_SIZE * 4 + +function TextSprites( + gl, + shader, + buffer, + vao) { + this.gl = gl + this.shader = shader + this.buffer = buffer + this.vao = vao + this.tickOffset = + this.tickCount = + this.labelOffset = + this.labelCount = null } -function createTextureDOM(gl, element, format, type) { - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element) - return new Texture2D(gl, tex, element.width|0, element.height|0, format, type) +var proto = TextSprites.prototype + +//Bind textures for rendering +var SHAPE = [0,0] +proto.bind = function(model, view, projection, pixelScale) { + this.vao.bind() + this.shader.bind() + var uniforms = this.shader.uniforms + uniforms.model = model + uniforms.view = view + uniforms.projection = projection + uniforms.pixelScale = pixelScale + SHAPE[0] = this.gl.drawingBufferWidth + SHAPE[1] = this.gl.drawingBufferHeight + this.shader.uniforms.resolution = SHAPE } -//Creates a texture from an ndarray -function createTextureArray(gl, array) { - var dtype = array.dtype - var shape = array.shape.slice() - var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { - throw new Error('gl-texture2d: Invalid texture size') - } - var packed = isPacked(shape, array.stride.slice()) - var type = 0 - if(dtype === 'float32') { - type = gl.FLOAT - } else if(dtype === 'float64') { - type = gl.FLOAT - packed = false - dtype = 'float32' - } else if(dtype === 'uint8') { - type = gl.UNSIGNED_BYTE - } else { - type = gl.UNSIGNED_BYTE - packed = false - dtype = 'uint8' - } - var format = 0 - if(shape.length === 2) { - format = gl.LUMINANCE - shape = [shape[0], shape[1], 1] - array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) - } else if(shape.length === 3) { - if(shape[2] === 1) { - format = gl.ALPHA - } else if(shape[2] === 2) { - format = gl.LUMINANCE_ALPHA - } else if(shape[2] === 3) { - format = gl.RGB - } else if(shape[2] === 4) { - format = gl.RGBA - } else { - throw new Error('gl-texture2d: Invalid shape for pixel coords') +proto.update = function(bounds, labels, labelFont, ticks, tickFont) { + var gl = this.gl + var data = [] + + function addItem(t, text, font, size) { + var fontcache = __TEXT_CACHE[font] + if(!fontcache) { + fontcache = __TEXT_CACHE[font] = {} } - } else { - throw new Error('gl-texture2d: Invalid shape for texture') - } - if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { - type = gl.UNSIGNED_BYTE - packed = false - } - var buffer, buf_store - var size = array.size - if(!packed) { - var stride = [shape[2], shape[2]*shape[0], 1] - buf_store = pool.malloc(size, dtype) - var buf_array = ndarray(buf_store, shape, stride, 0) - if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { - convertFloatToUint8(buf_array, array) - } else { - ops.assign(buf_array, array) + var mesh = fontcache[text] + if(!mesh) { + mesh = fontcache[text] = tryVectorizeText(text, { + triangles: true, + font: font, + textAlign: 'center', + textBaseline: 'middle' + }) } - buffer = buf_store.subarray(0, size) - } else if (array.offset === 0 && array.data.length === size) { - buffer = array.data - } else { - buffer = array.data.subarray(array.offset, array.offset + size) - } - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) - if(!packed) { - pool.free(buf_store) - } - return new Texture2D(gl, tex, shape[0], shape[1], format, type) -} - -function createTexture2D(gl) { - if(arguments.length <= 1) { - throw new Error('gl-texture2d: Missing arguments for texture2d constructor') - } - if(!linearTypes) { - lazyInitLinearTypes(gl) - } - if(typeof arguments[1] === 'number') { - return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) - } - if(Array.isArray(arguments[1])) { - return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) - } - if(typeof arguments[1] === 'object') { - var obj = arguments[1] - if(obj instanceof HTMLCanvasElement || - obj instanceof HTMLImageElement || - obj instanceof HTMLVideoElement || - obj instanceof ImageData) { - return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) - } else if(obj.shape && obj.data && obj.stride) { - return createTextureArray(gl, obj) + var scale = (size || 12) / 12 + var positions = mesh.positions + var cells = mesh.cells + var lo = [ Infinity, Infinity] + var hi = [-Infinity,-Infinity] + for(var i=0, nc=cells.length; i=0; --j) { + var p = positions[c[j]] + data.push(scale*p[0], -scale*p[1], t) + } } } - throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') -} -},{"ndarray":253,"ndarray-ops":252,"typedarray-pool":278}],223:[function(require,module,exports){ -"use strict" + //Generate sprites for all 3 axes, store data in texture atlases + var tickOffset = [0,0,0] + var tickCount = [0,0,0] + var labelOffset = [0,0,0] + var labelCount = [0,0,0] + for(var d=0; d<3; ++d) { -function doBind(gl, elements, attributes) { - if(elements) { - elements.bind() - } else { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) - } - var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0 - if(attributes) { - if(attributes.length > nattribs) { - throw new Error("gl-vao: Too many vertex attributes") - } - for(var i=0; i= 0) { + sigFigs = stepStr.length - u - 1 + } + var shift = Math.pow(10, sigFigs) + var x = Math.round(spacing * i * shift) + var xstr = x + "" + if(xstr.indexOf("e") >= 0) { + return xstr + } + var xi = x / shift, xf = x % shift + if(x < 0) { + xi = -Math.ceil(xi)|0 + xf = (-xf)|0 + } else { + xi = Math.floor(xi)|0 + xf = xf|0 + } + var xis = "" + xi + if(x < 0) { + xis = "-" + xis + } + if(sigFigs) { + var xs = "" + xf + while(xs.length < sigFigs) { + xs = "0" + xs } + return xis + "." + xs + } else { + return xis } - this._useElements = !!elements - this._elementsType = elementsType || this.gl.UNSIGNED_SHORT } -VAONative.prototype.draw = function(mode, count, offset) { - offset = offset || 0 - var gl = this.gl - if(this._useElements) { - gl.drawElements(mode, count, this._elementsType, offset) - } else { - gl.drawArrays(mode, offset, count) +function defaultTicks(bounds, tickSpacing) { + var array = [] + for(var d=0; d<3; ++d) { + var ticks = [] + var m = 0.5*(bounds[0][d]+bounds[1][d]) + for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) { + ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) + } + for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) { + ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) + } + array.push(ticks) } + return array } -function createVAONative(gl, ext) { - return new VAONative(gl, ext, ext.createVertexArrayOES()) +function ticksEqual(ticksA, ticksB) { + for(var i=0; i<3; ++i) { + if(ticksA[i].length !== ticksB[i].length) { + return false + } + for(var j=0; j 1.0) { + t = 1.0 + } + var ti = 1.0 - t + var n = a.length + var r = new Array(n) + for(var i=0; i 0) || (a > 0 && b < 0)) { + var p = lerpW(s, b, t, a) + pos.push(p) + neg.push(p.slice()) + } + if(b < 0) { + neg.push(t.slice()) + } else if(b > 0) { + pos.push(t.slice()) + } else { + pos.push(t.slice()) + neg.push(t.slice()) + } + a = b + } + return { positive: pos, negative: neg } +} + +function positive(points, plane) { + var pos = [] + var a = planeT(points[points.length-1], plane) + for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { + pos.push(lerpW(s, b, t, a)) + } + if(b >= 0) { + pos.push(t.slice()) + } + a = b } + return pos +} - function token(data) { - if (data.length) { - tokens.push({ - type: map[mode] - , data: data - , position: start - , line: line - , column: col - }) +function negative(points, plane) { + var neg = [] + var a = planeT(points[points.length-1], plane) + for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { + neg.push(lerpW(s, b, t, a)) + } + if(b <= 0) { + neg.push(t.slice()) + } + a = b + } + return neg +} +},{"robust-dot-product":483,"robust-sum":485}],483:[function(require,module,exports){ +"use strict" + +var twoProduct = require("two-product") +var robustSum = require("robust-sum") + +module.exports = robustDotProduct + +function robustDotProduct(a, b) { + var r = twoProduct(a[0], b[0]) + for(var i=1; i_inline_1_arg0_||255>_inline_1_arg1_||255>_inline_1_arg2_||255>_inline_1_arg3_){var _inline_1_l=_inline_1_arg4_-_inline_1_arg6_[0],_inline_1_a=_inline_1_arg5_-_inline_1_arg6_[1],_inline_1_f=_inline_1_l*_inline_1_l+_inline_1_a*_inline_1_a;_inline_1_f this.buffer.length) { + pool.free(this.buffer) + var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) + for(var i=0; i 0) continue - res = buf.slice(0, 1).join('') - } +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders/index') - token(res) +module.exports = createSpikes - start += res.length - content = content.slice(res.length) - return content.length - } while(1) - } +var identity = [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] - function hex() { - if(/[^a-fA-F0-9]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } +function AxisSpikes(gl, buffer, vao, shader) { + this.gl = gl + this.buffer = buffer + this.vao = vao + this.shader = shader + this.pixelRatio = 1 + this.bounds = [[-1000,-1000,-1000], [1000,1000,1000]] + this.position = [0,0,0] + this.lineWidth = [2,2,2] + this.colors = [[0,0,0,1], [0,0,0,1], [0,0,0,1]] + this.enabled = [true,true,true] + this.drawSides = [true,true,true] + this.axes = null +} - content.push(c) - last = c - return i + 1 - } +var proto = AxisSpikes.prototype - function integer() { - if(c === '.') { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } +var OUTER_FACE = [0,0,0] +var INNER_FACE = [0,0,0] - if(/[eE]/.test(c)) { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } +var SHAPE = [0,0] - if(c === 'x' && content.length === 1 && content[0] === '0') { - mode = HEX - content.push(c) - last = c - return i + 1 - } +proto.isTransparent = function() { + return false +} - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } +proto.drawTransparent = function(camera) {} - content.push(c) - last = c - return i + 1 - } +proto.draw = function(camera) { + var gl = this.gl + var vao = this.vao + var shader = this.shader - function decimal() { - if(c === 'f') { - content.push(c) - last = c - i += 1 - } + vao.bind() + shader.bind() - if(/[eE]/.test(c)) { - content.push(c) - last = c - return i + 1 - } + var model = camera.model || identity + var view = camera.view || identity + var projection = camera.projection || identity - if (c === '-' && /[eE]/.test(last)) { - content.push(c) - last = c - return i + 1 - } + var axis + if(this.axes) { + axis = this.axes.lastCubeProps.axis + } - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i + var outerFace = OUTER_FACE + var innerFace = INNER_FACE + for(var i=0; i<3; ++i) { + if(axis && axis[i] < 0) { + outerFace[i] = this.bounds[0][i] + innerFace[i] = this.bounds[1][i] + } else { + outerFace[i] = this.bounds[1][i] + innerFace[i] = this.bounds[0][i] } - - content.push(c) - last = c - return i + 1 } - function readtoken() { - if(/[^\d\w_]/.test(c)) { - var contentstr = content.join('') - if(allLiterals.indexOf(contentstr) > -1) { - mode = KEYWORD - } else if(allBuiltins.indexOf(contentstr) > -1) { - mode = BUILTIN - } else { - mode = IDENT + SHAPE[0] = gl.drawingBufferWidth + SHAPE[1] = gl.drawingBufferHeight + + shader.uniforms.model = model + shader.uniforms.view = view + shader.uniforms.projection = projection + shader.uniforms.coordinates = [this.position, outerFace, innerFace] + shader.uniforms.colors = this.colors + shader.uniforms.screenShape = SHAPE + + for(var i=0; i<3; ++i) { + shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio + if(this.enabled[i]) { + vao.draw(gl.TRIANGLES, 6, 6*i) + if(this.drawSides[i]) { + vao.draw(gl.TRIANGLES, 12, 18+12*i) } - token(content.join('')) - mode = NORMAL - return i } - content.push(c) - last = c - return i + 1 + } + + vao.unbind() +} + +proto.update = function(options) { + if(!options) { + return + } + if("bounds" in options) { + this.bounds = options.bounds + } + if("position" in options) { + this.position = options.position + } + if("lineWidth" in options) { + this.lineWidth = options.lineWidth + } + if("colors" in options) { + this.colors = options.colors + } + if("enabled" in options) { + this.enabled = options.enabled + } + if("drawSides" in options) { + this.drawSides = options.drawSides } } -},{"./lib/builtins":230,"./lib/builtins-300es":229,"./lib/literals":232,"./lib/literals-300es":231,"./lib/operators":233}],229:[function(require,module,exports){ -// 300es builtins/reserved words that were previously valid in v100 -var v100 = require('./builtins') - -// The texture2D|Cube functions have been removed -// And the gl_ features are updated -v100 = v100.slice().filter(function (b) { - return !/^(gl\_|texture)/.test(b) -}) +proto.dispose = function() { + this.vao.dispose() + this.buffer.dispose() + this.shader.dispose() +} -module.exports = v100.concat([ - // the updated gl_ constants - 'gl_VertexID' - , 'gl_InstanceID' - , 'gl_Position' - , 'gl_PointSize' - , 'gl_FragCoord' - , 'gl_FrontFacing' - , 'gl_FragDepth' - , 'gl_PointCoord' - , 'gl_MaxVertexAttribs' - , 'gl_MaxVertexUniformVectors' - , 'gl_MaxVertexOutputVectors' - , 'gl_MaxFragmentInputVectors' - , 'gl_MaxVertexTextureImageUnits' - , 'gl_MaxCombinedTextureImageUnits' - , 'gl_MaxTextureImageUnits' - , 'gl_MaxFragmentUniformVectors' - , 'gl_MaxDrawBuffers' - , 'gl_MinProgramTexelOffset' - , 'gl_MaxProgramTexelOffset' - , 'gl_DepthRangeParameters' - , 'gl_DepthRange' - // other builtins - , 'trunc' - , 'round' - , 'roundEven' - , 'isnan' - , 'isinf' - , 'floatBitsToInt' - , 'floatBitsToUint' - , 'intBitsToFloat' - , 'uintBitsToFloat' - , 'packSnorm2x16' - , 'unpackSnorm2x16' - , 'packUnorm2x16' - , 'unpackUnorm2x16' - , 'packHalf2x16' - , 'unpackHalf2x16' - , 'outerProduct' - , 'transpose' - , 'determinant' - , 'inverse' - , 'texture' - , 'textureSize' - , 'textureProj' - , 'textureLod' - , 'textureOffset' - , 'texelFetch' - , 'texelFetchOffset' - , 'textureProjOffset' - , 'textureLodOffset' - , 'textureProjLod' - , 'textureProjLodOffset' - , 'textureGrad' - , 'textureGradOffset' - , 'textureProjGrad' - , 'textureProjGradOffset' -]) -},{"./builtins":230}],230:[function(require,module,exports){ -module.exports = [ - // Keep this list sorted - 'abs' - , 'acos' - , 'all' - , 'any' - , 'asin' - , 'atan' - , 'ceil' - , 'clamp' - , 'cos' - , 'cross' - , 'dFdx' - , 'dFdy' - , 'degrees' - , 'distance' - , 'dot' - , 'equal' - , 'exp' - , 'exp2' - , 'faceforward' - , 'floor' - , 'fract' - , 'gl_BackColor' - , 'gl_BackLightModelProduct' - , 'gl_BackLightProduct' - , 'gl_BackMaterial' - , 'gl_BackSecondaryColor' - , 'gl_ClipPlane' - , 'gl_ClipVertex' - , 'gl_Color' - , 'gl_DepthRange' - , 'gl_DepthRangeParameters' - , 'gl_EyePlaneQ' - , 'gl_EyePlaneR' - , 'gl_EyePlaneS' - , 'gl_EyePlaneT' - , 'gl_Fog' - , 'gl_FogCoord' - , 'gl_FogFragCoord' - , 'gl_FogParameters' - , 'gl_FragColor' - , 'gl_FragCoord' - , 'gl_FragData' - , 'gl_FragDepth' - , 'gl_FragDepthEXT' - , 'gl_FrontColor' - , 'gl_FrontFacing' - , 'gl_FrontLightModelProduct' - , 'gl_FrontLightProduct' - , 'gl_FrontMaterial' - , 'gl_FrontSecondaryColor' - , 'gl_LightModel' - , 'gl_LightModelParameters' - , 'gl_LightModelProducts' - , 'gl_LightProducts' - , 'gl_LightSource' - , 'gl_LightSourceParameters' - , 'gl_MaterialParameters' - , 'gl_MaxClipPlanes' - , 'gl_MaxCombinedTextureImageUnits' - , 'gl_MaxDrawBuffers' - , 'gl_MaxFragmentUniformComponents' - , 'gl_MaxLights' - , 'gl_MaxTextureCoords' - , 'gl_MaxTextureImageUnits' - , 'gl_MaxTextureUnits' - , 'gl_MaxVaryingFloats' - , 'gl_MaxVertexAttribs' - , 'gl_MaxVertexTextureImageUnits' - , 'gl_MaxVertexUniformComponents' - , 'gl_ModelViewMatrix' - , 'gl_ModelViewMatrixInverse' - , 'gl_ModelViewMatrixInverseTranspose' - , 'gl_ModelViewMatrixTranspose' - , 'gl_ModelViewProjectionMatrix' - , 'gl_ModelViewProjectionMatrixInverse' - , 'gl_ModelViewProjectionMatrixInverseTranspose' - , 'gl_ModelViewProjectionMatrixTranspose' - , 'gl_MultiTexCoord0' - , 'gl_MultiTexCoord1' - , 'gl_MultiTexCoord2' - , 'gl_MultiTexCoord3' - , 'gl_MultiTexCoord4' - , 'gl_MultiTexCoord5' - , 'gl_MultiTexCoord6' - , 'gl_MultiTexCoord7' - , 'gl_Normal' - , 'gl_NormalMatrix' - , 'gl_NormalScale' - , 'gl_ObjectPlaneQ' - , 'gl_ObjectPlaneR' - , 'gl_ObjectPlaneS' - , 'gl_ObjectPlaneT' - , 'gl_Point' - , 'gl_PointCoord' - , 'gl_PointParameters' - , 'gl_PointSize' - , 'gl_Position' - , 'gl_ProjectionMatrix' - , 'gl_ProjectionMatrixInverse' - , 'gl_ProjectionMatrixInverseTranspose' - , 'gl_ProjectionMatrixTranspose' - , 'gl_SecondaryColor' - , 'gl_TexCoord' - , 'gl_TextureEnvColor' - , 'gl_TextureMatrix' - , 'gl_TextureMatrixInverse' - , 'gl_TextureMatrixInverseTranspose' - , 'gl_TextureMatrixTranspose' - , 'gl_Vertex' - , 'greaterThan' - , 'greaterThanEqual' - , 'inversesqrt' - , 'length' - , 'lessThan' - , 'lessThanEqual' - , 'log' - , 'log2' - , 'matrixCompMult' - , 'max' - , 'min' - , 'mix' - , 'mod' - , 'normalize' - , 'not' - , 'notEqual' - , 'pow' - , 'radians' - , 'reflect' - , 'refract' - , 'sign' - , 'sin' - , 'smoothstep' - , 'sqrt' - , 'step' - , 'tan' - , 'texture2D' - , 'texture2DLod' - , 'texture2DProj' - , 'texture2DProjLod' - , 'textureCube' - , 'textureCubeLod' - , 'texture2DLodEXT' - , 'texture2DProjLodEXT' - , 'textureCubeLodEXT' - , 'texture2DGradEXT' - , 'texture2DProjGradEXT' - , 'textureCubeGradEXT' -] +function createSpikes(gl, options) { + //Create buffers + var data = [ ] -},{}],231:[function(require,module,exports){ -var v100 = require('./literals') + function line(x,y,z,i,l,h) { + var row = [x,y,z, 0,0,0, 1] + row[i+3] = 1 + row[i] = l + data.push.apply(data, row) + row[6] = -1 + data.push.apply(data, row) + row[i] = h + data.push.apply(data, row) + data.push.apply(data, row) + row[6] = 1 + data.push.apply(data, row) + row[i] = l + data.push.apply(data, row) + } -module.exports = v100.slice().concat([ - 'layout' - , 'centroid' - , 'smooth' - , 'case' - , 'mat2x2' - , 'mat2x3' - , 'mat2x4' - , 'mat3x2' - , 'mat3x3' - , 'mat3x4' - , 'mat4x2' - , 'mat4x3' - , 'mat4x4' - , 'uint' - , 'uvec2' - , 'uvec3' - , 'uvec4' - , 'samplerCubeShadow' - , 'sampler2DArray' - , 'sampler2DArrayShadow' - , 'isampler2D' - , 'isampler3D' - , 'isamplerCube' - , 'isampler2DArray' - , 'usampler2D' - , 'usampler3D' - , 'usamplerCube' - , 'usampler2DArray' - , 'coherent' - , 'restrict' - , 'readonly' - , 'writeonly' - , 'resource' - , 'atomic_uint' - , 'noperspective' - , 'patch' - , 'sample' - , 'subroutine' - , 'common' - , 'partition' - , 'active' - , 'filter' - , 'image1D' - , 'image2D' - , 'image3D' - , 'imageCube' - , 'iimage1D' - , 'iimage2D' - , 'iimage3D' - , 'iimageCube' - , 'uimage1D' - , 'uimage2D' - , 'uimage3D' - , 'uimageCube' - , 'image1DArray' - , 'image2DArray' - , 'iimage1DArray' - , 'iimage2DArray' - , 'uimage1DArray' - , 'uimage2DArray' - , 'image1DShadow' - , 'image2DShadow' - , 'image1DArrayShadow' - , 'image2DArrayShadow' - , 'imageBuffer' - , 'iimageBuffer' - , 'uimageBuffer' - , 'sampler1DArray' - , 'sampler1DArrayShadow' - , 'isampler1D' - , 'isampler1DArray' - , 'usampler1D' - , 'usampler1DArray' - , 'isampler2DRect' - , 'usampler2DRect' - , 'samplerBuffer' - , 'isamplerBuffer' - , 'usamplerBuffer' - , 'sampler2DMS' - , 'isampler2DMS' - , 'usampler2DMS' - , 'sampler2DMSArray' - , 'isampler2DMSArray' - , 'usampler2DMSArray' -]) + line(0,0,0, 0, 0, 1) + line(0,0,0, 1, 0, 1) + line(0,0,0, 2, 0, 1) -},{"./literals":232}],232:[function(require,module,exports){ -module.exports = [ - // current - 'precision' - , 'highp' - , 'mediump' - , 'lowp' - , 'attribute' - , 'const' - , 'uniform' - , 'varying' - , 'break' - , 'continue' - , 'do' - , 'for' - , 'while' - , 'if' - , 'else' - , 'in' - , 'out' - , 'inout' - , 'float' - , 'int' - , 'void' - , 'bool' - , 'true' - , 'false' - , 'discard' - , 'return' - , 'mat2' - , 'mat3' - , 'mat4' - , 'vec2' - , 'vec3' - , 'vec4' - , 'ivec2' - , 'ivec3' - , 'ivec4' - , 'bvec2' - , 'bvec3' - , 'bvec4' - , 'sampler1D' - , 'sampler2D' - , 'sampler3D' - , 'samplerCube' - , 'sampler1DShadow' - , 'sampler2DShadow' - , 'struct' + line(1,0,0, 1, -1,1) + line(1,0,0, 2, -1,1) - // future - , 'asm' - , 'class' - , 'union' - , 'enum' - , 'typedef' - , 'template' - , 'this' - , 'packed' - , 'goto' - , 'switch' - , 'default' - , 'inline' - , 'noinline' - , 'volatile' - , 'public' - , 'static' - , 'extern' - , 'external' - , 'interface' - , 'long' - , 'short' - , 'double' - , 'half' - , 'fixed' - , 'unsigned' - , 'input' - , 'output' - , 'hvec2' - , 'hvec3' - , 'hvec4' - , 'dvec2' - , 'dvec3' - , 'dvec4' - , 'fvec2' - , 'fvec3' - , 'fvec4' - , 'sampler2DRect' - , 'sampler3DRect' - , 'sampler2DRectShadow' - , 'sizeof' - , 'cast' - , 'namespace' - , 'using' -] + line(0,1,0, 0, -1,1) + line(0,1,0, 2, -1,1) -},{}],233:[function(require,module,exports){ -module.exports = [ - '<<=' - , '>>=' - , '++' - , '--' - , '<<' - , '>>' - , '<=' - , '>=' - , '==' - , '!=' - , '&&' - , '||' - , '+=' - , '-=' - , '*=' - , '/=' - , '%=' - , '&=' - , '^^' - , '^=' - , '|=' - , '(' - , ')' - , '[' - , ']' - , '.' - , '!' - , '~' - , '*' - , '/' - , '%' - , '+' - , '-' - , '<' - , '>' - , '&' - , '^' - , '|' - , '?' - , ':' - , '=' - , ',' - , ';' - , '{' - , '}' -] + line(0,0,1, 0, -1,1) + line(0,0,1, 1, -1,1) -},{}],234:[function(require,module,exports){ -var tokenize = require('./index') + var buffer = createBuffer(gl, data) + var vao = createVAO(gl, [{ + type: gl.FLOAT, + buffer: buffer, + size: 3, + offset: 0, + stride: 28 + }, { + type: gl.FLOAT, + buffer: buffer, + size: 3, + offset: 12, + stride: 28 + }, { + type: gl.FLOAT, + buffer: buffer, + size: 1, + offset: 24, + stride: 28 + }]) -module.exports = tokenizeString + //Create shader + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.color.location = 1 + shader.attributes.weight.location = 2 -function tokenizeString(str, opt) { - var generator = tokenize(opt) - var tokens = [] + //Create spike object + var spikes = new AxisSpikes(gl, buffer, vao, shader) - tokens = tokens.concat(generator(str)) - tokens = tokens.concat(generator(null)) + //Set parameters + spikes.update(options) - return tokens + //Return resulting object + return spikes } -},{"./index":228}],235:[function(require,module,exports){ -"use strict" - -//High level idea: -// 1. Use Clarkson's incremental construction to find convex hull -// 2. Point location in triangulation by jump and walk +},{"./shaders/index":624,"gl-buffer":616,"gl-vao":623}],626:[function(require,module,exports){ +'use strict' -module.exports = incrementalConvexHull +module.exports = createScene -var orient = require("robust-orientation") -var compareCell = require("simplicial-complex").compareCells +var createCamera = require('3d-view-controls') +var createAxes = require('gl-axes3d') +var axesRanges = require('gl-axes3d/properties') +var createSpikes = require('gl-spikes3d') +var createSelect = require('gl-select-static') +var createFBO = require('gl-fbo') +var drawTriangle = require('a-big-triangle') +var mouseChange = require('mouse-change') +var perspective = require('gl-mat4/perspective') +var createShader = require('./lib/shader') -function compareInt(a, b) { - return a - b +function MouseSelect() { + this.mouse = [-1,-1] + this.screen = null + this.distance = Infinity + this.index = null + this.dataCoordinate = null + this.dataPosition = null + this.object = null + this.data = null } -function Simplex(vertices, adjacent, boundary) { - this.vertices = vertices - this.adjacent = adjacent - this.boundary = boundary - this.lastVisited = -1 +function getContext(canvas, options) { + var gl = null + try { + gl = canvas.getContext('webgl', options) + if(!gl) { + gl = canvas.getContext('experimental-webgl', options) + } + } catch(e) { + return null + } + return gl } -Simplex.prototype.flip = function() { - var t = this.vertices[0] - this.vertices[0] = this.vertices[1] - this.vertices[1] = t - var u = this.adjacent[0] - this.adjacent[0] = this.adjacent[1] - this.adjacent[1] = u +function roundUpPow10(x) { + var y = Math.round(Math.log(Math.abs(x)) / Math.log(10)) + if(y < 0) { + var base = Math.round(Math.pow(10, -y)) + return Math.ceil(x*base) / base + } else if(y > 0) { + var base = Math.round(Math.pow(10, y)) + return Math.ceil(x/base) * base + } + return Math.ceil(x) } -function GlueFacet(vertices, cell, index) { - this.vertices = vertices - this.cell = cell - this.index = index +function defaultBool(x) { + if(typeof x === 'boolean') { + return x + } + return true } -function compareGlue(a, b) { - return compareCell(a.vertices, b.vertices) -} +function createScene(options) { + options = options || {} -function bakeOrient(d) { - var code = ["function orient(){var tuple=this.tuple;return test("] - for(var i=0; i<=d; ++i) { - if(i > 0) { - code.push(",") + var stopped = false + + var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio) + + var canvas = options.canvas + if(!canvas) { + canvas = document.createElement('canvas') + if(options.container) { + var container = options.container + container.appendChild(canvas) + } else { + document.body.appendChild(canvas) } - code.push("tuple[", i, "]") } - code.push(")}return orient") - var proc = new Function("test", code.join("")) - var test = orient[d+1] - if(!test) { - test = orient + + var gl = options.gl + if(!gl) { + gl = getContext(canvas, + options.glOptions || { + premultipliedAlpha: true, + antialias: true + }) + } + if(!gl) { + throw new Error('webgl not supported') } - return proc(test) -} -var BAKED = [] + //Initial bounds + var bounds = options.bounds || [[-10,-10,-10], [10,10,10]] -function Triangulation(dimension, vertices, simplices) { - this.dimension = dimension - this.vertices = vertices - this.simplices = simplices - this.interior = simplices.filter(function(c) { - return !c.boundary - }) + //Create selection + var selection = new MouseSelect() - this.tuple = new Array(dimension+1) - for(var i=0; i<=dimension; ++i) { - this.tuple[i] = this.vertices[i] + //Accumulation buffer + var accumBuffer = createFBO(gl, + [gl.drawingBufferWidth, gl.drawingBufferHeight], { + preferFloat: true + }) + + var accumShader = createShader(gl) + + //Create a camera + var cameraOptions = options.camera || { + eye: [2,0,0], + center: [0,0,0], + up: [0,1,0], + zoomMin: 0.1, + zoomMax: 100, + mode: 'turntable' } - var o = BAKED[dimension] - if(!o) { - o = BAKED[dimension] = bakeOrient(dimension) + //Create axes + var axesOptions = options.axes || {} + var axes = createAxes(gl, axesOptions) + axes.enable = !axesOptions.disable + + //Create spikes + var spikeOptions = options.spikes || {} + var spikes = createSpikes(gl, spikeOptions) + + //Object list is empty initially + var objects = [] + var pickBufferIds = [] + var pickBufferCount = [] + var pickBuffers = [] + + //Dirty flag, skip redraw if scene static + var dirty = true + var pickDirty = true + + var projection = new Array(16) + var model = new Array(16) + + var cameraParams = { + view: null, + projection: projection, + model: model } - this.orient = o -} -var proto = Triangulation.prototype + var pickDirty = true -//Degenerate situation where we are on boundary, but coplanar to face -proto.handleBoundaryDegeneracy = function(cell, point) { - var d = this.dimension - var n = this.vertices.length - 1 - var tuple = this.tuple - var verts = this.vertices + var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ] - //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate - var toVisit = [ cell ] - cell.lastVisited = -n - while(toVisit.length > 0) { - cell = toVisit.pop() - var cellVerts = cell.vertices - var cellAdj = cell.adjacent - for(var i=0; i<=d; ++i) { - var neighbor = cellAdj[i] - if(!neighbor.boundary || neighbor.lastVisited <= -n) { + //Create scene object + var scene = { + gl: gl, + contextLost: false, + pixelRatio: options.pixelRatio || parseFloat(window.devicePixelRatio), + canvas: canvas, + selection: selection, + camera: createCamera(canvas, cameraOptions), + axes: axes, + axesPixels: null, + spikes: spikes, + bounds: bounds, + objects: objects, + shape: viewShape, + aspect: options.aspectRatio || [1,1,1], + pickRadius: options.pickRadius || 10, + zNear: options.zNear || 0.01, + zFar: options.zFar || 1000, + fovy: options.fovy || Math.PI/4, + clearColor: options.clearColor || [0,0,0,0], + autoResize: defaultBool(options.autoResize), + autoBounds: defaultBool(options.autoBounds), + autoScale: !!options.autoScale, + autoCenter: defaultBool(options.autoCenter), + clipToBounds: defaultBool(options.clipToBounds), + snapToData: !!options.snapToData, + onselect: options.onselect || null, + onrender: options.onrender || null, + onclick: options.onclick || null, + cameraParams: cameraParams, + oncontextloss: null, + mouseListener: null + } + + var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ] + + function resizeListener() { + if(stopped) { + return + } + if(!scene.autoResize) { + return + } + var parent = canvas.parentNode + var width = 1 + var height = 1 + if(parent && parent !== document.body) { + width = parent.clientWidth + height = parent.clientHeight + } else { + width = window.innerWidth + height = window.innerHeight + } + var nextWidth = Math.ceil(width * scene.pixelRatio)|0 + var nextHeight = Math.ceil(height * scene.pixelRatio)|0 + if(nextWidth !== canvas.width || nextHeight !== canvas.height) { + canvas.width = nextWidth + canvas.height = nextHeight + var style = canvas.style + style.position = style.position || 'absolute' + style.left = '0px' + style.top = '0px' + style.width = width + 'px' + style.height = height + 'px' + dirty = true + } + } + if(scene.autoResize) { + resizeListener() + } + window.addEventListener('resize', resizeListener) + + function reallocPickIds() { + var numObjs = objects.length + var numPick = pickBuffers.length + for(var i=0; i 0) { - return neighbor - } - neighbor.lastVisited = -n - if(o === 0) { - toVisit.push(neighbor) - } + //Create new pick buffer + var nbuffer = createSelect(gl, viewShape) + pickBufferIds[i] = numPick + pickBuffers.push(nbuffer) + pickBufferCount.push(pickCount) + obj.setPickBase(1) + numPick += 1 + } + while(numPick > 0 && pickBufferCount[numPick-1] === 0) { + pickBufferCount.pop() + pickBuffers.pop().dispose() } } - return null -} -proto.walk = function(point, random) { - //Alias local properties - var n = this.vertices.length - 1 - var d = this.dimension - var verts = this.vertices - var tuple = this.tuple + scene.update = function(options) { + if(stopped) { + return + } + options = options || {} + dirty = true + pickDirty = true + } - //Compute initial jump cell - var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1) - var cell = this.interior[ initIndex ] + scene.add = function(obj) { + if(stopped) { + return + } + obj.axes = axes + objects.push(obj) + pickBufferIds.push(-1) + dirty = true + pickDirty = true + reallocPickIds() + } - //Start walking -outerLoop: - while(!cell.boundary) { - var cellVerts = cell.vertices - var cellAdj = cell.adjacent + scene.remove = function(obj) { + if(stopped) { + return + } + var idx = objects.indexOf(obj) + if(idx < 0) { + return + } + objects.splice(idx, 1) + pickBufferIds.pop() + dirty = true + pickDirty = true + reallocPickIds() + } - for(var i=0; i<=d; ++i) { - tuple[i] = verts[cellVerts[i]] + scene.dispose = function() { + if(stopped) { + return } - cell.lastVisited = n - //Find farthest adjacent cell - for(var i=0; i<=d; ++i) { - var neighbor = cellAdj[i] - if(neighbor.lastVisited >= n) { - continue - } - var prev = tuple[i] - tuple[i] = point - var o = this.orient() - tuple[i] = prev - if(o < 0) { - cell = neighbor - continue outerLoop - } else { - if(!neighbor.boundary) { - neighbor.lastVisited = n - } else { - neighbor.lastVisited = -n - } - } + stopped = true + + window.removeEventListener('resize', resizeListener) + canvas.removeEventListener('webglcontextlost', checkContextLoss) + scene.mouseListener.enabled = false + + if(scene.contextLost) { + return } - return - } - return cell -} + //Destroy objects + axes.dispose() + spikes.dispose() + for(var i=0; i 0) { - //Pop off peak and walk over adjacent cells - var cell = tovisit.pop() - var cellVerts = cell.vertices - var cellAdj = cell.adjacent - var indexOfN = cellVerts.indexOf(n) - if(indexOfN < 0) { - continue + var prevButtons = 0 + + scene.mouseListener = mouseChange(canvas, function(buttons, x, y) { + if(stopped) { + return } - for(var i=0; i<=d; ++i) { - if(i === indexOfN) { - continue - } + var numPick = pickBuffers.length + var numObjs = objects.length + var prevObj = selection.object - //For each boundary neighbor of the cell - var neighbor = cellAdj[i] - if(!neighbor.boundary || neighbor.lastVisited >= n) { - continue - } + selection.distance = Infinity + selection.mouse[0] = x + selection.mouse[1] = y + selection.object = null + selection.screen = null + selection.dataCoordinate = selection.dataPosition = null - var nv = neighbor.vertices + var change = false - //Test if neighbor is a peak - if(neighbor.lastVisited !== -n) { - //Compute orientation of p relative to each boundary peak - var indexOfNeg1 = 0 - for(var j=0; j<=d; ++j) { - if(nv[j] < 0) { - indexOfNeg1 = j - tuple[j] = point - } else { - tuple[j] = verts[nv[j]] + if(buttons && prevButtons) { + mouseRotating = true + } else { + if(mouseRotating) { + pickDirty = true + } + mouseRotating = false + + for(var i=0; i selection.distance) { + continue + } + for(var j=0; j 0) { - nv[indexOfNeg1] = n - neighbor.boundary = false - interior.push(neighbor) - tovisit.push(neighbor) - neighbor.lastVisited = n - continue - } else { - neighbor.lastVisited = -n - } + if(prevObj && prevObj !== selection.object) { + if(prevObj.highlight) { + prevObj.highlight(null) + } + dirty = true + } + if(selection.object) { + if(selection.object.highlight) { + selection.object.highlight(selection.data) } + dirty = true + } - var na = neighbor.adjacent + change = change || (selection.object !== prevObj) + if(change && scene.onselect) { + scene.onselect(selection) + } - //Otherwise, replace neighbor with new face - var vverts = cellVerts.slice() - var vadj = cellAdj.slice() - var ncell = new Simplex(vverts, vadj, true) - simplices.push(ncell) + if((buttons & 1) && !(prevButtons & 1) && scene.onclick) { + scene.onclick(selection) + } + prevButtons = buttons + }) - //Connect to neighbor - var opposite = na.indexOf(cell) - if(opposite < 0) { - continue + function checkContextLoss() { + if(scene.contextLost) { + return true + } + if(gl.isContextLost()) { + scene.contextLost = true + scene.mouseListener.enabled = false + scene.selection.object = null + if(scene.oncontextloss) { + scene.oncontextloss() } - na[opposite] = ncell - vadj[indexOfN] = neighbor + } + } - //Connect to cell - vverts[i] = -1 - vadj[i] = cell - cellAdj[i] = ncell + canvas.addEventListener('webglcontextlost', checkContextLoss) - //Flip facet - ncell.flip() + //Render the scene for mouse picking + function renderPick() { + if(checkContextLoss()) { + return + } - //Add to glue list - for(var j=0; j<=d; ++j) { - var uu = vverts[j] - if(uu < 0 || uu === n) { + gl.colorMask(true, true, true, true) + gl.depthMask(true) + gl.disable(gl.BLEND) + gl.enable(gl.DEPTH_TEST) + + var numObjs = objects.length + var numPick = pickBuffers.length + for(var j=0; j= 0) { - bcell[ptr++] = cv[j] - } else { - parity = j&1 + dirty = dirty || !!obj.dirty + pickDirty = pickDirty || !!obj.dirty + var obb = obj.bounds + if(obb) { + var olo = obb[0] + var ohi = obb[1] + for(var j=0; j<3; ++j) { + lo[j] = Math.min(lo[j], olo[j]) + hi[j] = Math.max(hi[j], ohi[j]) } } - if(parity === (d&1)) { - var t = bcell[0] - bcell[0] = bcell[1] - bcell[1] = t - } - boundary.push(bcell) } - } - return boundary -} - -function incrementalConvexHull(points, randomSearch) { - var n = points.length - if(n === 0) { - throw new Error("Must have at least d+1 points") - } - var d = points[0].length - if(n <= d) { - throw new Error("Must input at least d+1 points") - } - - //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process - var initialSimplex = points.slice(0, d+1) - - //Make sure initial simplex is positively oriented - var o = orient.apply(void 0, initialSimplex) - if(o === 0) { - throw new Error("Input not in general position") - } - var initialCoords = new Array(d+1) - for(var i=0; i<=d; ++i) { - initialCoords[i] = i - } - if(o < 0) { - initialCoords[0] = 1 - initialCoords[1] = 0 - } - //Create initial topological index, glue pointers together (kind of messy) - var initialCell = new Simplex(initialCoords, new Array(d+1), false) - var boundary = initialCell.adjacent - var list = new Array(d+2) - for(var i=0; i<=d; ++i) { - var verts = initialCoords.slice() - for(var j=0; j<=d; ++j) { - if(j === i) { - verts[j] = -1 + //Recalculate bounds + var bounds = scene.bounds + if(scene.autoBounds) { + for(var j=0; j<3; ++j) { + if(hi[j] < lo[j]) { + lo[j] = -1 + hi[j] = 1 + } else { + if(lo[j] === hi[j]) { + lo[j] -= 1 + hi[j] += 1 + } + var padding = 0.05 * (hi[j] - lo[j]) + lo[j] = lo[j] - padding + hi[j] = hi[j] + padding + } + bounds[0][j] = lo[j] + bounds[1][j] = hi[j] } } - var t = verts[0] - verts[0] = verts[1] - verts[1] = t - var cell = new Simplex(verts, new Array(d+1), true) - boundary[i] = cell - list[i] = cell - } - list[d+1] = initialCell - for(var i=0; i<=d; ++i) { - var verts = boundary[i].vertices - var adj = boundary[i].adjacent - for(var j=0; j<=d; ++j) { - var v = verts[j] - if(v < 0) { - adj[j] = initialCell - continue + + var boundsChanged = false + for(var j=0; j<3; ++j) { + boundsChanged = boundsChanged || + (prevBounds[0][j] !== bounds[0][j]) || + (prevBounds[1][j] !== bounds[1][j]) + prevBounds[0][j] = bounds[0][j] + prevBounds[1][j] = bounds[1][j] + } + + if(boundsChanged) { + var tickSpacing = [0,0,0] + for(var i=0; i<3; ++i) { + tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0) } - for(var k=0; k<=d; ++k) { - if(boundary[k].vertices.indexOf(v) < 0) { - adj[j] = boundary[k] - } + if(axes.autoTicks) { + axes.update({ + bounds: bounds, + tickSpacing: tickSpacing + }) + } else { + axes.update({ + bounds: bounds + }) } } - } - - //Initialize triangles - var triangles = new Triangulation(d, initialSimplex, list) - //Insert remaining points - var useRandom = !!randomSearch - for(var i=d+1; i> 1 - , s = compareCells(cells[mid], c) - if(s <= 0) { - if(s === 0) { - r = mid - } - lo = mid + 1 - } else if(s > 0) { - hi = mid - 1 + spikes.axes = axes + if(selection.object) { + spikes.draw(cameraParams) } - } - return r -} -exports.findCell = findCell; -//Builds an index for an n-cell. This is more general than dual, but less efficient -function incidence(from_cells, to_cells) { - var index = new Array(from_cells.length) - for(var i=0, il=index.length; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { - break - } + if(obj.isTransparent && obj.isTransparent()) { + hasTransparent = true } } - } - return index -} -exports.incidence = incidence -//Computes the dual of the mesh. This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices -function dual(cells, vertex_count) { - if(!vertex_count) { - return incidence(unique(skeleton(cells, 0)), cells, 0) - } - var res = new Array(vertex_count) - for(var i=0; i>> k) & 1) { - b.push(c[k]) + //Render forward facing objects + if(axes.enable && axes.isTransparent()) { + axes.drawTransparent(cameraParams) + } + for(var i=0; i - * License: MIT - * - * `npm install is-buffer` - */ -module.exports = function (obj) { - return !!(obj != null && - (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) - (obj.constructor && - typeof obj.constructor.isBuffer === 'function' && - obj.constructor.isBuffer(obj)) - )) +module.exports = { + vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", + fragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n", + pickVertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", + pickFragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n" } -},{}],241:[function(require,module,exports){ +},{}],628:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":658}],629:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":630,"./lib/create-attributes":631,"./lib/create-uniforms":632,"./lib/reflect":633,"./lib/runtime-reflect":634,"./lib/shader-cache":635,"dup":94}],630:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],631:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":630,"dup":96}],632:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":630,"./reflect":633,"dup":97}],633:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],634:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],635:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":630,"dup":100,"gl-format-compiler-error":636,"weakmap-shim":654}],636:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":637,"dup":101,"gl-constants/lookup":641,"glsl-shader-name":642,"sprintf-js":651}],637:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":638}],638:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":639}],639:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],640:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],641:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":640,"dup":106}],642:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":643,"dup":107,"glsl-tokenizer":650}],643:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],644:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":646,"./lib/builtins-300es":645,"./lib/literals":648,"./lib/literals-300es":647,"./lib/operators":649,"dup":109}],645:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":646,"dup":110}],646:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],647:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":648,"dup":112}],648:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],649:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],650:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":644,"dup":115}],651:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],652:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":653,"dup":117}],653:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],654:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":652,"dup":119}],655:[function(require,module,exports){ +arguments[4][451][0].apply(exports,arguments) +},{"_process":70,"dup":451,"vectorize-text":659}],656:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],657:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],658:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":656,"buffer":65,"dup":122}],659:[function(require,module,exports){ +arguments[4][354][0].apply(exports,arguments) +},{"./lib/vtext":660,"dup":354}],660:[function(require,module,exports){ +arguments[4][355][0].apply(exports,arguments) +},{"cdt2d":661,"clean-pslg":673,"dup":355,"ndarray":1031,"planar-graph-to-polyline":728,"simplify-planar-graph":732,"surface-nets":745}],661:[function(require,module,exports){ +arguments[4][356][0].apply(exports,arguments) +},{"./lib/delaunay":662,"./lib/filter":663,"./lib/monotone":664,"./lib/triangulation":665,"dup":356}],662:[function(require,module,exports){ +arguments[4][357][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":357,"robust-in-sphere":667}],663:[function(require,module,exports){ +arguments[4][358][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":358}],664:[function(require,module,exports){ +arguments[4][359][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":359,"robust-orientation":1040}],665:[function(require,module,exports){ +arguments[4][360][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":360}],666:[function(require,module,exports){ +arguments[4][312][0].apply(exports,arguments) +},{"dup":312}],667:[function(require,module,exports){ +arguments[4][361][0].apply(exports,arguments) +},{"dup":361,"robust-scale":669,"robust-subtract":670,"robust-sum":671,"two-product":672}],668:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"dup":53}],669:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54,"two-product":672,"two-sum":668}],670:[function(require,module,exports){ +arguments[4][364][0].apply(exports,arguments) +},{"dup":364}],671:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],672:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56}],673:[function(require,module,exports){ +arguments[4][367][0].apply(exports,arguments) +},{"./lib/rat-seg-intersect":674,"big-rat":678,"big-rat/cmp":676,"big-rat/to-float":693,"box-intersect":694,"compare-cell":702,"dup":367,"nextafter":703,"rat-vec":706,"robust-segment-intersect":709,"union-find":710}],674:[function(require,module,exports){ +arguments[4][368][0].apply(exports,arguments) +},{"big-rat/div":677,"big-rat/mul":687,"big-rat/sign":691,"big-rat/sub":692,"big-rat/to-float":693,"dup":368,"rat-vec/add":705,"rat-vec/muls":707,"rat-vec/sub":708}],675:[function(require,module,exports){ +arguments[4][369][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":369}],676:[function(require,module,exports){ +arguments[4][370][0].apply(exports,arguments) +},{"dup":370}],677:[function(require,module,exports){ +arguments[4][371][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":371}],678:[function(require,module,exports){ +arguments[4][372][0].apply(exports,arguments) +},{"./div":677,"./is-rat":679,"./lib/is-bn":683,"./lib/num-to-bn":684,"./lib/rationalize":685,"./lib/str-to-bn":686,"dup":372}],679:[function(require,module,exports){ +arguments[4][373][0].apply(exports,arguments) +},{"./lib/is-bn":683,"dup":373}],680:[function(require,module,exports){ +arguments[4][374][0].apply(exports,arguments) +},{"bn.js":689,"dup":374}],681:[function(require,module,exports){ +arguments[4][375][0].apply(exports,arguments) +},{"dup":375}],682:[function(require,module,exports){ +arguments[4][376][0].apply(exports,arguments) +},{"bit-twiddle":688,"double-bits":690,"dup":376}],683:[function(require,module,exports){ +arguments[4][377][0].apply(exports,arguments) +},{"bn.js":689,"dup":377}],684:[function(require,module,exports){ +arguments[4][378][0].apply(exports,arguments) +},{"bn.js":689,"double-bits":690,"dup":378}],685:[function(require,module,exports){ +arguments[4][379][0].apply(exports,arguments) +},{"./bn-sign":680,"./num-to-bn":684,"dup":379}],686:[function(require,module,exports){ +arguments[4][380][0].apply(exports,arguments) +},{"bn.js":689,"dup":380}],687:[function(require,module,exports){ +arguments[4][381][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":381}],688:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],689:[function(require,module,exports){ +arguments[4][383][0].apply(exports,arguments) +},{"dup":383}],690:[function(require,module,exports){ +arguments[4][384][0].apply(exports,arguments) +},{"buffer":65,"dup":384}],691:[function(require,module,exports){ +arguments[4][385][0].apply(exports,arguments) +},{"./lib/bn-sign":680,"dup":385}],692:[function(require,module,exports){ +arguments[4][386][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":386}],693:[function(require,module,exports){ +arguments[4][387][0].apply(exports,arguments) +},{"./lib/bn-to-num":681,"./lib/ctz":682,"dup":387}],694:[function(require,module,exports){ +arguments[4][388][0].apply(exports,arguments) +},{"./lib/intersect":696,"./lib/sweep":700,"dup":388,"typedarray-pool":658}],695:[function(require,module,exports){ +arguments[4][389][0].apply(exports,arguments) +},{"dup":389}],696:[function(require,module,exports){ +arguments[4][390][0].apply(exports,arguments) +},{"./brute":695,"./median":697,"./partition":698,"./sweep":700,"bit-twiddle":701,"dup":390,"typedarray-pool":658}],697:[function(require,module,exports){ +arguments[4][391][0].apply(exports,arguments) +},{"./partition":698,"dup":391}],698:[function(require,module,exports){ +arguments[4][392][0].apply(exports,arguments) +},{"dup":392}],699:[function(require,module,exports){ +arguments[4][393][0].apply(exports,arguments) +},{"dup":393}],700:[function(require,module,exports){ +arguments[4][394][0].apply(exports,arguments) +},{"./sort":699,"bit-twiddle":701,"dup":394,"typedarray-pool":658}],701:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],702:[function(require,module,exports){ +arguments[4][61][0].apply(exports,arguments) +},{"dup":61}],703:[function(require,module,exports){ +arguments[4][399][0].apply(exports,arguments) +},{"double-bits":704,"dup":399}],704:[function(require,module,exports){ +arguments[4][384][0].apply(exports,arguments) +},{"buffer":65,"dup":384}],705:[function(require,module,exports){ +arguments[4][401][0].apply(exports,arguments) +},{"big-rat/add":675,"dup":401}],706:[function(require,module,exports){ +arguments[4][402][0].apply(exports,arguments) +},{"big-rat":678,"dup":402}],707:[function(require,module,exports){ +arguments[4][403][0].apply(exports,arguments) +},{"big-rat":678,"big-rat/mul":687,"dup":403}],708:[function(require,module,exports){ +arguments[4][404][0].apply(exports,arguments) +},{"big-rat/sub":692,"dup":404}],709:[function(require,module,exports){ +arguments[4][405][0].apply(exports,arguments) +},{"dup":405,"robust-orientation":1040}],710:[function(require,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],711:[function(require,module,exports){ +arguments[4][407][0].apply(exports,arguments) +},{"dup":407,"edges-to-adjacency-list":712}],712:[function(require,module,exports){ +arguments[4][408][0].apply(exports,arguments) +},{"dup":408,"uniq":727}],713:[function(require,module,exports){ +arguments[4][409][0].apply(exports,arguments) +},{"compare-angle":714,"dup":409}],714:[function(require,module,exports){ +arguments[4][410][0].apply(exports,arguments) +},{"dup":410,"robust-orientation":1040,"robust-product":716,"robust-sum":725,"signum":717,"two-sum":718}],715:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54,"two-product":726,"two-sum":718}],716:[function(require,module,exports){ +arguments[4][412][0].apply(exports,arguments) +},{"dup":412,"robust-scale":715,"robust-sum":725}],717:[function(require,module,exports){ +arguments[4][413][0].apply(exports,arguments) +},{"dup":413}],718:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"dup":53}],719:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],720:[function(require,module,exports){ +arguments[4][416][0].apply(exports,arguments) +},{"binary-search-bounds":719,"dup":416}],721:[function(require,module,exports){ +arguments[4][417][0].apply(exports,arguments) +},{"dup":417,"robust-orientation":1040}],722:[function(require,module,exports){ +arguments[4][418][0].apply(exports,arguments) +},{"dup":418}],723:[function(require,module,exports){ +arguments[4][419][0].apply(exports,arguments) +},{"./lib/order-segments":721,"binary-search-bounds":719,"dup":419,"functional-red-black-tree":722,"robust-orientation":1040}],724:[function(require,module,exports){ +arguments[4][420][0].apply(exports,arguments) +},{"binary-search-bounds":719,"dup":420,"interval-tree-1d":720,"robust-orientation":1040,"slab-decomposition":723}],725:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],726:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56}],727:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],728:[function(require,module,exports){ +arguments[4][424][0].apply(exports,arguments) +},{"./lib/trim-leaves":711,"dup":424,"edges-to-adjacency-list":712,"planar-dual":713,"point-in-big-polygon":724,"robust-sum":725,"two-product":726,"uniq":727}],729:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],730:[function(require,module,exports){ +arguments[4][426][0].apply(exports,arguments) +},{"dup":426}],731:[function(require,module,exports){ +arguments[4][79][0].apply(exports,arguments) +},{"bit-twiddle":729,"dup":79,"union-find":730}],732:[function(require,module,exports){ +arguments[4][428][0].apply(exports,arguments) +},{"dup":428,"robust-orientation":1040,"simplicial-complex":731}],733:[function(require,module,exports){ +arguments[4][429][0].apply(exports,arguments) +},{"dup":429,"typedarray-pool":658}],734:[function(require,module,exports){ +arguments[4][433][0].apply(exports,arguments) +},{"dup":433}],735:[function(require,module,exports){ +arguments[4][437][0].apply(exports,arguments) +},{"dup":437,"typedarray-pool":658}],736:[function(require,module,exports){ +arguments[4][438][0].apply(exports,arguments) +},{"dup":438,"invert-permutation":737,"typedarray-pool":658}],737:[function(require,module,exports){ +arguments[4][439][0].apply(exports,arguments) +},{"dup":439}],738:[function(require,module,exports){ +arguments[4][443][0].apply(exports,arguments) +},{"dup":443,"gamma":734,"permutation-parity":735,"permutation-rank":736}],739:[function(require,module,exports){ +arguments[4][444][0].apply(exports,arguments) +},{"cwise-compiler":740,"dup":444}],740:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./lib/thunk.js":742,"dup":319}],741:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320,"uniq":743}],742:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"./compile.js":741,"dup":321}],743:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],744:[function(require,module,exports){ +arguments[4][449][0].apply(exports,arguments) +},{"./lib/zc-core":739,"dup":449}],745:[function(require,module,exports){ +arguments[4][450][0].apply(exports,arguments) +},{"dup":450,"ndarray-extract-contour":733,"triangulate-hypercube":738,"zero-crossings":744}],746:[function(require,module,exports){ 'use strict' -module.exports = mouseListen +module.exports = createFancyScatter2D -var mouse = require('mouse-event') +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var textCache = require('text-cache') +var pool = require('typedarray-pool') +var vectorizeText = require('vectorize-text') +var shaders = require('./lib/shaders') -function mouseListen(element, callback) { +var BOUNDARIES = {} - if(!callback) { - callback = element - element = window +function getBoundary(glyph) { + if(glyph in BOUNDARIES) { + return BOUNDARIES[glyph] } - var buttonState = 0 - var x = 0 - var y = 0 - var mods = { - shift: false, - alt: false, - control: false, - meta: false - } - var attached = false + var polys = vectorizeText(glyph, { + polygons: true, + font: 'sans-serif', + textAlign: 'left', + textBaseline: 'alphabetic' + }) - function updateMods(ev) { - var changed = false - if('altKey' in ev) { - changed = changed || ev.altKey !== mods.alt - mods.alt = !!ev.altKey - } - if('shiftKey' in ev) { - changed = changed || ev.shiftKey !== mods.shift - mods.shift = !!ev.shiftKey - } - if('ctrlKey' in ev) { - changed = changed || ev.ctrlKey !== mods.control - mods.control = !!ev.ctrlKey - } - if('metaKey' in ev) { - changed = changed || ev.metaKey !== mods.meta - mods.meta = !!ev.metaKey - } - return changed - } + var coords = [] + var normals = [] - function handleEvent(nextButtons, ev) { - var nextX = mouse.x(ev) - var nextY = mouse.y(ev) - if('buttons' in ev) { - nextButtons = ev.buttons|0 - } - if(nextButtons !== buttonState || - nextX !== x || - nextY !== y || - updateMods(ev)) { - buttonState = nextButtons|0 - x = nextX||0 - y = nextY||0 - callback(buttonState, x, y, mods) - } - } + polys.forEach(function(loops) { + loops.forEach(function(loop) { + for(var i=0; i 0) { - return 1<<(b-1) - } - } else if('button' in ev) { - var b = ev.button - if(b === 1) { - return 4 - } else if(b === 2) { - return 2 - } else if(b >= 0) { - return 1<>(i*8)) & 0xff) } - var target = mouseElement(ev) - var bounds = target.getBoundingClientRect() - return ev.clientY - bounds.top - } - return 0 -} -exports.y = mouseRelativeY -},{}],243:[function(require,module,exports){ -module.exports = function parseUnit(str, out) { - if (!out) - out = [ 0, '' ] + calcScales.call(this) - str = String(str) - var num = parseFloat(str, 10) - out[0] = num - out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || '' - return out -} -},{}],244:[function(require,module,exports){ -'use strict' + shader.bind() -var parseUnit = require('parse-unit') + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.viewTransform = MATRIX + shader.uniforms.pickOffset = PICK_OFFSET -module.exports = toPX + this.positionBuffer.bind() + shader.attributes.position.pointer() -var PIXELS_PER_INCH = 96 + this.offsetBuffer.bind() + shader.attributes.offset.pointer() -function getPropertyInPX(element, prop) { - var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop)) - return parts[0] * toPX(parts[1], element) -} + this.idBuffer.bind() + shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false) -//This brutal hack is needed -function getSizeBrutal(unit, element) { - var testDIV = document.createElement('div') - testDIV.style['font-size'] = '128' + unit - element.appendChild(testDIV) - var size = getPropertyInPX(testDIV, 'font-size') / 128 - element.removeChild(testDIV) - return size -} + gl.drawArrays(gl.TRIANGLES, 0, numVertices) -function toPX(str, element) { - element = element || document.body - str = (str || 'px').trim().toLowerCase() - if(element === window || element === document) { - element = document.body - } - switch(str) { - case '%': //Ambiguous, not sure if we should use width or height - return element.clientHeight / 100.0 - case 'ch': - case 'ex': - return getSizeBrutal(str, element) - case 'em': - return getPropertyInPX(element, 'font-size') - case 'rem': - return getPropertyInPX(document.body, 'font-size') - case 'vw': - return window.innerWidth/100 - case 'vh': - return window.innerHeight/100 - case 'vmin': - return Math.min(window.innerWidth, window.innerHeight) / 100 - case 'vmax': - return Math.max(window.innerWidth, window.innerHeight) / 100 - case 'in': - return PIXELS_PER_INCH - case 'cm': - return PIXELS_PER_INCH / 2.54 - case 'mm': - return PIXELS_PER_INCH / 25.4 - case 'pt': - return PIXELS_PER_INCH / 72 - case 'pc': - return PIXELS_PER_INCH / 6 + return offset + this.numPoints } - return 1 -} -},{"parse-unit":243}],245:[function(require,module,exports){ -'use strict' - -var toPX = require('to-px') - -module.exports = mouseWheelListen +})() -function mouseWheelListen(element, callback, noScroll) { - if(typeof element === 'function') { - noScroll = !!callback - callback = element - element = window +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.numPoints + if(value < pickOffset || value >= pickOffset + pointCount) { + return null } - var lineHeight = toPX('ex', element) - var listener = function(ev) { - if(noScroll) { - ev.preventDefault() - } - var dx = ev.deltaX || 0 - var dy = ev.deltaY || 0 - var dz = ev.deltaZ || 0 - var mode = ev.deltaMode - var scale = 1 - switch(mode) { - case 1: - scale = lineHeight - break - case 2: - scale = window.innerHeight - break - } - dx *= scale - dy *= scale - dz *= scale - if(dx || dy || dz) { - return callback(dx, dy, dz) - } + var pointId = value - pickOffset + var points = this.points + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] } - element.addEventListener('wheel', listener) - return listener -} - -},{"to-px":244}],246:[function(require,module,exports){ -"use strict" - - - -var fill = require('cwise/lib/wrapper')({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}","args":[{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) - -module.exports = function(array, f) { - fill(array, f) - return array } -},{"cwise/lib/wrapper":112}],247:[function(require,module,exports){ -'use strict' +proto.update = function(options) { + options = options || {} -module.exports = invert + var positions = options.positions || [] + var colors = options.colors || [] + var glyphs = options.glyphs || [] + var sizes = options.sizes || [] + var borderWidths = options.borderWidths || [] + var borderColors = options.borderColors || [] -var invert2 = require('gl-mat2/invert') -var invert3 = require('gl-mat3/invert') -var invert4 = require('gl-mat4/invert') + this.points = positions -function invert(out, M) { - switch(M.length) { - case 0: - break - case 1: - out[0] = 1.0 / M[0] - break - case 4: - invert2(out, M) - break - case 9: - invert3(out, M) - break - case 16: - invert4(out, M) - break - default: - throw new Error('currently supports matrices up to 4x4') - break + var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + var numVertices = 0 + for(var i=0; i> 1 + for(var j=0; j<2; ++j) { + bounds[j] = Math.min(bounds[j], positions[2*i+j]) + bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j]) + } } - return out -} -},{"gl-mat2/invert":248,"gl-mat3/invert":130,"gl-mat4/invert":137}],248:[function(require,module,exports){ -module.exports = invert -/** - * Inverts a mat2 - * - * @alias mat2.invert - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ -function invert(out, a) { - var a0 = a[0] - var a1 = a[1] - var a2 = a[2] - var a3 = a[3] - var det = a0 * a3 - a2 * a1 + if(bounds[0] === bounds[2]) { + bounds[2] += 1 + } + if(bounds[3] === bounds[1]) { + bounds[3] += 1 + } - if (!det) return null - det = 1.0 / det + var sx = 1/(bounds[2] - bounds[0]) + var sy = 1/(bounds[3] - bounds[1]) + var tx = bounds[0] + var ty = bounds[1] - out[0] = a3 * det - out[1] = -a1 * det - out[2] = -a2 * det - out[3] = a0 * det + var v_position = pool.mallocFloat32(2 * numVertices) + var v_offset = pool.mallocFloat32(2 * numVertices) + var v_color = pool.mallocUint8(4 * numVertices) + var v_ids = pool.mallocUint32(numVertices) + var ptr = 0 - return out -} + for(var i=0; i left) { + var b_level = data_levels[j-1] + var b_x = data_points[2*(j-1)] + if(((b_level - a_level) || (a_x - b_x)) >= 0) { + break + } + data_levels[j] = b_level + data_points[2*j] = b_x + data_points[2*j+1] = data_points[2*j-1] + data_ids[j] = data_ids[j-1] + data_weights[j] = data_weights[j-1] + j -= 1 + } + + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } - var wrapper = new Function("P", [ - "return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}" - ].join("")) - return wrapper(pcompile(user_args)) } -var assign_ops = { - add: "+", - sub: "-", - mul: "*", - div: "/", - mod: "%", - band: "&", - bor: "|", - bxor: "^", - lshift: "<<", - rshift: ">>", - rrshift: ">>>" -} -;(function(){ - for(var id in assign_ops) { - var op = assign_ops[id] - exports[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a","b","c"], - body: "a=b"+op+"c"}, - funcName: id - }) - exports[id+"eq"] = makeOp({ - args: ["array","array"], - body: {args:["a","b"], - body:"a"+op+"=b"}, - rvalue: true, - funcName: id+"eq" - }) - exports[id+"s"] = makeOp({ - args: ["array", "array", "scalar"], - body: {args:["a","b","s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - exports[id+"seq"] = makeOp({ - args: ["array","scalar"], - body: {args:["a","s"], - body:"a"+op+"=s"}, - rvalue: true, - funcName: id+"seq" - }) - } -})(); +function swap(i, j, data_levels, data_points, data_ids, data_weights) { + var a_level = data_levels[i] + var a_x = data_points[2*i] + var a_y = data_points[2*i+1] + var a_id = data_ids[i] + var a_weight = data_weights[i] -var unary_ops = { - not: "!", - bnot: "~", - neg: "-", - recip: "1.0/" -} -;(function(){ - for(var id in unary_ops) { - var op = unary_ops[id] - exports[id] = makeOp({ - args: ["array", "array"], - body: {args:["a","b"], - body:"a="+op+"b"}, - funcName: id - }) - exports[id+"eq"] = makeOp({ - args: ["array"], - body: {args:["a"], - body:"a="+op+"a"}, - rvalue: true, - count: 2, - funcName: id+"eq" - }) - } -})(); + data_levels[i] = data_levels[j] + data_points[2*i] = data_points[2*j] + data_points[2*i+1] = data_points[2*j+1] + data_ids[i] = data_ids[j] + data_weights[i] = data_weights[j] -var binary_ops = { - and: "&&", - or: "||", - eq: "===", - neq: "!==", - lt: "<", - gt: ">", - leq: "<=", - geq: ">=" + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } -;(function() { - for(var id in binary_ops) { - var op = binary_ops[id] - exports[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a", "b", "c"], - body:"a=b"+op+"c"}, - funcName: id - }) - exports[id+"s"] = makeOp({ - args: ["array","array","scalar"], - body: {args:["a", "b", "s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - exports[id+"eq"] = makeOp({ - args: ["array", "array"], - body: {args:["a", "b"], - body:"a=a"+op+"b"}, - rvalue:true, - count:2, - funcName: id+"eq" - }) - exports[id+"seq"] = makeOp({ - args: ["array", "scalar"], - body: {args:["a","s"], - body:"a=a"+op+"s"}, - rvalue:true, - count:2, - funcName: id+"seq" - }) - } -})(); -var math_unary = [ - "abs", - "acos", - "asin", - "atan", - "ceil", - "cos", - "exp", - "floor", - "log", - "round", - "sin", - "sqrt", - "tan" -] -;(function() { - for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norminf" -}) +function compare(i, j, data_levels, data_points, data_ids) { + return ((data_levels[i] - data_levels[j]) || + (data_points[2*j] - data_points[2*i]) || + (data_ids[i] - data_ids[j])) < 0 +} -exports.norm1 = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norm1" -}) +function comparePivot(i, level, x, y, id, data_levels, data_points, data_ids) { + return ((level - data_levels[i]) || + (data_points[2*i] - x) || + (id - data_ids[i])) < 0 +} -exports.sup = compile({ - args: [ "array" ], - pre: - { body: "this_h=-Infinity", - args: [], - thisVars: [ "this_h" ], - localVars: [] }, - body: - { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", - args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], - thisVars: [ "this_h" ], - localVars: [] }, - post: - { body: "return this_h", - args: [], - thisVars: [ "this_h" ], - localVars: [] } - }) +function quickSort(left, right, data_levels, data_points, data_ids, data_weights) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, + tmp = 0 + if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el2 + el2 = tmp + } + if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el4 + el4 = el5 + el5 = tmp + } + if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el3 + el3 = tmp + } + if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el4 + el4 = tmp + } + if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) { + tmp = el3 + el3 = el4 + el4 = tmp + } + if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el5 + el5 = tmp + } + if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el4 + el4 = el5 + el5 = tmp + } -exports.inf = compile({ - args: [ "array" ], - pre: - { body: "this_h=Infinity", - args: [], - thisVars: [ "this_h" ], - localVars: [] }, - body: - { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", - args:[ - {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, - {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], - thisVars:["this_i","this_v"], - localVars:["_inline_1_k"]}, - post:{ - body:"{return this_i}", - args:[], - thisVars:["this_i"], - localVars:[]} -}) + var ptr0 = el1 + var ptr2 = el3 + var ptr4 = el5 + var ptr5 = index1 + var ptr6 = index3 + var ptr7 = index5 -exports.random = makeOp({ - args: ["array"], - pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, - body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, - funcName: "random" -}) + var level_x = data_levels[ptr0] + var level_y = data_levels[ptr2] + var level_z = data_levels[ptr4] + data_levels[ptr5] = level_x + data_levels[ptr6] = level_y + data_levels[ptr7] = level_z -exports.assign = makeOp({ - args:["array", "array"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assign" }) + for (var i1 = 0; i1 < 2; ++i1) { + var x = data_points[2*ptr0+i1] + var y = data_points[2*ptr2+i1] + var z = data_points[2*ptr4+i1] + data_points[2*ptr5+i1] = x + data_points[2*ptr6+i1] = y + data_points[2*ptr7+i1] = z + } -exports.assigns = makeOp({ - args:["array", "scalar"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assigns" }) + var id_x = data_ids[ptr0] + var id_y = data_ids[ptr2] + var id_z = data_ids[ptr4] + data_ids[ptr5] = id_x + data_ids[ptr6] = id_y + data_ids[ptr7] = id_z + var weight_x = data_weights[ptr0] + var weight_y = data_weights[ptr2] + var weight_z = data_weights[ptr4] + data_weights[ptr5] = weight_x + data_weights[ptr6] = weight_y + data_weights[ptr7] = weight_z -exports.equals = compile({ - args:["array", "array"], - pre: EmptyProc, - body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, - {name:"y", lvalue:false, rvalue:true, count:1}], - body: "if(x!==y){return false}", - localVars: [], - thisVars: []}, - post: {args:[], localVars:[], thisVars:[], body:"return true"}, - funcName: "equals" -}) + move(index2, left, data_levels, data_points, data_ids, data_weights) + move(index4, right, data_levels, data_points, data_ids, data_weights) + for (var k = less; k <= great; ++k) { + if (comparePivot(k, + pivot1_level, pivot1_x, pivot1_y, pivot1_id, + data_levels, data_points, data_ids)) { + if (k !== less) { + swap(k, less, data_levels, data_points, data_ids, data_weights) + } + ++less; + } else { + if (!comparePivot(k, + pivot2_level, pivot2_x, pivot2_y, pivot2_id, + data_levels, data_points, data_ids)) { + while (true) { + if (!comparePivot(great, + pivot2_level, pivot2_x, pivot2_y, pivot2_id, + data_levels, data_points, data_ids)) { + if (--great < k) { + break; + } + continue; + } else { + if (comparePivot(great, + pivot1_level, pivot1_x, pivot1_y, pivot1_id, + data_levels, data_points, data_ids)) { + rotate(k, less, great, data_levels, data_points, data_ids, data_weights) + ++less; + --great; + } else { + swap(k, great, data_levels, data_points, data_ids, data_weights) + --great; + } + break; + } + } + } + } + } + shufflePivot(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) + shufflePivot(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) + if (less - 2 - left <= INSERT_SORT_CUTOFF) { + insertionSort(left, less - 2, data_levels, data_points, data_ids, data_weights) + } else { + quickSort(left, less - 2, data_levels, data_points, data_ids, data_weights) + } + if (right - (great + 2) <= INSERT_SORT_CUTOFF) { + insertionSort(great + 2, right, data_levels, data_points, data_ids, data_weights) + } else { + quickSort(great + 2, right, data_levels, data_points, data_ids, data_weights) + } + if (great - less <= INSERT_SORT_CUTOFF) { + insertionSort(less, great, data_levels, data_points, data_ids, data_weights) + } else { + quickSort(less, great, data_levels, data_points, data_ids, data_weights) + } +} +},{}],777:[function(require,module,exports){ +'use strict' +var pool = require('typedarray-pool') -},{"cwise-compiler":109}],253:[function(require,module,exports){ -var iota = require("iota-array") -var isBuffer = require("is-buffer") +var sortLevels = require('./lib/sort') -var hasTypedArrays = ((typeof Float64Array) !== "undefined") +module.exports = snapPoints -function compare1st(a, b) { - return a[0] - b[0] +function partition(points, ids, start, end, lox, loy, hix, hiy) { + var mid = start + for(var i=start; i>> 1 + if(n < 1) { + return [] } - var useGetters = (dtype === "generic") - if(dimension === -1) { - //Special case for trivial arrays - var code = - "function "+className+"(a){this.data=a;};\ -var proto="+className+".prototype;\ -proto.dtype='"+dtype+"';\ -proto.index=function(){return -1};\ -proto.size=0;\ -proto.dimension=-1;\ -proto.shape=proto.stride=proto.order=[];\ -proto.lo=proto.hi=proto.transpose=proto.step=\ -function(){return new "+className+"(this.data);};\ -proto.get=proto.set=function(){};\ -proto.pick=function(){return null};\ -return function construct_"+className+"(a){return new "+className+"(a);}" - var procedure = new Function(code) - return procedure() - } else if(dimension === 0) { - //Special case for 0d arrays - var code = - "function "+className+"(a,d) {\ -this.data = a;\ -this.offset = d\ -};\ -var proto="+className+".prototype;\ -proto.dtype='"+dtype+"';\ -proto.index=function(){return this.offset};\ -proto.dimension=0;\ -proto.size=1;\ -proto.shape=\ -proto.stride=\ -proto.order=[];\ -proto.lo=\ -proto.hi=\ -proto.transpose=\ -proto.step=function "+className+"_copy() {\ -return new "+className+"(this.data,this.offset)\ -};\ -proto.pick=function "+className+"_pick(){\ -return TrivialArray(this.data);\ -};\ -proto.valueOf=proto.get=function "+className+"_get(){\ -return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ -"};\ -proto.set=function "+className+"_set(v){\ -return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ -};\ -return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" - var procedure = new Function("TrivialArray", code) - return procedure(CACHED_CONSTRUCTORS[dtype][0]) + var lox = Infinity, loy = Infinity + var hix = -Infinity, hiy = -Infinity + for(var i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") - } else if(dimension === 3) { - code.push( -"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ -if(s0>s1){\ -if(s1>s2){\ -return [2,1,0];\ -}else if(s0>s2){\ -return [1,2,0];\ -}else{\ -return [1,0,2];\ -}\ -}else if(s0>s2){\ -return [2,0,1];\ -}else if(s2>s1){\ -return [0,1,2];\ -}else{\ -return [0,2,1];\ -}}})") + bounds[0] = lox + bounds[1] = loy + bounds[2] = hix + bounds[3] = hiy + + var levels = pool.mallocInt32(n) + var ptr = 0 + + function snapRec(x, y, diam, start, end, level) { + var diam_2 = diam * 0.5 + var offset = start + 1 + var count = end - start + weights[ptr] = count + levels[ptr++] = level + for(var i=0; i<2; ++i) { + for(var j=0; j<2; ++j) { + var nx = x+i*diam_2 + var ny = y+j*diam_2 + var nextOffset = partition( + points + , ids + , offset + , end + , nx, ny + , nx+diam_2, ny+diam_2) + if(nextOffset === offset) { + continue + } + if(nextOffset - offset >= Math.max(0.9 * count, 32)) { + var mid = (end + start)>>>1 + snapRec(nx, ny, diam_2, offset, mid, level+1) + offset = mid + } + snapRec(nx, ny, diam_2, offset, nextOffset, level+1) + offset = nextOffset } - } else { - code.push("ORDER})") } } + snapRec(lox, loy, diam, 0, n, 0) + sortLevels(levels, points, ids, weights, n) - //view.set(i0, ..., v): - code.push( -"proto.set=function "+className+"_set("+args.join(",")+",v){") - if(useGetters) { - code.push("return this.data.set("+index_str+",v)}") - } else { - code.push("return this.data["+index_str+"]=v}") - } + var lod = [] + var lastLevel = 0 + var prevOffset = n + for(var ptr=n-1; ptr>=0; --ptr) { + points[2*ptr] = (points[2*ptr] - lox) * scaleX + points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY - //view.get(i0, ...): - code.push("proto.get=function "+className+"_get("+args.join(",")+"){") - if(useGetters) { - code.push("return this.data.get("+index_str+")}") - } else { - code.push("return this.data["+index_str+"]}") + var level = levels[ptr] + if(level === lastLevel) { + continue + } + + lod.push(new SnapInterval( + diam * Math.pow(0.5, level), + ptr+1, + prevOffset - (ptr+1) + )) + prevOffset = ptr+1 + + lastLevel = level } - //view.index: - code.push( - "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") + lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) + pool.free(levels) - //view.hi(): - code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ - indices.map(function(i) { - return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") - }).join(",")+","+ - indices.map(function(i) { - return "this.stride["+i + "]" - }).join(",")+",this.offset)}") + return lod +} - //view.lo(): - var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) - var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) - code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) - for(var i=0; i=0){\ -d=i"+i+"|0;\ -b+=c"+i+"*d;\ -a"+i+"-=d}") - } - code.push("return new "+className+"(this.data,"+ - indices.map(function(i) { - return "a"+i - }).join(",")+","+ - indices.map(function(i) { - return "c"+i - }).join(",")+",b)}") +},{"./lib/sort":776,"typedarray-pool":780}],778:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],779:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],780:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":778,"buffer":65,"dup":122}],781:[function(require,module,exports){ +'use strict' - //view.step(): - code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ - indices.map(function(i) { - return "a"+i+"=this.shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "b"+i+"=this.stride["+i+"]" - }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") - for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") - } - code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") +var SHADERS = require('./lib/shader') - //Add return statement - code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ - indices.map(function(i) { - return "shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "stride["+i+"]" - }).join(",")+",offset)}") +module.exports = createScatter2D - //Compile procedure - var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) - return procedure(CACHED_CONSTRUCTORS[dtype], order) +function Scatter2D(plot, offsetBuffer, pickBuffer, weightBuffer, shader, pickShader) { + this.plot = plot + this.offsetBuffer = offsetBuffer + this.pickBuffer = pickBuffer + this.weightBuffer = weightBuffer + this.shader = shader + this.pickShader = pickShader + this.scales = [] + this.size = 12.0 + this.borderSize = 1.0 + this.pointCount = 0 + this.color = [1,0,0,1] + this.borderColor = [0,0,0,1] + this.bounds = [Infinity,Infinity,-Infinity,-Infinity] + this.pickOffset = 0 + this.points = null + this.xCoords = null } -function arrayDType(data) { - if(isBuffer(data)) { - return "buffer" - } - if(hasTypedArrays) { - switch(Object.prototype.toString.call(data)) { - case "[object Float64Array]": - return "float64" - case "[object Float32Array]": - return "float32" - case "[object Int8Array]": - return "int8" - case "[object Int16Array]": - return "int16" - case "[object Int32Array]": - return "int32" - case "[object Uint8Array]": - return "uint8" - case "[object Uint16Array]": - return "uint16" - case "[object Uint32Array]": - return "uint32" - case "[object Uint8ClampedArray]": - return "uint8_clamped" - } - } - if(Array.isArray(data)) { - return "array" - } - return "generic" -} +var proto = Scatter2D.prototype -var CACHED_CONSTRUCTORS = { - "float32":[], - "float64":[], - "int8":[], - "int16":[], - "int32":[], - "uint8":[], - "uint16":[], - "uint32":[], - "array":[], - "uint8_clamped":[], - "buffer":[], - "generic":[] +proto.dispose = function() { + this.shader.dispose() + this.pickShader.dispose() + this.offsetBuffer.dispose() + this.pickBuffer.dispose() + if(this.xCoords) { + pool.free(this.xCoords) + } + this.plot.removeObject(this) } -;(function() { - for(var id in CACHED_CONSTRUCTORS) { - CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) - } -}); +proto.update = function(options) { + options = options || {} -function wrappedNDArrayCtor(data, shape, stride, offset) { - if(data === undefined) { - var ctor = CACHED_CONSTRUCTORS.array[0] - return ctor([]) - } else if(typeof data === "number") { - data = [data] - } - if(shape === undefined) { - shape = [ data.length ] - } - var d = shape.length - if(stride === undefined) { - stride = new Array(d) - for(var i=d-1, sz=1; i>=0; --i) { - stride[i] = sz - sz *= shape[i] + function dflt(opt, value) { + if(opt in options) { + return options[opt] } + return value } - if(offset === undefined) { - offset = 0 - for(var i=0; i>>1) + packed.set(data) + var packedW = pool.mallocFloat32(data.length) + this.points = data + this.scales = snapPoints(packed, packedId, packedW, this.bounds) + this.offsetBuffer.update(packed) + this.pickBuffer.update(packedId) + this.weightBuffer.update(packedW) + var xCoords = pool.mallocFloat32(data.length>>>1) + for(var i=0,j=0; i>> 1 + this.pickOffset = 0 } -module.exports = wrappedNDArrayCtor +proto.drawPick = (function() { + var MATRIX = [1,0,0, + 0,1,0, + 0,0,1] + var PICK_VEC4 = [0,0,0,0] +return function(pickOffset) { + var plot = this.plot + var shader = this.pickShader + var scales = this.scales + var offsetBuffer = this.offsetBuffer + var pickBuffer = this.pickBuffer + var bounds = this.bounds + var size = this.size + var borderSize = this.borderSize + var gl = plot.gl + var pixelRatio = plot.pickPixelRatio + var viewBox = plot.viewBox + var dataBox = plot.dataBox -},{"iota-array":239,"is-buffer":240}],254:[function(require,module,exports){ -/*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + if(this.pointCount === 0) { + return pickOffset + } -'use strict'; + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = (viewBox[2] - viewBox[0]) * pixelRatio / plot.pixelRatio + var screenY = (viewBox[3] - viewBox[1]) * pixelRatio / plot.pixelRatio -/** - * Results cache - */ + var pixelSize = Math.min(dataX / screenX, dataY / screenY) + var targetScale = pixelSize -var res = ''; -var cache; -/** - * Expose `repeat` - */ + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 -module.exports = repeat; + this.pickOffset = pickOffset + PICK_VEC4[0] = ( pickOffset & 0xff) + PICK_VEC4[1] = ((pickOffset>>8) & 0xff) + PICK_VEC4[2] = ((pickOffset>>16) & 0xff) + PICK_VEC4[3] = ((pickOffset>>24) & 0xff) -/** - * Repeat the given `string` the specified `number` - * of times. - * - * **Example:** - * - * ```js - * var repeat = require('repeat-string'); - * repeat('A', 5); - * //=> AAAAA - * ``` - * - * @param {String} `string` The string to repeat - * @param {Number} `number` The number of times to repeat the string - * @return {String} Repeated string - * @api public - */ + shader.bind() + shader.uniforms.matrix = MATRIX + shader.uniforms.color = this.color + shader.uniforms.borderColor = this.borderColor + shader.uniforms.pointSize = pixelRatio * (size + borderSize) + shader.uniforms.pickOffset = PICK_VEC4 -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('repeat-string expects a string.'); + if(this.borderSize === 0) { + shader.uniforms.centerFraction = 2.0; + } else { + shader.uniforms.centerFraction = size / (size + borderSize + 1.25) } - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; + offsetBuffer.bind() + shader.attributes.position.pointer() + pickBuffer.bind() + shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE) - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } + var xCoords = this.xCoords + var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX + var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX - while (max > res.length && num > 0) { - if (num & 1) { - res += str; + for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { + var lod = scales[scaleNum] + if(lod.pixelSize < pixelSize && scaleNum > 1) { + continue } - num >>= 1; - if (!num) break; - str += str; + var intervalStart = lod.offset + var intervalEnd = lod.count + intervalStart + + var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) + var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + + if(endOffset > startOffset) { + gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + } } - return res.substr(0, max); + return pickOffset + this.pointCount } +})() +proto.draw = (function() { + var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] -},{}],255:[function(require,module,exports){ -(function (global){ -module.exports = - global.performance && - global.performance.now ? function now() { - return performance.now() - } : Date.now || function now() { - return +new Date - } + return function() { + var plot = this.plot + var shader = this.shader + var scales = this.scales + var offsetBuffer = this.offsetBuffer + var bounds = this.bounds + var size = this.size + var borderSize = this.borderSize + var gl = plot.gl + var pixelRatio = plot.pixelRatio + var viewBox = plot.viewBox + var dataBox = plot.dataBox -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],256:[function(require,module,exports){ -"use strict" + if(this.pointCount === 0) { + return + } -var determinant = require("robust-determinant") + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] -var NUM_EXPAND = 6 + var pixelSize = Math.min(dataX / screenX, dataY / screenY) + var targetScale = pixelSize -function generateSolver(n) { - var funcName = "robustLinearSolve" + n + "d" - var code = ["function ", funcName, "(A,b){return ["] - for(var i=0; i 0) { - code.push(",") + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + shader.bind() + shader.uniforms.matrix = MATRIX + shader.uniforms.color = this.color + shader.uniforms.borderColor = this.borderColor + shader.uniforms.pointSize = pixelRatio * (size + borderSize) + shader.uniforms.useWeight = 1 + + if(this.borderSize === 0) { + shader.uniforms.centerFraction = 2.0; + } else { + shader.uniforms.centerFraction = size / (size + borderSize + 1.25) + } + + offsetBuffer.bind() + shader.attributes.position.pointer() + + this.weightBuffer.bind() + shader.attributes.weight.pointer() + + var xCoords = this.xCoords + var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX + var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX + + var firstLevel = true + + for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { + var lod = scales[scaleNum] + if(lod.pixelSize < pixelSize && scaleNum > 1) { + continue } - code.push("[") - for(var k=0; k 0) { - code.push(",") - } - if(k === i) { - code.push("+b[", j, "]") - } else { - code.push("+A[", j, "][", k, "]") - } + + var intervalStart = lod.offset + var intervalEnd = lod.count + intervalStart + + var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) + var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + + if(endOffset > startOffset) { + gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + } + + if(firstLevel) { + firstLevel = false + shader.uniforms.useWeight = 0 } - code.push("]") } - code.push("]),") } - code.push("det(A)]}return ", funcName) - var proc = new Function("det", code.join("")) - if(n < 6) { - return proc(determinant[n]) +})() + +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.pointCount + if(value < pickOffset || value >= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var points = this.points + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] } - return proc(determinant) } -function robustLinearSolve0d() { - return [ 0 ] -} +function createScatter2D(plot, options) { + var gl = plot.gl + var buffer = createBuffer(gl) + var pickBuffer = createBuffer(gl) + var weightBuffer = createBuffer(gl) + var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment) + var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) -function robustLinearSolve1d(A, b) { - return [ [ b[0] ], [ A[0][0] ] ] -} + var result = new Scatter2D( + plot, buffer, pickBuffer, weightBuffer, shader, pickShader) + result.update(options) -var CACHE = [ - robustLinearSolve0d, - robustLinearSolve1d -] + //Register with plot + plot.addObject(result) -function generateDispatch() { - while(CACHE.length < NUM_EXPAND) { - CACHE.push(generateSolver(CACHE.length)) - } - var procArgs = [] - var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] - for(var i=0; i=0; --i) { - var a = Q - var b = e[i] - Q = a + b - var bv = Q - a - var q = b - bv - if(q) { - e[--bottom] = Q - Q = q - } +module.exports = getGlyph + +var GLYPH_CACHE = {} + +function getGlyph(symbol, font) { + var fontCache = GLYPH_CACHE[font] + if(!fontCache) { + fontCache = GLYPH_CACHE[font] = {} } - var top = 0 - for(var i=bottom; i>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } -} +var perspectiveVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n \n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}" +var orthographicVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n \n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}" +var projectionVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * view * model * vec4(position, 1);\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n" +var drawFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n" +var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}" -function determinant(m) { - if(m.length === 2) { - return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") - } else { - var expr = [] - for(var i=0; i>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } +function ScatterPlotPickResult(index, position) { + this.index = index + this.dataCoordinate = this.position = position } -function determinant(m) { - if(m.length === 2) { - return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] - } else { - var expr = [] - for(var i=0; i 0) { - if(r <= 0) { - return det - } else { - s = l + r - } - } else if(l < 0) { - if(r >= 0) { - return det - } else { - s = -(l + r) - } - } else { - return det - } - var tol = ERRBOUND3 * s - if(det >= tol || det <= -tol) { - return det - } - return orientation3Exact(a, b, c) - }, - function orientation4(a,b,c,d) { - var adx = a[0] - d[0] - var bdx = b[0] - d[0] - var cdx = c[0] - d[0] - var ady = a[1] - d[1] - var bdy = b[1] - d[1] - var cdy = c[1] - d[1] - var adz = a[2] - d[2] - var bdz = b[2] - d[2] - var cdz = c[2] - d[2] - var bdxcdy = bdx * cdy - var cdxbdy = cdx * bdy - var cdxady = cdx * ady - var adxcdy = adx * cdy - var adxbdy = adx * bdy - var bdxady = bdx * ady - var det = adz * (bdxcdy - cdxbdy) - + bdz * (cdxady - adxcdy) - + cdz * (adxbdy - bdxady) - var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) - + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) - + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) - var tol = ERRBOUND4 * permanent - if ((det > tol) || (-det > tol)) { - return det - } - return orientation4Exact(a,b,c,d) - } -] + this.shader = shader + this.orthoShader = orthoShader + this.projectShader = projectShader -function slowOrient(args) { - var proc = CACHED[args.length] - if(!proc) { - proc = CACHED[args.length] = orientation(args.length) - } - return proc.apply(undefined, args) -} + this.pointBuffer = pointBuffer + this.colorBuffer = colorBuffer + this.glyphBuffer = glyphBuffer + this.idBuffer = idBuffer + this.vao = vao + this.vertexCount = 0 + this.lineVertexCount = 0 -function generateOrientationProc() { - while(CACHED.length <= NUM_EXPAND) { - CACHED.push(orientation(CACHED.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=NUM_EXPAND; ++i) { - args.push("a" + i) - procArgs.push("o" + i) - } - var code = [ - "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=NUM_EXPAND; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") - } - code.push("}var s=new Array(arguments.length);for(var i=0;i= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } +proto.isTransparent = function() { + if(this.opacity < 1) { + return true } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + for(var i=0; i<3; ++i) { + if(this.axesProject[i] && this.projectOpacity[i] < 1) { + return true } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - } + return false +} + +proto.isOpaque = function() { + if(this.opacity >= 1) { + return true } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] + for(var i=0; i<3; ++i) { + if(this.axesProject[i] && this.projectOpacity[i] >= 1) { + return true } } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g + return false } -},{}],262:[function(require,module,exports){ -"use strict" -module.exports = linearExpansionSum +var VIEW_SHAPE = [0,0] +var U_VEC = [0,0,0] +var V_VEC = [0,0,0] +var MU_VEC = [0,0,0,1] +var MV_VEC = [0,0,0,1] +var SCRATCH_MATRIX = IDENTITY.slice() +var SCRATCH_VEC = [0,0,0] +var CLIP_BOUNDS = [[0,0,0], [0,0,0]] -//Easy case: Add two scalars -function scalarScalar(a, b) { - var x = a + b - var bv = x - a - var av = x - bv - var br = b - bv - var ar = a - av - var y = ar + br - if(y) { - return [y, x] - } - return [x] +function zeroVec(a) { + a[0] = a[1] = a[2] = 0 + return a } -function linearExpansionSum(e, f) { - var ne = e.length|0 - var nf = f.length|0 - if(ne === 1 && nf === 1) { - return scalarScalar(e[0], f[0]) - } - var n = ne + nf - var g = new Array(n) - var count = 0 - var eptr = 0 - var fptr = 0 - var abs = Math.abs - var ei = e[eptr] - var ea = abs(ei) - var fi = f[fptr] - var fa = abs(fi) - var a, b - if(ea < fa) { - b = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - b = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) +function augment(hg, af) { + hg[0] = af[0] + hg[1] = af[1] + hg[2] = af[2] + hg[3] = 1 + return hg +} + +function setComponent(out, v, i, x) { + out[0] = v[0] + out[1] = v[1] + out[2] = v[2] + out[i] = x + return out +} + +function getClipBounds(bounds) { + var result = CLIP_BOUNDS + for(var i=0; i<2; ++i) { + for(var j=0; j<3; ++j) { + result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8) } } - if((eptr < ne && ea < fa) || (fptr >= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } + return result +} + +function drawProject(shader, points, camera, transparent, forceDraw) { + var axesProject = points.axesProject + + var gl = points.gl + var uniforms = shader.uniforms + var model = camera.model || IDENTITY + var view = camera.view || IDENTITY + var projection = camera.projection || IDENTITY + var bounds = points.axesBounds + var clipBounds = getClipBounds(points.clipBounds) + + var cubeAxis + if(points.axes) { + cubeAxis = points.axes.lastCubeProps.axis } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } + cubeAxis = [1,1,1] } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } + + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + + shader.bind() + uniforms.view = view + uniforms.projection = projection + uniforms.screenSize = VIEW_SHAPE + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + uniforms.clipBounds = clipBounds + uniforms.pickGroup = points.pickId / 255.0 + uniforms.pixelRatio = points.pixelRatio + + for(var i=0; i<3; ++i) { + if(!axesProject[i]) { + continue } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + if((points.projectOpacity[i] < 1) !== transparent) { + continue } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + + uniforms.scale = points.projectScale[i] + uniforms.opacity = points.projectOpacity[i] + + //Project model matrix + var pmodel = SCRATCH_MATRIX + for(var j=0; j<16; ++j) { + pmodel[j] = 0 } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] + for(var j=0; j<4; ++j) { + pmodel[5*j] = 1 } - } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = f[fptr] + pmodel[5*i] = 0 + if(cubeAxis[i] < 0) { + pmodel[12+i] = bounds[0][i] + } else { + pmodel[12+i] = bounds[1][i] } - } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g -} -},{}],263:[function(require,module,exports){ -'use strict' + mat4mult(pmodel, model, pmodel) + uniforms.model = pmodel -module.exports = toSuperScript + //Compute initial axes + var u = (i+1)%3 + var v = (i+2)%3 + var du = zeroVec(U_VEC) + var dv = zeroVec(V_VEC) + du[u] = 1 + dv[v] = 1 -var SUPERSCRIPTS = { - ' ': ' ', - '0': '⁰', - '1': '¹', - '2': '²', - '3': '³', - '4': '⁴', - '5': '⁵', - '6': '⁶', - '7': '⁷', - '8': '⁸', - '9': '⁹', - '+': '⁺', - '-': '⁻', - 'a': 'ᵃ', - 'b': 'ᵇ', - 'c': 'ᶜ', - 'd': 'ᵈ', - 'e': 'ᵉ', - 'f': 'ᶠ', - 'g': 'ᵍ', - 'h': 'ʰ', - 'i': 'ⁱ', - 'j': 'ʲ', - 'k': 'ᵏ', - 'l': 'ˡ', - 'm': 'ᵐ', - 'n': 'ⁿ', - 'o': 'ᵒ', - 'p': 'ᵖ', - 'r': 'ʳ', - 's': 'ˢ', - 't': 'ᵗ', - 'u': 'ᵘ', - 'v': 'ᵛ', - 'w': 'ʷ', - 'x': 'ˣ', - 'y': 'ʸ', - 'z': 'ᶻ' -} + //Align orientation relative to viewer + var mdu = project(projection, view, model, augment(MU_VEC, du)) + var mdv = project(projection, view, model, augment(MV_VEC, dv)) + if(Math.abs(mdu[1]) > Math.abs(mdv[1])) { + var tmp = mdu + mdu = mdv + mdv = tmp + tmp = du + du = dv + dv = tmp + var t = u + u = v + v = t + } + if(mdu[0] < 0) { + du[u] = -1 + } + if(mdv[1] > 0) { + dv[v] = -1 + } + var su = 0.0 + var sv = 0.0 + for(var j=0; j<4; ++j) { + su += Math.pow(model[4*u+j], 2) + sv += Math.pow(model[4*v+j], 2) + } + du[u] /= Math.sqrt(su) + dv[v] /= Math.sqrt(sv) + uniforms.axes[0] = du + uniforms.axes[1] = dv -function toSuperScript(x) { - return x.split('').map(function(c) { - if(c in SUPERSCRIPTS) { - return SUPERSCRIPTS[c] + //Update fragment clip bounds + uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8) + uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8) + + //Draw interior + points.vao.draw(gl.TRIANGLES, points.vertexCount) + + //Draw edges + if(points.lineWidth > 0) { + gl.lineWidth(points.lineWidth) + points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) } - return '' - }).join('') + } } -},{}],264:[function(require,module,exports){ -"use strict" -var pool = require("typedarray-pool") +var NEG_INFINITY3 = [-1e8, -1e8, -1e8] +var POS_INFINITY3 = [1e8, 1e8, 1e8] +var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] -module.exports = createSurfaceExtractor +function drawFull(shader, pshader, points, camera, transparent, forceDraw) { + var gl = points.gl -//Helper macros -function array(i) { - return "a" + i -} -function data(i) { - return "d" + i -} -function cube(i,bitmask) { - return "c" + i + "_" + bitmask -} -function shape(i) { - return "s" + i -} -function stride(i,j) { - return "t" + i + "_" + j -} -function offset(i) { - return "o" + i -} -function scalar(i) { - return "x" + i -} -function pointer(i) { - return "p" + i -} -function delta(i,bitmask) { - return "d" + i + "_" + bitmask -} -function index(i) { - return "i" + i -} -function step(i,j) { - return "u" + i + "_" + j -} -function pcube(bitmask) { - return "b" + bitmask + points.vao.bind() + + if(transparent === (points.opacity < 1) || forceDraw) { + shader.bind() + var uniforms = shader.uniforms + + uniforms.model = camera.model || IDENTITY + uniforms.view = camera.view || IDENTITY + uniforms.projection = camera.projection || IDENTITY + + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + uniforms.screenSize = VIEW_SHAPE + + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + + uniforms.fragClipBounds = CLIP_GROUP + uniforms.clipBounds = points.axes.bounds + + uniforms.opacity = points.opacity + uniforms.pickGroup = points.pickId / 255.0 + + uniforms.pixelRatio = points.pixelRatio + + //Draw interior + points.vao.draw(gl.TRIANGLES, points.vertexCount) + + //Draw edges + if(points.lineWidth > 0) { + gl.lineWidth(points.lineWidth) + points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) + } + } + + drawProject(pshader, points, camera, transparent, forceDraw) + + points.vao.unbind() } -function qcube(bitmask) { - return "y" + bitmask + +proto.draw = function(camera) { + var shader = this.useOrtho ? this.orthoShader : this.shader + drawFull(shader, this.projectShader, this, camera, false, false) } -function pdelta(bitmask) { - return "e" + bitmask + +proto.drawTransparent = function(camera) { + var shader = this.useOrtho ? this.orthoShader : this.shader + drawFull(shader, this.projectShader, this, camera, true, false) } -function vert(i) { - return "v" + i + +proto.drawPick = function(camera) { + var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader + drawFull(shader, this.pickProjectShader, this, camera, false, true) } -var VERTEX_IDS = "V" -var PHASES = "P" -var VERTEX_COUNT = "N" -var POOL_SIZE = "Q" -var POINTER = "X" -var TEMPORARY = "T" -function permBitmask(dimension, mask, order) { - var r = 0 - for(var i=0; i= this.pointCount || x < 0) { + return null } - return r -} -//Generates the surface procedure -function compileSurfaceProcedure(vertexFunc, faceFunc, phaseFunc, scalarArgs, order, typesig) { - var arrayArgs = typesig.length - var dimension = order.length + //Unpack result + var coord = this.points[x] + var result = this._selectResult + result.index = x + for(var i=0; i<3; ++i) { + result.position[i] = result.dataCoordinate[i] = coord[i] + } + return result +} - if(dimension < 2) { - throw new Error("ndarray-extract-contour: Dimension must be at least 2") +proto.highlight = function(selection) { + if(!selection) { + this.highlightId = [1,1,1,1] + } else { + var pointId = selection.index + var a0 = pointId &0xff + var a1 = (pointId>>8) &0xff + var a2 = (pointId>>16)&0xff + this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0] } +} - var funcName = "extractContour" + order.join("_") - var code = [] - var vars = [] - var args = [] +proto.update = function(options) { - //Assemble arguments - for(var i=0; i 0) { - stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) - } - vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + if('projectOpacity' in options) { + if(Array.isArray(options.projectOpacity)) { + this.projectOpacity = options.projectOpacity.slice() + } else { + var s = +options.projectOpacity + this.projectOpacity = [s,s,s] } } - //Create index variables - for(var i=0; i=0; --i) { - sizeVariable.push(shape(order[i])) + + //Set dirty flag + this.dirty = true + + //Create new buffers + var points = options.position + if(!points) { + return } - //Previous phases and vertex_ids - vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", - PHASES + "=mallocUint32(" + POOL_SIZE + ")", - VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", - POINTER + "=0") - //Create cube variables for phases - vars.push(pcube(0) + "=0") - for(var j=1; j<(1<=0; --i) { - forLoopBegin(i, 0) + var glyphData + if(Array.isArray(glyphs)) { + glyphData = getGlyph(glyphs[i], font) + } else if(glyphs) { + glyphData = getGlyph(glyphs, font) + } else { + glyphData = getGlyph('●', font) } - var phaseFuncArgs = [] - for(var i=0; i 0) { + textOffset[0] = -alignment[0] * (1+glyphBounds[0][0]) } - //Generate vertex - code.push("vertex(", vertexArgs.join(), ");", - vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;") + //Write out inner marker + var cells = glyphMesh.cells + var verts = glyphMesh.positions - //Check for face crossings - var base = (1<0; k=(k-1)&subset) { - faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") + for(var j=0; j0){", - index(order[i]), "=1;") - createLoop(i-1, mask|(1< 0") - } - if(typeof args.vertex !== "function") { - error("Must specify vertex creation function") - } - if(typeof args.cell !== "function") { - error("Must specify cell creation function") - } - if(typeof args.phase !== "function") { - error("Must specify phase function") - } - var getters = args.getters || [] - var typesig = new Array(arrays) - for(var i=0; i= 0) { - typesig[i] = true - } else { - typesig[i] = false - } - } - return compileSurfaceProcedure( - args.vertex, - args.cell, - args.phase, - scalars, - order, - typesig) +proto.dispose = function() { + //Shaders + this.shader.dispose() + this.orthoShader.dispose() + this.pickPerspectiveShader.dispose() + this.pickOrthoShader.dispose() + + //Vertex array + this.vao.dispose() + + //Buffers + this.pointBuffer.dispose() + this.colorBuffer.dispose() + this.glyphBuffer.dispose() + this.idBuffer.dispose() } -},{"typedarray-pool":278}],265:[function(require,module,exports){ -// transliterated from the python snippet here: -// http://en.wikipedia.org/wiki/Lanczos_approximation -var g = 7; -var p = [ - 0.99999999999980993, - 676.5203681218851, - -1259.1392167224028, - 771.32342877765313, - -176.61502916214059, - 12.507343278686905, - -0.13857109526572012, - 9.9843695780195716e-6, - 1.5056327351493116e-7 -]; +function createPointCloud(options) { + var gl = options.gl -var g_ln = 607/128; -var p_ln = [ - 0.99999999999999709182, - 57.156235665862923517, - -59.597960355475491248, - 14.136097974741747174, - -0.49191381609762019978, - 0.33994649984811888699e-4, - 0.46523628927048575665e-4, - -0.98374475304879564677e-4, - 0.15808870322491248884e-3, - -0.21026444172410488319e-3, - 0.21743961811521264320e-3, - -0.16431810653676389022e-3, - 0.84418223983852743293e-4, - -0.26190838401581408670e-4, - 0.36899182659531622704e-5 -]; + var shader = shaders.createPerspective(gl) + var orthoShader = shaders.createOrtho(gl) + var projectShader = shaders.createProject(gl) + var pickPerspectiveShader = shaders.createPickPerspective(gl) + var pickOrthoShader = shaders.createPickOrtho(gl) + var pickProjectShader = shaders.createPickProject(gl) -// Spouge approximation (suitable for large arguments) -function lngamma(z) { + var pointBuffer = createBuffer(gl) + var colorBuffer = createBuffer(gl) + var glyphBuffer = createBuffer(gl) + var idBuffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + buffer: pointBuffer, + size: 3, + type: gl.FLOAT + }, + { + buffer: colorBuffer, + size: 4, + type: gl.FLOAT + }, + { + buffer: glyphBuffer, + size: 2, + type: gl.FLOAT + }, + { + buffer: idBuffer, + size: 4, + type: gl.UNSIGNED_BYTE, + normalized: true + } + ]) - if(z < 0) return Number('0/0'); - var x = p_ln[0]; - for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); - var t = z + g_ln + 0.5; - return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); + var pointCloud = new PointCloud( + gl, + shader, + orthoShader, + projectShader, + pointBuffer, + colorBuffer, + glyphBuffer, + idBuffer, + vao, + pickPerspectiveShader, + pickOrthoShader, + pickProjectShader) + + pointCloud.update(options) + + return pointCloud } -module.exports = function gamma (z) { - if (z < 0.5) { - return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); - } - else if(z > 100) return Math.exp(lngamma(z)); - else { - z -= 1; - var x = p[0]; - for (var i = 1; i < g + 2; i++) { - x += p[i] / (z + i); - } - var t = z + g + 0.5; +},{"./lib/glyphs":782,"./lib/shaders":783,"gl-buffer":784,"gl-mat4/multiply":242,"gl-vao":814,"typedarray-pool":817}],906:[function(require,module,exports){ +'use strict' - return Math.sqrt(2 * Math.PI) - * Math.pow(t, z + 0.5) - * Math.exp(-t) - * x - ; - } -}; -module.exports.log = lngamma; -},{}],266:[function(require,module,exports){ -"use strict" +exports.boxVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n" +exports.boxFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n" -module.exports = permutationSign +},{}],907:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":910}],908:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],909:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],910:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":908,"buffer":65,"dup":122}],911:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":912,"./lib/create-attributes":913,"./lib/create-uniforms":914,"./lib/reflect":915,"./lib/runtime-reflect":916,"./lib/shader-cache":917,"dup":94}],912:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],913:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":912,"dup":96}],914:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":912,"./reflect":915,"dup":97}],915:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],916:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],917:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":912,"dup":100,"gl-format-compiler-error":918,"weakmap-shim":936}],918:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":919,"dup":101,"gl-constants/lookup":923,"glsl-shader-name":924,"sprintf-js":933}],919:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":920}],920:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":921}],921:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],922:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],923:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":922,"dup":106}],924:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":925,"dup":107,"glsl-tokenizer":932}],925:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],926:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":928,"./lib/builtins-300es":927,"./lib/literals":930,"./lib/literals-300es":929,"./lib/operators":931,"dup":109}],927:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":928,"dup":110}],928:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],929:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":930,"dup":112}],930:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],931:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],932:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":926,"dup":115}],933:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],934:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":935,"dup":117}],935:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],936:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":934,"dup":119}],937:[function(require,module,exports){ +'use strict' -var BRUTE_FORCE_CUTOFF = 32 +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') -var pool = require("typedarray-pool") +var SHADERS = require('./lib/shaders') -function permutationSign(p) { - var n = p.length - if(n < BRUTE_FORCE_CUTOFF) { - //Use quadratic algorithm for small n - var sgn = 1 - for(var i=0; i0; --i) { - t = pinv[i] - s = p[i] - p[i] = p[t] - p[t] = s - pinv[i] = pinv[s] - pinv[s] = t - r = (r + s) * i +proto.draw = function() { + if(!this.enabled) { + return } - pool.freeUint32(pinv) - pool.freeUint32(p) - return r -} -function unrank(n, r, p) { - switch(n) { - case 0: - if(p) { return p } - return [] - case 1: - if(p) { - p[0] = 0 - return p - } else { - return [0] - } - case 2: - if(p) { - if(r) { - p[0] = 0 - p[1] = 1 - } else { - p[0] = 1 - p[1] = 0 - } - return p - } else { - return r ? [0,1] : [1,0] - } - default: - break + var plot = this.plot + var selectBox = this.selectBox + var lineWidth = this.borderWidth + + var innerFill = this.innerFill + var innerColor = this.innerColor + var outerFill = this.outerFill + var outerColor = this.outerColor + var borderColor = this.borderColor + + var boxes = plot.box + var screenBox = plot.screenBox + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + + //Map select box into pixel coordinates + var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] + var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] + var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] + var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] + + loX = Math.max(loX, viewBox[0]) + loY = Math.max(loY, viewBox[1]) + hiX = Math.min(hiX, viewBox[2]) + hiY = Math.min(hiY, viewBox[3]) + + if(hiX < loX || hiY < loY) { + return } - p = p || new Array(n) - var s, t, i, nf=1 - p[0] = 0 - for(i=1; i0; --i) { - s = (r / nf)|0 - r = (r - s * nf)|0 - nf = (nf / i)|0 - t = p[i]|0 - p[i] = p[s]|0 - p[s] = t|0 + + if(this.innerFill) { + boxes.drawBox(loX, loY, hiX, hiY, innerColor) + } + + //Draw border + if(lineWidth > 0) { + + //Draw border + var w = lineWidth * pixelRatio + boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) + boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) + boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) + boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) } - return p } -exports.rank = rank -exports.unrank = unrank +proto.update = function(options) { + options = options || {} -},{"invert-permutation":268,"typedarray-pool":278}],268:[function(require,module,exports){ -"use strict" + this.innerFill = !!options.innerFill + this.outerFill = !!options.outerFill + this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() + this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() + this.borderColor = (options.borderColor || [0,0,0,1]).slice() + this.borderWidth = options.borderWidth || 0 + this.selectBox = (options.selectBox || this.selectBox).slice() +} -function invertPermutation(pi, result) { - result = result || new Array(pi.length) - for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", - "args": [{ - "name": "_inline_1_arg0_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg1_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg2_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg3_", - "lvalue": false, - "rvalue": true, - "count": 2 - }, { - "name": "_inline_1_arg4_", - "lvalue": false, - "rvalue": true, - "count": 1 - }], - "thisVars": [], - "localVars": ["_inline_1_da", "_inline_1_db"] - }, - funcName: 'zeroCrossings' -}) -},{"cwise-compiler":109}],271:[function(require,module,exports){ -"use strict" +proto.dispose = function() { + this.plot.removeOverlay(this) +} -module.exports = findZeroCrossings +function createSpikes2D(plot, options) { + var spikes = new GLSpikes2D(plot) + spikes.update(options) + plot.addOverlay(spikes) + return spikes +} -var core = require("./lib/zc-core") +},{}],939:[function(require,module,exports){ +var createShader = require('gl-shader') -function findZeroCrossings(array, level) { - var cross = [] - level = +level || 0.0 - core(array.hi(array.shape[0]-1), cross, level) - return cross + +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n" +var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n" +var pickSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n" + +exports.createShader = function (gl) { + var shader = createShader(gl, vertSrc, fragSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + shader.attributes.normal.location = 2 + return shader +} +exports.createPickShader = function (gl) { + var shader = createShader(gl, vertSrc, pickSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + shader.attributes.normal.location = 2 + return shader +} +exports.createContourShader = function (gl) { + var shader = createShader(gl, contourVertSrc, fragSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'float'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + return shader +} +exports.createPickContourShader = function (gl) { + var shader = createShader(gl, contourVertSrc, pickSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'float'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + return shader } -},{"./lib/zc-core":270}],272:[function(require,module,exports){ -"use strict" -module.exports = surfaceNets +},{"gl-shader":947}],940:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],941:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],942:[function(require,module,exports){ +arguments[4][262][0].apply(exports,arguments) +},{"dup":262}],943:[function(require,module,exports){ +arguments[4][263][0].apply(exports,arguments) +},{"./colorScales":942,"arraytools":64,"clone":944,"dup":263}],944:[function(require,module,exports){ +arguments[4][264][0].apply(exports,arguments) +},{"buffer":65,"dup":264}],945:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],946:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":1002}],947:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":948,"./lib/create-attributes":949,"./lib/create-uniforms":950,"./lib/reflect":951,"./lib/runtime-reflect":952,"./lib/shader-cache":953,"dup":94}],948:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],949:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":948,"dup":96}],950:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":948,"./reflect":951,"dup":97}],951:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],952:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],953:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":948,"dup":100,"gl-format-compiler-error":954,"weakmap-shim":972}],954:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":955,"dup":101,"gl-constants/lookup":959,"glsl-shader-name":960,"sprintf-js":969}],955:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":956}],956:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":957}],957:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],958:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],959:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":958,"dup":106}],960:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":961,"dup":107,"glsl-tokenizer":968}],961:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],962:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":964,"./lib/builtins-300es":963,"./lib/literals":966,"./lib/literals-300es":965,"./lib/operators":967,"dup":109}],963:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":964,"dup":110}],964:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],965:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":966,"dup":112}],966:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],967:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],968:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":962,"dup":115}],969:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],970:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":971,"dup":117}],971:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],972:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":970,"dup":119}],973:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":1002}],974:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],975:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":974,"dup":155}],976:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":974,"dup":156}],977:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":975,"./lib/vao-native.js":976,"dup":157}],978:[function(require,module,exports){ +'use strict' -var generateContourExtractor = require("ndarray-extract-contour") -var triangulateCube = require("triangulate-hypercube") -var zeroCrossings = require("zero-crossings") +module.exports = gradient -function buildSurfaceNets(order, dtype) { - var dimension = order.length - var code = ["'use strict';"] - var funcName = "surfaceNets" + order.join("_") + "d" + dtype +var dup = require('dup') +var cwiseCompiler = require('cwise-compiler') - //Contour extraction function - code.push( - "var contour=genContour({", - "order:[", order.join(), "],", - "scalarArguments: 3,", - "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },") - if(dtype === "generic") { - code.push("getters:[0],") - } +var TEMPLATE_CACHE = {} +var GRADIENT_CACHE = {} - //Generate vertex function - var cubeArgs = [] - var extraArgs = [] - for(var i=0; i>>7){") + var args = [ 'array' ] + var names = ['junk'] + for(var i=0; i 128) { - if((i%128)===0) { - if(extraFuncs.length > 0) { - currentFunc.push("}}") + return TEMPLATE_CACHE[d] = cwiseCompiler({ + args: args, + pre: EmptyProc, + post: EmptyProc, + body: { + body: code.join(''), + args: names.map(function(n) { + return { + name: n, + lvalue: n.indexOf('out') === 0, + rvalue: n.indexOf('inp') === 0, + count: (n!=='junk')|0 } - var efName = "vExtra" + extraFuncs.length - code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") - currentFunc = [ - "function ", efName, "(m,", extraArgs.join(), "){switch(m){" - ] - extraFuncs.push(currentFunc) - } + }), + thisVars: [], + localVars: [] + }, + funcName: 'fdTemplate' + d + }) +} + +function generateGradient(boundaryConditions) { + var token = boundaryConditions.join() + var proc = GRADIENT_CACHE[token] + if(proc) { + return proc + } + + var d = boundaryConditions.length + var code = ['function gradient(dst,src){var s=src.shape.slice();' ] + + function handleBoundary(facet) { + var cod = d - facet.length + + var loStr = [] + var hiStr = [] + var pickStr = [] + for(var i=0; i= 0) { + pickStr.push('0') + } else if(facet.indexOf(-(i+1)) >= 0) { + pickStr.push('s['+i+']-1') + } else { + pickStr.push('-1') + loStr.push('1') + hiStr.push('s['+i+']-2') + } } - currentFunc.push("case ", (i&0x7f), ":") - var crossings = new Array(dimension) - var denoms = new Array(dimension) - var crossingCount = new Array(dimension) - var bias = new Array(dimension) - var totalCrossings = 0 - for(var j=0; j j) { + + if(cod > 0) { + code.push('if(1') + for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { continue } - if(!(i&(1<2') + } + code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) + for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { + continue + } + code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr) + } + code.push(');') + } + + for(var i=0; i1){dst.set(', + pickStr.join(), ',', bnd, ',0.5*(src.get(', + cPickStr.join(), ')-src.get(', + dPickStr.join(), ')))}else{dst.set(', + pickStr.join(), ',', bnd, ',0)};') } else { - denoms[k].push("v" + j + "-v" + u) - sign = -sign + code.push('if(s[', bnd, ']>1){diff(', outStr, + ',src.pick(', cPickStr.join(), ')', boundStr, + ',src.pick(', dPickStr.join(), ')', boundStr, + ');}else{zero(', outStr, ');};') } - if(sign < 0) { - crossings[k].push("-v" + j + "-v" + u) - crossingCount[k] += 2 + break + + case 'mirror': + if(cod === 0) { + code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') } else { - crossings[k].push("v" + j + "+v" + u) - crossingCount[k] -= 2 + code.push('zero(', outStr, ');') } - totalCrossings += 1 - for(var l=0; l2){dst.set(', + pickStr.join(), ',', bnd, ',0.5*(src.get(', + aPickStr.join(), ')-src.get(', + bPickStr.join(), ')))}else{dst.set(', + pickStr.join(), ',', bnd, ',0)};') + } else { + code.push('if(s[', bnd, ']>2){diff(', outStr, + ',src.pick(', aPickStr.join(), ')', boundStr, + ',src.pick(', bPickStr.join(), ')', boundStr, + ');}else{zero(', outStr, ');};') + } + break + + default: + throw new Error('ndarray-gradient: Invalid boundary condition') } } - var vertexStr = [] - for(var k=0; k 0) { - cStr = "+" + crossingCount[k] + "*c" - } - var weight = 0.5 * (crossings[k].length / totalCrossings) - var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) - vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") - - } + + if(cod > 0) { + code.push('};') } - currentFunc.push("a.push([", vertexStr.join(), "]);", - "break;") - } - code.push("}},") - if(extraFuncs.length > 0) { - currentFunc.push("}}") } - //Create face function - var faceArgs = [] - for(var i=0; i<(1<<(dimension-1)); ++i) { - faceArgs.push("v" + i) + //Enumerate ridges, facets, etc. of hypercube + for(var i=0; i<(1<0) { - shapeX += 0.02 - } - } +},{"./doConvert.js":984,"ndarray":1031}],984:[function(require,module,exports){ +module.exports=require('cwise-compiler')({"args":["array","scalar","index"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}","args":[{"name":"_inline_1_arg0_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":4}],"thisVars":[],"localVars":["_inline_1_i","_inline_1_v"]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"funcName":"convert","blockSize":64}) - var data = new Float32Array(bufferSize) - var ptr = 0 - var xOffset = -0.5 * shapeX - for(var i=0; i= 0; - var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); + this.showContour = true + this.showSurface = true - if (needsAlphaFormat) { - // Special case for "transparent", all other non-alpha formats - // will return rgba when there is transparency. - if (format === "name" && this._a === 0) { - return this.toName(); - } - return this.toRgbString(); - } - if (format === "rgb") { - formattedString = this.toRgbString(); - } - if (format === "prgb") { - formattedString = this.toPercentageRgbString(); - } - if (format === "hex" || format === "hex6") { - formattedString = this.toHexString(); - } - if (format === "hex3") { - formattedString = this.toHexString(true); - } - if (format === "hex8") { - formattedString = this.toHex8String(); - } - if (format === "name") { - formattedString = this.toName(); - } - if (format === "hsl") { - formattedString = this.toHslString(); - } - if (format === "hsv") { - formattedString = this.toHsvString(); - } + this.enableHighlight = [true, true, true] + this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]] + this.highlightTint = [ 1, 1, 1 ] + this.highlightLevel = [-1, -1, -1] - return formattedString || this.toHexString(); - }, - clone: function() { - return tinycolor(this.toString()); - }, + // Dynamic contour options + this.enableDynamic = [ true, true, true ] + this.dynamicLevel = [ NaN, NaN, NaN ] + this.dynamicColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ] + this.dynamicTint = [ 1, 1, 1 ] + this.dynamicWidth = [ 1, 1, 1 ] - _applyModification: function(fn, args) { - var color = fn.apply(null, [this].concat([].slice.call(args))); - this._r = color._r; - this._g = color._g; - this._b = color._b; - this.setAlpha(color._a); - return this; - }, - lighten: function() { - return this._applyModification(lighten, arguments); - }, - brighten: function() { - return this._applyModification(brighten, arguments); - }, - darken: function() { - return this._applyModification(darken, arguments); - }, - desaturate: function() { - return this._applyModification(desaturate, arguments); - }, - saturate: function() { - return this._applyModification(saturate, arguments); - }, - greyscale: function() { - return this._applyModification(greyscale, arguments); - }, - spin: function() { - return this._applyModification(spin, arguments); - }, + this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]] + this.surfaceProject = [ false, false, false ] + this.contourProject = [[ false, false, false ], + [ false, false, false ], + [ false, false, false ]] - _applyCombination: function(fn, args) { - return fn.apply(null, [this].concat([].slice.call(args))); - }, - analogous: function() { - return this._applyCombination(analogous, arguments); - }, - complement: function() { - return this._applyCombination(complement, arguments); - }, - monochromatic: function() { - return this._applyCombination(monochromatic, arguments); - }, - splitcomplement: function() { - return this._applyCombination(splitcomplement, arguments); - }, - triad: function() { - return this._applyCombination(triad, arguments); - }, - tetrad: function() { - return this._applyCombination(tetrad, arguments); - } -}; + this.colorBounds = [ false, false ] -// If input is an object, force 1 into "1.0" to handle ratios properly -// String input requires "1.0" as input, so 1 will be treated as 1 -tinycolor.fromRatio = function(color, opts) { - if (typeof color == "object") { - var newColor = {}; - for (var i in color) { - if (color.hasOwnProperty(i)) { - if (i === "a") { - newColor[i] = color[i]; - } - else { - newColor[i] = convertToPercentage(color[i]); - } - } - } - color = newColor; + // Store xyz fields, need this for picking + this._field = [ + ndarray(pool.mallocFloat(1024), [0, 0]), + ndarray(pool.mallocFloat(1024), [0, 0]), + ndarray(pool.mallocFloat(1024), [0, 0]) ] + + this.pickId = 1 + this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]] + + this.snapToData = false + + this.opacity = 1.0 + + this.lightPosition = [10, 10000, 0] + this.ambientLight = 0.8 + this.diffuseLight = 0.8 + this.specularLight = 2.0 + this.roughness = 0.5 + this.fresnel = 1.5 + + this.dirty = true +} + +var proto = SurfacePlot.prototype + +proto.isTransparent = function () { + return this.opacity < 1 +} + +proto.isOpaque = function () { + if (this.opacity >= 1) { + return true + } + for (var i = 0; i < 3; ++i) { + if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) { + return true } + } + return false +} - return tinycolor(color, opts); -}; +proto.pickSlots = 1 -// Given a string or object, convert that input to RGB -// Possible string inputs: -// -// "red" -// "#f00" or "f00" -// "#ff0000" or "ff0000" -// "#ff000000" or "ff000000" -// "rgb 255 0 0" or "rgb (255, 0, 0)" -// "rgb 1.0 0 0" or "rgb (1, 0, 0)" -// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" -// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" -// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" -// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" -// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" -// -function inputToRGB(color) { +proto.setPickBase = function (id) { + this.pickId = id +} - var rgb = { r: 0, g: 0, b: 0 }; - var a = 1; - var ok = false; - var format = false; +var ZERO_VEC = [0, 0, 0] - if (typeof color == "string") { - color = stringInputToObject(color); +var PROJECT_DATA = { + showSurface: false, + showContour: false, + projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()], + clipBounds: [ + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]]] +} + +function computeProjectionData (camera, obj) { + var i, j, k + + // Compute cube properties + var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC + + var showSurface = obj.showSurface + var showContour = obj.showContour + + for (i = 0; i < 3; ++i) { + showSurface = showSurface || obj.surfaceProject[i] + for (j = 0; j < 3; ++j) { + showContour = showContour || obj.contourProject[i][j] } + } - if (typeof color == "object") { - if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { - rgb = rgbToRgb(color.r, color.g, color.b); - ok = true; - format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; - } - else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { - color.s = convertToPercentage(color.s); - color.v = convertToPercentage(color.v); - rgb = hsvToRgb(color.h, color.s, color.v); - ok = true; - format = "hsv"; - } - else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { - color.s = convertToPercentage(color.s); - color.l = convertToPercentage(color.l); - rgb = hslToRgb(color.h, color.s, color.l); - ok = true; - format = "hsl"; - } + for (i = 0; i < 3; ++i) { + // Construct projection onto axis + var axisSquish = PROJECT_DATA.projections[i] + for (j = 0; j < 16; ++j) { + axisSquish[j] = 0 + } + for (j = 0; j < 4; ++j) { + axisSquish[5 * j] = 1 + } + axisSquish[5 * i] = 0 + axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] + multiply(axisSquish, camera.model, axisSquish) - if (color.hasOwnProperty("a")) { - a = color.a; - } + var nclipBounds = PROJECT_DATA.clipBounds[i] + for (k = 0; k < 2; ++k) { + for (j = 0; j < 3; ++j) { + nclipBounds[k][j] = camera.clipBounds[k][j] + } } + nclipBounds[0][i] = -1e8 + nclipBounds[1][i] = 1e8 + } - a = boundAlpha(a); + PROJECT_DATA.showSurface = showSurface + PROJECT_DATA.showContour = showContour - return { - ok: ok, - format: color.format || format, - r: mathMin(255, mathMax(rgb.r, 0)), - g: mathMin(255, mathMax(rgb.g, 0)), - b: mathMin(255, mathMax(rgb.b, 0)), - a: a - }; + return PROJECT_DATA } +var UNIFORMS = { + model: IDENTITY, + view: IDENTITY, + projection: IDENTITY, + inverseModel: IDENTITY.slice(), + lowerBound: [0, 0, 0], + upperBound: [0, 0, 0], + colorMap: 0, + clipBounds: [[0, 0, 0], [0, 0, 0]], + height: 0.0, + contourTint: 0, + contourColor: [0, 0, 0, 1], + permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], + zOffset: -1e-4, + kambient: 1, + kdiffuse: 1, + kspecular: 1, + lightPosition: [1000, 1000, 1000], + eyePosition: [0, 0, 0], + roughness: 1, + fresnel: 1, + opacity: 1 +} -// Conversion Functions -// -------------------- +var MATRIX_INVERSE = IDENTITY.slice() +var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] -// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: -// +function drawCore (params, transparent) { + params = params || {} + var gl = this.gl -// `rgbToRgb` -// Handle bounds / percentage checking to conform to CSS color spec -// -// *Assumes:* r, g, b in [0, 255] or [0, 1] -// *Returns:* { r, g, b } in [0, 255] -function rgbToRgb(r, g, b){ - return { - r: bound01(r, 255) * 255, - g: bound01(g, 255) * 255, - b: bound01(b, 255) * 255 - }; -} + gl.disable(gl.CULL_FACE) -// `rgbToHsl` -// Converts an RGB color value to HSL. -// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] -// *Returns:* { h, s, l } in [0,1] -function rgbToHsl(r, g, b) { + this._colorMap.bind(0) - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); + var uniforms = UNIFORMS + uniforms.model = params.model || IDENTITY + uniforms.view = params.view || IDENTITY + uniforms.projection = params.projection || IDENTITY + uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] + uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] + uniforms.contourColor = this.contourColor[0] - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, l = (max + min) / 2; + uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model) - if(max == min) { - h = s = 0; // achromatic + for (var i = 0; i < 2; ++i) { + var clipClamped = uniforms.clipBounds[i] + for (var j = 0; j < 3; ++j) { + clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) } - else { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } + } - h /= 6; + uniforms.kambient = this.ambientLight + uniforms.kdiffuse = this.diffuseLight + uniforms.kspecular = this.specularLight + + uniforms.roughness = this.roughness + uniforms.fresnel = this.fresnel + uniforms.opacity = this.opacity + + uniforms.height = 0.0 + uniforms.permutation = DEFAULT_PERM + + // Compute camera matrix inverse + var invCameraMatrix = MATRIX_INVERSE + multiply(invCameraMatrix, uniforms.view, uniforms.model) + multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) + invert(invCameraMatrix, invCameraMatrix) + + for (i = 0; i < 3; ++i) { + uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15] + } + + var w = invCameraMatrix[15] + for (i = 0; i < 3; ++i) { + w += this.lightPosition[i] * invCameraMatrix[4 * i + 3] + } + for (i = 0; i < 3; ++i) { + var s = invCameraMatrix[12 + i] + for (j = 0; j < 3; ++j) { + s += invCameraMatrix[4 * j + i] * this.lightPosition[j] } + uniforms.lightPosition[i] = s / w + } - return { h: h, s: s, l: l }; -} + var projectData = computeProjectionData(uniforms, this) -// `hslToRgb` -// Converts an HSL color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] -function hslToRgb(h, s, l) { - var r, g, b; + if (projectData.showSurface && (transparent === (this.opacity < 1))) { + // Set up uniforms + this._shader.bind() + this._shader.uniforms = uniforms - h = bound01(h, 360); - s = bound01(s, 100); - l = bound01(l, 100); + // Draw it + this._vao.bind() - function hue2rgb(p, q, t) { - if(t < 0) t += 1; - if(t > 1) t -= 1; - if(t < 1/6) return p + (q - p) * 6 * t; - if(t < 1/2) return q; - if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; + if (this.showSurface && this._vertexCount) { + this._vao.draw(gl.TRIANGLES, this._vertexCount) } - if(s === 0) { - r = g = b = l; // achromatic + // Draw projections of surface + for (i = 0; i < 3; ++i) { + if (!this.surfaceProject[i] || !this.vertexCount) { + continue + } + this._shader.uniforms.model = projectData.projections[i] + this._shader.uniforms.clipBounds = projectData.clipBounds[i] + this._vao.draw(gl.TRIANGLES, this._vertexCount) } - else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); + + this._vao.unbind() + } + + if (projectData.showContour && !transparent) { + var shader = this._contourShader + + // Don't apply lighting to contours + uniforms.kambient = 1.0 + uniforms.kdiffuse = 0.0 + uniforms.kspecular = 0.0 + uniforms.opacity = 1.0 + + shader.bind() + shader.uniforms = uniforms + + // Draw contour lines + var vao = this._contourVAO + vao.bind() + + // Draw contour levels + for (i = 0; i < 3; ++i) { + shader.uniforms.permutation = PERMUTATIONS[i] + gl.lineWidth(this.contourWidth[i]) + + for (j = 0; j < this.contourLevels[i].length; ++j) { + if (!this._contourCounts[i][j]) { + continue + } + if (j === this.highlightLevel[i]) { + shader.uniforms.contourColor = this.highlightColor[i] + shader.uniforms.contourTint = this.highlightTint[i] + } else if (j === 0 || (j - 1) === this.highlightLevel[i]) { + shader.uniforms.contourColor = this.contourColor[i] + shader.uniforms.contourTint = this.contourTint[i] + } + shader.uniforms.height = this.contourLevels[i][j] + vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j]) + } + } + + // Draw projections of surface + for (i = 0; i < 3; ++i) { + shader.uniforms.model = projectData.projections[i] + shader.uniforms.clipBounds = projectData.clipBounds[i] + for (j = 0; j < 3; ++j) { + if (!this.contourProject[i][j]) { + continue + } + shader.uniforms.permutation = PERMUTATIONS[j] + gl.lineWidth(this.contourWidth[j]) + for (var k = 0; k < this.contourLevels[j].length; ++k) { + if (k === this.highlightLevel[j]) { + shader.uniforms.contourColor = this.highlightColor[j] + shader.uniforms.contourTint = this.highlightTint[j] + } else if (k === 0 || (k - 1) === this.highlightLevel[j]) { + shader.uniforms.contourColor = this.contourColor[j] + shader.uniforms.contourTint = this.contourTint[j] + } + shader.uniforms.height = this.contourLevels[j][k] + vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) + } + } } - return { r: r * 255, g: g * 255, b: b * 255 }; -} - -// `rgbToHsv` -// Converts an RGB color value to HSV -// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] -// *Returns:* { h, s, v } in [0,1] -function rgbToHsv(r, g, b) { + // Draw dynamic contours + vao = this._dynamicVAO + vao.bind() - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); + // Draw contour levels + for (i = 0; i < 3; ++i) { + if (this._dynamicCounts[i] === 0) { + continue + } - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, v = max; + shader.uniforms.model = uniforms.model + shader.uniforms.clipBounds = uniforms.clipBounds + shader.uniforms.permutation = PERMUTATIONS[i] + gl.lineWidth(this.dynamicWidth[i]) - var d = max - min; - s = max === 0 ? 0 : d / max; + shader.uniforms.contourColor = this.dynamicColor[i] + shader.uniforms.contourTint = this.dynamicTint[i] + shader.uniforms.height = this.dynamicLevel[i] + vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - if(max == min) { - h = 0; // achromatic - } - else { - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; + for (j = 0; j < 3; ++j) { + if (!this.contourProject[j][i]) { + continue } - h /= 6; + + shader.uniforms.model = projectData.projections[j] + shader.uniforms.clipBounds = projectData.clipBounds[j] + vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) + } } - return { h: h, s: s, v: v }; -} -// `hsvToRgb` -// Converts an HSV color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] - function hsvToRgb(h, s, v) { + vao.unbind() + } +} - h = bound01(h, 360) * 6; - s = bound01(s, 100); - v = bound01(v, 100); +proto.draw = function (params) { + return drawCore.call(this, params, false) +} - var i = math.floor(h), - f = h - i, - p = v * (1 - s), - q = v * (1 - f * s), - t = v * (1 - (1 - f) * s), - mod = i % 6, - r = [v, q, p, p, t, v][mod], - g = [t, v, v, q, p, p][mod], - b = [p, p, t, v, v, q][mod]; +proto.drawTransparent = function (params) { + return drawCore.call(this, params, true) +} - return { r: r * 255, g: g * 255, b: b * 255 }; +var PICK_UNIFORMS = { + model: IDENTITY, + view: IDENTITY, + projection: IDENTITY, + inverseModel: IDENTITY, + clipBounds: [[0, 0, 0], [0, 0, 0]], + height: 0.0, + shape: [0, 0], + pickId: 0, + lowerBound: [0, 0, 0], + upperBound: [0, 0, 0], + zOffset: 0.0, + permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], + lightPosition: [0, 0, 0], + eyePosition: [0, 0, 0] } -// `rgbToHex` -// Converts an RGB color to hex -// Assumes r, g, and b are contained in the set [0, 255] -// Returns a 3 or 6 character hex -function rgbToHex(r, g, b, allow3Char) { +proto.drawPick = function (params) { + params = params || {} + var gl = this.gl + gl.disable(gl.CULL_FACE) - var hex = [ - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + var uniforms = PICK_UNIFORMS + uniforms.model = params.model || IDENTITY + uniforms.view = params.view || IDENTITY + uniforms.projection = params.projection || IDENTITY + uniforms.shape = this._field[2].shape + uniforms.pickId = this.pickId / 255.0 + uniforms.lowerBound = this.bounds[0] + uniforms.upperBound = this.bounds[1] + uniforms.permutation = DEFAULT_PERM - // Return a 3 character hex if possible - if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { - return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + for (var i = 0; i < 2; ++i) { + var clipClamped = uniforms.clipBounds[i] + for (var j = 0; j < 3; ++j) { + clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) } + } - return hex.join(""); -} + var projectData = computeProjectionData(uniforms, this) -// `rgbaToHex` -// Converts an RGBA color plus alpha transparency to hex -// Assumes r, g, b and a are contained in the set [0, 255] -// Returns an 8 character hex -function rgbaToHex(r, g, b, a) { + if (projectData.showSurface) { + // Set up uniforms + this._pickShader.bind() + this._pickShader.uniforms = uniforms - var hex = [ - pad2(convertDecimalToHex(a)), - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + // Draw it + this._vao.bind() + this._vao.draw(gl.TRIANGLES, this._vertexCount) - return hex.join(""); -} + // Draw projections of surface + for (i = 0; i < 3; ++i) { + if (!this.surfaceProject[i]) { + continue + } + this._pickShader.uniforms.model = projectData.projections[i] + this._pickShader.uniforms.clipBounds = projectData.clipBounds[i] + this._vao.draw(gl.TRIANGLES, this._vertexCount) + } -// `equals` -// Can be called with any tinycolor input -tinycolor.equals = function (color1, color2) { - if (!color1 || !color2) { return false; } - return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); -}; + this._vao.unbind() + } -tinycolor.random = function() { - return tinycolor.fromRatio({ - r: mathRandom(), - g: mathRandom(), - b: mathRandom() - }); -}; + if (projectData.showContour) { + var shader = this._contourPickShader + shader.bind() + shader.uniforms = uniforms -// Modification Functions -// ---------------------- -// Thanks to less.js for some of the basics here -// + var vao = this._contourVAO + vao.bind() -function desaturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s -= amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} + for (j = 0; j < 3; ++j) { + gl.lineWidth(this.contourWidth[j]) + shader.uniforms.permutation = PERMUTATIONS[j] + for (i = 0; i < this.contourLevels[j].length; ++i) { + if (this._contourCounts[j][i]) { + shader.uniforms.height = this.contourLevels[j][i] + vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i]) + } + } + } -function saturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s += amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} + // Draw projections of surface + for (i = 0; i < 3; ++i) { + shader.uniforms.model = projectData.projections[i] + shader.uniforms.clipBounds = projectData.clipBounds[i] -function greyscale(color) { - return tinycolor(color).desaturate(100); -} + for (j = 0; j < 3; ++j) { + if (!this.contourProject[i][j]) { + continue + } -function lighten (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l += amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); -} + shader.uniforms.permutation = PERMUTATIONS[j] + gl.lineWidth(this.contourWidth[j]) + for (var k = 0; k < this.contourLevels[j].length; ++k) { + if (this._contourCounts[j][k]) { + shader.uniforms.height = this.contourLevels[j][k] + vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) + } + } + } + } -function brighten(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var rgb = tinycolor(color).toRgb(); - rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); - rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); - rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); - return tinycolor(rgb); + vao.unbind() + } } -function darken (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l -= amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); -} +proto.pick = function (selection) { + if (!selection) { + return null + } -// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. -// Values outside of this range will be wrapped into this range. -function spin(color, amount) { - var hsl = tinycolor(color).toHsl(); - var hue = (mathRound(hsl.h) + amount) % 360; - hsl.h = hue < 0 ? 360 + hue : hue; - return tinycolor(hsl); -} + if (selection.id !== this.pickId) { + return null + } -// Combination Functions -// --------------------- -// Thanks to jQuery xColor for some of the ideas behind these -// + var shape = this._field[2].shape -function complement(color) { - var hsl = tinycolor(color).toHsl(); - hsl.h = (hsl.h + 180) % 360; - return tinycolor(hsl); -} + var result = this._pickResult -function triad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) - ]; -} + // Compute uv coordinate + var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0 + var ix = Math.floor(x) + var fx = x - ix -function tetrad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) - ]; -} + var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0 + var iy = Math.floor(y) + var fy = y - iy -function splitcomplement(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), - tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) - ]; -} + ix += 1 + iy += 1 -function analogous(color, results, slices) { - results = results || 6; - slices = slices || 30; + // Compute xyz coordinate + var pos = result.position + pos[0] = pos[1] = pos[2] = 0 + for (var dx = 0; dx < 2; ++dx) { + var s = dx ? fx : 1.0 - fx + for (var dy = 0; dy < 2; ++dy) { + var t = dy ? fy : 1.0 - fy - var hsl = tinycolor(color).toHsl(); - var part = 360 / slices; - var ret = [tinycolor(color)]; + var r = ix + dx + var c = iy + dy + var w = s * t - for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { - hsl.h = (hsl.h + part) % 360; - ret.push(tinycolor(hsl)); + for (var i = 0; i < 3; ++i) { + pos[i] += this._field[i].get(r, c) * w + } } - return ret; -} - -function monochromatic(color, results) { - results = results || 6; - var hsv = tinycolor(color).toHsv(); - var h = hsv.h, s = hsv.s, v = hsv.v; - var ret = []; - var modification = 1 / results; + } - while (results--) { - ret.push(tinycolor({ h: h, s: s, v: v})); - v = (v + modification) % 1; + // Find closest level + var levelIndex = this._pickResult.level + for (var j = 0; j < 3; ++j) { + levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j]) + if (levelIndex[j] < 0) { + if (this.contourLevels[j].length > 0) { + levelIndex[j] = 0 + } + } else if (levelIndex[j] < this.contourLevels[j].length - 1) { + var a = this.contourLevels[j][levelIndex[j]] + var b = this.contourLevels[j][levelIndex[j] + 1] + if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) { + levelIndex[j] += 1 + } } + } - return ret; -} - -// Utility Functions -// --------------------- + result.index[0] = fx < 0.5 ? ix : (ix + 1) + result.index[1] = fy < 0.5 ? iy : (iy + 1) -tinycolor.mix = function(color1, color2, amount) { - amount = (amount === 0) ? 0 : (amount || 50); + result.uv[0] = x / shape[0] + result.uv[1] = y / shape[1] - var rgb1 = tinycolor(color1).toRgb(); - var rgb2 = tinycolor(color2).toRgb(); + for (i = 0; i < 3; ++i) { + result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]) + } - var p = amount / 100; - var w = p * 2 - 1; - var a = rgb2.a - rgb1.a; + return result +} - var w1; +function padField (nfield, field) { + var shape = field.shape.slice() + var nshape = nfield.shape.slice() - if (w * a == -1) { - w1 = w; - } else { - w1 = (w + a) / (1 + w * a); - } + // Center + ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) - w1 = (w1 + 1) / 2; + // Edges + ops.assign(nfield.lo(1).hi(shape[0], 1), + field.hi(shape[0], 1)) + ops.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), + field.lo(0, shape[1] - 1).hi(shape[0], 1)) + ops.assign(nfield.lo(0, 1).hi(1, shape[1]), + field.hi(1)) + ops.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), + field.lo(shape[0] - 1)) + // Corners + nfield.set(0, 0, field.get(0, 0)) + nfield.set(0, nshape[1] - 1, field.get(0, shape[1] - 1)) + nfield.set(nshape[0] - 1, 0, field.get(shape[0] - 1, 0)) + nfield.set(nshape[0] - 1, nshape[1] - 1, field.get(shape[0] - 1, shape[1] - 1)) +} - var w2 = 1 - w1; +function handleArray (param, ctor) { + if (Array.isArray(param)) { + return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ] + } + return [ ctor(param), ctor(param), ctor(param) ] +} - var rgba = { - r: rgb2.r * w1 + rgb1.r * w2, - g: rgb2.g * w1 + rgb1.g * w2, - b: rgb2.b * w1 + rgb1.b * w2, - a: rgb2.a * p + rgb1.a * (1 - p) - }; +function toColor (x) { + if (Array.isArray(x)) { + if (x.length === 3) { + return [x[0], x[1], x[2], 1] + } + return [x[0], x[1], x[2], x[3]] + } + return [0, 0, 0, 1] +} - return tinycolor(rgba); -}; +function handleColor (param) { + if (Array.isArray(param)) { + if (Array.isArray(param)) { + return [ + toColor(param[0]), + toColor(param[1]), + toColor(param[2]) ] + } else { + var c = toColor(param) + return [ + c.slice(), + c.slice(), + c.slice() ] + } + } +} +proto.update = function (params) { + params = params || {} -// Readability Functions -// --------------------- -// false -// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false -tinycolor.isReadable = function(color1, color2, wcag2) { - var readability = tinycolor.readability(color1, color2); - var wcag2Parms, out; + if (!field) { + if (this._field[2].shape[0] || this._field[2].shape[2]) { + field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2) + } else { + field = this._field[2].hi(0, 0) + } + } - out = false; + // Update field + if ('field' in params || 'coords' in params) { + var fsize = (field.shape[0] + 2) * (field.shape[1] + 2) - wcag2Parms = validateWCAG2Parms(wcag2); - switch (wcag2Parms.level + wcag2Parms.size) { - case "AAsmall": - case "AAAlarge": - out = readability >= 4.5; - break; - case "AAlarge": - out = readability >= 3; - break; - case "AAAsmall": - out = readability >= 7; - break; + // Resize if necessary + if (fsize > this._field[2].data.length) { + pool.freeFloat(this._field[2].data) + this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize)) } - return out; -}; + // Pad field + this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) + padField(this._field[2], field) -// `mostReadable` -// Given a base color and a list of possible foreground or background -// colors for that base, returns the most readable color. -// Optionally returns Black or White if the most readable color is unreadable. -// *Example* -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" -tinycolor.mostReadable = function(baseColor, colorList, args) { - var bestColor = null; - var bestScore = 0; - var readability; - var includeFallbackColors, level, size ; - args = args || {}; - includeFallbackColors = args.includeFallbackColors ; - level = args.level; - size = args.size; + // Save shape of field + this.shape = field.shape.slice() + var shape = this.shape - for (var i= 0; i < colorList.length ; i++) { - readability = tinycolor.readability(baseColor, colorList[i]); - if (readability > bestScore) { - bestScore = readability; - bestColor = tinycolor(colorList[i]); - } + // Resize coordinate fields if necessary + for (var i = 0; i < 2; ++i) { + if (this._field[2].size > this._field[i].data.length) { + pool.freeFloat(this._field[i].data) + this._field[i].data = pool.mallocFloat(this._field[2].size) + } + this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]) } - if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { - return bestColor; - } - else { - args.includeFallbackColors=false; - return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); + // Generate x/y coordinates + if (params.coords) { + var coords = params.coords + if (!Array.isArray(coords) || coords.length !== 3) { + throw new Error('gl-surface: invalid coordinates for x/y') + } + for (i = 0; i < 2; ++i) { + var coord = coords[i] + for (j = 0; j < 2; ++j) { + if (coord.shape[j] !== shape[j]) { + throw new Error('gl-surface: coords have incorrect shape') + } + } + padField(this._field[i], coord) + } + } else if (params.ticks) { + var ticks = params.ticks + if (!Array.isArray(ticks) || ticks.length !== 2) { + throw new Error('gl-surface: invalid ticks') + } + for (i = 0; i < 2; ++i) { + var tick = ticks[i] + if (Array.isArray(tick) || tick.length) { + tick = ndarray(tick) + } + if (tick.shape[0] !== shape[i]) { + throw new Error('gl-surface: invalid tick length') + } + // Make a copy view of the tick array + var tick2 = ndarray(tick.data, shape) + tick2.stride[i] = tick.stride[0] + tick2.stride[i ^ 1] = 0 + + // Fill in field array + padField(this._field[i], tick2) + } + } else { + for (i = 0; i < 2; ++i) { + var offset = [0, 0] + offset[i] = 1 + this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) + } + this._field[0].set(0, 0, 0) + for (var j = 0; j < shape[0]; ++j) { + this._field[0].set(j + 1, 0, j) + } + this._field[0].set(shape[0] + 1, 0, shape[0] - 1) + this._field[1].set(0, 0, 0) + for (j = 0; j < shape[1]; ++j) { + this._field[1].set(0, j + 1, j) + } + this._field[1].set(0, shape[1] + 1, shape[1] - 1) } -}; + // Save shape + var fields = this._field -// Big List of Colors -// ------------------ -// -var names = tinycolor.names = { - aliceblue: "f0f8ff", - antiquewhite: "faebd7", - aqua: "0ff", - aquamarine: "7fffd4", - azure: "f0ffff", - beige: "f5f5dc", - bisque: "ffe4c4", - black: "000", - blanchedalmond: "ffebcd", - blue: "00f", - blueviolet: "8a2be2", - brown: "a52a2a", - burlywood: "deb887", - burntsienna: "ea7e5d", - cadetblue: "5f9ea0", - chartreuse: "7fff00", - chocolate: "d2691e", - coral: "ff7f50", - cornflowerblue: "6495ed", - cornsilk: "fff8dc", - crimson: "dc143c", - cyan: "0ff", - darkblue: "00008b", - darkcyan: "008b8b", - darkgoldenrod: "b8860b", - darkgray: "a9a9a9", - darkgreen: "006400", - darkgrey: "a9a9a9", - darkkhaki: "bdb76b", - darkmagenta: "8b008b", - darkolivegreen: "556b2f", - darkorange: "ff8c00", - darkorchid: "9932cc", - darkred: "8b0000", - darksalmon: "e9967a", - darkseagreen: "8fbc8f", - darkslateblue: "483d8b", - darkslategray: "2f4f4f", - darkslategrey: "2f4f4f", - darkturquoise: "00ced1", - darkviolet: "9400d3", - deeppink: "ff1493", - deepskyblue: "00bfff", - dimgray: "696969", - dimgrey: "696969", - dodgerblue: "1e90ff", - firebrick: "b22222", - floralwhite: "fffaf0", - forestgreen: "228b22", - fuchsia: "f0f", - gainsboro: "dcdcdc", - ghostwhite: "f8f8ff", - gold: "ffd700", - goldenrod: "daa520", - gray: "808080", - green: "008000", - greenyellow: "adff2f", - grey: "808080", - honeydew: "f0fff0", - hotpink: "ff69b4", - indianred: "cd5c5c", - indigo: "4b0082", - ivory: "fffff0", - khaki: "f0e68c", - lavender: "e6e6fa", - lavenderblush: "fff0f5", - lawngreen: "7cfc00", - lemonchiffon: "fffacd", - lightblue: "add8e6", - lightcoral: "f08080", - lightcyan: "e0ffff", - lightgoldenrodyellow: "fafad2", - lightgray: "d3d3d3", - lightgreen: "90ee90", - lightgrey: "d3d3d3", - lightpink: "ffb6c1", - lightsalmon: "ffa07a", - lightseagreen: "20b2aa", - lightskyblue: "87cefa", - lightslategray: "789", - lightslategrey: "789", - lightsteelblue: "b0c4de", - lightyellow: "ffffe0", - lime: "0f0", - limegreen: "32cd32", - linen: "faf0e6", - magenta: "f0f", - maroon: "800000", - mediumaquamarine: "66cdaa", - mediumblue: "0000cd", - mediumorchid: "ba55d3", - mediumpurple: "9370db", - mediumseagreen: "3cb371", - mediumslateblue: "7b68ee", - mediumspringgreen: "00fa9a", - mediumturquoise: "48d1cc", - mediumvioletred: "c71585", - midnightblue: "191970", - mintcream: "f5fffa", - mistyrose: "ffe4e1", - moccasin: "ffe4b5", - navajowhite: "ffdead", - navy: "000080", - oldlace: "fdf5e6", - olive: "808000", - olivedrab: "6b8e23", - orange: "ffa500", - orangered: "ff4500", - orchid: "da70d6", - palegoldenrod: "eee8aa", - palegreen: "98fb98", - paleturquoise: "afeeee", - palevioletred: "db7093", - papayawhip: "ffefd5", - peachpuff: "ffdab9", - peru: "cd853f", - pink: "ffc0cb", - plum: "dda0dd", - powderblue: "b0e0e6", - purple: "800080", - rebeccapurple: "663399", - red: "f00", - rosybrown: "bc8f8f", - royalblue: "4169e1", - saddlebrown: "8b4513", - salmon: "fa8072", - sandybrown: "f4a460", - seagreen: "2e8b57", - seashell: "fff5ee", - sienna: "a0522d", - silver: "c0c0c0", - skyblue: "87ceeb", - slateblue: "6a5acd", - slategray: "708090", - slategrey: "708090", - snow: "fffafa", - springgreen: "00ff7f", - steelblue: "4682b4", - tan: "d2b48c", - teal: "008080", - thistle: "d8bfd8", - tomato: "ff6347", - turquoise: "40e0d0", - violet: "ee82ee", - wheat: "f5deb3", - white: "fff", - whitesmoke: "f5f5f5", - yellow: "ff0", - yellowgreen: "9acd32" -}; + // Compute surface normals + var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) + for (i = 0; i < 3; ++i) { + gradient(dfields.pick(i), fields[i], 'mirror') + } + var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) + for (i = 0; i < shape[0] + 2; ++i) { + for (j = 0; j < shape[1] + 2; ++j) { + var dxdu = dfields.get(0, i, j, 0) + var dxdv = dfields.get(0, i, j, 1) + var dydu = dfields.get(1, i, j, 0) + var dydv = dfields.get(1, i, j, 1) + var dzdu = dfields.get(2, i, j, 0) + var dzdv = dfields.get(2, i, j, 1) -// Make it easy to access colors via `hexNames[hex]` -var hexNames = tinycolor.hexNames = flip(names); + var nx = dydu * dzdv - dydv * dzdu + var ny = dzdu * dxdv - dzdv * dxdu + var nz = dxdu * dydv - dxdv * dydu + var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) + if (nl < 1e-8) { + nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz)) + if (nl < 1e-8) { + nz = 1.0 + ny = nx = 0.0 + nl = 1.0 + } else { + nl = 1.0 / nl + } + } else { + nl = 1.0 / Math.sqrt(nl) + } -// Utilities -// --------- + normals.set(i, j, 0, nx * nl) + normals.set(i, j, 1, ny * nl) + normals.set(i, j, 2, nz * nl) + } + } + pool.free(dfields.data) -// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` -function flip(o) { - var flipped = { }; - for (var i in o) { - if (o.hasOwnProperty(i)) { - flipped[o[i]] = i; + // Initialize surface + var lo = [ Infinity, Infinity, Infinity ] + var hi = [ -Infinity, -Infinity, -Infinity ] + var lo_intensity = Infinity + var hi_intensity = -Infinity + var count = (shape[0] - 1) * (shape[1] - 1) * 6 + var tverts = pool.mallocFloat(bits.nextPow2(10 * count)) + var tptr = 0 + var vertexCount = 0 + for (i = 0; i < shape[0] - 1; ++i) { + j_loop: + for (j = 0; j < shape[1] - 1; ++j) { + // Test for NaNs + for (var dx = 0; dx < 2; ++dx) { + for (var dy = 0; dy < 2; ++dy) { + for (var k = 0; k < 3; ++k) { + var f = this._field[k].get(1 + i + dx, 1 + j + dy) + if (isNaN(f) || !isFinite(f)) { + continue j_loop + } + } + } } - } - return flipped; -} + for (k = 0; k < 6; ++k) { + var r = i + QUAD[k][0] + var c = j + QUAD[k][1] -// Return a valid alpha value [0,1] with all invalid values being set to 1 -function boundAlpha(a) { - a = parseFloat(a); + var tx = this._field[0].get(r + 1, c + 1) + var ty = this._field[1].get(r + 1, c + 1) + f = this._field[2].get(r + 1, c + 1) + var vf = f + nx = normals.get(r + 1, c + 1, 0) + ny = normals.get(r + 1, c + 1, 1) + nz = normals.get(r + 1, c + 1, 2) - if (isNaN(a) || a < 0 || a > 1) { - a = 1; - } + if (params.intensity) { + vf = params.intensity.get(r, c) + } - return a; -} + tverts[tptr++] = r + tverts[tptr++] = c + tverts[tptr++] = tx + tverts[tptr++] = ty + tverts[tptr++] = f + tverts[tptr++] = 0 + tverts[tptr++] = vf + tverts[tptr++] = nx + tverts[tptr++] = ny + tverts[tptr++] = nz -// Take input from [0, n] and return it as [0, 1] -function bound01(n, max) { - if (isOnePointZero(n)) { n = "100%"; } + lo[0] = Math.min(lo[0], tx) + lo[1] = Math.min(lo[1], ty) + lo[2] = Math.min(lo[2], f) + lo_intensity = Math.min(lo_intensity, vf) - var processPercent = isPercentage(n); - n = mathMin(max, mathMax(0, parseFloat(n))); + hi[0] = Math.max(hi[0], tx) + hi[1] = Math.max(hi[1], ty) + hi[2] = Math.max(hi[2], f) + hi_intensity = Math.max(hi_intensity, vf) - // Automatically convert percentage into number - if (processPercent) { - n = parseInt(n * max, 10) / 100; + vertexCount += 1 + } + } } - // Handle floating point rounding errors - if ((math.abs(n - max) < 0.000001)) { - return 1; + if (params.intensityBounds) { + lo_intensity = +params.intensityBounds[0] + hi_intensity = +params.intensityBounds[1] } - // Convert into [0, 1] range if it isn't already - return (n % max) / parseFloat(max); -} + // Scale all vertex intensities + for (i = 6; i < tptr; i += 10) { + tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity) + } -// Force a number between 0 and 1 -function clamp01(val) { - return mathMin(1, mathMax(0, val)); -} + this._vertexCount = vertexCount + this._coordinateBuffer.update(tverts.subarray(0, tptr)) + pool.freeFloat(tverts) + pool.free(normals.data) -// Parse a base-16 hex value into a base-10 integer -function parseIntFromHex(val) { - return parseInt(val, 16); -} + // Update bounds + this.bounds = [lo, hi] -// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 -// -function isOnePointZero(n) { - return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; -} + // Save intensity + this.intensity = params.intensity || this._field[2] -// Check to see if string passed in is a percentage -function isPercentage(n) { - return typeof n === "string" && n.indexOf('%') != -1; -} + if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) { + levelsChanged = true + } -// Force a hex value to have 2 characters -function pad2(c) { - return c.length == 1 ? '0' + c : '' + c; -} + // Save intensity bound + this.intensityBounds = [lo_intensity, hi_intensity] + } -// Replace a decimal with it's percentage value -function convertToPercentage(n) { - if (n <= 1) { - n = (n * 100) + "%"; + // Update level crossings + if ('levels' in params) { + var levels = params.levels + if (!Array.isArray(levels[0])) { + levels = [ [], [], levels ] + } else { + levels = levels.slice() + } + for (i = 0; i < 3; ++i) { + levels[i] = levels[i].slice() + levels.sort(function (a, b) { + return a - b + }) + } + change_test: + for (i = 0; i < 3; ++i) { + if (levels[i].length !== this.contourLevels[i].length) { + levelsChanged = true + break + } + for (j = 0; j < levels[i].length; ++j) { + if (levels[i][j] !== this.contourLevels[i][j]) { + levelsChanged = true + break change_test + } + } } + this.contourLevels = levels + } + + if (levelsChanged) { + fields = this._field + shape = this.shape + + // Update contour lines + var contourVerts = [] + + for (var dim = 0; dim < 3; ++dim) { + levels = this.contourLevels[dim] + var levelOffsets = [] + var levelCounts = [] - return n; -} + var parts = [0, 0, 0] -// Converts a decimal to a hex value -function convertDecimalToHex(d) { - return Math.round(parseFloat(d) * 255).toString(16); -} -// Converts a hex value to a decimal -function convertHexToDecimal(h) { - return (parseIntFromHex(h) / 255); -} + for (i = 0; i < levels.length; ++i) { + var graph = surfaceNets(this._field[dim], levels[i]) + levelOffsets.push((contourVerts.length / 5) | 0) + vertexCount = 0 -var matchers = (function() { + edge_loop: + for (j = 0; j < graph.cells.length; ++j) { + var e = graph.cells[j] + for (k = 0; k < 2; ++k) { + var p = graph.positions[e[k]] - // - var CSS_INTEGER = "[-\\+]?\\d+%?"; + var x = p[0] + var ix = Math.floor(x) | 0 + var fx = x - ix - // - var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + var y = p[1] + var iy = Math.floor(y) | 0 + var fy = y - iy - // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. - var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + var hole = false + dd_loop: + for (var dd = 0; dd < 3; ++dd) { + parts[dd] = 0.0 + var iu = (dim + dd + 1) % 3 + for (dx = 0; dx < 2; ++dx) { + var s = dx ? fx : 1.0 - fx + r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0 + for (dy = 0; dy < 2; ++dy) { + var t = dy ? fy : 1.0 - fy + c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0 - // Actual matching. - // Parentheses and commas are optional, but not required. - // Whitespace can take the place of commas or opening paren - var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + if (dd < 2) { + f = this._field[iu].get(r, c) + } else { + f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]) + } + if (!isFinite(f) || isNaN(f)) { + hole = true + break dd_loop + } - return { - rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), - rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), - hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), - hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), - hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), - hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), - hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, - hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ - }; -})(); + var w = s * t + parts[dd] += w * f + } + } + } -// `stringInputToObject` -// Permissive string parsing. Take in a number of formats, and output an object -// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` -function stringInputToObject(color) { + if (!hole) { + contourVerts.push(parts[0], parts[1], p[0], p[1], parts[2]) + vertexCount += 1 + } else { + if (k > 0) { + // If we already added first edge, pop off verts + for (var l = 0; l < 5; ++l) { + contourVerts.pop() + } + vertexCount -= 1 + } + continue edge_loop + } + } + } + levelCounts.push(vertexCount) + } - color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); - var named = false; - if (names[color]) { - color = names[color]; - named = true; - } - else if (color == 'transparent') { - return { r: 0, g: 0, b: 0, a: 0, format: "name" }; + // Store results + this._contourOffsets[dim] = levelOffsets + this._contourCounts[dim] = levelCounts } - // Try to match string input using regular expressions. - // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] - // Just return an object and let the conversion functions handle that. - // This way the result will be the same whether the tinycolor is initialized with string or object. - var match; - if ((match = matchers.rgb.exec(color))) { - return { r: match[1], g: match[2], b: match[3] }; - } - if ((match = matchers.rgba.exec(color))) { - return { r: match[1], g: match[2], b: match[3], a: match[4] }; - } - if ((match = matchers.hsl.exec(color))) { - return { h: match[1], s: match[2], l: match[3] }; - } - if ((match = matchers.hsla.exec(color))) { - return { h: match[1], s: match[2], l: match[3], a: match[4] }; - } - if ((match = matchers.hsv.exec(color))) { - return { h: match[1], s: match[2], v: match[3] }; - } - if ((match = matchers.hsva.exec(color))) { - return { h: match[1], s: match[2], v: match[3], a: match[4] }; - } - if ((match = matchers.hex8.exec(color))) { - return { - a: convertHexToDecimal(match[1]), - r: parseIntFromHex(match[2]), - g: parseIntFromHex(match[3]), - b: parseIntFromHex(match[4]), - format: named ? "name" : "hex8" - }; - } - if ((match = matchers.hex6.exec(color))) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - format: named ? "name" : "hex" - }; - } - if ((match = matchers.hex3.exec(color))) { - return { - r: parseIntFromHex(match[1] + '' + match[1]), - g: parseIntFromHex(match[2] + '' + match[2]), - b: parseIntFromHex(match[3] + '' + match[3]), - format: named ? "name" : "hex" - }; + var floatBuffer = pool.mallocFloat(contourVerts.length) + for (i = 0; i < contourVerts.length; ++i) { + floatBuffer[i] = contourVerts[i] } + this._contourBuffer.update(floatBuffer) + pool.freeFloat(floatBuffer) + } - return false; + if (params.colormap) { + this._colorMap.setPixels(genColormap(params.colormap)) + } } -function validateWCAG2Parms(parms) { - // return valid WCAG2 parms for isReadable. - // If input parms are invalid, return {"level":"AA", "size":"small"} - var level, size; - parms = parms || {"level":"AA", "size":"small"}; - level = (parms.level || "AA").toUpperCase(); - size = (parms.size || "small").toLowerCase(); - if (level !== "AA" && level !== "AAA") { - level = "AA"; +proto.dispose = function () { + this._shader.dispose() + this._vao.dispose() + this._coordinateBuffer.dispose() + this._colorMap.dispose() + this._contourBuffer.dispose() + this._contourVAO.dispose() + this._contourShader.dispose() + this._contourPickShader.dispose() + this._dynamicBuffer.dispose() + this._dynamicVAO.dispose() + for (var i = 0; i < 3; ++i) { + pool.freeFloat(this._field[i].data) + } +} + +proto.highlight = function (selection) { + if (!selection) { + this._dynamicCounts = [0, 0, 0] + this.dyanamicLevel = [NaN, NaN, NaN] + this.highlightLevel = [-1, -1, -1] + return + } + + for (var i = 0; i < 3; ++i) { + if (this.enableHighlight[i]) { + this.highlightLevel[i] = selection.level[i] + } else { + this.highlightLevel[i] = -1 } - if (size !== "small" && size !== "large") { - size = "small"; + } + + var levels + if (this.snapToData) { + levels = selection.dataCoordinate + } else { + levels = selection.position + } + if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) && + (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) && + (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) { + return + } + + var vertexCount = 0 + var shape = this.shape + var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1]) + + for (var d = 0; d < 3; ++d) { + if (!this.enableDynamic[d]) { + this.dynamicLevel[d] = NaN + this._dynamicCounts[d] = 0 + continue } - return {"level":level, "size":size}; -} -// Node: Export function -if (typeof module !== "undefined" && module.exports) { - module.exports = tinycolor; -} -// AMD/requirejs: Define the module -else if (typeof define === 'function' && define.amd) { - define(function () {return tinycolor;}); -} -// Browser: Expose to window -else { - window.tinycolor = tinycolor; -} + this.dynamicLevel[d] = levels[d] -})(); + var u = (d + 1) % 3 + var v = (d + 2) % 3 -},{}],275:[function(require,module,exports){ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.topojson = {}))); -}(this, function (exports) { 'use strict'; + var f = this._field[d] + var g = this._field[u] + var h = this._field[v] + var intensity = this.intensity - function noop() {} + var graph = surfaceNets(f, levels[d]) + var edges = graph.cells + var positions = graph.positions - function absolute(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - point[0] = (x0 += point[0]) * kx + dx; - point[1] = (y0 += point[1]) * ky + dy; - }; - } + this._dynamicOffsets[d] = vertexCount - function relative(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - var x1 = (point[0] - dx) / kx | 0, - y1 = (point[1] - dy) / ky | 0; - point[0] = x1 - x0; - point[1] = y1 - y0; - x0 = x1; - y0 = y1; - }; - } + for (i = 0; i < edges.length; ++i) { + var e = edges[i] + for (var j = 0; j < 2; ++j) { + var p = positions[e[j]] - function reverse(array, n) { - var t, j = array.length, i = j - n; - while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; - } + var x = +p[0] + var ix = x | 0 + var jx = Math.min(ix + 1, shape[0]) | 0 + var fx = x - ix + var hx = 1.0 - fx - function bisect(a, x) { - var lo = 0, hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (a[mid] < x) lo = mid + 1; - else hi = mid; - } - return lo; - } + var y = +p[1] + var iy = y | 0 + var jy = Math.min(iy + 1, shape[1]) | 0 + var fy = y - iy + var hy = 1.0 - fy - function feature(topology, o) { - return o.type === "GeometryCollection" ? { - type: "FeatureCollection", - features: o.geometries.map(function(o) { return feature$1(topology, o); }) - } : feature$1(topology, o); - } + var w00 = hx * hy + var w01 = hx * fy + var w10 = fx * hy + var w11 = fx * fy - function feature$1(topology, o) { - var f = { - type: "Feature", - id: o.id, - properties: o.properties || {}, - geometry: object(topology, o) - }; - if (o.id == null) delete f.id; - return f; - } + var cu = w00 * g.get(ix, iy) + + w01 * g.get(ix, jy) + + w10 * g.get(jx, iy) + + w11 * g.get(jx, jy) - function object(topology, o) { - var absolute$$ = absolute(topology.transform), - arcs = topology.arcs; + var cv = w00 * h.get(ix, iy) + + w01 * h.get(ix, jy) + + w10 * h.get(jx, iy) + + w11 * h.get(jx, jy) - function arc(i, points) { - if (points.length) points.pop(); - for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { - points.push(p = a[k].slice()); - absolute$$(p, k); + if (isNaN(cu) || isNaN(cv)) { + if (j) { + vertexCount -= 1 + } + break + } + + scratchBuffer[2 * vertexCount + 0] = cu + scratchBuffer[2 * vertexCount + 1] = cv + + vertexCount += 1 } - if (i < 0) reverse(points, n); } - function point(p) { - p = p.slice(); - absolute$$(p, 0); - return p; - } + this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d] + } - function line(arcs) { - var points = []; - for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); - if (points.length < 2) points.push(points[0].slice()); - return points; - } + this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) + pool.freeFloat(scratchBuffer) +} - function ring(arcs) { - var points = line(arcs); - while (points.length < 4) points.push(points[0].slice()); - return points; - } +function createSurfacePlot (params) { + var gl = params.gl + var shader = createShader(gl) + var pickShader = createPickShader(gl) + var contourShader = createContourShader(gl) + var contourPickShader = createPickContourShader(gl) - function polygon(arcs) { - return arcs.map(ring); + var coordinateBuffer = createBuffer(gl) + var vao = createVAO(gl, [ + { buffer: coordinateBuffer, + size: 4, + stride: SURFACE_VERTEX_SIZE, + offset: 0 + }, + { buffer: coordinateBuffer, + size: 3, + stride: SURFACE_VERTEX_SIZE, + offset: 16 + }, + { + buffer: coordinateBuffer, + size: 3, + stride: SURFACE_VERTEX_SIZE, + offset: 28 } + ]) - function geometry(o) { - var t = o.type; - return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} - : t in geometryType ? {type: t, coordinates: geometryType[t](o)} - : null; + var contourBuffer = createBuffer(gl) + var contourVAO = createVAO(gl, [ + { + buffer: contourBuffer, + size: 4, + stride: 20, + offset: 0 + }, + { + buffer: contourBuffer, + size: 1, + stride: 20, + offset: 16 } + ]) - var geometryType = { - Point: function(o) { return point(o.coordinates); }, - MultiPoint: function(o) { return o.coordinates.map(point); }, - LineString: function(o) { return line(o.arcs); }, - MultiLineString: function(o) { return o.arcs.map(line); }, - Polygon: function(o) { return polygon(o.arcs); }, - MultiPolygon: function(o) { return o.arcs.map(polygon); } - }; + var dynamicBuffer = createBuffer(gl) + var dynamicVAO = createVAO(gl, [ + { + buffer: dynamicBuffer, + size: 2, + type: gl.FLOAT + }]) - return geometry(o); - } + var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) + cmap.minFilter = gl.LINEAR + cmap.magFilter = gl.LINEAR - function stitchArcs(topology, arcs) { - var stitchedArcs = {}, - fragmentByStart = {}, - fragmentByEnd = {}, - fragments = [], - emptyIndex = -1; + var surface = new SurfacePlot( + gl, + [0, 0], + [[0, 0, 0], [0, 0, 0]], + shader, + pickShader, + coordinateBuffer, + vao, + cmap, + contourShader, + contourPickShader, + contourBuffer, + contourVAO, + dynamicBuffer, + dynamicVAO) - // Stitch empty arcs first, since they may be subsumed by other arcs. - arcs.forEach(function(i, j) { - var arc = topology.arcs[i < 0 ? ~i : i], t; - if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { - t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; - } - }); + var nparams = { + levels: [[], [], []] + } + for (var id in params) { + nparams[id] = params[id] + } + nparams.colormap = nparams.colormap || 'jet' - arcs.forEach(function(i) { - var e = ends(i), - start = e[0], - end = e[1], - f, g; + surface.update(nparams) - if (f = fragmentByEnd[start]) { - delete fragmentByEnd[f.end]; - f.push(i); - f.end = end; - if (g = fragmentByStart[end]) { - delete fragmentByStart[g.start]; - var fg = g === f ? f : f.concat(g); - fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else if (f = fragmentByStart[end]) { - delete fragmentByStart[f.start]; - f.unshift(i); - f.start = start; - if (g = fragmentByEnd[start]) { - delete fragmentByEnd[g.end]; - var gf = g === f ? f : g.concat(f); - fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else { - f = [i]; - fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; - } - }); + return surface +} - function ends(i) { - var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; - if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); - else p1 = arc[arc.length - 1]; - return i < 0 ? [p1, p0] : [p0, p1]; - } +},{"./lib/shaders":939,"binary-search-bounds":940,"bit-twiddle":941,"colormap":943,"gl-buffer":946,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-texture2d":973,"gl-vao":977,"ndarray":1031,"ndarray-gradient":978,"ndarray-ops":1026,"ndarray-pack":983,"surface-nets":1001,"typedarray-pool":1002}],1004:[function(require,module,exports){ +'use strict' - function flush(fragmentByEnd, fragmentByStart) { - for (var k in fragmentByEnd) { - var f = fragmentByEnd[k]; - delete fragmentByStart[f.start]; - delete f.start; - delete f.end; - f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); - fragments.push(f); - } - } +module.exports = mouseListen - flush(fragmentByEnd, fragmentByStart); - flush(fragmentByStart, fragmentByEnd); - arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); +var mouse = require('mouse-event') - return fragments; +function mouseListen(element, callback) { + if(!callback) { + callback = element + element = window } - function mesh(topology) { - return object(topology, meshArcs.apply(this, arguments)); + var buttonState = 0 + var x = 0 + var y = 0 + var mods = { + shift: false, + alt: false, + control: false, + meta: false } + var attached = false - function meshArcs(topology, o, filter) { - var arcs = []; - - function arc(i) { - var j = i < 0 ? ~i : i; - (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); + function updateMods(ev) { + var changed = false + if('altKey' in ev) { + changed = changed || ev.altKey !== mods.alt + mods.alt = !!ev.altKey } - - function line(arcs) { - arcs.forEach(arc); + if('shiftKey' in ev) { + changed = changed || ev.shiftKey !== mods.shift + mods.shift = !!ev.shiftKey } - - function polygon(arcs) { - arcs.forEach(line); + if('ctrlKey' in ev) { + changed = changed || ev.ctrlKey !== mods.control + mods.control = !!ev.ctrlKey } - - function geometry(o) { - if (o.type === "GeometryCollection") o.geometries.forEach(geometry); - else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs); + if('metaKey' in ev) { + changed = changed || ev.metaKey !== mods.meta + mods.meta = !!ev.metaKey } + return changed + } - if (arguments.length > 1) { - var geomsByArc = [], - geom; - - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs) { arcs.forEach(polygon); } - }; - - geometry(o); - - geomsByArc.forEach(arguments.length < 3 - ? function(geoms) { arcs.push(geoms[0].i); } - : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); - } else { - for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); + function handleEvent(nextButtons, ev) { + var nextX = mouse.x(ev) + var nextY = mouse.y(ev) + if('buttons' in ev) { + nextButtons = ev.buttons|0 + } + if(nextButtons !== buttonState || + nextX !== x || + nextY !== y || + updateMods(ev)) { + buttonState = nextButtons|0 + x = nextX||0 + y = nextY||0 + callback && callback(buttonState, x, y, mods) } - - return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)}; } - function triangle(triangle) { - var a = triangle[0], b = triangle[1], c = triangle[2]; - return Math.abs((a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1])); + function clearState(ev) { + handleEvent(0, ev) } - function ring(ring) { - var i = -1, - n = ring.length, - a, - b = ring[n - 1], - area = 0; + function handleBlur() { + if(buttonState || + x || + y || + mods.shift || + mods.alt || + mods.meta || + mods.control) { - while (++i < n) { - a = b; - b = ring[i]; - area += a[0] * b[1] - a[1] * b[0]; + x = y = 0 + buttonState = 0 + mods.shift = mods.alt = mods.control = mods.meta = false + callback && callback(0, 0, 0, mods) } - - return area / 2; - } - - function merge(topology) { - return object(topology, mergeArcs.apply(this, arguments)); } - function mergeArcs(topology, objects) { - var polygonsByArc = {}, - polygons = [], - components = []; - - objects.forEach(function(o) { - if (o.type === "Polygon") register(o.arcs); - else if (o.type === "MultiPolygon") o.arcs.forEach(register); - }); - - function register(polygon) { - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); - }); - }); - polygons.push(polygon); + function handleMods(ev) { + if(updateMods(ev)) { + callback && callback(buttonState, x, y, mods) } + } - function exterior(ring$$) { - return ring(object(topology, {type: "Polygon", arcs: [ring$$]}).coordinates[0]) > 0; // TODO allow spherical? + function handleMouseMove(ev) { + if(mouse.buttons(ev) === 0) { + handleEvent(0, ev) + } else { + handleEvent(buttonState, ev) } + } - polygons.forEach(function(polygon) { - if (!polygon._) { - var component = [], - neighbors = [polygon]; - polygon._ = 1; - components.push(component); - while (polygon = neighbors.pop()) { - component.push(polygon); - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { - if (!polygon._) { - polygon._ = 1; - neighbors.push(polygon); - } - }); - }); - }); - } - } - }); + function handleMouseDown(ev) { + handleEvent(buttonState | mouse.buttons(ev), ev) + } - polygons.forEach(function(polygon) { - delete polygon._; - }); + function handleMouseUp(ev) { + handleEvent(buttonState & ~mouse.buttons(ev), ev) + } - return { - type: "MultiPolygon", - arcs: components.map(function(polygons) { - var arcs = [], n; + function attachListeners() { + if(attached) { + return + } + attached = true - // Extract the exterior (unique) arcs. - polygons.forEach(function(polygon) { - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { - arcs.push(arc); - } - }); - }); - }); + element.addEventListener('mousemove', handleMouseMove) - // Stitch the arcs into one or more rings. - arcs = stitchArcs(topology, arcs); + element.addEventListener('mousedown', handleMouseDown) - // If more than one ring is returned, - // at most one of these rings can be the exterior; - // this exterior ring has the same winding order - // as any exterior ring in the original polygons. - if ((n = arcs.length) > 1) { - var sgn = exterior(polygons[0][0]); - for (var i = 0, t; i < n; ++i) { - if (sgn === exterior(arcs[i])) { - t = arcs[0], arcs[0] = arcs[i], arcs[i] = t; - break; - } - } - } + element.addEventListener('mouseup', handleMouseUp) - return arcs; - }) - }; - } + element.addEventListener('mouseleave', clearState) + element.addEventListener('mouseenter', clearState) + element.addEventListener('mouseout', clearState) + element.addEventListener('mouseover', clearState) - function neighbors(objects) { - var indexesByArc = {}, // arc index -> array of object indexes - neighbors = objects.map(function() { return []; }); + element.addEventListener('blur', handleBlur) - function line(arcs, i) { - arcs.forEach(function(a) { - if (a < 0) a = ~a; - var o = indexesByArc[a]; - if (o) o.push(i); - else indexesByArc[a] = [i]; - }); - } + element.addEventListener('keyup', handleMods) + element.addEventListener('keydown', handleMods) + element.addEventListener('keypress', handleMods) - function polygon(arcs, i) { - arcs.forEach(function(arc) { line(arc, i); }); - } + if(element !== window) { + window.addEventListener('blur', handleBlur) - function geometry(o, i) { - if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); - else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + window.addEventListener('keyup', handleMods) + window.addEventListener('keydown', handleMods) + window.addEventListener('keypress', handleMods) } + } - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } - }; - - objects.forEach(geometry); - - for (var i in indexesByArc) { - for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { - for (var k = j + 1; k < m; ++k) { - var ij = indexes[j], ik = indexes[k], n; - if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); - if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); - } - } + function detachListeners() { + if(!attached) { + return } + attached = false - return neighbors; - } + element.removeEventListener('mousemove', handleMouseMove) - function compareArea(a, b) { - return a[1][2] - b[1][2]; - } + element.removeEventListener('mousedown', handleMouseDown) - function minAreaHeap() { - var heap = {}, - array = [], - size = 0; + element.removeEventListener('mouseup', handleMouseUp) - heap.push = function(object) { - up(array[object._ = size] = object, size++); - return size; - }; + element.removeEventListener('mouseleave', clearState) + element.removeEventListener('mouseenter', clearState) + element.removeEventListener('mouseout', clearState) + element.removeEventListener('mouseover', clearState) - heap.pop = function() { - if (size <= 0) return; - var removed = array[0], object; - if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); - return removed; - }; + element.removeEventListener('blur', handleBlur) - heap.remove = function(removed) { - var i = removed._, object; - if (array[i] !== removed) return; // invalid request - if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); - return i; - }; + element.removeEventListener('keyup', handleMods) + element.removeEventListener('keydown', handleMods) + element.removeEventListener('keypress', handleMods) - function up(object, i) { - while (i > 0) { - var j = ((i + 1) >> 1) - 1, - parent = array[j]; - if (compareArea(object, parent) >= 0) break; - array[parent._ = i] = parent; - array[object._ = i = j] = object; - } - } + if(element !== window) { + window.removeEventListener('blur', handleBlur) - function down(object, i) { - while (true) { - var r = (i + 1) << 1, - l = r - 1, - j = i, - child = array[j]; - if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; - if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; - if (j === i) break; - array[child._ = i] = child; - array[object._ = i = j] = object; - } + window.removeEventListener('keyup', handleMods) + window.removeEventListener('keydown', handleMods) + window.removeEventListener('keypress', handleMods) } - - return heap; } - function presimplify(topology, triangleArea) { - var absolute$$ = absolute(topology.transform), - relative$$ = relative(topology.transform), - heap = minAreaHeap(); + //Attach listeners + attachListeners() - if (!triangleArea) triangleArea = triangle; + var result = { + element: element + } - topology.arcs.forEach(function(arc) { - var triangles = [], - maxArea = 0, - triangle, - i, - n, - p; + Object.defineProperties(result, { + enabled: { + get: function() { return attached }, + set: function(f) { + if(f) { + attachListeners() + } else { + detachListeners + } + }, + enumerable: true + }, + buttons: { + get: function() { return buttonState }, + enumerable: true + }, + x: { + get: function() { return x }, + enumerable: true + }, + y: { + get: function() { return y }, + enumerable: true + }, + mods: { + get: function() { return mods }, + enumerable: true + } + }) - // To store each point’s effective area, we create a new array rather than - // extending the passed-in point to workaround a Chrome/V8 bug (getting - // stuck in smi mode). For midpoints, the initial effective area of - // Infinity will be computed in the next step. - for (i = 0, n = arc.length; i < n; ++i) { - p = arc[i]; - absolute$$(arc[i] = [p[0], p[1], Infinity], i); - } + return result +} - for (i = 1, n = arc.length - 1; i < n; ++i) { - triangle = arc.slice(i - 1, i + 2); - triangle[1][2] = triangleArea(triangle); - triangles.push(triangle); - heap.push(triangle); - } +},{"mouse-event":1005}],1005:[function(require,module,exports){ +'use strict' - for (i = 0, n = triangles.length; i < n; ++i) { - triangle = triangles[i]; - triangle.previous = triangles[i - 1]; - triangle.next = triangles[i + 1]; +function mouseButtons(ev) { + if(typeof ev === 'object') { + if('buttons' in ev) { + return ev.buttons + } else if('which' in ev) { + var b = ev.which + if(b === 2) { + return 4 + } else if(b === 3) { + return 2 + } else if(b > 0) { + return 1<<(b-1) } - - while (triangle = heap.pop()) { - var previous = triangle.previous, - next = triangle.next; - - // If the area of the current point is less than that of the previous point - // to be eliminated, use the latter's area instead. This ensures that the - // current point cannot be eliminated without eliminating previously- - // eliminated points. - if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; - else maxArea = triangle[1][2]; - - if (previous) { - previous.next = next; - previous[2] = triangle[2]; - update(previous); - } - - if (next) { - next.previous = previous; - next[0] = triangle[0]; - update(next); - } + } else if('button' in ev) { + var b = ev.button + if(b === 1) { + return 4 + } else if(b === 2) { + return 2 + } else if(b >= 0) { + return 1< 0) { - return d.pop() +var invert2 = require('gl-mat2/invert') +var invert3 = require('gl-mat3/invert') +var invert4 = require('gl-mat4/invert') + +function invert(out, M) { + switch(M.length) { + case 0: + break + case 1: + out[0] = 1.0 / M[0] + break + case 4: + invert2(out, M) + break + case 9: + invert3(out, M) + break + case 16: + invert4(out, M) + break + default: + throw new Error('currently supports matrices up to 4x4') + break } - return new ArrayBuffer(n) + return out } -exports.mallocArrayBuffer = mallocArrayBuffer +},{"gl-mat2/invert":1016,"gl-mat3/invert":1017,"gl-mat4/invert":240}],1016:[function(require,module,exports){ +module.exports = invert -function mallocUint8(n) { - return new Uint8Array(mallocArrayBuffer(n), 0, n) -} -exports.mallocUint8 = mallocUint8 +/** + * Inverts a mat2 + * + * @alias mat2.invert + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +function invert(out, a) { + var a0 = a[0] + var a1 = a[1] + var a2 = a[2] + var a3 = a[3] + var det = a0 * a3 - a2 * a1 -function mallocUint16(n) { - return new Uint16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocUint16 = mallocUint16 + if (!det) return null + det = 1.0 / det -function mallocUint32(n) { - return new Uint32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocUint32 = mallocUint32 + out[0] = a3 * det + out[1] = -a1 * det + out[2] = -a2 * det + out[3] = a0 * det -function mallocInt8(n) { - return new Int8Array(mallocArrayBuffer(n), 0, n) + return out } -exports.mallocInt8 = mallocInt8 -function mallocInt16(n) { - return new Int16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocInt16 = mallocInt16 +},{}],1017:[function(require,module,exports){ +module.exports = invert -function mallocInt32(n) { - return new Int32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocInt32 = mallocInt32 +/** + * Inverts a mat3 + * + * @alias mat3.invert + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2] + var a10 = a[3], a11 = a[4], a12 = a[5] + var a20 = a[6], a21 = a[7], a22 = a[8] -function mallocFloat(n) { - return new Float32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocFloat32 = exports.mallocFloat = mallocFloat + var b01 = a22 * a11 - a12 * a21 + var b11 = -a22 * a10 + a12 * a20 + var b21 = a21 * a10 - a11 * a20 -function mallocDouble(n) { - return new Float64Array(mallocArrayBuffer(8*n), 0, n) -} -exports.mallocFloat64 = exports.mallocDouble = mallocDouble + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21 -function mallocUint8Clamped(n) { - if(hasUint8C) { - return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) - } else { - return mallocUint8(n) - } -} -exports.mallocUint8Clamped = mallocUint8Clamped + if (!det) return null + det = 1.0 / det -function mallocDataView(n) { - return new DataView(mallocArrayBuffer(n), 0, n) -} -exports.mallocDataView = mallocDataView + out[0] = b01 * det + out[1] = (-a22 * a01 + a02 * a21) * det + out[2] = (a12 * a01 - a02 * a11) * det + out[3] = b11 * det + out[4] = (a22 * a00 - a02 * a20) * det + out[5] = (-a12 * a00 + a02 * a10) * det + out[6] = b21 * det + out[7] = (-a21 * a00 + a01 * a20) * det + out[8] = (a11 * a00 - a01 * a10) * det -function mallocBuffer(n) { - n = bits.nextPow2(n) - var log_n = bits.log2(n) - var cache = BUFFER[log_n] - if(cache.length > 0) { - return cache.pop() - } - return new Buffer(n) + return out } -exports.mallocBuffer = mallocBuffer -exports.clearCache = function clearCache() { - for(var i=0; i<32; ++i) { - POOL.UINT8[i].length = 0 - POOL.UINT16[i].length = 0 - POOL.UINT32[i].length = 0 - POOL.INT8[i].length = 0 - POOL.INT16[i].length = 0 - POOL.INT32[i].length = 0 - POOL.FLOAT[i].length = 0 - POOL.DOUBLE[i].length = 0 - POOL.UINT8C[i].length = 0 - DATA[i].length = 0 - BUFFER[i].length = 0 - } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"bit-twiddle":50,"buffer":51,"dup":115}],279:[function(require,module,exports){ +},{}],1018:[function(require,module,exports){ +arguments[4][318][0].apply(exports,arguments) +},{"cwise-compiler":1019,"dup":318}],1019:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./lib/thunk.js":1021,"dup":319}],1020:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320,"uniq":1022}],1021:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"./compile.js":1020,"dup":321}],1022:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],1023:[function(require,module,exports){ "use strict" -function unique_pred(list, compare) { - var ptr = 1 - , len = list.length - , a=list[0], b=list[0] - for(var i=1; i 8192) { - throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") - } - var height = 3 * size - if(canvas.height < height) { - canvas.height = height - } - - context.fillStyle = "#000" - context.fillRect(0, 0, canvas.width, canvas.height) - - context.fillStyle = "#fff" - context.fillText(str, size, 2*size) - - //Cut pixels from image - var pixelData = context.getImageData(0, 0, width, height) - var pixels = ndarray(pixelData.data, [height, width, 4]) +var compile = require("cwise-compiler") - return pixels.pick(-1,-1,0).transpose(1,0) +var EmptyProc = { + body: "", + args: [], + thisVars: [], + localVars: [] } -function getContour(pixels, doSimplify) { - var contour = surfaceNets(pixels, 128) - if(doSimplify) { - return simplify(contour.cells, contour.positions, 0.25) +function fixup(x) { + if(!x) { + return EmptyProc } - return { - edges: contour.cells, - positions: contour.positions + for(var i=0; i>", + rrshift: ">>>" +} +;(function(){ + for(var id in assign_ops) { + var op = assign_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a","b","c"], + body: "a=b"+op+"c"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array","array"], + body: {args:["a","b"], + body:"a"+op+"=b"}, + rvalue: true, + funcName: id+"eq" + }) + exports[id+"s"] = makeOp({ + args: ["array", "array", "scalar"], + body: {args:["a","b","s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"seq"] = makeOp({ + args: ["array","scalar"], + body: {args:["a","s"], + body:"a"+op+"=s"}, + rvalue: true, + funcName: id+"seq" + }) } - return { - edges: [], - positions: [] +})(); + +var unary_ops = { + not: "!", + bnot: "~", + neg: "-", + recip: "1.0/" +} +;(function(){ + for(var id in unary_ops) { + var op = unary_ops[id] + exports[id] = makeOp({ + args: ["array", "array"], + body: {args:["a","b"], + body:"a="+op+"b"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array"], + body: {args:["a"], + body:"a="+op+"a"}, + rvalue: true, + count: 2, + funcName: id+"eq" + }) } +})(); + +var binary_ops = { + and: "&&", + or: "||", + eq: "===", + neq: "!==", + lt: "<", + gt: ">", + leq: "<=", + geq: ">=" } +;(function() { + for(var id in binary_ops) { + var op = binary_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a", "b", "c"], + body:"a=b"+op+"c"}, + funcName: id + }) + exports[id+"s"] = makeOp({ + args: ["array","array","scalar"], + body: {args:["a", "b", "s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"eq"] = makeOp({ + args: ["array", "array"], + body: {args:["a", "b"], + body:"a=a"+op+"b"}, + rvalue:true, + count:2, + funcName: id+"eq" + }) + exports[id+"seq"] = makeOp({ + args: ["array", "scalar"], + body: {args:["a","s"], + body:"a=a"+op+"s"}, + rvalue:true, + count:2, + funcName: id+"seq" + }) + } +})(); -function vectorizeText(str, canvas, context, options) { - var size = options.size || 64 - var family = options.font || "normal" +var math_unary = [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan" +] +;(function() { + for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norminf" +}) - var dead = [] - for(var i=0; i 0) { - var v = dead.pop() - live[v] = false - var n = adj[v] - for(var i=0; ithis_h)this_h=_inline_1_arg0_", + args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], + thisVars: [ "this_h" ], + localVars: [] }, + post: + { body: "return this_h", + args: [], + thisVars: [ "this_h" ], + localVars: [] } + }) - var newIndex = new Array(positions.length) - var npositions = [] - for(var i=0; ithis_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", + args:[ + {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, + {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], + thisVars:["this_i","this_v"], + localVars:["_inline_1_k"]}, + post:{ + body:"{return this_i}", + args:[], + thisVars:["this_i"], + localVars:[]} +}) -var uniq = require("uniq") +exports.random = makeOp({ + args: ["array"], + pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, + body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, + funcName: "random" +}) -function edgeToAdjacency(edges, numVertices) { - var numEdges = edges.length - if(typeof numVertices !== "number") { - numVertices = 0 - for(var i=0; i 0) { - nextCell = adj[i][b][0] - nextDir = i - break - } - } - nextVertex = nextCell[nextDir^1] +function compare1st(a, b) { + return a[0] - b[0] +} - for(var dir=0; dir<2; ++dir) { - var nbhd = adj[dir][b] - for(var k=0; k 0) { - nextCell = e - nextVertex = p - nextDir = dir - } - } - } - if(noCut) { - return nextVertex - } - if(nextCell) { - cut(nextCell, nextDir) - } - return nextVertex +function order() { + var stride = this.stride + var terms = new Array(stride.length) + var i + for(i=0; i 0) { - var ni = adj[0][i].length - var ncycle = extractCycle(i,j) - if(shouldGlue(pcycle, ncycle)) { - //Glue together trivial cycles - pcycle.push.apply(pcycle, ncycle) - } else { - if(pcycle.length > 0) { - cycles.push(pcycle) - } - pcycle = ncycle - } - } - if(pcycle.length > 0) { - cycles.push(pcycle) - } - } + if(dimension === -1) { + //Special case for trivial arrays + var code = + "function "+className+"(a){this.data=a;};\ +var proto="+className+".prototype;\ +proto.dtype='"+dtype+"';\ +proto.index=function(){return -1};\ +proto.size=0;\ +proto.dimension=-1;\ +proto.shape=proto.stride=proto.order=[];\ +proto.lo=proto.hi=proto.transpose=proto.step=\ +function(){return new "+className+"(this.data);};\ +proto.get=proto.set=function(){};\ +proto.pick=function(){return null};\ +return function construct_"+className+"(a){return new "+className+"(a);}" + var procedure = new Function(code) + return procedure() + } else if(dimension === 0) { + //Special case for 0d arrays + var code = + "function "+className+"(a,d) {\ +this.data = a;\ +this.offset = d\ +};\ +var proto="+className+".prototype;\ +proto.dtype='"+dtype+"';\ +proto.index=function(){return this.offset};\ +proto.dimension=0;\ +proto.size=1;\ +proto.shape=\ +proto.stride=\ +proto.order=[];\ +proto.lo=\ +proto.hi=\ +proto.transpose=\ +proto.step=function "+className+"_copy() {\ +return new "+className+"(this.data,this.offset)\ +};\ +proto.pick=function "+className+"_pick(){\ +return TrivialArray(this.data);\ +};\ +proto.valueOf=proto.get=function "+className+"_get(){\ +return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ +"};\ +proto.set=function "+className+"_set(v){\ +return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ +};\ +return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" + var procedure = new Function("TrivialArray", code) + return procedure(CACHED_CONSTRUCTORS[dtype][0]) } - //Combine paths and loops together - return cycles -} -},{"compare-angle":285}],285:[function(require,module,exports){ -"use strict" - -module.exports = compareAngle - -var orient = require("robust-orientation") -var sgn = require("signum") -var twoSum = require("two-sum") -var robustProduct = require("robust-product") -var robustSum = require("robust-sum") - -function testInterior(a, b, c) { - var x0 = twoSum(a[0], -b[0]) - var y0 = twoSum(a[1], -b[1]) - var x1 = twoSum(c[0], -b[0]) - var y1 = twoSum(c[1], -b[1]) - - var d = robustSum( - robustProduct(x0, x1), - robustProduct(y0, y1)) - - return d[d.length-1] >= 0 -} + var code = ["'use strict'"] -function compareAngle(a, b, c, d) { - var bcd = orient(b, c, d) - if(bcd === 0) { - //Handle degenerate cases - var sabc = sgn(orient(a, b, c)) - var sabd = sgn(orient(a, b, d)) - if(sabc === sabd) { - if(sabc === 0) { - var ic = testInterior(a, b, c) - var id = testInterior(a, b, d) - if(ic === id) { - return 0 - } else if(ic) { - return 1 - } else { - return -1 - } - } - return 0 - } else if(sabd === 0) { - if(sabc > 0) { - return -1 - } else if(testInterior(a, b, d)) { - return -1 - } else { - return 1 - } - } else if(sabc === 0) { - if(sabd > 0) { - return 1 - } else if(testInterior(a, b, c)) { - return 1 - } else { - return -1 - } - } - return sgn(sabd - sabc) - } - var abc = orient(a, b, c) - if(abc > 0) { - if(bcd > 0 && orient(a, b, d) > 0) { - return 1 - } - return -1 - } else if(abc < 0) { - if(bcd > 0 || orient(a, b, d) > 0) { - return 1 - } - return -1 + //Create constructor for view + var indices = iota(dimension) + var args = indices.map(function(i) { return "i"+i }) + var index_str = "this.offset+" + indices.map(function(i) { + return "this.stride[" + i + "]*i" + i + }).join("+") + var shapeArg = indices.map(function(i) { + return "b"+i + }).join(",") + var strideArg = indices.map(function(i) { + return "c"+i + }).join(",") + code.push( + "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a", + "this.shape=[" + shapeArg + "]", + "this.stride=[" + strideArg + "]", + "this.offset=d|0}", + "var proto="+className+".prototype", + "proto.dtype='"+dtype+"'", + "proto.dimension="+dimension) + + //view.size: + code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\ +return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"), +"}})") + + //view.order: + if(dimension === 1) { + code.push("proto.order=[0]") } else { - var abd = orient(a, b, d) - if(abd > 0) { - return 1 - } else { - if(testInterior(a, b, c)) { - return 1 - } else { - return -1 + code.push("Object.defineProperty(proto,'order',{get:") + if(dimension < 4) { + code.push("function "+className+"_order(){") + if(dimension === 2) { + code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})") + } else if(dimension === 3) { + code.push( +"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ +if(s0>s1){\ +if(s1>s2){\ +return [2,1,0];\ +}else if(s0>s2){\ +return [1,2,0];\ +}else{\ +return [1,0,2];\ +}\ +}else if(s0>s2){\ +return [2,0,1];\ +}else if(s2>s1){\ +return [0,1,2];\ +}else{\ +return [0,2,1];\ +}}})") } + } else { + code.push("ORDER})") } } -} -},{"robust-orientation":259,"robust-product":286,"robust-sum":262,"signum":287,"two-sum":277}],286:[function(require,module,exports){ -"use strict" - -var robustSum = require("robust-sum") -var robustScale = require("robust-scale") - -module.exports = robustProduct -function robustProduct(a, b) { - if(a.length === 1) { - return robustScale(b, a[0]) - } - if(b.length === 1) { - return robustScale(a, b[0]) - } - if(a.length === 0 || b.length === 0) { - return [0] - } - var r = [0] - if(a.length < b.length) { - for(var i=0; i 0) { return 1 } - return 0.0 -} -},{}],288:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],289:[function(require,module,exports){ -"use strict" -var bounds = require("binary-search-bounds") + //view.get(i0, ...): + code.push("proto.get=function "+className+"_get("+args.join(",")+"){") + if(useGetters) { + code.push("return this.data.get("+index_str+")}") + } else { + code.push("return this.data["+index_str+"]}") + } -var NOT_FOUND = 0 -var SUCCESS = 1 -var EMPTY = 2 + //view.index: + code.push( + "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") -module.exports = createWrapper + //view.hi(): + code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ + indices.map(function(i) { + return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") + }).join(",")+","+ + indices.map(function(i) { + return "this.stride["+i + "]" + }).join(",")+",this.offset)}") -function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { - this.mid = mid - this.left = left - this.right = right - this.leftPoints = leftPoints - this.rightPoints = rightPoints - this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length -} + //view.lo(): + var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) + var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) + code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) + for(var i=0; i=0){\ +d=i"+i+"|0;\ +b+=c"+i+"*d;\ +a"+i+"-=d}") + } + code.push("return new "+className+"(this.data,"+ + indices.map(function(i) { + return "a"+i + }).join(",")+","+ + indices.map(function(i) { + return "c"+i + }).join(",")+",b)}") -var proto = IntervalTreeNode.prototype + //view.step(): + code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ + indices.map(function(i) { + return "a"+i+"=this.shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "b"+i+"=this.stride["+i+"]" + }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") + for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + } + code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") -function rebuildWithInterval(node, interval) { - var intervals = node.intervals([]) - intervals.push(interval) - rebuild(node, intervals) -} + //Add return statement + code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ + indices.map(function(i) { + return "shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "stride["+i+"]" + }).join(",")+",offset)}") -function rebuildWithoutInterval(node, interval) { - var intervals = node.intervals([]) - var idx = intervals.indexOf(interval) - if(idx < 0) { - return NOT_FOUND - } - intervals.splice(idx, 1) - rebuild(node, intervals) - return SUCCESS + //Compile procedure + var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) + return procedure(CACHED_CONSTRUCTORS[dtype], order) } -proto.intervals = function(result) { - result.push.apply(result, this.leftPoints) - if(this.left) { - this.left.intervals(result) - } - if(this.right) { - this.right.intervals(result) +function arrayDType(data) { + if(isBuffer(data)) { + return "buffer" } - return result -} - -proto.insert = function(interval) { - var weight = this.count - this.leftPoints.length - this.count += 1 - if(interval[1] < this.mid) { - if(this.left) { - if(4*(this.left.count+1) > 3*(weight+1)) { - rebuildWithInterval(this, interval) - } else { - this.left.insert(interval) - } - } else { - this.left = createIntervalTree([interval]) - } - } else if(interval[0] > this.mid) { - if(this.right) { - if(4*(this.right.count+1) > 3*(weight+1)) { - rebuildWithInterval(this, interval) - } else { - this.right.insert(interval) - } - } else { - this.right = createIntervalTree([interval]) + if(hasTypedArrays) { + switch(Object.prototype.toString.call(data)) { + case "[object Float64Array]": + return "float64" + case "[object Float32Array]": + return "float32" + case "[object Int8Array]": + return "int8" + case "[object Int16Array]": + return "int16" + case "[object Int32Array]": + return "int32" + case "[object Uint8Array]": + return "uint8" + case "[object Uint16Array]": + return "uint16" + case "[object Uint32Array]": + return "uint32" + case "[object Uint8ClampedArray]": + return "uint8_clamped" } - } else { - var l = bounds.ge(this.leftPoints, interval, compareBegin) - var r = bounds.ge(this.rightPoints, interval, compareEnd) - this.leftPoints.splice(l, 0, interval) - this.rightPoints.splice(r, 0, interval) } -} - -proto.remove = function(interval) { - var weight = this.count - this.leftPoints - if(interval[1] < this.mid) { - if(!this.left) { - return NOT_FOUND - } - var rw = this.right ? this.right.count : 0 - if(4 * rw > 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) - } - var r = this.left.remove(interval) - if(r === EMPTY) { - this.left = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 - } - return r - } else if(interval[0] > this.mid) { - if(!this.right) { - return NOT_FOUND - } - var lw = this.left ? this.left.count : 0 - if(4 * lw > 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) - } - var r = this.right.remove(interval) - if(r === EMPTY) { - this.right = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 - } - return r - } else { - if(this.count === 1) { - if(this.leftPoints[0] === interval) { - return EMPTY - } else { - return NOT_FOUND - } - } - if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { - if(this.left && this.right) { - var p = this - var n = this.left - while(n.right) { - p = n - n = n.right - } - if(p === this) { - n.right = this.right - } else { - var l = this.left - var r = this.right - p.count -= n.count - p.right = n.left - n.left = l - n.right = r - } - copy(this, n) - this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length - } else if(this.left) { - copy(this, this.left) - } else { - copy(this, this.right) - } - return SUCCESS - } - for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { - var r = cb(arr[i]) - if(r) { return r } +;(function() { + for(var id in CACHED_CONSTRUCTORS) { + CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) } -} +}); -function reportRange(arr, cb) { - for(var i=0; i this.mid) { - if(this.right) { - var r = this.right.queryPoint(x, cb) - if(r) { return r } - } - return reportRightRange(this.rightPoints, x, cb) - } else { - return reportRange(this.leftPoints, cb) + if(shape === undefined) { + shape = [ data.length ] } -} - -proto.queryInterval = function(lo, hi, cb) { - if(lo < this.mid && this.left) { - var r = this.left.queryInterval(lo, hi, cb) - if(r) { return r } + var d = shape.length + if(stride === undefined) { + stride = new Array(d) + for(var i=d-1, sz=1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } } - if(hi > this.mid && this.right) { - var r = this.right.queryInterval(lo, hi, cb) - if(r) { return r } + if(offset === undefined) { + offset = 0 + for(var i=0; i this.mid) { - return reportRightRange(this.rightPoints, lo, cb) - } else { - return reportRange(this.leftPoints, cb) + var dtype = arrayDType(data) + var ctor_list = CACHED_CONSTRUCTORS[dtype] + while(ctor_list.length <= d+1) { + ctor_list.push(compileConstructor(dtype, ctor_list.length-1)) } + var ctor = ctor_list[d+1] + return ctor(data, shape, stride, offset) } -function compareNumbers(a, b) { - return a - b -} +module.exports = wrappedNDArrayCtor -function compareBegin(a, b) { - var d = a[0] - b[0] - if(d) { return d } - return a[1] - b[1] -} +},{"iota-array":1032,"is-buffer":1033}],1032:[function(require,module,exports){ +"use strict" -function compareEnd(a, b) { - var d = a[1] - b[1] - if(d) { return d } - return a[0] - b[0] +function iota(n) { + var result = new Array(n) + for(var i=0; i + * License: MIT + * + * `npm install is-buffer` + */ - var mid = pts[pts.length>>1] +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) +} - var leftIntervals = [] - var rightIntervals = [] - var centerIntervals = [] - for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") } } -Object.defineProperty(tproto, "count", { - get: function() { - if(this.root) { - return this.root.count +function determinant(m) { + if(m.length === 2) { + return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] + } else { + var expr = [] + for(var i=0; i b[1][0]) { - bl = b[1] - br = b[0] - } else { - var alo = Math.min(a[0][1], a[1][1]) - var ahi = Math.max(a[0][1], a[1][1]) - var blo = Math.min(b[0][1], b[1][1]) - var bhi = Math.max(b[0][1], b[1][1]) - if(ahi < blo) { - return ahi - blo +var CACHED = [ + function orientation0() { return 0 }, + function orientation1() { return 0 }, + function orientation2(a, b) { + return b[0] - a[0] + }, + function orientation3(a, b, c) { + var l = (a[1] - c[1]) * (b[0] - c[0]) + var r = (a[0] - c[0]) * (b[1] - c[1]) + var det = l - r + var s + if(l > 0) { + if(r <= 0) { + return det + } else { + s = l + r + } + } else if(l < 0) { + if(r >= 0) { + return det + } else { + s = -(l + r) + } + } else { + return det } - if(alo > bhi) { - return alo - bhi + var tol = ERRBOUND3 * s + if(det >= tol || det <= -tol) { + return det } - return ahi - bhi - } - var al, ar - if(a[0][1] < a[1][1]) { - al = a[0] - ar = a[1] - } else { - al = a[1] - ar = a[0] - } - var d = orient(br, bl, al) - if(d) { - return d + return orientation3Exact(a, b, c) + }, + function orientation4(a,b,c,d) { + var adx = a[0] - d[0] + var bdx = b[0] - d[0] + var cdx = c[0] - d[0] + var ady = a[1] - d[1] + var bdy = b[1] - d[1] + var cdy = c[1] - d[1] + var adz = a[2] - d[2] + var bdz = b[2] - d[2] + var cdz = c[2] - d[2] + var bdxcdy = bdx * cdy + var cdxbdy = cdx * bdy + var cdxady = cdx * ady + var adxcdy = adx * cdy + var adxbdy = adx * bdy + var bdxady = bdx * ady + var det = adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady) + var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) + var tol = ERRBOUND4 * permanent + if ((det > tol) || (-det > tol)) { + return det + } + return orientation4Exact(a,b,c,d) } - d = orient(br, bl, ar) - if(d) { - return d +] + +function slowOrient(args) { + var proc = CACHED[args.length] + if(!proc) { + proc = CACHED[args.length] = orientation(args.length) } - return ar - br + return proc.apply(undefined, args) } -function orderSegments(b, a) { - var al, ar - if(a[0][0] < a[1][0]) { - al = a[0] - ar = a[1] - } else if(a[0][0] > a[1][0]) { - al = a[1] - ar = a[0] - } else { - return horizontalOrder(a, b) +function generateOrientationProc() { + while(CACHED.length <= NUM_EXPAND) { + CACHED.push(orientation(CACHED.length)) } - var bl, br - if(b[0][0] < b[1][0]) { - bl = b[0] - br = b[1] - } else if(b[0][0] > b[1][0]) { - bl = b[1] - br = b[0] - } else { - return -horizontalOrder(b, a) + var args = [] + var procArgs = ["slow"] + for(var i=0; i<=NUM_EXPAND; ++i) { + args.push("a" + i) + procArgs.push("o" + i) } - var d1 = orient(al, ar, br) - var d2 = orient(al, ar, bl) - if(d1 < 0) { - if(d2 <= 0) { - return d1 - } - } else if(d1 > 0) { - if(d2 >= 0) { - return d1 - } - } else if(d2) { - return d2 + var code = [ + "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" + ] + for(var i=2; i<=NUM_EXPAND; ++i) { + code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") } - d1 = orient(br, bl, ar) - d2 = orient(br, bl, al) - if(d1 < 0) { - if(d2 <= 0) { - return d1 - } - } else if(d1 > 0) { - if(d2 >= 0) { - return d1 - } - } else if(d2) { - return d2 + code.push("}var s=new Array(arguments.length);for(var i=0;i= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); -//Insert a new item into the tree -proto.insert = function(key, value) { - var cmp = this._compare - //Find point to insert new node at - var n = this.root - var n_stack = [] - var d_stack = [] - while(n) { - var d = cmp(key, n.key) - n_stack.push(n) - d_stack.push(d) - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - //Rebuild path to leaf node - n_stack.push(new RBNode(RED, key, value, null, null, 1)) - for(var s=n_stack.length-2; s>=0; --s) { - var n = n_stack[s] - if(d_stack[s] <= 0) { - n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) - } else { - n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) - } - } - //Rebalance tree using rotations - //console.log("start insert", key, d_stack) - for(var s=n_stack.length-1; s>1; --s) { - var p = n_stack[s-1] - var n = n_stack[s] - if(p._color === BLACK || n._color === BLACK) { - break - } - var pp = n_stack[s-2] - if(pp.left === p) { - if(p.left === n) { - var y = pp.right - if(y && y._color === RED) { - //console.log("LLr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LLb") - pp._color = RED - pp.left = p.right - p._color = BLACK - p.right = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = p - } else { - ppp.right = p + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); } - } - break + return this.toRgbString(); } - } else { - var y = pp.right - if(y && y._color === RED) { - //console.log("LRr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LRb") - p.right = n.left - pp._color = RED - pp.left = n.right - n._color = BLACK - n.left = p - n.right = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = n - } else { - ppp.right = n - } - } - break + if (format === "rgb") { + formattedString = this.toRgbString(); } - } - } else { - if(p.right === n) { - var y = pp.left - if(y && y._color === RED) { - //console.log("RRr", y.key) - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RRb") - pp._color = RED - pp.right = p.left - p._color = BLACK - p.left = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = p - } else { - ppp.left = p - } - } - break + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); } - } else { - var y = pp.left - if(y && y._color === RED) { - //console.log("RLr") - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RLb") - p.left = n.right - pp._color = RED - pp.right = n.left - n._color = BLACK - n.right = p - n.left = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = n - } else { - ppp.left = n - } - } - break + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); } - } - } - } - //Return new tree - n_stack[0]._color = BLACK - return new RedBlackTree(cmp, n_stack[0]) -} + return formattedString || this.toHexString(); + }, + clone: function() { + return tinycolor(this.toString()); + }, -//Visit all nodes inorder -function doVisitFull(visit, node) { - if(node.left) { - var v = doVisitFull(visit, node.left) - if(v) { return v } - } - var v = visit(node.key, node.value) - if(v) { return v } - if(node.right) { - return doVisitFull(visit, node.right) - } -} + _applyModification: function(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function() { + return this._applyModification(lighten, arguments); + }, + brighten: function() { + return this._applyModification(brighten, arguments); + }, + darken: function() { + return this._applyModification(darken, arguments); + }, + desaturate: function() { + return this._applyModification(desaturate, arguments); + }, + saturate: function() { + return this._applyModification(saturate, arguments); + }, + greyscale: function() { + return this._applyModification(greyscale, arguments); + }, + spin: function() { + return this._applyModification(spin, arguments); + }, -//Visit half nodes in order -function doVisitHalf(lo, compare, visit, node) { - var l = compare(lo, node.key) - if(l <= 0) { - if(node.left) { - var v = doVisitHalf(lo, compare, visit, node.left) - if(v) { return v } + _applyCombination: function(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function() { + return this._applyCombination(analogous, arguments); + }, + complement: function() { + return this._applyCombination(complement, arguments); + }, + monochromatic: function() { + return this._applyCombination(monochromatic, arguments); + }, + splitcomplement: function() { + return this._applyCombination(splitcomplement, arguments); + }, + triad: function() { + return this._applyCombination(triad, arguments); + }, + tetrad: function() { + return this._applyCombination(tetrad, arguments); } - var v = visit(node.key, node.value) - if(v) { return v } - } - if(node.right) { - return doVisitHalf(lo, compare, visit, node.right) - } -} +}; -//Visit all nodes within a range -function doVisit(lo, hi, compare, visit, node) { - var l = compare(lo, node.key) - var h = compare(hi, node.key) - var v - if(l <= 0) { - if(node.left) { - v = doVisit(lo, hi, compare, visit, node.left) - if(v) { return v } +// If input is an object, force 1 into "1.0" to handle ratios properly +// String input requires "1.0" as input, so 1 will be treated as 1 +tinycolor.fromRatio = function(color, opts) { + if (typeof color == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } + else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; } - if(h > 0) { - v = visit(node.key, node.value) - if(v) { return v } + + return tinycolor(color, opts); +}; + +// Given a string or object, convert that input to RGB +// Possible string inputs: +// +// "red" +// "#f00" or "f00" +// "#ff0000" or "ff0000" +// "#ff000000" or "ff000000" +// "rgb 255 0 0" or "rgb (255, 0, 0)" +// "rgb 1.0 0 0" or "rgb (1, 0, 0)" +// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" +// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" +// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" +// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" +// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" +// +function inputToRGB(color) { + + var rgb = { r: 0, g: 0, b: 0 }; + var a = 1; + var ok = false; + var format = false; + + if (typeof color == "string") { + color = stringInputToObject(color); } - } - if(h > 0 && node.right) { - return doVisit(lo, hi, compare, visit, node.right) - } -} + if (typeof color == "object") { + if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { + color.s = convertToPercentage(color.s); + color.v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, color.s, color.v); + ok = true; + format = "hsv"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { + color.s = convertToPercentage(color.s); + color.l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, color.s, color.l); + ok = true; + format = "hsl"; + } -proto.forEach = function rbTreeForEach(visit, lo, hi) { - if(!this.root) { - return - } - switch(arguments.length) { - case 1: - return doVisitFull(visit, this.root) - break + if (color.hasOwnProperty("a")) { + a = color.a; + } + } - case 2: - return doVisitHalf(lo, this._compare, visit, this.root) - break + a = boundAlpha(a); - case 3: - if(this._compare(lo, hi) >= 0) { - return - } - return doVisit(lo, hi, this._compare, visit, this.root) - break - } + return { + ok: ok, + format: color.format || format, + r: mathMin(255, mathMax(rgb.r, 0)), + g: mathMin(255, mathMax(rgb.g, 0)), + b: mathMin(255, mathMax(rgb.b, 0)), + a: a + }; } -//First item in list -Object.defineProperty(proto, "begin", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.left - } - return new RedBlackTreeIterator(this, stack) - } -}) -//Last item in list -Object.defineProperty(proto, "end", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.right - } - return new RedBlackTreeIterator(this, stack) - } -}) +// Conversion Functions +// -------------------- -//Find the ith item in the tree -proto.at = function(idx) { - if(idx < 0) { - return new RedBlackTreeIterator(this, []) - } - var n = this.root - var stack = [] - while(true) { - stack.push(n) - if(n.left) { - if(idx < n.left._count) { - n = n.left - continue - } - idx -= n.left._count - } - if(!idx) { - return new RedBlackTreeIterator(this, stack) - } - idx -= 1 - if(n.right) { - if(idx >= n.right._count) { - break - } - n = n.right - } else { - break - } - } - return new RedBlackTreeIterator(this, []) +// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: +// + +// `rgbToRgb` +// Handle bounds / percentage checking to conform to CSS color spec +// +// *Assumes:* r, g, b in [0, 255] or [0, 1] +// *Returns:* { r, g, b } in [0, 255] +function rgbToRgb(r, g, b){ + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; } -proto.ge = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d <= 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} +// `rgbToHsl` +// Converts an RGB color value to HSL. +// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] +// *Returns:* { h, s, l } in [0,1] +function rgbToHsl(r, g, b) { -proto.gt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d < 0) { - last_ptr = stack.length + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, l = (max + min) / 2; + + if(max == min) { + h = s = 0; // achromatic } - if(d < 0) { - n = n.left - } else { - n = n.right + else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + + h /= 6; } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + + return { h: h, s: s, l: l }; } -proto.lt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d > 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right +// `hslToRgb` +// Converts an HSL color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hslToRgb(h, s, l) { + var r, g, b; + + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + + function hue2rgb(p, q, t) { + if(t < 0) t += 1; + if(t > 1) t -= 1; + if(t < 1/6) return p + (q - p) * 6 * t; + if(t < 1/2) return q; + if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} -proto.le = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d >= 0) { - last_ptr = stack.length + if(s === 0) { + r = g = b = l; // achromatic } - if(d < 0) { - n = n.left - } else { - n = n.right + else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + + return { r: r * 255, g: g * 255, b: b * 255 }; } -//Finds the item with key if it exists -proto.find = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d === 0) { - return new RedBlackTreeIterator(this, stack) +// `rgbToHsv` +// Converts an RGB color value to HSV +// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] +// *Returns:* { h, s, v } in [0,1] +function rgbToHsv(r, g, b) { + + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, v = max; + + var d = max - min; + s = max === 0 ? 0 : d / max; + + if(max == min) { + h = 0; // achromatic } - if(d <= 0) { - n = n.left - } else { - n = n.right + else { + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; } - } - return new RedBlackTreeIterator(this, []) + return { h: h, s: s, v: v }; } -//Removes item with key from tree -proto.remove = function(key) { - var iter = this.find(key) - if(iter) { - return iter.remove() - } - return this +// `hsvToRgb` +// Converts an HSV color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + + var i = math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + + return { r: r * 255, g: g * 255, b: b * 255 }; } -//Returns the item at `key` -proto.get = function(key) { - var cmp = this._compare - var n = this.root - while(n) { - var d = cmp(key, n.key) - if(d === 0) { - return n.value - } - if(d <= 0) { - n = n.left - } else { - n = n.right +// `rgbToHex` +// Converts an RGB color to hex +// Assumes r, g, and b are contained in the set [0, 255] +// Returns a 3 or 6 character hex +function rgbToHex(r, g, b, allow3Char) { + + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } - } - return + + return hex.join(""); } -//Iterator for red black tree -function RedBlackTreeIterator(tree, stack) { - this.tree = tree - this._stack = stack +// `rgbaToHex` +// Converts an RGBA color plus alpha transparency to hex +// Assumes r, g, b and a are contained in the set [0, 255] +// Returns an 8 character hex +function rgbaToHex(r, g, b, a) { + + var hex = [ + pad2(convertDecimalToHex(a)), + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + return hex.join(""); } -var iproto = RedBlackTreeIterator.prototype +// `equals` +// Can be called with any tinycolor input +tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) { return false; } + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); +}; -//Test if iterator is valid -Object.defineProperty(iproto, "valid", { - get: function() { - return this._stack.length > 0 - } -}) +tinycolor.random = function() { + return tinycolor.fromRatio({ + r: mathRandom(), + g: mathRandom(), + b: mathRandom() + }); +}; -//Node of the iterator -Object.defineProperty(iproto, "node", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1] - } - return null - }, - enumerable: true -}) -//Makes a copy of an iterator -iproto.clone = function() { - return new RedBlackTreeIterator(this.tree, this._stack.slice()) +// Modification Functions +// ---------------------- +// Thanks to less.js for some of the basics here +// + +function desaturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); } -//Swaps two nodes -function swapNode(n, v) { - n.key = v.key - n.value = v.value - n.left = v.left - n.right = v.right - n._color = v._color - n._count = v._count +function saturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); } -//Fix up a double black node in a tree -function fixDoubleBlack(stack) { - var n, p, s, z - for(var i=stack.length-1; i>=0; --i) { - n = stack[i] - if(i === 0) { - n._color = BLACK - return - } - //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) - p = stack[i-1] - if(p.left === n) { - //console.log("left child") - s = p.right - if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.right = cloneNode(s) - z = s.right = cloneNode(s.right) - p.right = s.left - s.left = p - s.right = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - return - } else if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red") - s = p.right = cloneNode(s) - z = s.left = cloneNode(s.left) - p.right = z.left - s.left = z.right - z.left = p - z.right = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = z - } else { - pp.right = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent", p.right.value) - p._color = BLACK - p.right = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent", p.right.value) - p.right = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.right = s.left - s.left = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } else { - //console.log("right child") - s = p.left - if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red", p.value, p._color) - s = p.left = cloneNode(s) - z = s.left = cloneNode(s.left) - p.left = s.right - s.right = p - s.left = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - return - } else if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.left = cloneNode(s) - z = s.right = cloneNode(s.right) - p.left = z.right - s.right = z.left - z.right = p - z.left = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = z - } else { - pp.left = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent") - p._color = BLACK - p.left = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent") - p.left = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.left = s.right - s.right = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } - } +function greyscale(color) { + return tinycolor(color).desaturate(100); +} + +function lighten (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); } -//Removes item at iterator from tree -iproto.remove = function() { - var stack = this._stack - if(stack.length === 0) { - return this.tree - } - //First copy path to node - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - var n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - } +function brighten(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var rgb = tinycolor(color).toRgb(); + rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); + rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); + rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); + return tinycolor(rgb); +} - //Get node - n = cstack[cstack.length-1] - //console.log("start remove: ", n.value) +function darken (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} - //If not leaf, then swap with previous node - if(n.left && n.right) { - //console.log("moving to leaf") +// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. +// Values outside of this range will be wrapped into this range. +function spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (mathRound(hsl.h) + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); +} - //First walk to previous leaf - var split = cstack.length - n = n.left - while(n.right) { - cstack.push(n) - n = n.right - } - //Copy path to leaf - var v = cstack[split-1] - cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) - cstack[split-1].key = n.key - cstack[split-1].value = n.value +// Combination Functions +// --------------------- +// Thanks to jQuery xColor for some of the ideas behind these +// - //Fix up stack - for(var i=cstack.length-2; i>=split; --i) { - n = cstack[i] - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - cstack[split-1].left = cstack[split] - } - //console.log("stack=", cstack.map(function(v) { return v.value })) +function complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); +} - //Remove leaf node - n = cstack[cstack.length-1] - if(n._color === RED) { - //Easy case: removing red leaf - //console.log("RED leaf") - var p = cstack[cstack.length-2] - if(p.left === n) { - p.left = null - } else if(p.right === n) { - p.right = null - } - cstack.pop() - for(var i=0; i> 1)) + 720) % 360; --results; ) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); } - } - return new RedBlackTree(this.tree._compare, cstack[0]) + return ret; } -//Returns key -Object.defineProperty(iproto, "key", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].key +function monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, s = hsv.s, v = hsv.v; + var ret = []; + var modification = 1 / results; + + while (results--) { + ret.push(tinycolor({ h: h, s: s, v: v})); + v = (v + modification) % 1; } - return - }, - enumerable: true -}) -//Returns value -Object.defineProperty(iproto, "value", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].value + return ret; +} + +// Utility Functions +// --------------------- + +tinycolor.mix = function(color1, color2, amount) { + amount = (amount === 0) ? 0 : (amount || 50); + + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + + var p = amount / 100; + var w = p * 2 - 1; + var a = rgb2.a - rgb1.a; + + var w1; + + if (w * a == -1) { + w1 = w; + } else { + w1 = (w + a) / (1 + w * a); } - return - }, - enumerable: true -}) + w1 = (w1 + 1) / 2; -//Returns the position of this iterator in the sorted list -Object.defineProperty(iproto, "index", { - get: function() { - var idx = 0 - var stack = this._stack - if(stack.length === 0) { - var r = this.tree.root - if(r) { - return r._count - } - return 0 - } else if(stack[stack.length-1].left) { - idx = stack[stack.length-1].left._count + var w2 = 1 - w1; + + var rgba = { + r: rgb2.r * w1 + rgb1.r * w2, + g: rgb2.g * w1 + rgb1.g * w2, + b: rgb2.b * w1 + rgb1.b * w2, + a: rgb2.a * p + rgb1.a * (1 - p) + }; + + return tinycolor(rgba); +}; + + +// Readability Functions +// --------------------- +// false +// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false +tinycolor.isReadable = function(color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + + out = false; + + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; } - for(var s=stack.length-2; s>=0; --s) { - if(stack[s+1] === stack[s].right) { - ++idx - if(stack[s].left) { - idx += stack[s].left._count + return out; + +}; + +// `mostReadable` +// Given a base color and a list of possible foreground or background +// colors for that base, returns the most readable color. +// Optionally returns Black or White if the most readable color is unreadable. +// *Example* +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" +tinycolor.mostReadable = function(baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size ; + args = args || {}; + includeFallbackColors = args.includeFallbackColors ; + level = args.level; + size = args.size; + + for (var i= 0; i < colorList.length ; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); } - } } - return idx - }, - enumerable: true -}) -//Advances iterator to next element in list -iproto.next = function() { - var stack = this._stack - if(stack.length === 0) { - return - } - var n = stack[stack.length-1] - if(n.right) { - n = n.right - while(n) { - stack.push(n) - n = n.left + if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { + return bestColor; } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].right === n) { - n = stack[stack.length-1] - stack.pop() + else { + args.includeFallbackColors=false; + return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); } - } -} +}; + + +// Big List of Colors +// ------------------ +// +var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; + +// Make it easy to access colors via `hexNames[hex]` +var hexNames = tinycolor.hexNames = flip(names); + -//Checks if iterator is at end of tree -Object.defineProperty(iproto, "hasNext", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].right) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].left === stack[s]) { - return true - } - } - return false - } -}) +// Utilities +// --------- -//Update value -iproto.update = function(value) { - var stack = this._stack - if(stack.length === 0) { - throw new Error("Can't update empty node!") - } - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) +// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` +function flip(o) { + var flipped = { }; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } } - } - return new RedBlackTree(this.tree._compare, cstack[0]) + return flipped; } -//Moves iterator backward one element -iproto.prev = function() { - var stack = this._stack - if(stack.length === 0) { - return - } - var n = stack[stack.length-1] - if(n.left) { - n = n.left - while(n) { - stack.push(n) - n = n.right - } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].left === n) { - n = stack[stack.length-1] - stack.pop() +// Return a valid alpha value [0,1] with all invalid values being set to 1 +function boundAlpha(a) { + a = parseFloat(a); + + if (isNaN(a) || a < 0 || a > 1) { + a = 1; } - } + + return a; } -//Checks if iterator is at start of tree -Object.defineProperty(iproto, "hasPrev", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].left) { - return true +// Take input from [0, n] and return it as [0, 1] +function bound01(n, max) { + if (isOnePointZero(n)) { n = "100%"; } + + var processPercent = isPercentage(n); + n = mathMin(max, mathMax(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].right === stack[s]) { - return true - } + + // Handle floating point rounding errors + if ((math.abs(n - max) < 0.000001)) { + return 1; } - return false - } -}) -//Default comparison function -function defaultCompare(a, b) { - if(a < b) { - return -1 - } - if(a > b) { - return 1 - } - return 0 + // Convert into [0, 1] range if it isn't already + return (n % max) / parseFloat(max); } -//Build a tree -function createRBTree(compare) { - return new RedBlackTree(compare || defaultCompare, null) +// Force a number between 0 and 1 +function clamp01(val) { + return mathMin(1, mathMax(0, val)); } -},{}],292:[function(require,module,exports){ -"use strict" -module.exports = createSlabDecomposition +// Parse a base-16 hex value into a base-10 integer +function parseIntFromHex(val) { + return parseInt(val, 16); +} -var bounds = require("binary-search-bounds") -var createRBTree = require("functional-red-black-tree") -var orient = require("robust-orientation") -var orderSegments = require("./lib/order-segments") +// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 +// +function isOnePointZero(n) { + return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; +} -function SlabDecomposition(slabs, coordinates, horizontal) { - this.slabs = slabs - this.coordinates = coordinates - this.horizontal = horizontal +// Check to see if string passed in is a percentage +function isPercentage(n) { + return typeof n === "string" && n.indexOf('%') != -1; } -var proto = SlabDecomposition.prototype +// Force a hex value to have 2 characters +function pad2(c) { + return c.length == 1 ? '0' + c : '' + c; +} -function compareHorizontal(e, y) { - return e.y - y +// Replace a decimal with it's percentage value +function convertToPercentage(n) { + if (n <= 1) { + n = (n * 100) + "%"; + } + + return n; } -function searchBucket(root, p) { - var lastNode = null - while(root) { - var seg = root.key - var l, r - if(seg[0][0] < seg[1][0]) { - l = seg[0] - r = seg[1] - } else { - l = seg[1] - r = seg[0] +// Converts a decimal to a hex value +function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); +} +// Converts a hex value to a decimal +function convertHexToDecimal(h) { + return (parseIntFromHex(h) / 255); +} + +var matchers = (function() { + + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + + return { + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; +})(); + +// `stringInputToObject` +// Permissive string parsing. Take in a number of formats, and output an object +// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` +function stringInputToObject(color) { + + color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; } - var o = orient(l, r, p) - if(o < 0) { - root = root.left - } else if(o > 0) { - if(p[0] !== seg[1][0]) { - lastNode = root - root = root.right - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } - } else { - if(p[0] !== seg[1][0]) { - return root - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } + else if (color == 'transparent') { + return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } - } - return lastNode -} -proto.castUp = function(p) { - var bucket = bounds.le(this.coordinates, p[0]) - if(bucket < 0) { - return -1 - } - var root = this.slabs[bucket] - var hitNode = searchBucket(this.slabs[bucket], p) - var lastHit = -1 - if(hitNode) { - lastHit = hitNode.value - } - //Edge case: need to handle horizontal segments (sucks) - if(this.coordinates[bucket] === p[0]) { - var lastSegment = null - if(hitNode) { - lastSegment = hitNode.key + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if ((match = matchers.rgb.exec(color))) { + return { r: match[1], g: match[2], b: match[3] }; } - if(bucket > 0) { - var otherHitNode = searchBucket(this.slabs[bucket-1], p) - if(otherHitNode) { - if(lastSegment) { - if(orderSegments(otherHitNode.key, lastSegment) > 0) { - lastSegment = otherHitNode.key - lastHit = otherHitNode.value - } - } else { - lastHit = otherHitNode.value - lastSegment = otherHitNode.key - } - } + if ((match = matchers.rgba.exec(color))) { + return { r: match[1], g: match[2], b: match[3], a: match[4] }; } - var horiz = this.horizontal[bucket] - if(horiz.length > 0) { - var hbucket = bounds.ge(horiz, p[1], compareHorizontal) - if(hbucket < horiz.length) { - var e = horiz[hbucket] - if(p[1] === e.y) { - if(e.closed) { - return e.index - } else { - while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { - hbucket = hbucket+1 - e = horiz[hbucket] - if(e.closed) { - return e.index - } - } - if(e.y === p[1] && !e.start) { - hbucket = hbucket+1 - if(hbucket >= horiz.length) { - return lastHit - } - e = horiz[hbucket] - } - } - } - //Check if e is above/below last segment - if(e.start) { - if(lastSegment) { - var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) - if(lastSegment[0][0] > lastSegment[1][0]) { - o = -o - } - if(o > 0) { - lastHit = e.index - } - } else { - lastHit = e.index - } - } else if(e.y !== p[1]) { - lastHit = e.index - } - } + if ((match = matchers.hsl.exec(color))) { + return { h: match[1], s: match[2], l: match[3] }; } - } - return lastHit + if ((match = matchers.hsla.exec(color))) { + return { h: match[1], s: match[2], l: match[3], a: match[4] }; + } + if ((match = matchers.hsv.exec(color))) { + return { h: match[1], s: match[2], v: match[3] }; + } + if ((match = matchers.hsva.exec(color))) { + return { h: match[1], s: match[2], v: match[3], a: match[4] }; + } + if ((match = matchers.hex8.exec(color))) { + return { + a: convertHexToDecimal(match[1]), + r: parseIntFromHex(match[2]), + g: parseIntFromHex(match[3]), + b: parseIntFromHex(match[4]), + format: named ? "name" : "hex8" + }; + } + if ((match = matchers.hex6.exec(color))) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if ((match = matchers.hex3.exec(color))) { + return { + r: parseIntFromHex(match[1] + '' + match[1]), + g: parseIntFromHex(match[2] + '' + match[2]), + b: parseIntFromHex(match[3] + '' + match[3]), + format: named ? "name" : "hex" + }; + } + + return false; } -function IntervalSegment(y, index, start, closed) { - this.y = y - this.index = index - this.start = start - this.closed = closed +function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || {"level":"AA", "size":"small"}; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return {"level":level, "size":size}; } -function Event(x, segment, create, index) { - this.x = x - this.segment = segment - this.create = create - this.index = index +// Node: Export function +if (typeof module !== "undefined" && module.exports) { + module.exports = tinycolor; +} +// AMD/requirejs: Define the module +else if (typeof define === 'function' && define.amd) { + define(function () {return tinycolor;}); +} +// Browser: Expose to window +else { + window.tinycolor = tinycolor; } +})(); -function createSlabDecomposition(segments) { - var numSegments = segments.length - var numEvents = 2 * numSegments - var events = new Array(numEvents) - for(var i=0; i>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; } - return false + return lo; } -} -function buildVerticalIndex(segments) { - var table = {} - for(var i=0; i 0 && coordinates[bucket] === p[0]) { - root = slabs[bucket-1] - } else { - return 1 + function object(topology, o) { + var absolute = transformAbsolute(topology.transform), + arcs = topology.arcs; + + function arc(i, points) { + if (points.length) points.pop(); + for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { + points.push(p = a[k].slice()); + absolute(p, k); } + if (i < 0) reverse(points, n); } - var lastOrientation = 1 - while(root) { - var s = root.key - var o = orient(p, s[0], s[1]) - if(s[0][0] < s[1][0]) { - if(o < 0) { - root = root.left - } else if(o > 0) { - lastOrientation = -1 - root = root.right - } else { - return 0 - } - } else { - if(o > 0) { - root = root.left - } else if(o < 0) { - lastOrientation = 1 - root = root.right - } else { - return 0 - } - } + + function point(p) { + p = p.slice(); + absolute(p, 0); + return p; } - return lastOrientation - } -} -function classifyEmpty(p) { - return 1 -} + function line(arcs) { + var points = []; + for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); + if (points.length < 2) points.push(points[0].slice()); + return points; + } -function createClassifyVertical(testVertical) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 + function ring(arcs) { + var points = line(arcs); + while (points.length < 4) points.push(points[0].slice()); + return points; } - return 1 - } -} -function createClassifyPointDegen(testVertical, testNormal) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 + function polygon(arcs) { + return arcs.map(ring); } - return testNormal(p) + + function geometry(o) { + var t = o.type; + return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} + : t in geometryType ? {type: t, coordinates: geometryType[t](o)} + : null; + } + + var geometryType = { + Point: function(o) { return point(o.coordinates); }, + MultiPoint: function(o) { return o.coordinates.map(point); }, + LineString: function(o) { return line(o.arcs); }, + MultiLineString: function(o) { return o.arcs.map(line); }, + Polygon: function(o) { return polygon(o.arcs); }, + MultiPolygon: function(o) { return o.arcs.map(polygon); } + }; + + return geometry(o); } -} -function preprocessPolygon(loops) { - //Compute number of loops - var numLoops = loops.length + function stitchArcs(topology, arcs) { + var stitchedArcs = {}, + fragmentByStart = {}, + fragmentByEnd = {}, + fragments = [], + emptyIndex = -1; - //Unpack segments - var segments = [] - var vsegments = [] - var ptr = 0 - for(var i=0; i 1) { + var geomsByArc = [], + geom; - //Check orientation of a polygon using exact arithmetic - function ccw(c) { - var n = c.length - var area = [0] - for(var j=0; j 0 - } + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs) { arcs.forEach(polygon); } + }; - //Extract all clockwise faces - faces = faces.filter(ccw) + geometry(o); - //Detect which loops are contained in one another to handle parent-of relation - var numFaces = faces.length - var parent = new Array(numFaces) - var containment = new Array(numFaces) - for(var i=0; i 0) { - var top = toVisit.pop() - var nbhd = fadj[top] - uniq(nbhd, function(a,b) { - return a-b - }) - var nnbhr = nbhd.length - var p = parity[top] - var polyline - if(p === 0) { - var c = faces[top] - polyline = [c] + function area(ring$$) { + return Math.abs(ring(object(topology, {type: "Polygon", arcs: [ring$$]}).coordinates[0])); } - for(var i=0; i= 0) { - continue - } - parity[f] = p^1 - toVisit.push(f) - if(p === 0) { - var c = faces[f] - if(!sharedBoundary(c)) { - c.reverse() - polyline.push(c) + + polygons.forEach(function(polygon) { + if (!polygon._) { + var component = [], + neighbors = [polygon]; + polygon._ = 1; + components.push(component); + while (polygon = neighbors.pop()) { + component.push(polygon); + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { + if (!polygon._) { + polygon._ = 1; + neighbors.push(polygon); + } + }); + }); + }); } } - } - if(p === 0) { - result.push(polyline) - } - } + }); - return result -} -},{"./lib/trim-leaves":282,"edges-to-adjacency-list":283,"planar-dual":284,"point-in-big-polygon":293,"robust-sum":262,"two-product":276,"uniq":279}],295:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],296:[function(require,module,exports){ -"use strict"; "use restrict"; + polygons.forEach(function(polygon) { + delete polygon._; + }); -module.exports = UnionFind; + return { + type: "MultiPolygon", + arcs: components.map(function(polygons) { + var arcs = [], n; -function UnionFind(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; i 1) { + for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { + if ((ki = area(arcs[i])) > k) { + t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; + } + } + } -UnionFind.prototype.find = function(x) { - var roots = this.roots; - while(roots[x] !== x) { - var y = roots[x]; - roots[x] = roots[y]; - x = y; + return arcs; + }) + }; } - return x; -} -UnionFind.prototype.link = function(x, y) { - var xr = this.find(x) - , yr = this.find(y); - if(xr === yr) { - return; - } - var ranks = this.ranks - , roots = this.roots - , xd = ranks[xr] - , yd = ranks[yr]; - if(xd < yd) { - roots[xr] = yr; - } else if(yd < xd) { - roots[yr] = xr; - } else { - roots[yr] = xr; - ++ranks[xr]; - } -} + function neighbors(objects) { + var indexesByArc = {}, // arc index -> array of object indexes + neighbors = objects.map(function() { return []; }); + function line(arcs, i) { + arcs.forEach(function(a) { + if (a < 0) a = ~a; + var o = indexesByArc[a]; + if (o) o.push(i); + else indexesByArc[a] = [i]; + }); + } -},{}],297:[function(require,module,exports){ -arguments[4][238][0].apply(exports,arguments) -},{"bit-twiddle":295,"dup":238,"union-find":296}],298:[function(require,module,exports){ -"use strict" + function polygon(arcs, i) { + arcs.forEach(function(arc) { line(arc, i); }); + } -module.exports = simplifyPolygon + function geometry(o, i) { + if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); + else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + } -var orient = require("robust-orientation") -var sc = require("simplicial-complex") + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } + }; -function errorWeight(base, a, b) { - var area = Math.abs(orient(base, a, b)) - var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2)) - return area / perim -} + objects.forEach(geometry); -function simplifyPolygon(cells, positions, minArea) { + for (var i in indexesByArc) { + for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { + for (var k = j + 1; k < m; ++k) { + var ij = indexes[j], ik = indexes[k], n; + if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); + if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); + } + } + } - var n = positions.length - var nc = cells.length - var inv = new Array(n) - var outv = new Array(n) - var weights = new Array(n) - var dead = new Array(n) - - //Initialize tables - for(var i=0; i 0) object = array[size], down(array[object._ = 0] = object, 0); + return removed; + }; - function heapParent(i) { - if(i & 1) { - return (i - 1) >> 1 - } - return (i >> 1) - 1 - } + heap.remove = function(removed) { + var i = removed._, object; + if (array[i] !== removed) return; // invalid request + if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); + return i; + }; - //Bubble element i down the heap - function heapDown(i) { - var w = heapWeight(i) - while(true) { - var tw = w - var left = 2*i + 1 - var right = 2*(i + 1) - var next = i - if(left < heapCount) { - var lw = heapWeight(left) - if(lw < tw) { - next = left - tw = lw - } - } - if(right < heapCount) { - var rw = heapWeight(right) - if(rw < tw) { - next = right - } - } - if(next === i) { - return i + function up(object, i) { + while (i > 0) { + var j = ((i + 1) >> 1) - 1, + parent = array[j]; + if (compareArea(object, parent) >= 0) break; + array[parent._ = i] = parent; + array[object._ = i = j] = object; } - heapSwap(i, next) - i = next } - } - //Bubbles element i up the heap - function heapUp(i) { - var w = heapWeight(i) - while(i > 0) { - var parent = heapParent(i) - if(parent >= 0) { - var pw = heapWeight(parent) - if(w < pw) { - heapSwap(i, parent) - i = parent - continue - } + function down(object, i) { + while (true) { + var r = (i + 1) << 1, + l = r - 1, + j = i, + child = array[j]; + if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; + if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; + if (j === i) break; + array[child._ = i] = child; + array[object._ = i = j] = object; } - return i } - } - //Pop minimum element - function heapPop() { - if(heapCount > 0) { - var head = heap[0] - heapSwap(0, heapCount-1) - heapCount -= 1 - heapDown(0) - return head - } - return -1 + return heap; } - //Update heap item i - function heapUpdate(i, w) { - var a = heap[i] - if(weights[a] === w) { - return i - } - weights[a] = -Infinity - heapUp(i) - heapPop() - weights[a] = w - heapCount += 1 - return heapUp(heapCount-1) - } + function presimplify(topology, triangleArea) { + var absolute = transformAbsolute(topology.transform), + relative = transformRelative(topology.transform), + heap = minAreaHeap(); - //Kills a vertex (assume vertex already removed from heap) - function kill(i) { - if(dead[i]) { - return - } - //Kill vertex - dead[i] = true - //Fixup topology - var s = inv[i] - var t = outv[i] - if(inv[t] >= 0) { - inv[t] = s - } - if(outv[s] >= 0) { - outv[s] = t - } + if (!triangleArea) triangleArea = cartesianTriangleArea; - //Update weights on s and t - if(index[s] >= 0) { - heapUpdate(index[s], computeWeight(s)) - } - if(index[t] >= 0) { - heapUpdate(index[t], computeWeight(t)) - } - } + topology.arcs.forEach(function(arc) { + var triangles = [], + maxArea = 0, + triangle, + i, + n, + p; - //Initialize weights and heap - var heap = [] - var index = new Array(n) - for(var i=0; i>1; i>=0; --i) { - heapDown(i) - } - - //Kill vertices - while(true) { - var hmin = heapPop() - if((hmin < 0) || (weights[hmin] > minArea)) { - break - } - kill(hmin) - } + // To store each point’s effective area, we create a new array rather than + // extending the passed-in point to workaround a Chrome/V8 bug (getting + // stuck in smi mode). For midpoints, the initial effective area of + // Infinity will be computed in the next step. + for (i = 0, n = arc.length; i < n; ++i) { + p = arc[i]; + absolute(arc[i] = [p[0], p[1], Infinity], i); + } - //Build collapsed vertex table - var npositions = [] - for(var i=0; i= 0 && tout >= 0 && tin !== tout) { - var cin = index[tin] - var cout = index[tout] - if(cin !== cout) { - ncells.push([ cin, cout ]) - } - } - }) + var version = "1.6.26"; - //Normalize result - sc.unique(sc.normalize(ncells)) + exports.version = version; + exports.mesh = mesh; + exports.meshArcs = meshArcs; + exports.merge = merge; + exports.mergeArcs = mergeArcs; + exports.feature = feature; + exports.neighbors = neighbors; + exports.presimplify = presimplify; - //Return final list of cells - return { - positions: npositions, - edges: ncells - } -} -},{"robust-orientation":259,"simplicial-complex":297}],299:[function(require,module,exports){ +})); +},{}],1044:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -50296,7 +52313,7 @@ module.exports = [ } ]; -},{}],300:[function(require,module,exports){ +},{}],1045:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -50549,7 +52566,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/cartesian/constants":410,"../../plots/font_attributes":423,"./arrow_paths":299}],301:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/cartesian/constants":1155,"../../plots/font_attributes":1168,"./arrow_paths":1044}],1046:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51478,7 +53495,7 @@ function lineIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { return {x: x1 + a * t, y: y1 + d * t}; } -},{"../../lib":382,"../../lib/setcursor":391,"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/cartesian/axes":405,"../color":303,"../dragelement":324,"../drawing":326,"./arrow_paths":299,"./attributes":300,"d3":113,"fast-isnumeric":117}],302:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../dragelement":1069,"../drawing":1071,"./arrow_paths":1044,"./attributes":1045,"d3":82,"fast-isnumeric":90}],1047:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51516,7 +53533,7 @@ exports.background = '#fff'; // gives back exactly lightLine if the other colors are defaults. exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); -},{}],303:[function(require,module,exports){ +},{}],1048:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51660,7 +53677,7 @@ function cleanOne(val) { return 'rgb(' + rgbStr + ')'; } -},{"./attributes":302,"fast-isnumeric":117,"tinycolor2":274}],304:[function(require,module,exports){ +},{"./attributes":1047,"fast-isnumeric":90,"tinycolor2":1042}],1049:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51855,7 +53872,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/cartesian/layout_attributes":414,"../../plots/font_attributes":423}],305:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/cartesian/layout_attributes":1159,"../../plots/font_attributes":1168}],1050:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51922,7 +53939,7 @@ module.exports = function colorbarDefaults(containerIn, containerOut, layout) { coerce('titleside'); }; -},{"../../lib":382,"../../plots/cartesian/tick_label_defaults":420,"../../plots/cartesian/tick_mark_defaults":421,"../../plots/cartesian/tick_value_defaults":422,"./attributes":304}],306:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/tick_label_defaults":1165,"../../plots/cartesian/tick_mark_defaults":1166,"../../plots/cartesian/tick_value_defaults":1167,"./attributes":1049}],1051:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52552,7 +54569,7 @@ module.exports = function draw(gd, id) { return component; }; -},{"../../lib":382,"../../lib/extend":377,"../../lib/setcursor":391,"../../plotly":402,"../../plots/cartesian/axes":405,"../../plots/cartesian/axis_defaults":406,"../../plots/cartesian/layout_attributes":414,"../../plots/cartesian/position_defaults":417,"../../plots/plots":454,"../color":303,"../dragelement":324,"../drawing":326,"../titles":366,"./attributes":304,"d3":113,"tinycolor2":274}],307:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/extend":1122,"../../lib/setcursor":1136,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../../plots/cartesian/axis_defaults":1151,"../../plots/cartesian/layout_attributes":1159,"../../plots/cartesian/position_defaults":1162,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"../titles":1111,"./attributes":1049,"d3":82,"tinycolor2":1042}],1052:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52572,7 +54589,7 @@ module.exports = function hasColorbar(container) { ); }; -},{}],308:[function(require,module,exports){ +},{}],1053:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52593,7 +54610,7 @@ exports.draw = require('./draw'); exports.hasColorbar = require('./has_colorbar'); -},{"./attributes":304,"./defaults":305,"./draw":306,"./has_colorbar":307}],309:[function(require,module,exports){ +},{"./attributes":1049,"./defaults":1050,"./draw":1051,"./has_colorbar":1052}],1054:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52666,7 +54683,7 @@ module.exports = { } }; -},{}],310:[function(require,module,exports){ +},{}],1055:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52731,7 +54748,7 @@ module.exports = function calc(trace, vals, containerStr, cLetter) { } }; -},{"../../lib":382,"./flip_scale":314,"./scales":321}],311:[function(require,module,exports){ +},{"../../lib":1127,"./flip_scale":1059,"./scales":1066}],1056:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52811,7 +54828,7 @@ module.exports = function makeColorScaleAttributes(context) { }; }; -},{"../../lib/extend":377,"./attributes":309}],312:[function(require,module,exports){ +},{"../../lib/extend":1122,"./attributes":1054}],1057:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52827,7 +54844,7 @@ var scales = require('./scales'); module.exports = scales.RdBu; -},{"./scales":321}],313:[function(require,module,exports){ +},{"./scales":1066}],1058:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52891,7 +54908,7 @@ module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, if(showScale) colorbarDefaults(containerIn, containerOut, layout); }; -},{"../../lib":382,"../colorbar/defaults":305,"../colorbar/has_colorbar":307,"./flip_scale":314,"./is_valid_scale":318,"fast-isnumeric":117}],314:[function(require,module,exports){ +},{"../../lib":1127,"../colorbar/defaults":1050,"../colorbar/has_colorbar":1052,"./flip_scale":1059,"./is_valid_scale":1063,"fast-isnumeric":90}],1059:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52916,7 +54933,7 @@ module.exports = function flipScale(scl) { return sclNew; }; -},{}],315:[function(require,module,exports){ +},{}],1060:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52956,7 +54973,7 @@ module.exports = function getScale(scl, dflt) { return scl; }; -},{"./default_scale":312,"./is_valid_scale_array":319,"./scales":321}],316:[function(require,module,exports){ +},{"./default_scale":1057,"./is_valid_scale_array":1064,"./scales":1066}],1061:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53002,7 +55019,7 @@ module.exports = function hasColorscale(trace, containerStr) { ); }; -},{"../../lib":382,"./is_valid_scale":318,"fast-isnumeric":117}],317:[function(require,module,exports){ +},{"../../lib":1127,"./is_valid_scale":1063,"fast-isnumeric":90}],1062:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53034,7 +55051,7 @@ exports.flipScale = require('./flip_scale'); exports.makeScaleFunction = require('./make_scale_function'); -},{"./attributes":309,"./calc":310,"./default_scale":312,"./defaults":313,"./flip_scale":314,"./get_scale":315,"./has_colorscale":316,"./is_valid_scale":318,"./make_scale_function":320,"./scales":321}],318:[function(require,module,exports){ +},{"./attributes":1054,"./calc":1055,"./default_scale":1057,"./defaults":1058,"./flip_scale":1059,"./get_scale":1060,"./has_colorscale":1061,"./is_valid_scale":1063,"./make_scale_function":1065,"./scales":1066}],1063:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53055,7 +55072,7 @@ module.exports = function isValidScale(scl) { else return isValidScaleArray(scl); }; -},{"./is_valid_scale_array":319,"./scales":321}],319:[function(require,module,exports){ +},{"./is_valid_scale_array":1064,"./scales":1066}],1064:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53090,7 +55107,7 @@ module.exports = function isValidScaleArray(scl) { } }; -},{"tinycolor2":274}],320:[function(require,module,exports){ +},{"tinycolor2":1042}],1065:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53139,7 +55156,7 @@ module.exports = function makeScaleFunction(scl, cmin, cmax) { }; }; -},{"../../lib":382,"../color":303,"d3":113,"fast-isnumeric":117,"tinycolor2":274}],321:[function(require,module,exports){ +},{"../../lib":1127,"../color":1048,"d3":82,"fast-isnumeric":90,"tinycolor2":1042}],1066:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53270,7 +55287,7 @@ module.exports = { ] }; -},{}],322:[function(require,module,exports){ +},{}],1067:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53303,7 +55320,7 @@ module.exports = function align(v, dv, v0, v1, anchor) { return vc; }; -},{}],323:[function(require,module,exports){ +},{}],1068:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53341,7 +55358,7 @@ module.exports = function getCursor(x, y, xanchor, yanchor) { return cursorset[y][x]; }; -},{"../../lib":382}],324:[function(require,module,exports){ +},{"../../lib":1127}],1069:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53510,7 +55527,7 @@ function finishDrag(gd) { if(gd._replotPending) Plotly.plot(gd); } -},{"../../lib":382,"../../plotly":402,"../../plots/cartesian/constants":410,"./align":322,"./cursor":323,"./unhover":325}],325:[function(require,module,exports){ +},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/constants":1155,"./align":1067,"./cursor":1068,"./unhover":1070}],1070:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53561,7 +55578,7 @@ unhover.raw = function unhoverRaw(gd, evt) { gd._hoverdata = undefined; }; -},{"../../lib/events":376}],326:[function(require,module,exports){ +},{"../../lib/events":1121}],1071:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53610,16 +55627,61 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya) { - s.each(function(d) { +drawing.translatePoints = function(s, xa, ya, trace, transitionConfig, joinDirection) { + + var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; + + if (hasTransition) { + var size = s.size(); + } + + s.each(function(d, i) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), y = d.yp || ya.c2p(d.y), p = d3.select(this); if(isNumeric(x) && isNumeric(y)) { // for multiline text this works better - if(this.nodeName === 'text') p.attr('x', x).attr('y', y); - else p.attr('transform', 'translate(' + x + ',' + y + ')'); + if(this.nodeName==='text') { + p.attr('x',x).attr('y',y); + } else { + if (hasTransition) { + var trans; + if (!joinDirection) { + trans = p.transition() + .delay(transitionConfig.delay + transitionConfig.cascade / size * i) + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } + } else if (joinDirection === -1) { + trans = p.style('opacity', 1) + .transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .style('opacity', 0) + .remove(); + } else if (joinDirection === 1) { + trans = p.attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } + + trans.style('opacity', 0) + .transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .style('opacity', 1) + } + + } else { + p.attr('transform', 'translate('+x+','+y+')'); + } + } } else p.remove(); }); @@ -53782,7 +55844,7 @@ drawing.pointStyle = function(s, trace) { markerScale = drawing.tryColorscale(marker, markerIn, ''), lineScale = drawing.tryColorscale(marker, markerIn, 'line.'); - s.each(function(d) { + s.each(function(d, i) { // 'so' is suspected outliers, for box plots var fillColor, lineColor, @@ -53799,11 +55861,11 @@ drawing.pointStyle = function(s, trace) { if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(Array.isArray(markerLine.color)) lineColor = Color.defaultLine; + else if(Array.isArray(markerLine.color)) lineColor = marker.color[i]; else lineColor = markerLine.color; if('mc' in d) fillColor = d.mcc = markerScale(d.mc); - else if(Array.isArray(marker.color)) fillColor = Color.defaultLine; + else if(Array.isArray(marker.color)) fillColor = marker.color[i]; else fillColor = marker.color || 'rgba(0,0,0,0)'; } @@ -54124,7 +56186,7 @@ drawing.setClipUrl = function(s, localId) { s.attr('clip-path', 'url(' + url + ')'); }; -},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../../lib/svg_text_utils":395,"../../plots/plots":454,"../../traces/scatter/make_bubble_size_func":569,"../../traces/scatter/subtypes":575,"../color":303,"../colorscale":317,"./symbol_defs":327,"d3":113,"fast-isnumeric":117}],327:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plots/plots":1199,"../../traces/scatter/make_bubble_size_func":1315,"../../traces/scatter/subtypes":1322,"../color":1048,"../colorscale":1062,"./symbol_defs":1072,"d3":82,"fast-isnumeric":90}],1072:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54600,7 +56662,7 @@ module.exports = { } }; -},{"d3":113}],328:[function(require,module,exports){ +},{"d3":82}],1073:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54742,7 +56804,7 @@ module.exports = { } }; -},{}],329:[function(require,module,exports){ +},{}],1074:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54805,7 +56867,7 @@ function calcOneAxis(calcTrace, trace, axis, coord) { Axes.expand(axis, vals, {padded: true}); } -},{"../../plots/cartesian/axes":405,"../../plots/plots":454,"./compute_error":330,"fast-isnumeric":117}],330:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"./compute_error":1075,"fast-isnumeric":90}],1075:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54901,7 +56963,7 @@ function makeComputeErrorValue(type, value) { } } -},{}],331:[function(require,module,exports){ +},{}],1076:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54978,7 +57040,7 @@ module.exports = function(traceIn, traceOut, defaultColor, opts) { } }; -},{"../../lib":382,"../../plots/plots":454,"./attributes":328,"fast-isnumeric":117}],332:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1073,"fast-isnumeric":90}],1077:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55037,7 +57099,7 @@ errorBars.hoverInfo = function(calcPoint, trace, hoverPoint) { } }; -},{"./attributes":328,"./calc":329,"./defaults":331,"./plot":333,"./style":334}],333:[function(require,module,exports){ +},{"./attributes":1073,"./calc":1074,"./defaults":1076,"./plot":1078,"./style":1079}],1078:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55158,7 +57220,7 @@ function errorCoords(d, xa, ya) { return out; } -},{"../../lib":382,"../../traces/scatter/subtypes":575,"d3":113,"fast-isnumeric":117}],334:[function(require,module,exports){ +},{"../../lib":1127,"../../traces/scatter/subtypes":1322,"d3":82,"fast-isnumeric":90}],1079:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55195,7 +57257,7 @@ module.exports = function style(traces) { }); }; -},{"../color":303,"d3":113}],335:[function(require,module,exports){ +},{"../color":1048,"d3":82}],1080:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55355,7 +57417,7 @@ module.exports = { } }; -},{"../../plots/cartesian/constants":410}],336:[function(require,module,exports){ +},{"../../plots/cartesian/constants":1155}],1081:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55421,7 +57483,7 @@ function imageDefaults(imageIn, imageOut, fullLayout) { return imageOut; } -},{"../../lib":382,"../../plots/cartesian/axes":405,"./attributes":335}],337:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./attributes":1080}],1082:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55594,7 +57656,7 @@ module.exports = function draw(gd) { imagesAbove.each(applyAttributes); }; -},{"../../plots/cartesian/axes":405,"../drawing":326,"d3":113}],338:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../drawing":1071,"d3":82}],1083:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55617,7 +57679,7 @@ module.exports = { supplyLayoutDefaults: supplyLayoutDefaults }; -},{"./attributes":335,"./defaults":336,"./draw":337}],339:[function(require,module,exports){ +},{"./attributes":1080,"./defaults":1081,"./draw":1082}],1084:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55666,7 +57728,7 @@ exports.isMiddleAnchor = function isMiddleAnchor(opts) { ); }; -},{}],340:[function(require,module,exports){ +},{}],1085:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55781,7 +57843,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/font_attributes":423,"../color/attributes":302}],341:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047}],1086:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55799,7 +57861,7 @@ module.exports = { scrollBarMargin: 4 }; -},{}],342:[function(require,module,exports){ +},{}],1087:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55891,7 +57953,7 @@ module.exports = function legendDefaults(layoutIn, layoutOut, fullData) { Lib.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -},{"../../lib":382,"../../plots/plots":454,"./attributes":340,"./helpers":345}],343:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1085,"./helpers":1090}],1088:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56542,7 +58604,7 @@ function expandHorizontalMargin(gd) { }); } -},{"../../lib":382,"../../plotly":402,"../../plots/plots":454,"../color":303,"../dragelement":324,"../drawing":326,"./anchor_utils":339,"./constants":341,"./get_legend_data":344,"./helpers":345,"./style":347,"d3":113}],344:[function(require,module,exports){ +},{"../../lib":1127,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"./anchor_utils":1084,"./constants":1086,"./get_legend_data":1089,"./helpers":1090,"./style":1092,"d3":82}],1089:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56648,7 +58710,7 @@ module.exports = function getLegendData(calcdata, opts) { return legendData; }; -},{"../../plots/plots":454,"./helpers":345}],345:[function(require,module,exports){ +},{"../../plots/plots":1199,"./helpers":1090}],1090:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56679,7 +58741,7 @@ exports.isReversed = function isReversed(legendLayout) { return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; -},{"../../plots/plots":454}],346:[function(require,module,exports){ +},{"../../plots/plots":1199}],1091:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56702,7 +58764,7 @@ legend.draw = require('./draw'); legend.style = require('./style'); -},{"./attributes":340,"./defaults":342,"./draw":343,"./style":347}],347:[function(require,module,exports){ +},{"./attributes":1085,"./defaults":1087,"./draw":1088,"./style":1092}],1092:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56924,7 +58986,7 @@ function stylePies(d) { if(pts.size()) pts.call(stylePie, d[0], trace); } -},{"../../lib":382,"../../plots/plots":454,"../../traces/pie/style_one":554,"../../traces/scatter/subtypes":575,"../color":303,"../drawing":326,"d3":113}],348:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"../../traces/pie/style_one":1299,"../../traces/scatter/subtypes":1322,"../color":1048,"../drawing":1071,"d3":82}],1093:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57451,7 +59513,7 @@ modeBarButtons.resetViews = { } }; -},{"../../../build/ploticon":2,"../../lib":382,"../../lib/setcursor":391,"../../plotly":402,"../../snapshot/download":469}],349:[function(require,module,exports){ +},{"../../../build/ploticon":2,"../../lib":1127,"../../lib/setcursor":1136,"../../plotly":1147,"../../snapshot/download":1214}],1094:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57741,7 +59803,7 @@ function createModeBar(gd, buttons) { module.exports = createModeBar; -},{"../../../build/ploticon":2,"../../lib":382,"d3":113}],350:[function(require,module,exports){ +},{"../../../build/ploticon":2,"../../lib":1127,"d3":82}],1095:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57969,7 +60031,7 @@ function fillCustomButton(customButtons) { return customButtons; } -},{"../../plotly":402,"../../traces/scatter/subtypes":575,"./":349,"./buttons":348}],351:[function(require,module,exports){ +},{"../../plotly":1147,"../../traces/scatter/subtypes":1322,"./":1094,"./buttons":1093}],1096:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58068,7 +60130,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/font_attributes":423,"../color/attributes":302,"./button_attributes":352}],352:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047,"./button_attributes":1097}],1097:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58124,7 +60186,7 @@ module.exports = { } }; -},{}],353:[function(require,module,exports){ +},{}],1098:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58152,7 +60214,7 @@ module.exports = { activeColor: '#d3d3d3' }; -},{}],354:[function(require,module,exports){ +},{}],1099:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58239,7 +60301,7 @@ function getPosDflt(containerOut, layout, counterAxes) { return [containerOut.domain[0], posY + constants.yPad]; } -},{"../../lib":382,"./attributes":351,"./button_attributes":352,"./constants":353}],355:[function(require,module,exports){ +},{"../../lib":1127,"./attributes":1096,"./button_attributes":1097,"./constants":1098}],1100:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58514,7 +60576,7 @@ function reposition(gd, buttons, opts, axName) { }); } -},{"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/cartesian/axis_ids":407,"../../plots/plots":454,"../color":303,"../drawing":326,"../legend/anchor_utils":339,"./constants":353,"./get_update_object":356,"d3":113}],356:[function(require,module,exports){ +},{"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axis_ids":1152,"../../plots/plots":1199,"../color":1048,"../drawing":1071,"../legend/anchor_utils":1084,"./constants":1098,"./get_update_object":1101,"d3":82}],1101:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58572,7 +60634,7 @@ function getXRange(axisLayout, buttonLayout) { return [range0, range1]; } -},{"d3":113}],357:[function(require,module,exports){ +},{"d3":82}],1102:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58590,7 +60652,7 @@ exports.supplyLayoutDefaults = require('./defaults'); exports.draw = require('./draw'); -},{"./attributes":351,"./defaults":354,"./draw":355}],358:[function(require,module,exports){ +},{"./attributes":1096,"./defaults":1099,"./draw":1100}],1103:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58661,7 +60723,7 @@ module.exports = { } }; -},{"../color/attributes":302}],359:[function(require,module,exports){ +},{"../color/attributes":1047}],1104:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58957,7 +61019,7 @@ module.exports = function createSlider(gd) { }); }; -},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../../plotly":402,"../../plots/cartesian/axes":405,"./helpers":361,"./range_plot":363}],360:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"./helpers":1106,"./range_plot":1108}],1105:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59011,7 +61073,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, axName, coun } }; -},{"../../lib":382,"./attributes":358}],361:[function(require,module,exports){ +},{"../../lib":1127,"./attributes":1103}],1106:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59037,7 +61099,7 @@ exports.appendChildren = function appendChildren(el, children) { } }; -},{}],362:[function(require,module,exports){ +},{}],1107:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59094,7 +61156,7 @@ function draw(gd) { }); } -},{"../../plots/plots":454,"./create_slider":359,"./defaults":360}],363:[function(require,module,exports){ +},{"../../plots/plots":1199,"./create_slider":1104,"./defaults":1105}],1108:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59275,7 +61337,7 @@ function makeScatter(trace, pointPairs, w, h) { return [line, markers, fill]; } -},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../drawing":326,"../drawing/symbol_defs":327,"./helpers":361,"d3":113}],364:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../drawing":1071,"../drawing/symbol_defs":1072,"./helpers":1106,"d3":82}],1109:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59433,7 +61495,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../traces/scatter/attributes":556,"../annotations/attributes":300}],365:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../traces/scatter/attributes":1301,"../annotations/attributes":1045}],1110:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59996,7 +62058,7 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { if(max >= min) return [min, max]; } -},{"../../lib":382,"../../plotly":402,"../../plots/cartesian/axes":405,"../color":303,"../drawing":326,"./attributes":364,"fast-isnumeric":117}],366:[function(require,module,exports){ +},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../drawing":1071,"./attributes":1109,"fast-isnumeric":90}],1111:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60226,7 +62288,7 @@ Titles.draw = function(gd, titleClass, options) { el.classed('js-placeholder', isplaceholder); }; -},{"../../lib":382,"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/plots":454,"../color":303,"../drawing":326,"d3":113,"fast-isnumeric":117}],367:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../drawing":1071,"d3":82,"fast-isnumeric":90}],1112:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60247,7 +62309,7 @@ module.exports = { longdashdot: [8, 1, 1, 1] }; -},{}],368:[function(require,module,exports){ +},{}],1113:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60268,7 +62330,7 @@ module.exports = { longdashdot: [[0.5, 0.7, 0.8, 1], 10] }; -},{}],369:[function(require,module,exports){ +},{}],1114:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60291,7 +62353,7 @@ module.exports = { x: '❌' }; -},{}],370:[function(require,module,exports){ +},{}],1115:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60315,7 +62377,7 @@ exports.svgAttrs = { 'xmlns:xlink': exports.xlink }; -},{}],371:[function(require,module,exports){ +},{}],1116:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60339,6 +62401,7 @@ exports.version = '1.13.0'; exports.plot = Plotly.plot; exports.newPlot = Plotly.newPlot; exports.restyle = Plotly.restyle; +exports.animate = Plotly.animate; exports.relayout = Plotly.relayout; exports.redraw = Plotly.redraw; exports.extendTraces = Plotly.extendTraces; @@ -60365,7 +62428,7 @@ exports.Queue = Plotly.Queue; // export d3 used in the bundle exports.d3 = require('d3'); -},{"../build/ploticon":2,"./plot_api/set_plot_config":400,"./plot_api/to_image":401,"./plotly":402,"./snapshot/download":469,"d3":113}],372:[function(require,module,exports){ +},{"../build/ploticon":2,"./plot_api/set_plot_config":1145,"./plot_api/to_image":1146,"./plotly":1147,"./snapshot/download":1214,"d3":82}],1117:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60398,7 +62461,7 @@ if(typeof MathJax !== 'undefined') { exports.MathJax = false; } -},{}],373:[function(require,module,exports){ +},{}],1118:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60415,7 +62478,7 @@ module.exports = function arrayToCalcItem(traceAttr, calcItem, calcAttr, i) { if(Array.isArray(traceAttr)) calcItem[calcAttr] = traceAttr[i]; }; -},{}],374:[function(require,module,exports){ +},{}],1119:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60728,7 +62791,7 @@ exports.coerceFont = function(coerce, attr, dfltObj) { return out; }; -},{"../components/colorscale/get_scale":315,"../components/colorscale/scales":321,"./nested_property":386,"fast-isnumeric":117,"tinycolor2":274}],375:[function(require,module,exports){ +},{"../components/colorscale/get_scale":1060,"../components/colorscale/scales":1066,"./nested_property":1131,"fast-isnumeric":90,"tinycolor2":1042}],1120:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61067,7 +63130,7 @@ exports.parseDate = function(v) { return out; }; -},{"../lib":382,"d3":113,"fast-isnumeric":117}],376:[function(require,module,exports){ +},{"../lib":1127,"d3":82,"fast-isnumeric":90}],1121:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61201,7 +63264,7 @@ var Events = { module.exports = Events; -},{"events":55}],377:[function(require,module,exports){ +},{"events":69}],1122:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61281,7 +63344,7 @@ function _extend(inputs, isDeep, keepAllKeys) { return target; } -},{"./is_plain_object.js":383}],378:[function(require,module,exports){ +},{"./is_plain_object.js":1128}],1123:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61305,7 +63368,7 @@ module.exports = function filterVisible(dataIn) { return dataOut; }; -},{}],379:[function(require,module,exports){ +},{}],1124:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61364,7 +63427,7 @@ function countryNameToISO3(countryName) { Lib.warn('Unrecognized country name: ' + countryName + '.'); } -},{"../lib":382,"country-regex":108}],380:[function(require,module,exports){ +},{"../lib":1127,"country-regex":81}],1125:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61443,7 +63506,7 @@ function formatColor(containerIn, opacityIn, len) { module.exports = formatColor; -},{"../components/color/attributes":302,"../components/colorscale/make_scale_function":320,"./str2rgbarray":394,"fast-isnumeric":117,"tinycolor2":274}],381:[function(require,module,exports){ +},{"../components/color/attributes":1047,"../components/colorscale/make_scale_function":1065,"./str2rgbarray":1139,"fast-isnumeric":90,"tinycolor2":1042}],1126:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61517,7 +63580,7 @@ function convertHTMLToUnicode(html) { module.exports = convertHTMLToUnicode; -},{"superscript-text":263}],382:[function(require,module,exports){ +},{"superscript-text":1041}],1127:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62106,7 +64169,93 @@ lib.numSeparate = function(value, separators) { return x1 + x2; }; -},{"./coerce":374,"./dates":375,"./extend":377,"./is_plain_object":383,"./loggers":384,"./matrix":385,"./nested_property":386,"./notifier":387,"./search":390,"./stats":393,"d3":113}],383:[function(require,module,exports){ +/* + * Deep copy of an object, subject to some caveats. Adapted from + * http://stackoverflow.com/questions/10728412/in-javascript-when-performing-a-deep-copy-how-do-i-avoid-a-cycle-due-to-a-pro#answer-10729242 + * + * It does some basics like avoiding infinite loops, but leaves some gaps + * regarding prototypes and functions. But those shouldn't be part of the + * layout anyway, which is the intended use. + * + * @param {object} object the object to be cloned + * @param {function} shallowFilter a callback executed on each attribute name + * @param {Array} path a stack representing the current attr path + * + * @return {object} the cloned object + */ +lib.deepClone = function deepClone (object, shallowFilter, path) { + var nextPath, isShallow; + var gdcc = "__getDeepCircularCopy__"; + if (object !== Object(object)) { + return object; // primitive value + } + + var set = gdcc in object; + var cache = object[gdcc]; + var result; + if (set && typeof cache == "function") { + return cache(); + } + // else + object[gdcc] = function () { return result; }; // overwrite + + if (object instanceof Array) { + result = []; + for (var i=0; i= 0; i--) { + if (gd.data[i][isClonedFlag]) continue; + + // Clone this trace if it's not already cloned. Otherwise the original input + // to Plotly.plot gets mangled and we can't use it again, which is inconvenient. + // Notably, this does *not* copy data arrays. + type = gd._fullData[i].type; + schema = Plotly.PlotSchema.get().traces[type] + gd.data[i] = Lib.deepCloneTrace(gd.data[i], schema); + gd.data[i][isClonedFlag] = true; + } +} + +},{"../components/color":1048,"../components/drawing":1071,"../components/errorbars":1077,"../components/images":1083,"../components/legend":1091,"../components/modebar/manage":1095,"../components/rangeselector":1102,"../components/rangeslider":1107,"../components/shapes":1110,"../components/titles":1111,"../constants/xmlns_namespaces":1115,"../lib":1127,"../lib/events":1121,"../lib/queue":1134,"../plotly":1147,"../plots/cartesian/graph_interact":1157,"../plots/plots":1199,"d3":82,"fast-isnumeric":90,"gl-mat4/fromQuat":237}],1143:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67095,7 +69445,7 @@ function defaultSetBackground(gd, bgColor) { catch(e) { Lib.error(e); } } -},{"../lib":382}],399:[function(require,module,exports){ +},{"../lib":1127}],1144:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67421,7 +69771,7 @@ function handleLinkedToArray(layoutAttributes) { PlotSchema.crawl(layoutAttributes, callback); } -},{"../lib":382,"../plotly":402,"../plots/plots":454,"../plots/polar/area_attributes":455,"../plots/polar/axis_attributes":456}],400:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147,"../plots/plots":1199,"../plots/polar/area_attributes":1200,"../plots/polar/axis_attributes":1201}],1145:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67447,7 +69797,7 @@ module.exports = function setPlotConfig(configObj) { return Lib.extendFlat(Plotly.defaultConfig, configObj); }; -},{"../lib":382,"../plotly":402}],401:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147}],1146:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67560,7 +69910,7 @@ function toImage(gd, opts) { module.exports = toImage; -},{"../lib":382,"../plotly":402,"../snapshot":471,"fast-isnumeric":117}],402:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147,"../snapshot":1216,"fast-isnumeric":90}],1147:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67647,7 +69997,7 @@ exports.PlotSchema = require('./plot_api/plot_schema'); // imaging routines exports.Snapshot = require('./snapshot'); -},{"../build/plotcss":1,"./components/annotations":301,"./components/color":303,"./components/colorbar":308,"./components/colorscale":317,"./components/drawing":326,"./components/errorbars":332,"./components/images":338,"./components/legend":346,"./components/modebar":349,"./components/shapes":365,"./fonts/mathjax_config":372,"./lib":382,"./lib/queue":389,"./lib/svg_text_utils":395,"./plot_api/plot_api":397,"./plot_api/plot_config":398,"./plot_api/plot_schema":399,"./plots/cartesian/axes":405,"./plots/cartesian/graph_interact":412,"./plots/plots":454,"./plots/polar/micropolar":457,"./snapshot":471,"./traces/scatter":565,"es6-promise":116}],403:[function(require,module,exports){ +},{"../build/plotcss":1,"./components/annotations":1046,"./components/color":1048,"./components/colorbar":1053,"./components/colorscale":1062,"./components/drawing":1071,"./components/errorbars":1077,"./components/images":1083,"./components/legend":1091,"./components/modebar":1094,"./components/shapes":1110,"./fonts/mathjax_config":1117,"./lib":1127,"./lib/queue":1134,"./lib/svg_text_utils":1140,"./plot_api/plot_api":1142,"./plot_api/plot_config":1143,"./plot_api/plot_schema":1144,"./plots/cartesian/axes":1150,"./plots/cartesian/graph_interact":1157,"./plots/plots":1199,"./plots/polar/micropolar":1202,"./snapshot":1216,"./traces/scatter":1310,"es6-promise":89}],1148:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67751,7 +70101,7 @@ module.exports = { } }; -},{}],404:[function(require,module,exports){ +},{}],1149:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67790,7 +70140,7 @@ module.exports = { } }; -},{}],405:[function(require,module,exports){ +},{}],1150:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69763,7 +72113,7 @@ function swapAxisAttrs(layout, key, xFullAxes, yFullAxes) { // rather than built-in % which gives a negative value for negative v function mod(v, d) { return ((v % d) + d) % d; } -},{"../../components/color":303,"../../components/drawing":326,"../../components/titles":366,"../../lib":382,"../../lib/svg_text_utils":395,"../../plotly":402,"./axis_ids":407,"./layout_attributes":414,"./layout_defaults":415,"./set_convert":419,"d3":113,"fast-isnumeric":117}],406:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"./axis_ids":1152,"./layout_attributes":1159,"./layout_defaults":1160,"./set_convert":1164,"d3":82,"fast-isnumeric":90}],1151:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70046,7 +72396,7 @@ function category(a) { return curvecats > curvenums * 2; } -},{"../../components/color/attributes":302,"../../lib":382,"../plots":454,"./axis_ids":407,"./category_order_defaults":408,"./clean_datum":409,"./layout_attributes":414,"./ordered_categories":416,"./set_convert":419,"./tick_label_defaults":420,"./tick_mark_defaults":421,"./tick_value_defaults":422,"fast-isnumeric":117,"tinycolor2":274}],407:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../lib":1127,"../plots":1199,"./axis_ids":1152,"./category_order_defaults":1153,"./clean_datum":1154,"./layout_attributes":1159,"./ordered_categories":1161,"./set_convert":1164,"./tick_label_defaults":1165,"./tick_mark_defaults":1166,"./tick_value_defaults":1167,"fast-isnumeric":90,"tinycolor2":1042}],1152:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70167,7 +72517,7 @@ exports.getFromTrace = function(gd, fullTrace, type) { return ax; }; -},{"../../lib":382,"../plots":454,"./constants":410}],408:[function(require,module,exports){ +},{"../../lib":1127,"../plots":1199,"./constants":1155}],1153:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70201,7 +72551,7 @@ module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, } }; -},{}],409:[function(require,module,exports){ +},{}],1154:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70240,7 +72590,7 @@ module.exports = function cleanDatum(c) { return c; }; -},{"../../lib":382,"fast-isnumeric":117}],410:[function(require,module,exports){ +},{"../../lib":1127,"fast-isnumeric":90}],1155:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70318,7 +72668,7 @@ module.exports = { REDRAWDELAY: 50 }; -},{}],411:[function(require,module,exports){ +},{}],1156:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70990,7 +73340,7 @@ function removeZoombox(gd) { .remove(); } -},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../lib":382,"../../lib/setcursor":391,"../../lib/svg_text_utils":395,"../../plotly":402,"./axes":405,"./constants":410,"./select":418,"d3":113,"tinycolor2":274}],412:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"./axes":1150,"./constants":1155,"./select":1163,"d3":82,"tinycolor2":1042}],1157:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72337,7 +74687,7 @@ fx.inbox = function(v0, v1) { return Infinity; }; -},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../lib":382,"../../lib/events":376,"../../lib/svg_text_utils":395,"./axes":405,"./constants":410,"./dragbox":411,"d3":113,"fast-isnumeric":117,"tinycolor2":274}],413:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/events":1121,"../../lib/svg_text_utils":1140,"./axes":1150,"./constants":1155,"./dragbox":1156,"d3":82,"fast-isnumeric":90,"tinycolor2":1042}],1158:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72351,6 +74701,8 @@ fx.inbox = function(v0, v1) { var Plots = require('../plots'); +var d3 = require('d3'); + var constants = require('./constants'); exports.name = 'cartesian'; @@ -72365,7 +74717,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd) { +exports.plot = function(gd, traces, transitionOpts) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -72378,6 +74730,9 @@ exports.plot = function(gd) { var cd = calcdata[i]; var trace = cd[0].trace; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { cdSubplot.push(cd); } @@ -72407,9 +74762,13 @@ exports.plot = function(gd) { cdSubplot = getCdSubplot(calcdata, subplot); // remove old traces, then redraw everything - // TODO: use enter/exit appropriately in the plot functions - // so we don't need this - should sometimes be a big speedup - if(subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove(); + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(subplotInfo.plot) { + subplotInfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + } for(var j = 0; j < modules.length; j++) { var _module = modules[j]; @@ -72419,12 +74778,13 @@ exports.plot = function(gd) { // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); - _module.plot(gd, subplotInfo, cdModule); + + _module.plot(gd, subplotInfo, cdModule, traces, transitionOpts); } } }; -},{"../plots":454,"./attributes":404,"./constants":410}],414:[function(require,module,exports){ +},{"../plots":1199,"./attributes":1149,"./constants":1155,"d3":82}],1159:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72937,7 +75297,7 @@ module.exports = { } }; -},{"../../components/color/attributes":302,"../../components/rangeselector/attributes":351,"../../components/rangeslider/attributes":358,"../../lib/extend":377,"../font_attributes":423,"./constants":410}],415:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../components/rangeselector/attributes":1096,"../../components/rangeslider/attributes":1103,"../../lib/extend":1122,"../font_attributes":1168,"./constants":1155}],1160:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73110,7 +75470,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { }); }; -},{"../../components/color":303,"../../components/rangeselector":357,"../../components/rangeslider":362,"../../lib":382,"../plots":454,"./axis_defaults":406,"./axis_ids":407,"./constants":410,"./layout_attributes":414,"./position_defaults":417}],416:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/rangeselector":1102,"../../components/rangeslider":1107,"../../lib":1127,"../plots":1199,"./axis_defaults":1151,"./axis_ids":1152,"./constants":1155,"./layout_attributes":1159,"./position_defaults":1162}],1161:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73189,7 +75549,7 @@ module.exports = function orderedCategories(axisLetter, categoryorder, categorya } }; -},{"d3":113}],417:[function(require,module,exports){ +},{"d3":82}],1162:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73254,7 +75614,7 @@ module.exports = function handlePositionDefaults(containerIn, containerOut, coer return containerOut; }; -},{"../../lib":382,"fast-isnumeric":117}],418:[function(require,module,exports){ +},{"../../lib":1127,"fast-isnumeric":90}],1163:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73454,7 +75814,7 @@ module.exports = function prepSelect(e, startX, startY, dragOptions, mode) { }; }; -},{"../../components/color":303,"../../lib/polygon":388,"./axes":405,"./constants":410}],419:[function(require,module,exports){ +},{"../../components/color":1048,"../../lib/polygon":1133,"./axes":1150,"./constants":1155}],1164:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73698,7 +76058,7 @@ module.exports = function setConvert(ax) { ax._forceTick0 = null; }; -},{"../../lib":382,"./axis_ids":407,"./clean_datum":409,"./constants":410,"d3":113,"fast-isnumeric":117}],420:[function(require,module,exports){ +},{"../../lib":1127,"./axis_ids":1152,"./clean_datum":1154,"./constants":1155,"d3":82,"fast-isnumeric":90}],1165:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73781,7 +76141,7 @@ function getShowAttrDflt(containerIn) { } } -},{"../../lib":382}],421:[function(require,module,exports){ +},{"../../lib":1127}],1166:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73814,7 +76174,7 @@ module.exports = function handleTickDefaults(containerIn, containerOut, coerce, } }; -},{"../../lib":382,"./layout_attributes":414}],422:[function(require,module,exports){ +},{"../../lib":1127,"./layout_attributes":1159}],1167:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73855,7 +76215,7 @@ module.exports = function handleTickValueDefaults(containerIn, containerOut, coe } }; -},{"fast-isnumeric":117}],423:[function(require,module,exports){ +},{"fast-isnumeric":90}],1168:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73897,7 +76257,7 @@ module.exports = { } }; -},{}],424:[function(require,module,exports){ +},{}],1169:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74055,7 +76415,7 @@ params.layerNameToAdjective = { // base layers drawn over choropleth params.baseLayersOverChoropleth = ['rivers', 'lakes']; -},{}],425:[function(require,module,exports){ +},{}],1170:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74549,7 +76909,7 @@ function createMockAxis(fullLayout) { return mockAxis; } -},{"../../components/color":303,"../../components/drawing":326,"../../constants/xmlns_namespaces":370,"../../lib/filter_visible":378,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"./constants":424,"./projections":432,"./set_scale":433,"./zoom":434,"./zoom_reset":435,"d3":113,"topojson":275}],426:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../constants/xmlns_namespaces":1115,"../../lib/filter_visible":1123,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"./constants":1169,"./projections":1177,"./set_scale":1178,"./zoom":1179,"./zoom_reset":1180,"d3":82,"topojson":1043}],1171:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74655,7 +77015,7 @@ exports.toSVG = function(gd) { } }; -},{"../../plots/plots":454,"./geo":425,"./layout/attributes":427,"./layout/defaults":430,"./layout/layout_attributes":431}],427:[function(require,module,exports){ +},{"../../plots/plots":1199,"./geo":1170,"./layout/attributes":1172,"./layout/defaults":1175,"./layout/layout_attributes":1176}],1172:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74683,7 +77043,7 @@ module.exports = { } }; -},{}],428:[function(require,module,exports){ +},{}],1173:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74746,7 +77106,7 @@ module.exports = { } }; -},{"../../../components/color/attributes":302}],429:[function(require,module,exports){ +},{"../../../components/color/attributes":1047}],1174:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74820,7 +77180,7 @@ module.exports = function supplyGeoAxisLayoutDefaults(geoLayoutIn, geoLayoutOut) } }; -},{"../../../lib":382,"../constants":424,"./axis_attributes":428}],430:[function(require,module,exports){ +},{"../../../lib":1127,"../constants":1169,"./axis_attributes":1173}],1175:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74939,7 +77299,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { ]; } -},{"../../subplot_defaults":460,"../constants":424,"./axis_defaults":429,"./layout_attributes":431}],431:[function(require,module,exports){ +},{"../../subplot_defaults":1205,"../constants":1169,"./axis_defaults":1174,"./layout_attributes":1176}],1176:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75198,7 +77558,7 @@ module.exports = { lataxis: geoAxesAttrs }; -},{"../../../components/color/attributes":302,"../constants":424,"./axis_attributes":428}],432:[function(require,module,exports){ +},{"../../../components/color/attributes":1047,"../constants":1169,"./axis_attributes":1173}],1177:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75644,7 +78004,7 @@ function addProjectionsToD3(d3) { module.exports = addProjectionsToD3; -},{}],433:[function(require,module,exports){ +},{}],1178:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75795,7 +78155,7 @@ function getBounds(projection, rangeBox) { return d3.geo.path().projection(projection).bounds(rangeBox); } -},{"./constants":424,"d3":113}],434:[function(require,module,exports){ +},{"./constants":1169,"d3":82}],1179:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76222,7 +78582,7 @@ function d3_eventDispatch(target) { return dispatch; } -},{"d3":113}],435:[function(require,module,exports){ +},{"d3":82}],1180:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76257,7 +78617,7 @@ function createGeoZoomReset(geo, geoLayout) { module.exports = createGeoZoomReset; -},{"../cartesian/graph_interact":412}],436:[function(require,module,exports){ +},{"../cartesian/graph_interact":1157}],1181:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76412,7 +78772,7 @@ function createCamera(scene) { return result; } -},{"mouse-change":241,"mouse-wheel":245}],437:[function(require,module,exports){ +},{"mouse-change":1004,"mouse-wheel":1008}],1182:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76655,7 +79015,7 @@ function createAxes2D(scene) { module.exports = createAxes2D; -},{"../../lib/html2unicode":381,"../../lib/str2rgbarray":394,"../../plotly":402}],438:[function(require,module,exports){ +},{"../../lib/html2unicode":1126,"../../lib/str2rgbarray":1139,"../../plotly":1147}],1183:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76768,7 +79128,7 @@ exports.toSVG = function(gd) { } }; -},{"../../constants/xmlns_namespaces":370,"../cartesian/attributes":404,"../plots":454,"./scene2d":439}],439:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../cartesian/attributes":1149,"../plots":1199,"./scene2d":1184}],1184:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77305,7 +79665,7 @@ proto.hoverFormatter = function(axisName, val) { return Axes.tickText(axis, axis.c2l(val), 'hover').text; }; -},{"../../lib/html2unicode":381,"../../lib/show_no_webgl_msg":392,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"./camera":436,"./convert":437,"gl-plot2d":165,"gl-select-box":195,"gl-spikes2d":215}],440:[function(require,module,exports){ +},{"../../lib/html2unicode":1126,"../../lib/show_no_webgl_msg":1137,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"./camera":1181,"./convert":1182,"gl-plot2d":452,"gl-select-box":937,"gl-spikes2d":938}],1185:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77548,7 +79908,7 @@ function createCamera(element, options) { return camera; } -},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],441:[function(require,module,exports){ +},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],1186:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77682,7 +80042,7 @@ function initAxes(gd, sceneLayout) { } } -},{"../../constants/xmlns_namespaces":370,"../plots":454,"./layout/attributes":442,"./layout/defaults":446,"./layout/layout_attributes":447,"./scene":451,"./set_convert":452}],442:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../plots":1199,"./layout/attributes":1187,"./layout/defaults":1191,"./layout/layout_attributes":1192,"./scene":1196,"./set_convert":1197}],1187:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77710,7 +80070,7 @@ module.exports = { } }; -},{}],443:[function(require,module,exports){ +},{}],1188:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77826,7 +80186,7 @@ module.exports = { zerolinewidth: axesAttrs.zerolinewidth }; -},{"../../../components/color":303,"../../../lib/extend":377,"../../cartesian/layout_attributes":414}],444:[function(require,module,exports){ +},{"../../../components/color":1048,"../../../lib/extend":1122,"../../cartesian/layout_attributes":1159}],1189:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77895,7 +80255,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) { } }; -},{"../../../lib":382,"../../cartesian/axis_defaults":406,"./axis_attributes":443,"tinycolor2":274}],445:[function(require,module,exports){ +},{"../../../lib":1127,"../../cartesian/axis_defaults":1151,"./axis_attributes":1188,"tinycolor2":1042}],1190:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78051,7 +80411,7 @@ function createAxesOptions(plotlyOptions) { module.exports = createAxesOptions; -},{"../../../lib/html2unicode":381,"../../../lib/str2rgbarray":394,"arraytools":49}],446:[function(require,module,exports){ +},{"../../../lib/html2unicode":1126,"../../../lib/str2rgbarray":1139,"arraytools":64}],1191:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78158,7 +80518,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { coerce('hovermode', opts.getDfltFromLayout('hovermode')); } -},{"../../../components/color":303,"../../subplot_defaults":460,"./axis_defaults":444,"./layout_attributes":447}],447:[function(require,module,exports){ +},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1189,"./layout_attributes":1192}],1192:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78328,7 +80688,7 @@ module.exports = { } }; -},{"../../../lib/extend":377,"./axis_attributes":443}],448:[function(require,module,exports){ +},{"../../../lib/extend":1122,"./axis_attributes":1188}],1193:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78374,7 +80734,7 @@ function createSpikeOptions(layout) { module.exports = createSpikeOptions; -},{"../../../lib/str2rgbarray":394}],449:[function(require,module,exports){ +},{"../../../lib/str2rgbarray":1139}],1194:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78469,7 +80829,7 @@ function computeTickMarks(scene) { scene.contourLevels = contourLevelsFromTicks(ticks); } -},{"../../../lib/html2unicode":381,"../../../plotly":402}],450:[function(require,module,exports){ +},{"../../../lib/html2unicode":1126,"../../../plotly":1147}],1195:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78503,7 +80863,7 @@ function project(camera, v) { module.exports = project; -},{}],451:[function(require,module,exports){ +},{}],1196:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79232,7 +81592,7 @@ proto.toImage = function(format) { module.exports = Scene; -},{"../../lib":382,"../../lib/show_no_webgl_msg":392,"../../lib/str2rgbarray":394,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../../plots/plots":454,"./camera":440,"./layout/convert":445,"./layout/spikes":448,"./layout/tick_marks":449,"./project":450,"./set_convert":452,"gl-plot3d":183}],452:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/show_no_webgl_msg":1137,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/plots":1199,"./camera":1185,"./layout/convert":1190,"./layout/spikes":1193,"./layout/tick_marks":1194,"./project":1195,"./set_convert":1197,"gl-plot3d":626}],1197:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79254,7 +81614,7 @@ module.exports = function setConvert(containerOut) { containerOut.setScale = noop; }; -},{"../cartesian/axes":405}],453:[function(require,module,exports){ +},{"../cartesian/axes":1150}],1198:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79445,7 +81805,7 @@ module.exports = { } }; -},{"../components/color/attributes":302,"../plotly":402,"./font_attributes":423}],454:[function(require,module,exports){ +},{"../components/color/attributes":1047,"../plotly":1147,"./font_attributes":1168}],1199:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80551,7 +82911,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { return (output === 'object') ? obj : JSON.stringify(obj); }; -},{"../components/color":303,"../lib":382,"../plotly":402,"./attributes":403,"./font_attributes":423,"./layout_attributes":453,"d3":113,"fast-isnumeric":117}],455:[function(require,module,exports){ +},{"../components/color":1048,"../lib":1127,"../plotly":1147,"./attributes":1148,"./font_attributes":1168,"./layout_attributes":1198,"d3":82,"fast-isnumeric":90}],1200:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80576,7 +82936,7 @@ module.exports = { } }; -},{"../../traces/scatter/attributes":556}],456:[function(require,module,exports){ +},{"../../traces/scatter/attributes":1301}],1201:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80726,7 +83086,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../cartesian/layout_attributes":414}],457:[function(require,module,exports){ +},{"../../lib/extend":1122,"../cartesian/layout_attributes":1159}],1202:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82149,7 +84509,7 @@ var extendDeepAll = Plotly.Lib.extendDeepAll; return exports; }; -},{"../../plotly":402,"./micropolar_manager":458,"d3":113}],458:[function(require,module,exports){ +},{"../../plotly":1147,"./micropolar_manager":1203,"d3":82}],1203:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82232,7 +84592,7 @@ manager.fillLayout = function(_gd) { _gd._fullLayout = extendDeepAll(dflts, _gd.layout); }; -},{"../../plotly":402,"./undo_manager":459,"d3":113}],459:[function(require,module,exports){ +},{"../../plotly":1147,"./undo_manager":1204,"d3":82}],1204:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82298,7 +84658,7 @@ module.exports = function UndoManager() { }; }; -},{}],460:[function(require,module,exports){ +},{}],1205:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82373,7 +84733,7 @@ module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, o } }; -},{"../lib":382,"./plots":454}],461:[function(require,module,exports){ +},{"../lib":1127,"./plots":1199}],1206:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82447,7 +84807,7 @@ exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) } }; -},{"../../plots/plots":454,"./layout/attributes":462,"./layout/defaults":465,"./layout/layout_attributes":466,"./ternary":467}],462:[function(require,module,exports){ +},{"../../plots/plots":1199,"./layout/attributes":1207,"./layout/defaults":1210,"./layout/layout_attributes":1211,"./ternary":1212}],1207:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82473,7 +84833,7 @@ module.exports = { } }; -},{}],463:[function(require,module,exports){ +},{}],1208:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82537,7 +84897,7 @@ module.exports = { } }; -},{"../../../lib/extend":377,"../../cartesian/layout_attributes":414}],464:[function(require,module,exports){ +},{"../../../lib/extend":1122,"../../cartesian/layout_attributes":1159}],1209:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82621,7 +84981,7 @@ module.exports = function supplyLayoutDefaults(containerIn, containerOut, option } }; -},{"../../../lib":382,"../../cartesian/tick_label_defaults":420,"../../cartesian/tick_mark_defaults":421,"../../cartesian/tick_value_defaults":422,"./axis_attributes":463,"tinycolor2":274}],465:[function(require,module,exports){ +},{"../../../lib":1127,"../../cartesian/tick_label_defaults":1165,"../../cartesian/tick_mark_defaults":1166,"../../cartesian/tick_value_defaults":1167,"./axis_attributes":1208,"tinycolor2":1042}],1210:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82684,7 +85044,7 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option } } -},{"../../../components/color":303,"../../subplot_defaults":460,"./axis_defaults":464,"./layout_attributes":466}],466:[function(require,module,exports){ +},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1209,"./layout_attributes":1211}],1211:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82749,7 +85109,7 @@ module.exports = { caxis: ternaryAxesAttrs }; -},{"../../../components/color/attributes":302,"./axis_attributes":463}],467:[function(require,module,exports){ +},{"../../../components/color/attributes":1047,"./axis_attributes":1208}],1212:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83435,7 +85795,7 @@ function removeZoombox(gd) { .remove(); } -},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../components/titles":366,"../../lib":382,"../../lib/extend":377,"../../lib/filter_visible":378,"../../plotly":402,"../cartesian/axes":405,"../cartesian/constants":410,"../cartesian/graph_interact":412,"../cartesian/select":418,"../cartesian/set_convert":419,"d3":113,"tinycolor2":274}],468:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/extend":1122,"../../lib/filter_visible":1123,"../../plotly":1147,"../cartesian/axes":1150,"../cartesian/constants":1155,"../cartesian/graph_interact":1157,"../cartesian/select":1163,"../cartesian/set_convert":1164,"d3":82,"tinycolor2":1042}],1213:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83591,7 +85951,7 @@ module.exports = function clonePlot(graphObj, options) { return plotTile; }; -},{"../plotly":402}],469:[function(require,module,exports){ +},{"../plotly":1147}],1214:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83657,7 +86017,7 @@ function downloadImage(gd, opts) { module.exports = downloadImage; -},{"../lib":382,"../plot_api/to_image":401,"./filesaver":470}],470:[function(require,module,exports){ +},{"../lib":1127,"../plot_api/to_image":1146,"./filesaver":1215}],1215:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83725,7 +86085,7 @@ var fileSaver = function(url, name) { module.exports = fileSaver; -},{}],471:[function(require,module,exports){ +},{}],1216:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83770,7 +86130,7 @@ var Snapshot = { module.exports = Snapshot; -},{"./cloneplot":468,"./download":469,"./svgtoimg":472,"./toimage":473,"./tosvg":474}],472:[function(require,module,exports){ +},{"./cloneplot":1213,"./download":1214,"./svgtoimg":1217,"./toimage":1218,"./tosvg":1219}],1217:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83901,7 +86261,7 @@ function svgToImg(opts) { module.exports = svgToImg; -},{"../lib":382,"events":55}],473:[function(require,module,exports){ +},{"../lib":1127,"events":69}],1218:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83980,7 +86340,7 @@ function toImage(gd, opts) { module.exports = toImage; -},{"../lib":382,"../plotly":402,"events":55}],474:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147,"events":69}],1219:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84092,7 +86452,7 @@ module.exports = function toSVG(gd, format) { return s; }; -},{"../components/color":303,"../components/drawing":326,"../constants/xmlns_namespaces":370,"../lib/svg_text_utils":395,"d3":113}],475:[function(require,module,exports){ +},{"../components/color":1048,"../components/drawing":1071,"../constants/xmlns_namespaces":1115,"../lib/svg_text_utils":1140,"d3":82}],1220:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84120,7 +86480,7 @@ module.exports = function arraysToCalcdata(cd) { mergeArray(markerLine.width, cd, 'mlw'); }; -},{"../../lib":382}],476:[function(require,module,exports){ +},{"../../lib":1127}],1221:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84184,7 +86544,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../scatter/attributes":556}],477:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../scatter/attributes":1301}],1222:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84243,7 +86603,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":316,"../../plots/cartesian/axes":405,"fast-isnumeric":117}],478:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1223:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84285,7 +86645,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'}); }; -},{"../../components/color":303,"../../components/errorbars/defaults":331,"../../lib":382,"../bar/style_defaults":486,"../scatter/xy_defaults":577,"./attributes":476}],479:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"../scatter/xy_defaults":1324,"./attributes":1221}],1224:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84376,7 +86736,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return [pointData]; }; -},{"../../components/color":303,"../../components/errorbars":332,"../../plots/cartesian/graph_interact":412}],480:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157}],1225:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84417,7 +86777,7 @@ Bar.meta = { module.exports = Bar; -},{"../../plots/cartesian":413,"../scatter/colorbar":559,"./arrays_to_calcdata":475,"./attributes":476,"./calc":477,"./defaults":478,"./hover":479,"./layout_attributes":481,"./layout_defaults":482,"./plot":483,"./set_positions":484,"./style":485}],481:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../scatter/colorbar":1304,"./arrays_to_calcdata":1220,"./attributes":1221,"./calc":1222,"./defaults":1223,"./hover":1224,"./layout_attributes":1226,"./layout_defaults":1227,"./plot":1228,"./set_positions":1229,"./style":1230}],1226:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84482,7 +86842,7 @@ module.exports = { } }; -},{}],482:[function(require,module,exports){ +},{}],1227:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84540,7 +86900,7 @@ module.exports = function(layoutIn, layoutOut, fullData) { coerce('bargroupgap'); }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"./layout_attributes":481}],483:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"./layout_attributes":1226}],1228:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84652,7 +87012,7 @@ module.exports = function plot(gd, plotinfo, cdbar) { }; -},{"../../components/color":303,"../../components/errorbars":332,"../../lib":382,"./arrays_to_calcdata":475,"d3":113,"fast-isnumeric":117}],484:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1220,"d3":82,"fast-isnumeric":90}],1229:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84866,7 +87226,7 @@ module.exports = function setPositions(gd, plotinfo) { }); }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"fast-isnumeric":117}],485:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"fast-isnumeric":90}],1230:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84945,7 +87305,7 @@ module.exports = function style(gd) { s.call(ErrorBars.style); }; -},{"../../components/color":303,"../../components/drawing":326,"../../components/errorbars":332,"d3":113}],486:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../components/errorbars":1077,"d3":82}],1231:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84982,7 +87342,7 @@ module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, default coerce('marker.line.width'); }; -},{"../../components/color":303,"../../components/colorscale/defaults":313,"../../components/colorscale/has_colorscale":316}],487:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061}],1232:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85160,7 +87520,7 @@ module.exports = { fillcolor: scatterAttrs.fillcolor }; -},{"../../components/color/attributes":302,"../../lib/extend":377,"../scatter/attributes":556}],488:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../scatter/attributes":1301}],1233:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85309,7 +87669,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"fast-isnumeric":117}],489:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1234:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85378,7 +87738,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) { } }; -},{"../../components/color":303,"../../lib":382,"./attributes":487}],490:[function(require,module,exports){ +},{"../../components/color":1048,"../../lib":1127,"./attributes":1232}],1235:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85487,7 +87847,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return closeData; }; -},{"../../components/color":303,"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412}],491:[function(require,module,exports){ +},{"../../components/color":1048,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157}],1236:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85533,7 +87893,7 @@ Box.meta = { module.exports = Box; -},{"../../plots/cartesian":413,"./attributes":487,"./calc":488,"./defaults":489,"./hover":490,"./layout_attributes":492,"./layout_defaults":493,"./plot":494,"./set_positions":495,"./style":496}],492:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./attributes":1232,"./calc":1233,"./defaults":1234,"./hover":1235,"./layout_attributes":1237,"./layout_defaults":1238,"./plot":1239,"./set_positions":1240,"./style":1241}],1237:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85584,7 +87944,7 @@ module.exports = { } }; -},{}],493:[function(require,module,exports){ +},{}],1238:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85618,7 +87978,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { coerce('boxgroupgap'); }; -},{"../../lib":382,"../../plots/plots":454,"./layout_attributes":492}],494:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"./layout_attributes":1237}],1239:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85845,7 +88205,7 @@ module.exports = function plot(gd, plotinfo, cdbox) { }); }; -},{"../../components/drawing":326,"../../lib":382,"d3":113}],495:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../lib":1127,"d3":82}],1240:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85938,7 +88298,7 @@ module.exports = function setPositions(gd, plotinfo) { } }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454}],496:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199}],1241:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85977,7 +88337,7 @@ module.exports = function style(gd) { }); }; -},{"../../components/color":303,"../../components/drawing":326,"d3":113}],497:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"d3":82}],1242:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86028,7 +88388,7 @@ module.exports = extendFlat({}, { colorscaleAttrs ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../../plots/attributes":403,"../scattergeo/attributes":584}],498:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../../plots/attributes":1148,"../scattergeo/attributes":1331}],1243:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86047,7 +88407,7 @@ module.exports = function calc(gd, trace) { colorscaleCalc(trace, trace.z, '', 'z'); }; -},{"../../components/colorscale/calc":310}],499:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055}],1244:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86102,7 +88462,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('hoverinfo', (layout._dataLength === 1) ? 'location+z+text' : undefined); }; -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":497}],500:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1242}],1245:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86137,7 +88497,7 @@ Choropleth.meta = { module.exports = Choropleth; -},{"../../plots/geo":426,"../heatmap/colorbar":514,"./attributes":497,"./calc":498,"./defaults":499,"./plot":501}],501:[function(require,module,exports){ +},{"../../plots/geo":1171,"../heatmap/colorbar":1259,"./attributes":1242,"./calc":1243,"./defaults":1244,"./plot":1246}],1246:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86358,7 +88718,7 @@ function makeEventDataFunc(trace) { }; } -},{"../../components/color":303,"../../components/colorscale/get_scale":315,"../../components/colorscale/make_scale_function":320,"../../components/drawing":326,"../../lib/array_to_calc_item":373,"../../lib/geo_location_utils":379,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../../plots/geo/constants":424,"./attributes":497,"d3":113}],502:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/get_scale":1060,"../../components/colorscale/make_scale_function":1065,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/geo/constants":1169,"./attributes":1242,"d3":82}],1247:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86482,7 +88842,7 @@ module.exports = extendFlat({}, {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../heatmap/attributes":512,"../scatter/attributes":556}],503:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../scatter/attributes":1301}],1248:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86535,7 +88895,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../plots/cartesian/axes":405,"../heatmap/calc":513}],504:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../heatmap/calc":1258}],1249:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86596,7 +88956,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../plots/plots":454,"./make_color_map":508}],505:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../plots/plots":1199,"./make_color_map":1253}],1250:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86640,7 +89000,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout handleStyleDefaults(traceIn, traceOut, coerce, layout); }; -},{"../../lib":382,"../contour/style_defaults":511,"../heatmap/has_columns":517,"../heatmap/xyz_defaults":523,"./attributes":502}],506:[function(require,module,exports){ +},{"../../lib":1127,"../contour/style_defaults":1256,"../heatmap/has_columns":1262,"../heatmap/xyz_defaults":1268,"./attributes":1247}],1251:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86659,7 +89019,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return heatmapHoverPoints(pointData, xval, yval, hovermode, true); }; -},{"../heatmap/hover":518}],507:[function(require,module,exports){ +},{"../heatmap/hover":1263}],1252:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86700,7 +89060,7 @@ Contour.meta = { module.exports = Contour; -},{"../../plots/cartesian":413,"./attributes":502,"./calc":503,"./colorbar":504,"./defaults":505,"./hover":506,"./plot":509,"./style":510}],508:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./attributes":1247,"./calc":1248,"./colorbar":1249,"./defaults":1250,"./hover":1251,"./plot":1254,"./style":1255}],1253:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86780,7 +89140,7 @@ module.exports = function makeColorMap(trace) { return colorMap; }; -},{"../../components/colorscale/get_scale":315,"d3":113}],509:[function(require,module,exports){ +},{"../../components/colorscale/get_scale":1060,"d3":82}],1254:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87490,7 +89850,7 @@ function makeClipMask(cd0) { return z; } -},{"../../components/drawing":326,"../../lib":382,"../heatmap/plot":521,"d3":113}],510:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../lib":1127,"../heatmap/plot":1266,"d3":82}],1255:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87547,7 +89907,7 @@ module.exports = function style(gd) { heatmapStyle(gd); }; -},{"../../components/drawing":326,"../heatmap/style":522,"./make_color_map":508,"d3":113}],511:[function(require,module,exports){ +},{"../../components/drawing":1071,"../heatmap/style":1267,"./make_color_map":1253,"d3":82}],1256:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87583,7 +89943,7 @@ module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout) } }; -},{"../../components/colorscale/defaults":313}],512:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058}],1257:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87671,7 +90031,7 @@ module.exports = extendFlat({}, {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../scatter/attributes":556}],513:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../scatter/attributes":1301}],1258:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88107,7 +90467,7 @@ function iterateInterp2d(z, emptyPoints, overshoot) { return maxFractionalChange; } -},{"../../components/colorscale/calc":310,"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"../histogram2d/calc":533,"./convert_column_xyz":515,"./has_columns":517,"./max_row_length":520,"fast-isnumeric":117}],514:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"../histogram2d/calc":1278,"./convert_column_xyz":1260,"./has_columns":1262,"./max_row_length":1265,"fast-isnumeric":90}],1259:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88153,7 +90513,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,"d3":113,"fast-isnumeric":117}],515:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1260:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88210,7 +90570,7 @@ module.exports = function convertColumnXYZ(trace, xa, ya) { if(hasColumnText) trace.text = text; }; -},{"../../lib":382}],516:[function(require,module,exports){ +},{"../../lib":1127}],1261:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88248,7 +90608,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":512,"./has_columns":517,"./xyz_defaults":523}],517:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1257,"./has_columns":1262,"./xyz_defaults":1268}],1262:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88264,7 +90624,7 @@ module.exports = function(trace) { return !Array.isArray(trace.z[0]); }; -},{}],518:[function(require,module,exports){ +},{}],1263:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88378,7 +90738,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode, contour) })]; }; -},{"../../lib":382,"../../plots/cartesian/graph_interact":412}],519:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/graph_interact":1157}],1264:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88433,7 +90793,7 @@ Heatmap.meta = { module.exports = Heatmap; -},{"../../plots/cartesian":413,"./attributes":512,"./calc":513,"./colorbar":514,"./defaults":516,"./hover":518,"./plot":521,"./style":522}],520:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./attributes":1257,"./calc":1258,"./colorbar":1259,"./defaults":1261,"./hover":1263,"./plot":1266,"./style":1267}],1265:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88455,7 +90815,7 @@ module.exports = function maxRowLength(z) { return len; }; -},{}],521:[function(require,module,exports){ +},{}],1266:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88845,7 +91205,7 @@ function plotOne(gd, plotinfo, cd) { }); } -},{"../../components/colorscale/get_scale":315,"../../constants/xmlns_namespaces":370,"../../lib":382,"../../plots/plots":454,"./max_row_length":520,"d3":113,"tinycolor2":274}],522:[function(require,module,exports){ +},{"../../components/colorscale/get_scale":1060,"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plots/plots":1199,"./max_row_length":1265,"d3":82,"tinycolor2":1042}],1267:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88866,7 +91226,7 @@ module.exports = function style(gd) { }); }; -},{"d3":113}],523:[function(require,module,exports){ +},{"d3":82}],1268:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88955,7 +91315,7 @@ function isValidZ(z) { return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); } -},{"./has_columns":517,"fast-isnumeric":117}],524:[function(require,module,exports){ +},{"./has_columns":1262,"fast-isnumeric":90}],1269:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89134,7 +91494,7 @@ function makeBinsAttr(axLetter) { }; } -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../bar/attributes":476}],525:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../bar/attributes":1221}],1270:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89160,7 +91520,7 @@ module.exports = function doAvg(size, counts) { return total; }; -},{}],526:[function(require,module,exports){ +},{}],1271:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89190,7 +91550,7 @@ module.exports = function handleBinDefaults(traceIn, traceOut, coerce, binDirect return traceOut; }; -},{}],527:[function(require,module,exports){ +},{}],1272:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89264,7 +91624,7 @@ module.exports = { } }; -},{"fast-isnumeric":117}],528:[function(require,module,exports){ +},{"fast-isnumeric":90}],1273:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89394,7 +91754,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"./average":525,"./bin_functions":527,"./norm_functions":531,"fast-isnumeric":117}],529:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./average":1270,"./bin_functions":1272,"./norm_functions":1276,"fast-isnumeric":90}],1274:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89446,7 +91806,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'}); }; -},{"../../components/color":303,"../../components/errorbars/defaults":331,"../../lib":382,"../bar/style_defaults":486,"./attributes":524,"./bin_defaults":526}],530:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"./attributes":1269,"./bin_defaults":1271}],1275:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89501,7 +91861,7 @@ Histogram.meta = { module.exports = Histogram; -},{"../../plots/cartesian":413,"../bar/hover":479,"../bar/layout_attributes":481,"../bar/layout_defaults":482,"../bar/plot":483,"../bar/set_positions":484,"../bar/style":485,"../scatter/colorbar":559,"./attributes":524,"./calc":528,"./defaults":529}],531:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../bar/hover":1224,"../bar/layout_attributes":1226,"../bar/layout_defaults":1227,"../bar/plot":1228,"../bar/set_positions":1229,"../bar/style":1230,"../scatter/colorbar":1304,"./attributes":1269,"./calc":1273,"./defaults":1274}],1276:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89536,7 +91896,7 @@ module.exports = { } }; -},{}],532:[function(require,module,exports){ +},{}],1277:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89588,7 +91948,7 @@ module.exports = extendFlat({}, {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../heatmap/attributes":512,"../histogram/attributes":524}],533:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../histogram/attributes":1269}],1278:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89754,7 +92114,7 @@ module.exports = function calc(gd, trace) { }; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../histogram/average":525,"../histogram/bin_functions":527,"../histogram/norm_functions":531}],534:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../histogram/average":1270,"../histogram/bin_functions":1272,"../histogram/norm_functions":1276}],1279:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89787,7 +92147,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, layout) { ); }; -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":532,"./sample_defaults":536}],535:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1277,"./sample_defaults":1281}],1280:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89827,7 +92187,7 @@ Histogram2D.meta = { module.exports = Histogram2D; -},{"../../plots/cartesian":413,"../heatmap/calc":513,"../heatmap/colorbar":514,"../heatmap/hover":518,"../heatmap/plot":521,"../heatmap/style":522,"./attributes":532,"./defaults":534}],536:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../heatmap/calc":1258,"../heatmap/colorbar":1259,"../heatmap/hover":1263,"../heatmap/plot":1266,"../heatmap/style":1267,"./attributes":1277,"./defaults":1279}],1281:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89863,7 +92223,7 @@ module.exports = function handleSampleDefaults(traceIn, traceOut, coerce) { handleBinDefaults(traceIn, traceOut, coerce, binDirections); }; -},{"../histogram/bin_defaults":526}],537:[function(require,module,exports){ +},{"../histogram/bin_defaults":1271}],1282:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89907,7 +92267,7 @@ module.exports = extendFlat({}, { colorscaleAttrs ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../contour/attributes":502,"../histogram2d/attributes":532}],538:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../contour/attributes":1247,"../histogram2d/attributes":1277}],1283:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89943,7 +92303,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout handleStyleDefaults(traceIn, traceOut, coerce, layout); }; -},{"../../lib":382,"../contour/style_defaults":511,"../histogram2d/sample_defaults":536,"./attributes":537}],539:[function(require,module,exports){ +},{"../../lib":1127,"../contour/style_defaults":1256,"../histogram2d/sample_defaults":1281,"./attributes":1282}],1284:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89983,7 +92343,7 @@ Histogram2dContour.meta = { module.exports = Histogram2dContour; -},{"../../plots/cartesian":413,"../contour/calc":503,"../contour/colorbar":504,"../contour/hover":506,"../contour/plot":509,"../contour/style":510,"./attributes":537,"./defaults":538}],540:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../contour/calc":1248,"../contour/colorbar":1249,"../contour/hover":1251,"../contour/plot":1254,"../contour/style":1255,"./attributes":1282,"./defaults":1283}],1285:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90182,7 +92542,7 @@ module.exports = { } }; -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../surface/attributes":601}],541:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../surface/attributes":1348}],1286:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90344,7 +92704,7 @@ function createMesh3DTrace(scene, data) { module.exports = createMesh3DTrace; -},{"../../lib/str2rgbarray":394,"alpha-shape":40,"convex-hull":102,"delaunay-triangulate":114,"gl-mesh3d":150,"tinycolor2":274}],542:[function(require,module,exports){ +},{"../../lib/str2rgbarray":1139,"alpha-shape":46,"convex-hull":71,"delaunay-triangulate":88,"gl-mesh3d":253,"tinycolor2":1042}],1287:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90441,7 +92801,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout } }; -},{"../../components/colorbar/defaults":305,"../../lib":382,"./attributes":540}],543:[function(require,module,exports){ +},{"../../components/colorbar/defaults":1050,"../../lib":1127,"./attributes":1285}],1288:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90477,7 +92837,7 @@ Mesh3D.meta = { module.exports = Mesh3D; -},{"../../plots/gl3d":441,"../heatmap/colorbar":514,"./attributes":540,"./convert":541,"./defaults":542}],544:[function(require,module,exports){ +},{"../../plots/gl3d":1186,"../heatmap/colorbar":1259,"./attributes":1285,"./convert":1286,"./defaults":1287}],1289:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90741,7 +93101,7 @@ module.exports = { } }; -},{"../../components/color/attributes":302,"../../lib/extend":377,"../../plots/attributes":403,"../../plots/font_attributes":423}],545:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../../plots/attributes":1148,"../../plots/font_attributes":1168}],1290:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90788,7 +93148,7 @@ function getCdModule(calcdata, _module) { return cdModule; } -},{"../../plots/plots":454}],546:[function(require,module,exports){ +},{"../../plots/plots":1199}],1291:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90940,7 +93300,7 @@ function nextDefaultColor(index) { return pieDefaultColors[index % pieDefaultColors.length]; } -},{"../../components/color":303,"./helpers":548,"fast-isnumeric":117,"tinycolor2":274}],547:[function(require,module,exports){ +},{"../../components/color":1048,"./helpers":1293,"fast-isnumeric":90,"tinycolor2":1042}],1292:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91024,7 +93384,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('pull'); }; -},{"../../lib":382,"./attributes":544}],548:[function(require,module,exports){ +},{"../../lib":1127,"./attributes":1289}],1293:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91053,7 +93413,7 @@ exports.formatPieValue = function formatPieValue(v, separators) { return Lib.numSeparate(vRounded, separators); }; -},{"../../lib":382}],549:[function(require,module,exports){ +},{"../../lib":1127}],1294:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91089,7 +93449,7 @@ Pie.meta = { module.exports = Pie; -},{"./attributes":544,"./base_plot":545,"./calc":546,"./defaults":547,"./layout_attributes":550,"./layout_defaults":551,"./plot":552,"./style":553,"./style_one":554}],550:[function(require,module,exports){ +},{"./attributes":1289,"./base_plot":1290,"./calc":1291,"./defaults":1292,"./layout_attributes":1295,"./layout_defaults":1296,"./plot":1297,"./style":1298,"./style_one":1299}],1295:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91109,7 +93469,7 @@ module.exports = { hiddenlabels: {valType: 'data_array'} }; -},{}],551:[function(require,module,exports){ +},{}],1296:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91131,7 +93491,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) { coerce('hiddenlabels'); }; -},{"../../lib":382,"./layout_attributes":550}],552:[function(require,module,exports){ +},{"../../lib":1127,"./layout_attributes":1295}],1297:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91826,7 +94186,7 @@ function maxExtent(tilt, tiltAxisFraction, depth) { 2 * Math.sqrt(1 - sinTilt * sinTilt * tiltAxisFraction * tiltAxisFraction)); } -},{"../../components/color":303,"../../components/drawing":326,"../../lib/svg_text_utils":395,"../../plots/cartesian/graph_interact":412,"./helpers":548,"d3":113}],553:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/svg_text_utils":1140,"../../plots/cartesian/graph_interact":1157,"./helpers":1293,"d3":82}],1298:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91855,7 +94215,7 @@ module.exports = function style(gd) { }); }; -},{"./style_one":554,"d3":113}],554:[function(require,module,exports){ +},{"./style_one":1299,"d3":82}],1299:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91882,7 +94242,7 @@ module.exports = function styleOne(s, pt, trace) { .call(Color.stroke, lineColor); }; -},{"../../components/color":303}],555:[function(require,module,exports){ +},{"../../components/color":1048}],1300:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91920,7 +94280,7 @@ module.exports = function arraysToCalcdata(cd) { } }; -},{"../../lib":382}],556:[function(require,module,exports){ +},{"../../lib":1127}],1301:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91988,6 +94348,10 @@ module.exports = { 'See `y0` for more info.' ].join(' ') }, + key: { + valType: 'data_array', + description: 'A list of keys for object constancy of data points during animation' + }, text: { valType: 'string', role: 'info', @@ -92259,7 +94623,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../components/drawing":326,"../../lib/extend":377,"./constants":560}],557:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../components/drawing":1071,"../../lib/extend":1122,"./constants":1305}],1302:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92377,6 +94741,10 @@ module.exports = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ? {x: x[i], y: y[i]} : {x: false, y: false}; + + if (trace.key && trace.key[i] !== undefined) { + cd[i].key = trace.key[i]; + } } // this has migrated up from arraysToCalcdata as we have a reference to 's' here @@ -92386,7 +94754,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"./marker_colorscale_calc":570,"./subtypes":575,"fast-isnumeric":117}],558:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./marker_colorscale_calc":1316,"./subtypes":1322,"fast-isnumeric":90}],1303:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92427,7 +94795,7 @@ module.exports = function cleanData(fullData) { } }; -},{}],559:[function(require,module,exports){ +},{}],1304:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92480,7 +94848,7 @@ module.exports = function colorbar(gd, cd) { .options(marker.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,"d3":113,"fast-isnumeric":117}],560:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1305:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92496,7 +94864,7 @@ module.exports = { PTS_LINESONLY: 20 }; -},{}],561:[function(require,module,exports){ +},{}],1306:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92535,6 +94903,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout return; } + coerce('key'); coerce('text'); coerce('mode', defaultMode); @@ -92566,7 +94935,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); }; -},{"../../components/errorbars/defaults":331,"../../lib":382,"./attributes":556,"./constants":560,"./fillcolor_defaults":562,"./line_defaults":566,"./line_shape_defaults":568,"./marker_defaults":571,"./subtypes":575,"./text_defaults":576,"./xy_defaults":577}],562:[function(require,module,exports){ +},{"../../components/errorbars/defaults":1076,"../../lib":1127,"./attributes":1301,"./constants":1305,"./fillcolor_defaults":1307,"./line_defaults":1311,"./line_shape_defaults":1313,"./marker_defaults":1317,"./subtypes":1322,"./text_defaults":1323,"./xy_defaults":1324}],1307:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92605,7 +94974,7 @@ module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coe )); }; -},{"../../components/color":303}],563:[function(require,module,exports){ +},{"../../components/color":1048}],1308:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92658,7 +95027,7 @@ module.exports = function getTraceColor(trace, di) { } }; -},{"../../components/color":303,"./subtypes":575}],564:[function(require,module,exports){ +},{"../../components/color":1048,"./subtypes":1322}],1309:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92729,7 +95098,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return [pointData]; }; -},{"../../components/errorbars":332,"../../plots/cartesian/graph_interact":412,"./get_trace_color":563}],565:[function(require,module,exports){ +},{"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157,"./get_trace_color":1308}],1310:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92755,6 +95124,7 @@ Scatter.attributes = require('./attributes'); Scatter.supplyDefaults = require('./defaults'); Scatter.cleanData = require('./clean_data'); Scatter.calc = require('./calc'); +Scatter.setPositions = require('./set_positions'); Scatter.arraysToCalcdata = require('./arrays_to_calcdata'); Scatter.plot = require('./plot'); Scatter.colorbar = require('./colorbar'); @@ -92764,6 +95134,7 @@ Scatter.selectPoints = require('./select'); Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; +Scatter.animatable = true; Scatter.basePlotModule = require('../../plots/cartesian'); Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend']; Scatter.meta = { @@ -92778,7 +95149,7 @@ Scatter.meta = { module.exports = Scatter; -},{"../../plots/cartesian":413,"./arrays_to_calcdata":555,"./attributes":556,"./calc":557,"./clean_data":558,"./colorbar":559,"./defaults":561,"./hover":564,"./plot":572,"./select":573,"./style":574,"./subtypes":575}],566:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./arrays_to_calcdata":1300,"./attributes":1301,"./calc":1302,"./clean_data":1303,"./colorbar":1304,"./defaults":1306,"./hover":1309,"./plot":1318,"./select":1319,"./set_positions":1320,"./style":1321,"./subtypes":1322}],1311:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92802,7 +95173,7 @@ module.exports = function lineDefaults(traceIn, traceOut, defaultColor, coerce) coerce('line.dash'); }; -},{}],567:[function(require,module,exports){ +},{}],1312:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92865,7 +95236,7 @@ module.exports = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length, yFrac = pt[1] / ya._length; - return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance * 0; } function ptDist(pt1, pt2) { @@ -92971,7 +95342,7 @@ module.exports = function linePoints(d, opts) { return segments; }; -},{"../../plots/cartesian/axes":405}],568:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150}],1313:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92990,7 +95361,59 @@ module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) { if(shape === 'spline') coerce('line.smoothing'); }; -},{}],569:[function(require,module,exports){ +},{}],1314:[function(require,module,exports){ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); + +module.exports = function linkTraces(gd, plotinfo, cdscatter) { + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < cdscatter.length; ++i) { + cd = cdscatter[i]; + trace = cd[0].trace; + + // console.log('visible:', trace.uid, trace.visible); + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + trace._nexttrace = null; + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + + prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; + } + } + + /*for(i = 0; i < cdscatter.length; ++i) { + var trace = cdscatter[i][0].trace; + console.log('gd.cdscatter[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + }*/ +} + +},{"../../plots/plots":1199}],1315:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93032,7 +95455,7 @@ module.exports = function makeBubbleSizeFn(trace) { }; }; -},{"fast-isnumeric":117}],570:[function(require,module,exports){ +},{"fast-isnumeric":90}],1316:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93066,7 +95489,7 @@ module.exports = function calcMarkerColorscale(trace) { } }; -},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":316,"./subtypes":575}],571:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1317:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93129,7 +95552,7 @@ module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout } }; -},{"../../components/color":303,"../../components/colorscale/defaults":313,"../../components/colorscale/has_colorscale":316,"./subtypes":575}],572:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1318:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93150,74 +95573,176 @@ var ErrorBars = require('../../components/errorbars'); var subTypes = require('./subtypes'); var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); +var linkTraces = require('./link_traces'); +function cdscatterKey (d) { + return d[0].trace.uid; +} -module.exports = function plot(gd, plotinfo, cdscatter) { - selectMarkers(gd, plotinfo, cdscatter); +module.exports = function plot(gd, plotinfo, cdscatter, traces, transitionOpts) { + var i, uids, noremove; - var xa = plotinfo.x(), - ya = plotinfo.y(); + var transitionConfig = Lib.extendFlat({}, transitionOpts || {}); - // make the container for scatter plots - // (so error bars can find them along with bars) - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(cdscatter); + transitionConfig = Lib.extendFlat({ + duration: 0, + easing: 'in-out-cubic', + cascade: 0, + delay: 0, + }, transitionConfig); + + var hasTransition = transitionConfig.duration > 0; - scattertraces.enter().append('g') + if (!traces) { + // If no traces provided, redraw all: + for (i = 0, traces = []; i < cdscatter.length; i++) { + traces[i] = i; + } + noremove = false; + } else { + // If this is a partial update, then don't remove traces whose data is not updated + noremove = true; + } + + var scatterlayer = plotinfo.plot.select('g.scatterlayer'); + var traceJoin = scatterlayer.selectAll('g.trace').data(cdscatter, cdscatterKey); + + var traceEnter = traceJoin.enter().append('g') .attr('class', 'trace scatter') - .style('stroke-miterlimit', 2); + .style('stroke-miterlimit', 2) - // error bars are at the bottom - scattertraces.call(ErrorBars.plot, plotinfo); + // After the elements are created but before they've been draw, we have to do + // this extra step of linking the traces due to z-ordering + linkTraces(gd, plotinfo, cdscatter) + createFills(gd, scatterlayer, cdscatter, traces) - // BUILD LINES AND FILLS - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext; + traceEnter.each(function(d) { + //console.log('enter:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); - scattertraces.each(function(d) { - var trace = d[0].trace, - line = trace.line, - tr = d3.select(this); - if(trace.visible !== true) return; + traceJoin.transition() + .duration(0) + .each(function(d) { + //console.log('transition:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); + + + if (!noremove) { + traceJoin.exit().remove(); + } - ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; + // Sort the traces, once created, so that the ordering is preserved even when + // traces are shown and hidden. This is now needed since we're not just wiping + // everything out and recreating on every update. + for (i = 0, uids = []; i < cdscatter.length; i++) { + uids[i] = cdscatter[i][0].trace.uid; + } + + scatterlayer.selectAll('g.trace').sort(function (a, b) { + var idx1 = uids.indexOf(a[0].trace.uid); + var idx2 = uids.indexOf(b[0].trace.uid); + return idx1 > idx2 ? 1 : -1; + }); - d[0].node3 = tr; // store node for tweaking by selectPoints + // remove paths that didn't get used + // scatterlayer.selectAll('path:not([d])').remove(); +}; - arraysToCalcdata(d); +function createFills (gd, scatterlayer, cdscatter, traces) { + var i, trace, prevtrace; - if(!subTypes.hasLines(trace) && trace.fill === 'none') return; + scatterlayer.selectAll('g.trace').each(function (d) { + var tr = d3.select(this); - var thispath, - thisrevpath, - // fullpath is all paths for this curve, joined together straight - // across gaps, for filling - fullpath = '', - // revpath is fullpath reversed, for fill-to-next - revpath = '', - // functions for converting a point array to a path - pathfn, revpathbase, revpathfn; + // Loop only over the traces being redrawn: + trace = d[0].trace; - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevpath)) { - ownFillEl3 = tr.append('path') - .classed('js-fill', true); + (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)) { + trace._ownFill = tr.select('.js-fill.js-tozero'); + if (!trace._ownFill.size()) { + trace._ownFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tozero'); + } + } else { + tr.selectAll('.js-fill.js-tozero').remove(); + trace._ownFill = null; } - else ownFillEl3 = null; // make the fill-to-next path now for the NEXT trace, so it shows // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if(nexttonext) tonext = nexttonext.datum(d); + if (trace._nexttrace) { + trace._nextFill = tr.select('.js-fill.js-tonext'); + if (!trace._nextFill.size()) { + trace._nextFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tonext'); + } + } else { + tr.selectAll('.js-fill.js-tonext').remove(); + trace._nextFill = null; + } + }); +} + - // now make a new nexttonext for next time - nexttonext = tr.append('path').classed('js-fill', true); +function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { + selectMarkers(gd, plotinfo, cdscatter); + + function transition (selection) { + return selection.transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing); + } + + var xa = plotinfo.x(), + ya = plotinfo.y(); + + var trace = cdscatter[0].trace, + line = trace.line, + tr = d3.select(group); + + // (so error bars can find them along with bars) + // error bars are at the bottom + tr.call(ErrorBars.plot, plotinfo); + + if(trace.visible !== true) return; + + // BUILD LINES AND FILLS + var ownFillEl3, tonext, nexttonext; + var ownFillDir = trace.fill.charAt(trace.fill.length - 1); + if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; + + // store node for tweaking by selectPoints + cdscatter[0].node3 = tr; + + arraysToCalcdata(cdscatter); + + var prevpath = ''; + var prevtrace = trace._prevtrace; + + if (prevtrace) { + prevpath = prevtrace._revpath || ''; + tonext = prevtrace._nextFill; + } + + var thispath, + thisrevpath, + // fullpath is all paths for this curve, joined together straight + // across gaps, for filling + fullpath = '', + // revpath is fullpath reversed, for fill-to-next + revpath = '', + // functions for converting a point array to a path + pathfn, revpathbase, revpathfn; + + ownFillEl3 = trace._ownFill; + + if(subTypes.hasLines(trace) || trace.fill !== 'none') { + + if (tonext) { + // This tells .style which trace to use for fill information: + tonext.datum(cdscatter); + } if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { pathfn = Drawing.steps(line.shape); @@ -93249,7 +95774,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { return revpathbase(pts.reverse()); }; - var segments = linePoints(d, { + var segments = linePoints(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -93279,7 +95804,12 @@ module.exports = function plot(gd, plotinfo, cdscatter) { revpath = thisrevpath + 'Z' + revpath; } if(subTypes.hasLines(trace) && pts.length > 1) { - tr.append('path').classed('js-line', true).attr('d', thispath); + var lineJoin = tr.selectAll('.js-line').data([cdscatter]); + + lineJoin.enter() + .append('path').classed('js-line', true).attr('d', thispath); + + transition(lineJoin).attr('d', thispath); } } if(ownFillEl3) { @@ -93294,10 +95824,11 @@ module.exports = function plot(gd, plotinfo, cdscatter) { // fill to zero: full trace path, plus extension of // the endpoints to the appropriate axis - ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + transition(ownFillEl3).attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + } else { + // fill to self: just join the path to itself + transition(ownFillEl3).attr('d', fullpath + 'Z'); } - // fill to self: just join the path to itself - else ownFillEl3.attr('d', fullpath + 'Z'); } } else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { @@ -93307,7 +95838,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { // contours, we just add the two paths closed on themselves. // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. - tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); + transition(tonext).attr('d', fullpath + 'Z' + prevpath + 'Z'); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -93315,48 +95846,77 @@ module.exports = function plot(gd, plotinfo, cdscatter) { // y/x, but if they *aren't*, we should ideally do more complicated // things depending on whether the new endpoint projects onto the // existing curve or off the end of it - tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + transition(tonext).attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); } } - prevpath = revpath; } - }); - // remove paths that didn't get used - scattertraces.selectAll('path:not([d])').remove(); + trace._revpath = revpath; + } + function visFilter(d) { return d.filter(function(v) { return v.vis; }); } - scattertraces.append('g') - .attr('class', 'points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); + function keyFunc (d) { + return d.key; + } - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - .enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya); - } - if(showText) { - s.selectAll('g') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - // each text needs to go in its own 'g' in case - // it gets converted to mathjax - .enter().append('g') - .append('text') - .call(Drawing.translatePoints, xa, ya); - } + function getKeyFunc(trace) { + if (trace.key) { + return keyFunc; + } + } + + + function makePoints (d) { + var trace = d[0].trace, + s = d3.select(this), + showMarkers = subTypes.hasMarkers(trace), + showText = subTypes.hasText(trace); + + if((!showMarkers && !showText) || trace.visible !== true) s.remove(); + else { + if(showMarkers) { + var join = s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) + + join.enter().append('path') + .classed('point', true) + .call(Drawing.pointStyle, trace) + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1) + + join.transition() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 0) + .call(Drawing.pointStyle, trace) + + join.exit() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); } - }); + if(showText) { + s.selectAll('g') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + // each text needs to go in its own 'g' in case + // it gets converted to mathjax + .enter().append('g') + .append('text') + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1); + } + } + } + + var pointJoin = tr.selectAll('.points').data([cdscatter]); + + pointJoin.enter().append('g') + .classed('points', true) + .each(makePoints); + + pointJoin.transition() + .duration(0) + .each(makePoints); + + pointJoin.exit().remove(); }; function selectMarkers(gd, plotinfo, cdscatter) { @@ -93365,45 +95925,46 @@ function selectMarkers(gd, plotinfo, cdscatter) { xr = d3.extent(xa.range.map(xa.l2c)), yr = d3.extent(ya.range.map(ya.l2c)); - cdscatter.forEach(function(d, i) { - var trace = d[0].trace; - if(!subTypes.hasMarkers(trace)) return; - // if marker.maxdisplayed is used, select a maximum of - // mnum markers to show, from the set that are in the viewport - var mnum = trace.marker.maxdisplayed; + // XXX: Not okay. Just makes it work for now. + var i = 0; - // TODO: remove some as we get away from the viewport? - if(mnum === 0) return; + var trace = cdscatter[0].trace; + if(!subTypes.hasMarkers(trace)) return; + // if marker.maxdisplayed is used, select a maximum of + // mnum markers to show, from the set that are in the viewport + var mnum = trace.marker.maxdisplayed; - var cd = d.filter(function(v) { - return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; - }), - inc = Math.ceil(cd.length / mnum), - tnum = 0; - cdscatter.forEach(function(cdj, j) { - var tracei = cdj[0].trace; - if(subTypes.hasMarkers(tracei) && - tracei.marker.maxdisplayed > 0 && j < i) { - tnum++; - } - }); + // TODO: remove some as we get away from the viewport? + if(mnum === 0) return; - // if multiple traces use maxdisplayed, stagger which markers we - // display this formula offsets successive traces by 1/3 of the - // increment, adding an extra small amount after each triplet so - // it's not quite periodic - var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); - - // for error bars: save in cd which markers to show - // so we don't have to repeat this - d.forEach(function(v) { delete v.vis; }); - cd.forEach(function(v, i) { - if(Math.round((i + i0) % inc) === 0) v.vis = true; - }); + var cd = cdscatter.filter(function(v) { + return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; + }), + inc = Math.ceil(cd.length / mnum), + tnum = 0; + cdscatter.forEach(function(cdj, j) { + var tracei = cdj[0].trace; + if(subTypes.hasMarkers(tracei) && + tracei.marker.maxdisplayed > 0 && j < i) { + tnum++; + } + }); + + // if multiple traces use maxdisplayed, stagger which markers we + // display this formula offsets successive traces by 1/3 of the + // increment, adding an extra small amount after each triplet so + // it's not quite periodic + var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); + + // for error bars: save in cd which markers to show + // so we don't have to repeat this + cdscatter.forEach(function(v) { delete v.vis; }); + cd.forEach(function(v, i) { + if(Math.round((i + i0) % inc) === 0) v.vis = true; }); } -},{"../../components/drawing":326,"../../components/errorbars":332,"../../lib":382,"./arrays_to_calcdata":555,"./line_points":567,"./subtypes":575,"d3":113}],573:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1300,"./line_points":1312,"./link_traces":1314,"./subtypes":1322,"d3":82}],1319:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93473,7 +96034,67 @@ module.exports = function selectPoints(searchInfo, polygon) { return selection; }; -},{"./subtypes":575}],574:[function(require,module,exports){ +},{"./subtypes":1322}],1320:[function(require,module,exports){ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); +var Axes = require('../../plots/cartesian/axes'); +var Lib = require('../../lib'); + +/** + * setPositions is a bit of a misnomer here. It comes from the box plot + * type that actually does setting of positions. It's the hook though + * that we need to set up links between traces so that trace-level .plot + * doesn't require any links between traces. + */ +module.exports = function setPositions(gd, plotinfo) { + // console.log('setPositions:', plotinfo); + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < gd.calcdata.length; ++i) { + cd = gd.calcdata[i]; + trace = cd[0].trace; + + // console.log('visible:', trace.uid, trace.visible); + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + trace._nexttrace = null; + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + + prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; + } + } + for(i = 0; i < gd.calcdata.length; ++i) { + var trace = gd.calcdata[i][0].trace; + // console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + } +}; + +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199}],1321:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93515,7 +96136,7 @@ module.exports = function style(gd) { s.call(ErrorBars.style); }; -},{"../../components/drawing":326,"../../components/errorbars":332,"d3":113}],575:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../components/errorbars":1077,"d3":82}],1322:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93549,7 +96170,7 @@ module.exports = { } }; -},{}],576:[function(require,module,exports){ +},{}],1323:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93570,7 +96191,7 @@ module.exports = function(traceIn, traceOut, layout, coerce) { Lib.coerceFont(coerce, 'textfont', layout.font); }; -},{"../../lib":382}],577:[function(require,module,exports){ +},{"../../lib":1127}],1324:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93615,7 +96236,7 @@ module.exports = function handleXYDefaults(traceIn, traceOut, coerce) { return len; }; -},{}],578:[function(require,module,exports){ +},{}],1325:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93762,7 +96383,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../constants/gl_markers":369,"../../lib/extend":377,"../scatter/attributes":556}],579:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1326:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93791,7 +96412,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../scatter/arrays_to_calcdata":555,"../scatter/marker_colorscale_calc":570}],580:[function(require,module,exports){ +},{"../scatter/arrays_to_calcdata":1300,"../scatter/marker_colorscale_calc":1316}],1327:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93862,7 +96483,7 @@ function calculateErrors(data, scaleFactor) { module.exports = calculateErrors; -},{"../../components/errorbars/compute_error":330}],581:[function(require,module,exports){ +},{"../../components/errorbars/compute_error":1075}],1328:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94321,7 +96942,7 @@ function createLineWithMarkers(scene, data) { module.exports = createLineWithMarkers; -},{"../../constants/gl3d_dashes":368,"../../constants/gl_markers":369,"../../lib":382,"../../lib/gl_format_color":380,"../../lib/str2rgbarray":394,"../scatter/make_bubble_size_func":569,"./calc_errors":580,"delaunay-triangulate":114,"gl-error3d":121,"gl-line3d":127,"gl-mesh3d":150,"gl-scatter3d":193}],582:[function(require,module,exports){ +},{"../../constants/gl3d_dashes":1113,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../scatter/make_bubble_size_func":1315,"./calc_errors":1327,"delaunay-triangulate":88,"gl-error3d":123,"gl-line3d":193,"gl-mesh3d":253,"gl-scatter3d":905}],1329:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94406,7 +97027,7 @@ function handleXYZDefaults(traceIn, traceOut, coerce) { return len; } -},{"../../components/errorbars/defaults":331,"../../lib":382,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":578}],583:[function(require,module,exports){ +},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1325}],1330:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94444,7 +97065,7 @@ Scatter3D.meta = { module.exports = Scatter3D; -},{"../../constants/gl_markers":369,"../../plots/gl3d":441,"../scatter/colorbar":559,"./attributes":578,"./calc":579,"./convert":581,"./defaults":582}],584:[function(require,module,exports){ +},{"../../constants/gl_markers":1114,"../../plots/gl3d":1186,"../scatter/colorbar":1304,"./attributes":1325,"./calc":1326,"./convert":1328,"./defaults":1329}],1331:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94533,7 +97154,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../../plots/attributes":403,"../scatter/attributes":556}],585:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1332:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94556,7 +97177,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../scatter/marker_colorscale_calc":570}],586:[function(require,module,exports){ +},{"../scatter/marker_colorscale_calc":1316}],1333:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94629,7 +97250,7 @@ function handleLonLatLocDefaults(traceIn, traceOut, coerce) { return len; } -},{"../../lib":382,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":584}],587:[function(require,module,exports){ +},{"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1331}],1334:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94664,7 +97285,7 @@ ScatterGeo.meta = { module.exports = ScatterGeo; -},{"../../plots/geo":426,"../scatter/colorbar":559,"./attributes":584,"./calc":585,"./defaults":586,"./plot":588}],588:[function(require,module,exports){ +},{"../../plots/geo":1171,"../scatter/colorbar":1304,"./attributes":1331,"./calc":1332,"./defaults":1333,"./plot":1335}],1335:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94964,7 +97585,7 @@ function makeEventDataFunc(trace) { }; } -},{"../../components/color":303,"../../components/drawing":326,"../../lib/array_to_calc_item":373,"../../lib/geo_location_utils":379,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../scatter/subtypes":575,"./attributes":584,"d3":113}],589:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../scatter/subtypes":1322,"./attributes":1331,"d3":82}],1336:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95054,7 +97675,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../constants/gl2d_dashes":367,"../../constants/gl_markers":369,"../../lib/extend":377,"../scatter/attributes":556}],590:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1337:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95646,7 +98267,7 @@ function createLineWithMarkers(scene, data) { module.exports = createLineWithMarkers; -},{"../../components/errorbars":332,"../../constants/gl2d_dashes":367,"../../constants/gl_markers":369,"../../lib":382,"../../lib/gl_format_color":380,"../../lib/str2rgbarray":394,"../../plots/cartesian/axes":405,"../scatter/get_trace_color":563,"../scatter/make_bubble_size_func":569,"../scatter/subtypes":575,"fast-isnumeric":117,"gl-error2d":119,"gl-line2d":125,"gl-scatter2d":190,"gl-scatter2d-fancy":185}],591:[function(require,module,exports){ +},{"../../components/errorbars":1077,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../scatter/get_trace_color":1308,"../scatter/make_bubble_size_func":1315,"../scatter/subtypes":1322,"fast-isnumeric":90,"gl-error2d":91,"gl-line2d":160,"gl-scatter2d":781,"gl-scatter2d-fancy":746}],1338:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95703,7 +98324,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); }; -},{"../../components/errorbars/defaults":331,"../../lib":382,"../scatter/constants":560,"../scatter/fillcolor_defaults":562,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/xy_defaults":577,"./attributes":589}],592:[function(require,module,exports){ +},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/constants":1305,"../scatter/fillcolor_defaults":1307,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/xy_defaults":1324,"./attributes":1336}],1339:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95739,7 +98360,7 @@ ScatterGl.meta = { module.exports = ScatterGl; -},{"../../plots/gl2d":438,"../scatter/colorbar":559,"../scatter3d/calc":579,"./attributes":589,"./convert":590,"./defaults":591}],593:[function(require,module,exports){ +},{"../../plots/gl2d":1183,"../scatter/colorbar":1304,"../scatter3d/calc":1326,"./attributes":1336,"./convert":1337,"./defaults":1338}],1340:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95864,7 +98485,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../../plots/attributes":403,"../scatter/attributes":556}],594:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1341:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95963,7 +98584,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../scatter/marker_colorscale_calc":570,"../scatter/subtypes":575,"fast-isnumeric":117}],595:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../scatter/marker_colorscale_calc":1316,"../scatter/subtypes":1322,"fast-isnumeric":90}],1342:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96060,7 +98681,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('hoverinfo', (layout._dataLength === 1) ? 'a+b+c+text' : undefined); }; -},{"../../lib":382,"../scatter/constants":560,"../scatter/fillcolor_defaults":562,"../scatter/line_defaults":566,"../scatter/line_shape_defaults":568,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":593}],596:[function(require,module,exports){ +},{"../../lib":1127,"../scatter/constants":1305,"../scatter/fillcolor_defaults":1307,"../scatter/line_defaults":1311,"../scatter/line_shape_defaults":1313,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1340}],1343:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96110,7 +98731,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return scatterPointData; }; -},{"../../plots/cartesian/axes":405,"../scatter/hover":564}],597:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../scatter/hover":1309}],1344:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96146,7 +98767,7 @@ ScatterTernary.meta = { module.exports = ScatterTernary; -},{"../../plots/ternary":461,"../scatter/colorbar":559,"./attributes":593,"./calc":594,"./defaults":595,"./hover":596,"./plot":598,"./select":599,"./style":600}],598:[function(require,module,exports){ +},{"../../plots/ternary":1206,"../scatter/colorbar":1304,"./attributes":1340,"./calc":1341,"./defaults":1342,"./hover":1343,"./plot":1345,"./select":1346,"./style":1347}],1345:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96192,7 +98813,7 @@ module.exports = function plot(ternary, data) { scatterPlot(ternary.graphDiv, plotinfo, calcdata); }; -},{"../scatter/plot":572}],599:[function(require,module,exports){ +},{"../scatter/plot":1318}],1346:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96227,7 +98848,7 @@ module.exports = function selectPoints(searchInfo, polygon) { return selection; }; -},{"../scatter/select":573}],600:[function(require,module,exports){ +},{"../scatter/select":1319}],1347:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96256,7 +98877,7 @@ module.exports = function style(gd) { scatterStyle(gd); }; -},{"../scatter/style":574}],601:[function(require,module,exports){ +},{"../scatter/style":1321}],1348:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96504,7 +99125,7 @@ module.exports = { } }; -},{"../../components/color":303,"../../components/colorscale/attributes":309,"../../lib/extend":377}],602:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/attributes":1054,"../../lib/extend":1122}],1349:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96528,7 +99149,7 @@ module.exports = function calc(gd, trace) { } }; -},{"../../components/colorscale/calc":310}],603:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055}],1350:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96575,7 +99196,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,"d3":113,"fast-isnumeric":117}],604:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1351:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96938,7 +99559,7 @@ function createSurfaceTrace(scene, data) { module.exports = createSurfaceTrace; -},{"../../lib/str2rgbarray":394,"gl-surface3d":221,"ndarray":253,"ndarray-fill":246,"ndarray-homography":251,"ndarray-ops":252,"tinycolor2":274}],605:[function(require,module,exports){ +},{"../../lib/str2rgbarray":1139,"gl-surface3d":1003,"ndarray":1031,"ndarray-fill":1009,"ndarray-homography":1025,"ndarray-ops":1026,"tinycolor2":1042}],1352:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97055,7 +99676,7 @@ function mapLegacy(traceIn, oldAttr, newAttr) { } } -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":601}],606:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1348}],1353:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97098,5 +99719,5 @@ Surface.meta = { module.exports = Surface; -},{"../../plots/gl3d":441,"./attributes":601,"./calc":602,"./colorbar":603,"./convert":604,"./defaults":605}]},{},[12])(12) +},{"../../plots/gl3d":1186,"./attributes":1348,"./calc":1349,"./colorbar":1350,"./convert":1351,"./defaults":1352}]},{},[12])(12) }); \ No newline at end of file diff --git a/dist/plotly.js b/dist/plotly.js index 6f895d0fe5e..2de90857edb 100644 --- a/dist/plotly.js +++ b/dist/plotly.js @@ -68,7 +68,7 @@ for(var selector in rules) { Plotly.Lib.addStyleRule(fullSelector, rules[selector]); } -},{"../src/plotly":402}],2:[function(require,module,exports){ +},{"../src/plotly":1147}],2:[function(require,module,exports){ 'use strict'; module.exports = { @@ -199,7 +199,7 @@ module.exports = { module.exports = require('../src/traces/bar'); -},{"../src/traces/bar":480}],4:[function(require,module,exports){ +},{"../src/traces/bar":1225}],4:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -210,7 +210,7 @@ module.exports = require('../src/traces/bar'); module.exports = require('../src/traces/box'); -},{"../src/traces/box":491}],5:[function(require,module,exports){ +},{"../src/traces/box":1236}],5:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -221,7 +221,7 @@ module.exports = require('../src/traces/box'); module.exports = require('../src/traces/choropleth'); -},{"../src/traces/choropleth":500}],6:[function(require,module,exports){ +},{"../src/traces/choropleth":1245}],6:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -232,7 +232,7 @@ module.exports = require('../src/traces/choropleth'); module.exports = require('../src/traces/contour'); -},{"../src/traces/contour":507}],7:[function(require,module,exports){ +},{"../src/traces/contour":1252}],7:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -243,7 +243,7 @@ module.exports = require('../src/traces/contour'); module.exports = require('../src/core'); -},{"../src/core":371}],8:[function(require,module,exports){ +},{"../src/core":1116}],8:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -254,7 +254,7 @@ module.exports = require('../src/core'); module.exports = require('../src/traces/heatmap'); -},{"../src/traces/heatmap":519}],9:[function(require,module,exports){ +},{"../src/traces/heatmap":1264}],9:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -265,7 +265,7 @@ module.exports = require('../src/traces/heatmap'); module.exports = require('../src/traces/histogram'); -},{"../src/traces/histogram":530}],10:[function(require,module,exports){ +},{"../src/traces/histogram":1275}],10:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -276,7 +276,7 @@ module.exports = require('../src/traces/histogram'); module.exports = require('../src/traces/histogram2d'); -},{"../src/traces/histogram2d":535}],11:[function(require,module,exports){ +},{"../src/traces/histogram2d":1280}],11:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -287,7 +287,7 @@ module.exports = require('../src/traces/histogram2d'); module.exports = require('../src/traces/histogram2dcontour'); -},{"../src/traces/histogram2dcontour":539}],12:[function(require,module,exports){ +},{"../src/traces/histogram2dcontour":1284}],12:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -336,7 +336,7 @@ module.exports = Core; module.exports = require('../src/traces/mesh3d'); -},{"../src/traces/mesh3d":543}],14:[function(require,module,exports){ +},{"../src/traces/mesh3d":1288}],14:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -347,7 +347,7 @@ module.exports = require('../src/traces/mesh3d'); module.exports = require('../src/traces/pie'); -},{"../src/traces/pie":549}],15:[function(require,module,exports){ +},{"../src/traces/pie":1294}],15:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -358,7 +358,7 @@ module.exports = require('../src/traces/pie'); module.exports = require('../src/traces/scatter3d'); -},{"../src/traces/scatter3d":583}],16:[function(require,module,exports){ +},{"../src/traces/scatter3d":1330}],16:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -369,7 +369,7 @@ module.exports = require('../src/traces/scatter3d'); module.exports = require('../src/traces/scattergeo'); -},{"../src/traces/scattergeo":587}],17:[function(require,module,exports){ +},{"../src/traces/scattergeo":1334}],17:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -380,7 +380,7 @@ module.exports = require('../src/traces/scattergeo'); module.exports = require('../src/traces/scattergl'); -},{"../src/traces/scattergl":592}],18:[function(require,module,exports){ +},{"../src/traces/scattergl":1339}],18:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -391,7 +391,7 @@ module.exports = require('../src/traces/scattergl'); module.exports = require('../src/traces/scatterternary'); -},{"../src/traces/scatterternary":597}],19:[function(require,module,exports){ +},{"../src/traces/scatterternary":1344}],19:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -402,300 +402,206 @@ module.exports = require('../src/traces/scatterternary'); module.exports = require('../src/traces/surface'); -},{"../src/traces/surface":606}],20:[function(require,module,exports){ +},{"../src/traces/surface":1353}],20:[function(require,module,exports){ 'use strict' -module.exports = createFilteredVector +var bsearch = require('binary-search-bounds') +var m4interp = require('mat4-interpolate') +var invert44 = require('gl-mat4/invert') +var rotateX = require('gl-mat4/rotateX') +var rotateY = require('gl-mat4/rotateY') +var rotateZ = require('gl-mat4/rotateZ') +var lookAt = require('gl-mat4/lookAt') +var translate = require('gl-mat4/translate') +var scale = require('gl-mat4/scale') +var normalize = require('gl-vec3/normalize') -var cubicHermite = require('cubic-hermite') -var bsearch = require('binary-search-bounds') +var DEFAULT_CENTER = [0,0,0] -function clamp(lo, hi, x) { - return Math.min(hi, Math.max(lo, x)) -} +module.exports = createMatrixCameraController -function FilteredVector(state0, velocity0, t0) { - this.dimension = state0.length - this.bounds = [ new Array(this.dimension), new Array(this.dimension) ] - for(var i=0; i= n-1) { - var ptr = state.length-1 - var tf = t - time[n-1] - for(var i=0; i= n-1) { - var ptr = state.length-1 - var tf = t - time[n-1] - for(var i=0; i=0; --i) { - if(velocity[--ptr]) { - return false - } + var imat = this.computedInverse + invert44(imat, mat) + var eye = this.computedEye + var w = imat[15] + eye[0] = imat[12]/w + eye[1] = imat[13]/w + eye[2] = imat[14]/w + + var center = this.computedCenter + var radius = Math.exp(this.computedRadius[0]) + for(var i=0; i<3; ++i) { + center[i] = eye[i] - mat[2+4*i] * radius } - return true } -proto.jump = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t < t0 || arguments.length !== d+1) { +proto.idle = function(t) { + if(t < this.lastT()) { return } - var state = this._state - var velocity = this._velocity - var ptr = state.length-this.dimension - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - this._time.push(t0, t) - for(var j=0; j<2; ++j) { - for(var i=0; i0; --i) { - state.push(clamp(lo[i-1], hi[i-1], arguments[i])) - velocity.push(0) - } } -proto.push = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t < t0 || arguments.length !== d+1) { +proto.flush = function(t) { + var idx = bsearch.gt(this._time, t) - 2 + if(idx < 0) { return } - var state = this._state - var velocity = this._velocity - var ptr = state.length-this.dimension - var dt = t - t0 - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var sf = (dt > 1e-6) ? 1/dt : 0 - this._time.push(t) - for(var i=d; i>0; --i) { - var xc = clamp(lo[i-1], hi[i-1], arguments[i]) - state.push(xc) - velocity.push((xc - state[ptr++]) * sf) - } + this._time.slice(0, idx) + this._components.slice(0, 16*idx) } -proto.set = function(t) { - var d = this.dimension - if(t < this.lastT() || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - this._time.push(t) - for(var i=d; i>0; --i) { - state.push(clamp(lo[i-1], hi[i-1], arguments[i])) - velocity.push(0) - } +proto.lastT = function() { + return this._time[this._time.length-1] } -proto.move = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t <= t0 || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var statePtr = state.length - this.dimension - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var dt = t - t0 - var sf = (dt > 1e-6) ? 1/dt : 0.0 - this._time.push(t) - for(var i=d; i>0; --i) { - var dx = arguments[i] - state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx)) - velocity.push(dx * sf) +proto.lookAt = function(t, eye, center, up) { + this.recalcMatrix(t) + eye = eye || this.computedEye + center = center || DEFAULT_CENTER + up = up || this.computedUp + this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) + var d2 = 0.0 + for(var i=0; i<3; ++i) { + d2 += Math.pow(center[i] - eye[i], 2) } + d2 = Math.log(Math.sqrt(d2)) + this.computedRadius[0] = d2 } -proto.idle = function(t) { - var t0 = this.lastT() - if(t < t0) { +proto.rotate = function(t, yaw, pitch, roll) { + this.recalcMatrix(t) + var mat = this.computedInverse + if(yaw) rotateY(mat, mat, yaw) + if(pitch) rotateX(mat, mat, pitch) + if(roll) rotateZ(mat, mat, roll) + this.setMatrix(t, invert44(this.computedMatrix, mat)) +} + +var tvec = [0,0,0] + +proto.pan = function(t, dx, dy, dz) { + tvec[0] = -(dx || 0.0) + tvec[1] = -(dy || 0.0) + tvec[2] = -(dz || 0.0) + this.recalcMatrix(t) + var mat = this.computedInverse + translate(mat, mat, tvec) + this.setMatrix(t, invert44(mat, mat)) +} + +proto.translate = function(t, dx, dy, dz) { + tvec[0] = dx || 0.0 + tvec[1] = dy || 0.0 + tvec[2] = dz || 0.0 + this.recalcMatrix(t) + var mat = this.computedMatrix + translate(mat, mat, tvec) + this.setMatrix(t, mat) +} + +proto.setMatrix = function(t, mat) { + if(t < this.lastT()) { return } - var d = this.dimension - var state = this._state - var velocity = this._velocity - var statePtr = state.length-d - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var dt = t - t0 this._time.push(t) - for(var i=d-1; i>=0; --i) { - state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) - velocity.push(0) - statePtr += 1 + for(var i=0; i<16; ++i) { + this._components.push(mat[i]) } } -function getZero(d) { - var result = new Array(d) - for(var i=0; i=0; --i) { - f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i] - } - return f - } - return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1 -} - -function cubicHermite(p0, v0, p1, v1, t, f) { - var ti = (t-1), t2 = t*t, ti2 = ti*ti, - h00 = (1+2*t)*ti2, - h10 = t*ti2, - h01 = t2*(3-2*t), - h11 = t2*ti - if(p0.length) { - if(!f) { - f = new Array(p0.length) - } - for(var i=p0.length-1; i>=0; --i) { - f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i] - } - return f - } - return h00*p0 + h10*v0 + h01*p1 + h11*v1 -} - -module.exports = cubicHermite -module.exports.derivative = dcubicHermite -},{}],23:[function(require,module,exports){ module.exports = cross; /** @@ -817,7 +683,7 @@ function cross(out, a, b) { out[2] = ax * by - ay * bx return out } -},{}],24:[function(require,module,exports){ +},{}],23:[function(require,module,exports){ module.exports = dot; /** @@ -830,7 +696,7 @@ module.exports = dot; function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -},{}],25:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ module.exports = length; /** @@ -845,7 +711,7 @@ function length(a) { z = a[2] return Math.sqrt(x*x + y*y + z*z) } -},{}],26:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ module.exports = lerp; /** @@ -866,7 +732,7 @@ function lerp(out, a, b, t) { out[2] = az + t * (b[2] - az) return out } -},{}],27:[function(require,module,exports){ +},{}],26:[function(require,module,exports){ module.exports = normalize; /** @@ -890,252 +756,51 @@ function normalize(out, a) { } return out } -},{}],28:[function(require,module,exports){ -'use strict' +},{}],27:[function(require,module,exports){ +var lerp = require('gl-vec3/lerp') -var bsearch = require('binary-search-bounds') -var m4interp = require('mat4-interpolate') -var invert44 = require('gl-mat4/invert') -var rotateX = require('gl-mat4/rotateX') -var rotateY = require('gl-mat4/rotateY') -var rotateZ = require('gl-mat4/rotateZ') -var lookAt = require('gl-mat4/lookAt') -var translate = require('gl-mat4/translate') -var scale = require('gl-mat4/scale') -var normalize = require('gl-vec3/normalize') +var recompose = require('mat4-recompose') +var decompose = require('mat4-decompose') +var determinant = require('gl-mat4/determinant') +var slerp = require('quat-slerp') -var DEFAULT_CENTER = [0,0,0] +var state0 = state() +var state1 = state() +var tmp = state() -module.exports = createMatrixCameraController +module.exports = interpolate +function interpolate(out, start, end, alpha) { + if (determinant(start) === 0 || determinant(end) === 0) + return false -function MatrixCameraController(initialMatrix) { - this._components = initialMatrix.slice() - this._time = [0] - this.prevMatrix = initialMatrix.slice() - this.nextMatrix = initialMatrix.slice() - this.computedMatrix = initialMatrix.slice() - this.computedInverse = initialMatrix.slice() - this.computedEye = [0,0,0] - this.computedUp = [0,0,0] - this.computedCenter = [0,0,0] - this.computedRadius = [0] - this._limits = [-Infinity, Infinity] + //decompose the start and end matrices into individual components + var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) + var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) + if (!r0 || !r1) + return false + + + //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) + lerp(tmp.translate, state0.translate, state1.translate, alpha) + lerp(tmp.skew, state0.skew, state1.skew, alpha) + lerp(tmp.scale, state0.scale, state1.scale, alpha) + lerp(tmp.perspective, state0.perspective, state1.perspective, alpha) + slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha) + + //and recompose into our 'out' matrix + recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion) + return true } -var proto = MatrixCameraController.prototype - -proto.recalcMatrix = function(t) { - var time = this._time - var tidx = bsearch.le(time, t) - var mat = this.computedMatrix - if(tidx < 0) { - return - } - var comps = this._components - if(tidx === time.length-1) { - var ptr = 16*tidx - for(var i=0; i<16; ++i) { - mat[i] = comps[ptr++] - } - } else { - var dt = (time[tidx+1] - time[tidx]) - var ptr = 16*tidx - var prev = this.prevMatrix - var allEqual = true - for(var i=0; i<16; ++i) { - prev[i] = comps[ptr++] - } - var next = this.nextMatrix - for(var i=0; i<16; ++i) { - next[i] = comps[ptr++] - allEqual = allEqual && (prev[i] === next[i]) - } - if(dt < 1e-6 || allEqual) { - for(var i=0; i<16; ++i) { - mat[i] = prev[i] - } - } else { - m4interp(mat, prev, next, (t - time[tidx])/dt) - } - } - - var up = this.computedUp - up[0] = mat[1] - up[1] = mat[5] - up[2] = mat[6] - normalize(up, up) - - var imat = this.computedInverse - invert44(imat, mat) - var eye = this.computedEye - var w = imat[15] - eye[0] = imat[12]/w - eye[1] = imat[13]/w - eye[2] = imat[14]/w - - var center = this.computedCenter - var radius = Math.exp(this.computedRadius[0]) - for(var i=0; i<3; ++i) { - center[i] = eye[i] - mat[2+4*i] * radius - } -} - -proto.idle = function(t) { - if(t < this.lastT()) { - return - } - var mc = this._components - var ptr = mc.length-16 - for(var i=0; i<16; ++i) { - mc.push(mc[ptr++]) - } - this._time.push(t) -} - -proto.flush = function(t) { - var idx = bsearch.gt(this._time, t) - 2 - if(idx < 0) { - return - } - this._time.slice(0, idx) - this._components.slice(0, 16*idx) -} - -proto.lastT = function() { - return this._time[this._time.length-1] -} - -proto.lookAt = function(t, eye, center, up) { - this.recalcMatrix(t) - eye = eye || this.computedEye - center = center || DEFAULT_CENTER - up = up || this.computedUp - this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) - var d2 = 0.0 - for(var i=0; i<3; ++i) { - d2 += Math.pow(center[i] - eye[i], 2) - } - d2 = Math.log(Math.sqrt(d2)) - this.computedRadius[0] = d2 -} - -proto.rotate = function(t, yaw, pitch, roll) { - this.recalcMatrix(t) - var mat = this.computedInverse - if(yaw) rotateY(mat, mat, yaw) - if(pitch) rotateX(mat, mat, pitch) - if(roll) rotateZ(mat, mat, roll) - this.setMatrix(t, invert44(this.computedMatrix, mat)) -} - -var tvec = [0,0,0] - -proto.pan = function(t, dx, dy, dz) { - tvec[0] = -(dx || 0.0) - tvec[1] = -(dy || 0.0) - tvec[2] = -(dz || 0.0) - this.recalcMatrix(t) - var mat = this.computedInverse - translate(mat, mat, tvec) - this.setMatrix(t, invert44(mat, mat)) -} - -proto.translate = function(t, dx, dy, dz) { - tvec[0] = dx || 0.0 - tvec[1] = dy || 0.0 - tvec[2] = dz || 0.0 - this.recalcMatrix(t) - var mat = this.computedMatrix - translate(mat, mat, tvec) - this.setMatrix(t, mat) -} - -proto.setMatrix = function(t, mat) { - if(t < this.lastT()) { - return - } - this._time.push(t) - for(var i=0; i<16; ++i) { - this._components.push(mat[i]) - } -} - -proto.setDistance = function(t, d) { - this.computedRadius[0] = d -} - -proto.setDistanceLimits = function(a,b) { - var lim = this._limits - lim[0] = a - lim[1] = b -} - -proto.getDistanceLimits = function(out) { - var lim = this._limits - if(out) { - out[0] = lim[0] - out[1] = lim[1] - return out - } - return lim -} - -function createMatrixCameraController(options) { - options = options || {} - var matrix = options.matrix || - [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] - return new MatrixCameraController(matrix) -} -},{"binary-search-bounds":29,"gl-mat4/invert":137,"gl-mat4/lookAt":138,"gl-mat4/rotateX":142,"gl-mat4/rotateY":143,"gl-mat4/rotateZ":144,"gl-mat4/scale":145,"gl-mat4/translate":146,"gl-vec3/normalize":27,"mat4-interpolate":30}],29:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],30:[function(require,module,exports){ -var lerp = require('gl-vec3/lerp') - -var recompose = require('mat4-recompose') -var decompose = require('mat4-decompose') -var determinant = require('gl-mat4/determinant') -var slerp = require('quat-slerp') - -var state0 = state() -var state1 = state() -var tmp = state() - -module.exports = interpolate -function interpolate(out, start, end, alpha) { - if (determinant(start) === 0 || determinant(end) === 0) - return false - - //decompose the start and end matrices into individual components - var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) - var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) - if (!r0 || !r1) - return false - - - //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) - lerp(tmp.translate, state0.translate, state1.translate, alpha) - lerp(tmp.skew, state0.skew, state1.skew, alpha) - lerp(tmp.scale, state0.scale, state1.scale, alpha) - lerp(tmp.perspective, state0.perspective, state1.perspective, alpha) - slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha) - - //and recompose into our 'out' matrix - recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion) - return true -} - -function state() { - return { - translate: vec3(), - scale: vec3(1), - skew: vec3(), - perspective: vec4(), - quaternion: vec4() - } -} +function state() { + return { + translate: vec3(), + scale: vec3(1), + skew: vec3(), + perspective: vec4(), + quaternion: vec4() + } +} function vec3(n) { return [n||0,n||0,n||0] @@ -1144,7 +809,7 @@ function vec3(n) { function vec4() { return [0,0,0,1] } -},{"gl-mat4/determinant":133,"gl-vec3/lerp":26,"mat4-decompose":31,"mat4-recompose":33,"quat-slerp":34}],31:[function(require,module,exports){ +},{"gl-mat4/determinant":236,"gl-vec3/lerp":25,"mat4-decompose":28,"mat4-recompose":30,"quat-slerp":31}],28:[function(require,module,exports){ /*jshint unused:true*/ /* Input: matrix ; a 4x4 matrix @@ -1324,7 +989,7 @@ function combine(out, a, b, scale1, scale2) { out[1] = a[1] * scale1 + b[1] * scale2 out[2] = a[2] * scale1 + b[2] * scale2 } -},{"./normalize":32,"gl-mat4/clone":131,"gl-mat4/create":132,"gl-mat4/determinant":133,"gl-mat4/invert":137,"gl-mat4/transpose":147,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/length":25,"gl-vec3/normalize":27}],32:[function(require,module,exports){ +},{"./normalize":29,"gl-mat4/clone":234,"gl-mat4/create":235,"gl-mat4/determinant":236,"gl-mat4/invert":240,"gl-mat4/transpose":250,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],29:[function(require,module,exports){ module.exports = function normalize(out, mat) { var m44 = mat[15] // Cannot normalize. @@ -1335,7 +1000,7 @@ module.exports = function normalize(out, mat) { out[i] = mat[i] * scale return true } -},{}],33:[function(require,module,exports){ +},{}],30:[function(require,module,exports){ /* Input: translation ; a 3 component vector scale ; a 3 component vector @@ -1396,9 +1061,9 @@ module.exports = function recomposeMat4(matrix, translation, scale, skew, perspe mat4.scale(matrix, matrix, scale) return matrix } -},{"gl-mat4/create":132,"gl-mat4/fromRotationTranslation":135,"gl-mat4/identity":136,"gl-mat4/multiply":139,"gl-mat4/scale":145,"gl-mat4/translate":146}],34:[function(require,module,exports){ +},{"gl-mat4/create":235,"gl-mat4/fromRotationTranslation":238,"gl-mat4/identity":239,"gl-mat4/multiply":242,"gl-mat4/scale":248,"gl-mat4/translate":249}],31:[function(require,module,exports){ module.exports = require('gl-quat/slerp') -},{"gl-quat/slerp":35}],35:[function(require,module,exports){ +},{"gl-quat/slerp":32}],32:[function(require,module,exports){ module.exports = slerp /** @@ -1451,7 +1116,7 @@ function slerp (out, a, b, t) { return out } -},{}],36:[function(require,module,exports){ +},{}],33:[function(require,module,exports){ 'use strict' module.exports = quatFromFrame @@ -1493,135 +1158,470 @@ function quatFromFrame( } return out } -},{}],37:[function(require,module,exports){ +},{}],34:[function(require,module,exports){ 'use strict' -module.exports = createOrbitController - -var filterVector = require('filtered-vector') -var lookAt = require('gl-mat4/lookAt') -var mat4FromQuat = require('gl-mat4/fromQuat') -var invert44 = require('gl-mat4/invert') -var quatFromFrame = require('./lib/quatFromFrame') +module.exports = createFilteredVector -function len3(x,y,z) { - return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) -} +var cubicHermite = require('cubic-hermite') +var bsearch = require('binary-search-bounds') -function len4(w,x,y,z) { - return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) +function clamp(lo, hi, x) { + return Math.min(hi, Math.max(lo, x)) } -function normalize4(out, a) { - var ax = a[0] - var ay = a[1] - var az = a[2] - var aw = a[3] - var al = len4(ax, ay, az, aw) - if(al > 1e-6) { - out[0] = ax/al - out[1] = ay/al - out[2] = az/al - out[3] = aw/al - } else { - out[0] = out[1] = out[2] = 0.0 - out[3] = 1.0 +function FilteredVector(state0, velocity0, t0) { + this.dimension = state0.length + this.bounds = [ new Array(this.dimension), new Array(this.dimension) ] + for(var i=0; i= n-1) { + var ptr = state.length-1 + var tf = t - time[n-1] + for(var i=0; i= n-1) { + var ptr = state.length-1 + var tf = t - time[n-1] + for(var i=0; i=0; --i) { + if(velocity[--ptr]) { + return false } - mat[12+i] = -rr } + return true } -proto.getMatrix = function(t, result) { - this.recalcMatrix(t) - var m = this.computedMatrix - if(result) { - for(var i=0; i<16; ++i) { - result[i] = m[i] +proto.jump = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t < t0 || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var ptr = state.length-this.dimension + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + this._time.push(t0, t) + for(var j=0; j<2; ++j) { + for(var i=0; i0; --i) { + state.push(clamp(lo[i-1], hi[i-1], arguments[i])) + velocity.push(0) + } } -proto.idle = function(t) { - this.center.idle(t) - this.radius.idle(t) - this.rotation.idle(t) +proto.push = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t < t0 || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var ptr = state.length-this.dimension + var dt = t - t0 + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var sf = (dt > 1e-6) ? 1/dt : 0 + this._time.push(t) + for(var i=d; i>0; --i) { + var xc = clamp(lo[i-1], hi[i-1], arguments[i]) + state.push(xc) + velocity.push((xc - state[ptr++]) * sf) + } } -proto.flush = function(t) { - this.center.flush(t) - this.radius.flush(t) - this.rotation.flush(t) +proto.set = function(t) { + var d = this.dimension + if(t < this.lastT() || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + this._time.push(t) + for(var i=d; i>0; --i) { + state.push(clamp(lo[i-1], hi[i-1], arguments[i])) + velocity.push(0) + } } -proto.pan = function(t, dx, dy, dz) { - dx = dx || 0.0 - dy = dy || 0.0 - dz = dz || 0.0 - - this.recalcMatrix(t) - var mat = this.computedMatrix +proto.move = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t <= t0 || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var statePtr = state.length - this.dimension + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var dt = t - t0 + var sf = (dt > 1e-6) ? 1/dt : 0.0 + this._time.push(t) + for(var i=d; i>0; --i) { + var dx = arguments[i] + state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx)) + velocity.push(dx * sf) + } +} - var ux = mat[1] - var uy = mat[5] - var uz = mat[9] - var ul = len3(ux, uy, uz) - ux /= ul +proto.idle = function(t) { + var t0 = this.lastT() + if(t < t0) { + return + } + var d = this.dimension + var state = this._state + var velocity = this._velocity + var statePtr = state.length-d + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var dt = t - t0 + this._time.push(t) + for(var i=d-1; i>=0; --i) { + state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) + velocity.push(0) + statePtr += 1 + } +} + +function getZero(d) { + var result = new Array(d) + for(var i=0; i=0; --i) { + f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i] + } + return f + } + return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1 +} + +function cubicHermite(p0, v0, p1, v1, t, f) { + var ti = (t-1), t2 = t*t, ti2 = ti*ti, + h00 = (1+2*t)*ti2, + h10 = t*ti2, + h01 = t2*(3-2*t), + h11 = t2*ti + if(p0.length) { + if(!f) { + f = new Array(p0.length) + } + for(var i=p0.length-1; i>=0; --i) { + f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i] + } + return f + } + return h00*p0 + h10*v0 + h01*p1 + h11*v1 +} + +module.exports = cubicHermite +module.exports.derivative = dcubicHermite +},{}],37:[function(require,module,exports){ +'use strict' + +module.exports = createOrbitController + +var filterVector = require('filtered-vector') +var lookAt = require('gl-mat4/lookAt') +var mat4FromQuat = require('gl-mat4/fromQuat') +var invert44 = require('gl-mat4/invert') +var quatFromFrame = require('./lib/quatFromFrame') + +function len3(x,y,z) { + return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) +} + +function len4(w,x,y,z) { + return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) +} + +function normalize4(out, a) { + var ax = a[0] + var ay = a[1] + var az = a[2] + var aw = a[3] + var al = len4(ax, ay, az, aw) + if(al > 1e-6) { + out[0] = ax/al + out[1] = ay/al + out[2] = az/al + out[3] = aw/al + } else { + out[0] = out[1] = out[2] = 0.0 + out[3] = 1.0 + } +} + +function OrbitCameraController(initQuat, initCenter, initRadius) { + this.radius = filterVector([initRadius]) + this.center = filterVector(initCenter) + this.rotation = filterVector(initQuat) + + this.computedRadius = this.radius.curve(0) + this.computedCenter = this.center.curve(0) + this.computedRotation = this.rotation.curve(0) + this.computedUp = [0.1,0,0] + this.computedEye = [0.1,0,0] + this.computedMatrix = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] + + this.recalcMatrix(0) +} + +var proto = OrbitCameraController.prototype + +proto.lastT = function() { + return Math.max( + this.radius.lastT(), + this.center.lastT(), + this.rotation.lastT()) +} + +proto.recalcMatrix = function(t) { + this.radius.curve(t) + this.center.curve(t) + this.rotation.curve(t) + + var quat = this.computedRotation + normalize4(quat, quat) + + var mat = this.computedMatrix + mat4FromQuat(mat, quat) + + var center = this.computedCenter + var eye = this.computedEye + var up = this.computedUp + var radius = Math.exp(this.computedRadius[0]) + + eye[0] = center[0] + radius * mat[2] + eye[1] = center[1] + radius * mat[6] + eye[2] = center[2] + radius * mat[10] + up[0] = mat[1] + up[1] = mat[5] + up[2] = mat[9] + + for(var i=0; i<3; ++i) { + var rr = 0.0 + for(var j=0; j<3; ++j) { + rr += mat[i+4*j] * eye[j] + } + mat[12+i] = -rr + } +} + +proto.getMatrix = function(t, result) { + this.recalcMatrix(t) + var m = this.computedMatrix + if(result) { + for(var i=0; i<16; ++i) { + result[i] = m[i] + } + return result + } + return m +} + +proto.idle = function(t) { + this.center.idle(t) + this.radius.idle(t) + this.rotation.idle(t) +} + +proto.flush = function(t) { + this.center.flush(t) + this.radius.flush(t) + this.rotation.flush(t) +} + +proto.pan = function(t, dx, dy, dz) { + dx = dx || 0.0 + dy = dy || 0.0 + dz = dz || 0.0 + + this.recalcMatrix(t) + var mat = this.computedMatrix + + var ux = mat[1] + var uy = mat[5] + var uz = mat[9] + var ul = len3(ux, uy, uz) + ux /= ul uy /= ul uz /= ul @@ -1887,7 +1887,19 @@ function createOrbitController(options) { return result } -},{"./lib/quatFromFrame":36,"filtered-vector":20,"gl-mat4/fromQuat":134,"gl-mat4/invert":137,"gl-mat4/lookAt":138}],38:[function(require,module,exports){ +},{"./lib/quatFromFrame":33,"filtered-vector":34,"gl-mat4/fromQuat":237,"gl-mat4/invert":240,"gl-mat4/lookAt":241}],38:[function(require,module,exports){ +arguments[4][34][0].apply(exports,arguments) +},{"binary-search-bounds":39,"cubic-hermite":40,"dup":34}],39:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],40:[function(require,module,exports){ +arguments[4][36][0].apply(exports,arguments) +},{"dup":36}],41:[function(require,module,exports){ +arguments[4][22][0].apply(exports,arguments) +},{"dup":22}],42:[function(require,module,exports){ +arguments[4][23][0].apply(exports,arguments) +},{"dup":23}],43:[function(require,module,exports){ +arguments[4][26][0].apply(exports,arguments) +},{"dup":26}],44:[function(require,module,exports){ 'use strict' module.exports = createTurntableController @@ -2460,7 +2472,7 @@ function createTurntableController(options) { theta, phi) } -},{"filtered-vector":20,"gl-mat4/invert":137,"gl-mat4/rotate":141,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/normalize":27}],39:[function(require,module,exports){ +},{"filtered-vector":38,"gl-mat4/invert":240,"gl-mat4/rotate":244,"gl-vec3/cross":41,"gl-vec3/dot":42,"gl-vec3/normalize":43}],45:[function(require,module,exports){ 'use strict' module.exports = createViewController @@ -2583,7 +2595,7 @@ function createViewController(options) { matrix: matrix }, mode) } -},{"matrix-camera-controller":28,"orbit-camera-controller":37,"turntable-camera-controller":38}],40:[function(require,module,exports){ +},{"matrix-camera-controller":20,"orbit-camera-controller":37,"turntable-camera-controller":44}],46:[function(require,module,exports){ module.exports = alphaShape var ac = require('alpha-complex') @@ -2592,7 +2604,7 @@ var bnd = require('simplicial-complex-boundary') function alphaShape(alpha, points) { return bnd(ac(alpha, points)) } -},{"alpha-complex":41,"simplicial-complex-boundary":44}],41:[function(require,module,exports){ +},{"alpha-complex":47,"simplicial-complex-boundary":58}],47:[function(require,module,exports){ 'use strict' module.exports = alphaComplex @@ -2609,7 +2621,7 @@ function alphaComplex(alpha, points) { return circumradius(simplex) * alpha < 1 }) } -},{"circumradius":42,"delaunay-triangulate":114}],42:[function(require,module,exports){ +},{"circumradius":48,"delaunay-triangulate":88}],48:[function(require,module,exports){ module.exports = circumradius var circumcenter = require('circumcenter') @@ -2625,7 +2637,7 @@ function circumradius(points) { } return Math.sqrt(avgDist / points.length) } -},{"circumcenter":43}],43:[function(require,module,exports){ +},{"circumcenter":49}],49:[function(require,module,exports){ "use strict" var dup = require("dup") @@ -2694,504 +2706,885 @@ function circumcenter(points) { circumcenter.barycenetric = barycentricCircumcenter module.exports = circumcenter -},{"dup":115,"robust-linear-solve":256}],44:[function(require,module,exports){ -'use strict' - -module.exports = boundary - -var bnd = require('boundary-cells') -var reduce = require('reduce-simplicial-complex') - -function boundary(cells) { - return reduce(bnd(cells)) -} - -},{"boundary-cells":45,"reduce-simplicial-complex":48}],45:[function(require,module,exports){ +},{"dup":50,"robust-linear-solve":51}],50:[function(require,module,exports){ "use strict" -module.exports = boundary - -function boundary(cells) { - var n = cells.length - var sz = 0 - for(var i=0; i 0) { + return dupe_number(count|0, value) + } + break + case "object": + if(typeof (count.length) === "number") { + return dupe_array(count, value, 0) + } + break + } + return [] } -},{"cell-orientation":46,"compare-cell":101}],48:[function(require,module,exports){ -'use strict' +module.exports = dupe +},{}],51:[function(require,module,exports){ +"use strict" -var compareCell = require('compare-cell') -var compareOrientedCell = require('compare-oriented-cell') -var orientation = require('cell-orientation') +var determinant = require("robust-determinant") -module.exports = reduceCellComplex +var NUM_EXPAND = 6 -function reduceCellComplex(cells) { - cells.sort(compareOrientedCell) - var n = cells.length - var ptr = 0 +function generateSolver(n) { + var funcName = "robustLinearSolve" + n + "d" + var code = ["function ", funcName, "(A,b){return ["] for(var i=0; i 0) { - var f = cells[ptr-1] - if(compareCell(c, f) === 0 && - orientation(f) !== o) { - ptr -= 1 - continue + code.push("det([") + for(var j=0; j 0) { + code.push(",") + } + code.push("[") + for(var k=0; k 0) { + code.push(",") + } + if(k === i) { + code.push("+b[", j, "]") + } else { + code.push("+A[", j, "][", k, "]") + } } + code.push("]") } - cells[ptr++] = c + code.push("]),") } - cells.length = ptr - return cells + code.push("det(A)]}return ", funcName) + var proc = new Function("det", code.join("")) + if(n < 6) { + return proc(determinant[n]) + } + return proc(determinant) } -},{"cell-orientation":46,"compare-cell":101,"compare-oriented-cell":47}],49:[function(require,module,exports){ -'use strict'; - -var arraytools = function () { +function robustLinearSolve0d() { + return [ 0 ] +} - var that = {}; +function robustLinearSolve1d(A, b) { + return [ [ b[0] ], [ A[0][0] ] ] +} - var RGB_REGEX = /^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/; - var RGB_GROUP_REGEX = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/; +var CACHE = [ + robustLinearSolve0d, + robustLinearSolve1d +] - function isPlainObject (v) { - return !Array.isArray(v) && v !== null && typeof v === 'object'; +function generateDispatch() { + while(CACHE.length < NUM_EXPAND) { + CACHE.push(generateSolver(CACHE.length)) } - - function linspace (start, end, num) { - var inc = (end - start) / Math.max(num - 1, 1); - var a = []; - for( var ii = 0; ii < num; ii++) - a.push(start + ii*inc); - return a; + var procArgs = [] + var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] + for(var i=0; i=0; --i) { + var a = Q + var b = e[i] + Q = a + b + var bv = Q - a + var q = b - bv + if(q) { + e[--bottom] = Q + Q = q } - - return carr; } - - - function copy1D (arr) { - var carr = []; - for (var i = 0; i < arr.length; ++i) { - carr[i] = arr[i]; + var top = 0 + for(var i=bottom; i1 or 0->255 rgb array - var rgb, - match; - - if (typeof str !== 'string') return str; - - rgb = []; - // hex notation - if (str[0] === '#') { - str = str.substr(1) // remove hash - if (str.length === 3) str += str // fff -> ffffff - match = parseInt(str, 16); - rgb[0] = ((match >> 16) & 255); - rgb[1] = ((match >> 8) & 255); - rgb[2] = (match & 255); +function scaleLinearExpansion(e, scale) { + var n = e.length + if(n === 1) { + var ts = twoProduct(e[0], scale) + if(ts[0]) { + return ts } - - // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation - else if (RGB_REGEX.test(str)) { - match = str.match(RGB_GROUP_REGEX); - rgb[0] = parseInt(match[1]); - rgb[1] = parseInt(match[2]); - rgb[2] = parseInt(match[3]); + return [ ts[1] ] + } + var g = new Array(2 * n) + var q = [0.1, 0.1] + var t = [0.1, 0.1] + var count = 0 + twoProduct(e[0], scale, q) + if(q[0]) { + g[count++] = q[0] + } + for(var i=1; i1 or 0->255 rgb array - var rgb, - match; - - if (typeof str !== 'string') return str; +//Easy case: Add two scalars +function scalarScalar(a, b) { + var x = a + b + var bv = x - a + var av = x - bv + var br = b - bv + var ar = a - av + var y = ar + br + if(y) { + return [y, x] + } + return [x] +} - rgb = []; - // hex notation - if (str[0] === '#') { - str = str.substr(1) // remove hash - if (str.length === 3) str += str // fff -> ffffff - match = parseInt(str, 16); - rgb[0] = ((match >> 16) & 255); - rgb[1] = ((match >> 8) & 255); - rgb[2] = (match & 255); +function linearExpansionSum(e, f) { + var ne = e.length|0 + var nf = f.length|0 + if(ne === 1 && nf === 1) { + return scalarScalar(e[0], f[0]) + } + var n = ne + nf + var g = new Array(n) + var count = 0 + var eptr = 0 + var fptr = 0 + var abs = Math.abs + var ei = e[eptr] + var ea = abs(ei) + var fi = f[fptr] + var fa = abs(fi) + var a, b + if(ea < fa) { + b = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) } - - // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation - else if (RGB_REGEX.test(str)) { - match = str.match(RGB_GROUP_REGEX); - rgb[0] = parseInt(match[1]); - rgb[1] = parseInt(match[2]); - rgb[2] = parseInt(match[3]); - if (match[4]) rgb[3] = parseFloat(match[4]); - else rgb[3] = 1.0; + } else { + b = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) } - - - - if (!twoFiftySix) { - for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 + } + if((eptr < ne && ea < fa) || (fptr >= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) } - - - return rgb; } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } + } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + } + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g +} +},{}],56:[function(require,module,exports){ +"use strict" +module.exports = twoProduct +var SPLITTER = +(Math.pow(2, 27) + 1.0) +function twoProduct(a, b, result) { + var x = a * b + var c = SPLITTER * a + var abig = c - a + var ahi = c - abig + var alo = a - ahi - that.isPlainObject = isPlainObject; - that.linspace = linspace; - that.zip3 = zip3; - that.sum = sum; - that.zip = zip; - that.isEqual = isEqual; - that.copy2D = copy2D; - that.copy1D = copy1D; - that.str2RgbArray = str2RgbArray; - that.str2RgbaArray = str2RgbaArray; - - return that - -} + var d = SPLITTER * b + var bbig = d - b + var bhi = d - bbig + var blo = b - bhi + var err1 = x - (ahi * bhi) + var err2 = err1 - (alo * bhi) + var err3 = err2 - (ahi * blo) -module.exports = arraytools(); + var y = alo * blo - err3 -},{}],50:[function(require,module,exports){ -/** - * Bit twiddling hacks for JavaScript. - * - * Author: Mikola Lysenko - * - * Ported from Stanford bit twiddling hack library: - * http://graphics.stanford.edu/~seander/bithacks.html - */ + if(result) { + result[0] = y + result[1] = x + return result + } -"use strict"; "use restrict"; + return [ y, x ] +} +},{}],57:[function(require,module,exports){ +"use strict" -//Number of bits in an integer -var INT_BITS = 32; +var twoProduct = require("two-product") +var robustSum = require("robust-sum") +var robustScale = require("robust-scale") +var compress = require("robust-compress") -//Constants -exports.INT_BITS = INT_BITS; -exports.INT_MAX = 0x7fffffff; -exports.INT_MIN = -1<<(INT_BITS-1); +var NUM_EXPANDED = 6 -//Returns -1, 0, +1 depending on sign of x -exports.sign = function(v) { - return (v > 0) - (v < 0); +function cofactor(m, c) { + var result = new Array(m.length-1) + for(var i=1; i> (INT_BITS-1); - return (v ^ mask) - mask; +function matrix(n) { + var result = new Array(n) + for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") + } } -//Checks if a number is a power of two -exports.isPow2 = function(v) { - return !(v & (v-1)) && (!!v); +function determinant(m) { + if(m.length === 2) { + return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") + } else { + var expr = [] + for(var i=0; i 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); +function compileDeterminant(n) { + var proc = new Function("sum", "scale", "prod", "compress", [ + "function robustDeterminant",n, "(m){return compress(", + determinant(matrix(n)), + ")};return robustDeterminant", n].join("")) + return proc(robustSum, robustScale, twoProduct, compress) } -//Computes log base 10 of v -exports.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} +var CACHE = [ + function robustDeterminant0() { return [0] }, + function robustDeterminant1(m) { return [m[0][0]] } +] -//Counts number of bits -exports.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +function generateDispatch() { + while(CACHE.length < NUM_EXPANDED) { + CACHE.push(compileDeterminant(CACHE.length)) + } + var procArgs = [] + var code = ["function robustDeterminant(m){switch(m.length){"] + for(var i=0; i>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; -} +module.exports = boundary -//Rounds down to previous power of 2 -exports.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); -} +var bnd = require('boundary-cells') +var reduce = require('reduce-simplicial-complex') -//Computes parity of word -exports.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; +function boundary(cells) { + return reduce(bnd(cells)) } -var REVERSE_TABLE = new Array(256); +},{"boundary-cells":59,"reduce-simplicial-complex":63}],59:[function(require,module,exports){ +'use strict' -(function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; +module.exports = boundary + +function boundary (cells) { + var i, j, k + var n = cells.length + var sz = 0 + for (i = 0; i < n; ++i) { + sz += cells[i].length + } + var result = new Array(sz) + var ptr = 0 + for (i = 0; i < n; ++i) { + var c = cells[i] + var d = c.length + for (j = 0; j < d; ++j) { + var b = result[ptr++] = new Array(d - 1) + var p = 0 + for (k = 0; k < d; ++k) { + if (k === j) { + continue + } + b[p++] = c[k] + } + if (j & 1) { + var tmp = b[1] + b[1] = b[0] + b[0] = tmp + } } - tab[i] = (r << s) & 0xff; } -})(REVERSE_TABLE); - -//Reverse bits in a 32 bit word -exports.reverse = function(v) { - return (REVERSE_TABLE[ v & 0xff] << 24) | - (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; + return result } -//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -exports.interleave2 = function(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; +},{}],60:[function(require,module,exports){ +'use strict' - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; +module.exports = orientation - return x | (y << 1); +function orientation(s) { + var p = 1 + for(var i=1; i>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; +},{}],61:[function(require,module,exports){ +module.exports = compareCells + +var min = Math.min + +function compareInt(a, b) { + return a - b +} + +function compareCells(a, b) { + var n = a.length + , t = a.length - b.length + if(t) { + return t + } + switch(n) { + case 0: + return 0 + case 1: + return a[0] - b[0] + case 2: + return (a[0]+a[1]-b[0]-b[1]) || + min(a[0],a[1]) - min(b[0],b[1]) + case 3: + var l1 = a[0]+a[1] + , m1 = b[0]+b[1] + t = l1+a[2] - (m1+b[2]) + if(t) { + return t + } + var l0 = min(a[0], a[1]) + , m0 = min(b[0], b[1]) + return min(l0, a[2]) - min(m0, b[2]) || + min(l0+a[2], l1) - min(m0+b[2], m1) + case 4: + var aw=a[0], ax=a[1], ay=a[2], az=a[3] + , bw=b[0], bx=b[1], by=b[2], bz=b[3] + return (aw+ax+ay+az)-(bw+bx+by+bz) || + min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) || + min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) - + min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) || + min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) - + min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz) + default: + var as = a.slice().sort(compareInt) + var bs = b.slice().sort(compareInt) + for(var i=0; i>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; +},{"cell-orientation":60,"compare-cell":61}],63:[function(require,module,exports){ +'use strict' + +var compareCell = require('compare-cell') +var compareOrientedCell = require('compare-oriented-cell') +var orientation = require('cell-orientation') + +module.exports = reduceCellComplex + +function reduceCellComplex(cells) { + cells.sort(compareOrientedCell) + var n = cells.length + var ptr = 0 + for(var i=0; i 0) { + var f = cells[ptr-1] + if(compareCell(c, f) === 0 && + orientation(f) !== o) { + ptr -= 1 + continue + } + } + cells[ptr++] = c + } + cells.length = ptr + return cells } -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -exports.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +},{"cell-orientation":60,"compare-cell":61,"compare-oriented-cell":62}],64:[function(require,module,exports){ +'use strict'; + +var arraytools = function () { + + var that = {}; + + var RGB_REGEX = /^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/; + var RGB_GROUP_REGEX = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/; + + function isPlainObject (v) { + return !Array.isArray(v) && v !== null && typeof v === 'object'; + } + + function linspace (start, end, num) { + var inc = (end - start) / Math.max(num - 1, 1); + var a = []; + for( var ii = 0; ii < num; ii++) + a.push(start + ii*inc); + return a; + } + + function zip () { + var arrays = [].slice.call(arguments); + var lengths = arrays.map(function (a) {return a.length;}); + var len = Math.min.apply(null, lengths); + var zipped = []; + for (var i = 0; i < len; i++) { + zipped[i] = []; + for (var j = 0; j < arrays.length; ++j) { + zipped[i][j] = arrays[j][i]; + } + } + return zipped; + } + + function zip3 (a, b, c) { + var len = Math.min.apply(null, [a.length, b.length, c.length]); + var result = []; + for (var n = 0; n < len; n++) { + result.push([a[n], b[n], c[n]]); + } + return result; + } + + function sum (A) { + var acc = 0; + accumulate(A, acc); + function accumulate(x) { + for (var i = 0; i < x.length; i++) { + if (Array.isArray(x[i])) + accumulate(x[i], acc); + else + acc += x[i]; + } + } + return acc; + } + + function copy2D (arr) { + var carr = []; + for (var i = 0; i < arr.length; ++i) { + carr[i] = []; + for (var j = 0; j < arr[i].length; ++j) { + carr[i][j] = arr[i][j]; + } + } + + return carr; + } + + + function copy1D (arr) { + var carr = []; + for (var i = 0; i < arr.length; ++i) { + carr[i] = arr[i]; + } + + return carr; + } + + + function isEqual(arr1, arr2) { + if(arr1.length !== arr2.length) + return false; + for(var i = arr1.length; i--;) { + if(arr1[i] !== arr2[i]) + return false; + } + + return true; + } + + + function str2RgbArray(str, twoFiftySix) { + // convert hex or rbg strings to 0->1 or 0->255 rgb array + var rgb, + match; + + if (typeof str !== 'string') return str; + + rgb = []; + // hex notation + if (str[0] === '#') { + str = str.substr(1) // remove hash + if (str.length === 3) str += str // fff -> ffffff + match = parseInt(str, 16); + rgb[0] = ((match >> 16) & 255); + rgb[1] = ((match >> 8) & 255); + rgb[2] = (match & 255); + } + + // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation + else if (RGB_REGEX.test(str)) { + match = str.match(RGB_GROUP_REGEX); + rgb[0] = parseInt(match[1]); + rgb[1] = parseInt(match[2]); + rgb[2] = parseInt(match[3]); + } + + if (!twoFiftySix) { + for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 + } + + + return rgb; + } + + + function str2RgbaArray(str, twoFiftySix) { + // convert hex or rbg strings to 0->1 or 0->255 rgb array + var rgb, + match; + + if (typeof str !== 'string') return str; + + rgb = []; + // hex notation + if (str[0] === '#') { + str = str.substr(1) // remove hash + if (str.length === 3) str += str // fff -> ffffff + match = parseInt(str, 16); + rgb[0] = ((match >> 16) & 255); + rgb[1] = ((match >> 8) & 255); + rgb[2] = (match & 255); + } + + // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation + else if (RGB_REGEX.test(str)) { + match = str.match(RGB_GROUP_REGEX); + rgb[0] = parseInt(match[1]); + rgb[1] = parseInt(match[2]); + rgb[2] = parseInt(match[3]); + if (match[4]) rgb[3] = parseFloat(match[4]); + else rgb[3] = 1.0; + } + + + + if (!twoFiftySix) { + for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 + } + + + return rgb; + } + + + + + + that.isPlainObject = isPlainObject; + that.linspace = linspace; + that.zip3 = zip3; + that.sum = sum; + that.zip = zip; + that.isEqual = isEqual; + that.copy2D = copy2D; + that.copy1D = copy1D; + that.str2RgbArray = str2RgbArray; + that.str2RgbaArray = str2RgbaArray; + + return that + } -},{}],51:[function(require,module,exports){ +module.exports = arraytools(); + +},{}],65:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -3210,9 +3603,6 @@ var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 -Buffer.poolSize = 8192 // not used by this implementation - -var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -3242,6 +3632,11 @@ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + function typedArraySupport () { try { var arr = new Uint8Array(1) @@ -3260,6 +3655,25 @@ function kMaxLength () { : 0x3fffffff } +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of @@ -3269,183 +3683,208 @@ function kMaxLength () { * * The `Uint8Array` prototype remains unmodified. */ -function Buffer (arg) { - if (!(this instanceof Buffer)) { - // Avoid going through an ArgumentsAdaptorTrampoline in the common case. - if (arguments.length > 1) return new Buffer(arg, arguments[1]) - return new Buffer(arg) - } - if (!Buffer.TYPED_ARRAY_SUPPORT) { - this.length = 0 - this.parent = undefined +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { - return fromNumber(this, arg) - } - - // Slightly less common case. - if (typeof arg === 'string') { - return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) } - - // Unusual. - return fromObject(this, arg) + return from(this, arg, encodingOrOffset, length) } +Buffer.poolSize = 8192 // not used by this implementation + // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } -function fromNumber (that, length) { - that = allocate(that, length < 0 ? 0 : checked(length) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < length; i++) { - that[i] = 0 - } +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') } - return that -} -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } - // Assumption: byteLength() return value is always < kMaxLength. - var length = byteLength(string, encoding) | 0 - that = allocate(that, length) + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } - that.write(string, encoding) - return that + return fromObject(that, value) } -function fromObject (that, object) { - if (Buffer.isBuffer(object)) return fromBuffer(that, object) - - if (isArray(object)) return fromArray(that, object) +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} - if (object == null) { - throw new TypeError('must start with number, buffer, array or string') +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) } +} - if (typeof ArrayBuffer !== 'undefined') { - if (object.buffer instanceof ArrayBuffer) { - return fromTypedArray(that, object) - } - if (object instanceof ArrayBuffer) { - return fromArrayBuffer(that, object) - } +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') } +} - if (object.length) return fromArrayLike(that, object) - - return fromJsonObject(that, object) +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) } -function fromBuffer (that, buffer) { - var length = checked(buffer.length) | 0 - that = allocate(that, length) - buffer.copy(that, 0, 0, length) - return that +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) } -function fromArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; i++) { + that[i] = 0 + } } return that } -// Duplicate of fromArray() to keep fromArray() monomorphic. -function fromTypedArray (that, array) { - var length = checked(array.length) | 0 - that = allocate(that, length) - // Truncating the elements is probably not what people expect from typed - // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior - // of the old Buffer constructor. - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) } -function fromArrayBuffer (that, array) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(array) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromTypedArray(that, new Uint8Array(array)) + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + that.write(string, encoding) return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 - that = allocate(that, length) + that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } -// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. -// Returns a zero-length buffer for inputs that don't conform to the spec. -function fromJsonObject (that, object) { - var array - var length = 0 +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer - if (object.type === 'Buffer' && isArray(object.data)) { - array = object.data - length = checked(array.length) | 0 + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') } - that = allocate(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') } - return that -} -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) + if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) } -} else { - // pre-set for values that may exist in the future - Buffer.prototype.length = undefined - Buffer.prototype.parent = undefined -} -function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) + that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class - that.length = length + that = fromArrayLike(that, array) } + return that +} - var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 - if (fromPool) that.parent = rootParent +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) - return that + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { @@ -3458,12 +3897,11 @@ function checked (length) { return length | 0 } -function SlowBuffer (subject, encoding) { - if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) - - var buf = new Buffer(subject, encoding) - delete buf.parent - return buf +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { @@ -3480,17 +3918,12 @@ Buffer.compare = function compare (a, b) { var x = a.length var y = b.length - var i = 0 - var len = Math.min(x, y) - while (i < len) { - if (a[i] !== b[i]) break - - ++i - } - - if (i !== len) { - x = a[i] - y = b[i] + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } } if (x < y) return -1 @@ -3518,10 +3951,12 @@ Buffer.isEncoding = function isEncoding (encoding) { } Buffer.concat = function concat (list, length) { - if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } if (list.length === 0) { - return new Buffer(0) + return Buffer.alloc(0) } var i @@ -3532,18 +3967,30 @@ Buffer.concat = function concat (list, length) { } } - var buf = new Buffer(length) + var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; i++) { - var item = list[i] - item.copy(buf, pos) - pos += item.length + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length } - return buf + return buffer } function byteLength (string, encoding) { - if (typeof string !== 'string') string = '' + string + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } var len = string.length if (len === 0) return 0 @@ -3560,6 +4007,7 @@ function byteLength (string, encoding) { return len case 'utf8': case 'utf-8': + case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': @@ -3582,13 +4030,39 @@ Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false - start = start | 0 - end = end === undefined || end === Infinity ? this.length : end | 0 + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } if (!encoding) encoding = 'utf8' - if (start < 0) start = 0 - if (end > this.length) end = this.length - if (end <= start) return '' while (true) { switch (encoding) { @@ -3626,6 +4100,35 @@ function slowToString (encoding, start, end) { // Buffer instances. Buffer.prototype._isBuffer = true +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' @@ -3649,16 +4152,115 @@ Buffer.prototype.inspect = function inspect () { return '' } -Buffer.prototype.compare = function compare (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return 0 - return Buffer.compare(this, b) -} +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } -Buffer.prototype.indexOf = function indexOf (val, byteOffset) { - if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff - else if (byteOffset < -0x80000000) byteOffset = -0x80000000 - byteOffset >>= 0 + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +function arrayIndexOf (arr, val, byteOffset, encoding) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var foundIndex = -1 + for (var i = 0; byteOffset + i < arrLength; i++) { + if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + return -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 @@ -3667,35 +4269,30 @@ Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { - if (val.length === 0) return -1 // special case: looking for empty string always fails - return String.prototype.indexOf.call(this, val, byteOffset) + val = Buffer.from(val, encoding) } + if (Buffer.isBuffer(val)) { - return arrayIndexOf(this, val, byteOffset) + // special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(this, val, byteOffset, encoding) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } - return arrayIndexOf(this, [ val ], byteOffset) - } - - function arrayIndexOf (arr, val, byteOffset) { - var foundIndex = -1 - for (var i = 0; byteOffset + i < arr.length; i++) { - if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex - } else { - foundIndex = -1 - } - } - return -1 + return arrayIndexOf(this, [ val ], byteOffset, encoding) } throw new TypeError('val must be string, number or Buffer') } +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset @@ -3717,7 +4314,7 @@ function hexWrite (buf, string, offset, length) { } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) throw new Error('Invalid hex string') + if (isNaN(parsed)) return i buf[offset + i] = parsed } return i @@ -3766,17 +4363,16 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { - var swap = encoding - encoding = offset - offset = length | 0 - length = swap + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('attempt to write outside buffer bounds') + throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' @@ -4001,8 +4597,6 @@ Buffer.prototype.slice = function slice (start, end) { } } - if (newBuf.length) newBuf.parent = this.parent || this - return newBuf } @@ -4171,16 +4765,19 @@ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { } function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') - if (value > max || value < min) throw new RangeError('value is out of bounds') - if (offset + ext > buf.length) throw new RangeError('index out of range') + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var mul = 1 var i = 0 @@ -4196,7 +4793,10 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } var i = byteLength - 1 var mul = 1 @@ -4299,9 +4899,12 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no var i = 0 var mul = 1 - var sub = value < 0 ? 1 : 0 + var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -4319,9 +4922,12 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no var i = byteLength - 1 var mul = 1 - var sub = value < 0 ? 1 : 0 + var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -4396,8 +5002,8 @@ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) } function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('index out of range') - if (offset < 0) throw new RangeError('index out of range') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { @@ -4481,31 +5087,63 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { return len } -// fill(value, start=0, end=buffer.length) -Buffer.prototype.fill = function fill (value, start, end) { - if (!value) value = 0 - if (!start) start = 0 - if (!end) end = this.length +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } - if (end < start) throw new RangeError('end < start') + if (end <= start) { + return this + } - // Fill 0 bytes; we're done - if (end === start) return - if (this.length === 0) return + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 - if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') - if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + if (!val) val = 0 var i - if (typeof value === 'number') { + if (typeof val === 'number') { for (i = start; i < end; i++) { - this[i] = value + this[i] = val } } else { - var bytes = utf8ToBytes(value.toString()) + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length - for (i = start; i < end; i++) { - this[i] = bytes[i % len] + for (i = 0; i < end - start; i++) { + this[i + start] = bytes[i % len] } } @@ -4656,8 +5294,12 @@ function blitBuffer (src, dst, offset, length) { return i } +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":52,"ieee754":53,"isarray":54}],52:[function(require,module,exports){ +},{"base64-js":66,"ieee754":67,"isarray":68}],66:[function(require,module,exports){ 'use strict' exports.toByteArray = toByteArray @@ -4668,17 +5310,12 @@ var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array function init () { - var i var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - var len = code.length - - for (i = 0; i < len; i++) { + for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] - } - - for (i = 0; i < len; ++i) { revLookup[code.charCodeAt(i)] = i } + revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 } @@ -4710,8 +5347,8 @@ function toByteArray (b64) { for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp & 0xFF0000) >> 16 - arr[L++] = (tmp & 0xFF00) >> 8 + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } @@ -4773,7 +5410,7 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],53:[function(require,module,exports){ +},{}],67:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -4859,14 +5496,14 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],54:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],55:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -5166,16 +5803,44 @@ function isUndefined(arg) { return arg === void 0; } -},{}],56:[function(require,module,exports){ +},{}],70:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +(function () { + try { + cachedSetTimeout = setTimeout; + } catch (e) { + cachedSetTimeout = function () { + throw new Error('setTimeout is not defined'); + } + } + try { + cachedClearTimeout = clearTimeout; + } catch (e) { + cachedClearTimeout = function () { + throw new Error('clearTimeout is not defined'); + } + } +} ()) var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); @@ -5191,7 +5856,7 @@ function drainQueue() { if (draining) { return; } - var timeout = setTimeout(cleanUpNextTick); + var timeout = cachedSetTimeout(cleanUpNextTick); draining = true; var len = queue.length; @@ -5208,7 +5873,7 @@ function drainQueue() { } currentQueue = null; draining = false; - clearTimeout(timeout); + cachedClearTimeout(timeout); } process.nextTick = function (fun) { @@ -5220,7 +5885,7 @@ process.nextTick = function (fun) { } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { - setTimeout(drainQueue, 0); + cachedSetTimeout(drainQueue, 0); } }; @@ -5259,34921 +5924,36483 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],57:[function(require,module,exports){ -'use strict' - -var monotoneTriangulate = require('./lib/monotone') -var makeIndex = require('./lib/triangulation') -var delaunayFlip = require('./lib/delaunay') -var filterTriangulation = require('./lib/filter') - -module.exports = cdt2d - -function canonicalizeEdge(e) { - return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] -} - -function compareEdge(a, b) { - return a[0]-b[0] || a[1]-b[1] -} - -function canonicalizeEdges(edges) { - return edges.map(canonicalizeEdge).sort(compareEdge) -} +},{}],71:[function(require,module,exports){ +"use strict" -function getDefault(options, property, dflt) { - if(property in options) { - return options[property] - } - return dflt -} +var convexHull1d = require('./lib/ch1d') +var convexHull2d = require('./lib/ch2d') +var convexHullnd = require('./lib/chnd') -function cdt2d(points, edges, options) { +module.exports = convexHull - if(!Array.isArray(edges)) { - options = edges || {} - edges = [] - } else { - options = options || {} - edges = edges || [] +function convexHull(points) { + var n = points.length + if(n === 0) { + return [] + } else if(n === 1) { + return [[0]] } - - //Parse out options - var delaunay = !!getDefault(options, 'delaunay', true) - var interior = !!getDefault(options, 'interior', true) - var exterior = !!getDefault(options, 'exterior', true) - var infinity = !!getDefault(options, 'infinity', false) - - //Handle trivial case - if((!interior && !exterior) || points.length === 0) { + var d = points[0].length + if(d === 0) { return [] + } else if(d === 1) { + return convexHull1d(points) + } else if(d === 2) { + return convexHull2d(points) } + return convexHullnd(points, d) +} +},{"./lib/ch1d":72,"./lib/ch2d":73,"./lib/chnd":74}],72:[function(require,module,exports){ +"use strict" - //Construct initial triangulation - var cells = monotoneTriangulate(points, edges) - - //If delaunay refinement needed, then improve quality by edge flipping - if(delaunay || interior !== exterior || infinity) { - - //Index all of the cells to support fast neighborhood queries - var triangulation = makeIndex(points.length, canonicalizeEdges(edges)) - for(var i=0; i points[hi][0]) { + hi = i } - + } + if(lo < hi) { + return [[lo], [hi]] + } else if(lo > hi) { + return [[hi], [lo]] } else { - return cells + return [[lo]] } } - -},{"./lib/delaunay":58,"./lib/filter":59,"./lib/monotone":60,"./lib/triangulation":61}],58:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ 'use strict' -var inCircle = require('robust-in-sphere')[4] -var bsearch = require('binary-search-bounds') - -module.exports = delaunayRefine +module.exports = convexHull2D -function testFlip(points, triangulation, stack, a, b, x) { - var y = triangulation.opposite(a, b) +var monotoneHull = require('monotone-convex-hull-2d') - //Test boundary edge - if(y < 0) { - return +function convexHull2D(points) { + var hull = monotoneHull(points) + var h = hull.length + if(h <= 2) { + return [] } - - //Swap edge if order flipped - if(b < a) { - var tmp = a + var edges = new Array(h) + var a = hull[h-1] + for(var i=0; i= front[k]) { + x += 1 + } } + c[j] = x } + } + } + return cells +} - //If this is a boundary edge, don't flip it - if(y < 0) { - continue - } - - //If edge is in circle, flip it - if(inCircle(points[a], points[b], points[x], points[y]) < 0) { - stack.push(a, b) - } +function convexHullnD(points, d) { + try { + return ich(points, true) + } catch(e) { + //If point set is degenerate, try to find a basis and rerun it + var ah = aff(points) + if(ah.length <= d) { + //No basis, no try + return [] } + var npoints = permute(points, ah) + var nhull = ich(npoints, true) + return invPermute(nhull, ah) } +} +},{"affine-hull":75,"incremental-convex-hull":76}],75:[function(require,module,exports){ +'use strict' - while(stack.length > 0) { - var b = stack.pop() - var a = stack.pop() +module.exports = affineHull - //Find opposite pairs - var x = -1, y = -1 - var star = stars[a] - for(var i=1; i= 0) { +function affineHull(points) { + var n = points.length + if(n === 0) { + return [] + } + if(n === 1) { + return [0] + } + var d = points[0].length + var frame = [ points[0] ] + var index = [ 0 ] + for(var i=1; i 0) { + code.push(",") } + code.push("tuple[", i, "]") } - cells.sort(compareCell) - - //Initialize flag array - var flags = new Array(nc) - for(var i=0; i 0 || next.length > 0) { - while(active.length > 0) { - var t = active.pop() - if(flags[t] === -side) { + //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate + var toVisit = [ cell ] + cell.lastVisited = -n + while(toVisit.length > 0) { + cell = toVisit.pop() + var cellVerts = cell.vertices + var cellAdj = cell.adjacent + for(var i=0; i<=d; ++i) { + var neighbor = cellAdj[i] + if(!neighbor.boundary || neighbor.lastVisited <= -n) { continue } - flags[t] = side - var c = cells[t] - for(var j=0; j<3; ++j) { - var f = neighbor[3*t+j] - if(f >= 0 && flags[f] === 0) { - if(constraint[3*t+j]) { - next.push(f) - } else { - active.push(f) - flags[f] = side - } + var nv = neighbor.vertices + for(var j=0; j<=d; ++j) { + var vv = nv[j] + if(vv < 0) { + tuple[j] = point + } else { + tuple[j] = verts[vv] } } + var o = this.orient() + if(o > 0) { + return neighbor + } + neighbor.lastVisited = -n + if(o === 0) { + toVisit.push(neighbor) + } } - - //Swap arrays and loop - var tmp = next - next = active - active = tmp - next.length = 0 - side = -side - } - - var result = filterCells(cells, flags, target) - if(infinity) { - return result.concat(index.boundary) } - return result + return null } -},{"binary-search-bounds":62}],60:[function(require,module,exports){ -'use strict' +proto.walk = function(point, random) { + //Alias local properties + var n = this.vertices.length - 1 + var d = this.dimension + var verts = this.vertices + var tuple = this.tuple -var bsearch = require('binary-search-bounds') -var orient = require('robust-orientation')[3] + //Compute initial jump cell + var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1) + var cell = this.interior[ initIndex ] -var EVENT_POINT = 0 -var EVENT_END = 1 -var EVENT_START = 2 + //Start walking +outerLoop: + while(!cell.boundary) { + var cellVerts = cell.vertices + var cellAdj = cell.adjacent -module.exports = monotoneTriangulate + for(var i=0; i<=d; ++i) { + tuple[i] = verts[cellVerts[i]] + } + cell.lastVisited = n -//A partial convex hull fragment, made of two unimonotone polygons -function PartialHull(a, b, idx, lowerIds, upperIds) { - this.a = a - this.b = b - this.idx = idx - this.lowerIds = lowerIds - this.upperIds = upperIds -} + //Find farthest adjacent cell + for(var i=0; i<=d; ++i) { + var neighbor = cellAdj[i] + if(neighbor.lastVisited >= n) { + continue + } + var prev = tuple[i] + tuple[i] = point + var o = this.orient() + tuple[i] = prev + if(o < 0) { + cell = neighbor + continue outerLoop + } else { + if(!neighbor.boundary) { + neighbor.lastVisited = n + } else { + neighbor.lastVisited = -n + } + } + } + return + } -//An event in the sweep line procedure -function Event(a, b, type, idx) { - this.a = a - this.b = b - this.type = type - this.idx = idx + return cell } -//This is used to compare events for the sweep line procedure -// Points are: -// 1. sorted lexicographically -// 2. sorted by type (point < end < start) -// 3. segments sorted by winding order -// 4. sorted by index -function compareEvent(a, b) { - var d = - (a.a[0] - b.a[0]) || - (a.a[1] - b.a[1]) || - (a.type - b.type) - if(d) { return d } - if(a.type !== EVENT_POINT) { - d = orient(a.a, a.b, b.b) - if(d) { return d } - } - return a.idx - b.idx -} +proto.addPeaks = function(point, cell) { + var n = this.vertices.length - 1 + var d = this.dimension + var verts = this.vertices + var tuple = this.tuple + var interior = this.interior + var simplices = this.simplices -function testPoint(hull, p) { - return orient(hull.a, hull.b, p) -} + //Walking finished at boundary, time to add peaks + var tovisit = [ cell ] -function addPoint(cells, hulls, points, p, idx) { - var lo = bsearch.lt(hulls, p, testPoint) - var hi = bsearch.gt(hulls, p, testPoint) - for(var i=lo; i 1 && orient( - points[lowerIds[m-2]], - points[lowerIds[m-1]], - p) > 0) { - cells.push( - [lowerIds[m-1], - lowerIds[m-2], - idx]) - m -= 1 - } - lowerIds.length = m - lowerIds.push(idx) + //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done + var glueFacets = [] - //Insert p into upper hull - var upperIds = hull.upperIds - var m = upperIds.length - while(m > 1 && orient( - points[upperIds[m-2]], - points[upperIds[m-1]], - p) < 0) { - cells.push( - [upperIds[m-2], - upperIds[m-1], - idx]) - m -= 1 + //Do a traversal of the boundary walking outward from starting peak + while(tovisit.length > 0) { + //Pop off peak and walk over adjacent cells + var cell = tovisit.pop() + var cellVerts = cell.vertices + var cellAdj = cell.adjacent + var indexOfN = cellVerts.indexOf(n) + if(indexOfN < 0) { + continue } - upperIds.length = m - upperIds.push(idx) - } -} -function findSplit(hull, edge) { - var d - if(hull.a[0] < edge.a[0]) { - d = orient(hull.a, hull.b, edge.a) - } else { - d = orient(edge.b, edge.a, hull.a) - } - if(d) { return d } - if(edge.b[0] < hull.b[0]) { - d = orient(hull.a, hull.b, edge.b) - } else { - d = orient(edge.b, edge.a, hull.b) - } - return d || hull.idx - edge.idx -} + for(var i=0; i<=d; ++i) { + if(i === indexOfN) { + continue + } -function splitHulls(hulls, points, event) { - var splitIdx = bsearch.le(hulls, event, findSplit) - var hull = hulls[splitIdx] - var upperIds = hull.upperIds - var x = upperIds[upperIds.length-1] - hull.upperIds = [x] - hulls.splice(splitIdx+1, 0, - new PartialHull(event.a, event.b, event.idx, [x], upperIds)) -} + //For each boundary neighbor of the cell + var neighbor = cellAdj[i] + if(!neighbor.boundary || neighbor.lastVisited >= n) { + continue + } + var nv = neighbor.vertices -function mergeHulls(hulls, points, event) { - //Swap pointers for merge search - var tmp = event.a - event.a = event.b - event.b = tmp - var mergeIdx = bsearch.eq(hulls, event, findSplit) - var upper = hulls[mergeIdx] - var lower = hulls[mergeIdx-1] - lower.upperIds = upper.upperIds - hulls.splice(mergeIdx, 1) -} + //Test if neighbor is a peak + if(neighbor.lastVisited !== -n) { + //Compute orientation of p relative to each boundary peak + var indexOfNeg1 = 0 + for(var j=0; j<=d; ++j) { + if(nv[j] < 0) { + indexOfNeg1 = j + tuple[j] = point + } else { + tuple[j] = verts[nv[j]] + } + } + var o = this.orient() + //Test if neighbor cell is also a peak + if(o > 0) { + nv[indexOfNeg1] = n + neighbor.boundary = false + interior.push(neighbor) + tovisit.push(neighbor) + neighbor.lastVisited = n + continue + } else { + neighbor.lastVisited = -n + } + } -function monotoneTriangulate(points, edges) { + var na = neighbor.adjacent - var numPoints = points.length - var numEdges = edges.length + //Otherwise, replace neighbor with new face + var vverts = cellVerts.slice() + var vadj = cellAdj.slice() + var ncell = new Simplex(vverts, vadj, true) + simplices.push(ncell) - var events = [] + //Connect to neighbor + var opposite = na.indexOf(cell) + if(opposite < 0) { + continue + } + na[opposite] = ncell + vadj[indexOfN] = neighbor - //Create point events - for(var i=0; i b[0]) { - events.push( - new Event(b, a, EVENT_START, i), - new Event(a, b, EVENT_END, i)) + //Flip facet + ncell.flip() + + //Add to glue list + for(var j=0; j<=d; ++j) { + var uu = vverts[j] + if(uu < 0 || uu === n) { + continue + } + var nface = new Array(d-1) + var nptr = 0 + for(var k=0; k<=d; ++k) { + var vv = vverts[k] + if(vv < 0 || k === j) { + continue + } + nface[nptr++] = vv + } + glueFacets.push(new GlueFacet(nface, ncell, j)) + } } } - //Sort events - events.sort(compareEvent) - - //Initialize hull - var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52) - var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ] + //Glue boundary facets together + glueFacets.sort(compareGlue) - //Process events in order - var cells = [] - for(var i=0, numEvents=events.length; i= 0 + var o = this.orient(tuple) + if(o < 0) { + return + } else if(o === 0) { + cell = this.handleBoundaryDegeneracy(cell, point) + if(!cell) { + return + } } -})() -proto.removeTriangle = function(i, j, k) { - var stars = this.stars - removePair(stars[i], j, k) - removePair(stars[j], k, i) - removePair(stars[k], i, j) + //Add peaks + this.addPeaks(point, cell) } -proto.addTriangle = function(i, j, k) { - var stars = this.stars - stars[i].push(j, k) - stars[j].push(k, i) - stars[k].push(i, j) -} - -proto.opposite = function(j, i) { - var list = this.stars[i] - for(var k=1, n=list.length; k= 0) { + bcell[ptr++] = cv[j] + } else { + parity = j&1 + } + } + if(parity === (d&1)) { + var t = bcell[0] + bcell[0] = bcell[1] + bcell[1] = t + } + boundary.push(bcell) } } - return -1 + return boundary } -proto.flip = function(i, j) { - var a = this.opposite(i, j) - var b = this.opposite(j, i) - this.removeTriangle(i, j, a) - this.removeTriangle(j, i, b) - this.addTriangle(i, b, a) - this.addTriangle(j, a, b) -} +function incrementalConvexHull(points, randomSearch) { + var n = points.length + if(n === 0) { + throw new Error("Must have at least d+1 points") + } + var d = points[0].length + if(n <= d) { + throw new Error("Must input at least d+1 points") + } -proto.edges = function() { - var stars = this.stars - var result = [] - for(var i=0, n=stars.length; i>>1,x=a[m]"] - if(earlyOut) { - if(predicate.indexOf("c") < 0) { - code.push(";if(x===y){return m}else if(x<=y){") - } else { - code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") - } - } else { - code.push(";if(", predicate, "){i=m;") - } - if(reversed) { - code.push("l=m+1}else{h=m-1}") - } else { - code.push("h=m-1}else{l=m+1}") - } - code.push("}") - if(earlyOut) { - code.push("return -1};") - } else { - code.push("return i};") + //Insert remaining points + var useRandom = !!randomSearch + for(var i=d+1; i 0) - (v < 0); } -module.exports = { - ge: compileBoundsSearch(">=", false, "GE"), - gt: compileBoundsSearch(">", false, "GT"), - lt: compileBoundsSearch("<", true, "LT"), - le: compileBoundsSearch("<=", true, "LE"), - eq: compileBoundsSearch("-", true, "EQ", true) +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; } -},{}],63:[function(require,module,exports){ -"use strict" +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} -var twoProduct = require("two-product") -var robustSum = require("robust-sum") -var robustDiff = require("robust-subtract") -var robustScale = require("robust-scale") +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} -var NUM_EXPAND = 6 +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} -function cofactor(m, c) { - var result = new Array(m.length-1) - for(var i=1; i 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); } -function matrix(n) { - var result = new Array(n) - for(var i=0; i= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } -function generateSum(expr) { - if(expr.length === 1) { - return expr[0] - } else if(expr.length === 2) { - return ["sum(", expr[0], ",", expr[1], ")"].join("") - } else { - var m = expr.length>>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; } -function makeProduct(a, b) { - if(a.charAt(0) === "m") { - if(b.charAt(0) === "w") { - var toks = a.split("[") - return ["w", b.substr(1), "m", toks[0].substr(1)].join("") - } else { - return ["prod(", a, ",", b, ")"].join("") - } - } else { - return makeProduct(b, a) - } +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; } +exports.countTrailingZeros = countTrailingZeros; -function sign(s) { - if(s & 1 !== 0) { - return "-" - } - return "" +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; } -function determinant(m) { - if(m.length === 2) { - return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] - } else { - var expr = [] - for(var i=0; i>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); } -function makeSquare(d, n) { - var terms = [] - for(var i=0; i>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; } -function orientation(n) { - var pos = [] - var neg = [] - var m = matrix(n) - for(var i=0; i>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; } + tab[i] = (r << s) & 0xff; } - code.push("var p=", posExpr, ",n=", negExpr, ",d=diff(p,n);return d[d.length-1];}return ", funcName) - var proc = new Function("sum", "diff", "prod", "scale", code.join("")) - return proc(robustSum, robustDiff, twoProduct, robustScale) +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; } -function inSphere0() { return 0 } -function inSphere1() { return 0 } -function inSphere2() { return 0 } +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; -var CACHED = [ - inSphere0, - inSphere1, - inSphere2 -] + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; -function slowInSphere(args) { - var proc = CACHED[args.length] - if(!proc) { - proc = CACHED[args.length] = orientation(args.length) - } - return proc.apply(undefined, args) + return x | (y << 1); } -function generateInSphereTest() { - while(CACHED.length <= NUM_EXPAND) { - CACHED.push(orientation(CACHED.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=NUM_EXPAND; ++i) { - args.push("a" + i) - procArgs.push("o" + i) - } - var code = [ - "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=NUM_EXPAND; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") - } - code.push("}var s=new Array(arguments.length);for(var i=0;i>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; } -generateInSphereTest() -},{"robust-scale":260,"robust-subtract":261,"robust-sum":262,"two-product":276}],64:[function(require,module,exports){ -'use strict' -module.exports = cleanPSLG +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; -var UnionFind = require('union-find') -var boxIntersect = require('box-intersect') -var compareCell = require('compare-cell') -var segseg = require('robust-segment-intersect') -var rat = require('big-rat') -var ratCmp = require('big-rat/cmp') -var ratToFloat = require('big-rat/to-float') -var ratVec = require('rat-vec') -var nextafter = require('nextafter') + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} -var solveIntersection = require('./lib/rat-seg-intersect') +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} -//Bounds on a rational number when rounded to a float -function boundRat(r) { - var f = ratToFloat(r) - var cmp = ratCmp(rat(f), r) - if(cmp < 0) { - return [f, nextafter(f, Infinity)] - } else if(cmp > 0) { - return [nextafter(f, -Infinity), f] - } else { - return [f, f] - } +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } -//Convert a list of edges in a pslg to bounding boxes -function boundEdges(points, edges) { - var bounds = new Array(edges.length) - for(var i=0; i= floatPoints.length) { - return ratPoints[idx-floatPoints.length] - } - var p = floatPoints[idx] - return [ rat(p[0]), rat(p[1]) ] +//Returns a deep copy of cells +function cloneCells(cells) { + var ncells = new Array(cells.length) + for(var i=0, il=cells.length; i=0; --i) { - var junction = junctions[i] - var e = junction[0] +//Ranks a pair of cells up to permutation +function compareCells(a, b) { + var n = a.length + , t = a.length - b.length + , min = Math.min + if(t) { + return t + } + switch(n) { + case 0: + return 0; + case 1: + return a[0] - b[0]; + case 2: + var d = a[0]+a[1]-b[0]-b[1] + if(d) { + return d + } + return min(a[0],a[1]) - min(b[0],b[1]) + case 3: + var l1 = a[0]+a[1] + , m1 = b[0]+b[1] + d = l1+a[2] - (m1+b[2]) + if(d) { + return d + } + var l0 = min(a[0], a[1]) + , m0 = min(b[0], b[1]) + , d = min(l0, a[2]) - min(m0, b[2]) + if(d) { + return d + } + return min(l0+a[2], l1) - min(m0+b[2], m1) + + //TODO: Maybe optimize n=4 as well? + + default: + var as = a.slice(0) + as.sort() + var bs = b.slice(0) + bs.sort() + for(var i=0; i 0 && junctions[i-1][0] === e) { - var junction = junctions[--i] - var next = junction[1] - if(useColor) { - edges.push([last, next, color]) - } else { - edges.push([last, next]) +//Removes all duplicate cells in the complex +function unique(cells) { + if(cells.length === 0) { + return [] + } + var ptr = 1 + , len = cells.length + for(var i=1; i> 1 + , s = compareCells(cells[mid], c) + if(s <= 0) { + if(s === 0) { + r = mid + } + lo = mid + 1 + } else if(s > 0) { + hi = mid - 1 } } - - //Return constructed rational points - return ratPoints + return r } +exports.findCell = findCell; -//Merge overlapping points -function dedupPoints(floatPoints, ratPoints, floatBounds) { - var numPoints = floatPoints.length + ratPoints.length - var uf = new UnionFind(numPoints) - - //Compute rational bounds - var bounds = floatBounds - for(var i=0; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { + break + } + } } } - floatPoints.length = ptr + return index +} +exports.incidence = incidence - //If no duplicates, return null to signal termination - if(noDupes) { - return null +//Computes the dual of the mesh. This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices +function dual(cells, vertex_count) { + if(!vertex_count) { + return incidence(unique(skeleton(cells, 0)), cells, 0) } - - //Do a second pass to fix up missing labels - for(var i=0; i b[2]) { - return 1 +//Enumerates all cells in the complex +function explode(cells) { + var result = [] + for(var i=0, il=cells.length; i>> k) & 1) { + b.push(c[k]) + } + } + result.push(b) + } } - return 0 + return normalize(result) } +exports.explode = explode -//Remove duplicate edge labels -function dedupEdges(edges, labels, useColor) { - if(edges.length === 0) { - return +//Enumerates all of the n-cells of a cell complex +function skeleton(cells, n) { + if(n < 0) { + return [] } - if(labels) { - for(var i=0; i 0 || tjunctions.length > 0) - } - - // More iterations necessary - return true -} - -//Main loop, runs PSLG clean up until completion -function cleanPSLG(points, edges, colors) { - var modified = false - - //If using colors, augment edges with color data - var prevEdges - if(colors) { - prevEdges = edges - var augEdges = new Array(edges.length) - for(var i=0; i 0) { - a = a.shln(shift) - } else if(shift < 0) { - b = b.shln(-shift) } - return rationalize(a, b) + return components } -},{"./div":68,"./is-rat":70,"./lib/is-bn":74,"./lib/num-to-bn":75,"./lib/rationalize":76,"./lib/str-to-bn":77}],70:[function(require,module,exports){ -'use strict' - -var isBN = require('./lib/is-bn') - -module.exports = isRat - -function isRat(x) { - return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1]) +//Computes connected components for a cell complex +function connectedComponents(cells, vertex_count) { + if(vertex_count) { + return connectedComponents_dense(cells, vertex_count) + } + return connectedComponents_sparse(cells) } +exports.connectedComponents = connectedComponents -},{"./lib/is-bn":74}],71:[function(require,module,exports){ +},{"bit-twiddle":77,"union-find":78}],80:[function(require,module,exports){ 'use strict' -var bn = require('bn.js') - -module.exports = sign - -function sign(x) { - return x.cmp(new bn(0)) -} +module.exports = monotoneConvexHull2D -},{"bn.js":79}],72:[function(require,module,exports){ -'use strict' +var orient = require('robust-orientation')[3] -module.exports = bn2num +function monotoneConvexHull2D(points) { + var n = points.length -//TODO: Make this better -function bn2num(b) { - var l = b.length - var words = b.words - var out = 0 - if (l === 1) { - out = words[0] - } else if (l === 2) { - out = words[0] + (words[1] * 0x4000000) - } else { - var out = 0 - for (var i = 0; i < l; i++) { - var w = words[i] - out += w * Math.pow(0x4000000, i) + if(n < 3) { + var result = new Array(n) + for(var i=0; i 20) { - return 52 + return result } - return h + 32 -} - -},{"bit-twiddle":50,"double-bits":90}],74:[function(require,module,exports){ -'use strict' - -var BN = require('bn.js') - -module.exports = isBN - -//Test if x is a bignumber -//FIXME: obviously this is the wrong way to do it -function isBN(x) { - return x && typeof x === 'object' && Boolean(x.words) -} - -},{"bn.js":79}],75:[function(require,module,exports){ -'use strict' - -var BN = require('bn.js') -var db = require('double-bits') -module.exports = num2bn - -function num2bn(x) { - var e = db.exponent(x) - if(e < 52) { - return new BN(x) - } else { - return (new BN(x * Math.pow(2, 52-e))).shln(e-52) + //Sort point indices along x-axis + var sorted = new Array(n) + for(var i=0; i 1 && orient( + points[lower[m-2]], + points[lower[m-1]], + p) <= 0) { + m -= 1 + lower.pop() + } + lower.push(idx) -function rationalize(numer, denom) { - var snumer = sign(numer) - var sdenom = sign(denom) - if(snumer === 0) { - return [num2bn(0), num2bn(1)] - } - if(sdenom === 0) { - return [num2bn(0), num2bn(0)] - } - if(sdenom < 0) { - numer = numer.neg() - denom = denom.neg() - } - var d = numer.gcd(denom) - if(d.cmpn(1)) { - return [ numer.div(d), denom.div(d) ] + //Insert into upper list + m = upper.length + while(m > 1 && orient( + points[upper[m-2]], + points[upper[m-1]], + p) >= 0) { + m -= 1 + upper.pop() + } + upper.push(idx) } - return [ numer, denom ] -} - -},{"./bn-sign":71,"./num-to-bn":75}],77:[function(require,module,exports){ -'use strict' - -var BN = require('bn.js') - -module.exports = str2BN - -function str2BN(x) { - return new BN(x) -} - -},{"bn.js":79}],78:[function(require,module,exports){ -'use strict' - -var rationalize = require('./lib/rationalize') - -module.exports = mul - -function mul(a, b) { - return rationalize(a[0].mul(b[0]), a[1].mul(b[1])) -} - -},{"./lib/rationalize":76}],79:[function(require,module,exports){ -(function (module, exports) { - -'use strict'; - -// Utils - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -// Could use `inherits` module, but don't want to move from single file -// architecture yet. -function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; -} - -// BN -function BN(number, base, endian) { - // May be `new BN(bn)` ? - if (number !== null && - typeof number === 'object' && - Array.isArray(number.words)) { - return number; + //Merge lists together + var result = new Array(upper.length + lower.length - 2) + var ptr = 0 + for(var i=0, nl=lower.length; i0; --j) { + result[ptr++] = upper[j] } - if (number !== null) - this._init(number || 0, base || 10, endian || 'be'); + //Return result + return result } -if (typeof module === 'object') - module.exports = BN; -else - exports.BN = BN; - -BN.BN = BN; -BN.wordSize = 26; - -BN.prototype._init = function init(number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } else if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - if (base === 'hex') - base = 16; - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') - start++; - - if (base === 16) - this._parseHex(number, start); - else - this._parseBase(number, base, start); - - if (number[0] === '-') - this.sign = true; - - this.strip(); - - if (endian !== 'le') - return; - - this._initArray(this.toArray(), base, endian); -}; - -BN.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.sign = true; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') - return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); +},{"robust-orientation":1040}],81:[function(require,module,exports){ +module.exports = { + AFG: "afghan", + ALA: "\\b\\wland", + ALB: "albania", + DZA: "algeria", + ASM: "^(?=.*americ).*samoa", + AND: "andorra", + AGO: "angola", + AIA: "anguill?a", + ATA: "antarctica", + ATG: "antigua", + ARG: "argentin", + ARM: "armenia", + ABW: "^(?!.*bonaire).*\\baruba", + AUS: "australia", + AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp", + AZE: "azerbaijan", + BHS: "bahamas", + BHR: "bahrain", + BGD: "bangladesh|^(?=.*east).*paki?stan", + BRB: "barbados", + BLR: "belarus|byelo", + BEL: "^(?!.*luxem).*belgium", + BLZ: "belize|^(?=.*british).*honduras", + BEN: "benin|dahome", + BMU: "bermuda", + BTN: "bhutan", + BOL: "bolivia", + BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands", + BIH: "herzegovina|bosnia", + BWA: "botswana|bechuana", + BVT: "bouvet", + BRA: "brazil", + IOT: "british.?indian.?ocean", + BRN: "brunei", + BGR: "bulgaria", + BFA: "burkina|\\bfaso|upper.?volta", + BDI: "burundi", + KHM: "cambodia|kampuchea|khmer", + CMR: "cameroon", + CAN: "canada", + CPV: "verde", + CYM: "cayman", + CAF: "\\bcentral.african.republic", + TCD: "\\bchad", + CHL: "\\bchile", + CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china", + CXR: "christmas", + CCK: "\\bcocos|keeling", + COL: "colombia", + COM: "comoro", + COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc", + COG: "^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo", + COK: "\\bcook", + CRI: "costa.?rica", + CIV: "ivoire|ivory", + HRV: "croatia", + CUB: "\\bcuba", + CUW: "^(?!.*bonaire).*\\bcura(c|ç)ao", + CYP: "cyprus", + CZE: "^(?=.*rep).*czech|czechia|bohemia", + CSK: "czechoslovakia", + DNK: "denmark", + DJI: "djibouti", + DMA: "dominica(?!n)", + DOM: "dominican.rep", + ECU: "ecuador", + EGY: "egypt", + SLV: "el.?salvador", + GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea", + ERI: "eritrea", + EST: "estonia", + ETH: "ethiopia|abyssinia", + FLK: "falkland|malvinas", + FRO: "faroe|faeroe", + FJI: "fiji", + FIN: "finland", + FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul", + GUF: "^(?=.*french).*guiana", + PYF: "french.?polynesia|tahiti", + ATF: "french.?southern", + GAB: "gabon", + GMB: "gambia", + GEO: "^(?!.*south).*georgia", + DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany", + DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german", + GHA: "ghana|gold.?coast", + GIB: "gibraltar", + GRC: "greece|hellenic|hellas", + GRL: "greenland", + GRD: "grenada", + GLP: "guadeloupe", + GUM: "\\bguam", + GTM: "guatemala", + GGY: "guernsey", + GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea", + GNB: "bissau|^(?=.*portu).*guinea", + GUY: "guyana|british.?guiana", + HTI: "haiti", + HMD: "heard.*mcdonald", + VAT: "holy.?see|vatican|papal.?st", + HND: "^(?!.*brit).*honduras", + HKG: "hong.?kong", + HUN: "^(?!.*austr).*hungary", + ISL: "iceland", + IND: "india(?!.*ocea)", + IDN: "indonesia", + IRN: "\\biran|persia", + IRQ: "\\biraq|mesopotamia", + IRL: "ireland", + IMN: "^(?=.*isle).*\\bman", + ISR: "israel", + ITA: "italy", + JAM: "jamaica", + JPN: "japan", + JEY: "jersey", + JOR: "jordan", + KAZ: "kazak", + KEN: "kenya|british.?east.?africa|east.?africa.?prot", + KIR: "kiribati", + PRK: "^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk", + KOR: "^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea", + KWT: "kuwait", + KGZ: "kyrgyz|kirghiz", + LAO: "\\blaos?\\b", + LVA: "latvia", + LBN: "lebanon", + LSO: "lesotho|basuto", + LBR: "liberia", + LBY: "libya", + LIE: "liechtenstein", + LTU: "lithuania", + LUX: "^(?!.*belg).*luxem", + MAC: "maca(o|u)", + MKD: "macedonia|fyrom", + MDG: "madagascar|malagasy", + MWI: "malawi|nyasa", + MYS: "malaysia", + MDV: "maldive", + MLI: "\\bmali\\b", + MLT: "\\bmalta", + MHL: "marshall", + MTQ: "martinique", + MRT: "mauritania", + MUS: "mauritius", + MYT: "\\bmayotte", + MEX: "\\bmexic", + FSM: "micronesia", + MDA: "moldov|b(a|e)ssarabia", + MCO: "monaco", + MNG: "mongolia", + MNE: "^(?!.*serbia).*montenegro", + MSR: "montserrat", + MAR: "morocco|\\bmaroc", + MOZ: "mozambique", + MMR: "myanmar|burma", + NAM: "namibia", + NRU: "nauru", + NPL: "nepal", + NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands", + ANT: "^(?=.*\\bant).*(nether|dutch)", + NCL: "new.?caledonia", + NZL: "new.?zealand", + NIC: "nicaragua", + NER: "\\bniger(?!ia)", + NGA: "nigeria", + NIU: "niue", + NFK: "norfolk", + MNP: "mariana", + NOR: "norway", + OMN: "\\boman|trucial", + PAK: "^(?!.*east).*paki?stan", + PLW: "palau", + PSE: "palestin|\\bgaza|west.?bank", + PAN: "panama", + PNG: "papua|new.?guinea", + PRY: "paraguay", + PER: "peru", + PHL: "philippines", + PCN: "pitcairn", + POL: "poland", + PRT: "portugal", + PRI: "puerto.?rico", + QAT: "qatar", + REU: "r(e|é)union", + ROU: "r(o|u|ou)mania", + RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics", + RWA: "rwanda", + BLM: "barth(e|é)lemy", + SHN: "helena", + KNA: "kitts|\\bnevis", + LCA: "\\blucia", + MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)", + SPM: "miquelon", + VCT: "vincent", + WSM: "^(?!.*amer).*samoa", + SMR: "san.?marino", + STP: "\\bs(a|ã)o.?tom(e|é)", + SAU: "\\bsa\\w*.?arabia", + SEN: "senegal", + SRB: "^(?!.*monte).*serbia", + SYC: "seychell", + SLE: "sierra", + SGP: "singapore", + SXM: "^(?!.*martin)(?!.*saba).*maarten", + SVK: "^(?!.*cze).*slovak", + SVN: "slovenia", + SLB: "solomon", + SOM: "somali", + ZAF: "\\bs\\w*.?africa", + SGS: "south.?georgia|sandwich", + SSD: "\\bs\\w*.?sudan", + ESP: "spain", + LKA: "sri.?lanka|ceylon", + SDN: "^(?!.*\\bs(?!u)).*sudan", + SUR: "surinam|dutch.?guiana", + SJM: "svalbard", + SWZ: "swaziland", + SWE: "sweden", + CHE: "switz|swiss", + SYR: "syria", + TWN: "taiwan|taipei|formosa", + TJK: "tajik", + TZA: "tanzania", + THA: "thailand|\\bsiam", + TLS: "^(?=.*leste).*timor|^(?=.*east).*timor", + TGO: "togo", + TKL: "tokelau", + TON: "tonga", + TTO: "trinidad|tobago", + TUN: "tunisia", + TUR: "turkey", + TKM: "turkmen", + TCA: "turks", + TUV: "tuvalu", + UGA: "uganda", + UKR: "ukrain", + ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em", + GBR: "united.?kingdom|britain|^u\\.?k\\.?$", + USA: "united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)", + UMI: "minor.?outlying.?is", + URY: "uruguay", + UZB: "uzbek", + VUT: "vanuatu|new.?hebrides", + VEN: "venezuela", + VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam", + VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin", + VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin", + WLF: "futuna|wallis", + ESH: "western.sahara", + YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen", + YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen", + YUG: "yugoslavia", + ZMB: "zambia|northern.?rhodesia", + EAZ: "zanzibar", + ZWE: "zimbabwe|^(?!.*northern).*rhodesia" }; -BN.prototype._initArray = function _initArray(number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; +},{}],82:[function(require,module,exports){ +!function() { + var d3 = { + version: "3.5.17" + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = this.document; + function d3_documentElement(node) { + return node && (node.ownerDocument || node.document || node).documentElement; } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - var off = 0; - if (endian === 'be') { - for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { - var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (var i = 0, j = 0; i < number.length; i += 3) { - var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } + function d3_window(node) { + return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); } - return this.strip(); -}; - -function parseHex(str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) - r |= c - 49 + 0xa; - - // 'A' - 'F' - else if (c >= 17 && c <= 22) - r |= c - 17 + 0xa; - - // '0' - '9' - else - r |= c & 0xf; + if (d3_document) { + try { + d3_array(d3_document.documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array = new Array(i); + while (i--) array[i] = list[i]; + return array; + }; + } } - return r; -} - -BN.prototype._parseHex = function _parseHex(number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - // Scan 24-bit chunks and add them to the number - var off = 0; - for (var i = number.length - 6, j = 0; i >= start; i -= 6) { - var w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + if (!Date.now) Date.now = function() { + return +new Date(); + }; + if (d3_document) { + try { + d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name, value) { + d3_element_setAttribute.call(this, name, value + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value) { + d3_element_setAttributeNS.call(this, space, local, value + ""); + }; + d3_style_prototype.setProperty = function(name, value, priority) { + d3_style_setProperty.call(this, name, value + "", priority); + }; } } - if (i + 6 !== start) { - var w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + d3.ascending = d3_ascending; + function d3_ascending(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } - this.strip(); -}; - -function parseBase(str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) - r += c - 49 + 0xa; - - // 'A' - else if (c >= 17) - r += c - 17 + 0xa; - - // '0' - '9' - else - r += c; + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; + }; + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; + }; + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; + }; + function d3_number(x) { + return x === null ? NaN : +x; } - return r; -} - -BN.prototype._parseBase = function _parseBase(number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) - limbLen++; - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) - this.words[0] += word; - else - this._iaddn(word); + function d3_numeric(x) { + return !isNaN(x); } - - if (mod !== 0) { - var pow = 1; - var word = parseBase(number, i, number.length, base); - - for (var i = 0; i < mod; i++) - pow *= base; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) - this.words[0] += word; - else - this._iaddn(word); - } -}; - -BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - dest.words[i] = this.words[i]; - dest.length = this.length; - dest.sign = this.sign; - dest.red = this.red; -}; - -BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; -}; - -// Remove leading `0` from `this` -BN.prototype.strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) - this.length--; - return this._normSign(); -}; - -BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) - this.sign = false; - return this; -}; - -BN.prototype.inspect = function inspect() { - return (this.red ? ''; -}; - -/* - -var zeros = []; -var groupSizes = []; -var groupBases = []; - -var s = ''; -var i = -1; -while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; -} -groupSizes[0] = 0; -groupSizes[1] = 0; -groupBases[0] = 0; -groupBases[1] = 0; -var base = 2 - 1; -while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; -} - -*/ - -var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' -]; - -var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 -]; - -var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 -]; - -BN.prototype.toString = function toString(base, padding) { - base = base || 10; - if (base === 16 || base === 'hex') { - var out = ''; - var off = 0; - var padding = padding | 0 || 1; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) - out = zeros[6 - word.length] + word + out; - else - out = word + out; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = +array[i])) s += a; + } else { + while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; } - if (carry !== 0) - out = carry.toString(16) + out; - while (out.length % padding !== 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - var out = ''; - var c = this.clone(); - c.sign = false; - while (c.cmpn(0) !== 0) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (c.cmpn(0) !== 0) - out = zeros[groupSize - r.length] + r + out; - else - out = r + out; + return s; + }; + d3.mean = function(array, f) { + var s = 0, n = array.length, a, i = -1, j = n; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; } - if (this.cmpn(0) === 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else { - assert(false, 'Base should be between 2 and 36'); + if (j) return s / j; + }; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + var numbers = [], n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); + } + if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); + }; + d3.variance = function(array, f) { + var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) { + if (d3_numeric(a = d3_number(array[i]))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } else { + while (++i < n) { + if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } + if (j > 1) return s / (j - 1); + }; + d3.deviation = function() { + var v = d3.variance.apply(this, arguments); + return v ? Math.sqrt(v) : v; + }; + function d3_bisector(compare) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; + } + return lo; + } + }; } -}; - -BN.prototype.toJSON = function toJSON() { - return this.toString(16); -}; - -BN.prototype.toArray = function toArray(endian) { - this.strip(); - var res = new Array(this.byteLength()); - res[0] = 0; - - var q = this.clone(); - if (endian !== 'le') { - // Assume big-endian - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); - - res[res.length - i - 1] = b; + var d3_bisect = d3_bisector(d3_ascending); + d3.bisectLeft = d3_bisect.left; + d3.bisect = d3.bisectRight = d3_bisect.right; + d3.bisector = function(f) { + return d3_bisector(f.length === 1 ? function(d, x) { + return d3_ascending(f(d), x); + } : f); + }; + d3.shuffle = function(array, i0, i1) { + if ((m = arguments.length) < 3) { + i1 = array.length; + if (m < 2) i0 = 0; } - } else { - // Assume little-endian - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); - - res[i] = b; + var m = i1 - i0, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; + } + return array; + }; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.transpose = function(matrix) { + if (!(n = matrix.length)) return []; + for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { + for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { + row[j] = matrix[j][i]; + } } + return transpose; + }; + function d3_transposeLength(d) { + return d.length; } - - return res; -}; - -if (Math.clz32) { - BN.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); + d3.zip = function() { + return d3.transpose(arguments); }; -} else { - BN.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; + } } - if (t >= 0x40) { - r += 7; - t >>>= 7; + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } } - if (t >= 0x8) { - r += 4; - t >>>= 4; + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); } - if (t >= 0x02) { - r += 2; - t >>>= 2; + } + d3.map = function(object, f) { + var map = new d3_Map(); + if (object instanceof d3_Map) { + object.forEach(function(key, value) { + map.set(key, value); + }); + } else if (Array.isArray(object)) { + var i = -1, n = object.length, o; + if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); + } else { + for (var key in object) map.set(key, object[key]); } - return r + t; + return map; }; -} - -BN.prototype._zeroBits = function _zeroBits(w) { - // Short-cut - if (w === 0) - return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; + function d3_Map() { + this._ = Object.create(null); } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; + var d3_map_proto = "__proto__", d3_map_zero = "\x00"; + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this._[d3_map_escape(key)]; + }, + set: function(key, value) { + return this._[d3_map_escape(key)] = value; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + for (var key in this._) values.push(this._[key]); + return values; + }, + entries: function() { + var entries = []; + for (var key in this._) entries.push({ + key: d3_map_unescape(key), + value: this._[key] + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); + } + }); + function d3_map_escape(key) { + return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; + function d3_map_unescape(key) { + return (key += "")[0] === d3_map_zero ? key.slice(1) : key; } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; + function d3_map_has(key) { + return d3_map_escape(key) in this._; } - if ((t & 0x1) === 0) - r++; - return r; -}; - -// Return number of used bits in a BN -BN.prototype.bitLength = function bitLength() { - var hi = 0; - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; -}; - -// Number of trailing zero bits -BN.prototype.zeroBits = function zeroBits() { - if (this.cmpn(0) === 0) - return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) - break; + function d3_map_remove(key) { + return (key = d3_map_escape(key)) in this._ && delete this._[key]; } - return r; -}; - -BN.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); -}; - -// Return negative clone of `this` -BN.prototype.neg = function neg() { - if (this.cmpn(0) === 0) - return this.clone(); - - var r = this.clone(); - r.sign = !this.sign; - return r; -}; - - -// Or `num` with `this` in-place -BN.prototype.ior = function ior(num) { - this.sign = this.sign || num.sign; - - while (this.length < num.length) - this.words[this.length++] = 0; - - for (var i = 0; i < num.length; i++) - this.words[i] = this.words[i] | num.words[i]; - - return this.strip(); -}; - - -// Or `num` with `this` -BN.prototype.or = function or(num) { - if (this.length > num.length) - return this.clone().ior(num); - else - return num.clone().ior(this); -}; - - -// And `num` with `this` in-place -BN.prototype.iand = function iand(num) { - this.sign = this.sign && num.sign; - - // b = min-length(num, this) - var b; - if (this.length > num.length) - b = num; - else - b = this; - - for (var i = 0; i < b.length; i++) - this.words[i] = this.words[i] & num.words[i]; - - this.length = b.length; - - return this.strip(); -}; - - -// And `num` with `this` -BN.prototype.and = function and(num) { - if (this.length > num.length) - return this.clone().iand(num); - else - return num.clone().iand(this); -}; - - -// Xor `num` with `this` in-place -BN.prototype.ixor = function ixor(num) { - this.sign = this.sign || num.sign; - - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + function d3_map_keys() { + var keys = []; + for (var key in this._) keys.push(d3_map_unescape(key)); + return keys; } - - for (var i = 0; i < b.length; i++) - this.words[i] = a.words[i] ^ b.words[i]; - - if (this !== a) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - - this.length = a.length; - - return this.strip(); -}; - - -// Xor `num` with `this` -BN.prototype.xor = function xor(num) { - if (this.length > num.length) - return this.clone().ixor(num); - else - return num.clone().ixor(this); -}; - - -// Set `bit` of `this` -BN.prototype.setn = function setn(bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - while (this.length <= off) - this.words[this.length++] = 0; - - if (val) - this.words[off] = this.words[off] | (1 << wbit); - else - this.words[off] = this.words[off] & ~(1 << wbit); - - return this.strip(); -}; - - -// Add `num` to `this` in-place -BN.prototype.iadd = function iadd(num) { - // negative + positive - if (this.sign && !num.sign) { - this.sign = false; - var r = this.isub(num); - this.sign = !this.sign; - return this._normSign(); - - // positive + negative - } else if (!this.sign && num.sign) { - num.sign = false; - var r = this.isub(num); - num.sign = true; - return r._normSign(); + function d3_map_size() { + var size = 0; + for (var key in this._) ++size; + return size; } - - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + function d3_map_empty() { + for (var key in this._) return false; + return true; } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] + b.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); + } + } + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; + } + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); + }; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() { + this._ = Object.create(null); } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; + d3_class(d3_Set, { + has: d3_map_has, + add: function(key) { + this._[d3_map_escape(key += "")] = true; + return key; + }, + remove: d3_map_remove, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key)); + } + }); + d3.behavior = {}; + function d3_identity(d) { + return d; } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) - this.words[i] = a.words[i]; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; } - - return this; -}; - -// Add `num` to `this` -BN.prototype.add = function add(num) { - if (num.sign && !this.sign) { - num.sign = false; - var res = this.sub(num); - num.sign = true; - return res; - } else if (!num.sign && this.sign) { - this.sign = false; - var res = num.sub(this); - this.sign = true; - return res; + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.slice(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } } - - if (this.length > num.length) - return this.clone().iadd(num); - else - return num.clone().iadd(this); -}; - -// Subtract `num` from `this` in-place -BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.sign) { - num.sign = false; - var r = this.iadd(num); - num.sign = true; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.sign) { - this.sign = false; - this.iadd(num); - this.sign = true; - return this._normSign(); + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.slice(i + 1); + type = type.slice(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.sign = false; - this.length = 1; - this.words[0] = 0; - return this; + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); } - - // a > b - var a; - var b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] - b.words[i] + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - this.length = Math.max(this.length, i); - - if (a !== this) - this.sign = true; - - return this.strip(); -}; - -// Subtract `num` from `this` -BN.prototype.sub = function sub(num) { - return this.clone().isub(num); -}; - -/* -// NOTE: This could be potentionally used to generate loop-less multiplications -function _genCombMulTo(alen, blen) { - var len = alen + blen - 1; - var src = [ - 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + - 'mask = 0x3ffffff, shift = 0x4000000;', - 'out.length = ' + len + ';' - ]; - for (var k = 0; k < len; k++) { - var minJ = Math.max(0, k - alen + 1); - var maxJ = Math.min(k, blen - 1); - - for (var j = minJ; j <= maxJ; j++) { - var i = k - j; - var mul = 'a[' + i + '] * b[' + j + ']'; - - if (j === minJ) { - src.push('w = ' + mul + ' + c;'); - src.push('c = (w / shift) | 0;'); - } else { - src.push('w += ' + mul + ';'); - src.push('c += (w / shift) | 0;'); + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatches = function(n, s) { + var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; + d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + return d3_selectMatches(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = Sizzle; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3.select(d3_document.documentElement); + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } } - src.push('w &= mask;'); } - src.push('o[' + k + '] = w;'); + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; } - src.push('if (c !== 0) {', - ' o[' + k + '] = c;', - ' out.length++;', - '}', - 'return out;'); - - return src.join('\n'); -} -*/ - -BN.prototype._smallMulTo = function _smallMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; - - var carry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } } - out.words[k] = rword; - carry = ncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; } - - return out.strip(); -}; - -BN.prototype._bigMulTo = function _bigMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; + var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: d3_nsXhtml, + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); -}; - -BN.prototype.mulTo = function mulTo(num, out) { - var res; - if (this.length + num.length < 63) - res = this._smallMulTo(num, out); - else - res = this._bigMulTo(num, out); - return res; -}; - -// Multiply `this` by `num` -BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); -}; - -// In-place Multiplication -BN.prototype.imul = function imul(num) { - if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { - this.words[0] = 0; - this.length = 1; - return this; - } - - var tlen = this.length; - var nlen = num.length; - - this.sign = num.sign !== this.sign; - this.length = this.length + num.length; - this.words[this.length - 1] = 0; - - for (var k = this.length - 2; k >= 0; k--) { - // Sum all words with the same `i + j = k` and accumulate `carry`, - // note that carry could be >= 0x3ffffff - var carry = 0; - var rword = 0; - var maxJ = Math.min(k, nlen - 1); - for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i]; - var b = num.words[j]; - var r = a * b; - - var lo = r & 0x3ffffff; - carry += (r / 0x4000000) | 0; - lo += rword; - rword = lo & 0x3ffffff; - carry += lo >>> 26; + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; } - this.words[k] = rword; - this.words[k + 1] += carry; - carry = 0; - } - - // Propagate overflows - var carry = 0; - for (var i = 1; i < this.length; i++) { - var w = this.words[i] + carry; - this.words[i] = w & 0x3ffffff; - carry = w >>> 26; - } - - return this.strip(); -}; - -BN.prototype.imuln = function imuln(num) { - assert(typeof num === 'number'); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i] * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; -}; - -BN.prototype.muln = function muln(num) { - return this.clone().imuln(num); -}; - -// `this` * `this` -BN.prototype.sqr = function sqr() { - return this.mul(this); -}; - -// `this` * `this` in-place -BN.prototype.isqr = function isqr() { - return this.mul(this); -}; - -// Shift-left in-place -BN.prototype.ishln = function ishln(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - - if (r !== 0) { - var carry = 0; - for (var i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); } - if (carry) { - this.words[i] = carry; - this.length++; + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); } + function attrConstant() { + this.setAttribute(name, value); + } + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); + } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); + } + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + } + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } - - if (s !== 0) { - for (var i = this.length - 1; i >= 0; i--) - this.words[i + s] = this.words[i]; - for (var i = 0; i < s; i++) - this.words[i] = 0; - this.length += s; - } - - return this.strip(); -}; - -// Shift-right in-place -// NOTE: `hint` is a lowest bit before trailing zeroes -// NOTE: if `extended` is present - it will be filled with destroyed bits -BN.prototype.ishrn = function ishrn(bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) - h = (hint - (hint % 26)) / 26; - else - h = 0; - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) - maskedWords.words[i] = this.words[i]; - maskedWords.length = s; + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (var i = 0; i < this.length; i++) - this.words[i] = this.words[i + s]; - } else { - this.words[0] = 0; - this.length = 1; + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; + } + return true; + } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; + } + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } - - var carry = 0; - for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i]; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; + function d3_selection_classes(name) { + return (name + "").trim().split(/^|\s+/); } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) - maskedWords.words[maskedWords.length++] = carry; - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; + function d3_selection_classed(name, value) { + name = d3_selection_classes(name).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); + } + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; } - - this.strip(); - - return this; -}; - -// Shift-left -BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); -}; - -// Shift-right -BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); -}; - -// Test if n bit is set -BN.prototype.testn = function testn(bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - return false; + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); + } + }; } - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); -}; - -// Return only lowers bits of number (in-place) -BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(!this.sign, 'imaskn works only with positive numbers'); - - if (r !== 0) - s++; - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) { + var node = this.node(); + return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); + } + priority = ""; + } + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); + } + function styleConstant() { + this.style.setProperty(name, value, priority); + } + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + } + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; } - - return this.strip(); -}; - -// Return only lowers bits of number -BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); -}; - -// Add plain number `num` to `this` -BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.isubn(-num); - - // Possible sign change - if (this.sign) { - if (this.length === 1 && this.words[0] < num) { - this.words[0] = num - this.words[0]; - this.sign = false; + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); return this; } - - this.sign = false; - this.isubn(num); - this.sign = true; - return this; - } - - // Add without checks - return this._iaddn(num); -}; - -BN.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) - this.words[i + 1] = 1; - else - this.words[i + 1]++; - } - this.length = Math.max(this.length, i + 1); - - return this; -}; - -// Subtract plain number `num` from `this` -BN.prototype.isubn = function isubn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.iaddn(-num); - - if (this.sign) { - this.sign = false; - this.iaddn(num); - this.sign = true; - return this; + return this.each(d3_selection_property(name, value)); + }; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; + } + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; } - - this.words[0] -= num; - - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - - return this.strip(); -}; - -BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); -}; - -BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); -}; - -BN.prototype.iabs = function iabs() { - this.sign = false; - - return this; -}; - -BN.prototype.abs = function abs() { - return this.clone().iabs(); -}; - -BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { - // Bigger storage is needed - var len = num.length + shift; - var i; - if (this.words.length < len) { - var t = new Array(len); - for (var i = 0; i < this.length; i++) - t[i] = this.words[i]; - this.words = t; - } else { - i = this.length; - } - - // Zeroify rest - this.length = Math.max(this.length, len); - for (; i < this.length; i++) - this.words[i] = 0; - - var carry = 0; - for (var i = 0; i < num.length; i++) { - var w = this.words[i + shift] + carry; - var right = num.words[i] * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - var w = this.words[i + shift] + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) - return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (var i = 0; i < this.length; i++) { - var w = -this.words[i] + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.sign = true; - - return this.strip(); -}; - -BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1]; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.shln(shift); - a.ishln(shift); - bhi = b.words[b.length - 1]; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) - q.words[i] = 0; - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (!diff.sign) { - a = diff; - if (q) - q.words[m] = 1; - } - - for (var j = m - 1; j >= 0; j--) { - var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1]; - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.sign) { - qj--; - a.sign = false; - a._ishlnsubmul(b, 1, j); - if (a.cmpn(0) !== 0) - a.sign = !a.sign; + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + function create() { + var document = this.ownerDocument, namespace = this.namespaceURI; + return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); } - if (q) - q.words[j] = qj; - } - if (q) - q.strip(); - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) - a.ishrn(shift); - return { div: q ? q : null, mod: a }; -}; - -BN.prototype.divmod = function divmod(num, mode) { - assert(num.cmpn(0) !== 0); - - if (this.sign && !num.sign) { - var res = this.neg().divmod(num, mode); - var div; - var mod; - if (mode !== 'mod') - div = res.div.neg(); - if (mode !== 'div') - mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); - return { - div: div, - mod: mod - }; - } else if (!this.sign && num.sign) { - var res = this.divmod(num.neg(), mode); - var div; - if (mode !== 'mod') - div = res.div.neg(); - return { div: div, mod: res.mod }; - } else if (this.sign && num.sign) { - return this.neg().divmod(num.neg(), mode); - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) - return { div: new BN(0), mod: this }; - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') - return { div: this.divn(num.words[0]), mod: null }; - else if (mode === 'mod') - return { div: null, mod: new BN(this.modn(num.words[0])) }; - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); -}; - -// Find `this` / `num` -BN.prototype.div = function div(num) { - return this.divmod(num, 'div').div; -}; - -// Find `this` % `num` -BN.prototype.mod = function mod(num) { - return this.divmod(num, 'mod').mod; -}; - -// Find Round(`this` / `num`) -BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.cmpn(0) === 0) - return dm.div; - - var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; - - var half = num.shrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) - return dm.div; - - // Round up - return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); -}; - -BN.prototype.modn = function modn(num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) - acc = (p * acc + this.words[i]) % num; - - return acc; -}; - -// In-place division by number -BN.prototype.idivn = function idivn(num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = this.words[i] + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; + function createNS() { + return this.ownerDocument.createElementNS(name.space, name.local); + } + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; } - - return this.strip(); -}; - -BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); -}; - -BN.prototype.egcd = function egcd(p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); - - var x = this; - var y = p.clone(); - - if (x.sign) - x = x.mod(p); - else - x = x.clone(); - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.ishrn(1); - y.ishrn(1); - ++g; + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(d3_selectionRemove); + }; + function d3_selectionRemove() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); } - - var yp = y.clone(); - var xp = x.clone(); - - while (x.cmpn(0) !== 0) { - while (x.isEven()) { - x.ishrn(1); - if (A.isEven() && B.isEven()) { - A.ishrn(1); - B.ishrn(1); - } else { - A.iadd(yp).ishrn(1); - B.isub(xp).ishrn(1); + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } } + return value; } - - while (y.isEven()) { - y.ishrn(1); - if (C.isEven() && D.isEven()) { - C.ishrn(1); - D.ishrn(1); + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; + for (i = -1; ++i < n; ) { + if (node = group[i]) { + if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues[i] = keyValue; + } + } + for (i = -1; ++i < m; ) { + if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } else if (node !== true) { + updateNodes[i] = node; + node.__data__ = nodeData; + } + nodeByKeyValue.set(keyValue, true); + } + for (i = -1; ++i < n; ) { + if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { + exitNodes[i] = group[i]; + } + } } else { - C.iadd(yp).ishrn(1); - D.isub(xp).ishrn(1); + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } } else { - y.isub(x); - C.isub(A); - D.isub(B); + while (++i < n) { + bind(group = this[i], value); + } } + update.enter = function() { + return enter; + }; + update.exit = function() { + return exit; + }; + return update; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; } - - return { - a: C, - b: D, - gcd: y.ishln(g) + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); }; -}; - -// This is reduced incarnation of the binary EEA -// above, designated to invert members of the -// _prime_ fields F(p) at a maximal speed -BN.prototype._invmp = function _invmp(p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); - - var a = this; - var b = p.clone(); - - if (a.sign) - a = a.mod(p); - else - a = a.clone(); - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - while (a.isEven()) { - a.ishrn(1); - if (x1.isEven()) - x1.ishrn(1); - else - x1.iadd(delta).ishrn(1); - } - while (b.isEven()) { - b.ishrn(1); - if (x2.isEven()) - x2.ishrn(1); - else - x2.iadd(delta).ishrn(1); + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3_ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; } - if (a.cmpn(1) === 0) - return x1; - else - return x2; -}; - -BN.prototype.gcd = function gcd(num) { - if (this.cmpn(0) === 0) - return num.clone(); - if (num.cmpn(0) === 0) - return this.clone(); - - var a = this.clone(); - var b = num.clone(); - a.sign = false; - b.sign = false; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.ishrn(1); - b.ishrn(1); - } - - do { - while (a.isEven()) - a.ishrn(1); - while (b.isEven()) - b.ishrn(1); - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } } - - a.isub(b); - } while (true); - - return b.ishln(shift); -}; - -// Invert number in the field F(num) -BN.prototype.invm = function invm(num) { - return this.egcd(num).a.mod(num); -}; - -BN.prototype.isEven = function isEven() { - return (this.words[0] & 1) === 0; -}; - -BN.prototype.isOdd = function isOdd() { - return (this.words[0] & 1) === 1; -}; - -// And first word and num -BN.prototype.andln = function andln(num) { - return this.words[0] & num; -}; - -// Increment at the bit position in-line -BN.prototype.bincn = function bincn(bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - for (var i = this.length; i < s + 1; i++) - this.words[i] = 0; - this.words[s] |= q; - this.length = s + 1; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i]; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; + return groups; } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + d3_selection_each(this, function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; } - return this; -}; - -BN.prototype.cmpn = function cmpn(num) { - var sign = num < 0; - if (sign) - num = -num; - - if (this.sign && !sign) - return -1; - else if (!this.sign && sign) - return 1; - - num &= 0x3ffffff; - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - var w = this.words[0]; - res = w === num ? 0 : w < num ? -1 : 1; + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; } - if (this.sign) - res = -res; - return res; -}; - -// Compare two numbers and return: -// 1 - if `this` > `num` -// 0 - if `this` == `num` -// -1 - if `this` < `num` -BN.prototype.cmp = function cmp(num) { - if (this.sign && !num.sign) - return -1; - else if (!this.sign && num.sign) - return 1; - - var res = this.ucmp(num); - if (this.sign) - return -res; - else - return res; -}; - -// Unsigned comparison -BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) - return 1; - else if (this.length < num.length) - return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i]; - var b = num.words[i]; - - if (a === b) - continue; - if (a < b) - res = -1; - else if (a > b) - res = 1; - break; + d3.select = function(node) { + var group; + if (typeof node === "string") { + group = [ d3_select(node, d3_document) ]; + group.parentNode = d3_document.documentElement; + } else { + group = [ node ]; + group.parentNode = d3_documentElement(node); + } + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group; + if (typeof nodes === "string") { + group = d3_array(d3_selectAll(nodes, d3_document)); + group.parentNode = d3_document.documentElement; + } else { + group = d3_array(nodes); + group.parentNode = null; + } + return d3_selection([ group ]); + }; + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.slice(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; } - return res; -}; - -// -// A reduce context, could be using montgomery or something better, depending -// on the `m` itself. -// -BN.red = function red(num) { - return new Red(num); -}; - -BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(!this.sign, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); -}; - -BN.prototype.fromRed = function fromRed() { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); -}; - -BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; -}; - -BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); -}; - -BN.prototype.redAdd = function redAdd(num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); -}; - -BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); -}; - -BN.prototype.redSub = function redSub(num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); -}; - -BN.prototype.redISub = function redISub(num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); -}; - -BN.prototype.redShl = function redShl(num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); -}; - -BN.prototype.redMul = function redMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); -}; - -BN.prototype.redIMul = function redIMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); -}; - -BN.prototype.redSqr = function redSqr() { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); -}; - -BN.prototype.redISqr = function redISqr() { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); -}; - -// Square root over p -BN.prototype.redSqrt = function redSqrt() { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); -}; - -BN.prototype.redInvm = function redInvm() { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); -}; - -// Return negative clone of `this` % `red modulo` -BN.prototype.redNeg = function redNeg() { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); -}; - -BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); -}; - -// Prime numbers with efficient reduction -var primes = { - k256: null, - p224: null, - p192: null, - p25519: null -}; - -// Pseudo-Mersenne prime -function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).ishln(this.n).isub(this.p); - - this.tmp = this._tmp(); -} - -MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; -}; - -MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + if (d3_document) { + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); } - - return r; -}; - -MPrime.prototype.split = function split(input, out) { - input.ishrn(this.n, 0, out); -}; - -MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); -}; - -function K256() { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); -} -inherits(K256, MPrime); - -K256.prototype.split = function split(input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d3.event = o; + } + }; } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (var i = 10; i < input.length; i++) { - var next = input.words[i]; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; } - input.words[i - 10] = prev >>> 22; - input.length -= 9; -}; - -K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var hi; - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i]; - hi = w * 0x40; - lo += w * 0x3d1; - hi += (lo / 0x4000000) | 0; - lo &= 0x3ffffff; - - num.words[i] = lo; - - lo = hi; + var d3_event_dragSelect, d3_event_dragId = 0; + function d3_event_dragSuppress(node) { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect == null) { + d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); + } + if (d3_event_dragSelect) { + var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + var off = function() { + w.on(click, null); + }; + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) - num.length--; + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0) { + var window = d3_window(container); + if (window.scrollX || window.scrollY) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; + } + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; } - return num; -}; - -function P224() { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); -} -inherits(P224, MPrime); - -function P192() { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); -} -inherits(P192, MPrime); - -function P25519() { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); -} -inherits(P25519, MPrime); - -P25519.prototype.imulK = function imulK(num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = num.words[i] * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; + d3.touch = function(container, touches, identifier) { + if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; + if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { + if ((touch = touches[i]).identifier === identifier) { + return d3_mousePoint(container, touch); + } + } + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function dragstart(id, position, subject, move, end) { + return function() { + var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); + if (origin) { + dragOffset = origin.apply(that, arguments); + dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; + } else { + dragOffset = [ 0, 0 ]; + } + dispatch({ + type: "dragstart" + }); + function moved() { + var position1 = position(parent, dragId), dx, dy; + if (!position1) return; + dx = position1[0] - position0[0]; + dy = position1[1] - position0[1]; + dragged |= dx | dy; + position0 = position1; + dispatch({ + type: "drag", + x: position1[0] + dragOffset[0], + y: position1[1] + dragOffset[1], + dx: dx, + dy: dy + }); + } + function ended() { + if (!position(parent, dragId)) return; + dragSubject.on(move + dragName, null).on(end + dragName, null); + dragRestore(dragged); + dispatch({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d3.rebind(drag, event, "on"); + }; + function d3_behavior_dragTouchId() { + return d3.event.changedTouches[0].identifier; } - if (carry !== 0) - num.words[num.length++] = carry; - return num; -}; - -// Exported mostly for testing purposes, use plain name instead -BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) - return primes[name]; - - var prime; - if (name === 'k256') - prime = new K256(); - else if (name === 'p224') - prime = new P224(); - else if (name === 'p192') - prime = new P192(); - else if (name === 'p25519') - prime = new P25519(); - else - throw new Error('Unknown prime ' + name); - primes[name] = prime; - - return prime; -}; - -// -// Base reduction engine -// -function Red(m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - this.m = m; - this.prime = null; + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; } -} - -Red.prototype._verify1 = function _verify1(a) { - assert(!a.sign, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); -}; - -Red.prototype._verify2 = function _verify2(a, b) { - assert(!a.sign && !b.sign, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); -}; - -Red.prototype.imod = function imod(a) { - if (this.prime) - return this.prime.ireduce(a)._forceRed(this); - return a.mod(this.m)._forceRed(this); -}; - -Red.prototype.neg = function neg(a) { - var r = a.clone(); - r.sign = !r.sign; - return r.iadd(this.m)._forceRed(this); -}; - -Red.prototype.add = function add(a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res._forceRed(this); -}; - -Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res; -}; - -Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res._forceRed(this); -}; - -Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res; -}; - -Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.shln(num)); -}; - -Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); -}; - -Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); -}; - -Red.prototype.isqr = function isqr(a) { - return this.imul(a, a); -}; - -Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); -}; - -Red.prototype.sqrt = function sqrt(a) { - if (a.cmpn(0) === 0) - return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).ishrn(2); - var r = this.pow(a, pow); - return r; + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (q.cmpn(0) !== 0 && q.andln(1) === 0) { - s++; - q.ishrn(1); + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); } - assert(q.cmpn(0) !== 0); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).ishrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - while (this.pow(z, lpow).cmp(nOne) !== 0) - z.redIAdd(nOne); - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).ishrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) - tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).ishln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); } - - return r; -}; - -Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); - if (inv.sign) { - inv.sign = false; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; } -}; - -Red.prototype.pow = function pow(a, num) { - var w = []; - - if (num.cmpn(0) === 0) - return new BN(1); - - var q = num.clone(); - - while (q.cmpn(0) !== 0) { - w.push(q.andln(1)); - q.ishrn(1); + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; } - - // Skip leading zeroes - var res = a; - for (var i = 0; i < w.length; i++, res = this.sqr(res)) - if (w[i] !== 0) - break; - - if (++i < w.length) { - for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { - if (w[i] === 0) - continue; - res = this.mul(res, q); - } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); } - - return res; -}; - -Red.prototype.convertTo = function convertTo(num) { - var r = num.mod(this.m); - if (r === num) - return r.clone(); - else - return r; -}; - -Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; -}; - -// -// Montgomery method engine -// - -BN.mont = function mont(num) { - return new Mont(num); -}; - -function Mont(m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) - this.shift += 26 - (this.shift % 26); - this.r = new BN(1).ishln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv.sign = true; - this.minv = this.minv.mod(this.r); -} -inherits(Mont, Red); - -Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.shln(this.shift)); -}; - -Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; -}; - -Mont.prototype.imul = function imul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { - a.words[0] = 0; - a.length = 1; - return a; + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); - - return res._forceRed(this); -}; - -Mont.prototype.mul = function mul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) - return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); - - return res._forceRed(this); -}; - -Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); -}; - -})(typeof module === 'undefined' || module, this); - -},{}],80:[function(require,module,exports){ -'use strict' - -var bnsign = require('./lib/bn-sign') - -module.exports = sign - -function sign(x) { - return bnsign(x[0]) * bnsign(x[1]) -} - -},{"./lib/bn-sign":71}],81:[function(require,module,exports){ -'use strict' - -var rationalize = require('./lib/rationalize') - -module.exports = sub - -function sub(a, b) { - return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) -} - -},{"./lib/rationalize":76}],82:[function(require,module,exports){ -'use strict' - -var bn2num = require('./lib/bn-to-num') -var ctz = require('./lib/ctz') - -module.exports = roundRat - -//Round a rational to the closest float -function roundRat(f) { - var a = f[0] - var b = f[1] - if(a.cmpn(0) === 0) { - return 0 - } - var h = a.divmod(b) - var iv = h.div - var x = bn2num(iv) - var ir = h.mod - if(ir.cmpn(0) === 0) { - return x - } - if(x) { - var s = ctz(x) + 4 - var y = bn2num(ir.shln(s).divRound(b)) - - // flip the sign of y if x is negative - if (x<0) { - y = -y; + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < ε2) { + S = Math.log(w1 / w0) / ρ; + i = function(t) { + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; + }; + } else { + var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); + S = (r1 - r0) / ρ; + i = function(t) { + var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + }; } - - return x + y * Math.pow(2, -s) - } else { - var ybits = b.bitLength() - ir.bitLength() + 53 - var y = bn2num(ir.shln(ybits).divRound(b)) - if(ybits < 1023) { - return y * Math.pow(2, -ybits) + i.duration = S * 1e3; + return i; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + if (!d3_behavior_zoomWheel) { + d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); } - y *= Math.pow(2, -1023) - return y * Math.pow(2, 1023-ybits) - } -} - -},{"./lib/bn-to-num":72,"./lib/ctz":73}],83:[function(require,module,exports){ -'use strict' - -module.exports = boxIntersectWrapper - -var pool = require('typedarray-pool') -var sweep = require('./lib/sweep') -var boxIntersectIter = require('./lib/intersect') - -function boxEmpty(d, box) { - for(var j=0; j>>1 - if(d <= 0) { - return - } - - var retval - - //Convert red boxes - var redList = pool.mallocDouble(2*d*n) - var redIds = pool.mallocInt32(n) - n = convertBoxes(red, d, redList, redIds) - - if(n > 0) { - if(d === 1 && full) { - //Special case: 1d complete - sweep.init(n) - retval = sweep.sweepComplete( - d, visit, - 0, n, redList, redIds, - 0, n, redList, redIds) - } else { - - //Convert blue boxes - var blueList = pool.mallocDouble(2*d*m) - var blueIds = pool.mallocInt32(m) - m = convertBoxes(blue, d, blueList, blueIds) - - if(m > 0) { - sweep.init(n+m) - - if(d === 1) { - //Special case: 1d bipartite - retval = sweep.sweepBipartite( - d, visit, - 0, n, redList, redIds, - 0, m, blueList, blueIds) - } else { - //General case: d>1 - retval = boxIntersectIter( - d, visit, full, - n, redList, redIds, - m, blueList, blueIds) + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function zoomTo(that, p, l, k) { + that.__chart__ = { + x: view.x, + y: view.y, + k: view.k + }; + scaleTo(Math.pow(2, k)); + translateTo(center0 = p, l); + that = d3.select(that); + if (duration > 0) that = that.transition().duration(duration); + that.call(zoom.event); + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(dispatch) { + if (!zooming++) dispatch({ + type: "zoomstart" + }); + } + function zoomed(dispatch) { + rescale(); + dispatch({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(dispatch) { + if (!--zooming) dispatch({ + type: "zoomend" + }), center0 = null; + } + function mousedowned() { + var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); + d3_selection_interrupt.call(that); + zoomstarted(dispatch); + function moved() { + dragged = 1; + translateTo(d3.mouse(that), location0); + zoomed(dispatch); + } + function ended() { + subject.on(mousemove, null).on(mouseup, null); + dragRestore(dragged); + zoomended(dispatch); + } + } + function touchstarted() { + var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); + started(); + zoomstarted(dispatch); + subject.on(mousedown, null).on(touchstart, started); + function relocate() { + var touches = d3.touches(that); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var target = d3.event.target; + d3.select(target).on(touchmove, moved).on(touchend, ended); + targets.push(target); + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; } - - pool.free(blueList) - pool.free(blueIds) + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0]; + zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); + d3_eventPreventDefault(); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d3.touches(that), p0, l0, p1, l1; + d3_selection_interrupt.call(that); + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(dispatch); + } + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + d3.selectAll(targets).on(zoomName, null); + subject.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(dispatch); } } - - pool.free(redList) - pool.free(redIds) + function mousewheeled() { + var dispatch = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), + translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(dispatch); + }, 50); + d3_eventPreventDefault(); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(center0, translate0); + zoomed(dispatch); + } + function dblclicked() { + var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; + zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + } + return d3.rebind(zoom, event, "on"); + }; + var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; + d3.color = d3_color; + function d3_color() {} + d3_color.prototype.toString = function() { + return this.rgb() + ""; + }; + d3.hsl = d3_hsl; + function d3_hsl(h, s, l) { + return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); } - - return retval -} - - -var RESULT - -function appendItem(i,j) { - RESULT.push([i,j]) -} - -function intersectFullArray(x) { - RESULT = [] - boxIntersect(x, x, appendItem, true) - return RESULT -} - -function intersectBipartiteArray(x, y) { - RESULT = [] - boxIntersect(x, y, appendItem, false) - return RESULT -} - -//User-friendly wrapper, handle full input and no-visitor cases -function boxIntersectWrapper(arg0, arg1, arg2) { - var result - switch(arguments.length) { - case 1: - return intersectFullArray(arg0) - case 2: - if(typeof arg1 === 'function') { - return boxIntersect(arg0, arg0, arg1, true) - } else { - return intersectBipartiteArray(arg0, arg1) - } - case 3: - return boxIntersect(arg0, arg1, arg2, false) - default: - throw new Error('box-intersect: Invalid arguments') + var d3_hslPrototype = d3_hsl.prototype = new d3_color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; + } + function vv(h) { + return Math.round(v(h) * 255); + } + return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } -} -},{"./lib/intersect":85,"./lib/sweep":89,"typedarray-pool":278}],84:[function(require,module,exports){ -'use strict' - -var DIMENSION = 'd' -var AXIS = 'ax' -var VISIT = 'vv' -var FLIP = 'fp' - -var ELEM_SIZE = 'es' - -var RED_START = 'rs' -var RED_END = 're' -var RED_BOXES = 'rb' -var RED_INDEX = 'ri' -var RED_PTR = 'rp' - -var BLUE_START = 'bs' -var BLUE_END = 'be' -var BLUE_BOXES = 'bb' -var BLUE_INDEX = 'bi' -var BLUE_PTR = 'bp' - -var RETVAL = 'rv' - -var INNER_LABEL = 'Q' - -var ARGS = [ - DIMENSION, - AXIS, - VISIT, - RED_START, - RED_END, - RED_BOXES, - RED_INDEX, - BLUE_START, - BLUE_END, - BLUE_BOXES, - BLUE_INDEX -] - -function generateBruteForce(redMajor, flip, full) { - var funcName = 'bruteForce' + - (redMajor ? 'Red' : 'Blue') + - (flip ? 'Flip' : '') + - (full ? 'Full' : '') - - var code = ['function ', funcName, '(', ARGS.join(), '){', - 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] - - var redLoop = - 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + - 'i<' + RED_END +';' + - '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + - 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + - 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + - 'xi=' + RED_INDEX + '[i];' - - var blueLoop = - 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + - 'j<' + BLUE_END + ';' + - '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + - 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + - (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + - 'yi=' + BLUE_INDEX + '[j];' - - if(redMajor) { - code.push(redLoop, INNER_LABEL, ':', blueLoop) - } else { - code.push(blueLoop, INNER_LABEL, ':', redLoop) + d3.hcl = d3_hcl; + function d3_hcl(h, c, l) { + return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); } - - if(full) { - code.push('if(y1 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); } - - var code = ['function ' + funcName + '(' + fargs.join() + '){'] - - function invoke(redMajor, flip) { - var res = generateBruteForce(redMajor, flip, full) - prefix.push(res.code) - code.push('return ' + res.name + '(' + ARGS.join() + ');') + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; } - - code.push('if(' + RED_END + '-' + RED_START + '>' + - BLUE_END + '-' + BLUE_START + '){') - - if(full) { - invoke(true, false) - code.push('}else{') - invoke(false, false) - } else { - code.push('if(' + FLIP + '){') - invoke(true, true) - code.push('}else{') - invoke(true, false) - code.push('}}else{if(' + FLIP + '){') - invoke(false, true) - code.push('}else{') - invoke(false, false) - code.push('}') + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; } - code.push('}}return ' + funcName) - - var codeStr = prefix.join('') + code.join('') - var proc = new Function(codeStr) - return proc() -} - - -exports.partial = bruteForcePlanner(false) -exports.full = bruteForcePlanner(true) -},{}],85:[function(require,module,exports){ -'use strict' - -module.exports = boxIntersectIter - -var pool = require('typedarray-pool') -var bits = require('bit-twiddle') -var bruteForce = require('./brute') -var bruteForcePartial = bruteForce.partial -var bruteForceFull = bruteForce.full -var sweep = require('./sweep') -var findMedian = require('./median') -var genPartition = require('./partition') - -//Twiddle parameters -var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search -var SCAN_CUTOFF = (1<<22) //Cut off for two way scan -var SCAN_COMPLETE_CUTOFF = (1<<22) - -//Partition functions -var partitionInteriorContainsInterval = genPartition( - '!(lo>=p0)&&!(p1>=hi)', - ['p0', 'p1']) - -var partitionStartEqual = genPartition( - 'lo===p0', - ['p0']) - -var partitionStartLessThan = genPartition( - 'lo> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return new d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_rgb(k * this.r, k * this.g, k * this.b); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format, rgb, hsl) { + var r = 0, g = 0, b = 0, m1, m2, color; + m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": + { + return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } -red_loop: - for(var i=redStart, redPtr=redStart*elemSize; i> 4; + r = r >> 4 | r; + g = color & 240; + g = g >> 4 | g; + b = color & 15; + b = b << 4 | b; + } else if (format.length === 7) { + r = (color & 16711680) >> 16; + g = (color & 65280) >> 8; + b = color & 255; } } - var retval - if(flip) { - retval = visit(blueId, redId) + return rgb(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; } else { - retval = visit(redId, blueId) - } - if(retval !== void 0) { - return retval + h = NaN; + s = l > 0 && l < 1 ? 0 : h; } + return new d3_hsl(h, s, l); } -} - -//Special case: Intersect one point with list of intervals -function onePointFull( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueOffset, blue, blueId) { - - var elemSize = 2 * d - var bluePtr = blueOffset * elemSize - var blueX = blue[bluePtr + axis] - -red_loop: - for(var i=redStart, redPtr=redStart*elemSize; i 0) { - top -= 1 - - var iptr = top * IFRAME_SIZE - var axis = BOX_ISTACK[iptr] - var redStart = BOX_ISTACK[iptr+1] - var redEnd = BOX_ISTACK[iptr+2] - var blueStart = BOX_ISTACK[iptr+3] - var blueEnd = BOX_ISTACK[iptr+4] - var state = BOX_ISTACK[iptr+5] - - var dptr = top * DFRAME_SIZE - var lo = BOX_DSTACK[dptr] - var hi = BOX_DSTACK[dptr+1] - - //Unpack state info - var flip = (state & 1) - var full = !!(state & 16) - - //Unpack indices - var red = xBoxes - var redIndex = xIndex - var blue = yBoxes - var blueIndex = yIndex - if(flip) { - red = yBoxes - redIndex = yIndex - blue = xBoxes - blueIndex = xIndex - } - - if(state & 2) { - redEnd = partitionStartLessThan( - d, axis, - redStart, redEnd, red, redIndex, - hi) - if(redStart >= redEnd) { - continue - } - } - if(state & 4) { - redStart = partitionEndLessThanEqual( - d, axis, - redStart, redEnd, red, redIndex, - lo) - if(redStart >= redEnd) { - continue - } - } - - var redCount = redEnd - redStart - var blueCount = blueEnd - blueStart - - if(full) { - if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { - retval = sweep.scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } - } else { - if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { - //If input small, then use brute force - retval = bruteForcePartial( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } else if(d * redCount * blueCount < SCAN_CUTOFF) { - //If input medium sized, then use sweep and prune - retval = sweep.scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d3.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value) { + d3_rgb_names.set(key, d3_rgbNumber(value)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d3.functor = d3_functor; + d3.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, + mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; } - continue + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); } } - - //First, find all red intervals whose interior contains (lo,hi) - var red0 = partitionInteriorContainsInterval( - d, axis, - redStart, redEnd, red, redIndex, - lo, hi) - - //Lower dimensional case - if(redStart < red0) { - - if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { - //Special case for small inputs: use brute force - retval = bruteForceFull( - d, axis+1, visit, - redStart, red0, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; + } + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + function d3_xhrHasResponse(request) { + var type = request.responseType; + return type && type !== "text" ? request.response : request.responseText; + } + d3.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); + xhr.row = function(_) { + return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; + }; + return xhr; + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = new Function("d", "return {" + row.map(function(name, i) { + return JSON.stringify(name) + ": d[" + i + "]"; + }).join(",") + "}"); + o = f ? function(row, i) { + return f(a(row), i); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.slice(j + 1, i).replace(/""/g, '"'); } - } else if(axis === d-2) { - if(flip) { - retval = sweep.sweepBipartite( - d, visit, - blueStart, blueEnd, blue, blueIndex, - redStart, red0, red, redIndex) - } else { - retval = sweep.sweepBipartite( - d, visit, - redStart, red0, red, redIndex, - blueStart, blueEnd, blue, blueIndex) + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.slice(j, I - k); } - if(retval !== void 0) { - return retval + return text.slice(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); } - } else { - iterPush(top++, - axis+1, - redStart, red0, - blueStart, blueEnd, - flip, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blueStart, blueEnd, - redStart, red0, - flip^1, - -Infinity, Infinity) + if (f && (a = f(a, n++)) == null) continue; + rows.push(a); } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); } - - //Divide and conquer phase - if(red0 < redEnd) { - - //Cut blue into 3 parts: - // - // Points < mid point - // Points = mid point - // Points > mid point - // - var blue0 = findMedian( - d, axis, - blueStart, blueEnd, blue, blueIndex) - var mid = blue[elemSize * blue0 + axis] - var blue1 = partitionStartEqual( - d, axis, - blue0, blueEnd, blue, blueIndex, - mid) - - //Right case - if(blue1 < blueEnd) { - iterPush(top++, - axis, - red0, redEnd, - blue1, blueEnd, - (flip|4) + (full ? 16 : 0), - mid, hi) + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function() { + d3_timer.apply(this, arguments); + }; + function d3_timer(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + return timer; + } + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); } - - //Left case - if(blueStart < blue0) { - iterPush(top++, - axis, - red0, redEnd, - blueStart, blue0, - (flip|2) + (full ? 16 : 0), - lo, mid) - } - - //Center case (the hard part) - if(blue0 + 1 === blue1) { - //Optimization: Range with exactly 1 point, use a brute force scan - if(full) { - retval = onePointFull( - d, axis, visit, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) - } else { - retval = onePointPartial( - d, axis, visit, flip, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) - } - if(retval !== void 0) { - return retval - } - } else if(blue0 < blue1) { - var red1 - if(full) { - //If full intersection, need to handle special case - red1 = partitionContainsPoint( - d, axis, - red0, redEnd, red, redIndex, - mid) - if(red0 < red1) { - var redX = partitionStartEqual( - d, axis, - red0, red1, red, redIndex, - mid) - if(axis === d-2) { - //Degenerate sweep intersection: - // [red0, redX] with [blue0, blue1] - if(red0 < redX) { - retval = sweep.sweepComplete( - d, visit, - red0, redX, red, redIndex, - blue0, blue1, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } - - //Normal sweep intersection: - // [redX, red1] with [blue0, blue1] - if(redX < red1) { - retval = sweep.sweepBipartite( - d, visit, - redX, red1, red, redIndex, - blue0, blue1, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } - } else { - if(red0 < redX) { - iterPush(top++, - axis+1, - red0, redX, - blue0, blue1, - 16, - -Infinity, Infinity) - } - if(redX < red1) { - iterPush(top++, - axis+1, - redX, red1, - blue0, blue1, - 0, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blue0, blue1, - redX, red1, - 1, - -Infinity, Infinity) - } - } - } - } else { - if(flip) { - red1 = partitionContainsPointProper( - d, axis, - red0, redEnd, red, redIndex, - mid) - } else { - red1 = partitionContainsPoint( - d, axis, - red0, redEnd, red, redIndex, - mid) - } - if(red0 < red1) { - if(axis === d-2) { - if(flip) { - retval = sweep.sweepBipartite( - d, visit, - blue0, blue1, blue, blueIndex, - red0, red1, red, redIndex) - } else { - retval = sweep.sweepBipartite( - d, visit, - red0, red1, red, redIndex, - blue0, blue1, blue, blueIndex) - } - } else { - iterPush(top++, - axis+1, - red0, red1, - blue0, blue1, - flip, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blue0, blue1, - red0, red1, - flip^1, - -Infinity, Infinity) - } - } - } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(), timer = d3_timer_queueHead; + while (timer) { + if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; + timer = timer.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.c) { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } else { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } } + d3_timer_queueTail = t0; + return time; } -} -},{"./brute":84,"./median":86,"./partition":87,"./sweep":89,"bit-twiddle":50,"typedarray-pool":278}],86:[function(require,module,exports){ -'use strict' + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value = +value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); + } + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + function d3_locale_numberFormat(locale) { + var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { + var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; + while (i > 0 && g > 0) { + if (length + g + 1 > width) g = Math.max(1, width - length); + t.push(value.substring(i -= g, i + g)); + if ((length += g + 1) > width) break; + g = locale_grouping[j = (j + 1) % locale_grouping.length]; + } + return t.reverse().join(locale_thousands); + } : d3_identity; + return function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; + } + switch (type) { + case "n": + comma = true; + type = "g"; + break; -module.exports = findMedian + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; -var genPartition = require('./partition') + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; -var partitionStartLessThan = genPartition('lostart && boxes[ptr+axis] > x; - --j, ptr-=elemSize) { - //Swap - var aPtr = ptr - var bPtr = ptr+elemSize - for(var k=0; k" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; + }; + }; + } + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); } + }); + function d3_format_typeDefault(x) { + return x + ""; } -} - -//Find median using quick select algorithm -// takes O(n) time with high probability -function findMedian(d, axis, start, end, boxes, ids) { - if(end <= start+1) { - return start + var d3_time = d3.time = {}, d3_date = Date; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } - - var lo = start - var hi = end - var mid = ((end + start) >>> 1) - var elemSize = 2*d - var pivot = mid - var value = boxes[elemSize*mid+axis] - - while(lo < hi) { - if(hi - lo < PARTITION_THRESHOLD) { - insertionSort(d, axis, lo, hi, boxes, ids) - value = boxes[elemSize*mid+axis] - break + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); } - - //Select pivot using median-of-3 - var count = hi - lo - var pivot0 = (Math.random()*count+lo)|0 - var value0 = boxes[elemSize*pivot0 + axis] - var pivot1 = (Math.random()*count+lo)|0 - var value1 = boxes[elemSize*pivot1 + axis] - var pivot2 = (Math.random()*count+lo)|0 - var value2 = boxes[elemSize*pivot2 + axis] - if(value0 <= value1) { - if(value2 >= value1) { - pivot = pivot1 - value = value1 - } else if(value0 >= value2) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } - } else { - if(value1 >= value2) { - pivot = pivot1 - value = value1 - } else if(value2 >= value0) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } + }; + var d3_time_prototype = Date.prototype; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; } - - //Swap pivot to end of array - var aPtr = elemSize * (hi-1) - var bPtr = elemSize * pivot - for(var i=0; i 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); } - hi += 1 - } else if(pivot < mid) { - lo = pivot + 1 - while(lo < hi && - boxes[elemSize*lo+axis] === value) { - lo += 1 + return times; + } + function range_utc(t0, t1, dt) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; } - } else { - break } + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; } - - //Make sure pivot is at start - return partitionStartLessThan( - d, axis, - start, mid, boxes, ids, - boxes[elemSize*mid+axis]) -} -},{"./partition":87}],87:[function(require,module,exports){ -'use strict' - -module.exports = genPartition - -var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' - -function genPartition(predicate, args) { - var fargs ='abcdef'.split('').concat(args) - var reads = [] - if(predicate.indexOf('lo') >= 0) { - reads.push('lo=e[k+n]') - } - if(predicate.indexOf('hi') >= 0) { - reads.push('hi=e[k+o]') + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; } - fargs.push( - code.replace('_', reads.join()) - .replace('$', predicate)) - return Function.apply(void 0, fargs) -} -},{}],88:[function(require,module,exports){ -'use strict'; - -//This code is extracted from ndarray-sort -//It is inlined here as a temporary workaround - -module.exports = wrapper; - -var INSERT_SORT_CUTOFF = 32 - -function wrapper(data, n0) { - if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data); - } else { - quickSort(0, n0 - 1, data); - } -} - -function insertionSort(left, right, data) { - var ptr = 2*(left+1) - for(var i=left+1; i<=right; ++i) { - var a = data[ptr++] - var b = data[ptr++] - var j = i - var jptr = ptr-2 - while(j-- > left) { - var x = data[jptr-2] - var y = data[jptr-1] - if(x < a) { - break - } else if(x === a && y < b) { - break + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + function d3_locale_timeFormat(locale) { + var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.slice(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; + } + } + string.push(template.slice(j, i)); + return string.join(""); } - data[jptr] = x - data[jptr+1] = y - jptr -= 2 + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { + if (!("w" in d)) d.w = "W" in d ? 1 : 0; + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; } - data[jptr] = a - data[jptr+1] = b + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + d3_time_format.utc = function(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } + } + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; + } + }; + format.toString = local.toString; + return format; + }; + d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; + var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); + locale_periods.forEach(function(p, i) { + d3_time_periodLookup.set(p.toLowerCase(), i); + }); + var d3_time_formats = { + a: function(d) { + return locale_shortDays[d.getDay()]; + }, + A: function(d) { + return locale_days[d.getDay()]; + }, + b: function(d) { + return locale_shortMonths[d.getMonth()]; + }, + B: function(d) { + return locale_months[d.getMonth()]; + }, + c: d3_time_format(locale_dateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return locale_periods[+(d.getHours() >= 12)]; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(locale_date), + X: d3_time_format(locale_time), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; + } + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + } + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + } + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); + } + return d3_time_format; } -} - -function swap(i, j, data) { - i *= 2 - j *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = x - data[j+1] = y -} - -function move(i, j, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[i+1] = data[j+1] -} - -function rotate(i, j, k, data) { - i *= 2 - j *= 2 - k *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = data[k] - data[j+1] = data[k+1] - data[k] = x - data[k+1] = y -} - -function shufflePivot(i, j, px, py, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[j] = px - data[i+1] = data[j+1] - data[j+1] = py -} - -function compare(i, j, data) { - i *= 2 - j *= 2 - var x = data[i], - y = data[j] - if(x < y) { - return false - } else if(x === y) { - return data[i+1] > data[j+1] + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } - return true -} - -function comparePivot(i, y, b, data) { - i *= 2 - var x = data[i] - if(x < y) { - return true - } else if(x === y) { - return data[i+1] < b + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); } - return false -} - -function quickSort(left, right, data) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, - tmp = 0 - if(compare(el1, el2, data)) { - tmp = el1 - el1 = el2 - el2 = tmp + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; } - if(compare(el1, el3, data)) { - tmp = el1 - el1 = el3 - el3 = tmp + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; } - if(compare(el1, el4, data)) { - tmp = el1 - el1 = el4 - el4 = tmp + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; } - if(compare(el3, el4, data)) { - tmp = el3 - el3 = el4 - el4 = tmp + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; } - if(compare(el2, el5, data)) { - tmp = el2 - el2 = el5 - el5 = tmp + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, + i + 5) : -1; } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; } - - var pivot1X = data[2*el2] - var pivot1Y = data[2*el2+1] - var pivot2X = data[2*el4] - var pivot2Y = data[2*el4+1] - - var ptr0 = 2 * el1; - var ptr2 = 2 * el3; - var ptr4 = 2 * el5; - var ptr5 = 2 * index1; - var ptr6 = 2 * index3; - var ptr7 = 2 * index5; - for (var i1 = 0; i1 < 2; ++i1) { - var x = data[ptr0+i1]; - var y = data[ptr2+i1]; - var z = data[ptr4+i1]; - data[ptr5+i1] = x; - data[ptr6+i1] = y; - data[ptr7+i1] = z; + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; } - - move(index2, left, data) - move(index4, right, data) - for (var k = less; k <= great; ++k) { - if (comparePivot(k, pivot1X, pivot1Y, data)) { - if (k !== less) { - swap(k, less, data) - } - ++less; - } else { - if (!comparePivot(k, pivot2X, pivot2Y, data)) { - while (true) { - if (!comparePivot(great, pivot2X, pivot2Y, data)) { - if (--great < k) { - break; - } - continue; - } else { - if (comparePivot(great, pivot1X, pivot1Y, data)) { - rotate(k, less, great, data) - ++less; - --great; - } else { - swap(k, great, data) - --great; - } - break; - } - } - } - } - } - shufflePivot(left, less-1, pivot1X, pivot1Y, data) - shufflePivot(right, great+1, pivot2X, pivot2Y, data) - if (less - 2 - left <= INSERT_SORT_CUTOFF) { - insertionSort(left, less - 2, data); - } else { - quickSort(left, less - 2, data); + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; } - if (right - (great + 2) <= INSERT_SORT_CUTOFF) { - insertionSort(great + 2, right, data); - } else { - quickSort(great + 2, right, data); + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; } - if (great - less <= INSERT_SORT_CUTOFF) { - insertionSort(less, great, data); - } else { - quickSort(less, great, data); + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; } -} -},{}],89:[function(require,module,exports){ -'use strict' - -module.exports = { - init: sqInit, - sweepBipartite: sweepBipartite, - sweepComplete: sweepComplete, - scanBipartite: scanBipartite, - scanComplete: scanComplete -} - -var pool = require('typedarray-pool') -var bits = require('bit-twiddle') -var isort = require('./sort') - -//Flag for blue -var BLUE_FLAG = (1<<28) - -//1D sweep event queue stuff (use pool to save space) -var INIT_CAPACITY = 1024 -var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) - -//Reserves memory for the 1D sweep data structures -function sqInit(count) { - var rcount = bits.nextPow2(count) - if(RED_SWEEP_QUEUE.length < rcount) { - pool.free(RED_SWEEP_QUEUE) - RED_SWEEP_QUEUE = pool.mallocInt32(rcount) + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; } - if(RED_SWEEP_INDEX.length < rcount) { - pool.free(RED_SWEEP_INDEX) - RED_SWEEP_INDEX = pool.mallocInt32(rcount) + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; } - if(BLUE_SWEEP_QUEUE.length < rcount) { - pool.free(BLUE_SWEEP_QUEUE) - BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); } - if(BLUE_SWEEP_INDEX.length < rcount) { - pool.free(BLUE_SWEEP_INDEX) - BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.slice(i, i + 1)); + return n ? i + n[0].length : -1; } - if(COMMON_SWEEP_QUEUE.length < rcount) { - pool.free(COMMON_SWEEP_QUEUE) - COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) + function d3_time_formatMulti(formats) { + var n = formats.length, i = -1; + while (++i < n) formats[i][0] = this(formats[i][0]); + return function(date) { + var i = 0, f = formats[i]; + while (!f[1](date)) f = formats[++i]; + return f[0](date); + }; } - if(COMMON_SWEEP_INDEX.length < rcount) { - pool.free(COMMON_SWEEP_INDEX) - COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) + d3.locale = function(locale) { + return { + numberFormat: d3_locale_numberFormat(locale), + timeFormat: d3_locale_timeFormat(locale) + }; + }; + var d3_locale_enUS = d3.locale({ + decimal: ".", + thousands: ",", + grouping: [ 3 ], + currency: [ "$", "" ], + dateTime: "%a %b %e %X %Y", + date: "%m/%d/%Y", + time: "%H:%M:%S", + periods: [ "AM", "PM" ], + days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], + shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], + months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], + shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] + }); + d3.format = d3_locale_enUS.numberFormat; + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; + } + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); } - var eventLength = 8 * rcount - if(SWEEP_EVENTS.length < eventLength) { - pool.free(SWEEP_EVENTS) - SWEEP_EVENTS = pool.mallocDouble(eventLength) + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); + } + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); + } } -} - -//Remove an item from the active queue in O(1) -function sqPop(queue, index, count, item) { - var idx = index[item] - var top = queue[count-1] - queue[idx] = top - index[top] = idx -} - -//Insert an item into the active queue in O(1) -function sqPush(queue, index, count, item) { - queue[count] = item - index[item] = count -} - -//Recursion base case: use 1D sweep algorithm -function sweepBipartite( - d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - //store events as pairs [coordinate, idx] - // - // red create: -(idx+1) - // red destroy: idx - // blue create: -(idx+BLUE_FLAG) - // blue destroy: idx+BLUE_FLAG - // - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - for(var i=0; i= BLUE_FLAG) { - //blue destroy event - e = (e-BLUE_FLAG)|0 - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) - } else if(e >= 0) { - //red destroy event - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) - } else if(e <= -BLUE_FLAG) { - //blue create event - e = (-e-BLUE_FLAG)|0 - for(var j=0; j= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; } -} - -//Complete sweep -function sweepComplete(d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - var commonActive = 0 - for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { - color = 2 - i += 1 + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; + } + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; } - - if(e < 0) { - //Create event - var id = -(e>>1) - 1 - - //Intersect with common - for(var j=0; j 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; + } else { + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; } - } - - if(color !== 0) { - //Intersect with red - for(var j=0; j angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } - } - } - - if(color !== 1) { - //Intersect with blue - for(var j=0; j= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } } } + } else { + point(λ, φ); } - - if(color === 0) { - //Red - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id) - } else if(color === 1) { - //Blue - sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id) - } else if(color === 2) { - //Both - sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id) - } - } else { - //Destroy event - var id = (e>>1) - 1 - if(color === 0) { - //Red - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) - } else if(color === 1) { - //Blue - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) - } else if(color === 2) { - //Both - sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) + p0 = p, λ_ = λ; + } + function lineStart() { + bound.point = linePoint; + } + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; + } + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); + } + function ringStart() { + d3_geo_area.lineStart(); + } + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; + } + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + } + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } -} - -//Sweep and prune/scanline algorithm: -// Scan along axis, detect intersections -// Brute force all boxes along axis -function scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d - - var redShift = 1 - var blueShift = 1 - if(flip) { - blueShift = BLUE_FLAG - } else { - redShift = BLUE_FLAG + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; } - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - isRed = !flip - idx -= BLUE_FLAG - } else { - isRed = !!flip - idx -= 1 + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; + } + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; } - if(isRed) { - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) - } else { - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] - -red_loop: - for(var j=0; j= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); } + current = current.p; } - } - } else { - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift) + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); } } -} - -function scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d - - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG - } else { - idx -= 1 - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] - -red_loop: - for(var j=0; j=0; --j) { - if(RED_SWEEP_QUEUE[j] === idx) { - for(var k=j+1; k 0) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); } - break + return; } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); } - --redActive - } + return clip; + }; } -} -},{"./sort":88,"bit-twiddle":50,"typedarray-pool":278}],90:[function(require,module,exports){ -(function (Buffer){ -var hasTypedArrays = false -if(typeof Float64Array !== "undefined") { - var DOUBLE_VIEW = new Float64Array(1) - , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) - DOUBLE_VIEW[0] = 1.0 - hasTypedArrays = true - if(UINT_VIEW[1] === 0x3ff00000) { - //Use little endian - module.exports = function doubleBitsLE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[0], UINT_VIEW[1] ] - } - function toDoubleLE(lo, hi) { - UINT_VIEW[0] = lo - UINT_VIEW[1] = hi - return DOUBLE_VIEW[0] - } - module.exports.pack = toDoubleLE - function lowUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - module.exports.lo = lowUintLE - function highUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - module.exports.hi = highUintLE - } else if(UINT_VIEW[0] === 0x3ff00000) { - //Use big endian - module.exports = function doubleBitsBE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[1], UINT_VIEW[0] ] - } - function toDoubleBE(lo, hi) { - UINT_VIEW[1] = lo - UINT_VIEW[0] = hi - return DOUBLE_VIEW[0] - } - module.exports.pack = toDoubleBE - function lowUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - module.exports.lo = lowUintBE - function highUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - module.exports.hi = highUintBE - } else { - hasTypedArrays = false - } -} -if(!hasTypedArrays) { - var buffer = new Buffer(8) - module.exports = function doubleBits(n) { - buffer.writeDoubleLE(n, 0, true) - return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] - } - function toDouble(lo, hi) { - buffer.writeUInt32LE(lo, 0, true) - buffer.writeUInt32LE(hi, 4, true) - return buffer.readDoubleLE(0, true) - } - module.exports.pack = toDouble - function lowUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(0, true) + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; } - module.exports.lo = lowUint - function highUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(4, true) + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; } - module.exports.hi = highUint -} - -module.exports.sign = function(n) { - return module.exports.hi(n) >>> 31 -} - -module.exports.exponent = function(n) { - var b = module.exports.hi(n) - return ((b<<1) >>> 21) - 1023 -} - -module.exports.fraction = function(n) { - var lo = module.exports.lo(n) - var hi = module.exports.hi(n) - var b = hi & ((1<<20) - 1) - if(hi & 0x7ff00000) { - b += (1<<20) + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } - return [lo, b] -} - -module.exports.denormalized = function(n) { - var hi = module.exports.hi(n) - return !(hi & 0x7ff00000) -} -}).call(this,require("buffer").Buffer) -},{"buffer":51}],91:[function(require,module,exports){ -"use strict" - -var doubleBits = require("double-bits") - -var SMALLEST_DENORM = Math.pow(2, -1074) -var UINT_MAX = (-1)>>>0 - -module.exports = nextafter - -function nextafter(x, y) { - if(isNaN(x) || isNaN(y)) { - return NaN + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); + if (abs(dλ - π) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= π) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; + } + }; } - if(x === y) { - return x + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; } - if(x === 0) { - if(y < 0) { - return -SMALLEST_DENORM + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfπ; + listener.point(-π, φ); + listener.point(0, φ); + listener.point(π, φ); + listener.point(π, 0); + listener.point(π, -φ); + listener.point(0, -φ); + listener.point(-π, -φ); + listener.point(-π, 0); + listener.point(-π, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); } else { - return SMALLEST_DENORM + listener.point(to[0], to[1]); } } - var hi = doubleBits.hi(x) - var lo = doubleBits.lo(x) - if((y > x) === (x > 0)) { - if(lo === UINT_MAX) { - hi += 1 - lo = 0 - } else { - lo += 1 - } - } else { - if(lo === 0) { - lo = UINT_MAX - hi -= 1 - } else { - lo -= 1 + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); + polarAngle += antimeridian ? dλ + sdλ * τ : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; + } } + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1; } - return doubleBits.pack(lo, hi) -} -},{"double-bits":90}],92:[function(require,module,exports){ -'use strict' - -var bnadd = require('big-rat/add') - -module.exports = add - -function add(a, b) { - var n = a.length - var r = new Array(n) - for(var i=0; i 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; + } + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; + } + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } + } + function code(λ, φ) { + var r = smallRadius ? radius : π - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; } } - - return true -} - -function segmentsIntersect(a0, a1, b0, b1) { - var x0 = orient(a0, b0, b1) - var y0 = orient(a1, b0, b1) - if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { - return false - } - - var x1 = orient(b0, a0, a1) - var y1 = orient(b1, a0, a1) - if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { - return false - } - - //Check for degenerate collinear case - if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { - return checkCollinear(a0, a1, b0, b1) - } - - return true -} -},{"robust-orientation":259}],97:[function(require,module,exports){ -"use strict"; "use restrict"; - -module.exports = UnionFind; - -function UnionFind(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; i 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; } - return x; -} - -proto.link = function(x, y) { - var xr = this.find(x) - , yr = this.find(y); - if(xr === yr) { - return; - } - var ranks = this.ranks - , roots = this.roots - , xd = ranks[xr] - , yd = ranks[yr]; - if(xd < yd) { - roots[xr] = yr; - } else if(yd < xd) { - roots[yr] = xr; - } else { - roots[yr] = xr; - ++ranks[xr]; - } -} -},{}],98:[function(require,module,exports){ -(function (Buffer){ -var clone = (function() { -'use strict'; - -/** - * Clones (copies) an Object using deep copying. - * - * This function supports circular references by default, but if you are certain - * there are no circular references in your object, you can save some CPU time - * by calling clone(obj, false). - * - * Caution: if `circular` is false and `parent` contains circular references, - * your program may enter an infinite loop and crash. - * - * @param `parent` - the object to be cloned - * @param `circular` - set to true if the object to be cloned may contain - * circular references. (optional - true by default) - * @param `depth` - set to a number if the object is only to be cloned to - * a particular depth. (optional - defaults to Infinity) - * @param `prototype` - sets the prototype to be used when cloning an object. - * (optional - defaults to parent prototype). -*/ -function clone(parent, circular, depth, prototype) { - var filter; - if (typeof circular === 'object') { - depth = circular.depth; - prototype = circular.prototype; - filter = circular.filter; - circular = circular.circular - } - // maintain two arrays for circular references, where corresponding parents - // and children have the same index - var allParents = []; - var allChildren = []; - - var useBuffer = typeof Buffer != 'undefined'; - - if (typeof circular == 'undefined') - circular = true; - - if (typeof depth == 'undefined') - depth = Infinity; - - // recurse this function so we don't reset allParents and allChildren - function _clone(parent, depth) { - // cloning null always returns null - if (parent === null) - return null; - - if (depth == 0) - return parent; - - var child; - var proto; - if (typeof parent != 'object') { - return parent; - } - - if (clone.__isArray(parent)) { - child = []; - } else if (clone.__isRegExp(parent)) { - child = new RegExp(parent.source, __getRegExpFlags(parent)); - if (parent.lastIndex) child.lastIndex = parent.lastIndex; - } else if (clone.__isDate(parent)) { - child = new Date(parent.getTime()); - } else if (useBuffer && Buffer.isBuffer(parent)) { - child = new Buffer(parent.length); - parent.copy(child); - return child; - } else { - if (typeof prototype == 'undefined') { - proto = Object.getPrototypeOf(parent); - child = Object.create(proto); + var d3_geo_clipExtentMAX = 1e9; + d3.geo.clipExtent = function() { + var x0, y0, x1, y1, stream, clip, clipExtent = { + stream: function(output) { + if (stream) stream.valid = false; + stream = clip(output); + stream.valid = true; + return stream; + }, + extent: function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); + if (stream) stream.valid = false, stream = null; + return clipExtent; } - else { - child = Object.create(prototype); - proto = prototype; + }; + return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + }; + function d3_geo_clipExtent(x0, y0, x1, y1) { + return function(listener) { + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + listener = bufferListener; + segments = []; + polygon = []; + clean = true; + }, + polygonEnd: function() { + listener = listener_; + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { + listener.polygonStart(); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } + listener.polygonEnd(); + } + segments = polygon = ring = null; + } + }; + function insidePolygon(p) { + var wn = 0, n = polygon.length, y = p[1]; + for (var i = 0; i < n; ++i) { + for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { + b = v[j]; + if (a[1] <= y) { + if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; } - } - - if (circular) { - var index = allParents.indexOf(parent); - - if (index != -1) { - return allChildren[index]; + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); + } else { + listener.point(to[0], to[1]); + } } - allParents.push(parent); - allChildren.push(child); - } - - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; } - - if (attrs && attrs.set == null) { - continue; + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); } - child[i] = _clone(parent[i], depth - 1); - } - - return child; - } - - return _clone(parent, depth); -} - -/** - * Simple flat clone using prototype, accepts only objects, usefull for property - * override on FLAT configuration object (no nested props). - * - * USE WITH CAUTION! This may not behave as you wish if you do not know how this - * works. - */ -clone.clonePrototype = function clonePrototype(parent) { - if (parent === null) - return null; - - var c = function () {}; - c.prototype = parent; - return new c(); -}; - -// private utility functions - -function __objToStr(o) { - return Object.prototype.toString.call(o); -}; -clone.__objToStr = __objToStr; - -function __isDate(o) { - return typeof o === 'object' && __objToStr(o) === '[object Date]'; -}; -clone.__isDate = __isDate; - -function __isArray(o) { - return typeof o === 'object' && __objToStr(o) === '[object Array]'; -}; -clone.__isArray = __isArray; - -function __isRegExp(o) { - return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; -}; -clone.__isRegExp = __isRegExp; - -function __getRegExpFlags(re) { - var flags = ''; - if (re.global) flags += 'g'; - if (re.ignoreCase) flags += 'i'; - if (re.multiline) flags += 'm'; - return flags; -}; -clone.__getRegExpFlags = __getRegExpFlags; - -return clone; -})(); - -if (typeof module === 'object' && module.exports) { - module.exports = clone; -} - -}).call(this,require("buffer").Buffer) -},{"buffer":51}],99:[function(require,module,exports){ -module.exports={"jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}],"hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}],"hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}],"cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}],"spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}],"summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}],"autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}],"winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}],"bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}],"copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}],"greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}],"yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}],"greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}],"yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}],"bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}],"rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}],"picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}],"rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}],"portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}],"blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}],"earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}],"electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}]}; - -},{}],100:[function(require,module,exports){ -/* - * Ben Postlethwaite - * January 2013 - * License MIT - */ -'use strict'; - -var at = require('arraytools'); -var clone = require('clone'); -var colorScale = require('./colorScales'); - -module.exports = function (spec) { - - /* - * Default Options - */ - var indicies, rgba, fromrgba, torgba, - nsteps, cmap, colormap, format, - nshades, colors, alpha, index, i, - r = [], - g = [], - b = [], - a = []; - - if ( !at.isPlainObject(spec) ) spec = {}; - - nshades = spec.nshades || 72; - format = spec.format || 'hex'; - - colormap = spec.colormap; - if (!colormap) colormap = 'jet'; - - if (typeof colormap === 'string') { - colormap = colormap.toLowerCase(); - - if (!colorScale[colormap]) { - throw Error(colormap + ' not a supported colorscale'); + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); } - - cmap = clone(colorScale[colormap]); - - } else if (Array.isArray(colormap)) { - cmap = clone(colormap); - - } else { - throw Error('unsupported colormap option', colormap); - } - - if (cmap.length > nshades) { - throw new Error( - colormap+' map requires nshades to be at least size '+cmap.length - ); - } - - if (!Array.isArray(spec.alpha)) { - - if (typeof spec.alpha === 'number') { - alpha = [spec.alpha, spec.alpha]; - + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } } else { - alpha = [1, 1]; + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } } - - } else if (spec.alpha.length !== 2) { - alpha = [1, 1]; - - } else { - alpha = clone(spec.alpha); + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; } - - /* - * map index points from 0->1 to 0 -> n-1 - */ - indicies = cmap.map(function(c) { - return Math.round(c.index * nshades); - }); - - /* - * Add alpha channel to the map - */ - if (alpha[0] < 0) alpha[0] = 0; - if (alpha[1] < 0) alpha[0] = 0; - if (alpha[0] > 1) alpha[0] = 1; - if (alpha[1] > 1) alpha[0] = 1; - - for (i = 0; i < indicies.length; ++i) { - index = cmap[i].index; - rgba = cmap[i].rgb; - - // if user supplies their own map use it - if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue; - rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index; + function compare(a, b) { + return comparePoints(a.x, b.x); } - - /* - * map increasing linear values between indicies to - * linear steps in colorvalues - */ - for (i = 0; i < indicies.length-1; ++i) { - nsteps = indicies[i+1] - indicies[i]; - fromrgba = cmap[i].rgb; - torgba = cmap[i+1].rgb; - r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) ); - g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) ); - b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) ); - a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) ); + function comparePoints(a, b) { + var ca = corner(a, 1), cb = corner(b, 1); + return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; } - - r = r.map( Math.round ); - g = g.map( Math.round ); - b = b.map( Math.round ); - - colors = at.zip(r, g, b, a); - - if (format === 'hex') colors = colors.map( rgb2hex ); - if (format === 'rgbaString') colors = colors.map( rgbaStr ); - - return colors; -}; - - -function rgb2hex (rgba) { - var dig, hex = '#'; - for (var i = 0; i < 3; ++i) { - dig = rgba[i]; - dig = dig.toString(16); - hex += ('00' + dig).substr( dig.length ); + } + function d3_geo_conic(projectAt) { + var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); + p.parallels = function(_) { + if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; + return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); + }; + return p; + } + function d3_geo_conicEqualArea(φ0, φ1) { + var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; + function forward(λ, φ) { + var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; + return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; } - return hex; -} - -function rgbaStr (rgba) { - return 'rgba(' + rgba.join(',') + ')'; -} - -},{"./colorScales":99,"arraytools":49,"clone":98}],101:[function(require,module,exports){ -module.exports = compareCells - -var min = Math.min - -function compareInt(a, b) { - return a - b -} - -function compareCells(a, b) { - var n = a.length - , t = a.length - b.length - if(t) { - return t + forward.invert = function(x, y) { + var ρ0_y = ρ0 - y; + return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; + }; + return forward; } - switch(n) { - case 0: - return 0 - case 1: - return a[0] - b[0] - case 2: - return (a[0]+a[1]-b[0]-b[1]) || - min(a[0],a[1]) - min(b[0],b[1]) - case 3: - var l1 = a[0]+a[1] - , m1 = b[0]+b[1] - t = l1+a[2] - (m1+b[2]) - if(t) { - return t + (d3.geo.conicEqualArea = function() { + return d3_geo_conic(d3_geo_conicEqualArea); + }).raw = d3_geo_conicEqualArea; + d3.geo.albers = function() { + return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); + }; + d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); + var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); + var point, pointStream = { + point: function(x, y) { + point = [ x, y ]; } - var l0 = min(a[0], a[1]) - , m0 = min(b[0], b[1]) - return min(l0, a[2]) - min(m0, b[2]) || - min(l0+a[2], l1) - min(m0+b[2], m1) - case 4: - var aw=a[0], ax=a[1], ay=a[2], az=a[3] - , bw=b[0], bx=b[1], by=b[2], bz=b[3] - return (aw+ax+ay+az)-(bw+bx+by+bz) || - min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) || - min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) - - min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) || - min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) - - min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz) - default: - var as = a.slice().sort(compareInt) - var bs = b.slice().sort(compareInt) - for(var i=0; i= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); } - } - return 0 - } -} - -},{}],102:[function(require,module,exports){ -"use strict" - -var convexHull1d = require('./lib/ch1d') -var convexHull2d = require('./lib/ch2d') -var convexHullnd = require('./lib/chnd') - -module.exports = convexHull - -function convexHull(points) { - var n = points.length - if(n === 0) { - return [] - } else if(n === 1) { - return [[0]] - } - var d = points[0].length - if(d === 0) { - return [] - } else if(d === 1) { - return convexHull1d(points) - } else if(d === 2) { - return convexHull2d(points) - } - return convexHullnd(points, d) -} -},{"./lib/ch1d":103,"./lib/ch2d":104,"./lib/chnd":105}],103:[function(require,module,exports){ -"use strict" - -module.exports = convexHull1d - -function convexHull1d(points) { - var lo = 0 - var hi = 0 - for(var i=1; i points[hi][0]) { - hi = i + }; + function d3_geo_pathAreaRingStart() { + var x00, y00, x0, y0; + d3_geo_pathArea.point = function(x, y) { + d3_geo_pathArea.point = nextPoint; + x00 = x0 = x, y00 = y0 = y; + }; + function nextPoint(x, y) { + d3_geo_pathAreaPolygon += y0 * x - x0 * y; + x0 = x, y0 = y; } + d3_geo_pathArea.lineEnd = function() { + nextPoint(x00, y00); + }; } - if(lo < hi) { - return [[lo], [hi]] - } else if(lo > hi) { - return [[hi], [lo]] - } else { - return [[lo]] - } -} -},{}],104:[function(require,module,exports){ -'use strict' - -module.exports = convexHull2D - -var monotoneHull = require('monotone-convex-hull-2d') - -function convexHull2D(points) { - var hull = monotoneHull(points) - var h = hull.length - if(h <= 2) { - return [] - } - var edges = new Array(h) - var a = hull[h-1] - for(var i=0; i d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; } - return npoints -} - -function invPermute(cells, front) { - var nc = cells.length - var nf = front.length - for(var i=0; i= front[k]) { - x += 1 - } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; } - c[j] = x } + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); } - } - return cells -} - -function convexHullnD(points, d) { - try { - return ich(points, true) - } catch(e) { - //If point set is degenerate, try to find a basis and rerun it - var ah = aff(points) - if(ah.length <= d) { - //No basis, no try - return [] + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; } - var npoints = permute(points, ah) - var nhull = ich(npoints, true) - return invPermute(nhull, ah) - } -} -},{"affine-hull":106,"incremental-convex-hull":235}],106:[function(require,module,exports){ -'use strict' - -module.exports = affineHull - -var orient = require('robust-orientation') - -function linearlyIndependent(points, d) { - var nhull = new Array(d+1) - for(var i=0; i 1 && orient( - points[lower[m-2]], - points[lower[m-1]], - p) <= 0) { - m -= 1 - lower.pop() + function lineEnd() { + stream.point = point; } - lower.push(idx) - - //Insert into upper list - m = upper.length - while(m > 1 && orient( - points[upper[m-2]], - points[upper[m-1]], - p) >= 0) { - m -= 1 - upper.pop() + function lineEndPolygon() { + context.closePath(); } - upper.push(idx) - } - - //Merge lists together - var result = new Array(upper.length + lower.length - 2) - var ptr = 0 - for(var i=0, nl=lower.length; i0; --j) { - result[ptr++] = upper[j] + return stream; } - - //Return result - return result -} -},{"robust-orientation":259}],108:[function(require,module,exports){ -module.exports = { - AFG: "afghan", - ALA: "\\b\\wland", - ALB: "albania", - DZA: "algeria", - ASM: "^(?=.*americ).*samoa", - AND: "andorra", - AGO: "angola", - AIA: "anguill?a", - ATA: "antarctica", - ATG: "antigua", - ARG: "argentin", - ARM: "armenia", - ABW: "^(?!.*bonaire).*\\baruba", - AUS: "australia", - AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp", - AZE: "azerbaijan", - BHS: "bahamas", - BHR: "bahrain", - BGD: "bangladesh|^(?=.*east).*paki?stan", - BRB: "barbados", - BLR: "belarus|byelo", - BEL: "^(?!.*luxem).*belgium", - BLZ: "belize|^(?=.*british).*honduras", - BEN: "benin|dahome", - BMU: "bermuda", - BTN: "bhutan", - BOL: "bolivia", - BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands", - BIH: "herzegovina|bosnia", - BWA: "botswana|bechuana", - BVT: "bouvet", - BRA: "brazil", - IOT: "british.?indian.?ocean", - BRN: "brunei", - BGR: "bulgaria", - BFA: "burkina|\\bfaso|upper.?volta", - BDI: "burundi", - KHM: "cambodia|kampuchea|khmer", - CMR: "cameroon", - CAN: "canada", - CPV: "verde", - CYM: "cayman", - CAF: "\\bcentral.african.republic", - TCD: "\\bchad", - CHL: "\\bchile", - CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china", - CXR: "christmas", - CCK: "\\bcocos|keeling", - COL: "colombia", - COM: "comoro", - COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc", - COG: "^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo", - COK: "\\bcook", - CRI: "costa.?rica", - CIV: "ivoire|ivory", - HRV: "croatia", - CUB: "\\bcuba", - CUW: "^(?!.*bonaire).*\\bcura(c|ç)ao", - CYP: "cyprus", - CZE: "^(?=.*rep).*czech|czechia|bohemia", - CSK: "czechoslovakia", - DNK: "denmark", - DJI: "djibouti", - DMA: "dominica(?!n)", - DOM: "dominican.rep", - ECU: "ecuador", - EGY: "egypt", - SLV: "el.?salvador", - GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea", - ERI: "eritrea", - EST: "estonia", - ETH: "ethiopia|abyssinia", - FLK: "falkland|malvinas", - FRO: "faroe|faeroe", - FJI: "fiji", - FIN: "finland", - FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul", - GUF: "^(?=.*french).*guiana", - PYF: "french.?polynesia|tahiti", - ATF: "french.?southern", - GAB: "gabon", - GMB: "gambia", - GEO: "^(?!.*south).*georgia", - DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany", - DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german", - GHA: "ghana|gold.?coast", - GIB: "gibraltar", - GRC: "greece|hellenic|hellas", - GRL: "greenland", - GRD: "grenada", - GLP: "guadeloupe", - GUM: "\\bguam", - GTM: "guatemala", - GGY: "guernsey", - GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea", - GNB: "bissau|^(?=.*portu).*guinea", - GUY: "guyana|british.?guiana", - HTI: "haiti", - HMD: "heard.*mcdonald", - VAT: "holy.?see|vatican|papal.?st", - HND: "^(?!.*brit).*honduras", - HKG: "hong.?kong", - HUN: "^(?!.*austr).*hungary", - ISL: "iceland", - IND: "india(?!.*ocea)", - IDN: "indonesia", - IRN: "\\biran|persia", - IRQ: "\\biraq|mesopotamia", - IRL: "ireland", - IMN: "^(?=.*isle).*\\bman", - ISR: "israel", - ITA: "italy", - JAM: "jamaica", - JPN: "japan", - JEY: "jersey", - JOR: "jordan", - KAZ: "kazak", - KEN: "kenya|british.?east.?africa|east.?africa.?prot", - KIR: "kiribati", - PRK: "^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk", - KOR: "^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea", - KWT: "kuwait", - KGZ: "kyrgyz|kirghiz", - LAO: "\\blaos?\\b", - LVA: "latvia", - LBN: "lebanon", - LSO: "lesotho|basuto", - LBR: "liberia", - LBY: "libya", - LIE: "liechtenstein", - LTU: "lithuania", - LUX: "^(?!.*belg).*luxem", - MAC: "maca(o|u)", - MKD: "macedonia|fyrom", - MDG: "madagascar|malagasy", - MWI: "malawi|nyasa", - MYS: "malaysia", - MDV: "maldive", - MLI: "\\bmali\\b", - MLT: "\\bmalta", - MHL: "marshall", - MTQ: "martinique", - MRT: "mauritania", - MUS: "mauritius", - MYT: "\\bmayotte", - MEX: "\\bmexic", - FSM: "micronesia", - MDA: "moldov|b(a|e)ssarabia", - MCO: "monaco", - MNG: "mongolia", - MNE: "^(?!.*serbia).*montenegro", - MSR: "montserrat", - MAR: "morocco|\\bmaroc", - MOZ: "mozambique", - MMR: "myanmar|burma", - NAM: "namibia", - NRU: "nauru", - NPL: "nepal", - NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands", - ANT: "^(?=.*\\bant).*(nether|dutch)", - NCL: "new.?caledonia", - NZL: "new.?zealand", - NIC: "nicaragua", - NER: "\\bniger(?!ia)", - NGA: "nigeria", - NIU: "niue", - NFK: "norfolk", - MNP: "mariana", - NOR: "norway", - OMN: "\\boman|trucial", - PAK: "^(?!.*east).*paki?stan", - PLW: "palau", - PSE: "palestin|\\bgaza|west.?bank", - PAN: "panama", - PNG: "papua|new.?guinea", - PRY: "paraguay", - PER: "peru", - PHL: "philippines", - PCN: "pitcairn", - POL: "poland", - PRT: "portugal", - PRI: "puerto.?rico", - QAT: "qatar", - REU: "r(e|é)union", - ROU: "r(o|u|ou)mania", - RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics", - RWA: "rwanda", - BLM: "barth(e|é)lemy", - SHN: "helena", - KNA: "kitts|\\bnevis", - LCA: "\\blucia", - MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)", - SPM: "miquelon", - VCT: "vincent", - WSM: "^(?!.*amer).*samoa", - SMR: "san.?marino", - STP: "\\bs(a|ã)o.?tom(e|é)", - SAU: "\\bsa\\w*.?arabia", - SEN: "senegal", - SRB: "^(?!.*monte).*serbia", - SYC: "seychell", - SLE: "sierra", - SGP: "singapore", - SXM: "^(?!.*martin)(?!.*saba).*maarten", - SVK: "^(?!.*cze).*slovak", - SVN: "slovenia", - SLB: "solomon", - SOM: "somali", - ZAF: "\\bs\\w*.?africa", - SGS: "south.?georgia|sandwich", - SSD: "\\bs\\w*.?sudan", - ESP: "spain", - LKA: "sri.?lanka|ceylon", - SDN: "^(?!.*\\bs(?!u)).*sudan", - SUR: "surinam|dutch.?guiana", - SJM: "svalbard", - SWZ: "swaziland", - SWE: "sweden", - CHE: "switz|swiss", - SYR: "syria", - TWN: "taiwan|taipei|formosa", - TJK: "tajik", - TZA: "tanzania", - THA: "thailand|\\bsiam", - TLS: "^(?=.*leste).*timor|^(?=.*east).*timor", - TGO: "togo", - TKL: "tokelau", - TON: "tonga", - TTO: "trinidad|tobago", - TUN: "tunisia", - TUR: "turkey", - TKM: "turkmen", - TCA: "turks", - TUV: "tuvalu", - UGA: "uganda", - UKR: "ukrain", - ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em", - GBR: "united.?kingdom|britain|^u\\.?k\\.?$", - USA: "united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)", - UMI: "minor.?outlying.?is", - URY: "uruguay", - UZB: "uzbek", - VUT: "vanuatu|new.?hebrides", - VEN: "venezuela", - VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam", - VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin", - VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin", - WLF: "futuna|wallis", - ESH: "western.sahara", - YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen", - YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen", - YUG: "yugoslavia", - ZMB: "zambia|northern.?rhodesia", - EAZ: "zanzibar", - ZWE: "zimbabwe|^(?!.*northern).*rhodesia" -}; - -},{}],109:[function(require,module,exports){ -"use strict" - -var createThunk = require("./lib/thunk.js") - -function Procedure() { - this.argTypes = [] - this.shimArgs = [] - this.arrayArgs = [] - this.arrayBlockIndices = [] - this.scalarArgs = [] - this.offsetArgs = [] - this.offsetArgIndex = [] - this.indexArgs = [] - this.shapeArgs = [] - this.funcName = "" - this.pre = null - this.body = null - this.post = null - this.debug = false -} - -function compileCwise(user_args) { - //Create procedure - var proc = new Procedure() - - //Parse blocks - proc.pre = user_args.pre - proc.body = user_args.body - proc.post = user_args.post - - //Parse arguments - var proc_args = user_args.args.slice(0) - proc.argTypes = proc_args - for(var i=0; i0) { - throw new Error("cwise: pre() block may not reference array args") - } - if(i < proc.post.args.length && proc.post.args[i].count>0) { - throw new Error("cwise: post() block may not reference array args") - } - } else if(arg_type === "scalar") { - proc.scalarArgs.push(i) - proc.shimArgs.push("scalar" + i) - } else if(arg_type === "index") { - proc.indexArgs.push(i) - if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { - throw new Error("cwise: pre() block may not reference array index") - } - if(i < proc.body.args.length && proc.body.args[i].lvalue) { - throw new Error("cwise: body() block may not write to array index") - } - if(i < proc.post.args.length && proc.post.args[i].count > 0) { - throw new Error("cwise: post() block may not reference array index") - } - } else if(arg_type === "shape") { - proc.shapeArgs.push(i) - if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { - throw new Error("cwise: pre() block may not write to array shape") - } - if(i < proc.body.args.length && proc.body.args[i].lvalue) { - throw new Error("cwise: body() block may not write to array shape") - } - if(i < proc.post.args.length && proc.post.args[i].lvalue) { - throw new Error("cwise: post() block may not write to array shape") - } - } else if(typeof arg_type === "object" && arg_type.offset) { - proc.argTypes[i] = "offset" - proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) - proc.offsetArgIndex.push(i) - } else { - throw new Error("cwise: Unknown argument type " + proc_args[i]) - } - } - - //Make sure at least one array argument was specified - if(proc.arrayArgs.length <= 0) { - throw new Error("cwise: No array arguments specified") - } - - //Make sure arguments are correct - if(proc.pre.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in pre() block") - } - if(proc.body.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in body() block") - } - if(proc.post.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in post() block") - } - - //Check debug flag - proc.debug = !!user_args.printCode || !!user_args.debug - - //Retrieve name - proc.funcName = user_args.funcName || "cwise" - - //Read in block size - proc.blockSize = user_args.blockSize || 64 - - return createThunk(proc) -} - -module.exports = compileCwise - -},{"./lib/thunk.js":111}],110:[function(require,module,exports){ -"use strict" - -var uniq = require("uniq") - -// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) -// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. -function innerFill(order, proc, body) { - var dimension = order.length - , nargs = proc.arrayArgs.length - , has_index = proc.indexArgs.length>0 - , code = [] - , vars = [] - , idx=0, pidx=0, i, j - for(i=0; i=0; --i) { // Start at largest stride and work your way inwards - idx = order[i] - code.push(["for(i",i,"=0;i",i," 0) { - code.push(["index[",pidx,"]-=s",pidx].join("")) - } - code.push(["++index[",idx,"]"].join("")) - } - code.push("}") - } - return code.join("\n") -} - -// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. -// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. -// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. -function outerFill(matched, order, proc, body) { - var dimension = order.length - , nargs = proc.arrayArgs.length - , blockSize = proc.blockSize - , has_index = proc.indexArgs.length > 0 - , code = [] - for(var i=0; i0;){"].join("")) // Iterate back to front - code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). - code.push(["s",order[i],"=j",i].join("")) - code.push(["j",i,"=0"].join("")) - code.push(["}else{s",order[i],"=",blockSize].join("")) - code.push(["j",i,"-=",blockSize,"}"].join("")) - if(has_index) { - code.push(["index[",order[i],"]=j",i].join("")) - } - } - for(var i=0; i 0) { - allEqual = allEqual && summary[i] === summary[i-1] - } - } - if(allEqual) { - return summary[0] - } - return summary.join("") -} - -//Generates a cwise operator -function generateCWiseOp(proc, typesig) { - - //Compute dimension - // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. - var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 - var orders = new Array(proc.arrayArgs.length) - var dtypes = new Array(proc.arrayArgs.length) - for(var i=0; i 0) { - vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) - } - if(proc.indexArgs.length > 0) { - // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. - var zeros = new Array(dimension) - for(var i=0; i 3) { - code.push(processBlock(proc.pre, proc, dtypes)) - } - - //Process body - var body = processBlock(proc.body, proc, dtypes) - var matched = countMatches(loopOrders) - if(matched < dimension) { - code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. - } else { - code.push(innerFill(loopOrders[0], proc, body)) - } - - //Inline epilog - if(proc.post.body.length > 3) { - code.push(processBlock(proc.post, proc, dtypes)) - } - - if(proc.debug) { - console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") - } - - var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") - var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) - return f() -} -module.exports = generateCWiseOp - -},{"uniq":279}],111:[function(require,module,exports){ -"use strict" - -// The function below is called when constructing a cwise function object, and does the following: -// A function object is constructed which accepts as argument a compilation function and returns another function. -// It is this other function that is eventually returned by createThunk, and this function is the one that actually -// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. -// The compilation passed to the first function object is used for compiling new functions. -// Once this function object is created, it is called with compile as argument, where the first argument of compile -// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). -// So createThunk roughly works like this: -// function createThunk(proc) { -// var thunk = function(compileBound) { -// var CACHED = {} -// return function(arrays and scalars) { -// if (dtype and order of arrays in CACHED) { -// var func = CACHED[dtype and order of arrays] -// } else { -// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) -// } -// return func(arrays and scalars) -// } -// } -// return thunk(compile.bind1(proc)) -// } - -var compile = require("./compile.js") - -function createThunk(proc) { - var code = ["'use strict'", "var CACHED={}"] - var vars = [] - var thunkName = proc.funcName + "_cwise_thunk" - - //Build thunk - code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) - var typesig = [] - var string_typesig = [] - var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). - Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] - var shapeLengthConditions = [], shapeConditions = [] - // Process array arguments - for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) - shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) - shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") - } - } - // Check for shape equality - if (proc.arrayArgs.length > 1) { - code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") - code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") - code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") - code.push("}") - } - // Process scalar arguments - for(var i=0; i b ? 1 : a >= b ? 0 : NaN; - } - d3.descending = function(a, b) { - return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; - }; - d3.min = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array[i]) != null && a > b) a = b; - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; - } - return a; - }; - d3.max = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array[i]) != null && b > a) a = b; - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; - } - return a; - }; - d3.extent = function(array, f) { - var i = -1, n = array.length, a, b, c; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = array[i]) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } - return [ a, c ]; - }; - function d3_number(x) { - return x === null ? NaN : +x; - } - function d3_numeric(x) { - return !isNaN(x); - } - d3.sum = function(array, f) { - var s = 0, n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = +array[i])) s += a; - } else { - while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; - } - return s; - }; - d3.mean = function(array, f) { - var s = 0, n = array.length, a, i = -1, j = n; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; - } - if (j) return s / j; - }; - d3.quantile = function(values, p) { - var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; - return e ? v + e * (values[h] - v) : v; - }; - d3.median = function(array, f) { - var numbers = [], n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); - } - if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); - }; - d3.variance = function(array, f) { - var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; - if (arguments.length === 1) { - while (++i < n) { - if (d3_numeric(a = d3_number(array[i]))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } else { - while (++i < n) { - if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } - if (j > 1) return s / (j - 1); - }; - d3.deviation = function() { - var v = d3.variance.apply(this, arguments); - return v ? Math.sqrt(v) : v; - }; - function d3_bisector(compare) { - return { - left: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; - } - return lo; - }, - right: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; - } - return lo; - } - }; - } - var d3_bisect = d3_bisector(d3_ascending); - d3.bisectLeft = d3_bisect.left; - d3.bisect = d3.bisectRight = d3_bisect.right; - d3.bisector = function(f) { - return d3_bisector(f.length === 1 ? function(d, x) { - return d3_ascending(f(d), x); - } : f); - }; - d3.shuffle = function(array, i0, i1) { - if ((m = arguments.length) < 3) { - i1 = array.length; - if (m < 2) i0 = 0; - } - var m = i1 - i0, t, i; - while (m) { - i = Math.random() * m-- | 0; - t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; - } - return array; - }; - d3.permute = function(array, indexes) { - var i = indexes.length, permutes = new Array(i); - while (i--) permutes[i] = array[indexes[i]]; - return permutes; - }; - d3.pairs = function(array) { - var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); - while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; - return pairs; - }; - d3.transpose = function(matrix) { - if (!(n = matrix.length)) return []; - for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { - for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { - row[j] = matrix[j][i]; - } - } - return transpose; - }; - function d3_transposeLength(d) { - return d.length; - } - d3.zip = function() { - return d3.transpose(arguments); - }; - d3.keys = function(map) { - var keys = []; - for (var key in map) keys.push(key); - return keys; - }; - d3.values = function(map) { - var values = []; - for (var key in map) values.push(map[key]); - return values; - }; - d3.entries = function(map) { - var entries = []; - for (var key in map) entries.push({ - key: key, - value: map[key] - }); - return entries; - }; - d3.merge = function(arrays) { - var n = arrays.length, m, i = -1, j = 0, merged, array; - while (++i < n) j += arrays[i].length; - merged = new Array(j); - while (--n >= 0) { - array = arrays[n]; - m = array.length; - while (--m >= 0) { - merged[--j] = array[m]; - } - } - return merged; - }; - var abs = Math.abs; - d3.range = function(start, stop, step) { - if (arguments.length < 3) { - step = 1; - if (arguments.length < 2) { - stop = start; - start = 0; - } - } - if ((stop - start) / step === Infinity) throw new Error("infinite range"); - var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; - start *= k, stop *= k, step *= k; - if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); - return range; - }; - function d3_range_integerScale(x) { - var k = 1; - while (x * k % 1) k *= 10; - return k; - } - function d3_class(ctor, properties) { - for (var key in properties) { - Object.defineProperty(ctor.prototype, key, { - value: properties[key], - enumerable: false - }); - } - } - d3.map = function(object, f) { - var map = new d3_Map(); - if (object instanceof d3_Map) { - object.forEach(function(key, value) { - map.set(key, value); - }); - } else if (Array.isArray(object)) { - var i = -1, n = object.length, o; - if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); - } else { - for (var key in object) map.set(key, object[key]); - } - return map; - }; - function d3_Map() { - this._ = Object.create(null); - } - var d3_map_proto = "__proto__", d3_map_zero = "\x00"; - d3_class(d3_Map, { - has: d3_map_has, - get: function(key) { - return this._[d3_map_escape(key)]; - }, - set: function(key, value) { - return this._[d3_map_escape(key)] = value; - }, - remove: d3_map_remove, - keys: d3_map_keys, - values: function() { - var values = []; - for (var key in this._) values.push(this._[key]); - return values; - }, - entries: function() { - var entries = []; - for (var key in this._) entries.push({ - key: d3_map_unescape(key), - value: this._[key] - }); - return entries; - }, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); - } - }); - function d3_map_escape(key) { - return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; - } - function d3_map_unescape(key) { - return (key += "")[0] === d3_map_zero ? key.slice(1) : key; - } - function d3_map_has(key) { - return d3_map_escape(key) in this._; - } - function d3_map_remove(key) { - return (key = d3_map_escape(key)) in this._ && delete this._[key]; - } - function d3_map_keys() { - var keys = []; - for (var key in this._) keys.push(d3_map_unescape(key)); - return keys; - } - function d3_map_size() { - var size = 0; - for (var key in this._) ++size; - return size; - } - function d3_map_empty() { - for (var key in this._) return false; - return true; - } - d3.nest = function() { - var nest = {}, keys = [], sortKeys = [], sortValues, rollup; - function map(mapType, array, depth) { - if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; - var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; - while (++i < n) { - if (values = valuesByKey.get(keyValue = key(object = array[i]))) { - values.push(object); - } else { - valuesByKey.set(keyValue, [ object ]); - } - } - if (mapType) { - object = mapType(); - setter = function(keyValue, values) { - object.set(keyValue, map(mapType, values, depth)); - }; - } else { - object = {}; - setter = function(keyValue, values) { - object[keyValue] = map(mapType, values, depth); - }; - } - valuesByKey.forEach(setter); - return object; - } - function entries(map, depth) { - if (depth >= keys.length) return map; - var array = [], sortKey = sortKeys[depth++]; - map.forEach(function(key, keyMap) { - array.push({ - key: key, - values: entries(keyMap, depth) - }); - }); - return sortKey ? array.sort(function(a, b) { - return sortKey(a.key, b.key); - }) : array; - } - nest.map = function(array, mapType) { - return map(mapType, array, 0); - }; - nest.entries = function(array) { - return entries(map(d3.map, array, 0), 0); - }; - nest.key = function(d) { - keys.push(d); - return nest; - }; - nest.sortKeys = function(order) { - sortKeys[keys.length - 1] = order; - return nest; - }; - nest.sortValues = function(order) { - sortValues = order; - return nest; - }; - nest.rollup = function(f) { - rollup = f; - return nest; - }; - return nest; - }; - d3.set = function(array) { - var set = new d3_Set(); - if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); - return set; - }; - function d3_Set() { - this._ = Object.create(null); - } - d3_class(d3_Set, { - has: d3_map_has, - add: function(key) { - this._[d3_map_escape(key += "")] = true; - return key; - }, - remove: d3_map_remove, - values: d3_map_keys, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key)); - } - }); - d3.behavior = {}; - function d3_identity(d) { - return d; - } - d3.rebind = function(target, source) { - var i = 1, n = arguments.length, method; - while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); - return target; - }; - function d3_rebind(target, source, method) { - return function() { - var value = method.apply(source, arguments); - return value === source ? target : value; - }; - } - function d3_vendorSymbol(object, name) { - if (name in object) return name; - name = name.charAt(0).toUpperCase() + name.slice(1); - for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { - var prefixName = d3_vendorPrefixes[i] + name; - if (prefixName in object) return prefixName; - } - } - var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; - function d3_noop() {} - d3.dispatch = function() { - var dispatch = new d3_dispatch(), i = -1, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - return dispatch; - }; - function d3_dispatch() {} - d3_dispatch.prototype.on = function(type, listener) { - var i = type.indexOf("."), name = ""; - if (i >= 0) { - name = type.slice(i + 1); - type = type.slice(0, i); - } - if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); - if (arguments.length === 2) { - if (listener == null) for (type in this) { - if (this.hasOwnProperty(type)) this[type].on(name, null); - } - return this; + function d3_geo_resample(project) { + var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; + function resample(stream) { + return (maxDepth ? resampleRecursive : resampleNone)(stream); } - }; - function d3_dispatch_event(dispatch) { - var listeners = [], listenerByName = new d3_Map(); - function event() { - var z = listeners, i = -1, n = z.length, l; - while (++i < n) if (l = z[i].on) l.apply(this, arguments); - return dispatch; + function resampleNone(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + }); } - event.on = function(name, listener) { - var l = listenerByName.get(name), i; - if (arguments.length < 2) return l && l.on; - if (l) { - l.on = null; - listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); - listenerByName.remove(name); - } - if (listener) listeners.push(listenerByName.set(name, { - on: listener - })); - return dispatch; - }; - return event; - } - d3.event = null; - function d3_eventPreventDefault() { - d3.event.preventDefault(); - } - function d3_eventSource() { - var e = d3.event, s; - while (s = e.sourceEvent) e = s; - return e; - } - function d3_eventDispatch(target) { - var dispatch = new d3_dispatch(), i = 0, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - dispatch.of = function(thiz, argumentz) { - return function(e1) { - try { - var e0 = e1.sourceEvent = d3.event; - e1.target = target; - d3.event = e1; - dispatch[e1.type].apply(thiz, argumentz); - } finally { - d3.event = e0; + function resampleRecursive(stream) { + var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; + var resample = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + stream.polygonStart(); + resample.lineStart = ringStart; + }, + polygonEnd: function() { + stream.polygonEnd(); + resample.lineStart = lineStart; } }; - }; - return dispatch; - } - d3.requote = function(s) { - return s.replace(d3_requote_re, "\\$&"); - }; - var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; - var d3_subclass = {}.__proto__ ? function(object, prototype) { - object.__proto__ = prototype; - } : function(object, prototype) { - for (var property in prototype) object[property] = prototype[property]; - }; - function d3_selection(groups) { - d3_subclass(groups, d3_selectionPrototype); - return groups; - } - var d3_select = function(s, n) { - return n.querySelector(s); - }, d3_selectAll = function(s, n) { - return n.querySelectorAll(s); - }, d3_selectMatches = function(n, s) { - var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; - d3_selectMatches = function(n, s) { - return d3_selectMatcher.call(n, s); - }; - return d3_selectMatches(n, s); - }; - if (typeof Sizzle === "function") { - d3_select = function(s, n) { - return Sizzle(s, n)[0] || null; - }; - d3_selectAll = Sizzle; - d3_selectMatches = Sizzle.matchesSelector; - } - d3.selection = function() { - return d3.select(d3_document.documentElement); - }; - var d3_selectionPrototype = d3.selection.prototype = []; - d3_selectionPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, group, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(subnode = selector.call(node, node.__data__, i, j)); - if (subnode && "__data__" in node) subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selector(selector) { - return typeof selector === "function" ? selector : function() { - return d3_select(selector, this); - }; - } - d3_selectionPrototype.selectAll = function(selector) { - var subgroups = [], subgroup, node; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); - subgroup.parentNode = node; - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selectorAll(selector) { - return typeof selector === "function" ? selector : function() { - return d3_selectAll(selector, this); - }; - } - var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; - var d3_nsPrefix = { - svg: "http://www.w3.org/2000/svg", - xhtml: d3_nsXhtml, - xlink: "http://www.w3.org/1999/xlink", - xml: "http://www.w3.org/XML/1998/namespace", - xmlns: "http://www.w3.org/2000/xmlns/" - }; - d3.ns = { - prefix: d3_nsPrefix, - qualify: function(name) { - var i = name.indexOf(":"), prefix = name; - if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); - return d3_nsPrefix.hasOwnProperty(prefix) ? { - space: d3_nsPrefix[prefix], - local: name - } : name; - } - }; - d3_selectionPrototype.attr = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(); - name = d3.ns.qualify(name); - return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); - } - for (value in name) this.each(d3_selection_attr(value, name[value])); - return this; - } - return this.each(d3_selection_attr(name, value)); - }; - function d3_selection_attr(name, value) { - name = d3.ns.qualify(name); - function attrNull() { - this.removeAttribute(name); - } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); - } - function attrConstant() { - this.setAttribute(name, value); - } - function attrConstantNS() { - this.setAttributeNS(name.space, name.local, value); - } - function attrFunction() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); - } - function attrFunctionNS() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); - } - return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; - } - function d3_collapse(s) { - return s.trim().replace(/\s+/g, " "); - } - d3_selectionPrototype.classed = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; - if (value = node.classList) { - while (++i < n) if (!value.contains(name[i])) return false; - } else { - value = node.getAttribute("class"); - while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; - } - return true; - } - for (value in name) this.each(d3_selection_classed(value, name[value])); - return this; - } - return this.each(d3_selection_classed(name, value)); - }; - function d3_selection_classedRe(name) { - return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); - } - function d3_selection_classes(name) { - return (name + "").trim().split(/^|\s+/); - } - function d3_selection_classed(name, value) { - name = d3_selection_classes(name).map(d3_selection_classedName); - var n = name.length; - function classedConstant() { - var i = -1; - while (++i < n) name[i](this, value); - } - function classedFunction() { - var i = -1, x = value.apply(this, arguments); - while (++i < n) name[i](this, x); - } - return typeof value === "function" ? classedFunction : classedConstant; - } - function d3_selection_classedName(name) { - var re = d3_selection_classedRe(name); - return function(node, value) { - if (c = node.classList) return value ? c.add(name) : c.remove(name); - var c = node.getAttribute("class") || ""; - if (value) { - re.lastIndex = 0; - if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); - } else { - node.setAttribute("class", d3_collapse(c.replace(re, " "))); - } - }; - } - d3_selectionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); - return this; - } - if (n < 2) { - var node = this.node(); - return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); - } - priority = ""; - } - return this.each(d3_selection_style(name, value, priority)); - }; - function d3_selection_style(name, value, priority) { - function styleNull() { - this.style.removeProperty(name); - } - function styleConstant() { - this.style.setProperty(name, value, priority); - } - function styleFunction() { - var x = value.apply(this, arguments); - if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); - } - return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; - } - d3_selectionPrototype.property = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") return this.node()[name]; - for (value in name) this.each(d3_selection_property(value, name[value])); - return this; - } - return this.each(d3_selection_property(name, value)); - }; - function d3_selection_property(name, value) { - function propertyNull() { - delete this[name]; - } - function propertyConstant() { - this[name] = value; - } - function propertyFunction() { - var x = value.apply(this, arguments); - if (x == null) delete this[name]; else this[name] = x; - } - return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; - } - d3_selectionPrototype.text = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.textContent = v == null ? "" : v; - } : value == null ? function() { - this.textContent = ""; - } : function() { - this.textContent = value; - }) : this.node().textContent; - }; - d3_selectionPrototype.html = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.innerHTML = v == null ? "" : v; - } : value == null ? function() { - this.innerHTML = ""; - } : function() { - this.innerHTML = value; - }) : this.node().innerHTML; - }; - d3_selectionPrototype.append = function(name) { - name = d3_selection_creator(name); - return this.select(function() { - return this.appendChild(name.apply(this, arguments)); - }); - }; - function d3_selection_creator(name) { - function create() { - var document = this.ownerDocument, namespace = this.namespaceURI; - return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); - } - function createNS() { - return this.ownerDocument.createElementNS(name.space, name.local); - } - return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; - } - d3_selectionPrototype.insert = function(name, before) { - name = d3_selection_creator(name); - before = d3_selection_selector(before); - return this.select(function() { - return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); - }); - }; - d3_selectionPrototype.remove = function() { - return this.each(d3_selectionRemove); - }; - function d3_selectionRemove() { - var parent = this.parentNode; - if (parent) parent.removeChild(this); - } - d3_selectionPrototype.data = function(value, key) { - var i = -1, n = this.length, group, node; - if (!arguments.length) { - value = new Array(n = (group = this[0]).length); - while (++i < n) { - if (node = group[i]) { - value[i] = node.__data__; - } - } - return value; - } - function bind(group, groupData) { - var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; - if (key) { - var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; - for (i = -1; ++i < n; ) { - if (node = group[i]) { - if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { - exitNodes[i] = node; - } else { - nodeByKeyValue.set(keyValue, node); - } - keyValues[i] = keyValue; - } - } - for (i = -1; ++i < m; ) { - if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { - enterNodes[i] = d3_selection_dataNode(nodeData); - } else if (node !== true) { - updateNodes[i] = node; - node.__data__ = nodeData; - } - nodeByKeyValue.set(keyValue, true); - } - for (i = -1; ++i < n; ) { - if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { - exitNodes[i] = group[i]; - } - } - } else { - for (i = -1; ++i < n0; ) { - node = group[i]; - nodeData = groupData[i]; - if (node) { - node.__data__ = nodeData; - updateNodes[i] = node; - } else { - enterNodes[i] = d3_selection_dataNode(nodeData); - } - } - for (;i < m; ++i) { - enterNodes[i] = d3_selection_dataNode(groupData[i]); - } - for (;i < n; ++i) { - exitNodes[i] = group[i]; - } + function point(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); } - enterNodes.update = updateNodes; - enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; - enter.push(enterNodes); - update.push(updateNodes); - exit.push(exitNodes); - } - var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); - if (typeof value === "function") { - while (++i < n) { - bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + function lineStart() { + x0 = NaN; + resample.point = linePoint; + stream.lineStart(); } - } else { - while (++i < n) { - bind(group = this[i], value); + function linePoint(λ, φ) { + var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); + resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); + stream.point(x0, y0); } - } - update.enter = function() { - return enter; - }; - update.exit = function() { - return exit; - }; - return update; - }; - function d3_selection_dataNode(data) { - return { - __data__: data - }; - } - d3_selectionPrototype.datum = function(value) { - return arguments.length ? this.property("__data__", value) : this.property("__data__"); - }; - d3_selectionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); - } + function lineEnd() { + resample.point = point; + stream.lineEnd(); } - } - return d3_selection(subgroups); - }; - function d3_selection_filter(selector) { - return function() { - return d3_selectMatches(this, selector); - }; - } - d3_selectionPrototype.order = function() { - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { - if (node = group[i]) { - if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); - next = node; - } + function ringStart() { + lineStart(); + resample.point = ringPoint; + resample.lineEnd = ringEnd; } - } - return this; - }; - d3_selectionPrototype.sort = function(comparator) { - comparator = d3_selection_sortComparator.apply(this, arguments); - for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); - return this.order(); - }; - function d3_selection_sortComparator(comparator) { - if (!arguments.length) comparator = d3_ascending; - return function(a, b) { - return a && b ? comparator(a.__data__, b.__data__) : !a - !b; - }; - } - d3_selectionPrototype.each = function(callback) { - return d3_selection_each(this, function(node, i, j) { - callback.call(node, node.__data__, i, j); - }); - }; - function d3_selection_each(groups, callback) { - for (var j = 0, m = groups.length; j < m; j++) { - for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { - if (node = group[i]) callback(node, i, j); + function ringPoint(λ, φ) { + linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; + resample.point = linePoint; } - } - return groups; - } - d3_selectionPrototype.call = function(callback) { - var args = d3_array(arguments); - callback.apply(args[0] = this, args); - return this; - }; - d3_selectionPrototype.empty = function() { - return !this.node(); - }; - d3_selectionPrototype.node = function() { - for (var j = 0, m = this.length; j < m; j++) { - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - var node = group[i]; - if (node) return node; + function ringEnd() { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); + resample.lineEnd = lineEnd; + lineEnd(); } + return resample; } - return null; - }; - d3_selectionPrototype.size = function() { - var n = 0; - d3_selection_each(this, function() { - ++n; - }); - return n; - }; - function d3_selection_enter(selection) { - d3_subclass(selection, d3_selection_enterPrototype); - return selection; - } - var d3_selection_enterPrototype = []; - d3.selection.enter = d3_selection_enter; - d3.selection.enter.prototype = d3_selection_enterPrototype; - d3_selection_enterPrototype.append = d3_selectionPrototype.append; - d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; - d3_selection_enterPrototype.node = d3_selectionPrototype.node; - d3_selection_enterPrototype.call = d3_selectionPrototype.call; - d3_selection_enterPrototype.size = d3_selectionPrototype.size; - d3_selection_enterPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, upgroup, group, node; - for (var j = -1, m = this.length; ++j < m; ) { - upgroup = (group = this[j]).update; - subgroups.push(subgroup = []); - subgroup.parentNode = group.parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); - subnode.__data__ = node.__data__; - } else { - subgroup.push(null); + function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { + var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; + if (d2 > 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); } } } - return d3_selection(subgroups); - }; - d3_selection_enterPrototype.insert = function(name, before) { - if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); - return d3_selectionPrototype.insert.call(this, name, before); - }; - function d3_selection_enterInsertBefore(enter) { - var i0, j0; - return function(d, i, j) { - var group = enter[j].update, n = group.length, node; - if (j != j0) j0 = j, i0 = 0; - if (i >= i0) i0 = i + 1; - while (!(node = group[i0]) && ++i0 < n) ; - return node; + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; }; + return resample; } - d3.select = function(node) { - var group; - if (typeof node === "string") { - group = [ d3_select(node, d3_document) ]; - group.parentNode = d3_document.documentElement; - } else { - group = [ node ]; - group.parentNode = d3_documentElement(node); - } - return d3_selection([ group ]); - }; - d3.selectAll = function(nodes) { - var group; - if (typeof nodes === "string") { - group = d3_array(d3_selectAll(nodes, d3_document)); - group.parentNode = d3_document.documentElement; - } else { - group = d3_array(nodes); - group.parentNode = null; - } - return d3_selection([ group ]); - }; - d3_selectionPrototype.on = function(type, listener, capture) { - var n = arguments.length; - if (n < 3) { - if (typeof type !== "string") { - if (n < 2) listener = false; - for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); - return this; - } - if (n < 2) return (n = this.node()["__on" + type]) && n._; - capture = false; - } - return this.each(d3_selection_on(type, listener, capture)); - }; - function d3_selection_on(type, listener, capture) { - var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; - if (i > 0) type = type.slice(0, i); - var filter = d3_selection_onFilters.get(type); - if (filter) type = filter, wrap = d3_selection_onFilter; - function onRemove() { - var l = this[name]; - if (l) { - this.removeEventListener(type, l, l.$); - delete this[name]; + d3.geo.path = function() { + var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; + function path(object) { + if (object) { + if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); + if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); + d3.geo.stream(object, cacheStream); } + return contextStream.result(); } - function onAdd() { - var l = wrap(listener, d3_array(arguments)); - onRemove.call(this); - this.addEventListener(type, this[name] = l, l.$ = capture); - l._ = listener; - } - function removeAll() { - var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; - for (var name in this) { - if (match = name.match(re)) { - var l = this[name]; - this.removeEventListener(match[1], l, l.$); - delete this[name]; - } - } + path.area = function(object) { + d3_geo_pathAreaSum = 0; + d3.geo.stream(object, projectStream(d3_geo_pathArea)); + return d3_geo_pathAreaSum; + }; + path.centroid = function(object) { + d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); + return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + }; + path.bounds = function(object) { + d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); + d3.geo.stream(object, projectStream(d3_geo_pathBounds)); + return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + }; + path.projection = function(_) { + if (!arguments.length) return projection; + projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; + return reset(); + }; + path.context = function(_) { + if (!arguments.length) return context; + contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); + if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); + return reset(); + }; + path.pointRadius = function(_) { + if (!arguments.length) return pointRadius; + pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); + return path; + }; + function reset() { + cacheStream = null; + return path; } - return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; - } - var d3_selection_onFilters = d3.map({ - mouseenter: "mouseover", - mouseleave: "mouseout" - }); - if (d3_document) { - d3_selection_onFilters.forEach(function(k) { - if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + return path.projection(d3.geo.albersUsa()).context(null); + }; + function d3_geo_pathProjectStream(project) { + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); }); - } - function d3_selection_onListener(listener, argumentz) { - return function(e) { - var o = d3.event; - d3.event = e; - argumentz[0] = this.__data__; - try { - listener.apply(this, argumentz); - } finally { - d3.event = o; - } + return function(stream) { + return d3_geo_projectionRadians(resample(stream)); }; } - function d3_selection_onFilter(listener, argumentz) { - var l = d3_selection_onListener(listener, argumentz); - return function(e) { - var target = this, related = e.relatedTarget; - if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { - l.call(target, e); + d3.geo.transform = function(methods) { + return { + stream: function(stream) { + var transform = new d3_geo_transform(stream); + for (var k in methods) transform[k] = methods[k]; + return transform; } }; + }; + function d3_geo_transform(stream) { + this.stream = stream; } - var d3_event_dragSelect, d3_event_dragId = 0; - function d3_event_dragSuppress(node) { - var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); - if (d3_event_dragSelect == null) { - d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); - } - if (d3_event_dragSelect) { - var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; - style[d3_event_dragSelect] = "none"; + d3_geo_transform.prototype = { + point: function(x, y) { + this.stream.point(x, y); + }, + sphere: function() { + this.stream.sphere(); + }, + lineStart: function() { + this.stream.lineStart(); + }, + lineEnd: function() { + this.stream.lineEnd(); + }, + polygonStart: function() { + this.stream.polygonStart(); + }, + polygonEnd: function() { + this.stream.polygonEnd(); } - return function(suppressClick) { - w.on(name, null); - if (d3_event_dragSelect) style[d3_event_dragSelect] = select; - if (suppressClick) { - var off = function() { - w.on(click, null); - }; - w.on(click, function() { - d3_eventPreventDefault(); - off(); - }, true); - setTimeout(off, 0); + }; + function d3_geo_transformPoint(stream, point) { + return { + point: point, + sphere: function() { + stream.sphere(); + }, + lineStart: function() { + stream.lineStart(); + }, + lineEnd: function() { + stream.lineEnd(); + }, + polygonStart: function() { + stream.polygonStart(); + }, + polygonEnd: function() { + stream.polygonEnd(); } }; } - d3.mouse = function(container) { - return d3_mousePoint(container, d3_eventSource()); - }; - var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; - function d3_mousePoint(container, e) { - if (e.changedTouches) e = e.changedTouches[0]; - var svg = container.ownerSVGElement || container; - if (svg.createSVGPoint) { - var point = svg.createSVGPoint(); - if (d3_mouse_bug44083 < 0) { - var window = d3_window(container); - if (window.scrollX || window.scrollY) { - svg = d3.select("body").append("svg").style({ - position: "absolute", - top: 0, - left: 0, - margin: 0, - padding: 0, - border: "none" - }, "important"); - var ctm = svg[0][0].getScreenCTM(); - d3_mouse_bug44083 = !(ctm.f || ctm.e); - svg.remove(); - } - } - if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, - point.y = e.clientY; - point = point.matrixTransform(container.getScreenCTM().inverse()); - return [ point.x, point.y ]; - } - var rect = container.getBoundingClientRect(); - return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + d3.geo.projection = d3_geo_projection; + d3.geo.projectionMutator = d3_geo_projectionMutator; + function d3_geo_projection(project) { + return d3_geo_projectionMutator(function() { + return project; + })(); } - d3.touch = function(container, touches, identifier) { - if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; - if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { - if ((touch = touches[i]).identifier === identifier) { - return d3_mousePoint(container, touch); - } + function d3_geo_projectionMutator(projectAt) { + var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { + x = project(x, y); + return [ x[0] * k + δx, δy - x[1] * k ]; + }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; + function projection(point) { + point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); + return [ point[0] * k + δx, δy - point[1] * k ]; } - }; - d3.behavior.drag = function() { - var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); - function drag() { - this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + function invert(point) { + point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); + return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; } - function dragstart(id, position, subject, move, end) { - return function() { - var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); - if (origin) { - dragOffset = origin.apply(that, arguments); - dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; - } else { - dragOffset = [ 0, 0 ]; - } - dispatch({ - type: "dragstart" - }); - function moved() { - var position1 = position(parent, dragId), dx, dy; - if (!position1) return; - dx = position1[0] - position0[0]; - dy = position1[1] - position0[1]; - dragged |= dx | dy; - position0 = position1; - dispatch({ - type: "drag", - x: position1[0] + dragOffset[0], - y: position1[1] + dragOffset[1], - dx: dx, - dy: dy - }); - } - function ended() { - if (!position(parent, dragId)) return; - dragSubject.on(move + dragName, null).on(end + dragName, null); - dragRestore(dragged); - dispatch({ - type: "dragend" - }); - } - }; + projection.stream = function(output) { + if (stream) stream.valid = false; + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); + stream.valid = true; + return stream; + }; + projection.clipAngle = function(_) { + if (!arguments.length) return clipAngle; + preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); + return invalidate(); + }; + projection.clipExtent = function(_) { + if (!arguments.length) return clipExtent; + clipExtent = _; + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; + return invalidate(); + }; + projection.scale = function(_) { + if (!arguments.length) return k; + k = +_; + return reset(); + }; + projection.translate = function(_) { + if (!arguments.length) return [ x, y ]; + x = +_[0]; + y = +_[1]; + return reset(); + }; + projection.center = function(_) { + if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; + λ = _[0] % 360 * d3_radians; + φ = _[1] % 360 * d3_radians; + return reset(); + }; + projection.rotate = function(_) { + if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; + δλ = _[0] % 360 * d3_radians; + δφ = _[1] % 360 * d3_radians; + δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); } - drag.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return drag; + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); }; - return d3.rebind(drag, event, "on"); - }; - function d3_behavior_dragTouchId() { - return d3.event.changedTouches[0].identifier; - } - d3.touches = function(container, touches) { - if (arguments.length < 2) touches = d3_eventSource().touches; - return touches ? d3_array(touches).map(function(touch) { - var point = d3_mousePoint(container, touch); - point.identifier = touch.identifier; - return point; - }) : []; - }; - var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; - function d3_sgn(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; } - function d3_cross2d(a, b, c) { - return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); } - function d3_acos(x) { - return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; } - function d3_asin(x) { - return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + } + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; } - function d3_sinh(x) { - return ((x = Math.exp(x)) - 1 / x) / 2; + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; } - function d3_cosh(x) { - return ((x = Math.exp(x)) + 1 / x) / 2; + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + }; } - function d3_tanh(x) { - return ((x = Math.exp(2 * x)) - 1) / (x + 1); + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; } - function d3_haversin(x) { - return (x = Math.sin(x / 2)) * x; + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; } - var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; - d3.interpolateZoom = function(p0, p1) { - var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; - if (d2 < ε2) { - S = Math.log(w1 / w0) / ρ; - i = function(t) { - return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; - }; - } else { - var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); - S = (r1 - r0) / ρ; - i = function(t) { - var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); - return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] }; } - i.duration = S * 1e3; - return i; + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); }; - d3.behavior.zoom = function() { - var view = { - x: 0, - y: 0, - k: 1 - }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; - if (!d3_behavior_zoomWheel) { - d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); - }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return d3.event.wheelDelta; - }, "mousewheel") : (d3_behavior_zoomDelta = function() { - return -d3.event.detail; - }, "MozMousePixelScroll"); + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * τ; + } else { + from = radius + direction * τ; + to = radius - .5 * step; + } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + } + }; + } + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + } + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; } - function zoom(g) { - g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); } - zoom.event = function(g) { - g.each(function() { - var dispatch = event.of(this, arguments), view1 = view; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.zoom", function() { - view = this.__chart__ || { - x: 0, - y: 0, - k: 1 - }; - zoomstarted(dispatch); - }).tween("zoom:zoom", function() { - var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); - return function(t) { - var l = i(t), k = dx / l[2]; - this.__chart__ = view = { - x: cx - l[0] * k, - y: cy - l[1] * k, - k: k - }; - zoomed(dispatch); - }; - }).each("interrupt.zoom", function() { - zoomended(dispatch); - }).each("end.zoom", function() { - zoomended(dispatch); - }); - } else { - this.__chart__ = view; - zoomstarted(dispatch); - zoomed(dispatch); - zoomended(dispatch); - } + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; }); }; - zoom.translate = function(_) { - if (!arguments.length) return [ view.x, view.y ]; - view = { - x: +_[0], - y: +_[1], - k: view.k + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] }; - rescale(); - return zoom; }; - zoom.scale = function(_) { - if (!arguments.length) return view.k; - view = { - x: view.x, - y: view.y, - k: null - }; - scaleTo(+_); - rescale(); - return zoom; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); }; - zoom.scaleExtent = function(_) { - if (!arguments.length) return scaleExtent; - scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; - return zoom; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); }; - zoom.center = function(_) { - if (!arguments.length) return center; - center = _ && [ +_[0], +_[1] ]; - return zoom; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); }; - zoom.size = function(_) { - if (!arguments.length) return size; - size = _ && [ +_[0], +_[1] ]; - return zoom; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); }; - zoom.duration = function(_) { - if (!arguments.length) return duration; - duration = +_; - return zoom; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; }; - zoom.x = function(z) { - if (!arguments.length) return x1; - x1 = z; - x0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; }; - zoom.y = function(z) { - if (!arguments.length) return y1; - y1 = z; - y0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; }; - function location(p) { - return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; - } - function point(l) { - return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; - } - function scaleTo(s) { - view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); - } - function translateTo(p, l) { - l = point(l); - view.x += p[0] - l[0]; - view.y += p[1] - l[1]; - } - function zoomTo(that, p, l, k) { - that.__chart__ = { - x: view.x, - y: view.y, - k: view.k - }; - scaleTo(Math.pow(2, k)); - translateTo(center0 = p, l); - that = d3.select(that); - if (duration > 0) that = that.transition().duration(duration); - that.call(zoom.event); - } - function rescale() { - if (x1) x1.domain(x0.range().map(function(x) { - return (x - view.x) / view.k; - }).map(x0.invert)); - if (y1) y1.domain(y0.range().map(function(y) { - return (y - view.y) / view.k; - }).map(y0.invert)); - } - function zoomstarted(dispatch) { - if (!zooming++) dispatch({ - type: "zoomstart" + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; }); - } - function zoomed(dispatch) { - rescale(); - dispatch({ - type: "zoom", - scale: view.k, - translate: [ view.x, view.y ] + }; + } + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; }); + }; + } + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; } - function zoomended(dispatch) { - if (!--zooming) dispatch({ - type: "zoomend" - }), center0 = null; + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; + } + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; } - function mousedowned() { - var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); - d3_selection_interrupt.call(that); - zoomstarted(dispatch); - function moved() { - dragged = 1; - translateTo(d3.mouse(that), location0); - zoomed(dispatch); - } - function ended() { - subject.on(mousemove, null).on(mouseup, null); - dragRestore(dragged); - zoomended(dispatch); - } + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; } - function touchstarted() { - var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); - started(); - zoomstarted(dispatch); - subject.on(mousedown, null).on(touchstart, started); - function relocate() { - var touches = d3.touches(that); - scale0 = view.k; - touches.forEach(function(t) { - if (t.identifier in locations0) locations0[t.identifier] = location(t); - }); - return touches; - } - function started() { - var target = d3.event.target; - d3.select(target).on(touchmove, moved).on(touchend, ended); - targets.push(target); - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - locations0[changed[i].identifier] = null; - } - var touches = relocate(), now = Date.now(); - if (touches.length === 1) { - if (now - touchtime < 500) { - var p = touches[0]; - zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); - d3_eventPreventDefault(); - } - touchtime = now; - } else if (touches.length > 1) { - var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; - distance0 = dx * dx + dy * dy; - } - } - function moved() { - var touches = d3.touches(that), p0, l0, p1, l1; - d3_selection_interrupt.call(that); - for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { - p1 = touches[i]; - if (l1 = locations0[p1.identifier]) { - if (l0) break; - p0 = p1, l0 = l1; - } - } - if (l1) { - var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); - p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; - l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; - scaleTo(scale1 * scale0); - } - touchtime = null; - translateTo(p0, l0); - zoomed(dispatch); - } - function ended() { - if (d3.event.touches.length) { - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - delete locations0[changed[i].identifier]; - } - for (var identifier in locations0) { - return void relocate(); - } - } - d3.selectAll(targets).on(zoomName, null); - subject.on(mousedown, mousedowned).on(touchstart, touchstarted); - dragRestore(); - zoomended(dispatch); + azimuthal.invert = function(x, y) { + var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + }; + return azimuthal; + } + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(ρ) { + return 2 * Math.asin(ρ / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(π / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + if (F > 0) { + if (φ < -halfπ + ε) φ = -halfπ + ε; + } else { + if (φ > halfπ - ε) φ = halfπ - ε; } + var ρ = F / Math.pow(t(φ), n); + return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } - function mousewheeled() { - var dispatch = event.of(this, arguments); - if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), - translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); - mousewheelTimer = setTimeout(function() { - mousewheelTimer = null; - zoomended(dispatch); - }, 50); - d3_eventPreventDefault(); - scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); - translateTo(center0, translate0); - zoomed(dispatch); - } - function dblclicked() { - var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; - zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + forward.invert = function(x, y) { + var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; + }; + return forward; + } + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var ρ = G - φ; + return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; } - return d3.rebind(zoom, event, "on"); - }; - var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; - d3.color = d3_color; - function d3_color() {} - d3_color.prototype.toString = function() { - return this.rgb() + ""; - }; - d3.hsl = d3_hsl; - function d3_hsl(h, s, l) { - return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); + forward.invert = function(x, y) { + var ρ0_y = G - y; + return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + }; + return forward; } - var d3_hslPrototype = d3_hsl.prototype = new d3_color(); - d3_hslPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, this.l / k); - }; - d3_hslPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, k * this.l); + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; + } + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; }; - d3_hslPrototype.rgb = function() { - return d3_hsl_rgb(this.h, this.s, this.l); + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = π * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; + } + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(ρ) { + return 2 * Math.atan(ρ); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; + } + d3_geo_transverseMercator.invert = function(x, y) { + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; }; - function d3_hsl_rgb(h, s, l) { - var m1, m2; - h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; - s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; - l = l < 0 ? 0 : l > 1 ? 1 : l; - m2 = l <= .5 ? l * (1 + s) : l + s - l * s; - m1 = 2 * l - m2; - function v(h) { - if (h > 360) h -= 360; else if (h < 0) h += 360; - if (h < 60) return m1 + (m2 - m1) * h / 60; - if (h < 180) return m2; - if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; - return m1; + (d3.geo.transverseMercator = function() { + var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; + projection.center = function(_) { + return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + }; + projection.rotate = function(_) { + return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), + [ _[0], _[1], _[2] - 90 ]); + }; + return rotate([ 0, 0, 90 ]); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; + for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); + return polygon; } - function vv(h) { - return Math.round(v(h) * 255); + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [ 0, 1 ], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; } - return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + return hull.slice(0, hs); } - d3.hcl = d3_hcl; - function d3_hcl(h, c, l) { - return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; } - var d3_hclPrototype = d3_hcl.prototype = new d3_color(); - d3_hclPrototype.brighter = function(k) { - return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; }; - d3_hclPrototype.darker = function(k) { - return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; }; - d3_hclPrototype.rgb = function() { - return d3_hcl_lab(this.h, this.c, this.l).rgb(); + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; }; - function d3_hcl_lab(h, c, l) { - if (isNaN(h)) h = 0; - if (isNaN(c)) c = 0; - return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); } - d3.lab = d3_lab; - function d3_lab(l, a, b) { - return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; } - var d3_lab_K = 18; - var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; - var d3_labPrototype = d3_lab.prototype = new d3_color(); - d3_labPrototype.brighter = function(k) { - return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.darker = function(k) { - return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.rgb = function() { - return d3_lab_rgb(this.l, this.a, this.b); - }; - function d3_lab_rgb(l, a, b) { - var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; - x = d3_lab_xyz(x) * d3_lab_X; - y = d3_lab_xyz(y) * d3_lab_Y; - z = d3_lab_xyz(z) * d3_lab_Z; - return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); } - function d3_lab_hcl(l, a, b) { - return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; } - function d3_lab_xyz(x) { - return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; } - function d3_xyz_lab(x) { - return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); } - function d3_xyz_rgb(r) { - return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); } - d3.rgb = d3_rgb; - function d3_rgb(r, g, b) { - return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); } - function d3_rgbNumber(value) { - return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; } - function d3_rgbString(value) { - return d3_rgbNumber(value) + ""; + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; } - var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); - d3_rgbPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - var r = this.r, g = this.g, b = this.b, i = 30; - if (!r && !g && !b) return new d3_rgb(i, i, i); - if (r && r < i) r = i; - if (g && g < i) g = i; - if (b && b < i) b = i; - return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); - }; - d3_rgbPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_rgb(k * this.r, k * this.g, k * this.b); - }; - d3_rgbPrototype.hsl = function() { - return d3_rgb_hsl(this.r, this.g, this.b); - }; - d3_rgbPrototype.toString = function() { - return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); - }; - function d3_rgb_hex(v) { - return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; } - function d3_rgb_parse(format, rgb, hsl) { - var r = 0, g = 0, b = 0, m1, m2, color; - m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); - if (m1) { - m2 = m1[2].split(","); - switch (m1[1]) { - case "hsl": - { - return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); - } - - case "rgb": - { - return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; } } } - if (color = d3_rgb_names.get(format)) { - return rgb(color.r, color.g, color.b); - } - if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { - if (format.length === 4) { - r = (color & 3840) >> 4; - r = r >> 4 | r; - g = color & 240; - g = g >> 4 | g; - b = color & 15; - b = b << 4 | b; - } else if (format.length === 7) { - r = (color & 16711680) >> 16; - g = (color & 65280) >> 8; - b = color & 255; + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } } } - return rgb(r, g, b); + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; } - function d3_rgb_hsl(r, g, b) { - var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; - if (d) { - s = l < .5 ? d / (max + min) : d / (2 - max - min); - if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; - h *= 60; - } else { - h = NaN; - s = l > 0 && l < 1 ? 0 : h; + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; } - return new d3_hsl(h, s, l); - } - function d3_rgb_lab(r, g, b) { - r = d3_rgb_xyz(r); - g = d3_rgb_xyz(g); - b = d3_rgb_xyz(b); - var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); - return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); - } - function d3_rgb_xyz(r) { - return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); - } - function d3_rgb_parseNumber(c) { - var f = parseFloat(c); - return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; - } - var d3_rgb_names = d3.map({ - aliceblue: 15792383, - antiquewhite: 16444375, - aqua: 65535, - aquamarine: 8388564, - azure: 15794175, - beige: 16119260, - bisque: 16770244, - black: 0, - blanchedalmond: 16772045, - blue: 255, - blueviolet: 9055202, - brown: 10824234, - burlywood: 14596231, - cadetblue: 6266528, - chartreuse: 8388352, - chocolate: 13789470, - coral: 16744272, - cornflowerblue: 6591981, - cornsilk: 16775388, - crimson: 14423100, - cyan: 65535, - darkblue: 139, - darkcyan: 35723, - darkgoldenrod: 12092939, - darkgray: 11119017, - darkgreen: 25600, - darkgrey: 11119017, - darkkhaki: 12433259, - darkmagenta: 9109643, - darkolivegreen: 5597999, - darkorange: 16747520, - darkorchid: 10040012, - darkred: 9109504, - darksalmon: 15308410, - darkseagreen: 9419919, - darkslateblue: 4734347, - darkslategray: 3100495, - darkslategrey: 3100495, - darkturquoise: 52945, - darkviolet: 9699539, - deeppink: 16716947, - deepskyblue: 49151, - dimgray: 6908265, - dimgrey: 6908265, - dodgerblue: 2003199, - firebrick: 11674146, - floralwhite: 16775920, - forestgreen: 2263842, - fuchsia: 16711935, - gainsboro: 14474460, - ghostwhite: 16316671, - gold: 16766720, - goldenrod: 14329120, - gray: 8421504, - green: 32768, - greenyellow: 11403055, - grey: 8421504, - honeydew: 15794160, - hotpink: 16738740, - indianred: 13458524, - indigo: 4915330, - ivory: 16777200, - khaki: 15787660, - lavender: 15132410, - lavenderblush: 16773365, - lawngreen: 8190976, - lemonchiffon: 16775885, - lightblue: 11393254, - lightcoral: 15761536, - lightcyan: 14745599, - lightgoldenrodyellow: 16448210, - lightgray: 13882323, - lightgreen: 9498256, - lightgrey: 13882323, - lightpink: 16758465, - lightsalmon: 16752762, - lightseagreen: 2142890, - lightskyblue: 8900346, - lightslategray: 7833753, - lightslategrey: 7833753, - lightsteelblue: 11584734, - lightyellow: 16777184, - lime: 65280, - limegreen: 3329330, - linen: 16445670, - magenta: 16711935, - maroon: 8388608, - mediumaquamarine: 6737322, - mediumblue: 205, - mediumorchid: 12211667, - mediumpurple: 9662683, - mediumseagreen: 3978097, - mediumslateblue: 8087790, - mediumspringgreen: 64154, - mediumturquoise: 4772300, - mediumvioletred: 13047173, - midnightblue: 1644912, - mintcream: 16121850, - mistyrose: 16770273, - moccasin: 16770229, - navajowhite: 16768685, - navy: 128, - oldlace: 16643558, - olive: 8421376, - olivedrab: 7048739, - orange: 16753920, - orangered: 16729344, - orchid: 14315734, - palegoldenrod: 15657130, - palegreen: 10025880, - paleturquoise: 11529966, - palevioletred: 14381203, - papayawhip: 16773077, - peachpuff: 16767673, - peru: 13468991, - pink: 16761035, - plum: 14524637, - powderblue: 11591910, - purple: 8388736, - rebeccapurple: 6697881, - red: 16711680, - rosybrown: 12357519, - royalblue: 4286945, - saddlebrown: 9127187, - salmon: 16416882, - sandybrown: 16032864, - seagreen: 3050327, - seashell: 16774638, - sienna: 10506797, - silver: 12632256, - skyblue: 8900331, - slateblue: 6970061, - slategray: 7372944, - slategrey: 7372944, - snow: 16775930, - springgreen: 65407, - steelblue: 4620980, - tan: 13808780, - teal: 32896, - thistle: 14204888, - tomato: 16737095, - turquoise: 4251856, - violet: 15631086, - wheat: 16113331, - white: 16777215, - whitesmoke: 16119285, - yellow: 16776960, - yellowgreen: 10145074 - }); - d3_rgb_names.forEach(function(key, value) { - d3_rgb_names.set(key, d3_rgbNumber(value)); - }); - function d3_functor(v) { - return typeof v === "function" ? v : function() { - return v; - }; } - d3.functor = d3_functor; - d3.xhr = d3_xhrType(d3_identity); - function d3_xhrType(response) { - return function(url, mimeType, callback) { - if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, - mimeType = null; - return d3_xhr(url, mimeType, response, callback); - }; + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } } - function d3_xhr(url, mimeType, response, callback) { - var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; - if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); - "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { - request.readyState > 3 && respond(); - }; - function respond() { - var status = request.status, result; - if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { - try { - result = response.call(xhr, request); - } catch (e) { - dispatch.error.call(xhr, e); - return; + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; } - dispatch.load.call(xhr, result); } else { - dispatch.error.call(xhr, request); + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } } } - request.onprogress = function(event) { - var o = d3.event; - d3.event = event; - try { - dispatch.progress.call(xhr, request); - } finally { - d3.event = o; - } - }; - xhr.header = function(name, value) { - name = (name + "").toLowerCase(); - if (arguments.length < 2) return headers[name]; - if (value == null) delete headers[name]; else headers[name] = value + ""; - return xhr; - }; - xhr.mimeType = function(value) { - if (!arguments.length) return mimeType; - mimeType = value == null ? null : value + ""; - return xhr; - }; - xhr.responseType = function(value) { - if (!arguments.length) return responseType; - responseType = value; - return xhr; - }; - xhr.response = function(value) { - response = value; - return xhr; - }; - [ "get", "post" ].forEach(function(method) { - xhr[method] = function() { - return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); - }; - }); - xhr.send = function(method, data, callback) { - if (arguments.length === 2 && typeof data === "function") callback = data, data = null; - request.open(method, url, true); - if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; - if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); - if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); - if (responseType != null) request.responseType = responseType; - if (callback != null) xhr.on("error", callback).on("load", function(request) { - callback(null, request); - }); - dispatch.beforesend.call(xhr, request); - request.send(data == null ? null : data); - return xhr; - }; - xhr.abort = function() { - request.abort(); - return xhr; - }; - d3.rebind(xhr, dispatch, "on"); - return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + edge.a = va; + edge.b = vb; + return true; } - function d3_xhr_fixCallback(callback) { - return callback.length === 1 ? function(error, request) { - callback(error == null ? request : null); - } : callback; + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; } - function d3_xhrHasResponse(request) { - var type = request.responseType; - return type && type !== "text" ? request.response : request.responseText; + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; } - d3.dsv = function(delimiter, mimeType) { - var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); - function dsv(url, row, callback) { - if (arguments.length < 3) callback = row, row = null; - var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); - xhr.row = function(_) { - return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; - }; - return xhr; - } - function response(request) { - return dsv.parse(request.responseText); + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; } - function typedResponse(f) { - return function(request) { - return dsv.parse(request.responseText, f); - }; + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; } - dsv.parse = function(text, f) { - var o; - return dsv.parseRows(text, function(row, i) { - if (o) return o(row, i - 1); - var a = new Function("d", "return {" + row.map(function(name, i) { - return JSON.stringify(name) + ": d[" + i + "]"; - }).join(",") + "}"); - o = f ? function(row, i) { - return f(a(row), i); - } : a; - }); - }; - dsv.parseRows = function(text, f) { - var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; - function token() { - if (I >= N) return EOF; - if (eol) return eol = false, EOL; - var j = I; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); } - I = i + 2; - var c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); } - return text.slice(j + 1, i).replace(/""/g, '"'); - } - while (I < N) { - var c = text.charCodeAt(I++), k = 1; - if (c === 10) eol = true; else if (c === 13) { - eol = true; - if (text.charCodeAt(I) === 10) ++I, ++k; - } else if (c !== delimiterCode) continue; - return text.slice(j, I - k); } - return text.slice(j); + parent = after.U; } - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; } - if (f && (a = f(a, n++)) == null) continue; - rows.push(a); + } else { + red = node.C; + node = next; } - return rows; - }; - dsv.format = function(rows) { - if (Array.isArray(rows[0])) return dsv.formatRows(rows); - var fieldSet = new d3_Set(), fields = []; - rows.forEach(function(row) { - for (var field in row) { - if (!fieldSet.has(field)) { - fields.push(fieldSet.add(field)); + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; } } - }); - return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { - return fields.map(function(field) { - return formatValue(row[field]); - }).join(delimiter); - })).join("\n"); - }; - dsv.formatRows = function(rows) { - return rows.map(formatRow).join("\n"); - }; - function formatRow(row) { - return row.map(formatValue).join(delimiter); - } - function formatValue(text) { - return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; } - return dsv; - }; - d3.csv = d3.dsv(",", "text/csv"); - d3.tsv = d3.dsv(" ", "text/tab-separated-values"); - var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { - setTimeout(callback, 17); }; - d3.timer = function() { - d3_timer.apply(this, arguments); - }; - function d3_timer(callback, delay, then) { - var n = arguments.length; - if (n < 2) delay = 0; - if (n < 3) then = Date.now(); - var time = then + delay, timer = { - c: callback, - t: time, - n: null - }; - if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; - d3_timer_queueTail = timer; - if (!d3_timer_interval) { - d3_timer_timeout = clearTimeout(d3_timer_timeout); - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; } - return timer; + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; } - function d3_timer_step() { - var now = d3_timer_mark(), delay = d3_timer_sweep() - now; - if (delay > 24) { - if (isFinite(delay)) { - clearTimeout(d3_timer_timeout); - d3_timer_timeout = setTimeout(d3_timer_step, delay); - } - d3_timer_interval = 0; + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; } else { - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); + tree._ = q; } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; } - d3.timer.flush = function() { - d3_timer_mark(); - d3_timer_sweep(); - }; - function d3_timer_mark() { - var now = Date.now(), timer = d3_timer_queueHead; - while (timer) { - if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; - timer = timer.n; - } - return now; + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; } - function d3_timer_sweep() { - var t0, t1 = d3_timer_queueHead, time = Infinity; - while (t1) { - if (t1.c) { - if (t1.t < time) time = t1.t; - t1 = (t0 = t1).n; + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); } else { - t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + break; } } - d3_timer_queueTail = t0; - return time; + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; } - function d3_format_precision(x, p) { - return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; } - d3.round = function(x, n) { - return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); - }; - var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); - d3.formatPrefix = function(value, precision) { - var i = 0; - if (value = +value) { - if (value < 0) value *= -1; - if (precision) value = d3.round(value, d3_format_precision(value, precision)); - i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); - i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; } - return d3_formatPrefixes[8 + i / 3]; - }; - function d3_formatPrefix(d, i) { - var k = Math.pow(10, abs(8 - i) * 3); - return { - scale: i > 8 ? function(d) { - return d / k; - } : function(d) { - return d * k; - }, - symbol: d + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); }; - } - function d3_locale_numberFormat(locale) { - var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { - var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; - while (i > 0 && g > 0) { - if (length + g + 1 > width) g = Math.max(1, width - length); - t.push(value.substring(i -= g, i + g)); - if ((length += g + 1) > width) break; - g = locale_grouping[j = (j + 1) % locale_grouping.length]; - } - return t.reverse().join(locale_thousands); - } : d3_identity; - return function(specifier) { - var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; - if (precision) precision = +precision.substring(1); - if (zfill || fill === "0" && align === "=") { - zfill = fill = "0"; - align = "="; - } - switch (type) { - case "n": - comma = true; - type = "g"; - break; - - case "%": - scale = 100; - suffix = "%"; - type = "f"; - break; - - case "p": - scale = 100; - suffix = "%"; - type = "r"; - break; - - case "b": - case "o": - case "x": - case "X": - if (symbol === "#") prefix = "0" + type.toLowerCase(); - - case "c": - exponent = false; - - case "d": - integer = true; - precision = 0; - break; - - case "s": - scale = -1; - type = "r"; - break; - } - if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; - if (type == "r" && !precision) type = "g"; - if (precision != null) { - if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); - } - type = d3_format_types.get(type) || d3_format_typeDefault; - var zcomma = zfill && comma; - return function(value) { - var fullSuffix = suffix; - if (integer && value % 1) return ""; - var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; - if (scale < 0) { - var unit = d3.formatPrefix(value, precision); - value = unit.scale(value); - fullSuffix = unit.symbol + suffix; - } else { - value *= scale; - } - value = type(value, precision); - var i = value.lastIndexOf("."), before, after; - if (i < 0) { - var j = exponent ? value.lastIndexOf("e") : -1; - if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); - } else { - before = value.substring(0, i); - after = locale_decimal + value.substring(i + 1); + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } } - if (!zfill && comma) before = formatGroup(before, Infinity); - var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; - if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); - negative += prefix; - value = before + after; - return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; - }; + }); + return triangles; }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); } - var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; - var d3_format_types = d3.map({ - b: function(x) { - return x.toString(2); - }, - c: function(x) { - return String.fromCharCode(x); - }, - o: function(x) { - return x.toString(8); - }, - x: function(x) { - return x.toString(16); - }, - X: function(x) { - return x.toString(16).toUpperCase(); - }, - g: function(x, p) { - return x.toPrecision(p); - }, - e: function(x, p) { - return x.toExponential(p); - }, - f: function(x, p) { - return x.toFixed(p); - }, - r: function(x, p) { - return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); - } - }); - function d3_format_typeDefault(x) { - return x + ""; - } - var d3_time = d3.time = {}, d3_date = Date; - function d3_date_utc() { - this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); - } - d3_date_utc.prototype = { - getDate: function() { - return this._.getUTCDate(); - }, - getDay: function() { - return this._.getUTCDay(); - }, - getFullYear: function() { - return this._.getUTCFullYear(); - }, - getHours: function() { - return this._.getUTCHours(); - }, - getMilliseconds: function() { - return this._.getUTCMilliseconds(); - }, - getMinutes: function() { - return this._.getUTCMinutes(); - }, - getMonth: function() { - return this._.getUTCMonth(); - }, - getSeconds: function() { - return this._.getUTCSeconds(); - }, - getTime: function() { - return this._.getTime(); - }, - getTimezoneOffset: function() { - return 0; - }, - valueOf: function() { - return this._.valueOf(); - }, - setDate: function() { - d3_time_prototype.setUTCDate.apply(this._, arguments); - }, - setDay: function() { - d3_time_prototype.setUTCDay.apply(this._, arguments); - }, - setFullYear: function() { - d3_time_prototype.setUTCFullYear.apply(this._, arguments); - }, - setHours: function() { - d3_time_prototype.setUTCHours.apply(this._, arguments); - }, - setMilliseconds: function() { - d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); - }, - setMinutes: function() { - d3_time_prototype.setUTCMinutes.apply(this._, arguments); - }, - setMonth: function() { - d3_time_prototype.setUTCMonth.apply(this._, arguments); - }, - setSeconds: function() { - d3_time_prototype.setUTCSeconds.apply(this._, arguments); - }, - setTime: function() { - d3_time_prototype.setTime.apply(this._, arguments); - } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); }; - var d3_time_prototype = Date.prototype; - function d3_time_interval(local, step, number) { - function round(date) { - var d0 = local(date), d1 = offset(d0, 1); - return date - d0 < d1 - date ? d0 : d1; - } - function ceil(date) { - step(date = local(new d3_date(date - 1)), 1); - return date; - } - function offset(date, k) { - step(date = new d3_date(+date), k); - return date; - } - function range(t0, t1, dt) { - var time = ceil(t0), times = []; - if (dt > 1) { - while (time < t1) { - if (!(number(time) % dt)) times.push(new Date(+time)); - step(time, 1); - } - } else { - while (time < t1) times.push(new Date(+time)), step(time, 1); - } - return times; - } - function range_utc(t0, t1, dt) { - try { - d3_date = d3_date_utc; - var utc = new d3_date_utc(); - utc._ = t0; - return range(utc, t1, dt); - } finally { - d3_date = Date; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; } + return quadtree(points); } - local.floor = local; - local.round = round; - local.ceil = ceil; - local.offset = offset; - local.range = range; - var utc = local.utc = d3_time_interval_utc(local); - utc.floor = utc; - utc.round = d3_time_interval_utc(round); - utc.ceil = d3_time_interval_utc(ceil); - utc.offset = d3_time_interval_utc(offset); - utc.range = range_utc; - return local; - } - function d3_time_interval_utc(method) { - return function(date, k) { - try { - d3_date = d3_date_utc; - var utc = new d3_date_utc(); - utc._ = date; - return method(utc, k)._; - } finally { - d3_date = Date; + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } } - }; - } - d3_time.year = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setMonth(0, 1); - return date; - }, function(date, offset) { - date.setFullYear(date.getFullYear() + offset); - }, function(date) { - return date.getFullYear(); - }); - d3_time.years = d3_time.year.range; - d3_time.years.utc = d3_time.year.utc.range; - d3_time.day = d3_time_interval(function(date) { - var day = new d3_date(2e3, 0); - day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); - return day; - }, function(date, offset) { - date.setDate(date.getDate() + offset); - }, function(date) { - return date.getDate() - 1; - }); - d3_time.days = d3_time.day.range; - d3_time.days.utc = d3_time.day.utc.range; - d3_time.dayOfYear = function(date) { - var year = d3_time.year(date); - return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); - }; - [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { - i = 7 - i; - var interval = d3_time[day] = d3_time_interval(function(date) { - (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); - return date; - }, function(date, offset) { - date.setDate(date.getDate() + Math.floor(offset) * 7); - }, function(date) { - var day = d3_time.year(date).getDay(); - return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); - }); - d3_time[day + "s"] = interval.range; - d3_time[day + "s"].utc = interval.utc.range; - d3_time[day + "OfYear"] = function(date) { - var day = d3_time.year(date).getDay(); - return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); - }; - }); - d3_time.week = d3_time.sunday; - d3_time.weeks = d3_time.sunday.range; - d3_time.weeks.utc = d3_time.sunday.utc.range; - d3_time.weekOfYear = d3_time.sundayOfYear; - function d3_locale_timeFormat(locale) { - var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; - function d3_time_format(template) { - var n = template.length; - function format(date) { - var string = [], i = -1, j = 0, c, p, f; - while (++i < n) { - if (template.charCodeAt(i) === 37) { - string.push(template.slice(j, i)); - if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); - if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); - string.push(c); - j = i + 1; + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); } - string.push(template.slice(j, i)); - return string.join(""); } - format.parse = function(string) { - var d = { - y: 1900, - m: 0, - d: 1, - H: 0, - M: 0, - S: 0, - L: 0, - Z: null - }, i = d3_time_parse(d, template, string, 0); - if (i != string.length) return null; - if ("p" in d) d.H = d.H % 12 + d.p * 12; - var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); - if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { - if (!("w" in d)) d.w = "W" in d ? 1 : 0; - date.setFullYear(d.y, 0, 1); - date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); - } else date.setFullYear(d.y, d.m, d.d); - date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); - return localZ ? date._ : date; + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = xm; else x2 = xm; + if (below) y1 = ym; else y2 = ym; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); }; - format.toString = function() { - return template; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); }; - return format; - } - function d3_time_parse(date, template, string, j) { - var c, p, t, i = 0, n = template.length, m = string.length; - while (i < n) { - if (j >= m) return -1; - c = template.charCodeAt(i++); - if (c === 37) { - t = template.charAt(i++); - p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; - if (!p || (j = p(date, string, j)) < 0) return -1; - } else if (c != string.charCodeAt(j++)) { - return -1; + root.find = function(point) { + return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); } - } - return j; + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; } - d3_time_format.utc = function(template) { - var local = d3_time_format(template); - function format(date) { - try { - d3_date = d3_date_utc; - var utc = new d3_date(); - utc._ = date; - return local(utc); - } finally { - d3_date = Date; + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { + var minDistance2 = Infinity, closestPoint; + (function find(node, x1, y1, x2, y2) { + if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; + if (point = node.point) { + var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; + if (distance2 < minDistance2) { + var distance = Math.sqrt(minDistance2 = distance2); + x0 = x - distance, y0 = y - distance; + x3 = x + distance, y3 = y + distance; + closestPoint = point; } } - format.parse = function(string) { - try { - d3_date = d3_date_utc; - var date = local.parse(string); - return date && date._; - } finally { - d3_date = Date; + var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; + for (var i = below << 1 | right, j = i + 4; i < j; ++i) { + if (node = children[i & 3]) switch (i & 3) { + case 0: + find(node, x1, y1, xm, ym); + break; + + case 1: + find(node, xm, y1, x2, ym); + break; + + case 2: + find(node, x1, ym, xm, y2); + break; + + case 3: + find(node, xm, ym, x2, y2); + break; } - }; - format.toString = local.toString; - return format; - }; - d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; - var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); - locale_periods.forEach(function(p, i) { - d3_time_periodLookup.set(p.toLowerCase(), i); - }); - var d3_time_formats = { - a: function(d) { - return locale_shortDays[d.getDay()]; - }, - A: function(d) { - return locale_days[d.getDay()]; - }, - b: function(d) { - return locale_shortMonths[d.getMonth()]; - }, - B: function(d) { - return locale_months[d.getMonth()]; - }, - c: d3_time_format(locale_dateTime), - d: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - e: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - H: function(d, p) { - return d3_time_formatPad(d.getHours(), p, 2); - }, - I: function(d, p) { - return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); - }, - j: function(d, p) { - return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); - }, - L: function(d, p) { - return d3_time_formatPad(d.getMilliseconds(), p, 3); - }, - m: function(d, p) { - return d3_time_formatPad(d.getMonth() + 1, p, 2); - }, - M: function(d, p) { - return d3_time_formatPad(d.getMinutes(), p, 2); - }, - p: function(d) { - return locale_periods[+(d.getHours() >= 12)]; - }, - S: function(d, p) { - return d3_time_formatPad(d.getSeconds(), p, 2); - }, - U: function(d, p) { - return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); - }, - w: function(d) { - return d.getDay(); - }, - W: function(d, p) { - return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); - }, - x: d3_time_format(locale_date), - X: d3_time_format(locale_time), - y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 100, p, 2); - }, - Y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); - }, - Z: d3_time_zone, - "%": function() { - return "%"; } + })(root, x0, y0, x3, y3); + return closestPoint; + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; - var d3_time_parsers = { - a: d3_time_parseWeekdayAbbrev, - A: d3_time_parseWeekday, - b: d3_time_parseMonthAbbrev, - B: d3_time_parseMonth, - c: d3_time_parseLocaleFull, - d: d3_time_parseDay, - e: d3_time_parseDay, - H: d3_time_parseHour24, - I: d3_time_parseHour24, - j: d3_time_parseDayOfYear, - L: d3_time_parseMilliseconds, - m: d3_time_parseMonthNumber, - M: d3_time_parseMinutes, - p: d3_time_parseAmPm, - S: d3_time_parseSeconds, - U: d3_time_parseWeekNumberSunday, - w: d3_time_parseWeekdayNumber, - W: d3_time_parseWeekNumberMonday, - x: d3_time_parseLocaleDate, - X: d3_time_parseLocaleTime, - y: d3_time_parseYear, - Y: d3_time_parseFullYear, - Z: d3_time_parseZone, - "%": d3_time_parseLiteralPercent - }; - function d3_time_parseWeekdayAbbrev(date, string, i) { - d3_time_dayAbbrevRe.lastIndex = 0; - var n = d3_time_dayAbbrevRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseWeekday(date, string, i) { - d3_time_dayRe.lastIndex = 0; - var n = d3_time_dayRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonthAbbrev(date, string, i) { - d3_time_monthAbbrevRe.lastIndex = 0; - var n = d3_time_monthAbbrevRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonth(date, string, i) { - d3_time_monthRe.lastIndex = 0; - var n = d3_time_monthRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseLocaleFull(date, string, i) { - return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } } - function d3_time_parseLocaleDate(date, string, i) { - return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } } - function d3_time_parseLocaleTime(date, string, i) { - return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + a = +a, b = +b; + return function(t) { + return a * (1 - t) + b * t; + }; + } + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; else s[++i] = bm; + } else { + s[++i] = null; + q.push({ + i: i, + x: d3_interpolateNumber(am, bm) + }); + } + bi = d3_interpolate_numberB.lastIndex; } - function d3_time_parseAmPm(date, string, i) { - var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); - return n == null ? -1 : (date.p = n, i); + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; else s[++i] = bs; } - return d3_time_format; - } - var d3_time_formatPads = { - "-": "", - _: " ", - "0": "0" - }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; - function d3_time_formatPad(value, fill, width) { - var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; - return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); - } - function d3_time_formatRe(names) { - return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { + return b(t) + ""; + }) : function() { + return b; + } : (b = q.length, function(t) { + for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }); } - function d3_time_formatLookup(names) { - var map = new d3_Map(), i = -1, n = names.length; - while (++i < n) map.set(names[i].toLowerCase(), i); - return map; + var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; } - function d3_time_parseWeekdayNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 1)); - return n ? (date.w = +n[0], i + n[0].length) : -1; + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; } - function d3_time_parseWeekNumberSunday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.U = +n[0], i + n[0].length) : -1; + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; } - function d3_time_parseWeekNumberMonday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.W = +n[0], i + n[0].length) : -1; + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; } - function d3_time_parseFullYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 4)); - return n ? (date.y = +n[0], i + n[0].length) : -1; + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; } - function d3_time_parseYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + function d3_ease_quad(t) { + return t * t; } - function d3_time_parseZone(date, string, i) { - return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, - i + 5) : -1; + function d3_ease_cubic(t) { + return t * t * t; } - function d3_time_expandYear(d) { - return d + (d > 68 ? 1900 : 2e3); + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); } - function d3_time_parseMonthNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; } - function d3_time_parseDay(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.d = +n[0], i + n[0].length) : -1; + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); } - function d3_time_parseDayOfYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.j = +n[0], i + n[0].length) : -1; + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); } - function d3_time_parseHour24(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.H = +n[0], i + n[0].length) : -1; + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); } - function d3_time_parseMinutes(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.M = +n[0], i + n[0].length) : -1; + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; } - function d3_time_parseSeconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.S = +n[0], i + n[0].length) : -1; + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; } - function d3_time_parseMilliseconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.L = +n[0], i + n[0].length) : -1; + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } - function d3_time_zone(d) { - var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; - return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; } - function d3_time_parseLiteralPercent(date, string, i) { - d3_time_percentRe.lastIndex = 0; - var n = d3_time_percentRe.exec(string.slice(i, i + 1)); - return n ? i + n[0].length : -1; + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; } - function d3_time_formatMulti(formats) { - var n = formats.length, i = -1; - while (++i < n) formats[i][0] = this(formats[i][0]); - return function(date) { - var i = 0, f = formats[i]; - while (!f[1](date)) f = formats[++i]; - return f[0](date); + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; }; } - d3.locale = function(locale) { - return { - numberFormat: d3_locale_numberFormat(locale), - timeFormat: d3_locale_timeFormat(locale) + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); }; - }; - var d3_locale_enUS = d3.locale({ - decimal: ".", - thousands: ",", - grouping: [ 3 ], - currency: [ "$", "" ], - dateTime: "%a %b %e %X %Y", - date: "%m/%d/%Y", - time: "%H:%M:%S", - periods: [ "AM", "PM" ], - days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], - shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], - months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], - shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] - }); - d3.format = d3_locale_enUS.numberFormat; - d3.geo = {}; - function d3_adder() {} - d3_adder.prototype = { - s: 0, - t: 0, - add: function(y) { - d3_adderSum(y, this.t, d3_adderTemp); - d3_adderSum(d3_adderTemp.s, this.s, this); - if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; - }, - reset: function() { - this.s = this.t = 0; - }, - valueOf: function() { - return this.s; - } - }; - var d3_adderTemp = new d3_adder(); - function d3_adderSum(a, b, o) { - var x = o.s = a + b, bv = x - a, av = x - bv; - o.t = a - av + (b - bv); } - d3.geo.stream = function(object, listener) { - if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { - d3_geo_streamObjectType[object.type](object, listener); - } else { - d3_geo_streamGeometry(object, listener); - } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); }; - function d3_geo_streamGeometry(geometry, listener) { - if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { - d3_geo_streamGeometryType[geometry.type](geometry, listener); + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; } - var d3_geo_streamObjectType = { - Feature: function(feature, listener) { - d3_geo_streamGeometry(feature.geometry, listener); - }, - FeatureCollection: function(object, listener) { - var features = object.features, i = -1, n = features.length; - while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); - } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; }; - var d3_geo_streamGeometryType = { - Sphere: function(object, listener) { - listener.sphere(); - }, - Point: function(object, listener) { - object = object.coordinates; - listener.point(object[0], object[1], object[2]); - }, - MultiPoint: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); - }, - LineString: function(object, listener) { - d3_geo_streamLine(object.coordinates, listener, 0); - }, - MultiLineString: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); - }, - Polygon: function(object, listener) { - d3_geo_streamPolygon(object.coordinates, listener); - }, - MultiPolygon: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); - }, - GeometryCollection: function(object, listener) { - var geometries = object.geometries, i = -1, n = geometries.length; - while (++i < n) d3_geo_streamGeometry(geometries[i], listener); + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; } - }; - function d3_geo_streamLine(coordinates, listener, closed) { - var i = -1, n = coordinates.length - closed, coordinate; - listener.lineStart(); - while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); - listener.lineEnd(); + return k; } - function d3_geo_streamPolygon(coordinates, listener) { - var i = -1, n = coordinates.length; - listener.polygonStart(); - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); - listener.polygonEnd(); + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; } - d3.geo.area = function(object) { - d3_geo_areaSum = 0; - d3.geo.stream(object, d3_geo_area); - return d3_geo_areaSum; + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 }; - var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); - var d3_geo_area = { - sphere: function() { - d3_geo_areaSum += 4 * π; - }, - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_areaRingSum.reset(); - d3_geo_area.lineStart = d3_geo_areaRingStart; - }, - polygonEnd: function() { - var area = 2 * d3_geo_areaRingSum; - d3_geo_areaSum += area < 0 ? 4 * π + area : area; - d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + d3.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransformPop(s) { + return s.length ? s.pop() + "," : ""; + } + function d3_interpolateTranslate(ta, tb, s, q) { + if (ta[0] !== tb[0] || ta[1] !== tb[1]) { + var i = s.push("translate(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); } - }; - function d3_geo_areaRingStart() { - var λ00, φ00, λ0, cosφ0, sinφ0; - d3_geo_area.point = function(λ, φ) { - d3_geo_area.point = nextPoint; - λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), - sinφ0 = Math.sin(φ); - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - φ = φ * d3_radians / 2 + π / 4; - var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); - d3_geo_areaRingSum.add(Math.atan2(v, u)); - λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + function d3_interpolateRotate(ra, rb, s, q) { + if (ra !== rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); } - d3_geo_area.lineEnd = function() { - nextPoint(λ00, φ00); - }; } - function d3_geo_cartesian(spherical) { - var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); - return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + function d3_interpolateSkew(wa, wb, s, q) { + if (wa !== wb) { + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + } } - function d3_geo_cartesianDot(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + function d3_interpolateScale(ka, kb, s, q) { + if (ka[0] !== kb[0] || ka[1] !== kb[1]) { + var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] !== 1 || kb[1] !== 1) { + s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + } } - function d3_geo_cartesianCross(a, b) { - return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + function d3_interpolateTransform(a, b) { + var s = [], q = []; + a = d3.transform(a), b = d3.transform(b); + d3_interpolateTranslate(a.translate, b.translate, s, q); + d3_interpolateRotate(a.rotate, b.rotate, s, q); + d3_interpolateSkew(a.skew, b.skew, s, q); + d3_interpolateScale(a.scale, b.scale, s, q); + a = b = null; + return function(t) { + var i = -1, n = q.length, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; } - function d3_geo_cartesianAdd(a, b) { - a[0] += b[0]; - a[1] += b[1]; - a[2] += b[2]; + function d3_uninterpolateNumber(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return (x - a) / b; + }; } - function d3_geo_cartesianScale(vector, k) { - return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + function d3_uninterpolateClamp(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return Math.max(0, Math.min(1, (x - a) / b)); + }; } - function d3_geo_cartesianNormalize(d) { - var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); - d[0] /= l; - d[1] /= l; - d[2] /= l; + d3.layout = {}; + d3.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; } - function d3_geo_spherical(cartesian) { - return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; } - function d3_geo_sphericalEqual(a, b) { - return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; } - d3.geo.bounds = function() { - var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; - var bound = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - bound.point = ringPoint; - bound.lineStart = ringStart; - bound.lineEnd = ringEnd; - dλSum = 0; - d3_geo_area.polygonStart(); - }, - polygonEnd: function() { - d3_geo_area.polygonEnd(); - bound.point = point; - bound.lineStart = lineStart; - bound.lineEnd = lineEnd; - if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; - range[0] = λ0, range[1] = λ1; + d3.layout.chord = function() { + var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d3.range(n)); + k += x; } - }; - function point(λ, φ) { - ranges.push(range = [ λ0 = λ, λ1 = λ ]); - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; - } - function linePoint(λ, φ) { - var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); - if (p0) { - var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); - d3_geo_cartesianNormalize(inflection); - inflection = d3_geo_spherical(inflection); - var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; - if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = inflection[1] * d3_degrees; - if (φi > φ1) φ1 = φi; - } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = -inflection[1] * d3_degrees; - if (φi < φ0) φ0 = φi; - } else { - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i) { + d.sort(function(a, b) { + return sortSubgroups(matrix[i][a], matrix[i][b]); + }); + }); + } + k = (τ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; } - if (antimeridian) { - if (λ < λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; - } - } else { - if (λ1 >= λ0) { - if (λ < λ0) λ0 = λ; - if (λ > λ1) λ1 = λ; - } else { - if (λ > λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; - } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: groupSums[di] + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source: source, + target: target + }); } } - } else { - point(λ, φ); } - p0 = p, λ_ = λ; - } - function lineStart() { - bound.point = linePoint; - } - function lineEnd() { - range[0] = λ0, range[1] = λ1; - bound.point = point; - p0 = null; - } - function ringPoint(λ, φ) { - if (p0) { - var dλ = λ - λ_; - dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; - } else λ__ = λ, φ__ = φ; - d3_geo_area.point(λ, φ); - linePoint(λ, φ); - } - function ringStart() { - d3_geo_area.lineStart(); - } - function ringEnd() { - ringPoint(λ__, φ__); - d3_geo_area.lineEnd(); - if (abs(dλSum) > ε) λ0 = -(λ1 = 180); - range[0] = λ0, range[1] = λ1; - p0 = null; - } - function angle(λ0, λ1) { - return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + if (sortChords) resort(); } - function compareRanges(a, b) { - return a[0] - b[0]; + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); } - function withinRange(x, range) { - return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + chord.matrix = function(x) { + if (!arguments.length) return matrix; + n = (matrix = x) && matrix.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d3.layout.force = function() { + var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad, x1, _, x2) { + if (quad.point !== node) { + var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; + if (dw * dw / theta2 < dn) { + if (dn < chargeDistance2) { + var k = quad.charge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + return true; + } + if (quad.point && dn && dn < chargeDistance2) { + var k = quad.pointCharge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad.charge; + }; } - return function(feature) { - φ1 = λ1 = -(λ0 = φ0 = Infinity); - ranges = []; - d3.geo.stream(feature, bound); - var n = ranges.length; - if (n) { - ranges.sort(compareRanges); - for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { - b = ranges[i]; - if (withinRange(b[0], a) || withinRange(b[1], a)) { - if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; - if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; - } else { - merged.push(a = b); + force.tick = function() { + if ((alpha *= .99) < .005) { + timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); } } - var best = -Infinity, dλ; - for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { - b = merged[i]; - if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; } } - ranges = range = null; - return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + event.tick({ + type: "tick", + alpha: alpha + }); }; - }(); - d3.geo.centroid = function(object) { - d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, d3_geo_centroid); - var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; - if (m < ε2) { - x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; - if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; - m = x * x + y * y + z * z; - if (m < ε2) return [ NaN, NaN ]; - } - return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; - }; - var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; - var d3_geo_centroid = { - sphere: d3_noop, - point: d3_geo_centroidPoint, - lineStart: d3_geo_centroidLineStart, - lineEnd: d3_geo_centroidLineEnd, - polygonStart: function() { - d3_geo_centroid.lineStart = d3_geo_centroidRingStart; - }, - polygonEnd: function() { - d3_geo_centroid.lineStart = d3_geo_centroidLineStart; - } - }; - function d3_geo_centroidPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); - } - function d3_geo_centroidPointXYZ(x, y, z) { - ++d3_geo_centroidW0; - d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; - d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; - d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; - } - function d3_geo_centroidLineStart() { - var x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroid.point = nextPoint; - d3_geo_centroidPointXYZ(x0, y0, z0); + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); - } - } - function d3_geo_centroidLineEnd() { - d3_geo_centroid.point = d3_geo_centroidPoint; - } - function d3_geo_centroidRingStart() { - var λ00, φ00, x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ00 = λ, φ00 = φ; - d3_geo_centroid.point = nextPoint; - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroidPointXYZ(x0, y0, z0); + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.chargeDistance = function(x) { + if (!arguments.length) return Math.sqrt(chargeDistance2); + chargeDistance2 = x * x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return Math.sqrt(theta2); + theta2 = x * x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) { + alpha = x; + } else { + timer.c = null, timer.t = NaN, timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + } + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + timer = d3_timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, l = candidates.length, x; + while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); }; - d3_geo_centroid.lineEnd = function() { - nextPoint(λ00, φ00); - d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; - d3_geo_centroid.point = d3_geo_centroidPoint; + force.resume = function() { + return force.alpha(.1); }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); - d3_geo_centroidX2 += v * cx; - d3_geo_centroidY2 += v * cy; - d3_geo_centroidZ2 += v * cz; - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); } + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; } - function d3_geo_compose(a, b) { - function compose(x, y) { - return x = a(x, y), b(x[0], x[1]); - } - if (a.invert && b.invert) compose.invert = function(x, y) { - return x = b.invert(x, y), x && a.invert(x[0], x[1]); - }; - return compose; + function d3_layout_forceDragend(d) { + d.fixed &= ~6; } - function d3_true() { - return true; + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; } - function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { - var subject = [], clip = []; - segments.forEach(function(segment) { - if ((n = segment.length - 1) <= 0) return; - var n, p0 = segment[0], p1 = segment[n]; - if (d3_geo_sphericalEqual(p0, p1)) { - listener.lineStart(); - for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); - listener.lineEnd(); - return; + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; + } + function d3_layout_forceAccumulate(quad, alpha, charges) { + var cx = 0, cy = 0; + quad.charge = 0; + if (!quad.leaf) { + var nodes = quad.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; } - var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); - a.o = b; - subject.push(a); - clip.push(b); - a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); - b = new d3_geo_clipPolygonIntersection(p1, null, a, true); - a.o = b; - subject.push(a); - clip.push(b); - }); - clip.sort(compare); - d3_geo_clipPolygonLinkCircular(subject); - d3_geo_clipPolygonLinkCircular(clip); - if (!subject.length) return; - for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { - clip[i].e = entry = !entry; } - var start = subject[0], points, point; - while (1) { - var current = start, isSubject = true; - while (current.v) if ((current = current.n) === start) return; - points = current.z; - listener.lineStart(); - do { - current.v = current.o.v = true; - if (current.e) { - if (isSubject) { - for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.n.x, 1, listener); + if (quad.point) { + if (!quad.leaf) { + quad.point.x += Math.random() - .5; + quad.point.y += Math.random() - .5; + } + var k = alpha * charges[quad.point.index]; + quad.charge += quad.pointCharge = k; + cx += k * quad.point.x; + cy += k * quad.point.y; + } + quad.cx = cx / quad.charge; + quad.cy = cy / quad.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; + d3.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; + function hierarchy(root) { + var stack = [ root ], nodes = [], node; + root.depth = 0; + while ((node = stack.pop()) != null) { + nodes.push(node); + if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { + var n, childs, child; + while (--n >= 0) { + stack.push(child = childs[n]); + child.parent = node; + child.depth = node.depth + 1; } - current = current.n; + if (value) node.value = 0; + node.children = childs; } else { - if (isSubject) { - points = current.p.z; - for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.p.x, -1, listener); - } - current = current.p; + if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; + delete node.children; } - current = current.o; - points = current.z; - isSubject = !isSubject; - } while (!current.v); - listener.lineEnd(); + } + d3_layout_hierarchyVisitAfter(root, function(node) { + var childs, parent; + if (sort && (childs = node.children)) childs.sort(sort); + if (value && (parent = node.parent)) parent.value += node.value; + }); + return nodes; } + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + if (value) { + d3_layout_hierarchyVisitBefore(root, function(node) { + if (node.children) node.value = 0; + }); + d3_layout_hierarchyVisitAfter(root, function(node) { + var parent; + if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; + if (parent = node.parent) parent.value += node.value; + }); + } + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; } - function d3_geo_clipPolygonLinkCircular(array) { - if (!(n = array.length)) return; - var n, i = 0, a = array[0], b; - while (++i < n) { - a.n = b = array[i]; - b.p = a; - a = b; + function d3_layout_hierarchyVisitBefore(node, callback) { + var nodes = [ node ]; + while ((node = nodes.pop()) != null) { + callback(node); + if ((children = node.children) && (n = children.length)) { + var n, children; + while (--n >= 0) nodes.push(children[n]); + } } - a.n = b = array[0]; - b.p = a; } - function d3_geo_clipPolygonIntersection(point, points, other, entry) { - this.x = point; - this.z = points; - this.o = other; - this.e = entry; - this.v = false; - this.n = this.p = null; + function d3_layout_hierarchyVisitAfter(node, callback) { + var nodes = [ node ], nodes2 = []; + while ((node = nodes.pop()) != null) { + nodes2.push(node); + if ((children = node.children) && (n = children.length)) { + var i = -1, n, children; + while (++i < n) nodes.push(children[i]); + } + } + while ((node = nodes2.pop()) != null) { + callback(node); + } } - function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { - return function(rotate, listener) { - var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - clip.point = pointRing; - clip.lineStart = ringStart; - clip.lineEnd = ringEnd; - segments = []; - polygon = []; - }, - polygonEnd: function() { - clip.point = point; - clip.lineStart = lineStart; - clip.lineEnd = lineEnd; - segments = d3.merge(segments); - var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); - if (segments.length) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); - } else if (clipStartInside) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (polygonStarted) listener.polygonEnd(), polygonStarted = false; - segments = polygon = null; - }, - sphere: function() { - listener.polygonStart(); - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - listener.polygonEnd(); + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; } - }; - function point(λ, φ) { - var point = rotate(λ, φ); - if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); } - function pointLine(λ, φ) { - var point = rotate(λ, φ); - line.point(point[0], point[1]); + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); } - function lineStart() { - clip.point = pointLine; - line.lineStart(); + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; + function pie(data) { + var n = data.length, values = data.map(function(d, i) { + return +value.call(pie, d, i); + }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + index.forEach(function(i) { + arcs[i] = { + data: data[i], + value: v = values[i], + startAngle: a, + endAngle: a += v * k + pa, + padAngle: p + }; + }); + return arcs; + } + pie.value = function(_) { + if (!arguments.length) return value; + value = _; + return pie; + }; + pie.sort = function(_) { + if (!arguments.length) return sort; + sort = _; + return pie; + }; + pie.startAngle = function(_) { + if (!arguments.length) return startAngle; + startAngle = _; + return pie; + }; + pie.endAngle = function(_) { + if (!arguments.length) return endAngle; + endAngle = _; + return pie; + }; + pie.padAngle = function(_) { + if (!arguments.length) return padAngle; + padAngle = _; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + if (!(n = data.length)) return data; + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var m = series[0].length, n, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } } - function lineEnd() { - clip.point = point; - line.lineEnd(); + return data; + } + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } } - var segments; - var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; - function pointRing(λ, φ) { - ring.push([ λ, φ ]); - var point = rotate(λ, φ); - ringListener.point(point[0], point[1]); + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); } - function ringStart() { - ringListener.lineStart(); - ring = []; + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; } - function ringEnd() { - pointRing(ring[0][0], ring[0][1]); - ringListener.lineEnd(); - var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; - ring.pop(); - polygon.push(ring); - ring = null; - if (!n) return; - if (clean & 1) { - segment = ringSegments[0]; - var n = segment.length - 1, i = -1, point; - if (n > 0) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - while (++i < n) listener.point((point = segment[i])[0], point[1]); - listener.lineEnd(); + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; } - return; + s2 += s3 * data[i][j][1]; } - if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); - segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; } - return clip; - }; - } - function d3_geo_clipSegmentLength1(segment) { - return segment.length > 1; - } - function d3_geo_clipBufferListener() { - var lines = [], line; - return { - lineStart: function() { - lines.push(line = []); - }, - point: function(λ, φ) { - line.push([ λ, φ ]); - }, - lineEnd: d3_noop, - buffer: function() { - var buffer = lines; - lines = []; - line = null; - return buffer; - }, - rejoin: function() { - if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; } - }; + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); } - function d3_geo_clipSort(a, b) { - return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; } - var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); - function d3_geo_clipAntimeridianLine(listener) { - var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; - return { - lineStart: function() { - listener.lineStart(); - clean = 1; - }, - point: function(λ1, φ1) { - var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); - if (abs(dλ - π) < ε) { - listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - listener.point(λ1, φ0); - clean = 0; - } else if (sλ0 !== sλ1 && dλ >= π) { - if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; - if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; - φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - clean = 0; - } - listener.point(λ0 = λ1, φ0 = φ1); - sλ0 = sλ1; - }, - lineEnd: function() { - listener.lineEnd(); - λ0 = φ0 = NaN; - }, - clean: function() { - return 2 - clean; + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; } - }; + } + return j; } - function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { - var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); - return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); } - function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { - var φ; - if (from == null) { - φ = direction * halfπ; - listener.point(-π, φ); - listener.point(0, φ); - listener.point(π, φ); - listener.point(π, 0); - listener.point(π, -φ); - listener.point(0, -φ); - listener.point(-π, -φ); - listener.point(-π, 0); - listener.point(-π, φ); - } else if (abs(from[0] - to[0]) > ε) { - var s = from[0] < to[0] ? π : -π; - φ = direction * s / 2; - listener.point(-s, φ); - listener.point(0, φ); - listener.point(s, φ); - } else { - listener.point(to[0], to[1]); - } + function d3_layout_stackSum(p, d) { + return p + d[1]; } - function d3_geo_pointInPolygon(point, polygon) { - var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; - d3_geo_areaRingSum.reset(); - for (var i = 0, n = polygon.length; i < n; ++i) { - var ring = polygon[i], m = ring.length; - if (!m) continue; - var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; - while (true) { - if (j === m) j = 0; - point = ring[j]; - var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; - d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); - polarAngle += antimeridian ? dλ + sdλ * τ : dλ; - if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { - var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); - d3_geo_cartesianNormalize(arc); - var intersection = d3_geo_cartesianCross(meridianNormal, arc); - d3_geo_cartesianNormalize(intersection); - var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); - if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { - winding += antimeridian ^ dλ >= 0 ? 1 : -1; + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); } } - if (!j++) break; - λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; } + return bins; } - return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } - function d3_geo_clipCircle(radius) { - var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); - return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); - function visible(λ, φ) { - return Math.cos(λ) * Math.cos(φ) > cr; - } - function clipLine(listener) { - var point0, c0, v0, v00, clean; - return { - lineStart: function() { - v00 = v0 = false; - clean = 1; - }, - point: function(λ, φ) { - var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; - if (!point0 && (v00 = v0 = v)) listener.lineStart(); - if (v !== v0) { - point2 = intersect(point0, point1); - if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { - point1[0] += ε; - point1[1] += ε; - v = visible(point1[0], point1[1]); - } - } - if (v !== v0) { - clean = 0; - if (v) { - listener.lineStart(); - point2 = intersect(point1, point0); - listener.point(point2[0], point2[1]); - } else { - point2 = intersect(point0, point1); - listener.point(point2[0], point2[1]); - listener.lineEnd(); - } - point0 = point2; - } else if (notHemisphere && point0 && smallRadius ^ v) { - var t; - if (!(c & c0) && (t = intersect(point1, point0, true))) { - clean = 0; - if (smallRadius) { - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - } else { - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - } - } - } - if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { - listener.point(point1[0], point1[1]); - } - point0 = point1, v0 = v, c0 = c; - }, - lineEnd: function() { - if (v0) listener.lineEnd(); - point0 = null; - }, - clean: function() { - return clean | (v00 && v0) << 1; - } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; }; - } - function intersect(a, b, two) { - var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); - var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; - if (!determinant) return !two && a; - var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); - d3_geo_cartesianAdd(A, B); - var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); - if (t2 < 0) return; - var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); - d3_geo_cartesianAdd(q, A); - q = d3_geo_spherical(q); - if (!two) return q; - var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; - if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; - var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; - if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; - if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { - var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); - d3_geo_cartesianAdd(q1, A); - return [ q, d3_geo_spherical(q1) ]; + root.x = root.y = 0; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r -= dr; + }); } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; } - function code(λ, φ) { - var r = smallRadius ? radius : π - radius, code = 0; - if (λ < -r) code |= 1; else if (λ > r) code |= 2; - if (φ < -r) code |= 4; else if (φ > r) code |= 8; - return code; - } - } - function d3_geom_clipLine(x0, y0, x1, y1) { - return function(line) { - var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; - r = x0 - ax; - if (!dx && r > 0) return; - r /= dx; - if (dx < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dx > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = x1 - ax; - if (!dx && r < 0) return; - r /= dx; - if (dx < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dx > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - r = y0 - ay; - if (!dy && r > 0) return; - r /= dy; - if (dy < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dy > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = y1 - ay; - if (!dy && r < 0) return; - r /= dy; - if (dy < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dy > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - if (t0 > 0) line.a = { - x: ax + t0 * dx, - y: ay + t0 * dy - }; - if (t1 < 1) line.b = { - x: ax + t1 * dx, - y: ay + t1 * dy - }; - return line; + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; }; - } - var d3_geo_clipExtentMAX = 1e9; - d3.geo.clipExtent = function() { - var x0, y0, x1, y1, stream, clip, clipExtent = { - stream: function(output) { - if (stream) stream.valid = false; - stream = clip(output); - stream.valid = true; - return stream; - }, - extent: function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); - if (stream) stream.valid = false, stream = null; - return clipExtent; - } + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; }; - return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); }; - function d3_geo_clipExtent(x0, y0, x1, y1) { - return function(listener) { - var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - listener = bufferListener; - segments = []; - polygon = []; - clean = true; - }, - polygonEnd: function() { - listener = listener_; - segments = d3.merge(segments); - var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; - if (inside || visible) { - listener.polygonStart(); - if (inside) { - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (visible) { - d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); - } - listener.polygonEnd(); - } - segments = polygon = ring = null; - } - }; - function insidePolygon(p) { - var wn = 0, n = polygon.length, y = p[1]; - for (var i = 0; i < n; ++i) { - for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { - b = v[j]; - if (a[1] <= y) { - if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; - } else { - if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; - } - a = b; - } - } - return wn !== 0; - } - function interpolate(from, to, direction, listener) { - var a = 0, a1 = 0; - if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { - do { - listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); - } while ((a = (a + direction + 4) % 4) !== a1); - } else { - listener.point(to[0], to[1]); - } - } - function pointVisible(x, y) { - return x0 <= x && x <= x1 && y0 <= y && y <= y1; - } - function point(x, y) { - if (pointVisible(x, y)) listener.point(x, y); - } - var x__, y__, v__, x_, y_, v_, first, clean; - function lineStart() { - clip.point = linePoint; - if (polygon) polygon.push(ring = []); - first = true; - v_ = false; - x_ = y_ = NaN; - } - function lineEnd() { - if (segments) { - linePoint(x__, y__); - if (v__ && v_) bufferListener.rejoin(); - segments.push(bufferListener.buffer()); - } - clip.point = point; - if (v_) listener.lineEnd(); - } - function linePoint(x, y) { - x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); - y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); - var v = pointVisible(x, y); - if (polygon) ring.push([ x, y ]); - if (first) { - x__ = x, y__ = y, v__ = v; - first = false; - if (v) { - listener.lineStart(); - listener.point(x, y); + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } } - } else { - if (v && v_) listener.point(x, y); else { - var l = { - a: { - x: x_, - y: y_ - }, - b: { - x: x, - y: y - } - }; - if (clipLine(l)) { - if (!v_) { - listener.lineStart(); - listener.point(l.a.x, l.a.y); + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; } - listener.point(l.b.x, l.b.y); - if (!v) listener.lineEnd(); - clean = false; - } else if (v) { - listener.lineStart(); - listener.point(x, y); - clean = false; } } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } } - x_ = x, y_ = y, v_ = v; } - return clip; - }; - function corner(p, direction) { - return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; - } - function compare(a, b) { - return comparePoints(a.x, b.x); } - function comparePoints(a, b) { - var ca = corner(a, 1), cb = corner(b, 1); - return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); } - function d3_geo_conic(projectAt) { - var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); - p.parallels = function(_) { - if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; - return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); - }; - return p; + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; } - function d3_geo_conicEqualArea(φ0, φ1) { - var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; - function forward(λ, φ) { - var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; - return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); } - forward.invert = function(x, y) { - var ρ0_y = ρ0 - y; - return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; - }; - return forward; } - (d3.geo.conicEqualArea = function() { - return d3_geo_conic(d3_geo_conicEqualArea); - }).raw = d3_geo_conicEqualArea; - d3.geo.albers = function() { - return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); - }; - d3.geo.albersUsa = function() { - var lower48 = d3.geo.albers(); - var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); - var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); - var point, pointStream = { - point: function(x, y) { - point = [ x, y ]; + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); + d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; + d3_layout_hierarchyVisitBefore(root1, secondWalk); + if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { + var left = root0, right = root0, bottom = root0; + d3_layout_hierarchyVisitBefore(root0, function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); + d3_layout_hierarchyVisitBefore(root0, function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); } - }, lower48Point, alaskaPoint, hawaiiPoint; - function albersUsa(coordinates) { - var x = coordinates[0], y = coordinates[1]; - point = null; - (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); - return point; + return nodes; } - albersUsa.invert = function(coordinates) { - var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; - return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); - }; - albersUsa.stream = function(stream) { - var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); - return { - point: function(x, y) { - lower48Stream.point(x, y); - alaskaStream.point(x, y); - hawaiiStream.point(x, y); - }, - sphere: function() { - lower48Stream.sphere(); - alaskaStream.sphere(); - hawaiiStream.sphere(); - }, - lineStart: function() { - lower48Stream.lineStart(); - alaskaStream.lineStart(); - hawaiiStream.lineStart(); - }, - lineEnd: function() { - lower48Stream.lineEnd(); - alaskaStream.lineEnd(); - hawaiiStream.lineEnd(); - }, - polygonStart: function() { - lower48Stream.polygonStart(); - alaskaStream.polygonStart(); - hawaiiStream.polygonStart(); - }, - polygonEnd: function() { - lower48Stream.polygonEnd(); - alaskaStream.polygonEnd(); - hawaiiStream.polygonEnd(); + function wrapTree(root0) { + var root1 = { + A: null, + children: [ root0 ] + }, queue = [ root1 ], node1; + while ((node1 = queue.pop()) != null) { + for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { + queue.push((children[i] = child = { + _: children[i], + parent: node1, + children: (child = children[i].children) && child.slice() || [], + A: null, + a: null, + z: 0, + m: 0, + c: 0, + s: 0, + t: null, + i: i + }).a = child); } - }; - }; - albersUsa.precision = function(_) { - if (!arguments.length) return lower48.precision(); - lower48.precision(_); - alaska.precision(_); - hawaii.precision(_); - return albersUsa; - }; - albersUsa.scale = function(_) { - if (!arguments.length) return lower48.scale(); - lower48.scale(_); - alaska.scale(_ * .35); - hawaii.scale(_); - return albersUsa.translate(lower48.translate()); - }; - albersUsa.translate = function(_) { - if (!arguments.length) return lower48.translate(); - var k = lower48.scale(), x = +_[0], y = +_[1]; - lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; - alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - return albersUsa; - }; - return albersUsa.scale(1070); - }; - var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_pathAreaPolygon = 0; - d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; - }, - polygonEnd: function() { - d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; - d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); - } - }; - function d3_geo_pathAreaRingStart() { - var x00, y00, x0, y0; - d3_geo_pathArea.point = function(x, y) { - d3_geo_pathArea.point = nextPoint; - x00 = x0 = x, y00 = y0 = y; - }; - function nextPoint(x, y) { - d3_geo_pathAreaPolygon += y0 * x - x0 * y; - x0 = x, y0 = y; + } + return root1.children[0]; } - d3_geo_pathArea.lineEnd = function() { - nextPoint(x00, y00); - }; - } - var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; - var d3_geo_pathBounds = { - point: d3_geo_pathBoundsPoint, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop - }; - function d3_geo_pathBoundsPoint(x, y) { - if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; - if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; - if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; - if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; - } - function d3_geo_pathBuffer() { - var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointCircle = d3_geo_pathBufferCircle(_); - return stream; - }, - result: function() { - if (buffer.length) { - var result = buffer.join(""); - buffer = []; - return result; + function firstWalk(v) { + var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; + if (children.length) { + d3_layout_treeShift(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; } + } else if (w) { + v.z = w.z + separation(v._, w._); } - }; - function point(x, y) { - buffer.push("M", x, ",", y, pointCircle); - } - function pointLineStart(x, y) { - buffer.push("M", x, ",", y); - stream.point = pointLine; - } - function pointLine(x, y) { - buffer.push("L", x, ",", y); + v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } - function lineEnd() { - stream.point = point; + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; } - function lineEndPolygon() { - buffer.push("Z"); + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !d3_layout_treeRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; } - return stream; - } - function d3_geo_pathBufferCircle(radius) { - return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; - } - var d3_geo_pathCentroid = { - point: d3_geo_pathCentroidPoint, - lineStart: d3_geo_pathCentroidLineStart, - lineEnd: d3_geo_pathCentroidLineEnd, - polygonStart: function() { - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; - }, - polygonEnd: function() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; - d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + function sizeNode(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null ? sizeNode : null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) == null ? null : sizeNode; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); }; - function d3_geo_pathCentroidPoint(x, y) { - d3_geo_centroidX0 += x; - d3_geo_centroidY0 += y; - ++d3_geo_centroidZ0; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; } - function d3_geo_pathCentroidLineStart() { - var x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - } + function d3_layout_treeLeft(v) { + var children = v.children; + return children.length ? children[0] : v.t; } - function d3_geo_pathCentroidLineEnd() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + function d3_layout_treeRight(v) { + var children = v.children, n; + return (n = children.length) ? children[n - 1] : v.t; } - function d3_geo_pathCentroidRingStart() { - var x00, y00, x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - z = y0 * x - x0 * y; - d3_geo_centroidX2 += z * (x0 + x); - d3_geo_centroidY2 += z * (y0 + y); - d3_geo_centroidZ2 += z * 3; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - } - d3_geo_pathCentroid.lineEnd = function() { - nextPoint(x00, y00); - }; + function d3_layout_treeMove(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; } - function d3_geo_pathContext(context) { - var pointRadius = 4.5; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointRadius = _; - return stream; - }, - result: d3_noop - }; - function point(x, y) { - context.moveTo(x + pointRadius, y); - context.arc(x, y, pointRadius, 0, τ); - } - function pointLineStart(x, y) { - context.moveTo(x, y); - stream.point = pointLine; - } - function pointLine(x, y) { - context.lineTo(x, y); - } - function lineEnd() { - stream.point = point; + function d3_layout_treeShift(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); } - function lineEndPolygon() { - context.closePath(); + } + function d3_layout_treeAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; + } + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_hierarchyVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; } - return stream; + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); } - function d3_geo_resample(project) { - var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; - function resample(stream) { - return (maxDepth ? resampleRecursive : resampleNone)(stream); - } - function resampleNone(stream) { - return d3_geo_transformPoint(stream, function(x, y) { - x = project(x, y); - stream.point(x[0], x[1]); - }); + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } } - function resampleRecursive(stream) { - var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; - var resample = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - stream.polygonStart(); - resample.lineStart = ringStart; - }, - polygonEnd: function() { - stream.polygonEnd(); - resample.lineStart = lineStart; + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } } - }; - function point(x, y) { - x = project(x, y); - stream.point(x[0], x[1]); - } - function lineStart() { - x0 = NaN; - resample.point = linePoint; - stream.lineStart(); - } - function linePoint(λ, φ) { - var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); - resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); - stream.point(x0, y0); - } - function lineEnd() { - resample.point = point; - stream.lineEnd(); - } - function ringStart() { - lineStart(); - resample.point = ringPoint; - resample.lineEnd = ringEnd; + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); } - function ringPoint(λ, φ) { - linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; - resample.point = linePoint; + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); } - function ringEnd() { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); - resample.lineEnd = lineEnd; - lineEnd(); + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; } - return resample; + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; } - function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { - var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; - if (d2 > 4 * δ2 && depth--) { - var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; - if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); - stream.point(x2, y2); - resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; + } else { + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; } } - resample.precision = function(_) { - if (!arguments.length) return Math.sqrt(δ2); - maxDepth = (δ2 = _ * _) > 0 && 16; - return resample; - }; - return resample; - } - d3.geo.path = function() { - var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; - function path(object) { - if (object) { - if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); - if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); - d3.geo.stream(object, cacheStream); - } - return contextStream.result(); + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = root.y = 0; + if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; } - path.area = function(object) { - d3_geo_pathAreaSum = 0; - d3.geo.stream(object, projectStream(d3_geo_pathArea)); - return d3_geo_pathAreaSum; + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; }; - path.centroid = function(object) { - d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); - return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; }; - path.bounds = function(object) { - d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); - d3.geo.stream(object, projectStream(d3_geo_pathBounds)); - return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; }; - path.projection = function(_) { - if (!arguments.length) return projection; - projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; - return reset(); + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; }; - path.context = function(_) { - if (!arguments.length) return context; - contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); - if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); - return reset(); + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; }; - path.pointRadius = function(_) { - if (!arguments.length) return pointRadius; - pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); - return path; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; }; - function reset() { - cacheStream = null; - return path; - } - return path.projection(d3.geo.albersUsa()).context(null); + return d3_layout_hierarchyRebind(treemap, hierarchy); }; - function d3_geo_pathProjectStream(project) { - var resample = d3_geo_resample(function(x, y) { - return project([ x * d3_degrees, y * d3_degrees ]); - }); - return function(stream) { - return d3_geo_projectionRadians(resample(stream)); + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy }; } - d3.geo.transform = function(methods) { + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } return { - stream: function(stream) { - var transform = new d3_geo_transform(stream); - for (var k in methods) transform[k] = methods[k]; - return transform; - } + x: x, + y: y, + dx: dx, + dy: dy }; - }; - function d3_geo_transform(stream) { - this.stream = stream; } - d3_geo_transform.prototype = { - point: function(x, y) { - this.stream.point(x, y); - }, - sphere: function() { - this.stream.sphere(); - }, - lineStart: function() { - this.stream.lineStart(); + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; }, - lineEnd: function() { - this.stream.lineEnd(); + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; }, - polygonStart: function() { - this.stream.polygonStart(); + bates: function(m) { + var random = d3.random.irwinHall(m); + return function() { + return random() / m; + }; }, - polygonEnd: function() { - this.stream.polygonEnd(); + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; } }; - function d3_geo_transformPoint(stream, point) { - return { - point: point, - sphere: function() { - stream.sphere(); - }, - lineStart: function() { - stream.lineStart(); - }, - lineEnd: function() { - stream.lineEnd(); - }, - polygonStart: function() { - stream.polygonStart(); + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; + } + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); + } + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; }, - polygonEnd: function() { - stream.polygonEnd(); + ceil: function(x) { + return Math.ceil(x / step) * step; } - }; + } : d3_scale_niceIdentity; } - d3.geo.projection = d3_geo_projection; - d3.geo.projectionMutator = d3_geo_projectionMutator; - function d3_geo_projection(project) { - return d3_geo_projectionMutator(function() { - return project; - })(); + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; } - function d3_geo_projectionMutator(projectAt) { - var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { - x = project(x, y); - return [ x[0] * k + δx, δy - x[1] * k ]; - }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; - function projection(point) { - point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); - return [ point[0] * k + δx, δy - point[1] * k ]; + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; } - function invert(point) { - point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); - return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; + function scale(x) { + return output(x); } - projection.stream = function(output) { - if (stream) stream.valid = false; - stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); - stream.valid = true; - return stream; + scale.invert = function(y) { + return input(y); }; - projection.clipAngle = function(_) { - if (!arguments.length) return clipAngle; - preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); - return invalidate(); + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); }; - projection.clipExtent = function(_) { - if (!arguments.length) return clipExtent; - clipExtent = _; - postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; - return invalidate(); + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); }; - projection.scale = function(_) { - if (!arguments.length) return k; - k = +_; - return reset(); + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); }; - projection.translate = function(_) { - if (!arguments.length) return [ x, y ]; - x = +_[0]; - y = +_[1]; - return reset(); + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); }; - projection.center = function(_) { - if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; - λ = _[0] % 360 * d3_radians; - φ = _[1] % 360 * d3_radians; - return reset(); + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); }; - projection.rotate = function(_) { - if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; - δλ = _[0] % 360 * d3_radians; - δφ = _[1] % 360 * d3_radians; - δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; - return reset(); + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); }; - d3.rebind(projection, projectResample, "precision"); - function reset() { - projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); - var center = project(λ, φ); - δx = x - center[0] * k; - δy = y + center[1] * k; - return invalidate(); - } - function invalidate() { - if (stream) stream.valid = false, stream = null; - return projection; - } - return function() { - project = projectAt.apply(this, arguments); - projection.invert = project.invert && invert; - return reset(); + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); }; + return rescale(); } - function d3_geo_projectionRadians(stream) { - return d3_geo_transformPoint(stream, function(x, y) { - stream.point(x * d3_radians, y * d3_radians); - }); + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } - function d3_geo_equirectangular(λ, φ) { - return [ λ, φ ]; + function d3_scale_linearNice(domain, m) { + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + return domain; } - (d3.geo.equirectangular = function() { - return d3_geo_projection(d3_geo_equirectangular); - }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; - d3.geo.rotation = function(rotate) { - rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); - function forward(coordinates) { - coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - } - forward.invert = function(coordinates) { - coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - }; - return forward; - }; - function d3_geo_identityRotation(λ, φ) { - return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; } - d3_geo_identityRotation.invert = d3_geo_equirectangular; - function d3_geo_rotation(δλ, δφ, δγ) { - return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } - function d3_geo_forwardRotationλ(δλ) { - return function(λ, φ) { - return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; - }; + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + if (format) { + var match = d3_format_re.exec(format); + match.shift(); + if (match[8] === "s") { + var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); + if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); + match[8] = "f"; + format = d3.format(match.join("")); + return function(d) { + return format(prefix.scale(d)) + prefix.symbol; + }; + } + if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); + format = match.join(""); + } else { + format = ",." + d3_scale_linearPrecision(range[2]) + "f"; + } + return d3.format(format); } - function d3_geo_rotationλ(δλ) { - var rotation = d3_geo_forwardRotationλ(δλ); - rotation.invert = d3_geo_forwardRotationλ(-δλ); - return rotation; + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); } - function d3_geo_rotationφγ(δφ, δγ) { - var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); - function rotation(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; - return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + } + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); } - rotation.invert = function(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; - return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); }; - return rotation; - } - d3.geo.circle = function() { - var origin = [ 0, 0 ], angle, precision = 6, interpolate; - function circle() { - var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; - interpolate(null, null, 1, { - point: function(x, y) { - ring.push(x = rotate(x, y)); - x[0] *= d3_degrees, x[1] *= d3_degrees; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); } - }); - return { - type: "Polygon", - coordinates: [ ring ] + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); + } + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(1, base * n / scale.ticks().length); + return function(d) { + var i = d / pow(Math.round(log(d))); + if (i * base < base - .5) i *= base; + return i <= k ? format(d) : ""; }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); } - circle.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return circle; + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); + } + scale.invert = function(x) { + return powb(linear.invert(x)); }; - circle.angle = function(x) { - if (!arguments.length) return angle; - interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); - return circle; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; }; - circle.precision = function(_) { - if (!arguments.length) return precision; - interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); - return circle; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); }; - return circle.angle(90); - }; - function d3_geo_circleInterpolate(radius, precision) { - var cr = Math.cos(radius), sr = Math.sin(radius); - return function(from, to, direction, listener) { - var step = direction * precision; - if (from != null) { - from = d3_geo_circleAngle(cr, from); - to = d3_geo_circleAngle(cr, to); - if (direction > 0 ? from < to : from > to) from += direction * τ; - } else { - from = radius + direction * τ; - to = radius - .5 * step; - } - for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { - listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); - } + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); }; + return d3_scale_linearRebind(scale, linear); } - function d3_geo_circleAngle(cr, point) { - var a = d3_geo_cartesian(point); - a[0] -= cr; - d3_geo_cartesianNormalize(a); - var angle = d3_acos(-a[1]); - return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; } - d3.geo.distance = function(a, b) { - var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; - return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); }; - d3.geo.graticule = function() { - var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; - function graticule() { - return { - type: "MultiLineString", - coordinates: lines() - }; - } - function lines() { - return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { - return abs(x % DX) > ε; - }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { - return abs(y % DY) > ε; - }).map(y)); + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } - graticule.lines = function() { - return lines().map(function(coordinates) { - return { - type: "LineString", - coordinates: coordinates - }; + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; }); + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); }; - graticule.outline = function() { - return { - type: "Polygon", - coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments }; + return scale; }; - graticule.extent = function(_) { - if (!arguments.length) return graticule.minorExtent(); - return graticule.majorExtent(_).minorExtent(_); + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, + 0) : (stop - start) / (domain.length - 1 + padding); + range = steps(start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; }; - graticule.majorExtent = function(_) { - if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; - X0 = +_[0][0], X1 = +_[1][0]; - Y0 = +_[0][1], Y1 = +_[1][1]; - if (X0 > X1) _ = X0, X0 = X1, X1 = _; - if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; - return graticule.precision(precision); + scale.rangeRoundPoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), + 0) : (stop - start) / (domain.length - 1 + padding) | 0; + range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); + rangeBand = 0; + ranger = { + t: "rangeRoundPoints", + a: arguments + }; + return scale; }; - graticule.minorExtent = function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - x0 = +_[0][0], x1 = +_[1][0]; - y0 = +_[0][1], y1 = +_[1][1]; - if (x0 > x1) _ = x0, x0 = x1, x1 = _; - if (y0 > y1) _ = y0, y0 = y1, y1 = _; - return graticule.precision(precision); + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; }; - graticule.step = function(_) { - if (!arguments.length) return graticule.minorStep(); - return graticule.majorStep(_).minorStep(_); + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); + range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; }; - graticule.majorStep = function(_) { - if (!arguments.length) return [ DX, DY ]; - DX = +_[0], DY = +_[1]; - return graticule; + scale.rangeBand = function() { + return rangeBand; }; - graticule.minorStep = function(_) { - if (!arguments.length) return [ dx, dy ]; - dx = +_[0], dy = +_[1]; - return graticule; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); }; - graticule.precision = function(_) { - if (!arguments.length) return precision; - precision = +_; - x = d3_geo_graticuleX(y0, y1, 90); - y = d3_geo_graticuleY(x0, x1, precision); - X = d3_geo_graticuleX(Y0, Y1, 90); - Y = d3_geo_graticuleY(X0, X1, precision); - return graticule; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); }; - return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); }; - function d3_geo_graticuleX(y0, y1, dy) { - var y = d3.range(y0, y1 - ε, dy).concat(y1); - return function(x) { - return y.map(function(y) { - return [ x, y ]; - }); + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); + return rescale(); }; - } - function d3_geo_graticuleY(x0, x1, dx) { - var x = d3.range(x0, x1 - ε, dx).concat(x1); - return function(y) { - return x.map(function(x) { - return [ x, y ]; - }); + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); } - function d3_source(d) { - return d.source; - } - function d3_target(d) { - return d.target; - } - d3.geo.greatArc = function() { - var source = d3_source, source_, target = d3_target, target_; - function greatArc() { - return { - type: "LineString", - coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] - }; + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; } - greatArc.distance = function() { - return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); - }; - greatArc.source = function(_) { - if (!arguments.length) return source; - source = _, source_ = typeof _ === "function" ? null : _; - return greatArc; + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); }; - greatArc.target = function(_) { - if (!arguments.length) return target; - target = _, target_ = typeof _ === "function" ? null : _; - return greatArc; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); }; - greatArc.precision = function() { - return arguments.length ? greatArc : 0; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; }; - return greatArc; - }; - d3.geo.interpolate = function(source, target) { - return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); - }; - function d3_geo_interpolate(x0, y0, x1, y1) { - var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); - var interpolate = d ? function(t) { - var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; - return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; - } : function() { - return [ x0 * d3_degrees, y0 * d3_degrees ]; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); }; - interpolate.distance = d; - return interpolate; + return rescale(); } - d3.geo.length = function(object) { - d3_geo_lengthSum = 0; - d3.geo.stream(object, d3_geo_length); - return d3_geo_lengthSum; - }; - var d3_geo_lengthSum; - var d3_geo_length = { - sphere: d3_noop, - point: d3_noop, - lineStart: d3_geo_lengthLineStart, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); }; - function d3_geo_lengthLineStart() { - var λ0, sinφ0, cosφ0; - d3_geo_length.point = function(λ, φ) { - λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); - d3_geo_length.point = nextPoint; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; }; - d3_geo_length.lineEnd = function() { - d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; }; - function nextPoint(λ, φ) { - var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); - d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); - λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; - } + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; } - function d3_geo_azimuthal(scale, angle) { - function azimuthal(λ, φ) { - var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); - return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; } - azimuthal.invert = function(x, y) { - var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); - return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; }; - return azimuthal; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; } - var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { - return Math.sqrt(2 / (1 + cosλcosφ)); - }, function(ρ) { - return 2 * Math.asin(ρ / 2); - }); - (d3.geo.azimuthalEqualArea = function() { - return d3_geo_projection(d3_geo_azimuthalEqualArea); - }).raw = d3_geo_azimuthalEqualArea; - var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { - var c = Math.acos(cosλcosφ); - return c && c / Math.sin(c); - }, d3_identity); - (d3.geo.azimuthalEquidistant = function() { - return d3_geo_projection(d3_geo_azimuthalEquidistant); - }).raw = d3_geo_azimuthalEquidistant; - function d3_geo_conicConformal(φ0, φ1) { - var cosφ0 = Math.cos(φ0), t = function(φ) { - return Math.tan(π / 4 + φ / 2); - }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; - if (!n) return d3_geo_mercator; - function forward(λ, φ) { - if (F > 0) { - if (φ < -halfπ + ε) φ = -halfπ + ε; + d3.svg = {}; + function d3_zero() { + return 0; + } + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; + function arc() { + var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; + if (r1 < r0) rc = r1, r1 = r0, r0 = rc; + if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; + var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; + if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { + rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); + if (!cw) p1 *= -1; + if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); + if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); + } + if (r1) { + x0 = r1 * Math.cos(a0 + p1); + y0 = r1 * Math.sin(a0 + p1); + x1 = r1 * Math.cos(a1 - p1); + y1 = r1 * Math.sin(a1 - p1); + var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; + if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { + var h1 = (a0 + a1) / 2; + x0 = r1 * Math.cos(h1); + y0 = r1 * Math.sin(h1); + x1 = y1 = null; + } } else { - if (φ > halfπ - ε) φ = halfπ - ε; + x0 = y0 = 0; } - var ρ = F / Math.pow(t(φ), n); - return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; + if (r0) { + x2 = r0 * Math.cos(a1 - p0); + y2 = r0 * Math.sin(a1 - p0); + x3 = r0 * Math.cos(a0 + p0); + y3 = r0 * Math.sin(a0 + p0); + var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; + if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { + var h0 = (a0 + a1) / 2; + x2 = r0 * Math.cos(h0); + y2 = r0 * Math.sin(h0); + x3 = y3 = null; + } + } else { + x2 = y2 = 0; + } + if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var rc1 = rc, rc0 = rc; + if (da < π) { + var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); + rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); + } + if (x1 != null) { + var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); + if (rc === rc1) { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); + } else { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + } else { + path.push("M", x0, ",", y0); + } + if (x3 != null) { + var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); + if (rc === rc0) { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } else { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } + } else { + path.push("L", x2, ",", y2); + } + } else { + path.push("M", x0, ",", y0); + if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); + path.push("L", x2, ",", y2); + if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + } + path.push("Z"); + return path.join(""); } - forward.invert = function(x, y) { - var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); - return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; - }; - return forward; - } - (d3.geo.conicConformal = function() { - return d3_geo_conic(d3_geo_conicConformal); - }).raw = d3_geo_conicConformal; - function d3_geo_conicEquidistant(φ0, φ1) { - var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; - if (abs(n) < ε) return d3_geo_equirectangular; - function forward(λ, φ) { - var ρ = G - φ; - return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; + function circleSegment(r1, cw) { + return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } - forward.invert = function(x, y) { - var ρ0_y = G - y; - return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; }; - return forward; - } - (d3.geo.conicEquidistant = function() { - return d3_geo_conic(d3_geo_conicEquidistant); - }).raw = d3_geo_conicEquidistant; - var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / cosλcosφ; - }, Math.atan); - (d3.geo.gnomonic = function() { - return d3_geo_projection(d3_geo_gnomonic); - }).raw = d3_geo_gnomonic; - function d3_geo_mercator(λ, φ) { - return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; - } - d3_geo_mercator.invert = function(x, y) { - return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; - }; - function d3_geo_mercatorProjection(project) { - var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; - m.scale = function() { - var v = scale.apply(m, arguments); - return v === m ? clipAuto ? m.clipExtent(null) : m : v; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; }; - m.translate = function() { - var v = translate.apply(m, arguments); - return v === m ? clipAuto ? m.clipExtent(null) : m : v; + arc.cornerRadius = function(v) { + if (!arguments.length) return cornerRadius; + cornerRadius = d3_functor(v); + return arc; }; - m.clipExtent = function(_) { - var v = clipExtent.apply(m, arguments); - if (v === m) { - if (clipAuto = _ == null) { - var k = π * scale(), t = translate(); - clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); - } - } else if (clipAuto) { - v = null; - } - return v; + arc.padRadius = function(v) { + if (!arguments.length) return padRadius; + padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); + return arc; }; - return m.clipExtent(null); - } - (d3.geo.mercator = function() { - return d3_geo_mercatorProjection(d3_geo_mercator); - }).raw = d3_geo_mercator; - var d3_geo_orthographic = d3_geo_azimuthal(function() { - return 1; - }, Math.asin); - (d3.geo.orthographic = function() { - return d3_geo_projection(d3_geo_orthographic); - }).raw = d3_geo_orthographic; - var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / (1 + cosλcosφ); - }, function(ρ) { - return 2 * Math.atan(ρ); - }); - (d3.geo.stereographic = function() { - return d3_geo_projection(d3_geo_stereographic); - }).raw = d3_geo_stereographic; - function d3_geo_transverseMercator(λ, φ) { - return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; - } - d3_geo_transverseMercator.invert = function(x, y) { - return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; - }; - (d3.geo.transverseMercator = function() { - var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; - projection.center = function(_) { - return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; }; - projection.rotate = function(_) { - return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), - [ _[0], _[1], _[2] - 90 ]); + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; }; - return rotate([ 0, 0, 90 ]); - }).raw = d3_geo_transverseMercator; - d3.geom = {}; - function d3_geom_pointX(d) { - return d[0]; - } - function d3_geom_pointY(d) { - return d[1]; - } - d3.geom.hull = function(vertices) { - var x = d3_geom_pointX, y = d3_geom_pointY; - if (arguments.length) return hull(vertices); - function hull(data) { - if (data.length < 3) return []; - var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; - for (i = 0; i < n; i++) { - points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); - } - points.sort(d3_geom_hullOrder); - for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); - var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); - var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; - for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); - for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); - return polygon; - } - hull.x = function(_) { - return arguments.length ? (x = _, hull) : x; + arc.padAngle = function(v) { + if (!arguments.length) return padAngle; + padAngle = d3_functor(v); + return arc; }; - hull.y = function(_) { - return arguments.length ? (y = _, hull) : y; + arc.centroid = function() { + var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; + return [ Math.cos(a) * r, Math.sin(a) * r ]; }; - return hull; + return arc; }; - function d3_geom_hullUpper(points) { - var n = points.length, hull = [ 0, 1 ], hs = 2; - for (var i = 2; i < n; i++) { - while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; - hull[hs++] = i; - } - return hull.slice(0, hs); + var d3_svg_arcAuto = "auto"; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; } - function d3_geom_hullOrder(a, b) { - return a[0] - b[0] || a[1] - b[1]; + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; } - d3.geom.polygon = function(coordinates) { - d3_subclass(coordinates, d3_geom_polygonPrototype); - return coordinates; - }; - var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; - d3_geom_polygonPrototype.area = function() { - var i = -1, n = this.length, a, b = this[n - 1], area = 0; - while (++i < n) { - a = b; - b = this[i]; - area += a[1] * b[0] - a[0] * b[1]; - } - return area * .5; - }; - d3_geom_polygonPrototype.centroid = function(k) { - var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; - if (!arguments.length) k = -1 / (6 * this.area()); - while (++i < n) { - a = b; - b = this[i]; - c = a[0] * b[1] - b[0] * a[1]; - x += (a[0] + b[0]) * c; - y += (a[1] + b[1]) * c; - } - return [ x * k, y * k ]; - }; - d3_geom_polygonPrototype.clip = function(subject) { - var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; - while (++i < n) { - input = subject.slice(); - subject.length = 0; - b = this[i]; - c = input[(m = input.length - closed) - 1]; - j = -1; - while (++j < m) { - d = input[j]; - if (d3_geom_polygonInside(d, a, b)) { - if (!d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - subject.push(d); - } else if (d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_arcPadAngle(d) { + return d && d.padAngle; + } + function d3_svg_arcSweep(x0, y0, x1, y1) { + return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + } + function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { + var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; + if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; + return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; } - c = d; } - if (closed) subject.push(subject[0]); - a = b; + if (points.length) segment(); + return segments.length ? segments.join("") : null; } - return subject; + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); }; - function d3_geom_polygonInside(p, a, b) { - return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.length > 1 ? points.join("L") : points + "Z"; } - function d3_geom_polygonIntersect(c, d, a, b) { - var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); - return [ x1 + ua * x21, y1 + ua * y21 ]; + function d3_svg_lineLinearClosed(points) { + return points.join("L") + "Z"; } - function d3_geom_polygonClosed(coordinates) { - var a = coordinates[0], b = coordinates[coordinates.length - 1]; - return !(a[0] - b[0] || a[1] - b[1]); + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); } - var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; - function d3_geom_voronoiBeach() { - d3_geom_voronoiRedBlackNode(this); - this.edge = this.site = this.circle = null; + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); } - function d3_geom_voronoiCreateBeach(site) { - var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); - beach.site = site; - return beach; + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); } - function d3_geom_voronoiDetachBeach(beach) { - d3_geom_voronoiDetachCircle(beach); - d3_geom_voronoiBeaches.remove(beach); - d3_geom_voronoiBeachPool.push(beach); - d3_geom_voronoiRedBlackNode(beach); + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); } - function d3_geom_voronoiRemoveBeach(beach) { - var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { - x: x, - y: y - }, previous = beach.P, next = beach.N, disappearing = [ beach ]; - d3_geom_voronoiDetachBeach(beach); - var lArc = previous; - while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { - previous = lArc.P; - disappearing.unshift(lArc); - d3_geom_voronoiDetachBeach(lArc); - lArc = previous; - } - disappearing.unshift(lArc); - d3_geom_voronoiDetachCircle(lArc); - var rArc = next; - while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { - next = rArc.N; - disappearing.push(rArc); - d3_geom_voronoiDetachBeach(rArc); - rArc = next; + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); } - disappearing.push(rArc); - d3_geom_voronoiDetachCircle(rArc); - var nArcs = disappearing.length, iArc; - for (iArc = 1; iArc < nArcs; ++iArc) { - rArc = disappearing[iArc]; - lArc = disappearing[iArc - 1]; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; } - lArc = disappearing[0]; - rArc = disappearing[nArcs - 1]; - rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - } - function d3_geom_voronoiAddBeach(site) { - var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; - while (node) { - dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; - if (dxl > ε) node = node.L; else { - dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); - if (dxr > ε) { - if (!node.R) { - lArc = node; - break; - } - node = node.R; - } else { - if (dxl > -ε) { - lArc = node.P; - rArc = node; - } else if (dxr > -ε) { - lArc = node; - rArc = node.N; - } else { - lArc = rArc = node; - } - break; - } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; } } - var newArc = d3_geom_voronoiCreateBeach(site); - d3_geom_voronoiBeaches.insert(lArc, newArc); - if (!lArc && !rArc) return; - if (lArc === rArc) { - d3_geom_voronoiDetachCircle(lArc); - rArc = d3_geom_voronoiCreateBeach(lArc.site); - d3_geom_voronoiBeaches.insert(newArc, rArc); - newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - return; - } - if (!rArc) { - newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - return; + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; } - d3_geom_voronoiDetachCircle(lArc); - d3_geom_voronoiDetachCircle(rArc); - var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { - x: (cy * hb - by * hc) / d + ax, - y: (bx * hc - cx * hb) / d + ay - }; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); - newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); - rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); + return path; } - function d3_geom_voronoiLeftBreakPoint(arc, directrix) { - var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; - if (!pby2) return rfocx; - var lArc = arc.P; - if (!lArc) return -Infinity; - site = lArc.site; - var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; - if (!plby2) return lfocx; - var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; - if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; - return (rfocx + lfocx) / 2; + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; } - function d3_geom_voronoiRightBreakPoint(arc, directrix) { - var rArc = arc.N; - if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); - var site = arc.site; - return site.y === directrix ? site.x : Infinity; + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); } - function d3_geom_voronoiCell(site) { - this.site = site; - this.edges = []; + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); } - d3_geom_voronoiCell.prototype.prepare = function() { - var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; - while (iHalfEdge--) { - edge = halfEdges[iHalfEdge].edge; - if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); } - halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); - return halfEdges.length; - }; - function d3_geom_voronoiCloseCells(extent) { - var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; - while (iCell--) { - cell = cells[iCell]; - if (!cell || !cell.prepare()) continue; - halfEdges = cell.edges; - nHalfEdges = halfEdges.length; - iHalfEdge = 0; - while (iHalfEdge < nHalfEdges) { - end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; - start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; - if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { - halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { - x: x0, - y: abs(x2 - x0) < ε ? y2 : y1 - } : abs(y3 - y1) < ε && x1 - x3 > ε ? { - x: abs(y2 - y1) < ε ? x2 : x1, - y: y1 - } : abs(x3 - x1) < ε && y3 - y0 > ε ? { - x: x1, - y: abs(x2 - x1) < ε ? y2 : y0 - } : abs(y3 - y0) < ε && x3 - x0 > ε ? { - x: abs(y2 - y0) < ε ? x2 : x0, - y: y0 - } : null), cell.site, null)); - ++nHalfEdges; - } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); } } + return d3_svg_lineBasis(points); } - function d3_geom_voronoiHalfEdgeOrder(a, b) { - return b.angle - a.angle; + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } - function d3_geom_voronoiCircle() { - d3_geom_voronoiRedBlackNode(this); - this.x = this.y = this.arc = this.site = this.cy = null; + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); } - function d3_geom_voronoiAttachCircle(arc) { - var lArc = arc.P, rArc = arc.N; - if (!lArc || !rArc) return; - var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; - if (lSite === rSite) return; - var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; - var d = 2 * (ax * cy - ay * cx); - if (d >= -ε2) return; - var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; - var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); - circle.arc = arc; - circle.site = cSite; - circle.x = x + bx; - circle.y = cy + Math.sqrt(x * x + y * y); - circle.cy = cy; - arc.circle = circle; - var before = null, node = d3_geom_voronoiCircles._; - while (node) { - if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { - if (node.L) node = node.L; else { - before = node.P; - break; - } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; } else { - if (node.R) node = node.R; else { - before = node; - break; + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; } } } - d3_geom_voronoiCircles.insert(before, circle); - if (!before) d3_geom_voronoiFirstCircle = circle; - } - function d3_geom_voronoiDetachCircle(arc) { - var circle = arc.circle; - if (circle) { - if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; - d3_geom_voronoiCircles.remove(circle); - d3_geom_voronoiCirclePool.push(circle); - d3_geom_voronoiRedBlackNode(circle); - arc.circle = null; + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); } + return tangents; } - function d3_geom_voronoiClipEdges(extent) { - var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; - while (i--) { - e = edges[i]; - if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { - e.a = e.b = null; - edges.splice(i, 1); - } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] - halfπ; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); } + return points; } - function d3_geom_voronoiConnectEdge(edge, extent) { - var vb = edge.b; - if (vb) return true; - var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; - if (ry === ly) { - if (fx < x0 || fx >= x1) return; - if (lx > rx) { - if (!va) va = { - x: fx, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: fx, - y: y1 - }; - } else { - if (!va) va = { - x: fx, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: fx, - y: y0 - }; + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); } - } else { - fm = (lx - rx) / (ry - ly); - fb = fy - fm * fx; - if (fm < -1 || fm > 1) { - if (lx > rx) { - if (!va) va = { - x: (y0 - fb) / fm, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: (y1 - fb) / fm, - y: y1 - }; - } else { - if (!va) va = { - x: (y1 - fb) / fm, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: (y0 - fb) / fm, - y: y0 - }; - } - } else { - if (ly < ry) { - if (!va) va = { - x: x0, - y: fm * x0 + fb - }; else if (va.x >= x1) return; - vb = { - x: x1, - y: fm * x1 + fb - }; - } else { - if (!va) va = { - x: x1, - y: fm * x1 + fb - }; else if (va.x < x0) return; - vb = { - x: x0, - y: fm * x0 + fb - }; + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; } } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; } - edge.a = va; - edge.b = vb; - return true; + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; } - function d3_geom_voronoiEdge(lSite, rSite) { - this.l = lSite; - this.r = rSite; - this.a = this.b = null; + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; + } + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; } - function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, rSite); - d3_geom_voronoiEdges.push(edge); - if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); - if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); - d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); - d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); - return edge; + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; } - function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, null); - edge.a = va; - edge.b = vb; - d3_geom_voronoiEdges.push(edge); - return edge; + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; } - function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { - if (!edge.a && !edge.b) { - edge.a = vertex; - edge.l = lSite; - edge.r = rSite; - } else if (edge.l === rSite) { - edge.b = vertex; - } else { - edge.a = vertex; + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; } - function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { - var va = edge.a, vb = edge.b; - this.edge = edge; - this.site = lSite; - this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + function d3_svg_symbolType() { + return "circle"; } - d3_geom_voronoiHalfEdge.prototype = { - start: function() { - return this.edge.l === this.site ? this.edge.a : this.edge.b; + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; }, - end: function() { - return this.edge.l === this.site ? this.edge.b : this.edge.a; + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + d3_selectionPrototype.transition = function(name) { + var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); + subgroup.push(node); + } } + return d3_transition(subgroups, ns, id); }; - function d3_geom_voronoiRedBlackTree() { - this._ = null; + d3_selectionPrototype.interrupt = function(name) { + return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); + }; + var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); + function d3_selection_interruptNS(ns) { + return function() { + var lock, activeId, active; + if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { + active.timer.c = null; + active.timer.t = NaN; + if (--lock.count) delete lock[activeId]; else delete this[ns]; + lock.active += .5; + active.event && active.event.interrupt.call(this, this.__data__, active.index); + } + }; } - function d3_geom_voronoiRedBlackNode(node) { - node.U = node.C = node.L = node.R = node.P = node.N = null; + function d3_transition(groups, ns, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.namespace = ns; + groups.id = id; + return groups; } - d3_geom_voronoiRedBlackTree.prototype = { - insert: function(after, node) { - var parent, grandpa, uncle; - if (after) { - node.P = after; - node.N = after.N; - if (after.N) after.N.P = node; - after.N = node; - if (after.R) { - after = after.R; - while (after.L) after = after.L; - after.L = node; + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection, name) { + return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, ns, id, node[ns][id]); + subgroup.push(subnode); } else { - after.R = node; + subgroup.push(null); } - parent = after; - } else if (this._) { - after = d3_geom_voronoiRedBlackFirst(this._); - node.P = null; - node.N = after; - after.P = after.L = node; - parent = after; - } else { - node.P = node.N = null; - this._ = node; - parent = null; } - node.L = node.R = null; - node.U = parent; - node.C = true; - after = node; - while (parent && parent.C) { - grandpa = parent.U; - if (parent === grandpa.L) { - uncle = grandpa.R; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.R) { - d3_geom_voronoiRedBlackRotateLeft(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateRight(this, grandpa); - } - } else { - uncle = grandpa.L; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.L) { - d3_geom_voronoiRedBlackRotateRight(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node[ns][id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); + subgroup.push(subnode); } } - parent = after.U; - } - this._.C = false; - }, - remove: function(node) { - if (node.N) node.N.P = node.P; - if (node.P) node.P.N = node.N; - node.N = node.P = null; - var parent = node.U, sibling, left = node.L, right = node.R, next, red; - if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); - if (parent) { - if (parent.L === node) parent.L = next; else parent.R = next; - } else { - this._ = next; } - if (left && right) { - red = next.C; - next.C = node.C; - next.L = left; - left.U = next; - if (next !== right) { - parent = next.U; - next.U = node.U; - node = next.R; - parent.L = node; - next.R = right; - right.U = next; - } else { - next.U = parent; - parent = next; - node = next.R; + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); } - } else { - red = node.C; - node = next; - } - if (node) node.U = parent; - if (red) return; - if (node && node.C) { - node.C = false; - return; } - do { - if (node === this._) break; - if (node === parent.L) { - sibling = parent.R; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - sibling = parent.R; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.R || !sibling.R.C) { - sibling.L.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateRight(this, sibling); - sibling = parent.R; - } - sibling.C = parent.C; - parent.C = sibling.R.C = false; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - node = this._; - break; - } - } else { - sibling = parent.L; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateRight(this, parent); - sibling = parent.L; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.L || !sibling.L.C) { - sibling.R.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, sibling); - sibling = parent.L; - } - sibling.C = parent.C; - parent.C = sibling.L.C = false; - d3_geom_voronoiRedBlackRotateRight(this, parent); - node = this._; - break; - } - } - sibling.C = true; - node = parent; - parent = parent.U; - } while (!node.C); - if (node) node.C = false; } + return d3_transition(subgroups, this.namespace, this.id); + }; + d3_transitionPrototype.tween = function(name, tween) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) return this.node()[ns][id].tween.get(name); + return d3_selection_each(this, tween == null ? function(node) { + node[ns][id].tween.remove(name); + } : function(node) { + node[ns][id].tween.set(name, tween); + }); + }; + function d3_transition_tween(groups, name, value, tween) { + var id = groups.id, ns = groups.namespace; + return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { + node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); + } : (value = tween(value), function(node) { + node[ns][id].tween.set(name, value); + })); + } + d3_transitionPrototype.attr = function(nameNS, value) { + if (arguments.length < 2) { + for (value in nameNS) this.attr(value, nameNS[value]); + return this; + } + var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); }; - function d3_geom_voronoiRedBlackRotateLeft(tree, node) { - var p = node, q = node.R, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; - } else { - tree._ = q; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; } - q.U = parent; - p.U = q; - p.R = q.L; - if (p.R) p.R.U = p; - q.L = p; + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; } - function d3_geom_voronoiRedBlackRotateRight(tree, node) { - var p = node, q = node.L, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; + d3_transitionPrototype.remove = function() { + var ns = this.namespace; + return this.each("end.transition", function() { + var p; + if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node[ns][id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].delay; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node[ns][id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].duration; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node[ns][id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + try { + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node[ns][id]; + type.call(node, node.__data__, i, j); + }); + } finally { + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } } else { - tree._ = q; + d3_selection_each(this, function(node) { + var transition = node[ns][id]; + (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); + }); } - q.U = parent; - p.U = q; - p.L = q.R; - if (p.L) p.L.U = p; - q.R = p; - } - function d3_geom_voronoiRedBlackFirst(node) { - while (node.L) node = node.L; - return node; - } - function d3_geom_voronoi(sites, bbox) { - var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; - d3_geom_voronoiEdges = []; - d3_geom_voronoiCells = new Array(sites.length); - d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); - d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); - while (true) { - circle = d3_geom_voronoiFirstCircle; - if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { - if (site.x !== x0 || site.y !== y0) { - d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); - d3_geom_voronoiAddBeach(site); - x0 = site.x, y0 = site.y; + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition = node[ns][id0]; + d3_transitionNode(node, i, ns, id1, { + time: transition.time, + ease: transition.ease, + delay: transition.delay + transition.duration, + duration: transition.duration + }); } - site = sites.pop(); - } else if (circle) { - d3_geom_voronoiRemoveBeach(circle.arc); - } else { - break; + subgroup.push(node); } } - if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); - var diagram = { - cells: d3_geom_voronoiCells, - edges: d3_geom_voronoiEdges - }; - d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; - return diagram; - } - function d3_geom_voronoiVertexOrder(a, b) { - return b.y - a.y || b.x - a.x; + return d3_transition(subgroups, ns, id1); + }; + function d3_transitionNamespace(name) { + return name == null ? "__transition__" : "__transition_" + name + "__"; } - d3.geom.voronoi = function(points) { - var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; - if (points) return voronoi(points); - function voronoi(data) { - var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; - d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { - var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { - var s = e.start(); - return [ s.x, s.y ]; - }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; - polygon.point = data[i]; - }); - return polygons; + function d3_transitionNode(node, i, ns, id, inherit) { + var lock = node[ns] || (node[ns] = { + active: 0, + count: 0 + }), transition = lock[id], time, timer, duration, ease, tweens; + function schedule(elapsed) { + var delay = transition.delay; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; } - function sites(data) { - return data.map(function(d, i) { - return { - x: Math.round(fx(d, i) / ε) * ε, - y: Math.round(fy(d, i) / ε) * ε, - i: i - }; + function start(elapsed) { + var activeId = lock.active, active = lock[activeId]; + if (active) { + active.timer.c = null; + active.timer.t = NaN; + --lock.count; + delete lock[activeId]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + for (var cancelId in lock) { + if (+cancelId < id) { + var cancel = lock[cancelId]; + cancel.timer.c = null; + cancel.timer.t = NaN; + --lock.count; + delete lock[cancelId]; + } + } + timer.c = tick; + d3_timer(function() { + if (timer.c && tick(elapsed || 1)) { + timer.c = null; + timer.t = NaN; + } + return 1; + }, 0, time); + lock.active = id; + transition.event && transition.event.start.call(node, node.__data__, i); + tweens = []; + transition.tween.forEach(function(key, value) { + if (value = value.call(node, node.__data__, i)) { + tweens.push(value); + } }); + ease = transition.ease; + duration = transition.duration; } - voronoi.links = function(data) { - return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { - return edge.l && edge.r; - }).map(function(edge) { - return { - source: data[edge.l.i], - target: data[edge.r.i] - }; - }); - }; - voronoi.triangles = function(data) { - var triangles = []; - d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { - var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; - while (++j < m) { - e0 = e1; - s0 = s1; - e1 = edges[j].edge; - s1 = e1.l === site ? e1.r : e1.l; - if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { - triangles.push([ data[i], data[s0.i], data[s1.i] ]); - } + function tick(elapsed) { + var t = elapsed / duration, e = ease(t), n = tweens.length; + while (n > 0) { + tweens[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; + } + } + if (!transition) { + time = inherit.time; + timer = d3_timer(schedule, 0, time); + transition = lock[id] = { + tween: new d3_Map(), + time: time, + timer: timer, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + } + } + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; + if (orient === "bottom" || orient === "top") { + tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; + text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); + } else { + tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; + text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); + pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); + } + lineEnter.attr(y2, sign * innerTickSize); + textEnter.attr(y1, sign * tickSpacing); + lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); + textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1, scale0); } + tickEnter.call(tickTransform, scale0, scale1); + tickUpdate.call(tickTransform, scale1, scale1); }); - return triangles; + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; }; - voronoi.x = function(_) { - return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; }; - voronoi.y = function(_) { - return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = d3_array(arguments); + return axis; }; - voronoi.clipExtent = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; - clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; - return voronoi; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; }; - voronoi.size = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; - return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; }; - return voronoi; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; }; - var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; - function d3_geom_voronoiTriangleArea(a, b, c) { - return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); - } - d3.geom.delaunay = function(vertices) { - return d3.geom.voronoi().triangles(vertices); + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 }; - d3.geom.quadtree = function(points, x1, y1, x2, y2) { - var x = d3_geom_pointX, y = d3_geom_pointY, compat; - if (compat = arguments.length) { - x = d3_geom_quadtreeCompatX; - y = d3_geom_quadtreeCompatY; - if (compat === 3) { - y2 = y1; - x2 = x1; - y1 = x1 = 0; - } - return quadtree(points); + function d3_svg_axisX(selection, x0, x1) { + selection.attr("transform", function(d) { + var v0 = x0(d); + return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; + }); + } + function d3_svg_axisY(selection, y0, y1) { + selection.attr("transform", function(d) { + var v0 = y0(d); + return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; + }); + } + d3.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background = g.selectAll(".background").data([ 0 ]); + background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize = g.selectAll(".resize").data(resizes, d3_identity); + resize.exit().remove(); + resize.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); } - function quadtree(data) { - var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; - if (x1 != null) { - x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; + var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d3.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); } else { - x2_ = y2_ = -(x1_ = y1_ = Infinity); - xs = [], ys = []; - n = data.length; - if (compat) for (i = 0; i < n; ++i) { - d = data[i]; - if (d.x < x1_) x1_ = d.x; - if (d.y < y1_) y1_ = d.y; - if (d.x > x2_) x2_ = d.x; - if (d.y > y2_) y2_ = d.y; - xs.push(d.x); - ys.push(d.y); - } else for (i = 0; i < n; ++i) { - var x_ = +fx(d = data[i], i), y_ = +fy(d, i); - if (x_ < x1_) x1_ = x_; - if (y_ < y1_) y1_ = y_; - if (x_ > x2_) x2_ = x_; - if (y_ > y2_) y2_ = y_; - xs.push(x_); - ys.push(y_); + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d3.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d3.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d3.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); } } - var dx = x2_ - x1_, dy = y2_ - y1_; - if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; - function insert(n, d, x, y, x1, y1, x2, y2) { - if (isNaN(x) || isNaN(y)) return; - if (n.leaf) { - var nx = n.x, ny = n.y; - if (nx != null) { - if (abs(nx - x) + abs(ny - y) < .01) { - insertChild(n, d, x, y, x1, y1, x2, y2); - } else { - var nPoint = n.point; - n.x = n.y = n.point = null; - insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); - insertChild(n, d, x, y, x1, y1, x2, y2); - } + function keyup() { + if (d3.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d3.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d3.event.altKey) { + if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale, i) { + var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; } else { - n.x = x, n.y = y, n.point = d; + max = position; } - } else { - insertChild(n, d, x, y, x1, y1, x2, y2); + } + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; + return true; } } - function insertChild(n, d, x, y, x1, y1, x2, y2) { - var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; - n.leaf = false; - n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); - if (right) x1 = xm; else x2 = xm; - if (below) y1 = ym; else y2 = ym; - insert(n, d, x, y, x1, y1, x2, y2); + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d3.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); } - var root = d3_geom_quadtreeNode(); - root.add = function(d) { - insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); - }; - root.visit = function(f) { - d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); - }; - root.find = function(point) { - return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); - }; - i = -1; - if (x1 == null) { - while (++i < n) { - insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); - } - --i; - } else data.forEach(root.add); - xs = ys = data = d = null; - return root; } - quadtree.x = function(_) { - return arguments.length ? (x = _, quadtree) : x; - }; - quadtree.y = function(_) { - return arguments.length ? (y = _, quadtree) : y; - }; - quadtree.extent = function(_) { - if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], - y2 = +_[1][1]; - return quadtree; + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; }; - quadtree.size = function(_) { - if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; - return quadtree; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; }; - return quadtree; - }; - function d3_geom_quadtreeCompatX(d) { - return d.x; - } - function d3_geom_quadtreeCompatY(d) { - return d.y; - } - function d3_geom_quadtreeNode() { - return { - leaf: true, - nodes: [], - point: null, - x: null, - y: null + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; + return brush; }; - } - function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { - if (!f(node, x1, y1, x2, y2)) { - var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; - if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); - if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); - if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); - if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); - } - } - function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { - var minDistance2 = Infinity, closestPoint; - (function find(node, x1, y1, x2, y2) { - if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; - if (point = node.point) { - var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; - if (distance2 < minDistance2) { - var distance = Math.sqrt(minDistance2 = distance2); - x0 = x - distance, y0 = y - distance; - x3 = x + distance, y3 = y + distance; - closestPoint = point; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } } - } - var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; - for (var i = below << 1 | right, j = i + 4; i < j; ++i) { - if (node = children[i & 3]) switch (i & 3) { - case 0: - find(node, x1, y1, xm, ym); - break; - - case 1: - find(node, xm, y1, x2, ym); - break; - - case 2: - find(node, x1, ym, xm, y2); - break; - - case 3: - find(node, xm, ym, x2, y2); - break; + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } } + return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; } - })(root, x0, y0, x3, y3); - return closestPoint; - } - d3.interpolateRgb = d3_interpolateRgb; - function d3_interpolateRgb(a, b) { - a = d3.rgb(a); - b = d3.rgb(b); - var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; - return function(t) { - return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); - }; - } - d3.interpolateObject = d3_interpolateObject; - function d3_interpolateObject(a, b) { - var i = {}, c = {}, k; - for (k in a) { - if (k in b) { - i[k] = d3_interpolate(a[k], b[k]); - } else { - c[k] = a[k]; + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [ x0, x1 ]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; } - } - for (k in b) { - if (!(k in a)) { - c[k] = b[k]; + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [ y0, y1 ]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; } - } - return function(t) { - for (k in i) c[k] = i[k](t); - return c; - }; - } - d3.interpolateNumber = d3_interpolateNumber; - function d3_interpolateNumber(a, b) { - a = +a, b = +b; - return function(t) { - return a * (1 - t) + b * t; + return brush; }; - } - d3.interpolateString = d3_interpolateString; - function d3_interpolateString(a, b) { - var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; - a = a + "", b = b + ""; - while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { - if ((bs = bm.index) > bi) { - bs = b.slice(bi, bs); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - if ((am = am[0]) === (bm = bm[0])) { - if (s[i]) s[i] += bm; else s[++i] = bm; - } else { - s[++i] = null; - q.push({ - i: i, - x: d3_interpolateNumber(am, bm) - }); + brush.clear = function() { + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; } - bi = d3_interpolate_numberB.lastIndex; - } - if (bi < b.length) { - bs = b.slice(bi); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { - return b(t) + ""; - }) : function() { - return b; - } : (b = q.length, function(t) { - for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }); - } - var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); - d3.interpolate = d3_interpolate; - function d3_interpolate(a, b) { - var i = d3.interpolators.length, f; - while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; - return f; - } - d3.interpolators = [ function(a, b) { - var t = typeof b; - return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); - } ]; - d3.interpolateArray = d3_interpolateArray; - function d3_interpolateArray(a, b) { - var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; - for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); - for (;i < na; ++i) c[i] = a[i]; - for (;i < nb; ++i) c[i] = b[i]; - return function(t) { - for (i = 0; i < n0; ++i) c[i] = x[i](t); - return c; + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; }; + return d3.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; + var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; + var d3_time_formatUtc = d3_time_format.utc; + var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); + d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; + function d3_time_formatIsoNative(date) { + return date.toISOString(); } - var d3_ease_default = function() { - return d3_identity; + d3_time_formatIsoNative.parse = function(string) { + var date = new Date(string); + return isNaN(date) ? null : date; }; - var d3_ease = d3.map({ - linear: d3_ease_default, - poly: d3_ease_poly, - quad: function() { - return d3_ease_quad; - }, - cubic: function() { - return d3_ease_cubic; - }, - sin: function() { - return d3_ease_sin; - }, - exp: function() { - return d3_ease_exp; - }, - circle: function() { - return d3_ease_circle; - }, - elastic: d3_ease_elastic, - back: d3_ease_back, - bounce: function() { - return d3_ease_bounce; - } + d3_time_formatIsoNative.toString = d3_time_formatIso.toString; + d3_time.second = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 1e3) * 1e3); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 1e3); + }, function(date) { + return date.getSeconds(); }); - var d3_ease_mode = d3.map({ - "in": d3_identity, - out: d3_ease_reverse, - "in-out": d3_ease_reflect, - "out-in": function(f) { - return d3_ease_reflect(d3_ease_reverse(f)); - } + d3_time.seconds = d3_time.second.range; + d3_time.seconds.utc = d3_time.second.utc.range; + d3_time.minute = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 6e4) * 6e4); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 6e4); + }, function(date) { + return date.getMinutes(); }); - d3.ease = function(name) { - var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; - t = d3_ease.get(t) || d3_ease_default; - m = d3_ease_mode.get(m) || d3_identity; - return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); - }; - function d3_ease_clamp(f) { - return function(t) { - return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + d3_time.minutes = d3_time.minute.range; + d3_time.minutes.utc = d3_time.minute.utc.range; + d3_time.hour = d3_time_interval(function(date) { + var timezone = date.getTimezoneOffset() / 60; + return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 36e5); + }, function(date) { + return date.getHours(); + }); + d3_time.hours = d3_time.hour.range; + d3_time.hours.utc = d3_time.hour.utc.range; + d3_time.month = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setDate(1); + return date; + }, function(date, offset) { + date.setMonth(date.getMonth() + offset); + }, function(date) { + return date.getMonth(); + }); + d3_time.months = d3_time.month.range; + d3_time.months.utc = d3_time.month.utc.range; + function d3_time_scale(linear, methods, format) { + function scale(x) { + return linear(x); + } + scale.invert = function(x) { + return d3_time_scaleDate(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return linear.domain().map(d3_time_scaleDate); + linear.domain(x); + return scale; + }; + function tickMethod(extent, count) { + var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); + return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { + return d / 31536e6; + }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + } + scale.nice = function(interval, skip) { + var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); + if (method) interval = method[0], skip = method[1]; + function skipped(date) { + return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; + } + return scale.domain(d3_scale_nice(domain, skip > 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); }; - } - function d3_ease_reverse(f) { - return function(t) { - return 1 - f(1 - t); + scale.tickFormat = function() { + return format; }; - } - function d3_ease_reflect(f) { - return function(t) { - return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); }; + return d3_scale_linearRebind(scale, linear); } - function d3_ease_quad(t) { - return t * t; + function d3_time_scaleDate(t) { + return new Date(t); } - function d3_ease_cubic(t) { - return t * t * t; + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { + return d.getMilliseconds(); + } ], [ ":%S", function(d) { + return d.getSeconds(); + } ], [ "%I:%M", function(d) { + return d.getMinutes(); + } ], [ "%I %p", function(d) { + return d.getHours(); + } ], [ "%a %d", function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ "%b %d", function(d) { + return d.getDate() != 1; + } ], [ "%B", function(d) { + return d.getMonth(); + } ], [ "%Y", d3_true ] ]); + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { + return d.getUTCMilliseconds(); + } ], [ ":%S", function(d) { + return d.getUTCSeconds(); + } ], [ "%I:%M", function(d) { + return d.getUTCMinutes(); + } ], [ "%I %p", function(d) { + return d.getUTCHours(); + } ], [ "%a %d", function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ "%b %d", function(d) { + return d.getUTCDate() != 1; + } ], [ "%B", function(d) { + return d.getUTCMonth(); + } ], [ "%Y", d3_true ] ]); + d3_time_scaleUtcMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); } - function d3_ease_cubicInOut(t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - var t2 = t * t, t3 = t2 * t; - return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); } - function d3_ease_poly(e) { - return function(t) { - return Math.pow(t, e); - }; + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; +}(); +},{}],83:[function(require,module,exports){ +arguments[4][76][0].apply(exports,arguments) +},{"dup":76,"robust-orientation":1040,"simplicial-complex":86}],84:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],85:[function(require,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],86:[function(require,module,exports){ +arguments[4][79][0].apply(exports,arguments) +},{"bit-twiddle":84,"dup":79,"union-find":85}],87:[function(require,module,exports){ +"use strict" + +function unique_pred(list, compare) { + var ptr = 1 + , len = list.length + , a=list[0], b=list[0] + for(var i=1; i 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; - }; + var lifted = points.map(function(p, i) { + return [ p[0], i ] + }) + lifted.sort(function(a,b) { + return a[0] - b[0] + }) + var cells = new Array(n - 1) + for(var i=1; i 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; - }; + if(includePointAtInfinity) { + cells.push( + [ -1, cells[0][1], ], + [ cells[n-1][1], -1 ]) } - d3.interpolateLab = d3_interpolateLab; - function d3_interpolateLab(a, b) { - a = d3.lab(a); - b = d3.lab(b); - var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; - return function(t) { - return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; - }; + return cells +} + +function triangulate(points, includePointAtInfinity) { + var n = points.length + if(n === 0) { + return [] } - d3.interpolateRound = d3_interpolateRound; - function d3_interpolateRound(a, b) { - b -= a; - return function(t) { - return Math.round(a + b * t); - }; + + var d = points[0].length + if(d < 1) { + return [] } - d3.transform = function(string) { - var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); - return (d3.transform = function(string) { - if (string != null) { - g.setAttribute("transform", string); - var t = g.transform.baseVal.consolidate(); - } - return new d3_transform(t ? t.matrix : d3_transformIdentity); - })(string); - }; - function d3_transform(m) { - var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; - if (r0[0] * r1[1] < r1[0] * r0[1]) { - r0[0] *= -1; - r0[1] *= -1; - kx *= -1; - kz *= -1; + + //Special case: For 1D we can just sort the points + if(d === 1) { + return triangulate1D(n, points, includePointAtInfinity) + } + + //Lift points, sort + var lifted = new Array(n) + var upper = 1.0 + for(var i=0; i= 2) { + return false + } + } + cell[j] = v + } + return true + }) + } else { + hull = hull.filter(function(cell) { + for(var i=0; i<=d; ++i) { + var v = dindex[cell[i]] + if(v < 0) { + return false + } + cell[i] = v + } + return true + }) } - function d3_interpolateTranslate(ta, tb, s, q) { - if (ta[0] !== tb[0] || ta[1] !== tb[1]) { - var i = s.push("translate(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ta[0], tb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ta[1], tb[1]) - }); - } else if (tb[0] || tb[1]) { - s.push("translate(" + tb + ")"); + + if(d & 1) { + for(var i=0; i 180) rb += 360; else if (rb - ra > 180) ra += 360; - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, - x: d3_interpolateNumber(ra, rb) - }); - } else if (rb) { - s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); + + return hull +} +},{"incremental-convex-hull":83,"uniq":87}],89:[function(require,module,exports){ +(function (process,global){ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.2.1 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); } - } - function d3_interpolateSkew(wa, wb, s, q) { - if (wa !== wb) { - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, - x: d3_interpolateNumber(wa, wb) - }); - } else if (wb) { - s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; } - } - function d3_interpolateScale(ka, kb, s, q) { - if (ka[0] !== kb[0] || ka[1] !== kb[1]) { - var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ka[0], kb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ka[1], kb[1]) - }); - } else if (kb[0] !== 1 || kb[1] !== 1) { - s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; } - } - function d3_interpolateTransform(a, b) { - var s = [], q = []; - a = d3.transform(a), b = d3.transform(b); - d3_interpolateTranslate(a.translate, b.translate, s, q); - d3_interpolateRotate(a.rotate, b.rotate, s, q); - d3_interpolateSkew(a.skew, b.skew, s, q); - d3_interpolateScale(a.scale, b.scale, s, q); - a = b = null; - return function(t) { - var i = -1, n = q.length, o; - while (++i < n) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }; - } - function d3_uninterpolateNumber(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return (x - a) / b; - }; - } - function d3_uninterpolateClamp(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return Math.max(0, Math.min(1, (x - a) / b)); - }; - } - d3.layout = {}; - d3.layout.bundle = function() { - return function(links) { - var paths = [], i = -1, n = links.length; - while (++i < n) paths.push(d3_layout_bundlePath(links[i])); - return paths; - }; - }; - function d3_layout_bundlePath(link) { - var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; - while (start !== lca) { - start = start.parent; - points.push(start); + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; } - var k = points.length; - while (end !== lca) { - points.splice(k, 0, end); - end = end.parent; + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; } - return points; - } - function d3_layout_bundleAncestors(node) { - var ancestors = [], parent = node.parent; - while (parent != null) { - ancestors.push(node); - node = parent; - parent = parent.parent; + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; } - ancestors.push(node); - return ancestors; - } - function d3_layout_bundleLeastCommonAncestor(a, b) { - if (a === b) return a; - var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; - while (aNode === bNode) { - sharedNode = aNode; - aNode = aNodes.pop(); - bNode = bNodes.pop(); + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; } - return sharedNode; - } - d3.layout.chord = function() { - var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; - function relayout() { - var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; - chords = []; - groups = []; - k = 0, i = -1; - while (++i < n) { - x = 0, j = -1; - while (++j < n) { - x += matrix[i][j]; - } - groupSums.push(x); - subgroupIndex.push(d3.range(n)); - k += x; + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; } - if (sortGroups) { - groupIndex.sort(function(a, b) { - return sortGroups(groupSums[a], groupSums[b]); - }); + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); } - if (sortSubgroups) { - subgroupIndex.forEach(function(d, i) { - d.sort(function(a, b) { - return sortSubgroups(matrix[i][a], matrix[i][b]); - }); - }); + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + function lib$es6$promise$then$$then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + + if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { + lib$es6$promise$$internal$$makePromise(child); } - k = (τ - padding * n) / k; - x = 0, i = -1; - while (++i < n) { - x0 = x, j = -1; - while (++j < n) { - var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; - subgroups[di + "-" + dj] = { - index: di, - subindex: dj, - startAngle: a0, - endAngle: a1, - value: v - }; - } - groups[di] = { - index: di, - startAngle: x0, - endAngle: x, - value: groupSums[di] - }; - x += padding; + + var state = parent._state; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); } - i = -1; - while (++i < n) { - j = i - 1; - while (++j < n) { - var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; - if (source.value || target.value) { - chords.push(source.value < target.value ? { - source: target, - target: source - } : { - source: source, - target: target - }); - } - } + + return child; + } + var lib$es6$promise$then$$default = lib$es6$promise$then$$then; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; } - if (sortChords) resort(); + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; } - function resort() { - chords.sort(function(a, b) { - return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); - }); + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); } - chord.matrix = function(x) { - if (!arguments.length) return matrix; - n = (matrix = x) && matrix.length; - chords = groups = null; - return chord; - }; - chord.padding = function(x) { - if (!arguments.length) return padding; - padding = x; - chords = groups = null; - return chord; - }; - chord.sortGroups = function(x) { - if (!arguments.length) return sortGroups; - sortGroups = x; - chords = groups = null; - return chord; - }; - chord.sortSubgroups = function(x) { - if (!arguments.length) return sortSubgroups; - sortSubgroups = x; - chords = null; - return chord; - }; - chord.sortChords = function(x) { - if (!arguments.length) return sortChords; - sortChords = x; - if (chords) resort(); - return chord; - }; - chord.chords = function() { - if (!chords) relayout(); - return chords; - }; - chord.groups = function() { - if (!groups) relayout(); - return groups; - }; - return chord; - }; - d3.layout.force = function() { - var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; - function repulse(node) { - return function(quad, x1, _, x2) { - if (quad.point !== node) { - var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; - if (dw * dw / theta2 < dn) { - if (dn < chargeDistance2) { - var k = quad.charge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - return true; - } - if (quad.point && dn && dn < chargeDistance2) { - var k = quad.pointCharge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - } - return !quad.charge; - }; + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); } - force.tick = function() { - if ((alpha *= .99) < .005) { - timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); - return true; - } - var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; - for (i = 0; i < m; ++i) { - o = links[i]; - s = o.source; - t = o.target; - x = t.x - s.x; - y = t.y - s.y; - if (l = x * x + y * y) { - l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; - x *= l; - y *= l; - t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); - t.y -= y * k; - s.x += x * (k = 1 - k); - s.y += y * k; - } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; } - if (k = alpha * gravity) { - x = size[0] / 2; - y = size[1] / 2; - i = -1; - if (k) while (++i < n) { - o = nodes[i]; - o.x += (x - o.x) * k; - o.y += (y - o.y) * k; - } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; } - if (charge) { - d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); - i = -1; - while (++i < n) { - if (!(o = nodes[i]).fixed) { - q.visit(repulse(o)); + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); } - i = -1; - while (++i < n) { - o = nodes[i]; - if (o.fixed) { - o.x = o.px; - o.y = o.py; - } else { - o.x -= (o.px - (o.px = o.x)) * friction; - o.y -= (o.py - (o.py = o.y)) * friction; - } - } - event.tick({ - type: "tick", - alpha: alpha - }); - }; - force.nodes = function(x) { - if (!arguments.length) return nodes; - nodes = x; - return force; - }; - force.links = function(x) { - if (!arguments.length) return links; - links = x; - return force; - }; - force.size = function(x) { - if (!arguments.length) return size; - size = x; - return force; - }; - force.linkDistance = function(x) { - if (!arguments.length) return linkDistance; - linkDistance = typeof x === "function" ? x : +x; - return force; - }; - force.distance = force.linkDistance; - force.linkStrength = function(x) { - if (!arguments.length) return linkStrength; - linkStrength = typeof x === "function" ? x : +x; - return force; - }; - force.friction = function(x) { - if (!arguments.length) return friction; - friction = +x; - return force; - }; - force.charge = function(x) { - if (!arguments.length) return charge; - charge = typeof x === "function" ? x : +x; - return force; - }; - force.chargeDistance = function(x) { - if (!arguments.length) return Math.sqrt(chargeDistance2); - chargeDistance2 = x * x; - return force; - }; - force.gravity = function(x) { - if (!arguments.length) return gravity; - gravity = +x; - return force; - }; - force.theta = function(x) { - if (!arguments.length) return Math.sqrt(theta2); - theta2 = x * x; - return force; - }; - force.alpha = function(x) { - if (!arguments.length) return alpha; - x = +x; - if (alpha) { - if (x > 0) { - alpha = x; + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === lib$es6$promise$then$$default && + constructor.resolve === lib$es6$promise$promise$resolve$$default) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { - timer.c = null, timer.t = NaN, timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); } - } else if (x > 0) { - event.start({ - type: "start", - alpha: alpha = x - }); - timer = d3_timer(force.tick); } - return force; - }; - force.start = function() { - var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; - for (i = 0; i < n; ++i) { - (o = nodes[i]).index = i; - o.weight = 0; + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); } - for (i = 0; i < m; ++i) { - o = links[i]; - if (typeof o.source == "number") o.source = nodes[o.source]; - if (typeof o.target == "number") o.target = nodes[o.target]; - ++o.source.weight; - ++o.target.weight; + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); } - for (i = 0; i < n; ++i) { - o = nodes[i]; - if (isNaN(o.x)) o.x = position("x", w); - if (isNaN(o.y)) o.y = position("y", h); - if (isNaN(o.px)) o.px = o.x; - if (isNaN(o.py)) o.py = o.y; + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); } - distances = []; - if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; - strengths = []; - if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; - charges = []; - if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; - function position(dimension, size) { - if (!neighbors) { - neighbors = new Array(n); - for (j = 0; j < n; ++j) { - neighbors[j] = []; - } - for (j = 0; j < m; ++j) { - var o = links[j]; - neighbors[o.source.index].push(o.target); - neighbors[o.target.index].push(o.source); - } - } - var candidates = neighbors[i], j = -1, l = candidates.length, x; - while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; - return Math.random() * size; + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); } - return force.resume(); - }; - force.resume = function() { - return force.alpha(.1); - }; - force.stop = function() { - return force.alpha(0); - }; - force.drag = function() { - if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); - if (!arguments.length) return drag; - this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); - }; - function dragmove(d) { - d.px = d3.event.x, d.py = d3.event.y; - force.resume(); } - return d3.rebind(force, event, "on"); - }; - function d3_layout_forceDragstart(d) { - d.fixed |= 2; - } - function d3_layout_forceDragend(d) { - d.fixed &= ~6; - } - function d3_layout_forceMouseover(d) { - d.fixed |= 4; - d.px = d.x, d.py = d.y; - } - function d3_layout_forceMouseout(d) { - d.fixed &= ~4; - } - function d3_layout_forceAccumulate(quad, alpha, charges) { - var cx = 0, cy = 0; - quad.charge = 0; - if (!quad.leaf) { - var nodes = quad.nodes, n = nodes.length, i = -1, c; - while (++i < n) { - c = nodes[i]; - if (c == null) continue; - d3_layout_forceAccumulate(c, alpha, charges); - quad.charge += c.charge; - cx += c.charge * c.cx; - cy += c.charge * c.cy; + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } } + + promise._subscribers.length = 0; } - if (quad.point) { - if (!quad.leaf) { - quad.point.x += Math.random() - .5; - quad.point.y += Math.random() - .5; + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; } - var k = alpha * charges[quad.point.index]; - quad.charge += quad.pointCharge = k; - cx += k * quad.point.x; - cy += k * quad.point.y; } - quad.cx = cx / quad.charge; - quad.cy = cy / quad.charge; - } - var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; - d3.layout.hierarchy = function() { - var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; - function hierarchy(root) { - var stack = [ root ], nodes = [], node; - root.depth = 0; - while ((node = stack.pop()) != null) { - nodes.push(node); - if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { - var n, childs, child; - while (--n >= 0) { - stack.push(child = childs[n]); - child.parent = node; - child.depth = node.depth + 1; - } - if (value) node.value = 0; - node.children = childs; + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; } else { - if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; - delete node.children; + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); } - d3_layout_hierarchyVisitAfter(root, function(node) { - var childs, parent; - if (sort && (childs = node.children)) childs.sort(sort); - if (value && (parent = node.parent)) parent.value += node.value; - }); - return nodes; } - hierarchy.sort = function(x) { - if (!arguments.length) return sort; - sort = x; - return hierarchy; - }; - hierarchy.children = function(x) { - if (!arguments.length) return children; - children = x; - return hierarchy; - }; - hierarchy.value = function(x) { - if (!arguments.length) return value; - value = x; - return hierarchy; - }; - hierarchy.revalue = function(root) { - if (value) { - d3_layout_hierarchyVisitBefore(root, function(node) { - if (node.children) node.value = 0; - }); - d3_layout_hierarchyVisitAfter(root, function(node) { - var parent; - if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; - if (parent = node.parent) parent.value += node.value; + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); }); - } - return root; - }; - return hierarchy; - }; - function d3_layout_hierarchyRebind(object, hierarchy) { - d3.rebind(object, hierarchy, "sort", "children", "value"); - object.nodes = object; - object.links = d3_layout_hierarchyLinks; - return object; - } - function d3_layout_hierarchyVisitBefore(node, callback) { - var nodes = [ node ]; - while ((node = nodes.pop()) != null) { - callback(node); - if ((children = node.children) && (n = children.length)) { - var n, children; - while (--n >= 0) nodes.push(children[n]); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); } } - } - function d3_layout_hierarchyVisitAfter(node, callback) { - var nodes = [ node ], nodes2 = []; - while ((node = nodes.pop()) != null) { - nodes2.push(node); - if ((children = node.children) && (n = children.length)) { - var i = -1, n, children; - while (++i < n) nodes.push(children[i]); + + var lib$es6$promise$$internal$$id = 0; + function lib$es6$promise$$internal$$nextId() { + return lib$es6$promise$$internal$$id++; + } + + function lib$es6$promise$$internal$$makePromise(promise) { + promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; + } + + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!lib$es6$promise$utils$$isArray(entries)) { + return new Constructor(function(resolve, reject) { + reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); } } - while ((node = nodes2.pop()) != null) { - callback(node); + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; } - } - function d3_layout_hierarchyChildren(d) { - return d.children; - } - function d3_layout_hierarchyValue(d) { - return d.value; - } - function d3_layout_hierarchySort(a, b) { - return b.value - a.value; - } - function d3_layout_hierarchyLinks(nodes) { - return d3.merge(nodes.map(function(parent) { - return (parent.children || []).map(function(child) { - return { - source: parent, - target: child - }; + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); }); - })); - } - d3.layout.partition = function() { - var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; - function position(node, x, dx, dy) { - var children = node.children; - node.x = x; - node.y = node.depth * dy; - node.dx = dx; - node.dy = dy; - if (children && (n = children.length)) { - var i = -1, n, c, d; - dx = node.value ? dx / node.value : 0; - while (++i < n) { - position(c = children[i], x, d = c.value * dx, dy); - x += d; - } + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); } - } - function depth(node) { - var children = node.children, d = 0; - if (children && (n = children.length)) { - var i = -1, n; - while (++i < n) d = Math.max(d, depth(children[i])); + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); + this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); } - return 1 + d; - } - function partition(d, i) { - var nodes = hierarchy.call(this, d, i); - position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); - return nodes; } - partition.size = function(x) { - if (!arguments.length) return size; - size = x; - return partition; - }; - return d3_layout_hierarchyRebind(partition, hierarchy); - }; - d3.layout.pie = function() { - var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; - function pie(data) { - var n = data.length, values = data.map(function(d, i) { - return +value.call(pie, d, i); - }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; - if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { - return values[j] - values[i]; - } : function(i, j) { - return sort(data[i], data[j]); + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` }); - index.forEach(function(i) { - arcs[i] = { - data: data[i], - value: v = values[i], - startAngle: a, - endAngle: a += v * k + pa, - padAngle: p - }; + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); - return arcs; - } - pie.value = function(_) { - if (!arguments.length) return value; - value = _; - return pie; - }; - pie.sort = function(_) { - if (!arguments.length) return sort; - sort = _; - return pie; - }; - pie.startAngle = function(_) { - if (!arguments.length) return startAngle; - startAngle = _; - return pie; - }; - pie.endAngle = function(_) { - if (!arguments.length) return endAngle; - endAngle = _; - return pie; - }; - pie.padAngle = function(_) { - if (!arguments.length) return padAngle; - padAngle = _; - return pie; - }; - return pie; - }; - var d3_layout_pieSortByValue = {}; - d3.layout.stack = function() { - var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; - function stack(data, index) { - if (!(n = data.length)) return data; - var series = data.map(function(d, i) { - return values.call(stack, d, i); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here }); - var points = series.map(function(d) { - return d.map(function(v, i) { - return [ x.call(stack, v, i), y.call(stack, v, i) ]; - }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available }); - var orders = order.call(stack, points, index); - series = d3.permute(series, orders); - points = d3.permute(points, orders); - var offsets = offset.call(stack, points, index); - var m = series[0].length, n, i, j, o; - for (j = 0; j < m; ++j) { - out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); - for (i = 1; i < n; ++i) { - out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); - } + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure } - return data; - } - stack.values = function(x) { - if (!arguments.length) return values; - values = x; - return stack; - }; - stack.order = function(x) { - if (!arguments.length) return order; - order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; - return stack; - }; - stack.offset = function(x) { - if (!arguments.length) return offset; - offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; - return stack; - }; - stack.x = function(z) { - if (!arguments.length) return x; - x = z; - return stack; - }; - stack.y = function(z) { - if (!arguments.length) return y; - y = z; - return stack; - }; - stack.out = function(z) { - if (!arguments.length) return out; - out = z; - return stack; - }; - return stack; - }; - function d3_layout_stackX(d) { - return d.x; - } - function d3_layout_stackY(d) { - return d.y; - } - function d3_layout_stackOut(d, y0, y) { - d.y0 = y0; - d.y = y; - } - var d3_layout_stackOrders = d3.map({ - "inside-out": function(data) { - var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { - return max[a] - max[b]; - }), top = 0, bottom = 0, tops = [], bottoms = []; - for (i = 0; i < n; ++i) { - j = index[i]; - if (top < bottom) { - top += sums[j]; - tops.push(j); + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure } else { - bottom += sums[j]; - bottoms.push(j); - } - } - return bottoms.reverse().concat(tops); - }, - reverse: function(data) { - return d3.range(data.length).reverse(); - }, - "default": d3_layout_stackOrderDefault - }); - var d3_layout_stackOffsets = d3.map({ - silhouette: function(data) { - var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o > max) max = o; - sums.push(o); - } - for (j = 0; j < m; ++j) { - y0[j] = (max - sums[j]) / 2; - } - return y0; - }, - wiggle: function(data) { - var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; - y0[0] = o = o0 = 0; - for (j = 1; j < m; ++j) { - for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; - for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { - for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { - s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; - } - s2 += s3 * data[i][j][1]; + // success } - y0[j] = o -= s1 ? s2 / s1 * dx : 0; - if (o < o0) o0 = o; - } - for (j = 0; j < m; ++j) y0[j] -= o0; - return y0; - }, - expand: function(data) { - var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure } - for (j = 0; j < m; ++j) y0[j] = 0; - return y0; - }, - zero: d3_layout_stackOffsetZero - }); - function d3_layout_stackOrderDefault(data) { - return d3.range(data.length); - } - function d3_layout_stackOffsetZero(data) { - var j = -1, m = data[0].length, y0 = []; - while (++j < m) y0[j] = 0; - return y0; - } - function d3_layout_stackMaxIndex(array) { - var i = 1, j = 0, v = array[0][1], k, n = array.length; - for (;i < n; ++i) { - if ((k = array[i][1]) > v) { - j = i; - v = k; + ``` + + Errback Example + + ```js + + function foundBooks(books) { + } - } - return j; - } - function d3_layout_stackReduceSum(d) { - return d.reduce(d3_layout_stackSum, 0); - } - function d3_layout_stackSum(p, d) { - return p + d[1]; - } - d3.layout.histogram = function() { - var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; - function histogram(data, i) { - var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; - while (++i < m) { - bin = bins[i] = []; - bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); - bin.y = 0; + + function failure(reason) { + } - if (m > 0) { - i = -1; - while (++i < n) { - x = values[i]; - if (x >= range[0] && x <= range[1]) { - bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; - bin.y += k; - bin.push(data[i]); + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); } + // success } - } - return bins; - } - histogram.value = function(x) { - if (!arguments.length) return valuer; - valuer = x; - return histogram; - }; - histogram.range = function(x) { - if (!arguments.length) return ranger; - ranger = d3_functor(x); - return histogram; - }; - histogram.bins = function(x) { - if (!arguments.length) return binner; - binner = typeof x === "number" ? function(range) { - return d3_layout_histogramBinFixed(range, x); - } : d3_functor(x); - return histogram; - }; - histogram.frequency = function(x) { - if (!arguments.length) return frequency; - frequency = !!x; - return histogram; - }; - return histogram; - }; - function d3_layout_histogramBinSturges(range, values) { - return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); - } - function d3_layout_histogramBinFixed(range, n) { - var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; - while (++x <= n) f[x] = m * x + b; - return f; - } - function d3_layout_histogramRange(values) { - return [ d3.min(values), d3.max(values) ]; - } - d3.layout.pack = function() { - var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; - function pack(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { - return radius; - }; - root.x = root.y = 0; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r = +r(d.value); }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - if (padding) { - var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r += dr; - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r -= dr; - }); - } - d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); - return nodes; - } - pack.size = function(_) { - if (!arguments.length) return size; - size = _; - return pack; - }; - pack.radius = function(_) { - if (!arguments.length) return radius; - radius = _ == null || typeof _ === "function" ? _ : +_; - return pack; - }; - pack.padding = function(_) { - if (!arguments.length) return padding; - padding = +_; - return pack; - }; - return d3_layout_hierarchyRebind(pack, hierarchy); - }; - function d3_layout_packSort(a, b) { - return a.value - b.value; - } - function d3_layout_packInsert(a, b) { - var c = a._pack_next; - a._pack_next = b; - b._pack_prev = a; - b._pack_next = c; - c._pack_prev = b; - } - function d3_layout_packSplice(a, b) { - a._pack_next = b; - b._pack_prev = a; - } - function d3_layout_packIntersects(a, b) { - var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; - return .999 * dr * dr > dx * dx + dy * dy; - } - function d3_layout_packSiblings(node) { - if (!(nodes = node.children) || !(n = nodes.length)) return; - var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; - function bound(node) { - xMin = Math.min(node.x - node.r, xMin); - xMax = Math.max(node.x + node.r, xMax); - yMin = Math.min(node.y - node.r, yMin); - yMax = Math.max(node.y + node.r, yMax); - } - nodes.forEach(d3_layout_packLink); - a = nodes[0]; - a.x = -a.r; - a.y = 0; - bound(a); - if (n > 1) { - b = nodes[1]; - b.x = b.r; - b.y = 0; - bound(b); - if (n > 2) { - c = nodes[2]; - d3_layout_packPlace(a, b, c); - bound(c); - d3_layout_packInsert(a, c); - a._pack_prev = c; - d3_layout_packInsert(c, b); - b = a._pack_next; - for (i = 3; i < n; i++) { - d3_layout_packPlace(a, b, c = nodes[i]); - var isect = 0, s1 = 1, s2 = 1; - for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { - if (d3_layout_packIntersects(j, c)) { - isect = 1; - break; - } - } - if (isect == 1) { - for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { - if (d3_layout_packIntersects(k, c)) { - break; - } - } - } - if (isect) { - if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); - i--; - } else { - d3_layout_packInsert(a, c); - b = c; - bound(c); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: lib$es6$promise$then$$default, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { + lib$es6$promise$$internal$$makePromise(this.promise); + } + + if (lib$es6$promise$utils$$isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); } } + } else { + lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); } } - var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; - for (i = 0; i < n; i++) { - c = nodes[i]; - c.x -= cx; - c.y -= cy; - cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); - } - node.r = cr; - nodes.forEach(d3_layout_packUnlink); - } - function d3_layout_packLink(node) { - node._pack_next = node._pack_prev = node; - } - function d3_layout_packUnlink(node) { - delete node._pack_next; - delete node._pack_prev; - } - function d3_layout_packTransform(node, x, y, k) { - var children = node.children; - node.x = x += k * node.x; - node.y = y += k * node.y; - node.r *= k; - if (children) { - var i = -1, n = children.length; - while (++i < n) d3_layout_packTransform(children[i], x, y, k); - } - } - function d3_layout_packPlace(a, b, c) { - var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; - if (db && (dx || dy)) { - var da = b.r + c.r, dc = dx * dx + dy * dy; - da *= da; - db *= db; - var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); - c.x = a.x + x * dx + y * dy; - c.y = a.y + x * dy - y * dx; - } else { - c.x = a.x + db; - c.y = a.y; + + function lib$es6$promise$enumerator$$validationError() { + return new Error('Array Methods must be provided an Array'); } - } - d3.layout.tree = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; - function tree(d, i) { - var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); - d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; - d3_layout_hierarchyVisitBefore(root1, secondWalk); - if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { - var left = root0, right = root0, bottom = root0; - d3_layout_hierarchyVisitBefore(root0, function(node) { - if (node.x < left.x) left = node; - if (node.x > right.x) right = node; - if (node.depth > bottom.depth) bottom = node; - }); - var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); - d3_layout_hierarchyVisitBefore(root0, function(node) { - node.x = (node.x + tx) * kx; - node.y = node.depth * ky; - }); + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var length = this.length; + var input = this._input; + + for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + this._eachEntry(input[i], i); } - return nodes; - } - function wrapTree(root0) { - var root1 = { - A: null, - children: [ root0 ] - }, queue = [ root1 ], node1; - while ((node1 = queue.pop()) != null) { - for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { - queue.push((children[i] = child = { - _: children[i], - parent: node1, - children: (child = children[i].children) && child.slice() || [], - A: null, - a: null, - z: 0, - m: 0, - c: 0, - s: 0, - t: null, - i: i - }).a = child); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve = c.resolve; + + if (resolve === lib$es6$promise$promise$resolve$$default) { + var then = lib$es6$promise$$internal$$getThen(entry); + + if (then === lib$es6$promise$then$$default && + entry._state !== lib$es6$promise$$internal$$PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === lib$es6$promise$promise$$default) { + var promise = new c(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); } + } else { + this._willSettleAt(resolve(entry), i); } - return root1.children[0]; - } - function firstWalk(v) { - var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; - if (children.length) { - d3_layout_treeShift(v); - var midpoint = (children[0].z + children[children.length - 1].z) / 2; - if (w) { - v.z = w.z + separation(v._, w._); - v.m = v.z - midpoint; + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + this._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); } else { - v.z = midpoint; + this._result[i] = value; } - } else if (w) { - v.z = w.z + separation(v._, w._); } - v.parent.A = apportion(v, w, v.parent.A || siblings[0]); + + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, this._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; } - function secondWalk(v) { - v._.x = v.z + v.parent.m; - v.m += v.parent.m; + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; } - function apportion(v, w, ancestor) { - if (w) { - var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; - while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { - vom = d3_layout_treeLeft(vom); - vop = d3_layout_treeRight(vop); - vop.a = v; - shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); - if (shift > 0) { - d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); - sip += shift; - sop += shift; - } - sim += vim.m; - sip += vip.m; - som += vom.m; - sop += vop.m; - } - if (vim && !d3_layout_treeRight(vop)) { - vop.t = vim; - vop.m += sim - sop; - } - if (vip && !d3_layout_treeLeft(vom)) { - vom.t = vip; - vom.m += sip - som; - ancestor = v; + + lib$es6$promise$polyfill$$default(); +}).call(this); + + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":70}],90:[function(require,module,exports){ +/** + * inspired by is-number + * but significantly simplified and sped up by ignoring number and string constructors + * ie these return false: + * new Number(1) + * new String('1') + */ + +'use strict'; + +/** + * Is this string all whitespace? + * This solution kind of makes my brain hurt, but it's significantly faster + * than !str.trim() or any other solution I could find. + * + * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character + * and verified with: + * + * for(var i = 0; i < 65536; i++) { + * var s = String.fromCharCode(i); + * if(+s===0 && !s.trim()) console.log(i, s); + * } + * + * which counts a couple of these as *not* whitespace, but finds nothing else + * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears + * that there are no whitespace characters above this, and code points above + * this do not map onto white space characters. + */ +function allBlankCharCodes(str){ + var l = str.length, + a; + for(var i = 0; i < l; i++) { + a = str.charCodeAt(i); + if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) && + (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) && + (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) && + (a !== 8288) && (a !== 12288) && (a !== 65279)) { + return false; } - } - return ancestor; } - function sizeNode(node) { - node.x *= size[0]; - node.y = node.depth * size[1]; + return true; +} + +module.exports = function(n) { + var type = typeof n; + if(type === 'string') { + var original = n; + n = +n; + // whitespace strings cast to zero - filter them out + if(n===0 && allBlankCharCodes(original)) return false; } - tree.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return tree; - }; - tree.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null ? sizeNode : null; - return tree; - }; - tree.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) == null ? null : sizeNode; - return tree; - }; - return d3_layout_hierarchyRebind(tree, hierarchy); - }; - function d3_layout_treeSeparation(a, b) { - return a.parent == b.parent ? 1 : 2; + else if(type !== 'number') return false; + + return n - n < 1; +}; + +},{}],91:[function(require,module,exports){ +'use strict' + +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var pool = require('typedarray-pool') +var shaders = require('./lib/shaders') + +module.exports = createError2D + +var WEIGHTS = [ + // x-error bar + [1, 0, 0, 1, 0, 0], + [1, 0, 0, -1, 0, 0], + [-1, 0, 0, -1, 0, 0], + + [-1, 0, 0, -1, 0, 0], + [-1, 0, 0, 1, 0, 0], + [1, 0, 0, 1, 0, 0], + + // x-error right cap + [1, 0, -1, 0, 0, 1], + [1, 0, -1, 0, 0, -1], + [1, 0, 1, 0, 0, -1], + + [1, 0, 1, 0, 0, -1], + [1, 0, 1, 0, 0, 1], + [1, 0, -1, 0, 0, 1], + + // x-error left cap + [-1, 0, -1, 0, 0, 1], + [-1, 0, -1, 0, 0, -1], + [-1, 0, 1, 0, 0, -1], + + [-1, 0, 1, 0, 0, -1], + [-1, 0, 1, 0, 0, 1], + [-1, 0, -1, 0, 0, 1], + + // y-error bar + [0, 1, 1, 0, 0, 0], + [0, 1, -1, 0, 0, 0], + [0, -1, -1, 0, 0, 0], + + [0, -1, -1, 0, 0, 0], + [0, 1, 1, 0, 0, 0], + [0, -1, 1, 0, 0, 0], + + // y-error top cap + [0, 1, 0, -1, 1, 0], + [0, 1, 0, -1, -1, 0], + [0, 1, 0, 1, -1, 0], + + [0, 1, 0, 1, 1, 0], + [0, 1, 0, -1, 1, 0], + [0, 1, 0, 1, -1, 0], + + // y-error bottom cap + [0, -1, 0, -1, 1, 0], + [0, -1, 0, -1, -1, 0], + [0, -1, 0, 1, -1, 0], + + [0, -1, 0, 1, 1, 0], + [0, -1, 0, -1, 1, 0], + [0, -1, 0, 1, -1, 0] +] + +function GLError2D (plot, shader, buffer) { + this.plot = plot + + this.shader = shader + this.buffer = buffer + + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + + this.numPoints = 0 + + this.color = [0, 0, 0, 1] +} + +var proto = GLError2D.prototype + +proto.draw = (function () { + var MATRIX = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + + var PIXEL_SCALE = [1, 1] + + return function () { + var plot = this.plot + var shader = this.shader + var buffer = this.buffer + var bounds = this.bounds + var numPoints = this.numPoints + + if (!numPoints) { + return + } + + var gl = plot.gl + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] + + PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX + PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY + + buffer.bind() + shader.bind() + + shader.uniforms.viewTransform = MATRIX + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.color = this.color + + shader.attributes.position.pointer( + gl.FLOAT, + false, + 16, + 0) + + shader.attributes.pixelOffset.pointer( + gl.FLOAT, + false, + 16, + 8) + + gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length) } - function d3_layout_treeLeft(v) { - var children = v.children; - return children.length ? children[0] : v.t; +})() + +proto.drawPick = function (offset) { return offset } +proto.pick = function (x, y) { + return null +} + +proto.update = function (options) { + options = options || {} + + var i, x, y + + var positions = options.positions || [] + var errors = options.errors || [] + + var lineWidth = 1 + if ('lineWidth' in options) { + lineWidth = +options.lineWidth } - function d3_layout_treeRight(v) { - var children = v.children, n; - return (n = children.length) ? children[n - 1] : v.t; + + var capSize = 5 + if ('capSize' in options) { + capSize = +options.capSize } - function d3_layout_treeMove(wm, wp, shift) { - var change = shift / (wp.i - wm.i); - wp.c -= change; - wp.s += shift; - wm.c += change; - wp.z += shift; - wp.m += shift; + + this.color = (options.color || [0, 0, 0, 1]).slice() + + var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + + var numPoints = this.numPoints = positions.length >> 1 + for (i = 0; i < numPoints; ++i) { + x = positions[i * 2] + y = positions[i * 2 + 1] + + bounds[0] = Math.min(x, bounds[0]) + bounds[1] = Math.min(y, bounds[1]) + bounds[2] = Math.max(x, bounds[2]) + bounds[3] = Math.max(y, bounds[3]) } - function d3_layout_treeShift(v) { - var shift = 0, change = 0, children = v.children, i = children.length, w; - while (--i >= 0) { - w = children[i]; - w.z += shift; - w.m += shift; - shift += w.s + (change += w.c); - } + if (bounds[2] === bounds[0]) { + bounds[2] += 1 } - function d3_layout_treeAncestor(vim, v, ancestor) { - return vim.a.parent === v.parent ? vim.a : ancestor; + if (bounds[3] === bounds[1]) { + bounds[3] += 1 } - d3.layout.cluster = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; - function cluster(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; - d3_layout_hierarchyVisitAfter(root, function(node) { - var children = node.children; - if (children && children.length) { - node.x = d3_layout_clusterX(children); - node.y = d3_layout_clusterY(children); - } else { - node.x = previousNode ? x += separation(node, previousNode) : 0; - node.y = 0; - previousNode = node; - } - }); - var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; - d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { - node.x = (node.x - root.x) * size[0]; - node.y = (root.y - node.y) * size[1]; - } : function(node) { - node.x = (node.x - x0) / (x1 - x0) * size[0]; - node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; - }); - return nodes; + var sx = 1.0 / (bounds[2] - bounds[0]) + var sy = 1.0 / (bounds[3] - bounds[1]) + var tx = bounds[0] + var ty = bounds[1] + + var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4) + var ptr = 0 + for (i = 0; i < numPoints; ++i) { + x = positions[2 * i] + y = positions[2 * i + 1] + var ex0 = errors[4 * i] + var ex1 = errors[4 * i + 1] + var ey0 = errors[4 * i + 2] + var ey1 = errors[4 * i + 3] + + for (var j = 0; j < WEIGHTS.length; ++j) { + var w = WEIGHTS[j] + + var dx = w[0] + var dy = w[1] + + if (dx < 0) { + dx *= ex0 + } else if (dx > 0) { + dx *= ex1 + } + + if (dy < 0) { + dy *= ey0 + } else if (dy > 0) { + dy *= ey1 + } + + bufferData[ptr++] = sx * ((x - tx) + dx) + bufferData[ptr++] = sy * ((y - ty) + dy) + bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4] + bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5] } - cluster.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return cluster; - }; - cluster.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null; - return cluster; - }; - cluster.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) != null; - return cluster; - }; - return d3_layout_hierarchyRebind(cluster, hierarchy); - }; - function d3_layout_clusterY(children) { - return 1 + d3.max(children, function(child) { - return child.y; - }); } - function d3_layout_clusterX(children) { - return children.reduce(function(x, child) { - return x + child.x; - }, 0) / children.length; + this.buffer.update(bufferData) + pool.free(bufferData) +} + +proto.dispose = function () { + this.plot.removeObject(this) + this.shader.dispose() + this.buffer.dispose() +} + +function createError2D (plot, options) { + var shader = createShader(plot.gl, shaders.vertex, shaders.fragment) + var buffer = createBuffer(plot.gl) + + var errorbars = new GLError2D(plot, shader, buffer) + + errorbars.update(options) + + plot.addObject(errorbars) + + return errorbars +} + +},{"./lib/shaders":92,"gl-buffer":93,"gl-shader":94,"typedarray-pool":122}],92:[function(require,module,exports){ + + +module.exports = { + vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n", + fragment: "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" +} + +},{}],93:[function(require,module,exports){ +"use strict" + +var pool = require("typedarray-pool") +var ops = require("ndarray-ops") +var ndarray = require("ndarray") + +var SUPPORTED_TYPES = [ + "uint8", + "uint8_clamped", + "uint16", + "uint32", + "int8", + "int16", + "int32", + "float32" ] + +function GLBuffer(gl, type, handle, length, usage) { + this.gl = gl + this.type = type + this.handle = handle + this.length = length + this.usage = usage +} + +var proto = GLBuffer.prototype + +proto.bind = function() { + this.gl.bindBuffer(this.type, this.handle) +} + +proto.unbind = function() { + this.gl.bindBuffer(this.type, null) +} + +proto.dispose = function() { + this.gl.deleteBuffer(this.handle) +} + +function updateTypeArray(gl, type, len, usage, data, offset) { + var dataLen = data.length * data.BYTES_PER_ELEMENT + if(offset < 0) { + gl.bufferData(type, data, usage) + return dataLen } - function d3_layout_clusterLeft(node) { - var children = node.children; - return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + if(dataLen + offset > len) { + throw new Error("gl-buffer: If resizing buffer, must not specify offset") } - function d3_layout_clusterRight(node) { - var children = node.children, n; - return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + gl.bufferSubData(type, offset, data) + return len +} + +function makeScratchTypeArray(array, dtype) { + var res = pool.malloc(array.length, dtype) + var n = array.length + for(var i=0; i 0) { - row.push(child = remaining[n - 1]); - row.area += child.area; - if (mode !== "squarify" || (score = worst(row, u)) <= best) { - remaining.pop(); - best = score; - } else { - row.area -= row.pop().area; - position(row, u, rect, false); - u = Math.min(rect.dx, rect.dy); - row.length = row.area = 0; - best = Infinity; - } - } - if (row.length) { - position(row, u, rect, true); - row.length = row.area = 0; - } - children.forEach(squarify); - } - } - function stickify(node) { - var children = node.children; - if (children && children.length) { - var rect = pad(node), remaining = children.slice(), child, row = []; - scale(remaining, rect.dx * rect.dy / node.value); - row.area = 0; - while (child = remaining.pop()) { - row.push(child); - row.area += child.area; - if (child.z != null) { - position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); - row.length = row.area = 0; - } - } - children.forEach(stickify); - } + return res +} + +function isPacked(shape, stride) { + var n = 1 + for(var i=stride.length-1; i>=0; --i) { + if(stride[i] !== n) { + return false } - function worst(row, u) { - var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; - while (++i < n) { - if (!(r = row[i].area)) continue; - if (r < rmin) rmin = r; - if (r > rmax) rmax = r; - } - s *= s; - u *= u; - return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + n *= shape[i] + } + return true +} + +proto.update = function(array, offset) { + if(typeof offset !== "number") { + offset = -1 + } + this.bind() + if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray + var dtype = array.dtype + if(SUPPORTED_TYPES.indexOf(dtype) < 0) { + dtype = "float32" } - function position(row, u, rect, flush) { - var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; - if (u == rect.dx) { - if (flush || v > rect.dy) v = rect.dy; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dy = v; - x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); - } - o.z = true; - o.dx += rect.x + rect.dx - x; - rect.y += v; - rect.dy -= v; + if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { + var ext = gl.getExtension('OES_element_index_uint') + if(ext && dtype !== "uint16") { + dtype = "uint32" } else { - if (flush || v > rect.dx) v = rect.dx; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dx = v; - y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); - } - o.z = false; - o.dy += rect.y + rect.dy - y; - rect.x += v; - rect.dx -= v; + dtype = "uint16" } } - function treemap(d) { - var nodes = stickies || hierarchy(d), root = nodes[0]; - root.x = root.y = 0; - if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; - if (stickies) hierarchy.revalue(root); - scale([ root ], root.dx * root.dy / root.value); - (stickies ? stickify : squarify)(root); - if (sticky) stickies = nodes; - return nodes; - } - treemap.size = function(x) { - if (!arguments.length) return size; - size = x; - return treemap; - }; - treemap.padding = function(x) { - if (!arguments.length) return padding; - function padFunction(node) { - var p = x.call(treemap, node, node.depth); - return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + if(dtype === array.dtype && isPacked(array.shape, array.stride)) { + if(array.offset === 0 && array.data.length === array.shape[0]) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) } - function padConstant(node) { - return d3_layout_treemapPad(node, x); + } else { + var tmp = pool.malloc(array.size, dtype) + var ndt = ndarray(tmp, array.shape) + ops.assign(ndt, array) + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) } - var type; - pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], - padConstant) : padConstant; - return treemap; - }; - treemap.round = function(x) { - if (!arguments.length) return round != Number; - round = x ? Math.round : Number; - return treemap; - }; - treemap.sticky = function(x) { - if (!arguments.length) return sticky; - sticky = x; - stickies = null; - return treemap; - }; - treemap.ratio = function(x) { - if (!arguments.length) return ratio; - ratio = x; - return treemap; - }; - treemap.mode = function(x) { - if (!arguments.length) return mode; - mode = x + ""; - return treemap; - }; - return d3_layout_hierarchyRebind(treemap, hierarchy); - }; - function d3_layout_treemapPadNull(node) { - return { - x: node.x, - y: node.y, - dx: node.dx, - dy: node.dy - }; - } - function d3_layout_treemapPad(node, padding) { - var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; - if (dx < 0) { - x += dx / 2; - dx = 0; - } - if (dy < 0) { - y += dy / 2; - dy = 0; - } - return { - x: x, - y: y, - dx: dx, - dy: dy - }; - } - d3.random = { - normal: function(µ, σ) { - var n = arguments.length; - if (n < 2) σ = 1; - if (n < 1) µ = 0; - return function() { - var x, y, r; - do { - x = Math.random() * 2 - 1; - y = Math.random() * 2 - 1; - r = x * x + y * y; - } while (!r || r > 1); - return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); - }; - }, - logNormal: function() { - var random = d3.random.normal.apply(d3, arguments); - return function() { - return Math.exp(random()); - }; - }, - bates: function(m) { - var random = d3.random.irwinHall(m); - return function() { - return random() / m; - }; - }, - irwinHall: function(m) { - return function() { - for (var s = 0, j = 0; j < m; j++) s += Math.random(); - return s; - }; - } - }; - d3.scale = {}; - function d3_scaleExtent(domain) { - var start = domain[0], stop = domain[domain.length - 1]; - return start < stop ? [ start, stop ] : [ stop, start ]; - } - function d3_scaleRange(scale) { - return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); - } - function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { - var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); - return function(x) { - return i(u(x)); - }; - } - function d3_scale_nice(domain, nice) { - var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; - if (x1 < x0) { - dx = i0, i0 = i1, i1 = dx; - dx = x0, x0 = x1, x1 = dx; + pool.free(tmp) } - domain[i0] = nice.floor(x0); - domain[i1] = nice.ceil(x1); - return domain; - } - function d3_scale_niceStep(step) { - return step ? { - floor: function(x) { - return Math.floor(x / step) * step; - }, - ceil: function(x) { - return Math.ceil(x / step) * step; - } - } : d3_scale_niceIdentity; - } - var d3_scale_niceIdentity = { - floor: d3_identity, - ceil: d3_identity - }; - function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { - var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; - if (domain[k] < domain[0]) { - domain = domain.slice().reverse(); - range = range.slice().reverse(); + } else if(Array.isArray(array)) { //Vanilla array + var t + if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { + t = makeScratchTypeArray(array, "uint16") + } else { + t = makeScratchTypeArray(array, "float32") } - while (++j <= k) { - u.push(uninterpolate(domain[j - 1], domain[j])); - i.push(interpolate(range[j - 1], range[j])); + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) + } else { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) } - return function(x) { - var j = d3.bisect(domain, x, 1, k) - 1; - return i[j](u[j](x)); - }; - } - d3.scale.linear = function() { - return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); - }; - function d3_scale_linear(domain, range, interpolate, clamp) { - var output, input; - function rescale() { - var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; - output = linear(domain, range, uninterpolate, interpolate); - input = linear(range, domain, uninterpolate, d3_interpolate); - return scale; + pool.free(t) + } else if(typeof array === "object" && typeof array.length === "number") { //Typed array + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) + } else if(typeof array === "number" || array === undefined) { //Number/default + if(offset >= 0) { + throw new Error("gl-buffer: Cannot specify offset when resizing buffer") } - function scale(x) { - return output(x); + array = array | 0 + if(array <= 0) { + array = 1 } - scale.invert = function(y) { - return input(y); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = x.map(Number); - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.rangeRound = function(x) { - return scale.range(x).interpolate(d3_interpolateRound); - }; - scale.clamp = function(x) { - if (!arguments.length) return clamp; - clamp = x; - return rescale(); - }; - scale.interpolate = function(x) { - if (!arguments.length) return interpolate; - interpolate = x; - return rescale(); - }; - scale.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - scale.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - scale.nice = function(m) { - d3_scale_linearNice(domain, m); - return rescale(); - }; - scale.copy = function() { - return d3_scale_linear(domain, range, interpolate, clamp); - }; - return rescale(); + this.gl.bufferData(this.type, array|0, this.usage) + this.length = array + } else { //Error, case should not happen + throw new Error("gl-buffer: Invalid data type") } - function d3_scale_linearRebind(scale, linear) { - return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); +} + +function createBuffer(gl, data, type, usage) { + type = type || gl.ARRAY_BUFFER + usage = usage || gl.DYNAMIC_DRAW + if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { + throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") } - function d3_scale_linearNice(domain, m) { - d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - return domain; + if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { + throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") } - function d3_scale_linearTickRange(domain, m) { - if (m == null) m = 10; - var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; - if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; - extent[0] = Math.ceil(extent[0] / step) * step; - extent[1] = Math.floor(extent[1] / step) * step + step * .5; - extent[2] = step; - return extent; + var handle = gl.createBuffer() + var result = new GLBuffer(gl, type, handle, 0, usage) + result.update(data) + return result +} + +module.exports = createBuffer + +},{"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":122}],94:[function(require,module,exports){ +'use strict' + +var createUniformWrapper = require('./lib/create-uniforms') +var createAttributeWrapper = require('./lib/create-attributes') +var makeReflect = require('./lib/reflect') +var shaderCache = require('./lib/shader-cache') +var runtime = require('./lib/runtime-reflect') +var GLError = require("./lib/GLError") + +//Shader object +function Shader(gl) { + this.gl = gl + + //Default initialize these to null + this._vref = + this._fref = + this._relink = + this.vertShader = + this.fragShader = + this.program = + this.attributes = + this.uniforms = + this.types = null +} + +var proto = Shader.prototype + +proto.bind = function() { + if(!this.program) { + this._relink() } - function d3_scale_linearTicks(domain, m) { - return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); + this.gl.useProgram(this.program) +} + +proto.dispose = function() { + if(this._fref) { + this._fref.dispose() } - function d3_scale_linearTickFormat(domain, m, format) { - var range = d3_scale_linearTickRange(domain, m); - if (format) { - var match = d3_format_re.exec(format); - match.shift(); - if (match[8] === "s") { - var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); - if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); - match[8] = "f"; - format = d3.format(match.join("")); - return function(d) { - return format(prefix.scale(d)) + prefix.symbol; - }; - } - if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); - format = match.join(""); - } else { - format = ",." + d3_scale_linearPrecision(range[2]) + "f"; - } - return d3.format(format); + if(this._vref) { + this._vref.dispose() } - var d3_scale_linearFormatSignificant = { - s: 1, - g: 1, - p: 1, - r: 1, - e: 1 - }; - function d3_scale_linearPrecision(value) { - return -Math.floor(Math.log(value) / Math.LN10 + .01); + this.attributes = + this.types = + this.vertShader = + this.fragShader = + this.program = + this._relink = + this._fref = + this._vref = null +} + +function compareAttributes(a, b) { + if(a.name < b.name) { + return -1 } - function d3_scale_linearFormatPrecision(type, range) { - var p = d3_scale_linearPrecision(range[2]); - return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + return 1 +} + +//Update export hook for glslify-live +proto.update = function( + vertSource + , fragSource + , uniforms + , attributes) { + + //If only one object passed, assume glslify style output + if(!fragSource || arguments.length === 1) { + var obj = vertSource + vertSource = obj.vertex + fragSource = obj.fragment + uniforms = obj.uniforms + attributes = obj.attributes } - d3.scale.log = function() { - return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); - }; - function d3_scale_log(linear, base, positive, domain) { - function log(x) { - return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); - } - function pow(x) { - return positive ? Math.pow(base, x) : -Math.pow(base, -x); - } - function scale(x) { - return linear(log(x)); + + var wrapper = this + var gl = wrapper.gl + + //Compile vertex and fragment shaders + var pvref = wrapper._vref + wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource) + if(pvref) { + pvref.dispose() + } + wrapper.vertShader = wrapper._vref.shader + var pfref = this._fref + wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource) + if(pfref) { + pfref.dispose() + } + wrapper.fragShader = wrapper._fref.shader + + //If uniforms/attributes is not specified, use RT reflection + if(!uniforms || !attributes) { + + //Create initial test program + var testProgram = gl.createProgram() + gl.attachShader(testProgram, wrapper.fragShader) + gl.attachShader(testProgram, wrapper.vertShader) + gl.linkProgram(testProgram) + if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) { + var errLog = gl.getProgramInfoLog(testProgram) + throw new GLError(errLog, 'Error linking program:' + errLog) } - scale.invert = function(x) { - return pow(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - positive = x[0] >= 0; - linear.domain((domain = x.map(Number)).map(log)); - return scale; - }; - scale.base = function(_) { - if (!arguments.length) return base; - base = +_; - linear.domain(domain.map(log)); - return scale; - }; - scale.nice = function() { - var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); - linear.domain(niced); - domain = niced.map(pow); - return scale; - }; - scale.ticks = function() { - var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; - if (isFinite(j - i)) { - if (positive) { - for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); - ticks.push(pow(i)); + + //Load data from runtime + uniforms = uniforms || runtime.uniforms(gl, testProgram) + attributes = attributes || runtime.attributes(gl, testProgram) + + //Release test program + gl.deleteProgram(testProgram) + } + + //Sort attributes lexicographically + // overrides undefined WebGL behavior for attribute locations + attributes = attributes.slice() + attributes.sort(compareAttributes) + + //Convert attribute types, read out locations + var attributeUnpacked = [] + var attributeNames = [] + var attributeLocations = [] + for(var i=0; i= 0) { + var size = attr.type.charAt(attr.type.length-1)|0 + var locVector = new Array(size) + for(var j=0; j 0; k--) ticks.push(pow(i) * k); + attributeLocations.push(-1) } - for (i = 0; ticks[i] < u; i++) {} - for (j = ticks.length; ticks[j - 1] > v; j--) {} - ticks = ticks.slice(i, j); } - return ticks; - }; - scale.tickFormat = function(n, format) { - if (!arguments.length) return d3_scale_logFormat; - if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); - var k = Math.max(1, base * n / scale.ticks().length); - return function(d) { - var i = d / pow(Math.round(log(d))); - if (i * base < base - .5) i *= base; - return i <= k ? format(d) : ""; - }; - }; - scale.copy = function() { - return d3_scale_log(linear.copy(), base, positive, domain); - }; - return d3_scale_linearRebind(scale, linear); + attributeUnpacked.push({ + name: attr.name, + type: attr.type, + locations: locVector + }) + } else { + attributeUnpacked.push({ + name: attr.name, + type: attr.type, + locations: [ attributeLocations.length ] + }) + attributeNames.push(attr.name) + if(typeof attr.location === 'number') { + attributeLocations.push(attr.location|0) + } else { + attributeLocations.push(-1) + } + } } - var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { - floor: function(x) { - return -Math.ceil(-x); - }, - ceil: function(x) { - return -Math.floor(-x); + + //For all unspecified attributes, assign them lexicographically min attribute + var curLocation = 0 + for(var i=0; i= 0) { + curLocation += 1 + } + attributeLocations[i] = curLocation } - }; - d3.scale.pow = function() { - return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); - }; - function d3_scale_pow(linear, exponent, domain) { - var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); - function scale(x) { - return linear(powp(x)); + } + + //Rebuild program and recompute all uniform locations + var uniformLocations = new Array(uniforms.length) + function relink() { + wrapper.program = shaderCache.program( + gl + , wrapper._vref + , wrapper._fref + , attributeNames + , attributeLocations) + + for(var i=0; i 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; - }; - scale.copy = function() { - return d3_scale_quantile(domain, range); - }; - return rescale(); } - d3.scale.quantize = function() { - return d3_scale_quantize(0, 1, [ 0, 1 ]); - }; - function d3_scale_quantize(x0, x1, range) { - var kx, i; - function scale(x) { - return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + + var scratch = new Array(dimension) + var vertexAttrib = gl['vertexAttrib' + dimension + 'fv'] + + Object.defineProperty(obj, name, { + set: function(x) { + for(var i=0; i= 0) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addVectorAttribute( + gl + , wrapper + , locs[0] + , locations + , d + , obj + , name) + } else if(type.indexOf('mat') >= 0) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addMatrixAttribute( + gl + , wrapper + , locs + , locations + , d + , obj + , name) + } else { + throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type) + } + break } - scale.domain = function(_) { - if (!arguments.length) return domain; - domain = _; - return scale; - }; - scale.range = function(_) { - if (!arguments.length) return range; - range = _; - return scale; - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - return [ domain[y - 1], domain[y] ]; - }; - scale.copy = function() { - return d3_scale_threshold(domain, range); - }; - return scale; } - d3.scale.identity = function() { - return d3_scale_identity([ 0, 1 ]); - }; - function d3_scale_identity(domain) { - function identity(x) { - return +x; - } - identity.invert = identity; - identity.domain = identity.range = function(x) { - if (!arguments.length) return domain; - domain = x.map(identity); - return identity; - }; - identity.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - identity.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - identity.copy = function() { - return d3_scale_identity(domain); - }; - return identity; + return obj +} + +},{"./GLError":95}],97:[function(require,module,exports){ +'use strict' + +var coallesceUniforms = require('./reflect') +var GLError = require("./GLError") + +module.exports = createUniformWrapper + +//Binds a function and returns a value +function identity(x) { + var c = new Function('y', 'return function(){return y}') + return c(x) +} + +function makeVector(length, fill) { + var result = new Array(length) + for(var i=0; i a1 ? 0 : 1; - if (r1 < r0) rc = r1, r1 = r0, r0 = rc; - if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; - var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; - if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { - rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); - if (!cw) p1 *= -1; - if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); - if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); - } - if (r1) { - x0 = r1 * Math.cos(a0 + p1); - y0 = r1 * Math.sin(a0 + p1); - x1 = r1 * Math.cos(a1 - p1); - y1 = r1 * Math.sin(a1 - p1); - var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; - if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { - var h1 = (a0 + a1) / 2; - x0 = r1 * Math.cos(h1); - y0 = r1 * Math.sin(h1); - x1 = y1 = null; + + function makePropSetter(path, index, type) { + switch(type) { + case 'bool': + case 'int': + case 'sampler2D': + case 'samplerCube': + return 'gl.uniform1i(locations[' + index + '],obj' + path + ')' + case 'float': + return 'gl.uniform1f(locations[' + index + '],obj' + path + ')' + default: + var vidx = type.indexOf('vec') + if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type') + } + switch(type.charAt(0)) { + case 'b': + case 'i': + return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' + case 'v': + return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' + default: + throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type) + } + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + } + return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' + } else { + throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) } + break + } + } + + function enumerateIndices(prefix, type) { + if(typeof type !== 'object') { + return [ [prefix, type] ] + } + var indices = [] + for(var id in type) { + var prop = type[id] + var tprefix = prefix + if(parseInt(id) + '' === id) { + tprefix += '[' + id + ']' } else { - x0 = y0 = 0; + tprefix += '.' + id } - if (r0) { - x2 = r0 * Math.cos(a1 - p0); - y2 = r0 * Math.sin(a1 - p0); - x3 = r0 * Math.cos(a0 + p0); - y3 = r0 * Math.sin(a0 + p0); - var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; - if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { - var h0 = (a0 + a1) / 2; - x2 = r0 * Math.cos(h0); - y2 = r0 * Math.sin(h0); - x3 = y3 = null; - } + if(typeof prop === 'object') { + indices.push.apply(indices, enumerateIndices(tprefix, prop)) } else { - x2 = y2 = 0; + indices.push([tprefix, prop]) } - if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { - cr = r0 < r1 ^ cw ? 0 : 1; - var rc1 = rc, rc0 = rc; - if (da < π) { - var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); - rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); - rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); - } - if (x1 != null) { - var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); - if (rc === rc1) { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); - } else { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + return indices + } + + function makeSetter(type) { + var code = [ 'return function updateProperty(obj){' ] + var indices = enumerateIndices('', type) + for(var i=0; i 4) { + throw new GLError('', 'Invalid data type') } - } else { - path.push("M", x0, ",", y0); - } - if (x3 != null) { - var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); - if (rc === rc0) { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); - } else { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + if(type.charAt(0) === 'b') { + return makeVector(d, false) + } + return makeVector(d, 0) + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) } + return makeVector(d*d, 0) } else { - path.push("L", x2, ",", y2); + throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) } + break + } + } + + function storeProperty(obj, prop, type) { + if(typeof type === 'object') { + var child = processObject(type) + Object.defineProperty(obj, prop, { + get: identity(child), + set: makeSetter(type), + enumerable: true, + configurable: false + }) + } else { + if(locations[type]) { + Object.defineProperty(obj, prop, { + get: makeGetter(type), + set: makeSetter(type), + enumerable: true, + configurable: false + }) } else { - path.push("M", x0, ",", y0); - if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); - path.push("L", x2, ",", y2); - if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + obj[prop] = defaultValue(uniforms[type].type) } - path.push("Z"); - return path.join(""); - } - function circleSegment(r1, cw) { - return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } - arc.innerRadius = function(v) { - if (!arguments.length) return innerRadius; - innerRadius = d3_functor(v); - return arc; - }; - arc.outerRadius = function(v) { - if (!arguments.length) return outerRadius; - outerRadius = d3_functor(v); - return arc; - }; - arc.cornerRadius = function(v) { - if (!arguments.length) return cornerRadius; - cornerRadius = d3_functor(v); - return arc; - }; - arc.padRadius = function(v) { - if (!arguments.length) return padRadius; - padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); - return arc; - }; - arc.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return arc; - }; - arc.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return arc; - }; - arc.padAngle = function(v) { - if (!arguments.length) return padAngle; - padAngle = d3_functor(v); - return arc; - }; - arc.centroid = function() { - var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; - return [ Math.cos(a) * r, Math.sin(a) * r ]; - }; - return arc; - }; - var d3_svg_arcAuto = "auto"; - function d3_svg_arcInnerRadius(d) { - return d.innerRadius; - } - function d3_svg_arcOuterRadius(d) { - return d.outerRadius; - } - function d3_svg_arcStartAngle(d) { - return d.startAngle; - } - function d3_svg_arcEndAngle(d) { - return d.endAngle; - } - function d3_svg_arcPadAngle(d) { - return d && d.padAngle; - } - function d3_svg_arcSweep(x0, y0, x1, y1) { - return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; - } - function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { - var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; - if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; - return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; } - function d3_svg_line(projection) { - var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; - function line(data) { - var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); - function segment() { - segments.push("M", interpolate(projection(points), tension)); + + function processObject(obj) { + var result + if(Array.isArray(obj)) { + result = new Array(obj.length) + for(var i=0; i 1 ? points.join("L") : points + "Z"; - } - function d3_svg_lineLinearClosed(points) { - return points.join("L") + "Z"; - } - function d3_svg_lineStep(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); - if (n > 1) path.push("H", p[0]); - return path.join(""); - } - function d3_svg_lineStepBefore(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); - return path.join(""); - } - function d3_svg_lineStepAfter(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); - return path.join(""); - } - function d3_svg_lineCardinalOpen(points, tension) { - return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); - } - function d3_svg_lineCardinalClosed(points, tension) { - return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), - points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + return result } - function d3_svg_lineCardinal(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + + //Return data + var coallesced = coallesceUniforms(uniforms, true) + return { + get: identity(processObject(coallesced)), + set: makeSetter(coallesced), + enumerable: true, + configurable: true } - function d3_svg_lineHermite(points, tangents) { - if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { - return d3_svg_lineLinear(points); - } - var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; - if (quad) { - path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; - p0 = points[1]; - pi = 2; - } - if (tangents.length > 1) { - t = tangents[1]; - p = points[pi]; - pi++; - path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - for (var i = 2; i < tangents.length; i++, pi++) { - p = points[pi]; - t = tangents[i]; - path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; +} + +},{"./GLError":95,"./reflect":98}],98:[function(require,module,exports){ +'use strict' + +module.exports = makeReflectTypes + +//Construct type info for reflection. +// +// This iterates over the flattened list of uniform type values and smashes them into a JSON object. +// +// The leaves of the resulting object are either indices or type strings representing primitive glslify types +function makeReflectTypes(uniforms, useIndex) { + var obj = {} + for(var i=0; i 1) { + if(!(x[0] in o)) { + o[x[0]] = [] + } + o = o[x[0]] + for(var k=1; k 1) { + for(var j=0; j 9) { - s = d * 3 / Math.sqrt(s); - m[i] = s * a; - m[i + 1] = s * b; - } + return result +} + +},{}],100:[function(require,module,exports){ +'use strict' + +exports.shader = getShaderReference +exports.program = createProgram + +var GLError = require("./GLError") +var formatCompilerError = require('gl-format-compiler-error'); + +var weakMap = typeof WeakMap === 'undefined' ? require('weakmap-shim') : WeakMap +var CACHE = new weakMap() + +var SHADER_COUNTER = 0 + +function ShaderReference(id, src, type, shader, programs, count, cache) { + this.id = id + this.src = src + this.type = type + this.shader = shader + this.count = count + this.programs = [] + this.cache = cache +} + +ShaderReference.prototype.dispose = function() { + if(--this.count === 0) { + var cache = this.cache + var gl = cache.gl + + //Remove program references + var programs = this.programs + for(var i=0, n=programs.length; i π) + ",1 " + p; + return program +} + +proto.getProgram = function(vref, fref, attribs, locations) { + var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') + var prog = this.programs[token] + if(!prog || !this.gl.isProgram(prog)) { + this.programs[token] = prog = linkProgram( + this.gl, + vref.shader, + fref.shader, + attribs, + locations) + vref.programs.push(token) + fref.programs.push(token) + } + return prog +} + +function getCache(gl) { + var ctxCache = CACHE.get(gl) + if(!ctxCache) { + ctxCache = new ContextCache(gl) + CACHE.set(gl, ctxCache) + } + return ctxCache +} + +function getShaderReference(gl, type, src) { + return getCache(gl).getShaderReference(type, src) +} + +function createProgram(gl, vref, fref, attribs, locations) { + return getCache(gl).getProgram(vref, fref, attribs, locations) +} + +},{"./GLError":95,"gl-format-compiler-error":101,"weakmap-shim":119}],101:[function(require,module,exports){ + +var sprintf = require('sprintf-js').sprintf; +var glConstants = require('gl-constants/lookup'); +var shaderName = require('glsl-shader-name'); +var addLineNumbers = require('add-line-numbers'); + +module.exports = formatCompilerError; + +function formatCompilerError(errLog, src, type) { + "use strict"; + + var name = shaderName(src) || 'of unknown name (see npm glsl-shader-name)'; + + var typeName = 'unknown type'; + if (type !== undefined) { + typeName = type === glConstants.FRAGMENT_SHADER ? 'fragment' : 'vertex' } - function curve(r0, p0, r1, p1) { - return "Q 0,0 " + p1; + + var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name); + var shortForm = sprintf("%s%s", longForm, errLog); + + var errorStrings = errLog.split('\n'); + var errors = {}; + + for (var i = 0; i < errorStrings.length; i++) { + var errorString = errorStrings[i]; + if (errorString === '') continue; + var lineNo = parseInt(errorString.split(':')[2]); + if (isNaN(lineNo)) { + throw new Error(sprintf('Could not parse error: %s', errorString)); + } + errors[lineNo] = errorString; } - chord.radius = function(v) { - if (!arguments.length) return radius; - radius = d3_functor(v); - return chord; - }; - chord.source = function(v) { - if (!arguments.length) return source; - source = d3_functor(v); - return chord; - }; - chord.target = function(v) { - if (!arguments.length) return target; - target = d3_functor(v); - return chord; - }; - chord.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return chord; - }; - chord.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return chord; - }; - return chord; - }; - function d3_svg_chordRadius(d) { - return d.radius; - } - d3.svg.diagonal = function() { - var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; - function diagonal(d, i) { - var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { - x: p0.x, - y: m - }, { - x: p3.x, - y: m - }, p3 ]; - p = p.map(projection); - return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + + var lines = addLineNumbers(src).split('\n'); + + for (var i = 0; i < lines.length; i++) { + if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue; + var line = lines[i]; + longForm += line + '\n'; + if (errors[i+1]) { + var e = errors[i+1]; + e = e.substr(e.split(':', 3).join(':').length + 1).trim(); + longForm += sprintf('^^^ %s\n\n', e); + } } - diagonal.source = function(x) { - if (!arguments.length) return source; - source = d3_functor(x); - return diagonal; - }; - diagonal.target = function(x) { - if (!arguments.length) return target; - target = d3_functor(x); - return diagonal; - }; - diagonal.projection = function(x) { - if (!arguments.length) return projection; - projection = x; - return diagonal; + + return { + long: longForm.trim(), + short: shortForm.trim() }; - return diagonal; - }; - function d3_svg_diagonalProjection(d) { - return [ d.x, d.y ]; +} + + +},{"add-line-numbers":102,"gl-constants/lookup":106,"glsl-shader-name":107,"sprintf-js":116}],102:[function(require,module,exports){ +var padLeft = require('pad-left') + +module.exports = addLineNumbers +function addLineNumbers (string, start, delim) { + start = typeof start === 'number' ? start : 1 + delim = delim || ': ' + + var lines = string.split(/\r?\n/) + var totalDigits = String(lines.length + start - 1).length + return lines.map(function (line, i) { + var c = i + start + var digits = String(c).length + var prefix = padLeft(c, totalDigits - digits) + return prefix + delim + line + }).join('\n') +} + +},{"pad-left":103}],103:[function(require,module,exports){ +/*! + * pad-left + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT license. + */ + +'use strict'; + +var repeat = require('repeat-string'); + +module.exports = function padLeft(str, num, ch) { + ch = typeof ch !== 'undefined' ? (ch + '') : ' '; + return repeat(ch, num) + str; +}; +},{"repeat-string":104}],104:[function(require,module,exports){ +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +'use strict'; + +/** + * Results cache + */ + +var res = ''; +var cache; + +/** + * Expose `repeat` + */ + +module.exports = repeat; + +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ + +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('repeat-string expects a string.'); } - d3.svg.diagonal.radial = function() { - var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; - diagonal.projection = function(x) { - return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; - }; - return diagonal; - }; - function d3_svg_diagonalRadialProjection(projection) { - return function() { - var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; - return [ r * Math.cos(a), r * Math.sin(a) ]; - }; + + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; + + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; } - d3.svg.symbol = function() { - var type = d3_svg_symbolType, size = d3_svg_symbolSize; - function symbol(d, i) { - return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + + while (max > res.length && num > 0) { + if (num & 1) { + res += str; } - symbol.type = function(x) { - if (!arguments.length) return type; - type = d3_functor(x); - return symbol; - }; - symbol.size = function(x) { - if (!arguments.length) return size; - size = d3_functor(x); - return symbol; - }; - return symbol; - }; - function d3_svg_symbolSize() { - return 64; - } - function d3_svg_symbolType() { - return "circle"; + + num >>= 1; + if (!num) break; + str += str; } - function d3_svg_symbolCircle(size) { - var r = Math.sqrt(size / π); - return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + + return res.substr(0, max); +} + + +},{}],105:[function(require,module,exports){ +module.exports = { + 0: 'NONE', + 1: 'ONE', + 2: 'LINE_LOOP', + 3: 'LINE_STRIP', + 4: 'TRIANGLES', + 5: 'TRIANGLE_STRIP', + 6: 'TRIANGLE_FAN', + 256: 'DEPTH_BUFFER_BIT', + 512: 'NEVER', + 513: 'LESS', + 514: 'EQUAL', + 515: 'LEQUAL', + 516: 'GREATER', + 517: 'NOTEQUAL', + 518: 'GEQUAL', + 519: 'ALWAYS', + 768: 'SRC_COLOR', + 769: 'ONE_MINUS_SRC_COLOR', + 770: 'SRC_ALPHA', + 771: 'ONE_MINUS_SRC_ALPHA', + 772: 'DST_ALPHA', + 773: 'ONE_MINUS_DST_ALPHA', + 774: 'DST_COLOR', + 775: 'ONE_MINUS_DST_COLOR', + 776: 'SRC_ALPHA_SATURATE', + 1024: 'STENCIL_BUFFER_BIT', + 1028: 'FRONT', + 1029: 'BACK', + 1032: 'FRONT_AND_BACK', + 1280: 'INVALID_ENUM', + 1281: 'INVALID_VALUE', + 1282: 'INVALID_OPERATION', + 1285: 'OUT_OF_MEMORY', + 1286: 'INVALID_FRAMEBUFFER_OPERATION', + 2304: 'CW', + 2305: 'CCW', + 2849: 'LINE_WIDTH', + 2884: 'CULL_FACE', + 2885: 'CULL_FACE_MODE', + 2886: 'FRONT_FACE', + 2928: 'DEPTH_RANGE', + 2929: 'DEPTH_TEST', + 2930: 'DEPTH_WRITEMASK', + 2931: 'DEPTH_CLEAR_VALUE', + 2932: 'DEPTH_FUNC', + 2960: 'STENCIL_TEST', + 2961: 'STENCIL_CLEAR_VALUE', + 2962: 'STENCIL_FUNC', + 2963: 'STENCIL_VALUE_MASK', + 2964: 'STENCIL_FAIL', + 2965: 'STENCIL_PASS_DEPTH_FAIL', + 2966: 'STENCIL_PASS_DEPTH_PASS', + 2967: 'STENCIL_REF', + 2968: 'STENCIL_WRITEMASK', + 2978: 'VIEWPORT', + 3024: 'DITHER', + 3042: 'BLEND', + 3088: 'SCISSOR_BOX', + 3089: 'SCISSOR_TEST', + 3106: 'COLOR_CLEAR_VALUE', + 3107: 'COLOR_WRITEMASK', + 3317: 'UNPACK_ALIGNMENT', + 3333: 'PACK_ALIGNMENT', + 3379: 'MAX_TEXTURE_SIZE', + 3386: 'MAX_VIEWPORT_DIMS', + 3408: 'SUBPIXEL_BITS', + 3410: 'RED_BITS', + 3411: 'GREEN_BITS', + 3412: 'BLUE_BITS', + 3413: 'ALPHA_BITS', + 3414: 'DEPTH_BITS', + 3415: 'STENCIL_BITS', + 3553: 'TEXTURE_2D', + 4352: 'DONT_CARE', + 4353: 'FASTEST', + 4354: 'NICEST', + 5120: 'BYTE', + 5121: 'UNSIGNED_BYTE', + 5122: 'SHORT', + 5123: 'UNSIGNED_SHORT', + 5124: 'INT', + 5125: 'UNSIGNED_INT', + 5126: 'FLOAT', + 5386: 'INVERT', + 5890: 'TEXTURE', + 6401: 'STENCIL_INDEX', + 6402: 'DEPTH_COMPONENT', + 6406: 'ALPHA', + 6407: 'RGB', + 6408: 'RGBA', + 6409: 'LUMINANCE', + 6410: 'LUMINANCE_ALPHA', + 7680: 'KEEP', + 7681: 'REPLACE', + 7682: 'INCR', + 7683: 'DECR', + 7936: 'VENDOR', + 7937: 'RENDERER', + 7938: 'VERSION', + 9728: 'NEAREST', + 9729: 'LINEAR', + 9984: 'NEAREST_MIPMAP_NEAREST', + 9985: 'LINEAR_MIPMAP_NEAREST', + 9986: 'NEAREST_MIPMAP_LINEAR', + 9987: 'LINEAR_MIPMAP_LINEAR', + 10240: 'TEXTURE_MAG_FILTER', + 10241: 'TEXTURE_MIN_FILTER', + 10242: 'TEXTURE_WRAP_S', + 10243: 'TEXTURE_WRAP_T', + 10497: 'REPEAT', + 10752: 'POLYGON_OFFSET_UNITS', + 16384: 'COLOR_BUFFER_BIT', + 32769: 'CONSTANT_COLOR', + 32770: 'ONE_MINUS_CONSTANT_COLOR', + 32771: 'CONSTANT_ALPHA', + 32772: 'ONE_MINUS_CONSTANT_ALPHA', + 32773: 'BLEND_COLOR', + 32774: 'FUNC_ADD', + 32777: 'BLEND_EQUATION_RGB', + 32778: 'FUNC_SUBTRACT', + 32779: 'FUNC_REVERSE_SUBTRACT', + 32819: 'UNSIGNED_SHORT_4_4_4_4', + 32820: 'UNSIGNED_SHORT_5_5_5_1', + 32823: 'POLYGON_OFFSET_FILL', + 32824: 'POLYGON_OFFSET_FACTOR', + 32854: 'RGBA4', + 32855: 'RGB5_A1', + 32873: 'TEXTURE_BINDING_2D', + 32926: 'SAMPLE_ALPHA_TO_COVERAGE', + 32928: 'SAMPLE_COVERAGE', + 32936: 'SAMPLE_BUFFERS', + 32937: 'SAMPLES', + 32938: 'SAMPLE_COVERAGE_VALUE', + 32939: 'SAMPLE_COVERAGE_INVERT', + 32968: 'BLEND_DST_RGB', + 32969: 'BLEND_SRC_RGB', + 32970: 'BLEND_DST_ALPHA', + 32971: 'BLEND_SRC_ALPHA', + 33071: 'CLAMP_TO_EDGE', + 33170: 'GENERATE_MIPMAP_HINT', + 33189: 'DEPTH_COMPONENT16', + 33306: 'DEPTH_STENCIL_ATTACHMENT', + 33635: 'UNSIGNED_SHORT_5_6_5', + 33648: 'MIRRORED_REPEAT', + 33901: 'ALIASED_POINT_SIZE_RANGE', + 33902: 'ALIASED_LINE_WIDTH_RANGE', + 33984: 'TEXTURE0', + 33985: 'TEXTURE1', + 33986: 'TEXTURE2', + 33987: 'TEXTURE3', + 33988: 'TEXTURE4', + 33989: 'TEXTURE5', + 33990: 'TEXTURE6', + 33991: 'TEXTURE7', + 33992: 'TEXTURE8', + 33993: 'TEXTURE9', + 33994: 'TEXTURE10', + 33995: 'TEXTURE11', + 33996: 'TEXTURE12', + 33997: 'TEXTURE13', + 33998: 'TEXTURE14', + 33999: 'TEXTURE15', + 34000: 'TEXTURE16', + 34001: 'TEXTURE17', + 34002: 'TEXTURE18', + 34003: 'TEXTURE19', + 34004: 'TEXTURE20', + 34005: 'TEXTURE21', + 34006: 'TEXTURE22', + 34007: 'TEXTURE23', + 34008: 'TEXTURE24', + 34009: 'TEXTURE25', + 34010: 'TEXTURE26', + 34011: 'TEXTURE27', + 34012: 'TEXTURE28', + 34013: 'TEXTURE29', + 34014: 'TEXTURE30', + 34015: 'TEXTURE31', + 34016: 'ACTIVE_TEXTURE', + 34024: 'MAX_RENDERBUFFER_SIZE', + 34041: 'DEPTH_STENCIL', + 34055: 'INCR_WRAP', + 34056: 'DECR_WRAP', + 34067: 'TEXTURE_CUBE_MAP', + 34068: 'TEXTURE_BINDING_CUBE_MAP', + 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', + 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', + 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', + 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', + 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', + 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', + 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', + 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', + 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', + 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', + 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', + 34342: 'CURRENT_VERTEX_ATTRIB', + 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', + 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', + 34467: 'COMPRESSED_TEXTURE_FORMATS', + 34660: 'BUFFER_SIZE', + 34661: 'BUFFER_USAGE', + 34816: 'STENCIL_BACK_FUNC', + 34817: 'STENCIL_BACK_FAIL', + 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', + 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', + 34877: 'BLEND_EQUATION_ALPHA', + 34921: 'MAX_VERTEX_ATTRIBS', + 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', + 34930: 'MAX_TEXTURE_IMAGE_UNITS', + 34962: 'ARRAY_BUFFER', + 34963: 'ELEMENT_ARRAY_BUFFER', + 34964: 'ARRAY_BUFFER_BINDING', + 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', + 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', + 35040: 'STREAM_DRAW', + 35044: 'STATIC_DRAW', + 35048: 'DYNAMIC_DRAW', + 35632: 'FRAGMENT_SHADER', + 35633: 'VERTEX_SHADER', + 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', + 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', + 35663: 'SHADER_TYPE', + 35664: 'FLOAT_VEC2', + 35665: 'FLOAT_VEC3', + 35666: 'FLOAT_VEC4', + 35667: 'INT_VEC2', + 35668: 'INT_VEC3', + 35669: 'INT_VEC4', + 35670: 'BOOL', + 35671: 'BOOL_VEC2', + 35672: 'BOOL_VEC3', + 35673: 'BOOL_VEC4', + 35674: 'FLOAT_MAT2', + 35675: 'FLOAT_MAT3', + 35676: 'FLOAT_MAT4', + 35678: 'SAMPLER_2D', + 35680: 'SAMPLER_CUBE', + 35712: 'DELETE_STATUS', + 35713: 'COMPILE_STATUS', + 35714: 'LINK_STATUS', + 35715: 'VALIDATE_STATUS', + 35716: 'INFO_LOG_LENGTH', + 35717: 'ATTACHED_SHADERS', + 35718: 'ACTIVE_UNIFORMS', + 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', + 35720: 'SHADER_SOURCE_LENGTH', + 35721: 'ACTIVE_ATTRIBUTES', + 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', + 35724: 'SHADING_LANGUAGE_VERSION', + 35725: 'CURRENT_PROGRAM', + 36003: 'STENCIL_BACK_REF', + 36004: 'STENCIL_BACK_VALUE_MASK', + 36005: 'STENCIL_BACK_WRITEMASK', + 36006: 'FRAMEBUFFER_BINDING', + 36007: 'RENDERBUFFER_BINDING', + 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', + 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', + 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', + 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', + 36053: 'FRAMEBUFFER_COMPLETE', + 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', + 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', + 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', + 36061: 'FRAMEBUFFER_UNSUPPORTED', + 36064: 'COLOR_ATTACHMENT0', + 36096: 'DEPTH_ATTACHMENT', + 36128: 'STENCIL_ATTACHMENT', + 36160: 'FRAMEBUFFER', + 36161: 'RENDERBUFFER', + 36162: 'RENDERBUFFER_WIDTH', + 36163: 'RENDERBUFFER_HEIGHT', + 36164: 'RENDERBUFFER_INTERNAL_FORMAT', + 36168: 'STENCIL_INDEX8', + 36176: 'RENDERBUFFER_RED_SIZE', + 36177: 'RENDERBUFFER_GREEN_SIZE', + 36178: 'RENDERBUFFER_BLUE_SIZE', + 36179: 'RENDERBUFFER_ALPHA_SIZE', + 36180: 'RENDERBUFFER_DEPTH_SIZE', + 36181: 'RENDERBUFFER_STENCIL_SIZE', + 36194: 'RGB565', + 36336: 'LOW_FLOAT', + 36337: 'MEDIUM_FLOAT', + 36338: 'HIGH_FLOAT', + 36339: 'LOW_INT', + 36340: 'MEDIUM_INT', + 36341: 'HIGH_INT', + 36346: 'SHADER_COMPILER', + 36347: 'MAX_VERTEX_UNIFORM_VECTORS', + 36348: 'MAX_VARYING_VECTORS', + 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', + 37440: 'UNPACK_FLIP_Y_WEBGL', + 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', + 37442: 'CONTEXT_LOST_WEBGL', + 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', + 37444: 'BROWSER_DEFAULT_WEBGL' +} + +},{}],106:[function(require,module,exports){ +var gl10 = require('./1.0/numbers') + +module.exports = function lookupConstant (number) { + return gl10[number] +} + +},{"./1.0/numbers":105}],107:[function(require,module,exports){ +var tokenize = require('glsl-tokenizer') +var atob = require('atob-lite') + +module.exports = getName + +function getName(src) { + var tokens = Array.isArray(src) + ? src + : tokenize(src) + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i] + if (token.type !== 'preprocessor') continue + var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) + if (!match) continue + if (!match[2]) continue + + var b64 = match[1] + var name = match[2] + + return (b64 ? atob(name) : name).trim() } - var d3_svg_symbols = d3.map({ - circle: d3_svg_symbolCircle, - cross: function(size) { - var r = Math.sqrt(size / 5) / 2; - return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; - }, - diamond: function(size) { - var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; - return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; - }, - square: function(size) { - var r = Math.sqrt(size) / 2; - return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; - }, - "triangle-down": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; - }, - "triangle-up": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; - } - }); - d3.svg.symbolTypes = d3_svg_symbols.keys(); - var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); - d3_selectionPrototype.transition = function(name) { - var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { - time: Date.now(), - ease: d3_ease_cubicInOut, - delay: 0, - duration: 250 - }; - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); - subgroup.push(node); - } - } - return d3_transition(subgroups, ns, id); - }; - d3_selectionPrototype.interrupt = function(name) { - return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); - }; - var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); - function d3_selection_interruptNS(ns) { - return function() { - var lock, activeId, active; - if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { - active.timer.c = null; - active.timer.t = NaN; - if (--lock.count) delete lock[activeId]; else delete this[ns]; - lock.active += .5; - active.event && active.event.interrupt.call(this, this.__data__, active.index); - } - }; +} + +},{"atob-lite":108,"glsl-tokenizer":115}],108:[function(require,module,exports){ +module.exports = function _atob(str) { + return atob(str) +} + +},{}],109:[function(require,module,exports){ +module.exports = tokenize + +var literals100 = require('./lib/literals') + , operators = require('./lib/operators') + , builtins100 = require('./lib/builtins') + , literals300es = require('./lib/literals-300es') + , builtins300es = require('./lib/builtins-300es') + +var NORMAL = 999 // <-- never emitted + , TOKEN = 9999 // <-- never emitted + , BLOCK_COMMENT = 0 + , LINE_COMMENT = 1 + , PREPROCESSOR = 2 + , OPERATOR = 3 + , INTEGER = 4 + , FLOAT = 5 + , IDENT = 6 + , BUILTIN = 7 + , KEYWORD = 8 + , WHITESPACE = 9 + , EOF = 10 + , HEX = 11 + +var map = [ + 'block-comment' + , 'line-comment' + , 'preprocessor' + , 'operator' + , 'integer' + , 'float' + , 'ident' + , 'builtin' + , 'keyword' + , 'whitespace' + , 'eof' + , 'integer' +] + +function tokenize(opt) { + var i = 0 + , total = 0 + , mode = NORMAL + , c + , last + , content = [] + , tokens = [] + , token_idx = 0 + , token_offs = 0 + , line = 1 + , col = 0 + , start = 0 + , isnum = false + , isoperator = false + , input = '' + , len + + opt = opt || {} + var allBuiltins = builtins100 + var allLiterals = literals100 + if (opt.version === '300 es') { + allBuiltins = builtins300es + allLiterals = literals300es } - function d3_transition(groups, ns, id) { - d3_subclass(groups, d3_transitionPrototype); - groups.namespace = ns; - groups.id = id; - return groups; + + return function(data) { + tokens = [] + if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data) + return end() } - var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; - d3_transitionPrototype.call = d3_selectionPrototype.call; - d3_transitionPrototype.empty = d3_selectionPrototype.empty; - d3_transitionPrototype.node = d3_selectionPrototype.node; - d3_transitionPrototype.size = d3_selectionPrototype.size; - d3.transition = function(selection, name) { - return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); - }; - d3.transition.prototype = d3_transitionPrototype; - d3_transitionPrototype.select = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { - if ("__data__" in node) subnode.__data__ = node.__data__; - d3_transitionNode(subnode, i, ns, id, node[ns][id]); - subgroup.push(subnode); - } else { - subgroup.push(null); - } - } + + function token(data) { + if (data.length) { + tokens.push({ + type: map[mode] + , data: data + , position: start + , line: line + , column: col + }) } - return d3_transition(subgroups, ns, id); - }; - d3_transitionPrototype.selectAll = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - transition = node[ns][id]; - subnodes = selector.call(node, node.__data__, i, j); - subgroups.push(subgroup = []); - for (var k = -1, o = subnodes.length; ++k < o; ) { - if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); - subgroup.push(subnode); - } - } + } + + function write(chunk) { + i = 0 + input += chunk + len = input.length + + var last + + while(c = input[i], i < len) { + last = i + + switch(mode) { + case BLOCK_COMMENT: i = block_comment(); break + case LINE_COMMENT: i = line_comment(); break + case PREPROCESSOR: i = preprocessor(); break + case OPERATOR: i = operator(); break + case INTEGER: i = integer(); break + case HEX: i = hex(); break + case FLOAT: i = decimal(); break + case TOKEN: i = readtoken(); break + case WHITESPACE: i = whitespace(); break + case NORMAL: i = normal(); break } - } - return d3_transition(subgroups, ns, id); - }; - d3_transitionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); + + if(last !== i) { + switch(input[last]) { + case '\n': col = 0; ++line; break + default: ++col; break } } } - return d3_transition(subgroups, this.namespace, this.id); - }; - d3_transitionPrototype.tween = function(name, tween) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) return this.node()[ns][id].tween.get(name); - return d3_selection_each(this, tween == null ? function(node) { - node[ns][id].tween.remove(name); - } : function(node) { - node[ns][id].tween.set(name, tween); - }); - }; - function d3_transition_tween(groups, name, value, tween) { - var id = groups.id, ns = groups.namespace; - return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { - node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); - } : (value = tween(value), function(node) { - node[ns][id].tween.set(name, value); - })); + + total += i + input = input.slice(i) + return tokens } - d3_transitionPrototype.attr = function(nameNS, value) { - if (arguments.length < 2) { - for (value in nameNS) this.attr(value, nameNS[value]); - return this; + + function end(chunk) { + if(content.length) { + token(content.join('')) } - var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); - function attrNull() { - this.removeAttribute(name); + + mode = EOF + token('(eof)') + return tokens + } + + function normal() { + content = content.length ? [] : content + + if(last === '/' && c === '*') { + start = total + i - 1 + mode = BLOCK_COMMENT + last = c + return i + 1 } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); + + if(last === '/' && c === '/') { + start = total + i - 1 + mode = LINE_COMMENT + last = c + return i + 1 } - function attrTween(b) { - return b == null ? attrNull : (b += "", function() { - var a = this.getAttribute(name), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttribute(name, i(t)); - }); - }); + + if(c === '#') { + mode = PREPROCESSOR + start = total + i + return i } - function attrTweenNS(b) { - return b == null ? attrNullNS : (b += "", function() { - var a = this.getAttributeNS(name.space, name.local), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttributeNS(name.space, name.local, i(t)); - }); - }); + + if(/\s/.test(c)) { + mode = WHITESPACE + start = total + i + return i } - return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.attrTween = function(nameNS, tween) { - var name = d3.ns.qualify(nameNS); - function attrTween(d, i) { - var f = tween.call(this, d, i, this.getAttribute(name)); - return f && function(t) { - this.setAttribute(name, f(t)); - }; + + isnum = /\d/.test(c) + isoperator = /[^\w_]/.test(c) + + start = total + i + mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN + return i + } + + function whitespace() { + if(/[^\s]/g.test(c)) { + token(content.join('')) + mode = NORMAL + return i } - function attrTweenNS(d, i) { - var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); - return f && function(t) { - this.setAttributeNS(name.space, name.local, f(t)); - }; + content.push(c) + last = c + return i + 1 + } + + function preprocessor() { + if((c === '\r' || c === '\n') && last !== '\\') { + token(content.join('')) + mode = NORMAL + return i } - return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.style(priority, name[priority], value); - return this; - } - priority = ""; + content.push(c) + last = c + return i + 1 + } + + function line_comment() { + return preprocessor() + } + + function block_comment() { + if(c === '/' && last === '*') { + content.push(c) + token(content.join('')) + mode = NORMAL + return i + 1 } - function styleNull() { - this.style.removeProperty(name); + + content.push(c) + last = c + return i + 1 + } + + function operator() { + if(last === '.' && /\d/.test(c)) { + mode = FLOAT + return i } - function styleString(b) { - return b == null ? styleNull : (b += "", function() { - var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; - return a !== b && (i = d3_interpolate(a, b), function(t) { - this.style.setProperty(name, i(t), priority); - }); - }); + + if(last === '/' && c === '*') { + mode = BLOCK_COMMENT + return i } - return d3_transition_tween(this, "style." + name, value, styleString); - }; - d3_transitionPrototype.styleTween = function(name, tween, priority) { - if (arguments.length < 3) priority = ""; - function styleTween(d, i) { - var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); - return f && function(t) { - this.style.setProperty(name, f(t), priority); - }; + + if(last === '/' && c === '/') { + mode = LINE_COMMENT + return i } - return this.tween("style." + name, styleTween); - }; - d3_transitionPrototype.text = function(value) { - return d3_transition_tween(this, "text", value, d3_transition_text); - }; - function d3_transition_text(b) { - if (b == null) b = ""; - return function() { - this.textContent = b; - }; - } - d3_transitionPrototype.remove = function() { - var ns = this.namespace; - return this.each("end.transition", function() { - var p; - if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); - }); - }; - d3_transitionPrototype.ease = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].ease; - if (typeof value !== "function") value = d3.ease.apply(d3, arguments); - return d3_selection_each(this, function(node) { - node[ns][id].ease = value; - }); - }; - d3_transitionPrototype.delay = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].delay; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node[ns][id].delay = +value.call(node, node.__data__, i, j); - } : (value = +value, function(node) { - node[ns][id].delay = value; - })); - }; - d3_transitionPrototype.duration = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].duration; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); - } : (value = Math.max(1, value), function(node) { - node[ns][id].duration = value; - })); - }; - d3_transitionPrototype.each = function(type, listener) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) { - var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; - try { - d3_transitionInheritId = id; - d3_selection_each(this, function(node, i, j) { - d3_transitionInherit = node[ns][id]; - type.call(node, node.__data__, i, j); - }); - } finally { - d3_transitionInherit = inherit; - d3_transitionInheritId = inheritId; - } - } else { - d3_selection_each(this, function(node) { - var transition = node[ns][id]; - (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); - }); + + if(c === '.' && content.length) { + while(determine_operator(content)); + + mode = FLOAT + return i } - return this; - }; - d3_transitionPrototype.transition = function() { - var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if (node = group[i]) { - transition = node[ns][id0]; - d3_transitionNode(node, i, ns, id1, { - time: transition.time, - ease: transition.ease, - delay: transition.delay + transition.duration, - duration: transition.duration - }); - } - subgroup.push(node); + + if(c === ';' || c === ')' || c === '(') { + if(content.length) while(determine_operator(content)); + token(c) + mode = NORMAL + return i + 1 + } + + var is_composite_operator = content.length === 2 && c !== '=' + if(/[\w_\d\s]/.test(c) || is_composite_operator) { + while(determine_operator(content)); + mode = NORMAL + return i + } + + content.push(c) + last = c + return i + 1 + } + + function determine_operator(buf) { + var j = 0 + , idx + , res + + do { + idx = operators.indexOf(buf.slice(0, buf.length + j).join('')) + res = operators[idx] + + if(idx === -1) { + if(j-- + buf.length > 0) continue + res = buf.slice(0, 1).join('') } + + token(res) + + start += res.length + content = content.slice(res.length) + return content.length + } while(1) + } + + function hex() { + if(/[^a-fA-F0-9]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i } - return d3_transition(subgroups, ns, id1); - }; - function d3_transitionNamespace(name) { - return name == null ? "__transition__" : "__transition_" + name + "__"; + + content.push(c) + last = c + return i + 1 } - function d3_transitionNode(node, i, ns, id, inherit) { - var lock = node[ns] || (node[ns] = { - active: 0, - count: 0 - }), transition = lock[id], time, timer, duration, ease, tweens; - function schedule(elapsed) { - var delay = transition.delay; - timer.t = delay + time; - if (delay <= elapsed) return start(elapsed - delay); - timer.c = start; + + function integer() { + if(c === '.') { + content.push(c) + mode = FLOAT + last = c + return i + 1 } - function start(elapsed) { - var activeId = lock.active, active = lock[activeId]; - if (active) { - active.timer.c = null; - active.timer.t = NaN; - --lock.count; - delete lock[activeId]; - active.event && active.event.interrupt.call(node, node.__data__, active.index); - } - for (var cancelId in lock) { - if (+cancelId < id) { - var cancel = lock[cancelId]; - cancel.timer.c = null; - cancel.timer.t = NaN; - --lock.count; - delete lock[cancelId]; - } - } - timer.c = tick; - d3_timer(function() { - if (timer.c && tick(elapsed || 1)) { - timer.c = null; - timer.t = NaN; - } - return 1; - }, 0, time); - lock.active = id; - transition.event && transition.event.start.call(node, node.__data__, i); - tweens = []; - transition.tween.forEach(function(key, value) { - if (value = value.call(node, node.__data__, i)) { - tweens.push(value); - } - }); - ease = transition.ease; - duration = transition.duration; + + if(/[eE]/.test(c)) { + content.push(c) + mode = FLOAT + last = c + return i + 1 + } + + if(c === 'x' && content.length === 1 && content[0] === '0') { + mode = HEX + content.push(c) + last = c + return i + 1 + } + + if(/[^\d]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i + } + + content.push(c) + last = c + return i + 1 + } + + function decimal() { + if(c === 'f') { + content.push(c) + last = c + i += 1 } - function tick(elapsed) { - var t = elapsed / duration, e = ease(t), n = tweens.length; - while (n > 0) { - tweens[--n].call(node, e); - } - if (t >= 1) { - transition.event && transition.event.end.call(node, node.__data__, i); - if (--lock.count) delete lock[id]; else delete node[ns]; - return 1; + + if(/[eE]/.test(c)) { + content.push(c) + last = c + return i + 1 + } + + if (c === '-' && /[eE]/.test(last)) { + content.push(c) + last = c + return i + 1 + } + + if(/[^\d]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i + } + + content.push(c) + last = c + return i + 1 + } + + function readtoken() { + if(/[^\d\w_]/.test(c)) { + var contentstr = content.join('') + if(allLiterals.indexOf(contentstr) > -1) { + mode = KEYWORD + } else if(allBuiltins.indexOf(contentstr) > -1) { + mode = BUILTIN + } else { + mode = IDENT } + token(content.join('')) + mode = NORMAL + return i } - if (!transition) { - time = inherit.time; - timer = d3_timer(schedule, 0, time); - transition = lock[id] = { - tween: new d3_Map(), - time: time, - timer: timer, - delay: inherit.delay, - duration: inherit.duration, - ease: inherit.ease, - index: i - }; - inherit = null; - ++lock.count; + content.push(c) + last = c + return i + 1 + } +} + +},{"./lib/builtins":111,"./lib/builtins-300es":110,"./lib/literals":113,"./lib/literals-300es":112,"./lib/operators":114}],110:[function(require,module,exports){ +// 300es builtins/reserved words that were previously valid in v100 +var v100 = require('./builtins') + +// The texture2D|Cube functions have been removed +// And the gl_ features are updated +v100 = v100.slice().filter(function (b) { + return !/^(gl\_|texture)/.test(b) +}) + +module.exports = v100.concat([ + // the updated gl_ constants + 'gl_VertexID' + , 'gl_InstanceID' + , 'gl_Position' + , 'gl_PointSize' + , 'gl_FragCoord' + , 'gl_FrontFacing' + , 'gl_FragDepth' + , 'gl_PointCoord' + , 'gl_MaxVertexAttribs' + , 'gl_MaxVertexUniformVectors' + , 'gl_MaxVertexOutputVectors' + , 'gl_MaxFragmentInputVectors' + , 'gl_MaxVertexTextureImageUnits' + , 'gl_MaxCombinedTextureImageUnits' + , 'gl_MaxTextureImageUnits' + , 'gl_MaxFragmentUniformVectors' + , 'gl_MaxDrawBuffers' + , 'gl_MinProgramTexelOffset' + , 'gl_MaxProgramTexelOffset' + , 'gl_DepthRangeParameters' + , 'gl_DepthRange' + + // other builtins + , 'trunc' + , 'round' + , 'roundEven' + , 'isnan' + , 'isinf' + , 'floatBitsToInt' + , 'floatBitsToUint' + , 'intBitsToFloat' + , 'uintBitsToFloat' + , 'packSnorm2x16' + , 'unpackSnorm2x16' + , 'packUnorm2x16' + , 'unpackUnorm2x16' + , 'packHalf2x16' + , 'unpackHalf2x16' + , 'outerProduct' + , 'transpose' + , 'determinant' + , 'inverse' + , 'texture' + , 'textureSize' + , 'textureProj' + , 'textureLod' + , 'textureOffset' + , 'texelFetch' + , 'texelFetchOffset' + , 'textureProjOffset' + , 'textureLodOffset' + , 'textureProjLod' + , 'textureProjLodOffset' + , 'textureGrad' + , 'textureGradOffset' + , 'textureProjGrad' + , 'textureProjGradOffset' +]) + +},{"./builtins":111}],111:[function(require,module,exports){ +module.exports = [ + // Keep this list sorted + 'abs' + , 'acos' + , 'all' + , 'any' + , 'asin' + , 'atan' + , 'ceil' + , 'clamp' + , 'cos' + , 'cross' + , 'dFdx' + , 'dFdy' + , 'degrees' + , 'distance' + , 'dot' + , 'equal' + , 'exp' + , 'exp2' + , 'faceforward' + , 'floor' + , 'fract' + , 'gl_BackColor' + , 'gl_BackLightModelProduct' + , 'gl_BackLightProduct' + , 'gl_BackMaterial' + , 'gl_BackSecondaryColor' + , 'gl_ClipPlane' + , 'gl_ClipVertex' + , 'gl_Color' + , 'gl_DepthRange' + , 'gl_DepthRangeParameters' + , 'gl_EyePlaneQ' + , 'gl_EyePlaneR' + , 'gl_EyePlaneS' + , 'gl_EyePlaneT' + , 'gl_Fog' + , 'gl_FogCoord' + , 'gl_FogFragCoord' + , 'gl_FogParameters' + , 'gl_FragColor' + , 'gl_FragCoord' + , 'gl_FragData' + , 'gl_FragDepth' + , 'gl_FragDepthEXT' + , 'gl_FrontColor' + , 'gl_FrontFacing' + , 'gl_FrontLightModelProduct' + , 'gl_FrontLightProduct' + , 'gl_FrontMaterial' + , 'gl_FrontSecondaryColor' + , 'gl_LightModel' + , 'gl_LightModelParameters' + , 'gl_LightModelProducts' + , 'gl_LightProducts' + , 'gl_LightSource' + , 'gl_LightSourceParameters' + , 'gl_MaterialParameters' + , 'gl_MaxClipPlanes' + , 'gl_MaxCombinedTextureImageUnits' + , 'gl_MaxDrawBuffers' + , 'gl_MaxFragmentUniformComponents' + , 'gl_MaxLights' + , 'gl_MaxTextureCoords' + , 'gl_MaxTextureImageUnits' + , 'gl_MaxTextureUnits' + , 'gl_MaxVaryingFloats' + , 'gl_MaxVertexAttribs' + , 'gl_MaxVertexTextureImageUnits' + , 'gl_MaxVertexUniformComponents' + , 'gl_ModelViewMatrix' + , 'gl_ModelViewMatrixInverse' + , 'gl_ModelViewMatrixInverseTranspose' + , 'gl_ModelViewMatrixTranspose' + , 'gl_ModelViewProjectionMatrix' + , 'gl_ModelViewProjectionMatrixInverse' + , 'gl_ModelViewProjectionMatrixInverseTranspose' + , 'gl_ModelViewProjectionMatrixTranspose' + , 'gl_MultiTexCoord0' + , 'gl_MultiTexCoord1' + , 'gl_MultiTexCoord2' + , 'gl_MultiTexCoord3' + , 'gl_MultiTexCoord4' + , 'gl_MultiTexCoord5' + , 'gl_MultiTexCoord6' + , 'gl_MultiTexCoord7' + , 'gl_Normal' + , 'gl_NormalMatrix' + , 'gl_NormalScale' + , 'gl_ObjectPlaneQ' + , 'gl_ObjectPlaneR' + , 'gl_ObjectPlaneS' + , 'gl_ObjectPlaneT' + , 'gl_Point' + , 'gl_PointCoord' + , 'gl_PointParameters' + , 'gl_PointSize' + , 'gl_Position' + , 'gl_ProjectionMatrix' + , 'gl_ProjectionMatrixInverse' + , 'gl_ProjectionMatrixInverseTranspose' + , 'gl_ProjectionMatrixTranspose' + , 'gl_SecondaryColor' + , 'gl_TexCoord' + , 'gl_TextureEnvColor' + , 'gl_TextureMatrix' + , 'gl_TextureMatrixInverse' + , 'gl_TextureMatrixInverseTranspose' + , 'gl_TextureMatrixTranspose' + , 'gl_Vertex' + , 'greaterThan' + , 'greaterThanEqual' + , 'inversesqrt' + , 'length' + , 'lessThan' + , 'lessThanEqual' + , 'log' + , 'log2' + , 'matrixCompMult' + , 'max' + , 'min' + , 'mix' + , 'mod' + , 'normalize' + , 'not' + , 'notEqual' + , 'pow' + , 'radians' + , 'reflect' + , 'refract' + , 'sign' + , 'sin' + , 'smoothstep' + , 'sqrt' + , 'step' + , 'tan' + , 'texture2D' + , 'texture2DLod' + , 'texture2DProj' + , 'texture2DProjLod' + , 'textureCube' + , 'textureCubeLod' + , 'texture2DLodEXT' + , 'texture2DProjLodEXT' + , 'textureCubeLodEXT' + , 'texture2DGradEXT' + , 'texture2DProjGradEXT' + , 'textureCubeGradEXT' +] + +},{}],112:[function(require,module,exports){ +var v100 = require('./literals') + +module.exports = v100.slice().concat([ + 'layout' + , 'centroid' + , 'smooth' + , 'case' + , 'mat2x2' + , 'mat2x3' + , 'mat2x4' + , 'mat3x2' + , 'mat3x3' + , 'mat3x4' + , 'mat4x2' + , 'mat4x3' + , 'mat4x4' + , 'uint' + , 'uvec2' + , 'uvec3' + , 'uvec4' + , 'samplerCubeShadow' + , 'sampler2DArray' + , 'sampler2DArrayShadow' + , 'isampler2D' + , 'isampler3D' + , 'isamplerCube' + , 'isampler2DArray' + , 'usampler2D' + , 'usampler3D' + , 'usamplerCube' + , 'usampler2DArray' + , 'coherent' + , 'restrict' + , 'readonly' + , 'writeonly' + , 'resource' + , 'atomic_uint' + , 'noperspective' + , 'patch' + , 'sample' + , 'subroutine' + , 'common' + , 'partition' + , 'active' + , 'filter' + , 'image1D' + , 'image2D' + , 'image3D' + , 'imageCube' + , 'iimage1D' + , 'iimage2D' + , 'iimage3D' + , 'iimageCube' + , 'uimage1D' + , 'uimage2D' + , 'uimage3D' + , 'uimageCube' + , 'image1DArray' + , 'image2DArray' + , 'iimage1DArray' + , 'iimage2DArray' + , 'uimage1DArray' + , 'uimage2DArray' + , 'image1DShadow' + , 'image2DShadow' + , 'image1DArrayShadow' + , 'image2DArrayShadow' + , 'imageBuffer' + , 'iimageBuffer' + , 'uimageBuffer' + , 'sampler1DArray' + , 'sampler1DArrayShadow' + , 'isampler1D' + , 'isampler1DArray' + , 'usampler1D' + , 'usampler1DArray' + , 'isampler2DRect' + , 'usampler2DRect' + , 'samplerBuffer' + , 'isamplerBuffer' + , 'usamplerBuffer' + , 'sampler2DMS' + , 'isampler2DMS' + , 'usampler2DMS' + , 'sampler2DMSArray' + , 'isampler2DMSArray' + , 'usampler2DMSArray' +]) + +},{"./literals":113}],113:[function(require,module,exports){ +module.exports = [ + // current + 'precision' + , 'highp' + , 'mediump' + , 'lowp' + , 'attribute' + , 'const' + , 'uniform' + , 'varying' + , 'break' + , 'continue' + , 'do' + , 'for' + , 'while' + , 'if' + , 'else' + , 'in' + , 'out' + , 'inout' + , 'float' + , 'int' + , 'void' + , 'bool' + , 'true' + , 'false' + , 'discard' + , 'return' + , 'mat2' + , 'mat3' + , 'mat4' + , 'vec2' + , 'vec3' + , 'vec4' + , 'ivec2' + , 'ivec3' + , 'ivec4' + , 'bvec2' + , 'bvec3' + , 'bvec4' + , 'sampler1D' + , 'sampler2D' + , 'sampler3D' + , 'samplerCube' + , 'sampler1DShadow' + , 'sampler2DShadow' + , 'struct' + + // future + , 'asm' + , 'class' + , 'union' + , 'enum' + , 'typedef' + , 'template' + , 'this' + , 'packed' + , 'goto' + , 'switch' + , 'default' + , 'inline' + , 'noinline' + , 'volatile' + , 'public' + , 'static' + , 'extern' + , 'external' + , 'interface' + , 'long' + , 'short' + , 'double' + , 'half' + , 'fixed' + , 'unsigned' + , 'input' + , 'output' + , 'hvec2' + , 'hvec3' + , 'hvec4' + , 'dvec2' + , 'dvec3' + , 'dvec4' + , 'fvec2' + , 'fvec3' + , 'fvec4' + , 'sampler2DRect' + , 'sampler3DRect' + , 'sampler2DRectShadow' + , 'sizeof' + , 'cast' + , 'namespace' + , 'using' +] + +},{}],114:[function(require,module,exports){ +module.exports = [ + '<<=' + , '>>=' + , '++' + , '--' + , '<<' + , '>>' + , '<=' + , '>=' + , '==' + , '!=' + , '&&' + , '||' + , '+=' + , '-=' + , '*=' + , '/=' + , '%=' + , '&=' + , '^^' + , '^=' + , '|=' + , '(' + , ')' + , '[' + , ']' + , '.' + , '!' + , '~' + , '*' + , '/' + , '%' + , '+' + , '-' + , '<' + , '>' + , '&' + , '^' + , '|' + , '?' + , ':' + , '=' + , ',' + , ';' + , '{' + , '}' +] + +},{}],115:[function(require,module,exports){ +var tokenize = require('./index') + +module.exports = tokenizeString + +function tokenizeString(str, opt) { + var generator = tokenize(opt) + var tokens = [] + + tokens = tokens.concat(generator(str)) + tokens = tokens.concat(generator(null)) + + return tokens +} + +},{"./index":109}],116:[function(require,module,exports){ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[diefg]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ } - } - d3.svg.axis = function() { - var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; - function axis(g) { - g.each(function() { - var g = d3.select(this); - var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); - var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; - var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), - d3.transition(path)); - tickEnter.append("line"); - tickEnter.append("text"); - var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; - if (orient === "bottom" || orient === "top") { - tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; - text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); - } else { - tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; - text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); - pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); - } - lineEnter.attr(y2, sign * innerTickSize); - textEnter.attr(y1, sign * tickSpacing); - lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); - textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); - if (scale1.rangeBand) { - var x = scale1, dx = x.rangeBand() / 2; - scale0 = scale1 = function(d) { - return x(d) + dx; - }; - } else if (scale0.rangeBand) { - scale0 = scale1; - } else { - tickExit.call(tickTransform, scale1, scale0); + + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) } - tickEnter.call(tickTransform, scale0, scale1); - tickUpdate.call(tickTransform, scale1, scale1); - }); + return sprintf.format.call(null, cache[key], arguments) } - axis.scale = function(x) { - if (!arguments.length) return scale; - scale = x; - return axis; - }; - axis.orient = function(x) { - if (!arguments.length) return orient; - orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; - return axis; - }; - axis.ticks = function() { - if (!arguments.length) return tickArguments_; - tickArguments_ = d3_array(arguments); - return axis; - }; - axis.tickValues = function(x) { - if (!arguments.length) return tickValues; - tickValues = x; - return axis; - }; - axis.tickFormat = function(x) { - if (!arguments.length) return tickFormat_; - tickFormat_ = x; - return axis; - }; - axis.tickSize = function(x) { - var n = arguments.length; - if (!n) return innerTickSize; - innerTickSize = +x; - outerTickSize = +arguments[n - 1]; - return axis; - }; - axis.innerTickSize = function(x) { - if (!arguments.length) return innerTickSize; - innerTickSize = +x; - return axis; - }; - axis.outerTickSize = function(x) { - if (!arguments.length) return outerTickSize; - outerTickSize = +x; - return axis; - }; - axis.tickPadding = function(x) { - if (!arguments.length) return tickPadding; - tickPadding = +x; - return axis; - }; - axis.tickSubdivide = function() { - return arguments.length && axis; - }; - return axis; - }; - var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { - top: 1, - right: 1, - bottom: 1, - left: 1 - }; - function d3_svg_axisX(selection, x0, x1) { - selection.attr("transform", function(d) { - var v0 = x0(d); - return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; - }); - } - function d3_svg_axisY(selection, y0, y1) { - selection.attr("transform", function(d) { - var v0 = y0(d); - return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; - }); - } - d3.svg.brush = function() { - var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; - function brush(g) { - g.each(function() { - var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); - var background = g.selectAll(".background").data([ 0 ]); - background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); - g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); - var resize = g.selectAll(".resize").data(resizes, d3_identity); - resize.exit().remove(); - resize.enter().append("g").attr("class", function(d) { - return "resize " + d; - }).style("cursor", function(d) { - return d3_svg_brushCursor[d]; - }).append("rect").attr("x", function(d) { - return /[ew]$/.test(d) ? -3 : null; - }).attr("y", function(d) { - return /^[ns]/.test(d) ? -3 : null; - }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); - resize.style("display", brush.empty() ? "none" : null); - var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; - if (x) { - range = d3_scaleRange(x); - backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); - redrawX(gUpdate); - } - if (y) { - range = d3_scaleRange(y); - backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); - redrawY(gUpdate); + + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "j": + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "g": + arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output[output.length] = arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } } - redraw(gUpdate); - }); + return output.join("") } - brush.event = function(g) { - g.each(function() { - var event_ = event.of(this, arguments), extent1 = { - x: xExtent, - y: yExtent, - i: xExtentDomain, - j: yExtentDomain - }, extent0 = this.__chart__ || extent1; - this.__chart__ = extent1; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.brush", function() { - xExtentDomain = extent0.i; - yExtentDomain = extent0.j; - xExtent = extent0.x; - yExtent = extent0.y; - event_({ - type: "brushstart" - }); - }).tween("brush:brush", function() { - var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); - xExtentDomain = yExtentDomain = null; - return function(t) { - xExtent = extent1.x = xi(t); - yExtent = extent1.y = yi(t); - event_({ - type: "brush", - mode: "resize" - }); - }; - }).each("end.brush", function() { - xExtentDomain = extent1.i; - yExtentDomain = extent1.j; - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); - }); - } else { - event_({ - type: "brushstart" - }); - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); + + sprintf.cache = {} + + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) } - }); - }; - function redraw(g) { - g.selectAll(".resize").attr("transform", function(d) { - return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; - }); + return parse_tree } - function redrawX(g) { - g.select(".extent").attr("x", xExtent[0]); - g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) } - function redrawY(g) { - g.select(".extent").attr("y", yExtent[0]); - g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() } - function brushstart() { - var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; - var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); - if (d3.event.changedTouches) { - w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); - } else { - w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); - } - g.interrupt().selectAll("*").interrupt(); - if (dragging) { - origin[0] = xExtent[0] - origin[0]; - origin[1] = yExtent[0] - origin[1]; - } else if (resizing) { - var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); - offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; - origin[0] = xExtent[ex]; - origin[1] = yExtent[ey]; - } else if (d3.event.altKey) center = origin.slice(); - g.style("pointer-events", "none").selectAll(".resize").style("display", null); - d3.select("body").style("cursor", eventTarget.style("cursor")); - event_({ - type: "brushstart" - }); - brushmove(); - function keydown() { - if (d3.event.keyCode == 32) { - if (!dragging) { - center = null; - origin[0] -= xExtent[1]; - origin[1] -= yExtent[1]; - dragging = 2; - } - d3_eventPreventDefault(); - } - } - function keyup() { - if (d3.event.keyCode == 32 && dragging == 2) { - origin[0] += xExtent[1]; - origin[1] += yExtent[1]; - dragging = 0; - d3_eventPreventDefault(); - } - } - function brushmove() { - var point = d3.mouse(target), moved = false; - if (offset) { - point[0] += offset[0]; - point[1] += offset[1]; - } - if (!dragging) { - if (d3.event.altKey) { - if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; - origin[0] = xExtent[+(point[0] < center[0])]; - origin[1] = yExtent[+(point[1] < center[1])]; - } else center = null; - } - if (resizingX && move1(point, x, 0)) { - redrawX(g); - moved = true; - } - if (resizingY && move1(point, y, 1)) { - redrawY(g); - moved = true; - } - if (moved) { - redraw(g); - event_({ - type: "brush", - mode: dragging ? "move" : "resize" - }); - } - } - function move1(point, scale, i) { - var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; - if (dragging) { - r0 -= position; - r1 -= size + position; - } - min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; - if (dragging) { - max = (min += position) + size; - } else { - if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); - if (position < min) { - max = min; - min = position; - } else { - max = position; - } - } - if (extent[0] != min || extent[1] != max) { - if (i) yExtentDomain = null; else xExtentDomain = null; - extent[0] = min; - extent[1] = max; - return true; - } - } - function brushend() { - brushmove(); - g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); - d3.select("body").style("cursor", null); - w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); - dragRestore(); - event_({ - type: "brushend" - }); - } + + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } + + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf } - brush.x = function(z) { - if (!arguments.length) return x; - x = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.y = function(z) { - if (!arguments.length) return y; - y = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.clamp = function(z) { - if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; - if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; - return brush; - }; - brush.extent = function(z) { - var x0, x1, y0, y1, t; - if (!arguments.length) { - if (x) { - if (xExtentDomain) { - x0 = xExtentDomain[0], x1 = xExtentDomain[1]; - } else { - x0 = xExtent[0], x1 = xExtent[1]; - if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf + + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) } - if (y) { - if (yExtentDomain) { - y0 = yExtentDomain[0], y1 = yExtentDomain[1]; - } else { - y0 = yExtent[0], y1 = yExtent[1]; - if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - } + } +})(typeof window === "undefined" ? this : window); + +},{}],117:[function(require,module,exports){ +var hiddenStore = require('./hidden-store.js'); + +module.exports = createStore; + +function createStore() { + var key = {}; + + return function (obj) { + if ((typeof obj !== 'object' || obj === null) && + typeof obj !== 'function' + ) { + throw new Error('Weakmap-shim: Key must be object') } - return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; - } - if (x) { - x0 = z[0], x1 = z[1]; - if (y) x0 = x0[0], x1 = x1[0]; - xExtentDomain = [ x0, x1 ]; - if (x.invert) x0 = x(x0), x1 = x(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; - } - if (y) { - y0 = z[0], y1 = z[1]; - if (x) y0 = y0[1], y1 = y1[1]; - yExtentDomain = [ y0, y1 ]; - if (y.invert) y0 = y(y0), y1 = y(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; - } - return brush; - }; - brush.clear = function() { - if (!brush.empty()) { - xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; - xExtentDomain = yExtentDomain = null; - } - return brush; - }; - brush.empty = function() { - return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + + var store = obj.valueOf(key); + return store && store.identity === key ? + store : hiddenStore(obj, key); }; - return d3.rebind(brush, event, "on"); - }; - var d3_svg_brushCursor = { - n: "ns-resize", - e: "ew-resize", - s: "ns-resize", - w: "ew-resize", - nw: "nwse-resize", - ne: "nesw-resize", - se: "nwse-resize", - sw: "nesw-resize" - }; - var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; - var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; - var d3_time_formatUtc = d3_time_format.utc; - var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); - d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; - function d3_time_formatIsoNative(date) { - return date.toISOString(); +} + +},{"./hidden-store.js":118}],118:[function(require,module,exports){ +module.exports = hiddenStore; + +function hiddenStore(obj, key) { + var store = { identity: key }; + var valueOf = obj.valueOf; + + Object.defineProperty(obj, "valueOf", { + value: function (value) { + return value !== key ? + valueOf.apply(this, arguments) : store; + }, + writable: true + }); + + return store; +} + +},{}],119:[function(require,module,exports){ +// Original - @Gozola. +// https://gist.github.com/Gozala/1269991 +// This is a reimplemented version (with a few bug fixes). + +var createStore = require('./create-store.js'); + +module.exports = weakMap; + +function weakMap() { + var privates = createStore(); + + return { + 'get': function (key, fallback) { + var store = privates(key) + return store.hasOwnProperty('value') ? + store.value : fallback + }, + 'set': function (key, value) { + privates(key).value = value; + }, + 'has': function(key) { + return 'value' in privates(key); + }, + 'delete': function (key) { + return delete privates(key).value; + } + } +} + +},{"./create-store.js":117}],120:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],121:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],122:[function(require,module,exports){ +(function (global,Buffer){ +'use strict' + +var bits = require('bit-twiddle') +var dup = require('dup') + +//Legacy pool support +if(!global.__TYPEDARRAY_POOL) { + global.__TYPEDARRAY_POOL = { + UINT8 : dup([32, 0]) + , UINT16 : dup([32, 0]) + , UINT32 : dup([32, 0]) + , INT8 : dup([32, 0]) + , INT16 : dup([32, 0]) + , INT32 : dup([32, 0]) + , FLOAT : dup([32, 0]) + , DOUBLE : dup([32, 0]) + , DATA : dup([32, 0]) + , UINT8C : dup([32, 0]) + , BUFFER : dup([32, 0]) } - d3_time_formatIsoNative.parse = function(string) { - var date = new Date(string); - return isNaN(date) ? null : date; - }; - d3_time_formatIsoNative.toString = d3_time_formatIso.toString; - d3_time.second = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 1e3) * 1e3); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 1e3); - }, function(date) { - return date.getSeconds(); - }); - d3_time.seconds = d3_time.second.range; - d3_time.seconds.utc = d3_time.second.utc.range; - d3_time.minute = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 6e4) * 6e4); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 6e4); - }, function(date) { - return date.getMinutes(); - }); - d3_time.minutes = d3_time.minute.range; - d3_time.minutes.utc = d3_time.minute.utc.range; - d3_time.hour = d3_time_interval(function(date) { - var timezone = date.getTimezoneOffset() / 60; - return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 36e5); - }, function(date) { - return date.getHours(); - }); - d3_time.hours = d3_time.hour.range; - d3_time.hours.utc = d3_time.hour.utc.range; - d3_time.month = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setDate(1); - return date; - }, function(date, offset) { - date.setMonth(date.getMonth() + offset); - }, function(date) { - return date.getMonth(); - }); - d3_time.months = d3_time.month.range; - d3_time.months.utc = d3_time.month.utc.range; - function d3_time_scale(linear, methods, format) { - function scale(x) { - return linear(x); +} + +var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' +var POOL = global.__TYPEDARRAY_POOL + +//Upgrade pool +if(!POOL.UINT8C) { + POOL.UINT8C = dup([32, 0]) +} +if(!POOL.BUFFER) { + POOL.BUFFER = dup([32, 0]) +} + +//New technique: Only allocate from ArrayBufferView and Buffer +var DATA = POOL.DATA + , BUFFER = POOL.BUFFER + +exports.free = function free(array) { + if(Buffer.isBuffer(array)) { + BUFFER[bits.log2(array.length)].push(array) + } else { + if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { + array = array.buffer } - scale.invert = function(x) { - return d3_time_scaleDate(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return linear.domain().map(d3_time_scaleDate); - linear.domain(x); - return scale; - }; - function tickMethod(extent, count) { - var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); - return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { - return d / 31536e6; - }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + if(!array) { + return } - scale.nice = function(interval, skip) { - var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); - if (method) interval = method[0], skip = method[1]; - function skipped(date) { - return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; - } - return scale.domain(d3_scale_nice(domain, skip > 1 ? { - floor: function(date) { - while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); - return date; - }, - ceil: function(date) { - while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); - return date; - } - } : interval)); - }; - scale.ticks = function(interval, skip) { - var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { - range: interval - }, skip ]; - if (method) interval = method[0], skip = method[1]; - return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); - }; - scale.tickFormat = function() { - return format; - }; - scale.copy = function() { - return d3_time_scale(linear.copy(), methods, format); - }; - return d3_scale_linearRebind(scale, linear); + var n = array.length || array.byteLength + var log_n = bits.log2(n)|0 + DATA[log_n].push(array) } - function d3_time_scaleDate(t) { - return new Date(t); +} + +function freeArrayBuffer(buffer) { + if(!buffer) { + return } - var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; - var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; - var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { - return d.getMilliseconds(); - } ], [ ":%S", function(d) { - return d.getSeconds(); - } ], [ "%I:%M", function(d) { - return d.getMinutes(); - } ], [ "%I %p", function(d) { - return d.getHours(); - } ], [ "%a %d", function(d) { - return d.getDay() && d.getDate() != 1; - } ], [ "%b %d", function(d) { - return d.getDate() != 1; - } ], [ "%B", function(d) { - return d.getMonth(); - } ], [ "%Y", d3_true ] ]); - var d3_time_scaleMilliseconds = { - range: function(start, stop, step) { - return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); - }, - floor: d3_identity, - ceil: d3_identity - }; - d3_time_scaleLocalMethods.year = d3_time.year; - d3_time.scale = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); - }; - var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { - return [ m[0].utc, m[1] ]; - }); - var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { - return d.getUTCMilliseconds(); - } ], [ ":%S", function(d) { - return d.getUTCSeconds(); - } ], [ "%I:%M", function(d) { - return d.getUTCMinutes(); - } ], [ "%I %p", function(d) { - return d.getUTCHours(); - } ], [ "%a %d", function(d) { - return d.getUTCDay() && d.getUTCDate() != 1; - } ], [ "%b %d", function(d) { - return d.getUTCDate() != 1; - } ], [ "%B", function(d) { - return d.getUTCMonth(); - } ], [ "%Y", d3_true ] ]); - d3_time_scaleUtcMethods.year = d3_time.year.utc; - d3_time.scale.utc = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); - }; - d3.text = d3_xhrType(function(request) { - return request.responseText; - }); - d3.json = function(url, callback) { - return d3_xhr(url, "application/json", d3_json, callback); - }; - function d3_json(request) { - return JSON.parse(request.responseText); + var n = buffer.length || buffer.byteLength + var log_n = bits.log2(n) + DATA[log_n].push(buffer) +} + +function freeTypedArray(array) { + freeArrayBuffer(array.buffer) +} + +exports.freeUint8 = +exports.freeUint16 = +exports.freeUint32 = +exports.freeInt8 = +exports.freeInt16 = +exports.freeInt32 = +exports.freeFloat32 = +exports.freeFloat = +exports.freeFloat64 = +exports.freeDouble = +exports.freeUint8Clamped = +exports.freeDataView = freeTypedArray + +exports.freeArrayBuffer = freeArrayBuffer + +exports.freeBuffer = function freeBuffer(array) { + BUFFER[bits.log2(array.length)].push(array) +} + +exports.malloc = function malloc(n, dtype) { + if(dtype === undefined || dtype === 'arraybuffer') { + return mallocArrayBuffer(n) + } else { + switch(dtype) { + case 'uint8': + return mallocUint8(n) + case 'uint16': + return mallocUint16(n) + case 'uint32': + return mallocUint32(n) + case 'int8': + return mallocInt8(n) + case 'int16': + return mallocInt16(n) + case 'int32': + return mallocInt32(n) + case 'float': + case 'float32': + return mallocFloat(n) + case 'double': + case 'float64': + return mallocDouble(n) + case 'uint8_clamped': + return mallocUint8Clamped(n) + case 'buffer': + return mallocBuffer(n) + case 'data': + case 'dataview': + return mallocDataView(n) + + default: + return null + } } - d3.html = function(url, callback) { - return d3_xhr(url, "text/html", d3_html, callback); - }; - function d3_html(request) { - var range = d3_document.createRange(); - range.selectNode(d3_document.body); - return range.createContextualFragment(request.responseText); + return null +} + +function mallocArrayBuffer(n) { + var n = bits.nextPow2(n) + var log_n = bits.log2(n) + var d = DATA[log_n] + if(d.length > 0) { + return d.pop() + } + return new ArrayBuffer(n) +} +exports.mallocArrayBuffer = mallocArrayBuffer + +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocUint8 = mallocUint8 + +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocUint16 = mallocUint16 + +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocUint32 = mallocUint32 + +function mallocInt8(n) { + return new Int8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocInt8 = mallocInt8 + +function mallocInt16(n) { + return new Int16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocInt16 = mallocInt16 + +function mallocInt32(n) { + return new Int32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocInt32 = mallocInt32 + +function mallocFloat(n) { + return new Float32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocFloat32 = exports.mallocFloat = mallocFloat + +function mallocDouble(n) { + return new Float64Array(mallocArrayBuffer(8*n), 0, n) +} +exports.mallocFloat64 = exports.mallocDouble = mallocDouble + +function mallocUint8Clamped(n) { + if(hasUint8C) { + return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) + } else { + return mallocUint8(n) + } +} +exports.mallocUint8Clamped = mallocUint8Clamped + +function mallocDataView(n) { + return new DataView(mallocArrayBuffer(n), 0, n) +} +exports.mallocDataView = mallocDataView + +function mallocBuffer(n) { + n = bits.nextPow2(n) + var log_n = bits.log2(n) + var cache = BUFFER[log_n] + if(cache.length > 0) { + return cache.pop() } - d3.xml = d3_xhrType(function(request) { - return request.responseXML; - }); - if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; -}(); -},{}],114:[function(require,module,exports){ -"use strict" + return new Buffer(n) +} +exports.mallocBuffer = mallocBuffer -var ch = require("incremental-convex-hull") -var uniq = require("uniq") +exports.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"bit-twiddle":120,"buffer":65,"dup":121}],123:[function(require,module,exports){ +'use strict' -module.exports = triangulate +module.exports = createErrorBars -function LiftedPoint(p, i) { - this.point = p - this.index = i +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders/index') + +var IDENTITY = [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] + +function ErrorBars(gl, buffer, vao, shader) { + this.gl = gl + this.shader = shader + this.buffer = buffer + this.vao = vao + this.pixelRatio = 1 + this.bounds = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]] + this.clipBounds = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]] + this.lineWidth = [1,1,1] + this.capSize = [10,10,10] + this.lineCount = [0,0,0] + this.lineOffset = [0,0,0] + this.opacity = 1 } -function compareLifted(a, b) { - var ap = a.point - var bp = b.point - var d = ap.length - for(var i=0; i= 1 } -function triangulate1D(n, points, includePointAtInfinity) { - if(n === 1) { - if(includePointAtInfinity) { - return [ [-1, 0] ] - } else { - return [] - } - } - var lifted = points.map(function(p, i) { - return [ p[0], i ] - }) - lifted.sort(function(a,b) { - return a[0] - b[0] - }) - var cells = new Array(n - 1) - for(var i=1; i= 2) { - return false + if(position && error) { + + var verts = [] + var n = position.length + var vertexCount = 0 + this.bounds = [[ Infinity, Infinity, Infinity], + [-Infinity,-Infinity,-Infinity]] + this.lineCount = [0,0,0] + + //Build geometry for lines + for(var j=0; j<3; ++j) { + this.lineOffset[j] = vertexCount + +i_loop: + for(var i=0; i 0) { + var x = p.slice() + x[j] += e[1][j] + verts.push(p[0], p[1], p[2], + c[0], c[1], c[2], c[3], + 0, 0, 0, + x[0], x[1], x[2], + c[0], c[1], c[2], c[3], + 0, 0, 0) + updateBounds(this.bounds, x) + vertexCount += 2 + emitFace(verts, x, c, j) + } } - return true - }) + this.lineCount[j] = vertexCount - this.lineOffset[j] + } + this.buffer.update(verts) + } +} + +proto.dispose = function() { + this.shader.dispose() + this.buffer.dispose() + this.vao.dispose() +} + +function createErrorBars(options) { + var gl = options.gl + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 0, + stride: 40 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 4, + offset: 12, + stride: 40 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 28, + stride: 40 + } + ]) + + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.color.location = 1 + shader.attributes.offset.location = 2 + + var result = new ErrorBars(gl, buffer, vao, shader) + result.update(options) + return result +} + +},{"./shaders/index":158,"gl-buffer":124,"gl-vao":157}],124:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":127}],125:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],126:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],127:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":125,"buffer":65,"dup":122}],128:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":129,"./lib/create-attributes":130,"./lib/create-uniforms":131,"./lib/reflect":132,"./lib/runtime-reflect":133,"./lib/shader-cache":134,"dup":94}],129:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],130:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":129,"dup":96}],131:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":129,"./reflect":132,"dup":97}],132:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],133:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],134:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":129,"dup":100,"gl-format-compiler-error":135,"weakmap-shim":153}],135:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":136,"dup":101,"gl-constants/lookup":140,"glsl-shader-name":141,"sprintf-js":150}],136:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":137}],137:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":138}],138:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],139:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],140:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":139,"dup":106}],141:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":142,"dup":107,"glsl-tokenizer":149}],142:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],143:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":145,"./lib/builtins-300es":144,"./lib/literals":147,"./lib/literals-300es":146,"./lib/operators":148,"dup":109}],144:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":145,"dup":110}],145:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],146:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":147,"dup":112}],147:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],148:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],149:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":143,"dup":115}],150:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],151:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":152,"dup":117}],152:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],153:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":151,"dup":119}],154:[function(require,module,exports){ +"use strict" + +function doBind(gl, elements, attributes) { + if(elements) { + elements.bind() } else { - hull = hull.filter(function(cell) { - for(var i=0; i<=d; ++i) { - var v = dindex[cell[i]] - if(v < 0) { - return false + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) + } + var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0 + if(attributes) { + if(attributes.length > nattribs) { + throw new Error("gl-vao: Too many vertex attributes") + } + for(var i=0; i 0) { - return dupe_number(count|0, value) - } - break - case "object": - if(typeof (count.length) === "number") { - return dupe_array(count, value, 0) - } - break - } - return [] +function createVAONative(gl, ext) { + return new VAONative(gl, ext, ext.createVertexArrayOES()) } -module.exports = dupe -},{}],116:[function(require,module,exports){ -(function (process,global){ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 3.1.2 - */ +module.exports = createVAONative +},{"./do-bind.js":154}],157:[function(require,module,exports){ +"use strict" -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } +var createVAONative = require("./lib/vao-native.js") +var createVAOEmulated = require("./lib/vao-emulated.js") - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } +function createVAO(gl, attributes, elements, elementsType) { + var ext = gl.getExtension('OES_vertex_array_object') + var vao + if(ext) { + vao = createVAONative(gl, ext) + } else { + vao = createVAOEmulated(gl) + } + vao.update(attributes, elements, elementsType) + return vao +} - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } +module.exports = createVAO - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } +},{"./lib/vao-emulated.js":155,"./lib/vao-native.js":156}],158:[function(require,module,exports){ +'use strict' - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$vertxNext; - var lib$es6$promise$asap$$customSchedulerFn; - var lib$es6$promise$asap$$asap = function asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (lib$es6$promise$asap$$customSchedulerFn) { - lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); - } else { - lib$es6$promise$asap$$scheduleFlush(); - } - } - } +var createShader = require('gl-shader') - function lib$es6$promise$asap$$setScheduler(scheduleFn) { - lib$es6$promise$asap$$customSchedulerFn = scheduleFn; - } +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}" - function lib$es6$promise$asap$$setAsap(asapFn) { - lib$es6$promise$asap$$asap = asapFn; - } +module.exports = function(gl) { + return createShader(gl, vertSrc, fragSrc, null, [ + {name: 'position', type: 'vec3'}, + {name: 'offset', type: 'vec3'}, + {name: 'color', type: 'vec4'} + ]) +} - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; +},{"gl-shader":128}],159:[function(require,module,exports){ - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - // node - function lib$es6$promise$asap$$useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(lib$es6$promise$asap$$flush); - }; - } +exports.lineVertex = "precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n vec2 dir = (matrix * vec3(d, 0)).xy;\n vec3 base = matrix * vec3(a, 1);\n vec2 n = 0.5 * width *\n normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n vec2 tangent = normalize(screenShape.xy * dir);\n if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n direction = -tangent;\n } else {\n direction = tangent;\n }\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n" +exports.lineFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n" +exports.mitreVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 p;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n vec3 pp = matrix * vec3(p, 1);\n gl_Position = vec4(pp.xy, 0, pp.z);\n gl_PointSize = radius;\n}\n" +exports.mitreFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n discard;\n }\n gl_FragColor = vec4(color.rgb, color.a);\n}\n" +exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 n = width *\n normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n pickA = pick0;\n pickB = pick1;\n}\n" +exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n vec4 fragId = vec4(pickA.xyz, 0.0);\n if(pickB.w > pickA.w) {\n fragId.xyz = pickB.xyz;\n }\n\n fragId += pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n gl_FragColor = fragId / 255.0;\n}\n" +exports.fillVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 p = base.xy / base.z;\n if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n if(dot(p, projectAxis) < projectValue) {\n p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n }\n }\n gl_Position = vec4(p, depth, 1);\n}\n" +exports.fillFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } +},{}],160:[function(require,module,exports){ +'use strict' - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); +module.exports = createLinePlot - return function() { - node.data = (iterations = ++iterations % 2); - }; - } +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var createTexture = require('gl-texture2d') +var ndarray = require('ndarray') +var pool = require('typedarray-pool') - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } +var SHADERS = require('./lib/shaders') - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } +function GLLine2D( + plot, + dashPattern, + lineBuffer, + pickBuffer, + lineShader, + mitreShader, + fillShader, + pickShader) { - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; + this.plot = plot + this.dashPattern = dashPattern + this.lineBuffer = lineBuffer + this.pickBuffer = pickBuffer + this.lineShader = lineShader + this.mitreShader = mitreShader + this.fillShader = fillShader + this.pickShader = pickShader + this.usingDashes = false - callback(arg); + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } + this.width = 1 + this.color = [0,0,1,1] - lib$es6$promise$asap$$len = 0; - } + //Fill to axes + this.fill = [false, false, false, false] + this.fillColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - function lib$es6$promise$asap$$attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } + this.data = null + this.numPoints = 0 + this.vertCount = 0 - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - function lib$es6$promise$then$$then(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; + this.pickOffset = 0 - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } + this.lodBuffer = [] +} - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; +var proto = GLLine2D.prototype - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$asap(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } +proto.draw = (function() { +var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] +var SCREEN_SHAPE = [0,0] +var PX_AXIS = [1,0] +var NX_AXIS = [-1,0] +var PY_AXIS = [0,1] +var NY_AXIS = [0,-1] +return function() { + var plot = this.plot + var color = this.color + var width = this.width + var numPoints = this.numPoints + var bounds = this.bounds + var count = this.vertCount - return child; - } - var lib$es6$promise$then$$default = lib$es6$promise$then$$then; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; + if(!count) { + return + } - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } + var gl = plot.gl + var viewBox = plot.viewBox + var dataBox = plot.dataBox + var pixelRatio = plot.pixelRatio - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] - function lib$es6$promise$$internal$$noop() {} + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; + SCREEN_SHAPE[0] = screenX + SCREEN_SHAPE[1] = screenY - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + var buffer = this.lineBuffer + buffer.bind() - function lib$es6$promise$$internal$$selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } + var fill = this.fill - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } + if(fill[0] || fill[1] || fill[2] || fill[3]) { - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } + var fillShader = this.fillShader + fillShader.bind() - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } + var fillUniforms = fillShader.uniforms + fillUniforms.matrix = MATRIX + fillUniforms.depth = plot.nextDepthValue() - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$asap(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; + var fillAttributes = fillShader.attributes + fillAttributes.a.pointer(gl.FLOAT, false, 16, 0) + fillAttributes.d.pointer(gl.FLOAT, false, 16, 8) - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); + gl.depthMask(true) + gl.enable(gl.DEPTH_TEST) - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); + var fillColor = this.fillColor + if(fill[0]) { + fillUniforms.color = fillColor[0] + fillUniforms.projectAxis = NX_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } + if(fill[1]) { + fillUniforms.color = fillColor[1] + fillUniforms.projectAxis = NY_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { - if (maybeThenable.constructor === promise.constructor && - then === lib$es6$promise$then$$default && - constructor.resolve === lib$es6$promise$promise$resolve$$default) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } + if(fill[2]) { + fillUniforms.color = fillColor[2] + fillUniforms.projectAxis = PX_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } + if(fill[3]) { + fillUniforms.color = fillColor[3] + fillUniforms.projectAxis = PY_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } + gl.depthMask(false) + gl.disable(gl.DEPTH_TEST) + } - lib$es6$promise$$internal$$publish(promise); - } + var shader = this.lineShader + shader.bind() - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + var uniforms = shader.uniforms + uniforms.matrix = MATRIX + uniforms.color = color + uniforms.width = width * pixelRatio + uniforms.screenShape = SCREEN_SHAPE + uniforms.dashPattern = this.dashPattern.bind() + uniforms.dashLength = this.dashLength * pixelRatio - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; + var attributes = shader.attributes + attributes.a.pointer(gl.FLOAT, false, 16, 0) + attributes.d.pointer(gl.FLOAT, false, 16, 8) - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); - } - } + gl.drawArrays(gl.TRIANGLES, 0, count) - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; + //Draw mitres + if(width > 2 && !this.usingDashes) { + var mshader = this.mitreShader + mshader.bind() - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); - } + var muniforms = mshader.uniforms + muniforms.matrix = MATRIX + muniforms.color = color + muniforms.screenShape = SCREEN_SHAPE + muniforms.radius = width * pixelRatio - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; + mshader.attributes.p.pointer(gl.FLOAT, false, 48, 0) + gl.drawArrays(gl.POINTS, 0, (count/3)|0) + } +} +})() - parent._onerror = null; +proto.drawPick = (function() { + var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] + var SCREEN_SHAPE = [0,0] + var PICK_OFFSET = [0,0,0,0] + return function(pickOffset) { + var plot = this.plot + var shader = this.pickShader + var buffer = this.lineBuffer + var pickBuffer= this.pickBuffer + var width = this.width + var numPoints = this.numPoints + var bounds = this.bounds + var count = this.vertCount + + var gl = plot.gl + var viewBox = plot.viewBox + var dataBox = plot.dataBox + var pixelRatio = plot.pickPixelRatio + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + this.pickOffset = pickOffset - if (length === 0 && parent._state) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); - } + if(!count) { + return pickOffset + numPoints } - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - if (subscribers.length === 0) { return; } + SCREEN_SHAPE[0] = screenX + SCREEN_SHAPE[1] = screenY - var child, callback, detail = promise._result; + PICK_OFFSET[0] = pickOffset & 0xff + PICK_OFFSET[1] = (pickOffset>>>8) & 0xff + PICK_OFFSET[2] = (pickOffset>>>16) & 0xff + PICK_OFFSET[3] = pickOffset>>>24 - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; + shader.bind() - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } + var uniforms = shader.uniforms + uniforms.matrix = MATRIX + uniforms.width = width * pixelRatio + uniforms.pickOffset = PICK_OFFSET + uniforms.screenShape = SCREEN_SHAPE - promise._subscribers.length = 0; - } + var attributes = shader.attributes - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } + buffer.bind() + attributes.a.pointer(gl.FLOAT, false, 16, 0) + attributes.d.pointer(gl.FLOAT, false, 16, 8) - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + pickBuffer.bind() + attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0) + attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4) - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } + gl.drawArrays(gl.TRIANGLES, 0, count) - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; + return pickOffset + numPoints + } +})() - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.numPoints + if(value < pickOffset || value >= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var points = this.data + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] + } +} - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } +function deepCopy(arr) { + return arr.map(function(x) { + return x.slice() + }) +} - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } +proto.update = function(options) { + options = options || {} - } else { - value = detail; - succeeded = true; - } + var gl = this.plot.gl - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } + var connectGaps = !!options.connectGaps - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } + this.color = (options.color || [0,0,1,1]).slice() + this.width = +(options.width || 1) - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; + this.fill = (options.fill || [false,false,false,false]).slice() + this.fillColor = deepCopy(options.fillColor || [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]]) - var promise = new Constructor(lib$es6$promise$$internal$$noop); + var dashes = options.dashes || [1] + var dashLength = 0 + for(var i=0; i 1 - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } + this.dashPattern = createTexture(gl, + ndarray(dashData, [dashLength, 1, 4], [1, 0, 0])) + this.dashPattern.minFilter = gl.NEAREST + this.dashPattern.magFilter = gl.NEAREST + this.dashLength = dashLength + pool.free(dashData) - var length = entries.length; + var data = options.positions + this.data = data - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } + var bounds = this.bounds + bounds[0] = bounds[1] = Infinity + bounds[2] = bounds[3] = -Infinity - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } + var numPoints = this.numPoints = data.length>>>1 + if(numPoints === 0) { + return + } - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } + for(var i=0; i 1) { + var id = --ptr + var ax = data[2*ptr] + var ay = data[2*ptr+1] - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. + var next = id-1 + var bx = data[2*next] + var by = data[2*next+1] - A promise can be in one of three states: pending, fulfilled, or rejected. + if (isNaN(ax) || isNaN(ay) || isNaN(bx) || isNaN(by)) { + continue + } - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. + count += 1 - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. + ax = (ax - bounds[0]) / (bounds[2] - bounds[0]) + ay = (ay - bounds[1]) / (bounds[3] - bounds[1]) + bx = (bx - bounds[0]) / (bounds[2] - bounds[0]) + by = (by - bounds[1]) / (bounds[3] - bounds[1]) - Basic Usage: - ------------ + var dx = bx - ax + var dy = by - ay - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); + var akey0 = id | (1<<24) + var akey1 = (id-1) + var bkey0 = id + var bkey1 = (id-1) | (1<<24) - // on failure - reject(reason); - }); + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 - Advanced Usage: - --------------- + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 + } - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } + this.vertCount = 6 * count + this.lineBuffer.update(lineData.subarray(lineDataPtr)) + this.pickBuffer.update(pickData.subarray(pickDataPtr)) - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` + pool.free(lineData) + pool.free(pickData) +} - Unlike callbacks, promises are great composable primitives. +proto.dispose = function() { + this.plot.removeObject(this) + this.lineBuffer.dispose() + this.pickBuffer.dispose() + this.lineShader.dispose() + this.mitreShader.dispose() + this.fillShader.dispose() + this.pickShader.dispose() + this.dashPattern.dispose() +} - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON +function createLinePlot(plot, options) { + var gl = plot.gl + var lineBuffer = createBuffer(gl) + var pickBuffer = createBuffer(gl) + var dashPattern = createTexture(gl, [1,1]) + var lineShader = createShader(gl, SHADERS.lineVertex, SHADERS.lineFragment) + var mitreShader = createShader(gl, SHADERS.mitreVertex, SHADERS.mitreFragment) + var fillShader = createShader(gl, SHADERS.fillVertex, SHADERS.fillFragment) + var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) + var linePlot = new GLLine2D( + plot, + dashPattern, + lineBuffer, + pickBuffer, + lineShader, + mitreShader, + fillShader, + pickShader) + plot.addObject(linePlot) + linePlot.update(options) + return linePlot +} - return values; - }); - ``` +},{"./lib/shaders":159,"gl-buffer":161,"gl-shader":162,"gl-texture2d":188,"ndarray":1031,"typedarray-pool":191}],161:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":191}],162:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":163,"./lib/create-attributes":164,"./lib/create-uniforms":165,"./lib/reflect":166,"./lib/runtime-reflect":167,"./lib/shader-cache":168,"dup":94}],163:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],164:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":163,"dup":96}],165:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":163,"./reflect":166,"dup":97}],166:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],167:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],168:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":163,"dup":100,"gl-format-compiler-error":169,"weakmap-shim":187}],169:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":170,"dup":101,"gl-constants/lookup":174,"glsl-shader-name":175,"sprintf-js":184}],170:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":171}],171:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":172}],172:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],173:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],174:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":173,"dup":106}],175:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":176,"dup":107,"glsl-tokenizer":183}],176:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],177:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":179,"./lib/builtins-300es":178,"./lib/literals":181,"./lib/literals-300es":180,"./lib/operators":182,"dup":109}],178:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":179,"dup":110}],179:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],180:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":181,"dup":112}],181:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],182:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],183:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":177,"dup":115}],184:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],185:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":186,"dup":117}],186:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],187:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":185,"dup":119}],188:[function(require,module,exports){ +'use strict' - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; +var ndarray = require('ndarray') +var ops = require('ndarray-ops') +var pool = require('typedarray-pool') - if (lib$es6$promise$$internal$$noop !== resolver) { - typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); - this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); - } - } +module.exports = createTexture2D - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; - lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; - lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; +var linearTypes = null +var filterTypes = null +var wrapTypes = null - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, +function lazyInitLinearTypes(gl) { + linearTypes = [ + gl.LINEAR, + gl.NEAREST_MIPMAP_LINEAR, + gl.LINEAR_MIPMAP_NEAREST, + gl.LINEAR_MIPMAP_NEAREST + ] + filterTypes = [ + gl.NEAREST, + gl.LINEAR, + gl.NEAREST_MIPMAP_NEAREST, + gl.NEAREST_MIPMAP_LINEAR, + gl.LINEAR_MIPMAP_NEAREST, + gl.LINEAR_MIPMAP_LINEAR + ] + wrapTypes = [ + gl.REPEAT, + gl.CLAMP_TO_EDGE, + gl.MIRRORED_REPEAT + ] +} - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. +var convertFloatToUint8 = function(out, inp) { + ops.muls(out, inp, 255.0) +} - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` +function reshapeTexture(tex, w, h) { + var gl = tex.gl + var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(w < 0 || w > maxSize || h < 0 || h > maxSize) { + throw new Error('gl-texture2d: Invalid texture size') + } + tex._shape = [w, h] + tex.bind() + gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) + tex._mipLevels = [0] + return tex +} - Chaining - -------- +function Texture2D(gl, handle, width, height, format, type) { + this.gl = gl + this.handle = handle + this.format = format + this.type = type + this._shape = [width, height] + this._mipLevels = [0] + this._magFilter = gl.NEAREST + this._minFilter = gl.NEAREST + this._wrapS = gl.CLAMP_TO_EDGE + this._wrapT = gl.CLAMP_TO_EDGE + this._anisoSamples = 1 + + var parent = this + var wrapVector = [this._wrapS, this._wrapT] + Object.defineProperties(wrapVector, [ + { + get: function() { + return parent._wrapS + }, + set: function(v) { + return parent.wrapS = v + } + }, + { + get: function() { + return parent._wrapT + }, + set: function(v) { + return parent.wrapT = v + } + } + ]) + this._wrapVector = wrapVector - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. + var shapeVector = [this._shape[0], this._shape[1]] + Object.defineProperties(shapeVector, [ + { + get: function() { + return parent._shape[0] + }, + set: function(v) { + return parent.width = v + } + }, + { + get: function() { + return parent._shape[1] + }, + set: function(v) { + return parent.height = v + } + } + ]) + this._shapeVector = shapeVector +} - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); +var proto = Texture2D.prototype - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. +Object.defineProperties(proto, { + minFilter: { + get: function() { + return this._minFilter + }, + set: function(v) { + this.bind() + var gl = this.gl + if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { + if(!gl.getExtension('OES_texture_float_linear')) { + v = gl.NEAREST + } + } + if(filterTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown filter mode ' + v) + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v) + return this._minFilter = v + } + }, + magFilter: { + get: function() { + return this._magFilter + }, + set: function(v) { + this.bind() + var gl = this.gl + if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { + if(!gl.getExtension('OES_texture_float_linear')) { + v = gl.NEAREST + } + } + if(filterTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown filter mode ' + v) + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) + return this._magFilter = v + } + }, + mipSamples: { + get: function() { + return this._anisoSamples + }, + set: function(i) { + var psamples = this._anisoSamples + this._anisoSamples = Math.max(i, 1)|0 + if(psamples !== this._anisoSamples) { + var ext = gl.getExtension('EXT_texture_filter_anisotropic') + if(ext) { + this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) + } + } + return this._anisoSamples + } + }, + wrapS: { + get: function() { + return this._wrapS + }, + set: function(v) { + this.bind() + if(wrapTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v) + return this._wrapS = v + } + }, + wrapT: { + get: function() { + return this._wrapT + }, + set: function(v) { + this.bind() + if(wrapTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v) + return this._wrapT = v + } + }, + wrap: { + get: function() { + return this._wrapVector + }, + set: function(v) { + if(!Array.isArray(v)) { + v = [v,v] + } + if(v.length !== 2) { + throw new Error('gl-texture2d: Must specify wrap mode for rows and columns') + } + for(var i=0; i<2; ++i) { + if(wrapTypes.indexOf(v[i]) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + } + this._wrapS = v[0] + this._wrapT = v[1] - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` + var gl = this.gl + this.bind() + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT) - Assimilation - ------------ + return v + } + }, + shape: { + get: function() { + return this._shapeVector + }, + set: function(x) { + if(!Array.isArray(x)) { + x = [x|0,x|0] + } else { + if(x.length !== 2) { + throw new Error('gl-texture2d: Invalid texture shape') + } + } + reshapeTexture(this, x[0]|0, x[1]|0) + return [x[0]|0, x[1]|0] + } + }, + width: { + get: function() { + return this._shape[0] + }, + set: function(w) { + w = w|0 + reshapeTexture(this, w, this._shape[1]) + return w + } + }, + height: { + get: function() { + return this._shape[1] + }, + set: function(h) { + h = h|0 + reshapeTexture(this, this._shape[0], h) + return h + } + } +}) - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. +proto.bind = function(unit) { + var gl = this.gl + if(unit !== undefined) { + gl.activeTexture(gl.TEXTURE0 + (unit|0)) + } + gl.bindTexture(gl.TEXTURE_2D, this.handle) + if(unit !== undefined) { + return (unit|0) + } + return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0 +} - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` +proto.dispose = function() { + this.gl.deleteTexture(this.handle) +} - If the assimliated promise rejects, then the downstream promise will also reject. +proto.generateMipmap = function() { + this.bind() + this.gl.generateMipmap(this.gl.TEXTURE_2D) - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` + //Update mip levels + var l = Math.min(this._shape[0], this._shape[1]) + for(var i=0; l>0; ++i, l>>>=1) { + if(this._mipLevels.indexOf(i) < 0) { + this._mipLevels.push(i) + } + } +} - Simple Example - -------------- +proto.setPixels = function(data, x_off, y_off, mip_level) { + var gl = this.gl + this.bind() + if(Array.isArray(x_off)) { + mip_level = y_off + y_off = x_off[1]|0 + x_off = x_off[0]|0 + } else { + x_off = x_off || 0 + y_off = y_off || 0 + } + mip_level = mip_level || 0 + if(data instanceof HTMLCanvasElement || + data instanceof ImageData || + data instanceof HTMLImageElement || + data instanceof HTMLVideoElement) { + var needsMip = this._mipLevels.indexOf(mip_level) < 0 + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data) + this._mipLevels.push(mip_level) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data) + } + } else if(data.shape && data.stride && data.data) { + if(data.shape.length < 2 || + x_off + data.shape[1] > this._shape[1]>>>mip_level || + y_off + data.shape[0] > this._shape[0]>>>mip_level || + x_off < 0 || + y_off < 0) { + throw new Error('gl-texture2d: Texture dimensions are out of bounds') + } + texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data) + } else { + throw new Error('gl-texture2d: Unsupported data type') + } +} - Synchronous Example - ```javascript - var result; +function isPacked(shape, stride) { + if(shape.length === 3) { + return (stride[2] === 1) && + (stride[1] === shape[0]*shape[2]) && + (stride[0] === shape[2]) + } + return (stride[0] === 1) && + (stride[1] === shape[0]) +} - try { - result = findResult(); - // success - } catch(reason) { - // failure +function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) { + var dtype = array.dtype + var shape = array.shape.slice() + if(shape.length < 2 || shape.length > 3) { + throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') + } + var type = 0, format = 0 + var packed = isPacked(shape, array.stride.slice()) + if(dtype === 'float32') { + type = gl.FLOAT + } else if(dtype === 'float64') { + type = gl.FLOAT + packed = false + dtype = 'float32' + } else if(dtype === 'uint8') { + type = gl.UNSIGNED_BYTE + } else { + type = gl.UNSIGNED_BYTE + packed = false + dtype = 'uint8' + } + var channels = 1 + if(shape.length === 2) { + format = gl.LUMINANCE + shape = [shape[0], shape[1], 1] + array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + } else if(shape.length === 3) { + if(shape[2] === 1) { + format = gl.ALPHA + } else if(shape[2] === 2) { + format = gl.LUMINANCE_ALPHA + } else if(shape[2] === 3) { + format = gl.RGB + } else if(shape[2] === 4) { + format = gl.RGBA + } else { + throw new Error('gl-texture2d: Invalid shape for pixel coords') + } + channels = shape[2] + } else { + throw new Error('gl-texture2d: Invalid shape for texture') + } + //For 1-channel textures allow conversion between formats + if((format === gl.LUMINANCE || format === gl.ALPHA) && + (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { + format = cformat + } + if(format !== cformat) { + throw new Error('gl-texture2d: Incompatible texture format for setPixels') + } + var size = array.size + var needsMip = mipLevels.indexOf(mip_level) < 0 + if(needsMip) { + mipLevels.push(mip_level) + } + if(type === ctype && packed) { + //Array data types are compatible, can directly copy into texture + if(array.offset === 0 && array.data.length === size) { + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) } - ``` + } else { + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + } + } + } else { + //Need to do type conversion to pack data into buffer + var pack_buffer + if(ctype === gl.FLOAT) { + pack_buffer = pool.mallocFloat32(size) + } else { + pack_buffer = pool.mallocUint8(size) + } + var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) + if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { + convertFloatToUint8(pack_view, array) + } else { + ops.assign(pack_view, array) + } + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) + } + if(ctype === gl.FLOAT) { + pool.freeFloat32(pack_buffer) + } else { + pool.freeUint8(pack_buffer) + } + } +} - Errback Example +function initTexture(gl) { + var tex = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, tex) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + return tex +} - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` +function createTextureShape(gl, width, height, format, type) { + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { + throw new Error('gl-texture2d: Invalid texture shape') + } + if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { + throw new Error('gl-texture2d: Floating point textures not supported on this platform') + } + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) + return new Texture2D(gl, tex, width, height, format, type) +} - Promise Example; +function createTextureDOM(gl, element, format, type) { + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element) + return new Texture2D(gl, tex, element.width|0, element.height|0, format, type) +} - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` +//Creates a texture from an ndarray +function createTextureArray(gl, array) { + var dtype = array.dtype + var shape = array.shape.slice() + var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { + throw new Error('gl-texture2d: Invalid texture size') + } + var packed = isPacked(shape, array.stride.slice()) + var type = 0 + if(dtype === 'float32') { + type = gl.FLOAT + } else if(dtype === 'float64') { + type = gl.FLOAT + packed = false + dtype = 'float32' + } else if(dtype === 'uint8') { + type = gl.UNSIGNED_BYTE + } else { + type = gl.UNSIGNED_BYTE + packed = false + dtype = 'uint8' + } + var format = 0 + if(shape.length === 2) { + format = gl.LUMINANCE + shape = [shape[0], shape[1], 1] + array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + } else if(shape.length === 3) { + if(shape[2] === 1) { + format = gl.ALPHA + } else if(shape[2] === 2) { + format = gl.LUMINANCE_ALPHA + } else if(shape[2] === 3) { + format = gl.RGB + } else if(shape[2] === 4) { + format = gl.RGBA + } else { + throw new Error('gl-texture2d: Invalid shape for pixel coords') + } + } else { + throw new Error('gl-texture2d: Invalid shape for texture') + } + if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { + type = gl.UNSIGNED_BYTE + packed = false + } + var buffer, buf_store + var size = array.size + if(!packed) { + var stride = [shape[2], shape[2]*shape[0], 1] + buf_store = pool.malloc(size, dtype) + var buf_array = ndarray(buf_store, shape, stride, 0) + if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { + convertFloatToUint8(buf_array, array) + } else { + ops.assign(buf_array, array) + } + buffer = buf_store.subarray(0, size) + } else if (array.offset === 0 && array.data.length === size) { + buffer = array.data + } else { + buffer = array.data.subarray(array.offset, array.offset + size) + } + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) + if(!packed) { + pool.free(buf_store) + } + return new Texture2D(gl, tex, shape[0], shape[1], format, type) +} - Advanced Example - -------------- +function createTexture2D(gl) { + if(arguments.length <= 1) { + throw new Error('gl-texture2d: Missing arguments for texture2d constructor') + } + if(!linearTypes) { + lazyInitLinearTypes(gl) + } + if(typeof arguments[1] === 'number') { + return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) + } + if(Array.isArray(arguments[1])) { + return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) + } + if(typeof arguments[1] === 'object') { + var obj = arguments[1] + if(obj instanceof HTMLCanvasElement || + obj instanceof HTMLImageElement || + obj instanceof HTMLVideoElement || + obj instanceof ImageData) { + return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) + } else if(obj.shape && obj.data && obj.stride) { + return createTextureArray(gl, obj) + } + } + throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') +} - Synchronous Example +},{"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":191}],189:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],190:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],191:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":189,"buffer":65,"dup":122}],192:[function(require,module,exports){ - ```javascript - var author, books; +var createShader = require('gl-shader') - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n" +var forwardFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n" +var pickFrag = "precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}" - Errback Example +var ATTRIBUTES = [ + {name: 'position', type: 'vec3'}, + {name: 'nextPosition', type: 'vec3'}, + {name: 'arcLength', type: 'float'}, + {name: 'lineWidth', type: 'float'}, + {name: 'color', type: 'vec4'} +] - ```js +exports.createShader = function(gl) { + return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES) +} - function foundBooks(books) { +exports.createPickShader = function(gl) { + return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES) +} - } +},{"gl-shader":199}],193:[function(require,module,exports){ +'use strict' - function failure(reason) { +module.exports = createLinePlot - } +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createTexture = require('gl-texture2d') +var unpackFloat = require('glsl-read-float') +var bsearch = require('binary-search-bounds') +var ndarray = require('ndarray') +var shaders = require('./lib/shaders') - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` +var createShader = shaders.createShader +var createPickShader = shaders.createPickShader - Promise Example; +var identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1] - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` +function distance (a, b) { + var s = 0.0 + for (var i = 0; i < 3; ++i) { + var d = a[i] - b[i] + s += d * d + } + return Math.sqrt(s) +} - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: lib$es6$promise$then$$default, +function filterClipBounds (bounds) { + var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]] + for (var i = 0; i < 3; ++i) { + result[0][i] = Math.max(bounds[0][i], result[0][i]) + result[1][i] = Math.min(bounds[1][i], result[1][i]) + } + return result +} - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. +function PickResult (tau, position, index, dataCoordinate) { + this.arcLength = tau + this.position = position + this.index = index + this.dataCoordinate = dataCoordinate +} - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } +function LinePlot (gl, shader, pickShader, buffer, vao, texture) { + this.gl = gl + this.shader = shader + this.pickShader = pickShader + this.buffer = buffer + this.vao = vao + this.clipBounds = [ + [ -Infinity, -Infinity, -Infinity ], + [ Infinity, Infinity, Infinity ]] + this.points = [] + this.arcLength = [] + this.vertexCount = 0 + this.bounds = [[0, 0, 0], [0, 0, 0]] + this.pickId = 0 + this.lineWidth = 1 + this.texture = texture + this.dashScale = 1 + this.opacity = 1 + this.dirty = true + this.pixelRatio = 1 +} - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } +var proto = LinePlot.prototype - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` +proto.isTransparent = function () { + return this.opacity < 1 +} - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(lib$es6$promise$$internal$$noop); +proto.isOpaque = function () { + return this.opacity >= 1 +} - if (Array.isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; +proto.pickSlots = 1 - this._result = new Array(this.length); +proto.setPickBase = function (id) { + this.pickId = id +} - if (this.length === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(); - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); - } - } - } else { - lib$es6$promise$$internal$$reject(this.promise, this._validationError()); - } - } +proto.drawTransparent = proto.draw = function (camera) { + var gl = this.gl + var shader = this.shader + var vao = this.vao + shader.bind() + shader.uniforms = { + model: camera.model || identity, + view: camera.view || identity, + projection: camera.projection || identity, + clipBounds: filterClipBounds(this.clipBounds), + dashTexture: this.texture.bind(), + dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], + opacity: this.opacity, + screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], + pixelRatio: this.pixelRatio + } + vao.bind() + vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) +} - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; +proto.drawPick = function (camera) { + var gl = this.gl + var shader = this.pickShader + var vao = this.vao + shader.bind() + shader.uniforms = { + model: camera.model || identity, + view: camera.view || identity, + projection: camera.projection || identity, + pickId: this.pickId, + clipBounds: filterClipBounds(this.clipBounds), + screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], + pixelRatio: this.pixelRatio + } + vao.bind() + vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) +} - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var length = this.length; - var input = this._input; +proto.update = function (options) { + var i, j - for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - this._eachEntry(input[i], i); - } - }; + this.dirty = true - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var c = this._instanceConstructor; - var resolve = c.resolve; + var connectGaps = !!options.connectGaps - if (resolve === lib$es6$promise$promise$resolve$$default) { - var then = lib$es6$promise$$internal$$getThen(entry); + if ('dashScale' in options) { + this.dashScale = options.dashScale + } + if ('opacity' in options) { + this.opacity = +options.opacity + } - if (then === lib$es6$promise$then$$default && - entry._state !== lib$es6$promise$$internal$$PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === lib$es6$promise$promise$$default) { - var promise = new c(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); - } - } else { - this._willSettleAt(resolve(entry), i); - } - }; + var positions = options.position || options.positions + if (!positions) { + return + } - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var promise = this.promise; + // Default color + var colors = options.color || options.colors || [0, 0, 0, 1] - if (promise._state === lib$es6$promise$$internal$$PENDING) { - this._remaining--; + var lineWidth = options.lineWidth || 1 - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - this._result[i] = value; - } - } + // Recalculate buffer data + var buffer = [] + var arcLengthArray = [] + var pointArray = [] + var arcLength = 0.0 + var vertexCount = 0 + var bounds = [ + [ Infinity, Infinity, Infinity ], + [ -Infinity, -Infinity, -Infinity ]] + var hadGap = false - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, this._result); - } - }; + fill_loop: + for (i = 1; i < positions.length; ++i) { + var a = positions[i - 1] + var b = positions[i] - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; + arcLengthArray.push(arcLength) + pointArray.push(a.slice()) - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; + for (j = 0; j < 3; ++j) { + if (isNaN(a[j]) || isNaN(b[j]) || + !isFinite(a[j]) || !isFinite(b[j])) { - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); + if (!connectGaps && buffer.length > 0) { + for (var k = 0; k < 24; ++k) { + buffer.push(buffer[buffer.length - 12]) } - } - - var P = local.Promise; + vertexCount += 2 + hadGap = true + } - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; + continue fill_loop } - - local.Promise = lib$es6$promise$promise$$default; + bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]) + bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]) } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + var acolor, bcolor + if (Array.isArray(colors[0])) { + acolor = colors[i - 1] + bcolor = colors[i] + } else { + acolor = bcolor = colors } - - lib$es6$promise$polyfill$$default(); -}).call(this); - - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":56}],117:[function(require,module,exports){ -/** - * inspired by is-number - * but significantly simplified and sped up by ignoring number and string constructors - * ie these return false: - * new Number(1) - * new String('1') - */ - -'use strict'; - -/** - * Is this string all whitespace? - * This solution kind of makes my brain hurt, but it's significantly faster - * than !str.trim() or any other solution I could find. - * - * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character - * and verified with: - * - * for(var i = 0; i < 65536; i++) { - * var s = String.fromCharCode(i); - * if(+s===0 && !s.trim()) console.log(i, s); - * } - * - * which counts a couple of these as *not* whitespace, but finds nothing else - * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears - * that there are no whitespace characters above this, and code points above - * this do not map onto white space characters. - */ -function allBlankCharCodes(str){ - var l = str.length, - a; - for(var i = 0; i < l; i++) { - a = str.charCodeAt(i); - if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) && - (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) && - (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) && - (a !== 8288) && (a !== 12288) && (a !== 65279)) { - return false; - } + if (acolor.length === 3) { + acolor = [acolor[0], acolor[1], acolor[2], 1] } - return true; -} - -module.exports = function(n) { - var type = typeof n; - if(type === 'string') { - var original = n; - n = +n; - // whitespace strings cast to zero - filter them out - if(n===0 && allBlankCharCodes(original)) return false; + if (bcolor.length === 3) { + bcolor = [bcolor[0], bcolor[1], bcolor[2], 1] } - else if(type !== 'number') return false; - return n - n < 1; -}; - -},{}],118:[function(require,module,exports){ -"use strict" - -var pool = require("typedarray-pool") -var ops = require("ndarray-ops") -var ndarray = require("ndarray") + var w0 + if (Array.isArray(lineWidth)) { + w0 = lineWidth[i - 1] + } else { + w0 = lineWidth + } -var SUPPORTED_TYPES = [ - "uint8", - "uint8_clamped", - "uint16", - "uint32", - "int8", - "int16", - "int32", - "float32" ] + var t0 = arcLength + arcLength += distance(a, b) -function GLBuffer(gl, type, handle, length, usage) { - this.gl = gl - this.type = type - this.handle = handle - this.length = length - this.usage = usage -} + if (hadGap) { + for (j = 0; j < 2; ++j) { + buffer.push( + a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3]) + } + vertexCount += 2 + hadGap = false + } -var proto = GLBuffer.prototype + buffer.push( + a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3], + a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3], + b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3], + b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3]) -proto.bind = function() { - this.gl.bindBuffer(this.type, this.handle) -} + vertexCount += 4 + } + this.buffer.update(buffer) -proto.unbind = function() { - this.gl.bindBuffer(this.type, null) -} + arcLengthArray.push(arcLength) + pointArray.push(positions[positions.length - 1].slice()) -proto.dispose = function() { - this.gl.deleteBuffer(this.handle) -} + this.bounds = bounds -function updateTypeArray(gl, type, len, usage, data, offset) { - var dataLen = data.length * data.BYTES_PER_ELEMENT - if(offset < 0) { - gl.bufferData(type, data, usage) - return dataLen - } - if(dataLen + offset > len) { - throw new Error("gl-buffer: If resizing buffer, must not specify offset") - } - gl.bufferSubData(type, offset, data) - return len -} + this.vertexCount = vertexCount -function makeScratchTypeArray(array, dtype) { - var res = pool.malloc(array.length, dtype) - var n = array.length - for(var i=0; i=0; --i) { - if(stride[i] !== n) { - return false - } - n *= shape[i] - } - return true -} + if ('dashes' in options) { + var dashArray = options.dashes -proto.update = function(array, offset) { - if(typeof offset !== "number") { - offset = -1 - } - this.bind() - if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray - var dtype = array.dtype - if(SUPPORTED_TYPES.indexOf(dtype) < 0) { - dtype = "float32" - } - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - var ext = gl.getExtension('OES_element_index_uint') - if(ext && dtype !== "uint16") { - dtype = "uint32" - } else { - dtype = "uint16" - } + // Calculate prefix sum + var prefixSum = dashArray.slice() + prefixSum.unshift(0) + for (i = 1; i < prefixSum.length; ++i) { + prefixSum[i] = prefixSum[i - 1] + prefixSum[i] } - if(dtype === array.dtype && isPacked(array.shape, array.stride)) { - if(array.offset === 0 && array.data.length === array.shape[0]) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) + + var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]) + for (i = 0; i < 256; ++i) { + for (j = 0; j < 4; ++j) { + dashTexture.set(i, 0, j, 0) } - } else { - var tmp = pool.malloc(array.size, dtype) - var ndt = ndarray(tmp, array.shape) - ops.assign(ndt, array) - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) + if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { + dashTexture.set(i, 0, 0, 0) } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) + dashTexture.set(i, 0, 0, 255) } - pool.free(tmp) - } - } else if(Array.isArray(array)) { //Vanilla array - var t - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - t = makeScratchTypeArray(array, "uint16") - } else { - t = makeScratchTypeArray(array, "float32") - } - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) - } - pool.free(t) - } else if(typeof array === "object" && typeof array.length === "number") { //Typed array - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) - } else if(typeof array === "number" || array === undefined) { //Number/default - if(offset >= 0) { - throw new Error("gl-buffer: Cannot specify offset when resizing buffer") - } - array = array | 0 - if(array <= 0) { - array = 1 } - this.gl.bufferData(this.type, array|0, this.usage) - this.length = array - } else { //Error, case should not happen - throw new Error("gl-buffer: Invalid data type") + + this.texture.setPixels(dashTexture) } } -function createBuffer(gl, data, type, usage) { - type = type || gl.ARRAY_BUFFER - usage = usage || gl.DYNAMIC_DRAW - if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { - throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") +proto.dispose = function () { + this.shader.dispose() + this.vao.dispose() + this.buffer.dispose() +} + +proto.pick = function (selection) { + if (!selection) { + return null } - if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { - throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") + if (selection.id !== this.pickId) { + return null } - var handle = gl.createBuffer() - var result = new GLBuffer(gl, type, handle, 0, usage) - result.update(data) - return result + var tau = unpackFloat( + selection.value[0], + selection.value[1], + selection.value[2], + 0) + var index = bsearch.le(this.arcLength, tau) + if (index < 0) { + return null + } + if (index === this.arcLength.length - 1) { + return new PickResult( + this.arcLength[this.arcLength.length - 1], + this.points[this.points.length - 1].slice(), + index) + } + var a = this.points[index] + var b = this.points[Math.min(index + 1, this.points.length - 1)] + var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]) + var ti = 1.0 - t + var x = [0, 0, 0] + for (var i = 0; i < 3; ++i) { + x[i] = ti * a[i] + t * b[i] + } + var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1) + return new PickResult( + tau, + x, + dataIndex, + this.points[dataIndex]) } -module.exports = createBuffer +function createLinePlot (options) { + var gl = options.gl || (options.scene && options.scene.gl) -},{"ndarray":253,"ndarray-ops":252,"typedarray-pool":278}],119:[function(require,module,exports){ -'use strict' + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.nextPosition.location = 1 + shader.attributes.arcLength.location = 2 + shader.attributes.lineWidth.location = 3 + shader.attributes.color.location = 4 -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var pool = require('typedarray-pool') -var shaders = require('./lib/shaders') + var pickShader = createPickShader(gl) + pickShader.attributes.position.location = 0 + pickShader.attributes.nextPosition.location = 1 + pickShader.attributes.arcLength.location = 2 + pickShader.attributes.lineWidth.location = 3 + pickShader.attributes.color.location = 4 -module.exports = createError2D + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + 'buffer': buffer, + 'size': 3, + 'offset': 0, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 3, + 'offset': 12, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 1, + 'offset': 24, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 1, + 'offset': 28, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 4, + 'offset': 32, + 'stride': 48 + } + ]) -var WEIGHTS = [ - // x-error bar - [1, 0, 0, 1, 0, 0], - [1, 0, 0, -1, 0, 0], - [-1, 0, 0, -1, 0, 0], + // Create texture for dash pattern + var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) + for (var i = 0; i < 256 * 4; ++i) { + defaultTexture.data[i] = 255 + } + var texture = createTexture(gl, defaultTexture) + texture.wrap = gl.REPEAT - [-1, 0, 0, -1, 0, 0], - [-1, 0, 0, 1, 0, 0], - [1, 0, 0, 1, 0, 0], + var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) + linePlot.update(options) + return linePlot +} - // x-error right cap - [1, 0, -1, 0, 0, 1], - [1, 0, -1, 0, 0, -1], - [1, 0, 1, 0, 0, -1], +},{"./lib/shaders":192,"binary-search-bounds":194,"gl-buffer":195,"gl-texture2d":228,"gl-vao":232,"glsl-read-float":233,"ndarray":1031}],194:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],195:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":198}],196:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],197:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],198:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":196,"buffer":65,"dup":122}],199:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":200,"./lib/create-attributes":201,"./lib/create-uniforms":202,"./lib/reflect":203,"./lib/runtime-reflect":204,"./lib/shader-cache":205,"dup":94}],200:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],201:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":200,"dup":96}],202:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":200,"./reflect":203,"dup":97}],203:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],204:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],205:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":200,"dup":100,"gl-format-compiler-error":206,"weakmap-shim":224}],206:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":207,"dup":101,"gl-constants/lookup":211,"glsl-shader-name":212,"sprintf-js":221}],207:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":208}],208:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":209}],209:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],210:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],211:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":210,"dup":106}],212:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":213,"dup":107,"glsl-tokenizer":220}],213:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],214:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":216,"./lib/builtins-300es":215,"./lib/literals":218,"./lib/literals-300es":217,"./lib/operators":219,"dup":109}],215:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":216,"dup":110}],216:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],217:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":218,"dup":112}],218:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],219:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],220:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":214,"dup":115}],221:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],222:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":223,"dup":117}],223:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],224:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":222,"dup":119}],225:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],226:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],227:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":225,"buffer":65,"dup":122}],228:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":227}],229:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],230:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":229,"dup":155}],231:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":229,"dup":156}],232:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":230,"./lib/vao-native.js":231,"dup":157}],233:[function(require,module,exports){ +module.exports = decodeFloat - [1, 0, 1, 0, 0, -1], - [1, 0, 1, 0, 0, 1], - [1, 0, -1, 0, 0, 1], +var UINT8_VIEW = new Uint8Array(4) +var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) - // x-error left cap - [-1, 0, -1, 0, 0, 1], - [-1, 0, -1, 0, 0, -1], - [-1, 0, 1, 0, 0, -1], +function decodeFloat(x, y, z, w) { + UINT8_VIEW[0] = w + UINT8_VIEW[1] = z + UINT8_VIEW[2] = y + UINT8_VIEW[3] = x + return FLOAT_VIEW[0] +} - [-1, 0, 1, 0, 0, -1], - [-1, 0, 1, 0, 0, 1], - [-1, 0, -1, 0, 0, 1], +},{}],234:[function(require,module,exports){ +module.exports = clone; - // y-error bar - [0, 1, 1, 0, 0, 0], - [0, 1, -1, 0, 0, 0], - [0, -1, -1, 0, 0, 0], +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {mat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ +function clone(a) { + var out = new Float32Array(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; +},{}],235:[function(require,module,exports){ +module.exports = create; - [0, -1, -1, 0, 0, 0], - [0, 1, 1, 0, 0, 0], - [0, -1, 1, 0, 0, 0], +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ +function create() { + var out = new Float32Array(16); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; +},{}],236:[function(require,module,exports){ +module.exports = determinant; - // y-error top cap - [0, 1, 0, -1, 1, 0], - [0, 1, 0, -1, -1, 0], - [0, 1, 0, 1, -1, 0], +/** + * Calculates the determinant of a mat4 + * + * @param {mat4} a the source matrix + * @returns {Number} determinant of a + */ +function determinant(a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - [0, 1, 0, 1, 1, 0], - [0, 1, 0, -1, 1, 0], - [0, 1, 0, 1, -1, 0], + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32; - // y-error bottom cap - [0, -1, 0, -1, 1, 0], - [0, -1, 0, -1, -1, 0], - [0, -1, 0, 1, -1, 0], + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +}; +},{}],237:[function(require,module,exports){ +module.exports = fromQuat; - [0, -1, 0, 1, 1, 0], - [0, -1, 0, -1, 1, 0], - [0, -1, 0, 1, -1, 0] -] +/** + * Creates a matrix from a quaternion rotation. + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @returns {mat4} out + */ +function fromQuat(out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, -function GLError2D (plot, shader, buffer) { - this.plot = plot + xx = x * x2, + yx = y * x2, + yy = y * y2, + zx = z * x2, + zy = z * y2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; - this.shader = shader - this.buffer = buffer + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; - this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; - this.numPoints = 0 + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; - this.color = [0, 0, 0, 1] -} + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; -var proto = GLError2D.prototype + return out; +}; +},{}],238:[function(require,module,exports){ +module.exports = fromRotationTranslation; -proto.draw = (function () { - var MATRIX = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {vec3} v Translation vector + * @returns {mat4} out + */ +function fromRotationTranslation(out, q, v) { + // Quaternion math + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + xy = x * y2, + xz = x * z2, + yy = y * y2, + yz = y * z2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + + return out; +}; +},{}],239:[function(require,module,exports){ +module.exports = identity; + +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ +function identity(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; +},{}],240:[function(require,module,exports){ +module.exports = invert; + +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - var PIXEL_SCALE = [1, 1] + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, - return function () { - var plot = this.plot - var shader = this.shader - var buffer = this.buffer - var bounds = this.bounds - var numPoints = this.numPoints + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - if (!numPoints) { - return + if (!det) { + return null; } + det = 1.0 / det; - var gl = plot.gl - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + return out; +}; +},{}],241:[function(require,module,exports){ +var identity = require('./identity'); - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] +module.exports = lookAt; - PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX - PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {vec3} eye Position of the viewer + * @param {vec3} center Point the viewer is looking at + * @param {vec3} up vec3 pointing up + * @returns {mat4} out + */ +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, + eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2], + centerx = center[0], + centery = center[1], + centerz = center[2]; - buffer.bind() - shader.bind() + if (Math.abs(eyex - centerx) < 0.000001 && + Math.abs(eyey - centery) < 0.000001 && + Math.abs(eyez - centerz) < 0.000001) { + return identity(out); + } - shader.uniforms.viewTransform = MATRIX - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.color = this.color + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; - shader.attributes.position.pointer( - gl.FLOAT, - false, - 16, - 0) + len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len; + z1 *= len; + z2 *= len; - shader.attributes.pixelOffset.pointer( - gl.FLOAT, - false, - 16, - 8) + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } - gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length) - } -})() + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; -proto.drawPick = function (offset) { return offset } -proto.pick = function (x, y) { - return null -} + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } -proto.update = function (options) { - options = options || {} + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; - var i, x, y + return out; +}; +},{"./identity":239}],242:[function(require,module,exports){ +module.exports = multiply; - var positions = options.positions || [] - var errors = options.errors || [] +/** + * Multiplies two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +function multiply(out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - var lineWidth = 1 - if ('lineWidth' in options) { - lineWidth = +options.lineWidth - } + // Cache only the current line of the second matrix + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - var capSize = 5 - if ('capSize' in options) { - capSize = +options.capSize - } + b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; + out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - this.color = (options.color || [0, 0, 0, 1]).slice() + b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; + out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; + out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + return out; +}; +},{}],243:[function(require,module,exports){ +module.exports = perspective; - var numPoints = this.numPoints = positions.length >> 1 - for (i = 0; i < numPoints; ++i) { - x = positions[i * 2] - y = positions[i * 2 + 1] +/** + * Generates a perspective projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +function perspective(out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf = 1 / (near - far); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = (2 * far * near) * nf; + out[15] = 0; + return out; +}; +},{}],244:[function(require,module,exports){ +module.exports = rotate; - bounds[0] = Math.min(x, bounds[0]) - bounds[1] = Math.min(y, bounds[1]) - bounds[2] = Math.max(x, bounds[2]) - bounds[3] = Math.max(y, bounds[3]) - } - if (bounds[2] === bounds[0]) { - bounds[2] += 1 - } - if (bounds[3] === bounds[1]) { - bounds[3] += 1 - } - var sx = 1.0 / (bounds[2] - bounds[0]) - var sy = 1.0 / (bounds[3] - bounds[1]) - var tx = bounds[0] - var ty = bounds[1] +/** + * Rotates a mat4 by the given angle + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ +function rotate(out, a, rad, axis) { + var x = axis[0], y = axis[1], z = axis[2], + len = Math.sqrt(x * x + y * y + z * z), + s, c, t, + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + b00, b01, b02, + b10, b11, b12, + b20, b21, b22; - var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4) - var ptr = 0 - for (i = 0; i < numPoints; ++i) { - x = positions[2 * i] - y = positions[2 * i + 1] - var ex0 = errors[4 * i] - var ex1 = errors[4 * i + 1] - var ey0 = errors[4 * i + 2] - var ey1 = errors[4 * i + 3] + if (Math.abs(len) < 0.000001) { return null; } + + len = 1 / len; + x *= len; + y *= len; + z *= len; - for (var j = 0; j < WEIGHTS.length; ++j) { - var w = WEIGHTS[j] + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; - var dx = w[0] - var dy = w[1] + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; - if (dx < 0) { - dx *= ex0 - } else if (dx > 0) { - dx *= ex1 - } + // Construct the elements of the rotation matrix + b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; + b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; + b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; - if (dy < 0) { - dy *= ey0 - } else if (dy > 0) { - dy *= ey1 - } + // Perform rotation-specific matrix multiplication + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; - bufferData[ptr++] = sx * ((x - tx) + dx) - bufferData[ptr++] = sy * ((y - ty) + dy) - bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4] - bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5] + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; } - } - this.buffer.update(bufferData) - pool.free(bufferData) -} - -proto.dispose = function () { - this.plot.removeObject(this) - this.shader.dispose() - this.buffer.dispose() -} - -function createError2D (plot, options) { - var shader = createShader(plot.gl, shaders.vertex, shaders.fragment) - var buffer = createBuffer(plot.gl) + return out; +}; +},{}],245:[function(require,module,exports){ +module.exports = rotateX; - var errorbars = new GLError2D(plot, shader, buffer) +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +function rotateX(out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; - errorbars.update(options) + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } - plot.addObject(errorbars) + // Perform axis-specific matrix multiplication + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +}; +},{}],246:[function(require,module,exports){ +module.exports = rotateY; - return errorbars -} +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +function rotateY(out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; -},{"./lib/shaders":120,"gl-buffer":118,"gl-shader":197,"typedarray-pool":278}],120:[function(require,module,exports){ + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + // Perform axis-specific matrix multiplication + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +}; +},{}],247:[function(require,module,exports){ +module.exports = rotateZ; -module.exports = { - vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n", - fragment: "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" -} +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +function rotateZ(out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; -},{}],121:[function(require,module,exports){ -'use strict' + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } -module.exports = createErrorBars + // Perform axis-specific matrix multiplication + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +}; +},{}],248:[function(require,module,exports){ +module.exports = scale; -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders/index') +/** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {vec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ +function scale(out, a, v) { + var x = v[0], y = v[1], z = v[2]; -var IDENTITY = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; +},{}],249:[function(require,module,exports){ +module.exports = translate; -function ErrorBars(gl, buffer, vao, shader) { - this.gl = gl - this.shader = shader - this.buffer = buffer - this.vao = vao - this.pixelRatio = 1 - this.bounds = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]] - this.clipBounds = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]] - this.lineWidth = [1,1,1] - this.capSize = [10,10,10] - this.lineCount = [0,0,0] - this.lineOffset = [0,0,0] - this.opacity = 1 -} +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to translate + * @param {vec3} v vector to translate by + * @returns {mat4} out + */ +function translate(out, a, v) { + var x = v[0], y = v[1], z = v[2], + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23; -var proto = ErrorBars.prototype + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; -proto.isOpaque = function() { - return this.opacity >= 1 -} + out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; + out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; + out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; -proto.isTransparent = function() { - return this.opacity < 1 -} + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } -proto.drawTransparent = proto.draw = function(cameraParams) { - var gl = this.gl - var uniforms = this.shader.uniforms + return out; +}; +},{}],250:[function(require,module,exports){ +module.exports = transpose; - this.shader.bind() - var view = uniforms.view = cameraParams.view || IDENTITY - var projection = uniforms.projection = cameraParams.projection || IDENTITY - uniforms.model = cameraParams.model || IDENTITY - uniforms.clipBounds = this.clipBounds - uniforms.opacity = this.opacity +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +function transpose(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], a02 = a[2], a03 = a[3], + a12 = a[6], a13 = a[7], + a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +}; +},{}],251:[function(require,module,exports){ +'use strict' - var cx = view[12] - var cy = view[13] - var cz = view[14] - var cw = view[15] - var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight +var barycentric = require('barycentric') +var closestPointToTriangle = require('polytope-closest-point/lib/closest_point_2d.js') +module.exports = closestPointToPickLocation - this.vao.bind() - for(var i=0; i<3; ++i) { - gl.lineWidth(this.lineWidth[i]) - uniforms.capSize = this.capSize[i] * pixelScaleF - gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i]) +function xformMatrix(m, v) { + var out = [0,0,0,0] + for(var i=0; i<4; ++i) { + for(var j=0; j<4; ++j) { + out[j] += m[4*i + j] * v[i] + } } - this.vao.unbind() + return out } -function updateBounds(bounds, point) { +function projectVertex(v, model, view, projection, resolution) { + var p = xformMatrix(projection, + xformMatrix(view, + xformMatrix(model, [v[0], v[1], v[2], 1]))) for(var i=0; i<3; ++i) { - bounds[0][i] = Math.min(bounds[0][i], point[i]) - bounds[1][i] = Math.max(bounds[1][i], point[i]) + p[i] /= p[3] } + return [ 0.5 * resolution[0] * (1.0+p[0]), 0.5 * resolution[1] * (1.0-p[1]) ] } -var FACE_TABLE = (function(){ - var table = new Array(3) - for(var d=0; d<3; ++d) { - var row = [] - for(var j=1; j<=2; ++j) { - for(var s=-1; s<=1; s+=2) { - var u = (j+d) % 3 - var y = [0,0,0] - y[u] = s - row.push(y) - } +function barycentricCoord(simplex, point) { + if(simplex.length === 2) { + var d0 = 0.0 + var d1 = 0.0 + for(var i=0; i<2; ++i) { + d0 += Math.pow(point[i] - simplex[0][i], 2) + d1 += Math.pow(point[i] - simplex[1][i], 2) } - table[d] = row - } - return table -})() - - -function emitFace(verts, x, c, d) { - var offsets = FACE_TABLE[d] - for(var i=0; i 0) { - var x = p.slice() - x[j] += e[1][j] - verts.push(p[0], p[1], p[2], - c[0], c[1], c[2], c[3], - 0, 0, 0, - x[0], x[1], x[2], - c[0], c[1], c[2], c[3], - 0, 0, 0) - updateBounds(this.bounds, x) - vertexCount += 2 + emitFace(verts, x, c, j) - } - } - this.lineCount[j] = vertexCount - this.lineOffset[j] + var weights = barycentricCoord(simplex2D, pixelCoord) + var s = 0.0 + for(var i=0; i<3; ++i) { + if(weights[i] < -0.001 || + weights[i] > 1.0001) { + return null } - this.buffer.update(verts) + s += weights[i] } + if(Math.abs(s - 1.0) > 0.001) { + return null + } + return [closestIndex, interpolate(simplex, weights), weights] } +},{"barycentric":254,"polytope-closest-point/lib/closest_point_2d.js":298}],252:[function(require,module,exports){ -proto.dispose = function() { - this.shader.dispose() - this.buffer.dispose() - this.vao.dispose() -} - -function createErrorBars(options) { - var gl = options.gl - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 0, - stride: 40 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 4, - offset: 12, - stride: 40 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 28, - stride: 40 - } - ]) - - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.color.location = 1 - shader.attributes.offset.location = 2 - - var result = new ErrorBars(gl, buffer, vao, shader) - result.update(options) - return result -} - -},{"./shaders/index":122,"gl-buffer":118,"gl-vao":226}],122:[function(require,module,exports){ -'use strict' - - -var createShader = require('gl-shader') -var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}" -var fragSrc = "precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}" +var triVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}" +var triFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}" +var edgeVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}" +var edgeFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" +var pointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}" +var pointFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" +var pickVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}" +var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}" +var pickPointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}" +var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}" +var contourFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n" -module.exports = function(gl) { - return createShader(gl, vertSrc, fragSrc, null, [ +exports.meshShader = { + vertex: triVertSrc, + fragment: triFragSrc, + attributes: [ {name: 'position', type: 'vec3'}, - {name: 'offset', type: 'vec3'}, - {name: 'color', type: 'vec4'} - ]) -} - -},{"gl-shader":197}],123:[function(require,module,exports){ -'use strict' - -var createTexture = require('gl-texture2d') - -module.exports = createFBO - -var colorAttachmentArrays = null -var FRAMEBUFFER_UNSUPPORTED -var FRAMEBUFFER_INCOMPLETE_ATTACHMENT -var FRAMEBUFFER_INCOMPLETE_DIMENSIONS -var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT - -function saveFBOState(gl) { - var fbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) - var rbo = gl.getParameter(gl.RENDERBUFFER_BINDING) - var tex = gl.getParameter(gl.TEXTURE_BINDING_2D) - return [fbo, rbo, tex] + {name: 'normal', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'} + ] } - -function restoreFBOState(gl, data) { - gl.bindFramebuffer(gl.FRAMEBUFFER, data[0]) - gl.bindRenderbuffer(gl.RENDERBUFFER, data[1]) - gl.bindTexture(gl.TEXTURE_2D, data[2]) +exports.wireShader = { + vertex: edgeVertSrc, + fragment: edgeFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'} + ] } - -function lazyInitColorAttachments(gl, ext) { - var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL) - colorAttachmentArrays = new Array(maxColorAttachments + 1) - for(var i=0; i<=maxColorAttachments; ++i) { - var x = new Array(maxColorAttachments) - for(var j=0; j 1) { - ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]) - } +var identityMatrix = [ + 1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] - //Allocate depth/stencil buffers - var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture') - if(WEBGL_depth_texture) { - if(useStencil) { - fbo.depth = initTexture(gl, width, height, - WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, - gl.DEPTH_STENCIL, - gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo.depth = initTexture(gl, width, height, - gl.UNSIGNED_SHORT, - gl.DEPTH_COMPONENT, - gl.DEPTH_ATTACHMENT) - } - } else { - if(useDepth && useStencil) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT) - } else if(useStencil) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT) - } - } +function SimplicialMesh(gl + , texture + , triShader + , lineShader + , pointShader + , pickShader + , pointPickShader + , contourShader + , trianglePositions + , triangleIds + , triangleColors + , triangleUVs + , triangleNormals + , triangleVAO + , edgePositions + , edgeIds + , edgeColors + , edgeUVs + , edgeVAO + , pointPositions + , pointIds + , pointColors + , pointUVs + , pointSizes + , pointVAO + , contourPositions + , contourVAO) { - //Check frame buffer state - var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) - if(status !== gl.FRAMEBUFFER_COMPLETE) { + this.gl = gl + this.cells = [] + this.positions = [] + this.intensity = [] + this.texture = texture + this.dirty = true - //Release all partially allocated resources - fbo._destroyed = true + this.triShader = triShader + this.lineShader = lineShader + this.pointShader = pointShader + this.pickShader = pickShader + this.pointPickShader = pointPickShader + this.contourShader = contourShader - //Release all resources - gl.bindFramebuffer(gl.FRAMEBUFFER, null) - gl.deleteFramebuffer(fbo.handle) - fbo.handle = null - if(fbo.depth) { - fbo.depth.dispose() - fbo.depth = null - } - if(fbo._depth_rb) { - gl.deleteRenderbuffer(fbo._depth_rb) - fbo._depth_rb = null - } - for(var i=0; i= 1 } -var proto = Framebuffer.prototype +proto.isTransparent = function() { + return this.opacity < 1 +} -function reshapeFBO(fbo, w, h) { - //If fbo is invalid, just skip this - if(fbo._destroyed) { - throw new Error('gl-fbo: Can\'t resize destroyed FBO') - } +proto.pickSlots = 1 - //Don't resize if no change in shape - if( (fbo._shape[0] === w) && - (fbo._shape[1] === h) ) { - return - } +proto.setPickBase = function(id) { + this.pickId = id +} - var gl = fbo.gl +function genColormap(param) { + var colors = colormap({ + colormap: param + , nshades: 256 + , format: 'rgba' + }) - //Check parameter ranges - var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) - if( w < 0 || w > maxFBOSize || - h < 0 || h > maxFBOSize) { - throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions') + var result = new Uint8Array(256*4) + for(var i=0; i<256; ++i) { + var c = colors[i] + for(var j=0; j<3; ++j) { + result[4*i+j] = c[j] + } + result[4*i+3] = c[3]*255 } - //Update shape - fbo._shape[0] = w - fbo._shape[1] = h - - //Save framebuffer state - var state = saveFBOState(gl) + return ndarray(result, [256,256,4], [4,0,1]) +} - //Resize framebuffer attachments - for(var i=0; i maxFBOSize || height < 0 || height > maxFBOSize) { - throw new Error('gl-fbo: Parameters are too large for FBO') + if('opacity' in params) { + this.opacity = params.opacity } - - //Handle each option type - options = options || {} - - //Figure out number of color buffers to use - var numColors = 1 - if('color' in options) { - numColors = Math.max(options.color|0, 0) - if(numColors < 0) { - throw new Error('gl-fbo: Must specify a nonnegative number of colors') - } - if(numColors > 1) { - //Check if multiple render targets supported - if(!WEBGL_draw_buffers) { - throw new Error('gl-fbo: Multiple draw buffer extension not supported') - } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) { - throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers') - } - } + if('ambient' in params) { + this.ambientLight = params.ambient + } + if('diffuse' in params) { + this.diffuseLight = params.diffuse + } + if('specular' in params) { + this.specularLight = params.specular } - - //Determine whether to use floating point textures - var colorType = gl.UNSIGNED_BYTE - var OES_texture_float = gl.getExtension('OES_texture_float') - if(options.float && numColors > 0) { - if(!OES_texture_float) { - throw new Error('gl-fbo: Context does not support floating point textures') - } - colorType = gl.FLOAT - } else if(options.preferFloat && numColors > 0) { - if(OES_texture_float) { - colorType = gl.FLOAT - } + if('roughness' in params) { + this.roughness = params.roughness } - - //Check if we should use depth buffer - var useDepth = true - if('depth' in options) { - useDepth = !!options.depth + if('fresnel' in params) { + this.fresnel = params.fresnel } - //Check if we should use a stencil buffer - var useStencil = false - if('stencil' in options) { - useStencil = !!options.stencil + if(params.texture) { + this.texture.dispose() + this.texture = createTexture(gl, params.texture) + } else if (params.colormap) { + this.texture.shape = [256,256] + this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR + this.texture.magFilter = gl.LINEAR + this.texture.setPixels(genColormap(params.colormap)) + this.texture.generateMipmap() } - return new Framebuffer( - gl, - width, - height, - colorType, - numColors, - useDepth, - useStencil, - WEBGL_draw_buffers) -} + var cells = params.cells + var positions = params.positions -},{"gl-texture2d":222}],124:[function(require,module,exports){ + if(!positions || !cells) { + return + } + var tPos = [] + var tCol = [] + var tNor = [] + var tUVs = [] + var tIds = [] -exports.lineVertex = "precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n vec2 dir = (matrix * vec3(d, 0)).xy;\n vec3 base = matrix * vec3(a, 1);\n vec2 n = 0.5 * width *\n normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n vec2 tangent = normalize(screenShape.xy * dir);\n if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n direction = -tangent;\n } else {\n direction = tangent;\n }\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n" -exports.lineFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n" -exports.mitreVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 p;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n vec3 pp = matrix * vec3(p, 1);\n gl_Position = vec4(pp.xy, 0, pp.z);\n gl_PointSize = radius;\n}\n" -exports.mitreFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n discard;\n }\n gl_FragColor = vec4(color.rgb, color.a);\n}\n" -exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 n = width *\n normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n pickA = pick0;\n pickB = pick1;\n}\n" -exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n vec4 fragId = vec4(pickA.xyz, 0.0);\n if(pickB.w > pickA.w) {\n fragId.xyz = pickB.xyz;\n }\n\n fragId += pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n gl_FragColor = fragId / 255.0;\n}\n" -exports.fillVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 p = base.xy / base.z;\n if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n if(dot(p, projectAxis) < projectValue) {\n p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n }\n }\n gl_Position = vec4(p, depth, 1);\n}\n" -exports.fillFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" + var ePos = [] + var eCol = [] + var eUVs = [] + var eIds = [] -},{}],125:[function(require,module,exports){ -'use strict' + var pPos = [] + var pCol = [] + var pUVs = [] + var pSiz = [] + var pIds = [] -module.exports = createLinePlot + //Save geometry data for picking calculations + this.cells = cells + this.positions = positions -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var createTexture = require('gl-texture2d') -var ndarray = require('ndarray') -var pool = require('typedarray-pool') + //Compute normals + var vertexNormals = params.vertexNormals + var cellNormals = params.cellNormals + var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon + var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon + if(params.useFacetNormals && !cellNormals) { + cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon) + } + if(!cellNormals && !vertexNormals) { + vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon) + } -var SHADERS = require('./lib/shaders') + //Compute colors + var vertexColors = params.vertexColors + var cellColors = params.cellColors + var meshColor = params.meshColor || [1,1,1,1] -function GLLine2D( - plot, - dashPattern, - lineBuffer, - pickBuffer, - lineShader, - mitreShader, - fillShader, - pickShader) { + //UVs + var vertexUVs = params.vertexUVs + var vertexIntensity = params.vertexIntensity + var cellUVs = params.cellUVs + var cellIntensity = params.cellIntensity - this.plot = plot - this.dashPattern = dashPattern - this.lineBuffer = lineBuffer - this.pickBuffer = pickBuffer - this.lineShader = lineShader - this.mitreShader = mitreShader - this.fillShader = fillShader - this.pickShader = pickShader - this.usingDashes = false + var intensityLo = Infinity + var intensityHi = -Infinity + if(!vertexUVs && !cellUVs) { + if(vertexIntensity) { + for(var i=0; i 2 && !this.usingDashes) { - var mshader = this.mitreShader - mshader.bind() + this.pointPositions.update(pPos) + this.pointColors.update(pCol) + this.pointUVs.update(pUVs) + this.pointSizes.update(pSiz) + this.pointIds.update(new Uint32Array(pIds)) - var muniforms = mshader.uniforms - muniforms.matrix = MATRIX - muniforms.color = color - muniforms.screenShape = SCREEN_SHAPE - muniforms.radius = width * pixelRatio + this.edgePositions.update(ePos) + this.edgeColors.update(eCol) + this.edgeUVs.update(eUVs) + this.edgeIds.update(new Uint32Array(eIds)) - mshader.attributes.p.pointer(gl.FLOAT, false, 48, 0) - gl.drawArrays(gl.POINTS, 0, (count/3)|0) - } + this.trianglePositions.update(tPos) + this.triangleColors.update(tCol) + this.triangleUVs.update(tUVs) + this.triangleNormals.update(tNor) + this.triangleIds.update(new Uint32Array(tIds)) } -})() - -proto.drawPick = (function() { - var MATRIX = [1, 0, 0, - 0, 1, 0, - 0, 0, 1] - var SCREEN_SHAPE = [0,0] - var PICK_OFFSET = [0,0,0,0] - return function(pickOffset) { - var plot = this.plot - var shader = this.pickShader - var buffer = this.lineBuffer - var pickBuffer= this.pickBuffer - var width = this.width - var numPoints = this.numPoints - var bounds = this.bounds - var count = this.vertCount - - var gl = plot.gl - var viewBox = plot.viewBox - var dataBox = plot.dataBox - var pixelRatio = plot.pickPixelRatio - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] - this.pickOffset = pickOffset +proto.drawTransparent = proto.draw = function(params) { + params = params || {} + var gl = this.gl + var model = params.model || identityMatrix + var view = params.view || identityMatrix + var projection = params.projection || identityMatrix - if(!count) { - return pickOffset + numPoints - } + var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]] + for(var i=0; i<3; ++i) { + clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]) + clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]) + } - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + var uniforms = { + model: model, + view: view, + projection: projection, - SCREEN_SHAPE[0] = screenX - SCREEN_SHAPE[1] = screenY + clipBounds: clipBounds, - PICK_OFFSET[0] = pickOffset & 0xff - PICK_OFFSET[1] = (pickOffset>>>8) & 0xff - PICK_OFFSET[2] = (pickOffset>>>16) & 0xff - PICK_OFFSET[3] = pickOffset>>>24 + kambient: this.ambientLight, + kdiffuse: this.diffuseLight, + kspecular: this.specularLight, + roughness: this.roughness, + fresnel: this.fresnel, - shader.bind() + eyePosition: [0,0,0], + lightPosition: [0,0,0], - var uniforms = shader.uniforms - uniforms.matrix = MATRIX - uniforms.width = width * pixelRatio - uniforms.pickOffset = PICK_OFFSET - uniforms.screenShape = SCREEN_SHAPE + opacity: this.opacity, - var attributes = shader.attributes + contourColor: this.contourColor, - buffer.bind() - attributes.a.pointer(gl.FLOAT, false, 16, 0) - attributes.d.pointer(gl.FLOAT, false, 16, 8) + texture: 0 + } - pickBuffer.bind() - attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0) - attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4) + this.texture.bind(0) - gl.drawArrays(gl.TRIANGLES, 0, count) + var invCameraMatrix = new Array(16) + multiply(invCameraMatrix, uniforms.view, uniforms.model) + multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) + invert(invCameraMatrix, invCameraMatrix) - return pickOffset + numPoints + for(var i=0; i<3; ++i) { + uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15] } -})() -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.numPoints - if(value < pickOffset || value >= pickOffset + pointCount) { - return null + var w = invCameraMatrix[15] + for(var i=0; i<3; ++i) { + w += this.lightPosition[i] * invCameraMatrix[4*i+3] } - var pointId = value - pickOffset - var points = this.data - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + for(var i=0; i<3; ++i) { + var s = invCameraMatrix[12+i] + for(var j=0; j<3; ++j) { + s += invCameraMatrix[4*j+i] * this.lightPosition[j] + } + uniforms.lightPosition[i] = s / w } -} - -function deepCopy(arr) { - return arr.map(function(x) { - return x.slice() - }) -} -proto.update = function(options) { - options = options || {} + if(this.triangleCount > 0) { + var shader = this.triShader + shader.bind() + shader.uniforms = uniforms - var gl = this.plot.gl + this.triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) + this.triangleVAO.unbind() + } - var connectGaps = !!options.connectGaps + if(this.edgeCount > 0 && this.lineWidth > 0) { + var shader = this.lineShader + shader.bind() + shader.uniforms = uniforms - this.color = (options.color || [0,0,1,1]).slice() - this.width = +(options.width || 1) + this.edgeVAO.bind() + gl.lineWidth(this.lineWidth) + gl.drawArrays(gl.LINES, 0, this.edgeCount*2) + this.edgeVAO.unbind() + } - this.fill = (options.fill || [false,false,false,false]).slice() - this.fillColor = deepCopy(options.fillColor || [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]]) + if(this.pointCount > 0) { + var shader = this.pointShader + shader.bind() + shader.uniforms = uniforms - var dashes = options.dashes || [1] - var dashLength = 0 - for(var i=0; i 0 && this.contourLineWidth > 0) { + var shader = this.contourShader + shader.bind() + shader.uniforms = uniforms + + this.contourVAO.bind() + gl.drawArrays(gl.LINES, 0, this.contourCount) + this.contourVAO.unbind() } - this.dashPattern.dispose() - this.usingDashes = dashes.length > 1 +} - this.dashPattern = createTexture(gl, - ndarray(dashData, [dashLength, 1, 4], [1, 0, 0])) - this.dashPattern.minFilter = gl.NEAREST - this.dashPattern.magFilter = gl.NEAREST - this.dashLength = dashLength - pool.free(dashData) +proto.drawPick = function(params) { + params = params || {} - var data = options.positions - this.data = data + var gl = this.gl - var bounds = this.bounds - bounds[0] = bounds[1] = Infinity - bounds[2] = bounds[3] = -Infinity + var model = params.model || identityMatrix + var view = params.view || identityMatrix + var projection = params.projection || identityMatrix - var numPoints = this.numPoints = data.length>>>1 - if(numPoints === 0) { - return + var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]] + for(var i=0; i<3; ++i) { + clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]) + clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]) } - for(var i=0; i 0) { + this.triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) + this.triangleVAO.unbind() } - //Generate line data - var lineData = pool.mallocFloat32(24*(numPoints-1)) - var pickData = pool.mallocUint32(12*(numPoints-1)) - var lineDataPtr = lineData.length - var pickDataPtr = pickData.length - var ptr = numPoints + if(this.edgeCount > 0) { + this.edgeVAO.bind() + gl.lineWidth(this.lineWidth) + gl.drawArrays(gl.LINES, 0, this.edgeCount*2) + this.edgeVAO.unbind() + } - var count = 0 + if(this.pointCount > 0) { + var shader = this.pointPickShader + shader.bind() + shader.uniforms = uniforms - while(ptr > 1) { - var id = --ptr - var ax = data[2*ptr] - var ay = data[2*ptr+1] + this.pointVAO.bind() + gl.drawArrays(gl.POINTS, 0, this.pointCount) + this.pointVAO.unbind() + } +} - var next = id-1 - var bx = data[2*next] - var by = data[2*next+1] - if (isNaN(ax) || isNaN(ay) || isNaN(bx) || isNaN(by)) { - continue - } +proto.pick = function(pickData) { + if(!pickData) { + return null + } + if(pickData.id !== this.pickId) { + return null + } - count += 1 + var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2] + var cell = this.cells[cellId] + var positions = this.positions - ax = (ax - bounds[0]) / (bounds[2] - bounds[0]) - ay = (ay - bounds[1]) / (bounds[3] - bounds[1]) + var simplex = new Array(cell.length) + for(var i=0; i= 1 -} +module.exports = createSimplicialMesh -proto.pickSlots = 1 +},{"./lib/closest-point":251,"./lib/shaders":252,"colormap":263,"gl-buffer":265,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-shader":266,"gl-texture2d":292,"gl-vao":296,"ndarray":1031,"normals":297,"simplicial-complex-contour":299,"typedarray-pool":306}],254:[function(require,module,exports){ +'use strict' -proto.setPickBase = function (id) { - this.pickId = id -} +module.exports = barycentric -proto.drawTransparent = proto.draw = function (camera) { - var gl = this.gl - var shader = this.shader - var vao = this.vao - shader.bind() - shader.uniforms = { - model: camera.model || identity, - view: camera.view || identity, - projection: camera.projection || identity, - clipBounds: filterClipBounds(this.clipBounds), - dashTexture: this.texture.bind(), - dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], - opacity: this.opacity, - screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], - pixelRatio: this.pixelRatio - } - vao.bind() - vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) -} +var solve = require('robust-linear-solve') -proto.drawPick = function (camera) { - var gl = this.gl - var shader = this.pickShader - var vao = this.vao - shader.bind() - shader.uniforms = { - model: camera.model || identity, - view: camera.view || identity, - projection: camera.projection || identity, - pickId: this.pickId, - clipBounds: filterClipBounds(this.clipBounds), - screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], - pixelRatio: this.pixelRatio +function reduce(x) { + var r = 0 + for(var i=0; i 0) { - for (var k = 0; k < 24; ++k) { - buffer.push(buffer[buffer.length - 12]) - } - vertexCount += 2 - hadGap = true - } + "hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}], - continue fill_loop - } - bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]) - bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]) - } + "hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}], - var acolor, bcolor - if (Array.isArray(colors[0])) { - acolor = colors[i - 1] - bcolor = colors[i] - } else { - acolor = bcolor = colors - } - if (acolor.length === 3) { - acolor = [acolor[0], acolor[1], acolor[2], 1] - } - if (bcolor.length === 3) { - bcolor = [bcolor[0], bcolor[1], bcolor[2], 1] - } + "cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}], - var w0 - if (Array.isArray(lineWidth)) { - w0 = lineWidth[i - 1] - } else { - w0 = lineWidth - } + "spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}], - var t0 = arcLength - arcLength += distance(a, b) + "summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}], - if (hadGap) { - for (j = 0; j < 2; ++j) { - buffer.push( - a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3]) - } - vertexCount += 2 - hadGap = false - } + "autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}], - buffer.push( - a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3], - a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3], - b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3], - b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3]) + "winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}], - vertexCount += 4 - } - this.buffer.update(buffer) + "bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}], - arcLengthArray.push(arcLength) - pointArray.push(positions[positions.length - 1].slice()) + "copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}], - this.bounds = bounds + "greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}], - this.vertexCount = vertexCount + "yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}], - this.points = pointArray - this.arcLength = arcLengthArray + "greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}], - if ('dashes' in options) { - var dashArray = options.dashes + "yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}], - // Calculate prefix sum - var prefixSum = dashArray.slice() - prefixSum.unshift(0) - for (i = 1; i < prefixSum.length; ++i) { - prefixSum[i] = prefixSum[i - 1] + prefixSum[i] - } + "bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}], - var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]) - for (i = 0; i < 256; ++i) { - for (j = 0; j < 4; ++j) { - dashTexture.set(i, 0, j, 0) - } - if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { - dashTexture.set(i, 0, 0, 0) - } else { - dashTexture.set(i, 0, 0, 255) - } - } + "rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}], - this.texture.setPixels(dashTexture) - } -} + "picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}], -proto.dispose = function () { - this.shader.dispose() - this.vao.dispose() - this.buffer.dispose() -} + "rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}], -proto.pick = function (selection) { - if (!selection) { - return null - } - if (selection.id !== this.pickId) { - return null - } - var tau = unpackFloat( - selection.value[0], - selection.value[1], - selection.value[2], - 0) - var index = bsearch.le(this.arcLength, tau) - if (index < 0) { - return null - } - if (index === this.arcLength.length - 1) { - return new PickResult( - this.arcLength[this.arcLength.length - 1], - this.points[this.points.length - 1].slice(), - index) - } - var a = this.points[index] - var b = this.points[Math.min(index + 1, this.points.length - 1)] - var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]) - var ti = 1.0 - t - var x = [0, 0, 0] - for (var i = 0; i < 3; ++i) { - x[i] = ti * a[i] + t * b[i] - } - var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1) - return new PickResult( - tau, - x, - dataIndex, - this.points[dataIndex]) -} + "portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}], -function createLinePlot (options) { - var gl = options.gl || (options.scene && options.scene.gl) + "blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}], - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.nextPosition.location = 1 - shader.attributes.arcLength.location = 2 - shader.attributes.lineWidth.location = 3 - shader.attributes.color.location = 4 + "earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}], - var pickShader = createPickShader(gl) - pickShader.attributes.position.location = 0 - pickShader.attributes.nextPosition.location = 1 - pickShader.attributes.arcLength.location = 2 - pickShader.attributes.lineWidth.location = 3 - pickShader.attributes.color.location = 4 + "electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - 'buffer': buffer, - 'size': 3, - 'offset': 0, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 3, - 'offset': 12, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 1, - 'offset': 24, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 1, - 'offset': 28, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 4, - 'offset': 32, - 'stride': 48 - } - ]) + "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}], - // Create texture for dash pattern - var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) - for (var i = 0; i < 256 * 4; ++i) { - defaultTexture.data[i] = 255 - } - var texture = createTexture(gl, defaultTexture) - texture.wrap = gl.REPEAT + "viridis": [{"index":0,"rgb":[68,1,84]},{"index":0.13,"rgb":[71,44,122]},{"index":0.25,"rgb":[59,81,139]},{"index":0.38,"rgb":[44,113,142]},{"index":0.5,"rgb":[33,144,141]},{"index":0.63,"rgb":[39,173,129]},{"index":0.75,"rgb":[92,200,99]},{"index":0.88,"rgb":[170,220,50]},{"index":1,"rgb":[253,231,37]}], - var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) - linePlot.update(options) - return linePlot -} + "inferno": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[31,12,72]},{"index":0.25,"rgb":[85,15,109]},{"index":0.38,"rgb":[136,34,106]},{"index":0.5,"rgb":[186,54,85]},{"index":0.63,"rgb":[227,89,51]},{"index":0.75,"rgb":[249,140,10]},{"index":0.88,"rgb":[249,201,50]},{"index":1,"rgb":[252,255,164]}], -},{"./lib/shaders":126,"binary-search-bounds":128,"gl-buffer":118,"gl-texture2d":222,"gl-vao":226,"glsl-read-float":129,"ndarray":253}],128:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],129:[function(require,module,exports){ -module.exports = decodeFloat + "magma": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[28,16,68]},{"index":0.25,"rgb":[79,18,123]},{"index":0.38,"rgb":[129,37,129]},{"index":0.5,"rgb":[181,54,122]},{"index":0.63,"rgb":[229,80,100]},{"index":0.75,"rgb":[251,135,97]},{"index":0.88,"rgb":[254,194,135]},{"index":1,"rgb":[252,253,191]}], -var UINT8_VIEW = new Uint8Array(4) -var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) + "plasma": [{"index":0,"rgb":[13,8,135]},{"index":0.13,"rgb":[75,3,161]},{"index":0.25,"rgb":[125,3,168]},{"index":0.38,"rgb":[168,34,150]},{"index":0.5,"rgb":[203,70,121]},{"index":0.63,"rgb":[229,107,93]},{"index":0.75,"rgb":[248,148,65]},{"index":0.88,"rgb":[253,195,40]},{"index":1,"rgb":[240,249,33]}], -function decodeFloat(x, y, z, w) { - UINT8_VIEW[0] = w - UINT8_VIEW[1] = z - UINT8_VIEW[2] = y - UINT8_VIEW[3] = x - return FLOAT_VIEW[0] -} + "warm": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[172,0,187]},{"index":0.25,"rgb":[219,0,170]},{"index":0.38,"rgb":[255,0,130]},{"index":0.5,"rgb":[255,63,74]},{"index":0.63,"rgb":[255,123,0]},{"index":0.75,"rgb":[234,176,0]},{"index":0.88,"rgb":[190,228,0]},{"index":1,"rgb":[147,255,0]}], -},{}],130:[function(require,module,exports){ -module.exports = invert + "cool": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[116,0,218]},{"index":0.25,"rgb":[98,74,237]},{"index":0.38,"rgb":[68,146,231]},{"index":0.5,"rgb":[0,204,197]},{"index":0.63,"rgb":[0,247,146]},{"index":0.75,"rgb":[0,255,88]},{"index":0.88,"rgb":[40,255,8]},{"index":1,"rgb":[147,255,0]}], -/** - * Inverts a mat3 - * - * @alias mat3.invert - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2] - var a10 = a[3], a11 = a[4], a12 = a[5] - var a20 = a[6], a21 = a[7], a22 = a[8] + "rainbow-soft": [{"index":0,"rgb":[125,0,179]},{"index":0.1,"rgb":[199,0,180]},{"index":0.2,"rgb":[255,0,121]},{"index":0.3,"rgb":[255,108,0]},{"index":0.4,"rgb":[222,194,0]},{"index":0.5,"rgb":[150,255,0]},{"index":0.6,"rgb":[0,255,55]},{"index":0.7,"rgb":[0,246,150]},{"index":0.8,"rgb":[50,167,222]},{"index":0.9,"rgb":[103,51,235]},{"index":1,"rgb":[124,0,186]}], - var b01 = a22 * a11 - a12 * a21 - var b11 = -a22 * a10 + a12 * a20 - var b21 = a21 * a10 - a11 * a20 + "bathymetry": [{"index":0,"rgb":[40,26,44]},{"index":0.13,"rgb":[59,49,90]},{"index":0.25,"rgb":[64,76,139]},{"index":0.38,"rgb":[63,110,151]},{"index":0.5,"rgb":[72,142,158]},{"index":0.63,"rgb":[85,174,163]},{"index":0.75,"rgb":[120,206,163]},{"index":0.88,"rgb":[187,230,172]},{"index":1,"rgb":[253,254,204]}], - // Calculate the determinant - var det = a00 * b01 + a01 * b11 + a02 * b21 + "cdom": [{"index":0,"rgb":[47,15,62]},{"index":0.13,"rgb":[87,23,86]},{"index":0.25,"rgb":[130,28,99]},{"index":0.38,"rgb":[171,41,96]},{"index":0.5,"rgb":[206,67,86]},{"index":0.63,"rgb":[230,106,84]},{"index":0.75,"rgb":[242,149,103]},{"index":0.88,"rgb":[249,193,135]},{"index":1,"rgb":[254,237,176]}], - if (!det) return null - det = 1.0 / det + "chlorophyll": [{"index":0,"rgb":[18,36,20]},{"index":0.13,"rgb":[25,63,41]},{"index":0.25,"rgb":[24,91,59]},{"index":0.38,"rgb":[13,119,72]},{"index":0.5,"rgb":[18,148,80]},{"index":0.63,"rgb":[80,173,89]},{"index":0.75,"rgb":[132,196,122]},{"index":0.88,"rgb":[175,221,162]},{"index":1,"rgb":[215,249,208]}], - out[0] = b01 * det - out[1] = (-a22 * a01 + a02 * a21) * det - out[2] = (a12 * a01 - a02 * a11) * det - out[3] = b11 * det - out[4] = (a22 * a00 - a02 * a20) * det - out[5] = (-a12 * a00 + a02 * a10) * det - out[6] = b21 * det - out[7] = (-a21 * a00 + a01 * a20) * det - out[8] = (a11 * a00 - a01 * a10) * det + "density": [{"index":0,"rgb":[54,14,36]},{"index":0.13,"rgb":[89,23,80]},{"index":0.25,"rgb":[110,45,132]},{"index":0.38,"rgb":[120,77,178]},{"index":0.5,"rgb":[120,113,213]},{"index":0.63,"rgb":[115,151,228]},{"index":0.75,"rgb":[134,185,227]},{"index":0.88,"rgb":[177,214,227]},{"index":1,"rgb":[230,241,241]}], - return out -} + "freesurface-blue": [{"index":0,"rgb":[30,4,110]},{"index":0.13,"rgb":[47,14,176]},{"index":0.25,"rgb":[41,45,236]},{"index":0.38,"rgb":[25,99,212]},{"index":0.5,"rgb":[68,131,200]},{"index":0.63,"rgb":[114,156,197]},{"index":0.75,"rgb":[157,181,203]},{"index":0.88,"rgb":[200,208,216]},{"index":1,"rgb":[241,237,236]}], -},{}],131:[function(require,module,exports){ -module.exports = clone; + "freesurface-red": [{"index":0,"rgb":[60,9,18]},{"index":0.13,"rgb":[100,17,27]},{"index":0.25,"rgb":[142,20,29]},{"index":0.38,"rgb":[177,43,27]},{"index":0.5,"rgb":[192,87,63]},{"index":0.63,"rgb":[205,125,105]},{"index":0.75,"rgb":[216,162,148]},{"index":0.88,"rgb":[227,199,193]},{"index":1,"rgb":[241,237,236]}], -/** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param {mat4} a matrix to clone - * @returns {mat4} a new 4x4 matrix - */ -function clone(a) { - var out = new Float32Array(16); - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -}; -},{}],132:[function(require,module,exports){ -module.exports = create; + "oxygen": [{"index":0,"rgb":[64,5,5]},{"index":0.13,"rgb":[106,6,15]},{"index":0.25,"rgb":[144,26,7]},{"index":0.38,"rgb":[168,64,3]},{"index":0.5,"rgb":[188,100,4]},{"index":0.63,"rgb":[206,136,11]},{"index":0.75,"rgb":[220,174,25]},{"index":0.88,"rgb":[231,215,44]},{"index":1,"rgb":[248,254,105]}], -/** - * Creates a new identity mat4 - * - * @returns {mat4} a new 4x4 matrix - */ -function create() { - var out = new Float32Array(16); - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -}; -},{}],133:[function(require,module,exports){ -module.exports = determinant; + "par": [{"index":0,"rgb":[51,20,24]},{"index":0.13,"rgb":[90,32,35]},{"index":0.25,"rgb":[129,44,34]},{"index":0.38,"rgb":[159,68,25]},{"index":0.5,"rgb":[182,99,19]},{"index":0.63,"rgb":[199,134,22]},{"index":0.75,"rgb":[212,171,35]},{"index":0.88,"rgb":[221,210,54]},{"index":1,"rgb":[225,253,75]}], -/** - * Calculates the determinant of a mat4 - * - * @param {mat4} a the source matrix - * @returns {Number} determinant of a - */ -function determinant(a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + "phase": [{"index":0,"rgb":[145,105,18]},{"index":0.13,"rgb":[184,71,38]},{"index":0.25,"rgb":[186,58,115]},{"index":0.38,"rgb":[160,71,185]},{"index":0.5,"rgb":[110,97,218]},{"index":0.63,"rgb":[50,123,164]},{"index":0.75,"rgb":[31,131,110]},{"index":0.88,"rgb":[77,129,34]},{"index":1,"rgb":[145,105,18]}], - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32; + "salinity": [{"index":0,"rgb":[42,24,108]},{"index":0.13,"rgb":[33,50,162]},{"index":0.25,"rgb":[15,90,145]},{"index":0.38,"rgb":[40,118,137]},{"index":0.5,"rgb":[59,146,135]},{"index":0.63,"rgb":[79,175,126]},{"index":0.75,"rgb":[120,203,104]},{"index":0.88,"rgb":[193,221,100]},{"index":1,"rgb":[253,239,154]}], - // Calculate the determinant - return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + "temperature": [{"index":0,"rgb":[4,35,51]},{"index":0.13,"rgb":[23,51,122]},{"index":0.25,"rgb":[85,59,157]},{"index":0.38,"rgb":[129,79,143]},{"index":0.5,"rgb":[175,95,130]},{"index":0.63,"rgb":[222,112,101]},{"index":0.75,"rgb":[249,146,66]},{"index":0.88,"rgb":[249,196,65]},{"index":1,"rgb":[232,250,91]}], + + "turbidity": [{"index":0,"rgb":[34,31,27]},{"index":0.13,"rgb":[65,50,41]},{"index":0.25,"rgb":[98,69,52]},{"index":0.38,"rgb":[131,89,57]},{"index":0.5,"rgb":[161,112,59]},{"index":0.63,"rgb":[185,140,66]},{"index":0.75,"rgb":[202,174,88]},{"index":0.88,"rgb":[216,209,126]},{"index":1,"rgb":[233,246,171]}], + + "velocity-blue": [{"index":0,"rgb":[17,32,64]},{"index":0.13,"rgb":[35,52,116]},{"index":0.25,"rgb":[29,81,156]},{"index":0.38,"rgb":[31,113,162]},{"index":0.5,"rgb":[50,144,169]},{"index":0.63,"rgb":[87,173,176]},{"index":0.75,"rgb":[149,196,189]},{"index":0.88,"rgb":[203,221,211]},{"index":1,"rgb":[254,251,230]}], + + "velocity-green": [{"index":0,"rgb":[23,35,19]},{"index":0.13,"rgb":[24,64,38]},{"index":0.25,"rgb":[11,95,45]},{"index":0.38,"rgb":[39,123,35]},{"index":0.5,"rgb":[95,146,12]},{"index":0.63,"rgb":[152,165,18]},{"index":0.75,"rgb":[201,186,69]},{"index":0.88,"rgb":[233,216,137]},{"index":1,"rgb":[255,253,205]}], + + "cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}] }; -},{}],134:[function(require,module,exports){ -module.exports = fromQuat; -/** - * Creates a matrix from a quaternion rotation. - * - * @param {mat4} out mat4 receiving operation result - * @param {quat4} q Rotation quaternion - * @returns {mat4} out +},{}],263:[function(require,module,exports){ +/* + * Ben Postlethwaite + * January 2013 + * License MIT */ -function fromQuat(out, q) { - var x = q[0], y = q[1], z = q[2], w = q[3], - x2 = x + x, - y2 = y + y, - z2 = z + z, +'use strict'; - xx = x * x2, - yx = y * x2, - yy = y * y2, - zx = z * x2, - zy = z * y2, - zz = z * z2, - wx = w * x2, - wy = w * y2, - wz = w * z2; +var at = require('arraytools'); +var clone = require('clone'); +var colorScale = require('./colorScales'); - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; +module.exports = createColormap; - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; +function createColormap (spec) { + /* + * Default Options + */ + var indicies, rgba, fromrgba, torgba, + nsteps, cmap, colormap, format, + nshades, colors, alpha, index, i, + r = [], + g = [], + b = [], + a = []; - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; + if ( !at.isPlainObject(spec) ) spec = {}; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; + nshades = spec.nshades || 72; + format = spec.format || 'hex'; - return out; -}; -},{}],135:[function(require,module,exports){ -module.exports = fromRotationTranslation; + colormap = spec.colormap; + if (!colormap) colormap = 'jet'; -/** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat4} q Rotation quaternion - * @param {vec3} v Translation vector - * @returns {mat4} out - */ -function fromRotationTranslation(out, q, v) { - // Quaternion math - var x = q[0], y = q[1], z = q[2], w = q[3], - x2 = x + x, - y2 = y + y, - z2 = z + z, + if (typeof colormap === 'string') { + colormap = colormap.toLowerCase(); - xx = x * x2, - xy = x * y2, - xz = x * z2, - yy = y * y2, - yz = y * z2, - zz = z * z2, - wx = w * x2, - wy = w * y2, - wz = w * z2; + if (!colorScale[colormap]) { + throw Error(colormap + ' not a supported colorscale'); + } - out[0] = 1 - (yy + zz); - out[1] = xy + wz; - out[2] = xz - wy; - out[3] = 0; - out[4] = xy - wz; - out[5] = 1 - (xx + zz); - out[6] = yz + wx; - out[7] = 0; - out[8] = xz + wy; - out[9] = yz - wx; - out[10] = 1 - (xx + yy); - out[11] = 0; - out[12] = v[0]; - out[13] = v[1]; - out[14] = v[2]; - out[15] = 1; - - return out; -}; -},{}],136:[function(require,module,exports){ -module.exports = identity; + cmap = clone(colorScale[colormap]); -/** - * Set a mat4 to the identity matrix - * - * @param {mat4} out the receiving matrix - * @returns {mat4} out - */ -function identity(out) { - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -}; -},{}],137:[function(require,module,exports){ -module.exports = invert; + } else if (Array.isArray(colormap)) { + cmap = clone(colormap); -/** - * Inverts a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + } else { + throw Error('unsupported colormap option', colormap); + } - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32, + if (cmap.length > nshades) { + throw new Error( + colormap+' map requires nshades to be at least size '+cmap.length + ); + } - // Calculate the determinant - det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + if (!Array.isArray(spec.alpha)) { - if (!det) { - return null; + if (typeof spec.alpha === 'number') { + alpha = [spec.alpha, spec.alpha]; + + } else { + alpha = [1, 1]; + } + + } else if (spec.alpha.length !== 2) { + alpha = [1, 1]; + + } else { + alpha = clone(spec.alpha); } - det = 1.0 / det; - out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + /* + * map index points from 0->1 to 0 -> n-1 + */ + indicies = cmap.map(function(c) { + return Math.round(c.index * nshades); + }); - return out; + /* + * Add alpha channel to the map + */ + if (alpha[0] < 0) alpha[0] = 0; + if (alpha[1] < 0) alpha[0] = 0; + if (alpha[0] > 1) alpha[0] = 1; + if (alpha[1] > 1) alpha[0] = 1; + + for (i = 0; i < indicies.length; ++i) { + index = cmap[i].index; + rgba = cmap[i].rgb; + + // if user supplies their own map use it + if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue; + rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index; + } + + /* + * map increasing linear values between indicies to + * linear steps in colorvalues + */ + for (i = 0; i < indicies.length-1; ++i) { + nsteps = indicies[i+1] - indicies[i]; + fromrgba = cmap[i].rgb; + torgba = cmap[i+1].rgb; + r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) ); + g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) ); + b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) ); + a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) ); + } + + r = r.map( Math.round ); + g = g.map( Math.round ); + b = b.map( Math.round ); + + colors = at.zip(r, g, b, a); + + if (format === 'hex') colors = colors.map( rgb2hex ); + if (format === 'rgbaString') colors = colors.map( rgbaStr ); + + return colors; }; -},{}],138:[function(require,module,exports){ -var identity = require('./identity'); -module.exports = lookAt; + +function rgb2hex (rgba) { + var dig, hex = '#'; + for (var i = 0; i < 3; ++i) { + dig = rgba[i]; + dig = dig.toString(16); + hex += ('00' + dig).substr( dig.length ); + } + return hex; +} + +function rgbaStr (rgba) { + return 'rgba(' + rgba.join(',') + ')'; +} + +},{"./colorScales":262,"arraytools":64,"clone":264}],264:[function(require,module,exports){ +(function (Buffer){ +var clone = (function() { +'use strict'; /** - * Generates a look-at matrix with the given eye position, focal point, and up axis + * Clones (copies) an Object using deep copying. * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {vec3} eye Position of the viewer - * @param {vec3} center Point the viewer is looking at - * @param {vec3} up vec3 pointing up - * @returns {mat4} out - */ -function lookAt(out, eye, center, up) { - var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, - eyex = eye[0], - eyey = eye[1], - eyez = eye[2], - upx = up[0], - upy = up[1], - upz = up[2], - centerx = center[0], - centery = center[1], - centerz = center[2]; + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). +*/ +function clone(parent, circular, depth, prototype) { + var filter; + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + filter = circular.filter; + circular = circular.circular + } + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; - if (Math.abs(eyex - centerx) < 0.000001 && - Math.abs(eyey - centery) < 0.000001 && - Math.abs(eyez - centerz) < 0.000001) { - return identity(out); - } + var useBuffer = typeof Buffer != 'undefined'; - z0 = eyex - centerx; - z1 = eyey - centery; - z2 = eyez - centerz; + if (typeof circular == 'undefined') + circular = true; - len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); - z0 *= len; - z1 *= len; - z2 *= len; + if (typeof depth == 'undefined') + depth = Infinity; - x0 = upy * z2 - upz * z1; - x1 = upz * z0 - upx * z2; - x2 = upx * z1 - upy * z0; - len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); - if (!len) { - x0 = 0; - x1 = 0; - x2 = 0; + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth == 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; + } + + if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + child = new Buffer(parent.length); + parent.copy(child); + return child; } else { - len = 1 / len; - x0 *= len; - x1 *= len; - x2 *= len; + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } } - y0 = z1 * x2 - z2 * x1; - y1 = z2 * x0 - z0 * x2; - y2 = z0 * x1 - z1 * x0; + if (circular) { + var index = allParents.indexOf(parent); - len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); - if (!len) { - y0 = 0; - y1 = 0; - y2 = 0; - } else { - len = 1 / len; - y0 *= len; - y1 *= len; - y2 *= len; + if (index != -1) { + return allChildren[index]; + } + allParents.push(parent); + allChildren.push(child); } - out[0] = x0; - out[1] = y0; - out[2] = z0; - out[3] = 0; - out[4] = x1; - out[5] = y1; - out[6] = z1; - out[7] = 0; - out[8] = x2; - out[9] = y2; - out[10] = z2; - out[11] = 0; - out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); - out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); - out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); - out[15] = 1; + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); + } - return out; -}; -},{"./identity":136}],139:[function(require,module,exports){ -module.exports = multiply; + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + return child; + } + + return _clone(parent, depth); +} /** - * Multiplies two mat4's + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. */ -function multiply(out, a, b) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; +clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); +}; + +// private utility functions + +function __objToStr(o) { + return Object.prototype.toString.call(o); +}; +clone.__objToStr = __objToStr; + +function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; +}; +clone.__isDate = __isDate; + +function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; +}; +clone.__isArray = __isArray; + +function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; +}; +clone.__isRegExp = __isRegExp; + +function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; +}; +clone.__getRegExpFlags = __getRegExpFlags; - // Cache only the current line of the second matrix - var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; +return clone; +})(); - b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; - out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; +if (typeof module === 'object' && module.exports) { + module.exports = clone; +} - b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; - out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; +}).call(this,require("buffer").Buffer) +},{"buffer":65}],265:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":306}],266:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":267,"./lib/create-attributes":268,"./lib/create-uniforms":269,"./lib/reflect":270,"./lib/runtime-reflect":271,"./lib/shader-cache":272,"dup":94}],267:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],268:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":267,"dup":96}],269:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":267,"./reflect":270,"dup":97}],270:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],271:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],272:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":267,"dup":100,"gl-format-compiler-error":273,"weakmap-shim":291}],273:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":274,"dup":101,"gl-constants/lookup":278,"glsl-shader-name":279,"sprintf-js":288}],274:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":275}],275:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":276}],276:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],277:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],278:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":277,"dup":106}],279:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":280,"dup":107,"glsl-tokenizer":287}],280:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],281:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":283,"./lib/builtins-300es":282,"./lib/literals":285,"./lib/literals-300es":284,"./lib/operators":286,"dup":109}],282:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":283,"dup":110}],283:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],284:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":285,"dup":112}],285:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],286:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],287:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":281,"dup":115}],288:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],289:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":290,"dup":117}],290:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],291:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":289,"dup":119}],292:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":306}],293:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],294:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":293,"dup":155}],295:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":293,"dup":156}],296:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":294,"./lib/vao-native.js":295,"dup":157}],297:[function(require,module,exports){ +var DEFAULT_NORMALS_EPSILON = 1e-6; +var DEFAULT_FACE_EPSILON = 1e-6; - b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; - out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - return out; -}; -},{}],140:[function(require,module,exports){ -module.exports = perspective; +//Estimate the vertex normals of a mesh +exports.vertexNormals = function(faces, positions, specifiedEpsilon) { -/** - * Generates a perspective projection matrix with the given bounds - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {number} fovy Vertical field of view in radians - * @param {number} aspect Aspect ratio. typically viewport width/height - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ -function perspective(out, fovy, aspect, near, far) { - var f = 1.0 / Math.tan(fovy / 2), - nf = 1 / (near - far); - out[0] = f / aspect; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = f; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = (far + near) * nf; - out[11] = -1; - out[12] = 0; - out[13] = 0; - out[14] = (2 * far * near) * nf; - out[15] = 0; - return out; -}; -},{}],141:[function(require,module,exports){ -module.exports = rotate; + var N = positions.length; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon; -/** - * Rotates a mat4 by the given angle - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ -function rotate(out, a, rad, axis) { - var x = axis[0], y = axis[1], z = axis[2], - len = Math.sqrt(x * x + y * y + z * z), - s, c, t, - a00, a01, a02, a03, - a10, a11, a12, a13, - a20, a21, a22, a23, - b00, b01, b02, - b10, b11, b12, - b20, b21, b22; + //Initialize normal array + for(var i=0; i epsilon) { + var norm = normals[c]; + var w = 1.0 / Math.sqrt(m01 * m21); + for(var k=0; k<3; ++k) { + var u = (k+1)%3; + var v = (k+2)%3; + norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); + } + } + } + } - if (a !== out) { // If the source and destination differ, copy the unchanged last row - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + //Scale all normals to unit length + for(var i=0; i epsilon) { + var w = 1.0 / Math.sqrt(m); + for(var k=0; k<3; ++k) { + norm[k] *= w; + } + } else { + for(var k=0; k<3; ++k) { + norm[k] = 0.0; + } + } + } -/** - * Rotates a matrix by the given angle around the X axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateX(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a10 = a[4], - a11 = a[5], - a12 = a[6], - a13 = a[7], - a20 = a[8], - a21 = a[9], - a22 = a[10], - a23 = a[11]; + //Return the resulting set of patches + return normals; +} - if (a !== out) { // If the source and destination differ, copy the unchanged rows - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - } +//Compute face normals of a mesh +exports.faceNormals = function(faces, positions, specifiedEpsilon) { - // Perform axis-specific matrix multiplication - out[4] = a10 * c + a20 * s; - out[5] = a11 * c + a21 * s; - out[6] = a12 * c + a22 * s; - out[7] = a13 * c + a23 * s; - out[8] = a20 * c - a10 * s; - out[9] = a21 * c - a11 * s; - out[10] = a22 * c - a12 * s; - out[11] = a23 * c - a13 * s; - return out; -}; -},{}],143:[function(require,module,exports){ -module.exports = rotateY; + var N = faces.length; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon; -/** - * Rotates a matrix by the given angle around the Y axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateY(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a[0], - a01 = a[1], - a02 = a[2], - a03 = a[3], - a20 = a[8], - a21 = a[9], - a22 = a[10], - a23 = a[11]; + for(var i=0; i epsilon) { + l = 1.0 / Math.sqrt(l); + } else { + l = 0.0; + } + for(var j=0; j<3; ++j) { + n[j] *= l; + } + normals[i] = n; + } + return normals; +} -/** - * Rotates a matrix by the given angle around the Z axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateZ(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a[0], - a01 = a[1], - a02 = a[2], - a03 = a[3], - a10 = a[4], - a11 = a[5], - a12 = a[6], - a13 = a[7]; - if (a !== out) { // If the source and destination differ, copy the unchanged last row - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + +},{}],298:[function(require,module,exports){ +//Optimized version for triangle closest point +// Based on Eberly's WildMagick codes +// http://www.geometrictools.com/LibMathematics/Distance/Distance.html +"use strict"; + +var diff = new Float64Array(4); +var edge0 = new Float64Array(4); +var edge1 = new Float64Array(4); + +function closestPoint2d(V0, V1, V2, point, result) { + //Reallocate buffers if necessary + if(diff.length < point.length) { + diff = new Float64Array(point.length); + edge0 = new Float64Array(point.length); + edge1 = new Float64Array(point.length); + } + //Compute edges + for(var i=0; i= a00) { + s = 1.0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } else { + s = 0; + if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else if (-b1 >= a11) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else { // region 3 + s = 0; + if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else if (-b1 >= a11) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else if (t < 0) { // region 5 + t = 0; + if (b0 >= 0) { + s = 0; + sqrDistance = c; + } else if (-b0 >= a00) { + s = 1; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } else { // region 0 + // minimum at interior point + var invDet = 1.0 / det; + s *= invDet; + t *= invDet; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + var tmp0, tmp1, numer, denom; + + if (s < 0) { // region 2 + tmp0 = a01 + b0; + tmp1 = a11 + b1; + if (tmp1 > tmp0) { + numer = tmp1 - tmp0; + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + s = 1; + t = 0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = numer/denom; + t = 1 - s; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + s = 0; + if (tmp1 <= 0) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else if (t < 0) { // region 6 + tmp0 = a01 + b1; + tmp1 = a00 + b0; + if (tmp1 > tmp0) { + numer = tmp1 - tmp0; + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + t = 1; + s = 0; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = numer/denom; + s = 1 - t; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + t = 0; + if (tmp1 <= 0) { + s = 1; + sqrDistance = a00 + 2.0*b0 + c; + } else if (b0 >= 0) { + s = 0; + sqrDistance = c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } + } else { // region 1 + numer = a11 + b1 - a01 - b0; + if (numer <= 0) { + s = 0; + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + s = 1; + t = 0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = numer/denom; + t = 1 - s; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } } + } + var u = 1.0 - s - t; + for(var i=0; i 1.0001) { - return null + //Count number of cells + var numCells = cells.length + if(numCells === 0 || d < 1) { + return { + cells: [], + vertexIds: [], + vertexWeights: [] } - s += weights[i] - } - if(Math.abs(s - 1.0) > 0.001) { - return null } - return [closestIndex, interpolate(simplex, weights), weights] -} -},{"barycentric":151,"polytope-closest-point/lib/closest_point_2d.js":153}],149:[function(require,module,exports){ - -var triVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}" -var triFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}" -var edgeVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}" -var edgeFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" -var pointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}" -var pointFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" -var pickVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}" -var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}" -var pickPointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}" -var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}" -var contourFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n" + //Read in vertex signs + var vertexSigns = getSigns(values, +level) -exports.meshShader = { - vertex: triVertSrc, - fragment: triFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'normal', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'} - ] -} -exports.wireShader = { - vertex: edgeVertSrc, - fragment: edgeFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'} - ] -} -exports.pointShader = { - vertex: pointVertSrc, - fragment: pointFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'}, - {name: 'pointSize', type: 'float'} - ] -} -exports.pickShader = { - vertex: pickVertSrc, - fragment: pickFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'id', type: 'vec4'} - ] -} -exports.pointPickShader = { - vertex: pickPointVertSrc, - fragment: pickFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'pointSize', type: 'float'}, - {name: 'id', type: 'vec4'} - ] -} -exports.contourShader = { - vertex: contourVertSrc, - fragment: contourFragSrc, - attributes: [ - {name: 'position', type: 'vec3'} - ] -} + //First get 1-skeleton, find all crossings + var edges = getEdges(cells, d) + var weights = getCrossingWeights(edges, values, vertexSigns, +level) -},{}],150:[function(require,module,exports){ -'use strict' + //Build vertex cascade to speed up binary search + var vcascade = getCascade(edges, values.length|0) -var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small -var DEFAULT_FACE_NORMALS_EPSILON = 1e-6; + //Then construct cells + var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns) -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createTexture = require('gl-texture2d') -var normals = require('normals') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var ndarray = require('ndarray') -var colormap = require('colormap') -var getContour = require('simplicial-complex-contour') -var pool = require('typedarray-pool') -var shaders = require('./lib/shaders') -var closestPoint = require('./lib/closest-point') + //Unpack data into pretty format + var uedges = unpackEdges(edges) + var uweights = [].slice.call(weights.data, 0, weights.shape[0]) -var meshShader = shaders.meshShader -var wireShader = shaders.wireShader -var pointShader = shaders.pointShader -var pickShader = shaders.pickShader -var pointPickShader = shaders.pointPickShader -var contourShader = shaders.contourShader + //Release data + pool.free(vertexSigns) + pool.free(edges.data) + pool.free(weights.data) + pool.free(vcascade) + + return { + cells: faces, + vertexIds: uedges, + vertexWeights: uweights + } +} +},{"./lib/codegen":300,"ndarray":1031,"ndarray-sort":303,"typedarray-pool":306}],300:[function(require,module,exports){ +'use strict' -var identityMatrix = [ - 1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] +module.exports = getPolygonizer -function SimplicialMesh(gl - , texture - , triShader - , lineShader - , pointShader - , pickShader - , pointPickShader - , contourShader - , trianglePositions - , triangleIds - , triangleColors - , triangleUVs - , triangleNormals - , triangleVAO - , edgePositions - , edgeIds - , edgeColors - , edgeUVs - , edgeVAO - , pointPositions - , pointIds - , pointColors - , pointUVs - , pointSizes - , pointVAO - , contourPositions - , contourVAO) { +var pool = require('typedarray-pool') +var createMSTable = require('marching-simplex-table') - this.gl = gl - this.cells = [] - this.positions = [] - this.intensity = [] - this.texture = texture - this.dirty = true +var CACHE = {} - this.triShader = triShader - this.lineShader = lineShader - this.pointShader = pointShader - this.pickShader = pickShader - this.pointPickShader = pointPickShader - this.contourShader = contourShader +function createCellPolygonizer(d) { + var maxCellSize = 0 + var tables = new Array(d+1) + tables[0] = [ [] ] + for(var i=1; i<=d; ++i) { + var tab = tables[i] = createMSTable(i) + for(var j=0; j>1,v=E[2*m+1];', + 'if(v===b){return m}', + 'if(b 0) { + code.push(',') + } + code.push('[') + for(var j=0; j 0) { + code.push(',') + } + code.push('B(C,E,c[', f[0], '],c[', f[1], '])') + } + code.push(']') + } + code.push(');') + } - this.pointPositions = pointPositions - this.pointColors = pointColors - this.pointUVs = pointUVs - this.pointSizes = pointSizes - this.pointIds = pointIds - this.pointVAO = pointVAO - this.pointCount = 0 + for(var i=d+1; i>1; --i) { + if(i < d+1) { + code.push('else ') + } + code.push('if(l===', i, '){') - this.contourLineWidth = 1 - this.contourPositions = contourPositions - this.contourVAO = contourVAO - this.contourCount = 0 - this.contourColor = [0,0,0] - this.contourEnable = true + //Generate mask + var maskStr = [] + for(var j=0; j= 1 -} +var chull = require('convex-hull') -proto.isTransparent = function() { - return this.opacity < 1 +function constructVertex(d, a, b) { + var x = new Array(d) + for(var i=0; i 1) { + var scratch_shape = [] + for(var i=1; i 1) { + + //Copy data into scratch + code.push("dptr=0;sptr=ptr") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"left){", + "dptr=0", + "sptr=cptr-s0") + for(var i=1; ib){break __l}"].join("")) + for(var i=order.length-1; i>=1; --i) { + code.push( + "sptr+=e"+i, + "dptr+=f"+i, + "}") + } + + //Copy data back + code.push("dptr=cptr;sptr=cptr-s0") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"left)&&("+dataRead("cptr-s0")+">scratch)){", + dataWrite("cptr", dataRead("cptr-s0")), + "cptr-=s0", + "}", + dataWrite("cptr", "scratch")) + } + + //Close outer loop body + code.push("}") + if(order.length > 1 && allocator) { + code.push("free(scratch)") + } + code.push("} return " + funcName) + + //Compile and link function + if(allocator) { + var result = new Function("malloc", "free", code.join("\n")) + return result(allocator[0], allocator[1]) + } else { + var result = new Function(code.join("\n")) + return result() } - return result } -proto.highlight = function(selection) { - if(!selection || !this.contourEnable) { - this.contourCount = 0 - return +function createQuickSort(order, dtype, insertionSort) { + var code = [ "'use strict'" ] + var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("") + var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length)) + var allocator = getMallocFree(dtype) + var labelCounter=0 + + code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) + + var vars = [ + "sixth=((right-left+1)/6)|0", + "index1=left+sixth", + "index5=right-sixth", + "index3=(left+right)>>1", + "index2=index3-sixth", + "index4=index3+sixth", + "el1=index1", + "el2=index2", + "el3=index3", + "el4=index4", + "el5=index5", + "less=left+1", + "great=right-1", + "pivots_are_equal=true", + "tmp", + "tmp0", + "x", + "y", + "z", + "k", + "ptr0", + "ptr1", + "ptr2", + "comp_pivot1=0", + "comp_pivot2=0", + "comp=0" + ] + + if(order.length > 1) { + var ele_size = [] + for(var i=1; i=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j," 1) { + for(var i=0; i1) { + code.push("ptr_shift+=d"+j) + } else { + code.push("ptr0+=d"+j) } + code.push("}") } } - this.contourCount = (ptr / 3)|0 - this.contourPositions.update(result.subarray(0, ptr)) - pool.free(result) -} - -proto.update = function(params) { - params = params || {} - var gl = this.gl - - this.dirty = true - - if('contourEnable' in params) { - this.contourEnable = params.contourEnable + + function lexicoLoop(label, ptrs, usePivot, body) { + if(ptrs.length === 1) { + code.push("ptr0="+toPointer(ptrs[0])) + } else { + for(var i=0; i 1) { + for(var i=0; i=1; --i) { + if(usePivot) { + code.push("pivot_ptr+=f"+i) + } + if(ptrs.length > 1) { + code.push("ptr_shift+=e"+i) + } else { + code.push("ptr0+=e"+i) + } + code.push("}") + } } - if('contourColor' in params) { - this.contourColor = params.contourColor + + function cleanUp() { + if(order.length > 1 && allocator) { + code.push("free(pivot1)", "free(pivot2)") + } } - if('lineWidth' in params) { - this.lineWidth = params.lineWidth + + function compareSwap(a_id, b_id) { + var a = "el"+a_id + var b = "el"+b_id + if(order.length > 1) { + var lbl = "__l" + (++labelCounter) + lexicoLoop(lbl, [a, b], false, [ + "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n", + "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n", + "if(comp<0){break ", lbl, "}" + ].join("")) + } else { + code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join("")) + } } - if('lightPosition' in params) { - this.lightPosition = params.lightPosition + + compareSwap(1, 2) + compareSwap(4, 5) + compareSwap(1, 3) + compareSwap(2, 3) + compareSwap(1, 4) + compareSwap(3, 4) + compareSwap(2, 5) + compareSwap(2, 3) + compareSwap(4, 5) + + if(order.length > 1) { + cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [ + "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n", + "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n", + "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n", + "x=",dataRead("ptr0"),"\n", + "y=",dataRead("ptr2"),"\n", + "z=",dataRead("ptr4"),"\n", + dataWrite("ptr5", "x"),"\n", + dataWrite("ptr6", "y"),"\n", + dataWrite("ptr7", "z") + ].join("")) + } else { + code.push([ + "pivot1=", dataRead(toPointer("el2")), "\n", + "pivot2=", dataRead(toPointer("el4")), "\n", + "pivots_are_equal=pivot1===pivot2\n", + "x=", dataRead(toPointer("el1")), "\n", + "y=", dataRead(toPointer("el3")), "\n", + "z=", dataRead(toPointer("el5")), "\n", + dataWrite(toPointer("index1"), "x"), "\n", + dataWrite(toPointer("index3"), "y"), "\n", + dataWrite(toPointer("index5"), "z") + ].join("")) } - if('opacity' in params) { - this.opacity = params.opacity + + + function moveElement(dst, src) { + if(order.length > 1) { + cacheLoop([dst, src], false, + dataWrite("ptr0", dataRead("ptr1")) + ) + } else { + code.push(dataWrite(toPointer(dst), dataRead(toPointer(src)))) + } } - if('ambient' in params) { - this.ambientLight = params.ambient + + moveElement("index2", "left") + moveElement("index4", "right") + + function comparePivot(result, ptr, n) { + if(order.length > 1) { + var lbl = "__l" + (++labelCounter) + lexicoLoop(lbl, [ptr], true, [ + result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n", + "if(",result,"!==0){break ", lbl, "}" + ].join("")) + } else { + code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join("")) + } } - if('diffuse' in params) { - this.diffuseLight = params.diffuse + + function swapElements(a, b) { + if(order.length > 1) { + cacheLoop([a,b],false,[ + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", "tmp") + ].join("")) + } else { + code.push([ + "ptr0=",toPointer(a),"\n", + "ptr1=",toPointer(b),"\n", + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", "tmp") + ].join("")) + } } - if('specular' in params) { - this.specularLight = params.specular + + function tripleSwap(k, less, great) { + if(order.length > 1) { + cacheLoop([k,less,great], false, [ + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", dataRead("ptr2")),"\n", + dataWrite("ptr2", "tmp") + ].join("")) + code.push("++"+less, "--"+great) + } else { + code.push([ + "ptr0=",toPointer(k),"\n", + "ptr1=",toPointer(less),"\n", + "ptr2=",toPointer(great),"\n", + "++",less,"\n", + "--",great,"\n", + "tmp=", dataRead("ptr0"), "\n", + dataWrite("ptr0", dataRead("ptr1")), "\n", + dataWrite("ptr1", dataRead("ptr2")), "\n", + dataWrite("ptr2", "tmp") + ].join("")) + } } - if('roughness' in params) { - this.roughness = params.roughness + + function swapAndDecrement(k, great) { + swapElements(k, great) + code.push("--"+great) } - if('fresnel' in params) { - this.fresnel = params.fresnel + + code.push("if(pivots_are_equal){") + //Pivots are equal case + code.push("for(k=less;k<=great;++k){") + comparePivot("comp", "k", 1) + code.push("if(comp===0){continue}") + code.push("if(comp<0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + code.push("while(true){") + comparePivot("comp", "great", 1) + code.push("if(comp>0){") + code.push("great--") + code.push("}else if(comp<0){") + tripleSwap("k", "less", "great") + code.push("break") + code.push("}else{") + swapAndDecrement("k", "great") + code.push("break") + code.push("}") + code.push("}") + code.push("}") + code.push("}") + code.push("}else{") + //Pivots not equal case + code.push("for(k=less;k<=great;++k){") + comparePivot("comp_pivot1", "k", 1) + code.push("if(comp_pivot1<0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + comparePivot("comp_pivot2", "k", 2) + code.push("if(comp_pivot2>0){") + code.push("while(true){") + comparePivot("comp", "great", 2) + code.push("if(comp>0){") + code.push("if(--great1) { + cacheLoop([mem_dest, pivot_dest], true, [ + dataWrite("ptr0", dataRead("ptr1")), "\n", + dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join("")) + ].join("")) + } else { + code.push( + dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))), + dataWrite(toPointer(pivot_dest), "pivot"+pivot)) + } } + + storePivot("left", "(less-1)", 1) + storePivot("right", "(great+1)", 2) - if(params.texture) { - this.texture.dispose() - this.texture = createTexture(gl, params.texture) - } else if (params.colormap) { - this.texture.shape = [256,256] - this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR - this.texture.magFilter = gl.LINEAR - this.texture.setPixels(genColormap(params.colormap)) - this.texture.generateMipmap() + //Recursive sort call + function doSort(left, right) { + code.push([ + "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n", + "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", + "}else{\n", + funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", + "}" + ].join("")) } - - var cells = params.cells - var positions = params.positions - - if(!positions || !cells) { - return + doSort("left", "(less-2)") + doSort("(great+2)", "right") + + //If pivots are equal, then early out + code.push("if(pivots_are_equal){") + cleanUp() + code.push("return") + code.push("}") + + function walkPointer(ptr, pivot, body) { + if(order.length > 1) { + code.push(["__l",++labelCounter,":while(true){"].join("")) + cacheLoop([ptr], true, [ + "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}" + ].join("")) + code.push(body, "}") + } else { + code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join("")) + } } + + //Check bounds + code.push("if(lessindex5){") + + walkPointer("less", 1, "++less") + walkPointer("great", 2, "--great") + + code.push("for(k=less;k<=great;++k){") + comparePivot("comp_pivot1", "k", 1) + code.push("if(comp_pivot1===0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + comparePivot("comp_pivot2", "k", 2) + code.push("if(comp_pivot2===0){") + code.push("while(true){") + comparePivot("comp", "great", 2) + code.push("if(comp===0){") + code.push("if(--great 1 && allocator) { + var compiled = new Function("insertionSort", "malloc", "free", code.join("\n")) + return compiled(insertionSort, allocator[0], allocator[1]) + } + var compiled = new Function("insertionSort", code.join("\n")) + return compiled(insertionSort) +} - var tPos = [] - var tCol = [] - var tNor = [] - var tUVs = [] - var tIds = [] - - var ePos = [] - var eCol = [] - var eUVs = [] - var eIds = [] - - var pPos = [] - var pCol = [] - var pUVs = [] - var pSiz = [] - var pIds = [] - - //Save geometry data for picking calculations - this.cells = cells - this.positions = positions - - //Compute normals - var vertexNormals = params.vertexNormals - var cellNormals = params.cellNormals - var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon - var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon - if(params.useFacetNormals && !cellNormals) { - cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon) +function compileSort(order, dtype) { + var code = ["'use strict'"] + var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("") + var funcArgs = [ "array" ] + + code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) + + //Unpack local variables from array + var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"] + for(var i=0; i 0) { + vars.push(["d",j,"=s",j,"-d",p,"*n",p].join("")) + } else { + vars.push(["d",j,"=s",j].join("")) } - } else { - for(var i=0; i 0) { + vars.push(["e",k,"=s",k,"-e",q,"*n",q, + ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join("")) + } else { + vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join("")) } + q = k } } + + //Declare local variables + code.push("var " + vars.join(",")) + + //Create arguments for subroutine + var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length)) + + //Call main sorting routine + code.push([ + "if(n0<=",INSERTION_SORT_THRESHOLD,"){", + "insertionSort(", sortArgs.join(","), ")}else{", + "quickSort(", sortArgs.join(","), + ")}" + ].join("")) + + //Return + code.push("}return " + funcName) + + //Link everything together + var result = new Function("insertionSort", "quickSort", code.join("\n")) + var insertionSort = createInsertionSort(order, dtype) + var quickSort = createQuickSort(order, dtype, insertionSort) + return result(insertionSort, quickSort) +} - if(vertexIntensity) { - this.intensity = vertexIntensity - } else if(cellIntensity) { - this.intensity = unpackIntensity(cells, positions.length, cellIntensity) - } else { - this.intensity = takeZComponent(positions) - } - - //Point size - var pointSizes = params.pointSizes - var meshPointSize = params.pointSize || 1.0 +module.exports = compileSort +},{"typedarray-pool":306}],303:[function(require,module,exports){ +"use strict" - //Update bounds - this.bounds = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]] - for(var i=0; i 0) { - var shader = this.triShader - shader.bind() - shader.uniforms = uniforms + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight - this.triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) - this.triangleVAO.unbind() - } + if(xCount) { + uniforms.color = tickMarkColor[0] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } - if(this.edgeCount > 0 && this.lineWidth > 0) { - var shader = this.lineShader - shader.bind() - shader.uniforms = uniforms + SCR_OFFSET[0] = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0 + SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkLength[3] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkWidth[3] * pixelRatio / screenHeight - this.edgeVAO.bind() - gl.lineWidth(this.lineWidth) - gl.drawArrays(gl.LINES, 0, this.edgeCount*2) - this.edgeVAO.unbind() - } + if(yCount) { + uniforms.color = tickMarkColor[3] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = Y_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, yOffset, yCount) + } - if(this.pointCount > 0) { - var shader = this.pointShader - shader.bind() - shader.uniforms = uniforms + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[2] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[2] * pixelRatio / screenHeight - this.pointVAO.bind() - gl.drawArrays(gl.POINTS, 0, this.pointCount) - this.pointVAO.unbind() + if(xCount) { + uniforms.color = tickMarkColor[2] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } } +})() - if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) { - var shader = this.contourShader - shader.bind() - shader.uniforms = uniforms - - this.contourVAO.bind() - gl.drawArrays(gl.LINES, 0, this.contourCount) - this.contourVAO.unbind() - } -} +proto.update = (function() { + var OFFSET_X = [1, 1, -1, -1, 1, -1] + var OFFSET_Y = [1, -1, 1, 1, -1, -1] -proto.drawPick = function(params) { - params = params || {} + return function(options) { + var ticks = options.ticks + var bounds = options.bounds + var data = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length)) - var gl = this.gl + var zeroLineEnable = this.plot.zeroLineEnable - var model = params.model || identityMatrix - var view = params.view || identityMatrix - var projection = params.projection || identityMatrix + var ptr = 0 + var gridTicks = [[], []] + for(var dim=0; dim<2; ++dim) { + var localTicks = gridTicks[dim] + var axisTicks = ticks[dim] + var lo = bounds[dim] + var hi = bounds[dim+2] + for(var i=0; i 0) { - this.triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) - this.triangleVAO.unbind() - } +module.exports = createLines - if(this.edgeCount > 0) { - this.edgeVAO.bind() - gl.lineWidth(this.lineWidth) - gl.drawArrays(gl.LINES, 0, this.edgeCount*2) - this.edgeVAO.unbind() - } +var createBuffer = require('gl-buffer') +var createShader = require('gl-shader') - if(this.pointCount > 0) { - var shader = this.pointPickShader - shader.bind() - shader.uniforms = uniforms +var shaders = require('./shaders') - this.pointVAO.bind() - gl.drawArrays(gl.POINTS, 0, this.pointCount) - this.pointVAO.unbind() - } +function Lines(plot, vbo, shader) { + this.plot = plot + this.vbo = vbo + this.shader = shader } +var proto = Lines.prototype -proto.pick = function(pickData) { - if(!pickData) { - return null - } - if(pickData.id !== this.pickId) { - return null - } +proto.bind = function() { + var shader = this.shader + this.vbo.bind() + this.shader.bind() + shader.attributes.coord.pointer() + shader.uniforms.screenBox = this.plot.screenBox +} - var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2] - var cell = this.cells[cellId] - var positions = this.positions +proto.drawLine = (function() { + var start = [0,0] + var end = [0,0] + return function(startX, startY, endX, endY, width, color) { + var plot = this.plot + var shader = this.shader + var gl = plot.gl - var simplex = new Array(cell.length) - for(var i=0; i tickOffset[start]) { + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = textColor[axis] + shader.uniforms.angle = textAngle[axis] + gl.drawArrays( + gl.TRIANGLES, + tickOffset[start], + tickOffset[end] - tickOffset[start]) + } + } + if(labelEnable[axis] && labelCount) { + SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis] + shader.uniforms.dataAxis = ZERO_2 + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = labelColor[axis] + shader.uniforms.angle = labelAngle[axis] + gl.drawArrays( + gl.TRIANGLES, + labelOffset, + labelCount) } - ]) - var edgePositions = createBuffer(gl) - var edgeColors = createBuffer(gl) - var edgeUVs = createBuffer(gl) - var edgeIds = createBuffer(gl) - var edgeVAO = createVAO(gl, [ - { buffer: edgePositions, - type: gl.FLOAT, - size: 3 - }, - { buffer: edgeIds, - type: gl.UNSIGNED_BYTE, - size: 4, - normalized: true - }, - { buffer: edgeColors, - type: gl.FLOAT, - size: 4 - }, - { buffer: edgeUVs, - type: gl.FLOAT, - size: 2 + SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0 + if(tickEnable[axis+2]) { + SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2] + if(start < end && tickOffset[end] > tickOffset[start]) { + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = textColor[axis+2] + shader.uniforms.angle = textAngle[axis+2] + gl.drawArrays( + gl.TRIANGLES, + tickOffset[start], + tickOffset[end] - tickOffset[start]) + } + } + if(labelEnable[axis+2] && labelCount) { + SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2] + shader.uniforms.dataAxis = ZERO_2 + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = labelColor[axis+2] + shader.uniforms.angle = labelAngle[axis+2] + gl.drawArrays( + gl.TRIANGLES, + labelOffset, + labelCount) } - ]) - var pointPositions = createBuffer(gl) - var pointColors = createBuffer(gl) - var pointUVs = createBuffer(gl) - var pointSizes = createBuffer(gl) - var pointIds = createBuffer(gl) - var pointVAO = createVAO(gl, [ - { buffer: pointPositions, - type: gl.FLOAT, - size: 3 - }, - { buffer: pointIds, - type: gl.UNSIGNED_BYTE, - size: 4, - normalized: true - }, - { buffer: pointColors, - type: gl.FLOAT, - size: 4 - }, - { buffer: pointUVs, - type: gl.FLOAT, - size: 2 - }, - { buffer: pointSizes, - type: gl.FLOAT, - size: 1 + } +})() + +proto.drawTitle = (function() { + var DATA_AXIS = [0,0] + var SCREEN_OFFSET = [0,0] + + return function() { + var plot = this.plot + var shader = this.shader + var gl = plot.gl + var screenBox = plot.screenBox + var titleCenter = plot.titleCenter + var titleAngle = plot.titleAngle + var titleColor = plot.titleColor + var titleCenter = plot.titleCenter + var pixelRatio = plot.pixelRatio + + if(!this.titleCount) { + return } - ]) - var contourPositions = createBuffer(gl) - var contourVAO = createVAO(gl, [ - { buffer: contourPositions, - type: gl.FLOAT, - size: 3 - }]) + for(var i=0; i<2; ++i) { + SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) / + (screenBox[2+i] - screenBox[i]) - 1 + } - var mesh = new SimplicialMesh(gl - , meshTexture - , triShader - , lineShader - , pointShader - , pickShader - , pointPickShader - , contourShader - , trianglePositions - , triangleIds - , triangleColors - , triangleUVs - , triangleNormals - , triangleVAO - , edgePositions - , edgeIds - , edgeColors - , edgeUVs - , edgeVAO - , pointPositions - , pointIds - , pointColors - , pointUVs - , pointSizes - , pointVAO - , contourPositions - , contourVAO) + shader.bind() + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.angle = titleAngle + shader.uniforms.color = titleColor - mesh.update(params) + gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount) + } +})() - return mesh -} +proto.bind = (function() { + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var TEXT_SCALE = [0,0] -module.exports = createSimplicialMesh + return function() { + var plot = this.plot + var shader = this.shader + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var screenBox = plot.screenBox + var viewBox = plot.viewBox -},{"./lib/closest-point":148,"./lib/shaders":149,"colormap":100,"gl-buffer":118,"gl-mat4/invert":137,"gl-mat4/multiply":139,"gl-shader":197,"gl-texture2d":222,"gl-vao":226,"ndarray":253,"normals":152,"simplicial-complex-contour":154,"typedarray-pool":278}],151:[function(require,module,exports){ -'use strict' + shader.bind() -module.exports = barycentric + //Set up coordinate scaling uniforms + for(var i=0; i<2; ++i) { -var solve = require('robust-linear-solve') + var lo = bounds[i] + var hi = bounds[i+2] + var boundScale = hi - lo + var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) + var dataWidth = (dataBox[i+2] - dataBox[i]) -function reduce(x) { - var r = 0 - for(var i=0; i epsilon) { - var norm = normals[c]; - var w = 1.0 / Math.sqrt(m01 * m21); - for(var k=0; k<3; ++k) { - var u = (k+1)%3; - var v = (k+2)%3; - norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); - } - } + offsets.push(Math.floor(vertices.length/3)) + tickX.push(x) } - } - //Scale all normals to unit length - for(var i=0; i epsilon) { - var w = 1.0 / Math.sqrt(m); - for(var k=0; k<3; ++k) { - norm[k] *= w; - } - } else { - for(var k=0; k<3; ++k) { - norm[k] = 0.0; - } - } + this.tickOffset[dimension] = offsets + this.tickX[dimension] = tickX } - //Return the resulting set of patches - return normals; -} - -//Compute face normals of a mesh -exports.faceNormals = function(faces, positions, specifiedEpsilon) { - - var N = faces.length; - var normals = new Array(N); - var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon; + //Add labels + for(var dimension=0; dimension<2; ++dimension) { + this.labelOffset[dimension] = Math.floor(vertices.length/3) - for(var i=0; i epsilon) { - l = 1.0 / Math.sqrt(l); - } else { - l = 0.0; - } - for(var j=0; j<3; ++j) { - n[j] *= l; - } - normals[i] = n; + //Add title + this.titleOffset = Math.floor(vertices.length/3) + var data = getText(options.titleFont, options.title).data + var scale = options.titleSize + for(var i=0; i= a00) { - s = 1.0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } else { - s = 0; - if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else if (-b1 >= a11) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else { // region 3 - s = 0; - if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else if (-b1 >= a11) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else if (t < 0) { // region 5 - t = 0; - if (b0 >= 0) { - s = 0; - sqrDistance = c; - } else if (-b0 >= a00) { - s = 1; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } else { // region 0 - // minimum at interior point - var invDet = 1.0 / det; - s *= invDet; - t *= invDet; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c; +function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) { + var code = [ + "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", +earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), +";while(l<=h){\ +var m=(l+h)>>>1,x=a[m]"] + if(earlyOut) { + if(predicate.indexOf("c") < 0) { + code.push(";if(x===y){return m}else if(x<=y){") + } else { + code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") } } else { - var tmp0, tmp1, numer, denom; - - if (s < 0) { // region 2 - tmp0 = a01 + b0; - tmp1 = a11 + b1; - if (tmp1 > tmp0) { - numer = tmp1 - tmp0; - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - s = 1; - t = 0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = numer/denom; - t = 1 - s; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - s = 0; - if (tmp1 <= 0) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else if (t < 0) { // region 6 - tmp0 = a01 + b1; - tmp1 = a00 + b0; - if (tmp1 > tmp0) { - numer = tmp1 - tmp0; - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - t = 1; - s = 0; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = numer/denom; - s = 1 - t; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - t = 0; - if (tmp1 <= 0) { - s = 1; - sqrDistance = a00 + 2.0*b0 + c; - } else if (b0 >= 0) { - s = 0; - sqrDistance = c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } - } else { // region 1 - numer = a11 + b1 - a01 - b0; - if (numer <= 0) { - s = 0; - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - s = 1; - t = 0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = numer/denom; - t = 1 - s; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } - } + code.push(";if(", predicate, "){i=m;") } - var u = 1.0 - s - t; - for(var i=0; i=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) } -module.exports = closestPoint2d; +},{}],313:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":316}],314:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],315:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],316:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":314,"buffer":65,"dup":122}],317:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],318:[function(require,module,exports){ +module.exports = require("cwise-compiler") +},{"cwise-compiler":319}],319:[function(require,module,exports){ +"use strict" + +var createThunk = require("./lib/thunk.js") + +function Procedure() { + this.argTypes = [] + this.shimArgs = [] + this.arrayArgs = [] + this.arrayBlockIndices = [] + this.scalarArgs = [] + this.offsetArgs = [] + this.offsetArgIndex = [] + this.indexArgs = [] + this.shapeArgs = [] + this.funcName = "" + this.pre = null + this.body = null + this.post = null + this.debug = false +} + +function compileCwise(user_args) { + //Create procedure + var proc = new Procedure() + + //Parse blocks + proc.pre = user_args.pre + proc.body = user_args.body + proc.post = user_args.post + + //Parse arguments + var proc_args = user_args.args.slice(0) + proc.argTypes = proc_args + for(var i=0; i0) { + throw new Error("cwise: pre() block may not reference array args") + } + if(i < proc.post.args.length && proc.post.args[i].count>0) { + throw new Error("cwise: post() block may not reference array args") + } + } else if(arg_type === "scalar") { + proc.scalarArgs.push(i) + proc.shimArgs.push("scalar" + i) + } else if(arg_type === "index") { + proc.indexArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { + throw new Error("cwise: pre() block may not reference array index") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array index") + } + if(i < proc.post.args.length && proc.post.args[i].count > 0) { + throw new Error("cwise: post() block may not reference array index") + } + } else if(arg_type === "shape") { + proc.shapeArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { + throw new Error("cwise: pre() block may not write to array shape") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array shape") + } + if(i < proc.post.args.length && proc.post.args[i].lvalue) { + throw new Error("cwise: post() block may not write to array shape") + } + } else if(typeof arg_type === "object" && arg_type.offset) { + proc.argTypes[i] = "offset" + proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) + proc.offsetArgIndex.push(i) + } else { + throw new Error("cwise: Unknown argument type " + proc_args[i]) + } + } + + //Make sure at least one array argument was specified + if(proc.arrayArgs.length <= 0) { + throw new Error("cwise: No array arguments specified") + } + + //Make sure arguments are correct + if(proc.pre.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in pre() block") + } + if(proc.body.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in body() block") + } + if(proc.post.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in post() block") + } + + //Check debug flag + proc.debug = !!user_args.printCode || !!user_args.debug + + //Retrieve name + proc.funcName = user_args.funcName || "cwise" + + //Read in block size + proc.blockSize = user_args.blockSize || 64 + + return createThunk(proc) +} + +module.exports = compileCwise + +},{"./lib/thunk.js":321}],320:[function(require,module,exports){ +"use strict" + +var uniq = require("uniq") + +// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) +// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. +function innerFill(order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , has_index = proc.indexArgs.length>0 + , code = [] + , vars = [] + , idx=0, pidx=0, i, j + for(i=0; i=0; --i) { // Start at largest stride and work your way inwards + idx = order[i] + code.push(["for(i",i,"=0;i",i," 0) { + code.push(["index[",pidx,"]-=s",pidx].join("")) + } + code.push(["++index[",idx,"]"].join("")) + } + code.push("}") + } + return code.join("\n") +} + +// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. +// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. +// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. +function outerFill(matched, order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , blockSize = proc.blockSize + , has_index = proc.indexArgs.length > 0 + , code = [] + for(var i=0; i0;){"].join("")) // Iterate back to front + code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). + code.push(["s",order[i],"=j",i].join("")) + code.push(["j",i,"=0"].join("")) + code.push(["}else{s",order[i],"=",blockSize].join("")) + code.push(["j",i,"-=",blockSize,"}"].join("")) + if(has_index) { + code.push(["index[",order[i],"]=j",i].join("")) + } + } + for(var i=0; i 0) { + allEqual = allEqual && summary[i] === summary[i-1] + } + } + if(allEqual) { + return summary[0] + } + return summary.join("") +} + +//Generates a cwise operator +function generateCWiseOp(proc, typesig) { + + //Compute dimension + // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. + var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 + var orders = new Array(proc.arrayArgs.length) + var dtypes = new Array(proc.arrayArgs.length) + for(var i=0; i 0) { + vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) + } + if(proc.indexArgs.length > 0) { + // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. + var zeros = new Array(dimension) + for(var i=0; i 3) { + code.push(processBlock(proc.pre, proc, dtypes)) + } + + //Process body + var body = processBlock(proc.body, proc, dtypes) + var matched = countMatches(loopOrders) + if(matched < dimension) { + code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. + } else { + code.push(innerFill(loopOrders[0], proc, body)) + } + + //Inline epilog + if(proc.post.body.length > 3) { + code.push(processBlock(proc.post, proc, dtypes)) + } + + if(proc.debug) { + console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") + } + + var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") + var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) + return f() +} +module.exports = generateCWiseOp -},{}],154:[function(require,module,exports){ -'use strict' +},{"uniq":322}],321:[function(require,module,exports){ +"use strict" + +// The function below is called when constructing a cwise function object, and does the following: +// A function object is constructed which accepts as argument a compilation function and returns another function. +// It is this other function that is eventually returned by createThunk, and this function is the one that actually +// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. +// The compilation passed to the first function object is used for compiling new functions. +// Once this function object is created, it is called with compile as argument, where the first argument of compile +// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). +// So createThunk roughly works like this: +// function createThunk(proc) { +// var thunk = function(compileBound) { +// var CACHED = {} +// return function(arrays and scalars) { +// if (dtype and order of arrays in CACHED) { +// var func = CACHED[dtype and order of arrays] +// } else { +// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) +// } +// return func(arrays and scalars) +// } +// } +// return thunk(compile.bind1(proc)) +// } + +var compile = require("./compile.js") + +function createThunk(proc) { + var code = ["'use strict'", "var CACHED={}"] + var vars = [] + var thunkName = proc.funcName + "_cwise_thunk" + + //Build thunk + code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) + var typesig = [] + var string_typesig = [] + var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). + Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] + var shapeLengthConditions = [], shapeConditions = [] + // Process array arguments + for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) + shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) + shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") + } + } + // Check for shape equality + if (proc.arrayArgs.length > 1) { + code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") + code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") + code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") + code.push("}") + } + // Process scalar arguments + for(var i=0; i 1) { + ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]) } - //Read in vertex signs - var vertexSigns = getSigns(values, +level) + //Allocate depth/stencil buffers + var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture') + if(WEBGL_depth_texture) { + if(useStencil) { + fbo.depth = initTexture(gl, width, height, + WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, + gl.DEPTH_STENCIL, + gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo.depth = initTexture(gl, width, height, + gl.UNSIGNED_SHORT, + gl.DEPTH_COMPONENT, + gl.DEPTH_ATTACHMENT) + } + } else { + if(useDepth && useStencil) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT) + } else if(useStencil) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT) + } + } - //First get 1-skeleton, find all crossings - var edges = getEdges(cells, d) - var weights = getCrossingWeights(edges, values, vertexSigns, +level) + //Check frame buffer state + var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) + if(status !== gl.FRAMEBUFFER_COMPLETE) { - //Build vertex cascade to speed up binary search - var vcascade = getCascade(edges, values.length|0) + //Release all partially allocated resources + fbo._destroyed = true - //Then construct cells - var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns) + //Release all resources + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.deleteFramebuffer(fbo.handle) + fbo.handle = null + if(fbo.depth) { + fbo.depth.dispose() + fbo.depth = null + } + if(fbo._depth_rb) { + gl.deleteRenderbuffer(fbo._depth_rb) + fbo._depth_rb = null + } + for(var i=0; i>1,v=E[2*m+1];', - 'if(v===b){return m}', - 'if(b 0) { - code.push(',') + //Shape vector for resizing + var parent = this + var shapeVector = [width|0, height|0] + Object.defineProperties(shapeVector, { + 0: { + get: function() { + return parent._shape[0] + }, + set: function(w) { + return parent.width = w } - code.push('[') - for(var j=0; j 0) { - code.push(',') - } - code.push('B(C,E,c[', f[0], '],c[', f[1], '])') + }, + 1: { + get: function() { + return parent._shape[1] + }, + set: function(h) { + return parent.height = h } - code.push(']') } - code.push(');') - } + }) + this._shapeVector = shapeVector - for(var i=d+1; i>1; --i) { - if(i < d+1) { - code.push('else ') - } - code.push('if(l===', i, '){') + //Initialize all attachments + rebuildFBO(this) +} - //Generate mask - var maskStr = [] - for(var j=0; j maxFBOSize || + h < 0 || h > maxFBOSize) { + throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions') } - return alg -} -},{"marching-simplex-table":156,"typedarray-pool":278}],156:[function(require,module,exports){ -'use strict' -module.exports = createTable + //Update shape + fbo._shape[0] = w + fbo._shape[1] = h -var chull = require('convex-hull') + //Save framebuffer state + var state = saveFBOState(gl) -function constructVertex(d, a, b) { - var x = new Array(d) - for(var i=0; i 1) { - var scratch_shape = [] - for(var i=1; i 1) { - - //Copy data into scratch - code.push("dptr=0;sptr=ptr") - for(var i=order.length-1; i>=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"left){", - "dptr=0", - "sptr=cptr-s0") - for(var i=1; ib){break __l}"].join("")) - for(var i=order.length-1; i>=1; --i) { - code.push( - "sptr+=e"+i, - "dptr+=f"+i, - "}") - } - - //Copy data back - code.push("dptr=cptr;sptr=cptr-s0") - for(var i=order.length-1; i>=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j," maxFBOSize || height < 0 || height > maxFBOSize) { + throw new Error('gl-fbo: Parameters are too large for FBO') + } + + //Handle each option type + options = options || {} + + //Figure out number of color buffers to use + var numColors = 1 + if('color' in options) { + numColors = Math.max(options.color|0, 0) + if(numColors < 0) { + throw new Error('gl-fbo: Must specify a nonnegative number of colors') } - code.push(dataWrite("dptr", "scratch[sptr++]")) - for(var i=0; i 1) { + //Check if multiple render targets supported + if(!WEBGL_draw_buffers) { + throw new Error('gl-fbo: Multiple draw buffer extension not supported') + } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) { + throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers') } - code.push("dptr+=d"+j,"}") } - } else { - code.push("scratch=" + dataRead("ptr"), - "while((j-->left)&&("+dataRead("cptr-s0")+">scratch)){", - dataWrite("cptr", dataRead("cptr-s0")), - "cptr-=s0", - "}", - dataWrite("cptr", "scratch")) - } - - //Close outer loop body - code.push("}") - if(order.length > 1 && allocator) { - code.push("free(scratch)") } - code.push("} return " + funcName) - - //Compile and link function - if(allocator) { - var result = new Function("malloc", "free", code.join("\n")) - return result(allocator[0], allocator[1]) - } else { - var result = new Function(code.join("\n")) - return result() - } -} -function createQuickSort(order, dtype, insertionSort) { - var code = [ "'use strict'" ] - var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("") - var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length)) - var allocator = getMallocFree(dtype) - var labelCounter=0 - - code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) - - var vars = [ - "sixth=((right-left+1)/6)|0", - "index1=left+sixth", - "index5=right-sixth", - "index3=(left+right)>>1", - "index2=index3-sixth", - "index4=index3+sixth", - "el1=index1", - "el2=index2", - "el3=index3", - "el4=index4", - "el5=index5", - "less=left+1", - "great=right-1", - "pivots_are_equal=true", - "tmp", - "tmp0", - "x", - "y", - "z", - "k", - "ptr0", - "ptr1", - "ptr2", - "comp_pivot1=0", - "comp_pivot2=0", - "comp=0" - ] - - if(order.length > 1) { - var ele_size = [] - for(var i=1; i 0) { + if(!OES_texture_float) { + throw new Error('gl-fbo: Context does not support floating point textures') } - vars.push( - "ptr3", - "ptr4", - "ptr5", - "ptr6", - "ptr7", - "pivot_ptr", - "ptr_shift", - "elementSize="+ele_size.join("*")) - if(allocator) { - vars.push("pivot1=malloc(elementSize)", - "pivot2=malloc(elementSize)") - } else { - vars.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)") + colorType = gl.FLOAT + } else if(options.preferFloat && numColors > 0) { + if(OES_texture_float) { + colorType = gl.FLOAT } - } else { - vars.push("pivot1", "pivot2") } - - //Initialize local variables - code.push("var " + vars.join(",")) - - function toPointer(v) { - return ["(offset+",v,"*s0)"].join("") + + //Check if we should use depth buffer + var useDepth = true + if('depth' in options) { + useDepth = !!options.depth } - - function dataRead(ptr) { - if(dtype === "generic") { - return ["data.get(", ptr, ")"].join("") - } - return ["data[",ptr,"]"].join("") + + //Check if we should use a stencil buffer + var useStencil = false + if('stencil' in options) { + useStencil = !!options.stencil } - - function dataWrite(ptr, v) { - if(dtype === "generic") { - return ["data.set(", ptr, ",", v, ")"].join("") + + return new Framebuffer( + gl, + width, + height, + colorType, + numColors, + useDepth, + useStencil, + WEBGL_draw_buffers) +} + +},{"gl-texture2d":324}],324:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":326}],325:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],326:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":317,"buffer":65,"dup":122}],327:[function(require,module,exports){ +'use strict' + +module.exports = createSelectBuffer + +var createFBO = require('gl-fbo') +var pool = require('typedarray-pool') +var ndarray = require('ndarray') + +var nextPow2 = require('bit-twiddle').nextPow2 + +var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_1_arg0_||255>_inline_1_arg1_||255>_inline_1_arg2_||255>_inline_1_arg3_){var _inline_1_l=_inline_1_arg4_-_inline_1_arg6_[0],_inline_1_a=_inline_1_arg5_-_inline_1_arg6_[1],_inline_1_f=_inline_1_l*_inline_1_l+_inline_1_a*_inline_1_a;_inline_1_f=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j," 1) { - for(var i=0; i1) { - code.push("ptr_shift+=d"+j) - } else { - code.push("ptr0+=d"+j) + this.fbo.shape = v + var c = this.fbo.shape[0] + var r = this.fbo.shape[1] + if(r*c*4 > this.buffer.length) { + pool.free(this.buffer) + var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) + for(var i=0; i 1) { - for(var i=0; i=1; --i) { - if(usePivot) { - code.push("pivot_ptr+=f"+i) - } - if(ptrs.length > 1) { - code.push("ptr_shift+=e"+i) - } else { - code.push("ptr0+=e"+i) - } - code.push("}") - } +}) + +proto.begin = function() { + var gl = this.gl + var shape = this.shape + if(!gl) { + return + } + + this.fbo.bind() + gl.clearColor(1,1,1,1) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) +} + +proto.end = function() { + var gl = this.gl + if(!gl) { + return + } + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + if(!this._readTimeout) { + clearTimeout(this._readTimeout) + } + this._readTimeout = setTimeout(this._readCallback, 1) +} + +proto.query = function(x, y, radius) { + if(!this.gl) { + return null } - - function cleanUp() { - if(order.length > 1 && allocator) { - code.push("free(pivot1)", "free(pivot2)") - } + + var shape = this.fbo.shape.slice() + + x = x|0 + y = y|0 + if(typeof radius !== 'number') { + radius = 1.0 } - - function compareSwap(a_id, b_id) { - var a = "el"+a_id - var b = "el"+b_id - if(order.length > 1) { - var lbl = "__l" + (++labelCounter) - lexicoLoop(lbl, [a, b], false, [ - "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n", - "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n", - "if(comp<0){break ", lbl, "}" - ].join("")) - } else { - code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join("")) - } + + var x0 = Math.min(Math.max(x - radius, 0), shape[0])|0 + var x1 = Math.min(Math.max(x + radius, 0), shape[0])|0 + var y0 = Math.min(Math.max(y - radius, 0), shape[1])|0 + var y1 = Math.min(Math.max(y + radius, 0), shape[1])|0 + + if(x1 <= x0 || y1 <= y0) { + return null } - - compareSwap(1, 2) - compareSwap(4, 5) - compareSwap(1, 3) - compareSwap(2, 3) - compareSwap(1, 4) - compareSwap(3, 4) - compareSwap(2, 5) - compareSwap(2, 3) - compareSwap(4, 5) - - if(order.length > 1) { - cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [ - "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n", - "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n", - "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n", - "x=",dataRead("ptr0"),"\n", - "y=",dataRead("ptr2"),"\n", - "z=",dataRead("ptr4"),"\n", - dataWrite("ptr5", "x"),"\n", - dataWrite("ptr6", "y"),"\n", - dataWrite("ptr7", "z") - ].join("")) - } else { - code.push([ - "pivot1=", dataRead(toPointer("el2")), "\n", - "pivot2=", dataRead(toPointer("el4")), "\n", - "pivots_are_equal=pivot1===pivot2\n", - "x=", dataRead(toPointer("el1")), "\n", - "y=", dataRead(toPointer("el3")), "\n", - "z=", dataRead(toPointer("el5")), "\n", - dataWrite(toPointer("index1"), "x"), "\n", - dataWrite(toPointer("index3"), "y"), "\n", - dataWrite(toPointer("index5"), "z") - ].join("")) + + var dims = [x1-x0,y1-y0] + var region = ndarray( + this.buffer, + [dims[0], dims[1], 4], + [4, shape[0]*4, 1], + 4*(x0 + shape[0]*y0)); + + var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius) + var dx = closest[0] + var dy = closest[1] + if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) { + return null } - - function moveElement(dst, src) { - if(order.length > 1) { - cacheLoop([dst, src], false, - dataWrite("ptr0", dataRead("ptr1")) - ) - } else { - code.push(dataWrite(toPointer(dst), dataRead(toPointer(src)))) - } + var c0 = region.get(dx, dy, 0) + var c1 = region.get(dx, dy, 1) + var c2 = region.get(dx, dy, 2) + var c3 = region.get(dx, dy, 3) + + return new SelectResult( + (dx + x0)|0, + (dy + y0)|0, + c0, + [c1, c2, c3], + Math.sqrt(closest[2])) +} + +proto.dispose = function() { + if(!this.gl) { + return } - - moveElement("index2", "left") - moveElement("index4", "right") - - function comparePivot(result, ptr, n) { - if(order.length > 1) { - var lbl = "__l" + (++labelCounter) - lexicoLoop(lbl, [ptr], true, [ - result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n", - "if(",result,"!==0){break ", lbl, "}" - ].join("")) - } else { - code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join("")) - } + this.fbo.dispose() + pool.free(this.buffer) + this.gl = null + if(this._readTimeout) { + clearTimeout(this._readTimeout) } - - function swapElements(a, b) { - if(order.length > 1) { - cacheLoop([a,b],false,[ - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", "tmp") - ].join("")) - } else { - code.push([ - "ptr0=",toPointer(a),"\n", - "ptr1=",toPointer(b),"\n", - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", "tmp") - ].join("")) - } +} + +function createSelectBuffer(gl, shape) { + var fbo = createFBO(gl, shape) + var buffer = pool.mallocUint8(shape[0]*shape[1]*4) + return new SelectBuffer(gl, fbo, buffer) +} + +},{"bit-twiddle":317,"cwise/lib/wrapper":318,"gl-fbo":323,"ndarray":1031,"typedarray-pool":326}],328:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":329,"./lib/create-attributes":330,"./lib/create-uniforms":331,"./lib/reflect":332,"./lib/runtime-reflect":333,"./lib/shader-cache":334,"dup":94}],329:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],330:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":329,"dup":96}],331:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":329,"./reflect":332,"dup":97}],332:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],333:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],334:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":329,"dup":100,"gl-format-compiler-error":335,"weakmap-shim":353}],335:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":336,"dup":101,"gl-constants/lookup":340,"glsl-shader-name":341,"sprintf-js":350}],336:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":337}],337:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":338}],338:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],339:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],340:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":339,"dup":106}],341:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":342,"dup":107,"glsl-tokenizer":349}],342:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],343:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":345,"./lib/builtins-300es":344,"./lib/literals":347,"./lib/literals-300es":346,"./lib/operators":348,"dup":109}],344:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":345,"dup":110}],345:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],346:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":347,"dup":112}],347:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],348:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],349:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":343,"dup":115}],350:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],351:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":352,"dup":117}],352:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],353:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":351,"dup":119}],354:[function(require,module,exports){ +"use strict" + +module.exports = createText + +var vectorizeText = require("./lib/vtext") +var defaultCanvas = null +var defaultContext = null + +if(typeof document !== 'undefined') { + defaultCanvas = document.createElement('canvas') + defaultCanvas.width = 8192 + defaultCanvas.height = 1024 + defaultContext = defaultCanvas.getContext("2d") +} + +function createText(str, options) { + if((typeof options !== "object") || (options === null)) { + options = {} } - - function tripleSwap(k, less, great) { - if(order.length > 1) { - cacheLoop([k,less,great], false, [ - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", dataRead("ptr2")),"\n", - dataWrite("ptr2", "tmp") - ].join("")) - code.push("++"+less, "--"+great) - } else { - code.push([ - "ptr0=",toPointer(k),"\n", - "ptr1=",toPointer(less),"\n", - "ptr2=",toPointer(great),"\n", - "++",less,"\n", - "--",great,"\n", - "tmp=", dataRead("ptr0"), "\n", - dataWrite("ptr0", dataRead("ptr1")), "\n", - dataWrite("ptr1", dataRead("ptr2")), "\n", - dataWrite("ptr2", "tmp") - ].join("")) + return vectorizeText( + str, + options.canvas || defaultCanvas, + options.context || defaultContext, + options) +} + +},{"./lib/vtext":355}],355:[function(require,module,exports){ +"use strict" + +module.exports = vectorizeText +module.exports.processPixels = processPixels + +var surfaceNets = require('surface-nets') +var ndarray = require('ndarray') +var simplify = require('simplify-planar-graph') +var cleanPSLG = require('clean-pslg') +var cdt2d = require('cdt2d') +var toPolygonCrappy = require('planar-graph-to-polyline') + +function transformPositions(positions, options, size) { + var align = options.textAlign || "start" + var baseline = options.textBaseline || "alphabetic" + + var lo = [1<<30, 1<<30] + var hi = [0,0] + var n = positions.length + for(var i=0; i0){") - code.push("great--") - code.push("}else if(comp<0){") - tripleSwap("k", "less", "great") - code.push("break") - code.push("}else{") - swapAndDecrement("k", "great") - code.push("break") - code.push("}") - code.push("}") - code.push("}") - code.push("}") - code.push("}else{") - //Pivots not equal case - code.push("for(k=less;k<=great;++k){") - comparePivot("comp_pivot1", "k", 1) - code.push("if(comp_pivot1<0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - comparePivot("comp_pivot2", "k", 2) - code.push("if(comp_pivot2>0){") - code.push("while(true){") - comparePivot("comp", "great", 2) - code.push("if(comp>0){") - code.push("if(--great1) { - cacheLoop([mem_dest, pivot_dest], true, [ - dataWrite("ptr0", dataRead("ptr1")), "\n", - dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join("")) - ].join("")) - } else { - code.push( - dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))), - dataWrite(toPointer(pivot_dest), "pivot"+pivot)) - } + + var yShift = 0 + switch(baseline) { + case "hanging": + case "top": + yShift = -lo[1] + break + + case "middle": + yShift = -0.5 * (lo[1] + hi[1]) + break + + case "alphabetic": + case "ideographic": + yShift = -3 * size + break + + case "bottom": + yShift = -hi[1] + break + + default: + throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'") } - - storePivot("left", "(less-1)", 1) - storePivot("right", "(great+1)", 2) - //Recursive sort call - function doSort(left, right) { - code.push([ - "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n", - "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", - "}else{\n", - funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", - "}" - ].join("")) + var scale = 1.0 / size + if("lineHeight" in options) { + scale *= +options.lineHeight + } else if("width" in options) { + scale = options.width / (hi[0] - lo[0]) + } else if("height" in options) { + scale = options.height / (hi[1] - lo[1]) } - doSort("left", "(less-2)") - doSort("(great+2)", "right") - - //If pivots are equal, then early out - code.push("if(pivots_are_equal){") - cleanUp() - code.push("return") - code.push("}") - - function walkPointer(ptr, pivot, body) { - if(order.length > 1) { - code.push(["__l",++labelCounter,":while(true){"].join("")) - cacheLoop([ptr], true, [ - "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}" - ].join("")) - code.push(body, "}") - } else { - code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join("")) - } + + return positions.map(function(p) { + return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ] + }) +} + +function getPixels(canvas, context, str, size) { + var width = Math.ceil(context.measureText(str).width + 2*size)|0 + if(width > 8192) { + throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") } - - //Check bounds - code.push("if(lessindex5){") - - walkPointer("less", 1, "++less") - walkPointer("great", 2, "--great") - - code.push("for(k=less;k<=great;++k){") - comparePivot("comp_pivot1", "k", 1) - code.push("if(comp_pivot1===0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - comparePivot("comp_pivot2", "k", 2) - code.push("if(comp_pivot2===0){") - code.push("while(true){") - comparePivot("comp", "great", 2) - code.push("if(comp===0){") - code.push("if(--great 1 && allocator) { - var compiled = new Function("insertionSort", "malloc", "free", code.join("\n")) - return compiled(insertionSort, allocator[0], allocator[1]) + var height = 3 * size + if(canvas.height < height) { + canvas.height = height + } + + context.fillStyle = "#000" + context.fillRect(0, 0, canvas.width, canvas.height) + + context.fillStyle = "#fff" + context.fillText(str, size, 2*size) + + //Cut pixels from image + var pixelData = context.getImageData(0, 0, width, height) + var pixels = ndarray(pixelData.data, [height, width, 4]) + + return pixels.pick(-1,-1,0).transpose(1,0) +} + +function getContour(pixels, doSimplify) { + var contour = surfaceNets(pixels, 128) + if(doSimplify) { + return simplify(contour.cells, contour.positions, 0.25) + } + return { + edges: contour.cells, + positions: contour.positions + } +} + +function processPixelsImpl(pixels, options, size, simplify) { + //Extract contour + var contour = getContour(pixels, simplify) + + //Apply warp to positions + var positions = transformPositions(contour.positions, options, size) + var edges = contour.edges + var flip = "ccw" === options.orientation + + //Clean up the PSLG, resolve self intersections, etc. + cleanPSLG(positions, edges) + + //If triangulate flag passed, triangulate the result + if(options.polygons || options.polygon || options.polyline) { + var result = toPolygonCrappy(edges, positions) + var nresult = new Array(result.length) + for(var i=0; i 0) { - vars.push(["d",j,"=s",j,"-d",p,"*n",p].join("")) - } else { - vars.push(["d",j,"=s",j].join("")) - } - p = j - } - var k = order.length-1-i - if(k !== 0) { - if(q > 0) { - vars.push(["e",k,"=s",k,"-e",q,"*n",q, - ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join("")) - } else { - vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join("")) - } - q = k - } + return { + edges: [], + positions: [] } - - //Declare local variables - code.push("var " + vars.join(",")) - - //Create arguments for subroutine - var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length)) - - //Call main sorting routine - code.push([ - "if(n0<=",INSERTION_SORT_THRESHOLD,"){", - "insertionSort(", sortArgs.join(","), ")}else{", - "quickSort(", sortArgs.join(","), - ")}" - ].join("")) - - //Return - code.push("}return " + funcName) - - //Link everything together - var result = new Function("insertionSort", "quickSort", code.join("\n")) - var insertionSort = createInsertionSort(order, dtype) - var quickSort = createQuickSort(order, dtype, insertionSort) - return result(insertionSort, quickSort) } -module.exports = compileSort -},{"typedarray-pool":278}],158:[function(require,module,exports){ -"use strict" +function vectorizeText(str, canvas, context, options) { + var size = options.size || 64 + var family = options.font || "normal" -var compile = require("./lib/compile_sort.js") -var CACHE = {} + context.font = size + "px " + family + context.textAlign = "start" + context.textBaseline = "alphabetic" + context.direction = "ltr" -function sort(array) { - var order = array.order - var dtype = array.dtype - var typeSig = [order, dtype ] - var typeName = typeSig.join(":") - var compiled = CACHE[typeName] - if(!compiled) { - CACHE[typeName] = compiled = compile(order, dtype) - } - compiled(array) - return array + var pixels = getPixels(canvas, context, str, size) + + return processPixels(pixels, options, size) } -module.exports = sort -},{"./lib/compile_sort.js":157}],159:[function(require,module,exports){ +},{"cdt2d":356,"clean-pslg":367,"ndarray":1031,"planar-graph-to-polyline":424,"simplify-planar-graph":428,"surface-nets":450}],356:[function(require,module,exports){ 'use strict' -module.exports = createBoxes +var monotoneTriangulate = require('./lib/monotone') +var makeIndex = require('./lib/triangulation') +var delaunayFlip = require('./lib/delaunay') +var filterTriangulation = require('./lib/filter') -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') +module.exports = cdt2d -var shaders = require('./shaders') +function canonicalizeEdge(e) { + return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] +} -function Boxes(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader +function compareEdge(a, b) { + return a[0]-b[0] || a[1]-b[1] } -var proto = Boxes.prototype +function canonicalizeEdges(edges) { + return edges.map(canonicalizeEdge).sort(compareEdge) +} -proto.bind = function() { - var shader = this.shader - this.vbo.bind() - this.shader.bind() - shader.attributes.coord.pointer() - shader.uniforms.screenBox = this.plot.screenBox +function getDefault(options, property, dflt) { + if(property in options) { + return options[property] + } + return dflt } -proto.drawBox = (function() { - var lo = [0,0] - var hi = [0,0] - return function(loX, loY, hiX, hiY, color) { - var plot = this.plot - var shader = this.shader - var gl = plot.gl +function cdt2d(points, edges, options) { - lo[0] = loX - lo[1] = loY - hi[0] = hiX - hi[1] = hiY + if(!Array.isArray(edges)) { + options = edges || {} + edges = [] + } else { + options = options || {} + edges = edges || [] + } - shader.uniforms.lo = lo - shader.uniforms.hi = hi - shader.uniforms.color = color + //Parse out options + var delaunay = !!getDefault(options, 'delaunay', true) + var interior = !!getDefault(options, 'interior', true) + var exterior = !!getDefault(options, 'exterior', true) + var infinity = !!getDefault(options, 'infinity', false) - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) + //Handle trivial case + if((!interior && !exterior) || points.length === 0) { + return [] } -}()) -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() -} + //Construct initial triangulation + var cells = monotoneTriangulate(points, edges) -function createBoxes(plot) { - var gl = plot.gl - var vbo = createBuffer(gl, [ - 0,0, - 0,1, - 1,0, - 1,1]) - var shader = createShader(gl, shaders.boxVert, shaders.lineFrag) - return new Boxes(plot, vbo, shader) + //If delaunay refinement needed, then improve quality by edge flipping + if(delaunay || interior !== exterior || infinity) { + + //Index all of the cells to support fast neighborhood queries + var triangulation = makeIndex(points.length, canonicalizeEdges(edges)) + for(var i=0; i 0) { + var b = stack.pop() + var a = stack.pop() - for(var i=0; i<2; ++i) { - var lo = bounds[i] - var hi = bounds[i+2] - var boundScale = hi - lo - var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) - var dataWidth = (dataBox[i+2] - dataBox[i]) - DATA_SCALE[i] = 2.0 * boundScale / dataWidth - DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth + //Find opposite pairs + var x = -1, y = -1 + var star = stars[a] + for(var i=1; i= 0) { + continue + } - shader.bind() - vbo.bind() + //Flip the edge + triangulation.flip(a, b) - shader.attributes.dataCoord.pointer() + //Test flipping neighboring edges + testFlip(points, triangulation, stack, x, a, y) + testFlip(points, triangulation, stack, a, y, x) + testFlip(points, triangulation, stack, y, b, x) + testFlip(points, triangulation, stack, b, x, y) + } +} - var uniforms = shader.uniforms - uniforms.dataShift = DATA_SHIFT - uniforms.dataScale = DATA_SCALE +},{"binary-search-bounds":312,"robust-in-sphere":361}],358:[function(require,module,exports){ +'use strict' - var tickMarkLength = plot.tickMarkLength - var tickMarkWidth = plot.tickMarkWidth - var tickMarkColor = plot.tickMarkColor +var bsearch = require('binary-search-bounds') - var xTicksOffset = 0 - var yTicksOffset = ticks[0].length * 6 +module.exports = classifyFaces - var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xEnd = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xOffset = xTicksOffset + 6 * xStart - var xCount = 6 * Math.max(0, xEnd - xStart) +function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) { + this.cells = cells + this.neighbor = neighbor + this.flags = flags + this.constraint = constraint + this.active = active + this.next = next + this.boundary = boundary +} - var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yEnd = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yOffset = yTicksOffset + 6 * yStart - var yCount = 6 * Math.max(0, yEnd - yStart) +var proto = FaceIndex.prototype - SCR_OFFSET[0] = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0 - SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkLength[1] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkWidth[1] * pixelRatio / screenHeight +function compareCell(a, b) { + return a[0] - b[0] || + a[1] - b[1] || + a[2] - b[2] +} - if(yCount) { - uniforms.color = tickMarkColor[1] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = Y_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, yOffset, yCount) +proto.locate = (function() { + var key = [0,0,0] + return function(a, b, c) { + var x = a, y = b, z = c + if(b < c) { + if(b < a) { + x = b + y = c + z = a + } + } else if(c < a) { + x = c + y = a + z = b } + if(x < 0) { + return -1 + } + key[0] = x + key[1] = y + key[2] = z + return bsearch.eq(this.cells, key, compareCell) + } +})() - SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 - SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight - - if(xCount) { - uniforms.color = tickMarkColor[0] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = X_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, xOffset, xCount) +function indexCells(triangulation, infinity) { + //First get cells and canonicalize + var cells = triangulation.cells() + var nc = cells.length + for(var i=0; i 0 || next.length > 0) { + while(active.length > 0) { + var t = active.pop() + if(flags[t] === -side) { + continue + } + flags[t] = side + var c = cells[t] + for(var j=0; j<3; ++j) { + var f = neighbor[3*t+j] + if(f >= 0 && flags[f] === 0) { + if(constraint[3*t+j]) { + next.push(f) + } else { + active.push(f) + flags[f] = side + } } } } - this.ticks = gridTicks - this.vbo.update(data) + //Swap arrays and loop + var tmp = next + next = active + active = tmp + next.length = 0 + side = -side } -})() - -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() - this.tickShader.dispose() -} -function createGrid(plot) { - var gl = plot.gl - var vbo = createBuffer(gl) - var shader = createShader(gl, shaders.gridVert, shaders.gridFrag) - var tickShader = createShader(gl, shaders.tickVert, shaders.gridFrag) - var grid = new Grid(plot, vbo, shader, tickShader) - return grid + var result = filterCells(cells, flags, target) + if(infinity) { + return result.concat(index.boundary) + } + return result } -},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197}],161:[function(require,module,exports){ +},{"binary-search-bounds":312}],359:[function(require,module,exports){ 'use strict' -module.exports = createLines +var bsearch = require('binary-search-bounds') +var orient = require('robust-orientation')[3] -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') +var EVENT_POINT = 0 +var EVENT_END = 1 +var EVENT_START = 2 -var shaders = require('./shaders') +module.exports = monotoneTriangulate -function Lines(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader +//A partial convex hull fragment, made of two unimonotone polygons +function PartialHull(a, b, idx, lowerIds, upperIds) { + this.a = a + this.b = b + this.idx = idx + this.lowerIds = lowerIds + this.upperIds = upperIds } -var proto = Lines.prototype - -proto.bind = function() { - var shader = this.shader - this.vbo.bind() - this.shader.bind() - shader.attributes.coord.pointer() - shader.uniforms.screenBox = this.plot.screenBox +//An event in the sweep line procedure +function Event(a, b, type, idx) { + this.a = a + this.b = b + this.type = type + this.idx = idx } -proto.drawLine = (function() { - var start = [0,0] - var end = [0,0] - return function(startX, startY, endX, endY, width, color) { - var plot = this.plot - var shader = this.shader - var gl = plot.gl - - start[0] = startX - start[1] = startY - end[0] = endX - end[1] = endY - - shader.uniforms.start = start - shader.uniforms.end = end - shader.uniforms.width = width * plot.pixelRatio - shader.uniforms.color = color - - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) +//This is used to compare events for the sweep line procedure +// Points are: +// 1. sorted lexicographically +// 2. sorted by type (point < end < start) +// 3. segments sorted by winding order +// 4. sorted by index +function compareEvent(a, b) { + var d = + (a.a[0] - b.a[0]) || + (a.a[1] - b.a[1]) || + (a.type - b.type) + if(d) { return d } + if(a.type !== EVENT_POINT) { + d = orient(a.a, a.b, b.b) + if(d) { return d } } -}()) - -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() + return a.idx - b.idx } -function createLines(plot) { - var gl = plot.gl - var vbo = createBuffer(gl, [ - -1,-1, - -1,1, - 1,-1, - 1,1]) - var shader = createShader(gl, shaders.lineVert, shaders.lineFrag) - var lines = new Lines(plot, vbo, shader) - return lines +function testPoint(hull, p) { + return orient(hull.a, hull.b, p) } -},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],162:[function(require,module,exports){ -'use strict' - - +function addPoint(cells, hulls, points, p, idx) { + var lo = bsearch.lt(hulls, p, testPoint) + var hi = bsearch.gt(hulls, p, testPoint) + for(var i=lo; i 1 && orient( + points[lowerIds[m-2]], + points[lowerIds[m-1]], + p) > 0) { + cells.push( + [lowerIds[m-1], + lowerIds[m-2], + idx]) + m -= 1 + } + lowerIds.length = m + lowerIds.push(idx) -module.exports = { - lineVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n", - lineFrag: FRAGMENT, - textVert: "#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n", - textFrag: FRAGMENT, - gridVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n", - gridFrag: FRAGMENT, - boxVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n", - tickVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n" + //Insert p into upper hull + var upperIds = hull.upperIds + var m = upperIds.length + while(m > 1 && orient( + points[upperIds[m-2]], + points[upperIds[m-1]], + p) < 0) { + cells.push( + [upperIds[m-2], + upperIds[m-1], + idx]) + m -= 1 + } + upperIds.length = m + upperIds.push(idx) + } } -},{}],163:[function(require,module,exports){ -'use strict' - -module.exports = createTextElements - -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') -var getText = require('text-cache') -var bsearch = require('binary-search-bounds') -var shaders = require('./shaders') - -function TextElements(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader - this.tickOffset = [[],[]] - this.tickX = [[],[]] - this.labelOffset = [0,0] - this.labelCount = [0,0] +function findSplit(hull, edge) { + var d + if(hull.a[0] < edge.a[0]) { + d = orient(hull.a, hull.b, edge.a) + } else { + d = orient(edge.b, edge.a, hull.a) + } + if(d) { return d } + if(edge.b[0] < hull.b[0]) { + d = orient(hull.a, hull.b, edge.b) + } else { + d = orient(edge.b, edge.a, hull.b) + } + return d || hull.idx - edge.idx } -var proto = TextElements.prototype - -proto.drawTicks = (function() { - var DATA_AXIS = [0,0] - var SCREEN_OFFSET = [0,0] - var ZERO_2 = [0,0] +function splitHulls(hulls, points, event) { + var splitIdx = bsearch.le(hulls, event, findSplit) + var hull = hulls[splitIdx] + var upperIds = hull.upperIds + var x = upperIds[upperIds.length-1] + hull.upperIds = [x] + hulls.splice(splitIdx+1, 0, + new PartialHull(event.a, event.b, event.idx, [x], upperIds)) +} - return function(axis) { - var plot = this.plot - var shader = this.shader - var tickX = this.tickX[axis] - var tickOffset = this.tickOffset[axis] - var gl = plot.gl - var viewBox = plot.viewBox - var dataBox = plot.dataBox - var screenBox = plot.screenBox - var pixelRatio = plot.pixelRatio - var tickEnable = plot.tickEnable - var tickPad = plot.tickPad - var textColor = plot.tickColor - var textAngle = plot.tickAngle - var tickLength = plot.tickMarkLength - var labelEnable = plot.labelEnable - var labelPad = plot.labelPad - var labelColor = plot.labelColor - var labelAngle = plot.labelAngle - var labelOffset = this.labelOffset[axis] - var labelCount = this.labelCount[axis] +function mergeHulls(hulls, points, event) { + //Swap pointers for merge search + var tmp = event.a + event.a = event.b + event.b = tmp + var mergeIdx = bsearch.eq(hulls, event, findSplit) + var upper = hulls[mergeIdx] + var lower = hulls[mergeIdx-1] + lower.upperIds = upper.upperIds + hulls.splice(mergeIdx, 1) +} - var start = bsearch.lt(tickX, dataBox[axis]) - var end = bsearch.le(tickX, dataBox[axis+2]) - DATA_AXIS[0] = DATA_AXIS[1] = 0 - DATA_AXIS[axis] = 1 +function monotoneTriangulate(points, edges) { - SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0 + var numPoints = points.length + var numEdges = edges.length - var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1] + var events = [] - SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0 - if(tickEnable[axis]) { - SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis] - if(start < end && tickOffset[end] > tickOffset[start]) { - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = textColor[axis] - shader.uniforms.angle = textAngle[axis] - gl.drawArrays( - gl.TRIANGLES, - tickOffset[start], - tickOffset[end] - tickOffset[start]) - } - } - if(labelEnable[axis] && labelCount) { - SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis] - shader.uniforms.dataAxis = ZERO_2 - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = labelColor[axis] - shader.uniforms.angle = labelAngle[axis] - gl.drawArrays( - gl.TRIANGLES, - labelOffset, - labelCount) - } + //Create point events + for(var i=0; i tickOffset[start]) { - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = textColor[axis+2] - shader.uniforms.angle = textAngle[axis+2] - gl.drawArrays( - gl.TRIANGLES, - tickOffset[start], - tickOffset[end] - tickOffset[start]) - } - } - if(labelEnable[axis+2] && labelCount) { - SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2] - shader.uniforms.dataAxis = ZERO_2 - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = labelColor[axis+2] - shader.uniforms.angle = labelAngle[axis+2] - gl.drawArrays( - gl.TRIANGLES, - labelOffset, - labelCount) + //Create edge events + for(var i=0; i b[0]) { + events.push( + new Event(b, a, EVENT_START, i), + new Event(a, b, EVENT_END, i)) } - } -})() - -proto.drawTitle = (function() { - var DATA_AXIS = [0,0] - var SCREEN_OFFSET = [0,0] - return function() { - var plot = this.plot - var shader = this.shader - var gl = plot.gl - var screenBox = plot.screenBox - var titleCenter = plot.titleCenter - var titleAngle = plot.titleAngle - var titleColor = plot.titleColor - var titleCenter = plot.titleCenter - var pixelRatio = plot.pixelRatio + //Sort events + events.sort(compareEvent) - if(!this.titleCount) { - return - } + //Initialize hull + var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52) + var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ] - for(var i=0; i<2; ++i) { - SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) / - (screenBox[2+i] - screenBox[i]) - 1 + //Process events in order + var cells = [] + for(var i=0, numEvents=events.length; i= 0 } })() -proto.update = function(options) { - var vertices = [] - var axesTicks = options.ticks - var bounds = options.bounds +proto.removeTriangle = function(i, j, k) { + var stars = this.stars + removePair(stars[i], j, k) + removePair(stars[j], k, i) + removePair(stars[k], i, j) +} - for(var dimension=0; dimension<2; ++dimension) { - var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity] +proto.addTriangle = function(i, j, k) { + var stars = this.stars + stars[i].push(j, k) + stars[j].push(k, i) + stars[k].push(i, j) +} - //Copy vertices over to buffer - var ticks = axesTicks[dimension] - for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") + } } -},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197,"text-cache":273}],164:[function(require,module,exports){ -arguments[4][62][0].apply(exports,arguments) -},{"dup":62}],165:[function(require,module,exports){ -'use strict' +function makeProduct(a, b) { + if(a.charAt(0) === "m") { + if(b.charAt(0) === "w") { + var toks = a.split("[") + return ["w", b.substr(1), "m", toks[0].substr(1)].join("") + } else { + return ["prod(", a, ",", b, ")"].join("") + } + } else { + return makeProduct(b, a) + } +} -module.exports = createGLPlot2D +function sign(s) { + if(s & 1 !== 0) { + return "-" + } + return "" +} -var createPick = require('gl-select-static') +function determinant(m) { + if(m.length === 2) { + return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] + } else { + var expr = [] + for(var i=0; i= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } + } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } + } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + } + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g +} +},{}],365:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],366:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56}],367:[function(require,module,exports){ +'use strict' - //Drawing parameters - this.grid = null - this.text = null - this.line = null - this.box = null - this.objects = [] - this.overlays = [] +module.exports = cleanPSLG - this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] +var UnionFind = require('union-find') +var boxIntersect = require('box-intersect') +var compareCell = require('compare-cell') +var segseg = require('robust-segment-intersect') +var rat = require('big-rat') +var ratCmp = require('big-rat/cmp') +var ratToFloat = require('big-rat/to-float') +var ratVec = require('rat-vec') +var nextafter = require('nextafter') - this.dirty = false - this.pickDirty = false - this.pickDelay = 120 - this.pickRadius = 10 - this._pickTimeout = null - this._drawPick = this.drawPick.bind(this) +var solveIntersection = require('./lib/rat-seg-intersect') - this._depthCounter = 0 +//Bounds on a rational number when rounded to a float +function boundRat(r) { + var f = ratToFloat(r) + var cmp = ratCmp(rat(f), r) + if(cmp < 0) { + return [f, nextafter(f, Infinity)] + } else if(cmp > 0) { + return [nextafter(f, -Infinity), f] + } else { + return [f, f] + } } -var proto = GLPlot2D.prototype - -proto.setDirty = function() { - this.dirty = this.pickDirty = true +//Convert a list of edges in a pslg to bounding boxes +function boundEdges(points, edges) { + var bounds = new Array(edges.length) + for(var i=0; i= floatPoints.length) { + return ratPoints[idx-floatPoints.length] + } + var p = floatPoints[idx] + return [ rat(p[0]), rat(p[1]) ] } - this.dirty = false + junctions.sort(function(a, b) { + if(a[0] !== b[0]) { + return a[0] - b[0] + } + var u = getPoint(a[1]) + var v = getPoint(b[1]) + return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1]) + }) - gl.bindFramebuffer(gl.FRAMEBUFFER, null) + //Split edges along junctions + for(var i=junctions.length-1; i>=0; --i) { + var junction = junctions[i] + var e = junction[0] - //Turn on scissor - gl.enable(gl.SCISSOR_TEST) + var edge = edges[e] + var s = edge[0] + var t = edge[1] - //Turn off depth buffer - gl.disable(gl.DEPTH_TEST) - gl.depthFunc(gl.LESS) - gl.depthMask(false) + //Check if edge is not lexicographically sorted + var a = floatPoints[s] + var b = floatPoints[t] + if(((a[0] - b[0]) || (a[1] - b[1])) < 0) { + var tmp = s + s = t + t = tmp + } - //Configure premultiplied alpha blending - gl.enable(gl.BLEND) - gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + //Split leading edge + edge[0] = s + var last = edge[1] = junction[1] - //Draw border - gl.scissor( - screenBox[0], - screenBox[1], - screenBox[2]-screenBox[0], - screenBox[3]-screenBox[1]) - var borderColor = this.borderColor - gl.clearColor( - borderColor[0]*borderColor[3], - borderColor[1]*borderColor[3], - borderColor[2]*borderColor[3], - borderColor[3]) - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) + //If we are grouping edges by color, remember to track data + var color + if(useColor) { + color = edge[2] + } - //Draw center pane - gl.scissor( - viewPixels[0], - viewPixels[1], - viewPixels[2]-viewPixels[0], - viewPixels[3]-viewPixels[1]) - gl.viewport( - viewPixels[0], - viewPixels[1], - viewPixels[2]-viewPixels[0], - viewPixels[3]-viewPixels[1]) - var backgroundColor = this.backgroundColor - gl.clearColor( - backgroundColor[0]*backgroundColor[3], - backgroundColor[1]*backgroundColor[3], - backgroundColor[2]*backgroundColor[3], - backgroundColor[3]) - gl.clear(gl.COLOR_BUFFER_BIT) + //Split other edges + while(i > 0 && junctions[i-1][0] === e) { + var junction = junctions[--i] + var next = junction[1] + if(useColor) { + edges.push([last, next, color]) + } else { + edges.push([last, next]) + } + last = next + } - //Draw grid - grid.draw() + //Add final edge + if(useColor) { + edges.push([last, t, color]) + } else { + edges.push([last, t]) + } + } - //Draw zero lines separately - var zeroLineEnable = this.zeroLineEnable - var zeroLineColor = this.zeroLineColor - var zeroLineWidth = this.zeroLineWidth - if(zeroLineEnable[0] || zeroLineEnable[1]) { - line.bind() - for(var i=0; i<2; ++i) { - if(!zeroLineEnable[i] || - !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) { - continue - } + //Return constructed rational points + return ratPoints +} - var zeroIntercept = screenBox[i] - - dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) +//Merge overlapping points +function dedupPoints(floatPoints, ratPoints, floatBounds) { + var numPoints = floatPoints.length + ratPoints.length + var uf = new UnionFind(numPoints) - if(i === 0) { - line.drawLine( - zeroIntercept, screenBox[1], zeroIntercept, screenBox[3], - zeroLineWidth[i], - zeroLineColor[i]) - } else { - line.drawLine( - screenBox[0], zeroIntercept, screenBox[2], zeroIntercept, - zeroLineWidth[i], - zeroLineColor[i]) - } - } + //Compute rational bounds + var bounds = floatBounds + for(var i=0; i b[2]) { + return 1 } - if(borderLineEnable[3]) { - line.drawLine( - viewPixels[2], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio, - viewPixels[2], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio, - borderLineWidth[3], borderLineColor[3]) + return 0 +} + +//Remove duplicate edge labels +function dedupEdges(edges, labels, useColor) { + if(edges.length === 0) { + return } - if(borderLineEnable[2]) { - line.drawLine( - viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[3], - viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[3], - borderLineWidth[2], borderLineColor[2]) + if(labels) { + for(var i=0; i 0 || tjunctions.length > 0) } - pickBuffer.end() + // More iterations necessary + return true } -})() - -proto.pick = (function() { -return function(x, y) { - var pixelRatio = this.pixelRatio - var pickPixelRatio = this.pickPixelRatio - var viewBox = this.viewBox - var scrX = Math.round((x - viewBox[0] / pixelRatio) * pickPixelRatio)|0 - var scrY = Math.round((y - viewBox[1] / pixelRatio) * pickPixelRatio)|0 +//Main loop, runs PSLG clean up until completion +function cleanPSLG(points, edges, colors) { + var modified = false - var pickResult = this.pickBuffer.query(scrX, scrY, this.pickRadius) - if(!pickResult) { - return null + //If using colors, augment edges with color data + var prevEdges + if(colors) { + prevEdges = edges + var augEdges = new Array(edges.length) + for(var i=0; i=0; --i) { - this.objects[i].dispose() + var shift = 0 + var a, b + if(isBN(numer)) { + a = numer.clone() + } else if(typeof numer === 'string') { + a = str2bn(numer) + } else if(numer === 0) { + return [num2bn(0), num2bn(1)] + } else if(numer === Math.floor(numer)) { + a = num2bn(numer) + } else { + while(numer !== Math.floor(numer)) { + numer = numer * Math.pow(2, 256) + shift -= 256 + } + a = num2bn(numer) } - this.objects.length = 0 - for(var i=this.overlays.length-1; i>=0; --i) { - this.overlays[i].dispose() + if(isRat(denom)) { + a.mul(denom[1]) + b = denom[0].clone() + } else if(isBN(denom)) { + b = denom.clone() + } else if(typeof denom === 'string') { + b = str2bn(denom) + } else if(!denom) { + b = num2bn(1) + } else if(denom === Math.floor(denom)) { + b = num2bn(denom) + } else { + while(denom !== Math.floor(denom)) { + denom = denom * Math.pow(2, 256) + shift += 256 + } + b = num2bn(denom) } - this.overlays.length = 0 - - this.gl = null -} - -proto.addObject = function(object) { - if(this.objects.indexOf(object) < 0) { - this.objects.push(object) - this.setDirty() + if(shift > 0) { + a = a.shln(shift) + } else if(shift < 0) { + b = b.shln(-shift) } + return rationalize(a, b) } -proto.removeObject = function(object) { - var objects = this.objects - for(var i=0; i 20) { + return 52 } + return h + 32 +} - var view = createView({ - center: options.center || [0,0,0], - up: options.up || [0,1,0], - eye: options.eye || [0,0,10], - mode: options.mode || 'orbit', - distanceLimits: limits - }) +},{"bit-twiddle":382,"double-bits":384}],377:[function(require,module,exports){ +'use strict' - var pmatrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] - var distance = 0.0 - var width = element.clientWidth - var height = element.clientHeight +var BN = require('bn.js') - var camera = { - view: view, - element: element, - delay: options.delay || 16, - rotateSpeed: options.rotateSpeed || 1, - zoomSpeed: options.zoomSpeed || 1, - translateSpeed: options.translateSpeed || 1, - flipX: !!options.flipX, - flipY: !!options.flipY, - modes: view.modes, - tick: function() { - var t = now() - var delay = this.delay - view.idle(t-delay) - view.flush(t-(100+delay*2)) - var ctime = t - 2 * delay - view.recalcMatrix(ctime) - var allEqual = true - var matrix = view.computedMatrix - for(var i=0; i<16; ++i) { - allEqual = allEqual && (pmatrix[i] === matrix[i]) - pmatrix[i] = matrix[i] - } - var sizeChanged = - element.clientWidth === width && - element.clientHeight === height - width = element.clientWidth - height = element.clientHeight - if(allEqual) { - return !sizeChanged - } - distance = Math.exp(view.computedRadius[0]) - return true - }, - lookAt: function(center, eye, up) { - view.lookAt(view.lastT(), center, eye, up) - }, - rotate: function(pitch, yaw, roll) { - view.rotate(view.lastT(), pitch, yaw, roll) - }, - pan: function(dx, dy, dz) { - view.pan(view.lastT(), dx, dy, dz) - }, - translate: function(dx, dy, dz) { - view.translate(view.lastT(), dx, dy, dz) - } - } +module.exports = isBN - Object.defineProperties(camera, { - matrix: { - get: function() { - return view.computedMatrix - }, - set: function(mat) { - view.setMatrix(view.lastT(), mat) - return view.computedMatrix - }, - enumerable: true - }, - mode: { - get: function() { - return view.getMode() - }, - set: function(mode) { - view.setMode(mode) - return view.getMode() - }, - enumerable: true - }, - center: { - get: function() { - return view.computedCenter - }, - set: function(ncenter) { - view.lookAt(view.lastT(), ncenter) - return view.computedCenter - }, - enumerable: true - }, - eye: { - get: function() { - return view.computedEye - }, - set: function(neye) { - view.lookAt(view.lastT(), null, neye) - return view.computedEye - }, - enumerable: true - }, - up: { - get: function() { - return view.computedUp - }, - set: function(nup) { - view.lookAt(view.lastT(), null, null, nup) - return view.computedUp - }, - enumerable: true - }, - distance: { - get: function() { - return distance - }, - set: function(d) { - view.setDistance(view.lastT(), d) - return d - }, - enumerable: true - }, - distanceLimits: { - get: function() { - return view.getDistanceLimits(limits) - }, - set: function(v) { - view.setDistanceLimits(v) - return v - }, - enumerable: true - } - }) - - element.addEventListener('contextmenu', function(ev) { - ev.preventDefault() - return false - }) +//Test if x is a bignumber +//FIXME: obviously this is the wrong way to do it +function isBN(x) { + return x && typeof x === 'object' && Boolean(x.words) +} - var lastX = 0, lastY = 0 - mouseChange(element, function(buttons, x, y, mods) { - var scale = 1.0 / element.clientHeight - var dx = scale * (x - lastX) - var dy = scale * (y - lastY) +},{"bn.js":383}],378:[function(require,module,exports){ +'use strict' - var flipX = camera.flipX ? 1 : -1 - var flipY = camera.flipY ? 1 : -1 +var BN = require('bn.js') +var db = require('double-bits') - var drot = Math.PI * camera.rotateSpeed +module.exports = num2bn - var t = now() +function num2bn(x) { + var e = db.exponent(x) + if(e < 52) { + return new BN(x) + } else { + return (new BN(x * Math.pow(2, 52-e))).shln(e-52) + } +} - if(buttons & 1) { - if(mods.shift) { - view.rotate(t, 0, 0, -dx * drot) - } else { - view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0) - } - } else if(buttons & 2) { - view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0) - } else if(buttons & 4) { - var kzoom = camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 50.0 - view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) - } +},{"bn.js":383,"double-bits":384}],379:[function(require,module,exports){ +'use strict' - lastX = x - lastY = y - }) +var num2bn = require('./num-to-bn') +var sign = require('./bn-sign') - mouseWheel(element, function(dx, dy, dz) { - var flipX = camera.flipX ? 1 : -1 - var flipY = camera.flipY ? 1 : -1 - var t = now() - if(Math.abs(dx) > Math.abs(dy)) { - view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) - } else { - var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0 - view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) - } - }, true) +module.exports = rationalize - return camera +function rationalize(numer, denom) { + var snumer = sign(numer) + var sdenom = sign(denom) + if(snumer === 0) { + return [num2bn(0), num2bn(1)] + } + if(sdenom === 0) { + return [num2bn(0), num2bn(0)] + } + if(sdenom < 0) { + numer = numer.neg() + denom = denom.neg() + } + var d = numer.gcd(denom) + if(d.cmpn(1)) { + return [ numer.div(d), denom.div(d) ] + } + return [ numer, denom ] } -},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],168:[function(require,module,exports){ -// Copyright (C) 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/** - * @fileoverview Install a leaky WeakMap emulation on platforms that - * don't provide a built-in one. - * - *

Assumes that an ES5 platform where, if {@code WeakMap} is - * already present, then it conforms to the anticipated ES6 - * specification. To run this file on an ES5 or almost ES5 - * implementation where the {@code WeakMap} specification does not - * quite conform, run repairES5.js first. - * - *

Even though WeakMapModule is not global, the linter thinks it - * is, which is why it is in the overrides list below. - * - *

NOTE: Before using this WeakMap emulation in a non-SES - * environment, see the note below about hiddenRecord. - * - * @author Mark S. Miller - * @requires crypto, ArrayBuffer, Uint8Array, navigator, console - * @overrides WeakMap, ses, Proxy - * @overrides WeakMapModule - */ +},{"./bn-sign":374,"./num-to-bn":378}],380:[function(require,module,exports){ +'use strict' -/** - * This {@code WeakMap} emulation is observably equivalent to the - * ES-Harmony WeakMap, but with leakier garbage collection properties. - * - *

As with true WeakMaps, in this emulation, a key does not - * retain maps indexed by that key and (crucially) a map does not - * retain the keys it indexes. A map by itself also does not retain - * the values associated with that map. - * - *

However, the values associated with a key in some map are - * retained so long as that key is retained and those associations are - * not overridden. For example, when used to support membranes, all - * values exported from a given membrane will live for the lifetime - * they would have had in the absence of an interposed membrane. Even - * when the membrane is revoked, all objects that would have been - * reachable in the absence of revocation will still be reachable, as - * far as the GC can tell, even though they will no longer be relevant - * to ongoing computation. - * - *

The API implemented here is approximately the API as implemented - * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, - * rather than the offially approved proposal page. TODO(erights): - * upgrade the ecmascript WeakMap proposal page to explain this API - * change and present to EcmaScript committee for their approval. - * - *

The first difference between the emulation here and that in - * FF6.0a1 is the presence of non enumerable {@code get___, has___, - * set___, and delete___} methods on WeakMap instances to represent - * what would be the hidden internal properties of a primitive - * implementation. Whereas the FF6.0a1 WeakMap.prototype methods - * require their {@code this} to be a genuine WeakMap instance (i.e., - * an object of {@code [[Class]]} "WeakMap}), since there is nothing - * unforgeable about the pseudo-internal method names used here, - * nothing prevents these emulated prototype methods from being - * applied to non-WeakMaps with pseudo-internal methods of the same - * names. - * - *

Another difference is that our emulated {@code - * WeakMap.prototype} is not itself a WeakMap. A problem with the - * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap - * providing ambient mutability and an ambient communications - * channel. Thus, if a WeakMap is already present and has this - * problem, repairES5.js wraps it in a safe wrappper in order to - * prevent access to this channel. (See - * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). - */ +var BN = require('bn.js') -/** - * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is - * absent, install an approximate emulation. - * - *

If WeakMap is present but cannot store some objects, use our approximate - * emulation as a wrapper. - * - *

If this is almost a secureable ES5 platform, then WeakMap.js - * should be run after repairES5.js. - * - *

See {@code WeakMap} for documentation of the garbage collection - * properties of this WeakMap emulation. - */ -(function WeakMapModule() { - "use strict"; +module.exports = str2BN - if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { - // already too broken, so give up - return; +function str2BN(x) { + return new BN(x) +} + +},{"bn.js":383}],381:[function(require,module,exports){ +'use strict' + +var rationalize = require('./lib/rationalize') + +module.exports = mul + +function mul(a, b) { + return rationalize(a[0].mul(b[0]), a[1].mul(b[1])) +} + +},{"./lib/rationalize":379}],382:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],383:[function(require,module,exports){ +(function (module, exports) { + +'use strict'; + +// Utils + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +// Could use `inherits` module, but don't want to move from single file +// architecture yet. +function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; +} + +// BN + +function BN(number, base, endian) { + // May be `new BN(bn)` ? + if (number !== null && + typeof number === 'object' && + Array.isArray(number.words)) { + return number; } - /** - * In some cases (current Firefox), we must make a choice betweeen a - * WeakMap which is capable of using all varieties of host objects as - * keys and one which is capable of safely using proxies as keys. See - * comments below about HostWeakMap and DoubleWeakMap for details. - * - * This function (which is a global, not exposed to guests) marks a - * WeakMap as permitted to do what is necessary to index all host - * objects, at the cost of making it unsafe for proxies. - * - * Do not apply this function to anything which is not a genuine - * fresh WeakMap. - */ - function weakMapPermitHostObjects(map) { - // identity of function used as a secret -- good enough and cheap - if (map.permitHostObjects___) { - map.permitHostObjects___(weakMapPermitHostObjects); - } + this.sign = false; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (base === 'le' || base === 'be') { + endian = base; + base = 10; } - if (typeof ses !== 'undefined') { - ses.weakMapPermitHostObjects = weakMapPermitHostObjects; + + if (number !== null) + this._init(number || 0, base || 10, endian || 'be'); +} +if (typeof module === 'object') + module.exports = BN; +else + exports.BN = BN; + +BN.BN = BN; +BN.wordSize = 26; + +BN.prototype._init = function init(number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } else if (typeof number === 'object') { + return this._initArray(number, base, endian); } + if (base === 'hex') + base = 16; + assert(base === (base | 0) && base >= 2 && base <= 36); - // IE 11 has no Proxy but has a broken WeakMap such that we need to patch - // it using DoubleWeakMap; this flag tells DoubleWeakMap so. - var doubleWeakMapCheckSilentFailure = false; + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') + start++; - // Check if there is already a good-enough WeakMap implementation, and if so - // exit without replacing it. - if (typeof WeakMap === 'function') { - var HostWeakMap = WeakMap; - // There is a WeakMap -- is it good enough? - if (typeof navigator !== 'undefined' && - /Firefox/.test(navigator.userAgent)) { - // We're now *assuming not*, because as of this writing (2013-05-06) - // Firefox's WeakMaps have a miscellany of objects they won't accept, and - // we don't want to make an exhaustive list, and testing for just one - // will be a problem if that one is fixed alone (as they did for Event). + if (base === 16) + this._parseHex(number, start); + else + this._parseBase(number, base, start); - // If there is a platform that we *can* reliably test on, here's how to - // do it: - // var problematic = ... ; - // var testHostMap = new HostWeakMap(); - // try { - // testHostMap.set(problematic, 1); // Firefox 20 will throw here - // if (testHostMap.get(problematic) === 1) { - // return; - // } - // } catch (e) {} + if (number[0] === '-') + this.sign = true; - } else { - // IE 11 bug: WeakMaps silently fail to store frozen objects. - var testMap = new HostWeakMap(); - var testObject = Object.freeze({}); - testMap.set(testObject, 1); - if (testMap.get(testObject) !== 1) { - doubleWeakMapCheckSilentFailure = true; - // Fall through to installing our WeakMap. - } else { - module.exports = WeakMap; - return; - } - } - } + this.strip(); - var hop = Object.prototype.hasOwnProperty; - var gopn = Object.getOwnPropertyNames; - var defProp = Object.defineProperty; - var isExtensible = Object.isExtensible; + if (endian !== 'le') + return; - /** - * Security depends on HIDDEN_NAME being both unguessable and - * undiscoverable by untrusted code. - * - *

Given the known weaknesses of Math.random() on existing - * browsers, it does not generate unguessability we can be confident - * of. - * - *

It is the monkey patching logic in this file that is intended - * to ensure undiscoverability. The basic idea is that there are - * three fundamental means of discovering properties of an object: - * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), - * as well as some proposed ES6 extensions that appear on our - * whitelist. The first two only discover enumerable properties, and - * we only use HIDDEN_NAME to name a non-enumerable property, so the - * only remaining threat should be getOwnPropertyNames and some - * proposed ES6 extensions that appear on our whitelist. We monkey - * patch them to remove HIDDEN_NAME from the list of properties they - * returns. - * - *

TODO(erights): On a platform with built-in Proxies, proxies - * could be used to trap and thereby discover the HIDDEN_NAME, so we - * need to monkey patch Proxy.create, Proxy.createFunction, etc, in - * order to wrap the provided handler with the real handler which - * filters out all traps using HIDDEN_NAME. - * - *

TODO(erights): Revisit Mike Stay's suggestion that we use an - * encapsulated function at a not-necessarily-secret name, which - * uses the Stiegler shared-state rights amplification pattern to - * reveal the associated value only to the WeakMap in which this key - * is associated with that value. Since only the key retains the - * function, the function can also remember the key without causing - * leakage of the key, so this doesn't violate our general gc - * goals. In addition, because the name need not be a guarded - * secret, we could efficiently handle cross-frame frozen keys. - */ - var HIDDEN_NAME_PREFIX = 'weakmap:'; - var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; + this._initArray(this.toArray(), base, endian); +}; - if (typeof crypto !== 'undefined' && - typeof crypto.getRandomValues === 'function' && - typeof ArrayBuffer === 'function' && - typeof Uint8Array === 'function') { - var ab = new ArrayBuffer(25); - var u8s = new Uint8Array(ab); - crypto.getRandomValues(u8s); - HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + - Array.prototype.map.call(u8s, function(u8) { - return (u8 % 36).toString(36); - }).join('') + '___'; +BN.prototype._initNumber = function _initNumber(number, base, endian) { + if (number < 0) { + this.sign = true; + number = -number; } - - function isNotHiddenName(name) { - return !( - name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && - name.substr(name.length - 3) === '___'); + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; } - /** - * Monkey patch getOwnPropertyNames to avoid revealing the - * HIDDEN_NAME. - * - *

The ES5.1 spec requires each name to appear only once, but as - * of this writing, this requirement is controversial for ES6, so we - * made this code robust against this case. If the resulting extra - * search turns out to be expensive, we can probably relax this once - * ES6 is adequately supported on all major browsers, iff no browser - * versions we support at that time have relaxed this constraint - * without providing built-in ES6 WeakMaps. - */ - defProp(Object, 'getOwnPropertyNames', { - value: function fakeGetOwnPropertyNames(obj) { - return gopn(obj).filter(isNotHiddenName); - } - }); + if (endian !== 'le') + return; - /** - * getPropertyNames is not in ES5 but it is proposed for ES6 and - * does appear in our whitelist, so we need to clean it too. - */ - if ('getPropertyNames' in Object) { - var originalGetPropertyNames = Object.getPropertyNames; - defProp(Object, 'getPropertyNames', { - value: function fakeGetPropertyNames(obj) { - return originalGetPropertyNames(obj).filter(isNotHiddenName); - } - }); + // Reverse the bytes + this._initArray(this.toArray(), base, endian); +}; + +BN.prototype._initArray = function _initArray(number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; } - /** - *

To treat objects as identity-keys with reasonable efficiency - * on ES5 by itself (i.e., without any object-keyed collections), we - * need to add a hidden property to such key objects when we - * can. This raises several issues: - *

    - *
  • Arranging to add this property to objects before we lose the - * chance, and - *
  • Hiding the existence of this new property from most - * JavaScript code. - *
  • Preventing certification theft, where one object is - * created falsely claiming to be the key of an association - * actually keyed by another object. - *
  • Preventing value theft, where untrusted code with - * access to a key object but not a weak map nevertheless - * obtains access to the value associated with that key in that - * weak map. - *
- * We do so by - *
    - *
  • Making the name of the hidden property unguessable, so "[]" - * indexing, which we cannot intercept, cannot be used to access - * a property without knowing the name. - *
  • Making the hidden property non-enumerable, so we need not - * worry about for-in loops or {@code Object.keys}, - *
  • monkey patching those reflective methods that would - * prevent extensions, to add this hidden property first, - *
  • monkey patching those methods that would reveal this - * hidden property. - *
- * Unfortunately, because of same-origin iframes, we cannot reliably - * add this hidden property before an object becomes - * non-extensible. Instead, if we encounter a non-extensible object - * without a hidden record that we can detect (whether or not it has - * a hidden record stored under a name secret to us), then we just - * use the key object itself to represent its identity in a brute - * force leaky map stored in the weak map, losing all the advantages - * of weakness for these. - */ - function getHiddenRecord(key) { - if (key !== Object(key)) { - throw new TypeError('Not an object: ' + key); + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + var off = 0; + if (endian === 'be') { + for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { + var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } } - var hiddenRecord = key[HIDDEN_NAME]; - if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } - if (!isExtensible(key)) { - // Weak map must brute force, as explained in doc-comment above. - return void 0; + } else if (endian === 'le') { + for (var i = 0, j = 0; i < number.length; i += 3) { + var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; + } } + } + return this.strip(); +}; - // The hiddenRecord and the key point directly at each other, via - // the "key" and HIDDEN_NAME properties respectively. The key - // field is for quickly verifying that this hidden record is an - // own property, not a hidden record from up the prototype chain. - // - // NOTE: Because this WeakMap emulation is meant only for systems like - // SES where Object.prototype is frozen without any numeric - // properties, it is ok to use an object literal for the hiddenRecord. - // This has two advantages: - // * It is much faster in a performance critical place - // * It avoids relying on Object.create(null), which had been - // problematic on Chrome 28.0.1480.0. See - // https://code.google.com/p/google-caja/issues/detail?id=1687 - hiddenRecord = { key: key }; - - // When using this WeakMap emulation on platforms where - // Object.prototype might not be frozen and Object.create(null) is - // reliable, use the following two commented out lines instead. - // hiddenRecord = Object.create(null); - // hiddenRecord.key = key; +function parseHex(str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; - // Please contact us if you need this to work on platforms where - // Object.prototype might not be frozen and - // Object.create(null) might not be reliable. + r <<= 4; - try { - defProp(key, HIDDEN_NAME, { - value: hiddenRecord, - writable: false, - enumerable: false, - configurable: false - }); - return hiddenRecord; - } catch (error) { - // Under some circumstances, isExtensible seems to misreport whether - // the HIDDEN_NAME can be defined. - // The circumstances have not been isolated, but at least affect - // Node.js v0.10.26 on TravisCI / Linux, but not the same version of - // Node.js on OS X. - return void 0; - } - } + // 'a' - 'f' + if (c >= 49 && c <= 54) + r |= c - 49 + 0xa; - /** - * Monkey patch operations that would make their argument - * non-extensible. - * - *

The monkey patched versions throw a TypeError if their - * argument is not an object, so it should only be done to functions - * that should throw a TypeError anyway if their argument is not an - * object. - */ - (function(){ - var oldFreeze = Object.freeze; - defProp(Object, 'freeze', { - value: function identifyingFreeze(obj) { - getHiddenRecord(obj); - return oldFreeze(obj); - } - }); - var oldSeal = Object.seal; - defProp(Object, 'seal', { - value: function identifyingSeal(obj) { - getHiddenRecord(obj); - return oldSeal(obj); - } - }); - var oldPreventExtensions = Object.preventExtensions; - defProp(Object, 'preventExtensions', { - value: function identifyingPreventExtensions(obj) { - getHiddenRecord(obj); - return oldPreventExtensions(obj); - } - }); - })(); + // 'A' - 'F' + else if (c >= 17 && c <= 22) + r |= c - 17 + 0xa; - function constFunc(func) { - func.prototype = null; - return Object.freeze(func); + // '0' - '9' + else + r |= c & 0xf; } + return r; +} - var calledAsFunctionWarningDone = false; - function calledAsFunctionWarning() { - // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() - // but we used to permit it and do it ourselves, so warn only. - if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { - calledAsFunctionWarningDone = true; - console.warn('WeakMap should be invoked as new WeakMap(), not ' + - 'WeakMap(). This will be an error in the future.'); +BN.prototype._parseHex = function _parseHex(number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Scan 24-bit chunks and add them to the number + var off = 0; + for (var i = number.length - 6, j = 0; i >= start; i -= 6) { + var w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; } } + if (i + 6 !== start) { + var w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); +}; - var nextId = 0; +function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; - var OurWeakMap = function() { - if (!(this instanceof OurWeakMap)) { // approximate test for new ...() - calledAsFunctionWarning(); - } + r *= mul; - // We are currently (12/25/2012) never encountering any prematurely - // non-extensible keys. - var keys = []; // brute force for prematurely non-extensible keys. - var values = []; // brute force for corresponding values. - var id = nextId++; + // 'a' + if (c >= 49) + r += c - 49 + 0xa; - function get___(key, opt_default) { - var index; - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - return id in hiddenRecord ? hiddenRecord[id] : opt_default; - } else { - index = keys.indexOf(key); - return index >= 0 ? values[index] : opt_default; - } - } + // 'A' + else if (c >= 17) + r += c - 17 + 0xa; - function has___(key) { - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - return id in hiddenRecord; - } else { - return keys.indexOf(key) >= 0; - } - } + // '0' - '9' + else + r += c; + } + return r; +} - function set___(key, value) { - var index; - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - hiddenRecord[id] = value; - } else { - index = keys.indexOf(key); - if (index >= 0) { - values[index] = value; - } else { - // Since some browsers preemptively terminate slow turns but - // then continue computing with presumably corrupted heap - // state, we here defensively get keys.length first and then - // use it to update both the values and keys arrays, keeping - // them in sync. - index = keys.length; - values[index] = value; - // If we crash here, values will be one longer than keys. - keys[index] = key; - } - } - return this; - } +BN.prototype._parseBase = function _parseBase(number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; - function delete___(key) { - var hiddenRecord = getHiddenRecord(key); - var index, lastIndex; - if (hiddenRecord) { - return id in hiddenRecord && delete hiddenRecord[id]; - } else { - index = keys.indexOf(key); - if (index < 0) { - return false; - } - // Since some browsers preemptively terminate slow turns but - // then continue computing with potentially corrupted heap - // state, we here defensively get keys.length first and then use - // it to update both the keys and the values array, keeping - // them in sync. We update the two with an order of assignments, - // such that any prefix of these assignments will preserve the - // key/value correspondence, either before or after the delete. - // Note that this needs to work correctly when index === lastIndex. - lastIndex = keys.length - 1; - keys[index] = void 0; - // If we crash here, there's a void 0 in the keys array, but - // no operation will cause a "keys.indexOf(void 0)", since - // getHiddenRecord(void 0) will always throw an error first. - values[index] = values[lastIndex]; - // If we crash here, values[index] cannot be found here, - // because keys[index] is void 0. - keys[index] = keys[lastIndex]; - // If index === lastIndex and we crash here, then keys[index] - // is still void 0, since the aliasing killed the previous key. - keys.length = lastIndex; - // If we crash here, keys will be one shorter than values. - values.length = lastIndex; - return true; - } - } + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) + limbLen++; + limbLen--; + limbPow = (limbPow / base) | 0; - return Object.create(OurWeakMap.prototype, { - get___: { value: constFunc(get___) }, - has___: { value: constFunc(has___) }, - set___: { value: constFunc(set___) }, - delete___: { value: constFunc(delete___) } - }); - }; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; - OurWeakMap.prototype = Object.create(Object.prototype, { - get: { - /** - * Return the value most recently associated with key, or - * opt_default if none. - */ - value: function get(key, opt_default) { - return this.get___(key, opt_default); - }, - writable: true, - configurable: true - }, + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); - has: { - /** - * Is there a value associated with key in this WeakMap? - */ - value: function has(key) { - return this.has___(key); - }, - writable: true, - configurable: true - }, + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) + this.words[0] += word; + else + this._iaddn(word); + } - set: { - /** - * Associate value with key in this WeakMap, overwriting any - * previous association if present. - */ - value: function set(key, value) { - return this.set___(key, value); - }, - writable: true, - configurable: true - }, + if (mod !== 0) { + var pow = 1; + var word = parseBase(number, i, number.length, base); - 'delete': { - /** - * Remove any association for key in this WeakMap, returning - * whether there was one. - * - *

Note that the boolean return here does not work like the - * {@code delete} operator. The {@code delete} operator returns - * whether the deletion succeeds at bringing about a state in - * which the deleted property is absent. The {@code delete} - * operator therefore returns true if the property was already - * absent, whereas this {@code delete} method returns false if - * the association was already absent. - */ - value: function remove(key) { - return this.delete___(key); - }, - writable: true, - configurable: true - } - }); + for (var i = 0; i < mod; i++) + pow *= base; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) + this.words[0] += word; + else + this._iaddn(word); + } +}; - if (typeof HostWeakMap === 'function') { - (function() { - // If we got here, then the platform has a WeakMap but we are concerned - // that it may refuse to store some key types. Therefore, make a map - // implementation which makes use of both as possible. +BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + dest.words[i] = this.words[i]; + dest.length = this.length; + dest.sign = this.sign; + dest.red = this.red; +}; - // In this mode we are always using double maps, so we are not proxy-safe. - // This combination does not occur in any known browser, but we had best - // be safe. - if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { - Proxy = undefined; - } +BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; +}; - function DoubleWeakMap() { - if (!(this instanceof OurWeakMap)) { // approximate test for new ...() - calledAsFunctionWarning(); - } +// Remove leading `0` from `this` +BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) + this.length--; + return this._normSign(); +}; - // Preferable, truly weak map. - var hmap = new HostWeakMap(); +BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) + this.sign = false; + return this; +}; - // Our hidden-property-based pseudo-weak-map. Lazily initialized in the - // 'set' implementation; thus we can avoid performing extra lookups if - // we know all entries actually stored are entered in 'hmap'. - var omap = undefined; +BN.prototype.inspect = function inspect() { + return (this.red ? ''; +}; - // Hidden-property maps are not compatible with proxies because proxies - // can observe the hidden name and either accidentally expose it or fail - // to allow the hidden property to be set. Therefore, we do not allow - // arbitrary WeakMaps to switch to using hidden properties, but only - // those which need the ability, and unprivileged code is not allowed - // to set the flag. - // - // (Except in doubleWeakMapCheckSilentFailure mode in which case we - // disable proxies.) - var enableSwitching = false; +/* - function dget(key, opt_default) { - if (omap) { - return hmap.has(key) ? hmap.get(key) - : omap.get___(key, opt_default); - } else { - return hmap.get(key, opt_default); - } - } +var zeros = []; +var groupSizes = []; +var groupBases = []; - function dhas(key) { - return hmap.has(key) || (omap ? omap.has___(key) : false); - } +var s = ''; +var i = -1; +while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; +} +groupSizes[0] = 0; +groupSizes[1] = 0; +groupBases[0] = 0; +groupBases[1] = 0; +var base = 2 - 1; +while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; +} - var dset; - if (doubleWeakMapCheckSilentFailure) { - dset = function(key, value) { - hmap.set(key, value); - if (!hmap.has(key)) { - if (!omap) { omap = new OurWeakMap(); } - omap.set(key, value); - } - return this; - }; - } else { - dset = function(key, value) { - if (enableSwitching) { - try { - hmap.set(key, value); - } catch (e) { - if (!omap) { omap = new OurWeakMap(); } - omap.set___(key, value); - } - } else { - hmap.set(key, value); - } - return this; - }; - } +*/ - function ddelete(key) { - var result = !!hmap['delete'](key); - if (omap) { return omap.delete___(key) || result; } - return result; - } +var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' +]; - return Object.create(OurWeakMap.prototype, { - get___: { value: constFunc(dget) }, - has___: { value: constFunc(dhas) }, - set___: { value: constFunc(dset) }, - delete___: { value: constFunc(ddelete) }, - permitHostObjects___: { value: constFunc(function(token) { - if (token === weakMapPermitHostObjects) { - enableSwitching = true; - } else { - throw new Error('bogus call to permitHostObjects___'); - } - })} - }); - } - DoubleWeakMap.prototype = OurWeakMap.prototype; - module.exports = DoubleWeakMap; +var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 +]; - // define .constructor to hide OurWeakMap ctor - Object.defineProperty(WeakMap.prototype, 'constructor', { - value: WeakMap, - enumerable: false, // as default .constructor is - configurable: true, - writable: true - }); - })(); - } else { - // There is no host WeakMap, so we must use the emulation. +var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 +]; - // Emulated WeakMaps are incompatible with native proxies (because proxies - // can observe the hidden name), so we must disable Proxy usage (in - // ArrayLike and Domado, currently). - if (typeof Proxy !== 'undefined') { - Proxy = undefined; +BN.prototype.toString = function toString(base, padding) { + base = base || 10; + if (base === 16 || base === 'hex') { + var out = ''; + var off = 0; + var padding = padding | 0 || 1; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) + out = zeros[6 - word.length] + word + out; + else + out = word + out; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } } + if (carry !== 0) + out = carry.toString(16) + out; + while (out.length % padding !== 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + var out = ''; + var c = this.clone(); + c.sign = false; + while (c.cmpn(0) !== 0) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); - module.exports = OurWeakMap; + if (c.cmpn(0) !== 0) + out = zeros[groupSize - r.length] + r + out; + else + out = r + out; + } + if (this.cmpn(0) === 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else { + assert(false, 'Base should be between 2 and 36'); } -})(); +}; -},{}],169:[function(require,module,exports){ -'use strict' +BN.prototype.toJSON = function toJSON() { + return this.toString(16); +}; -var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') +BN.prototype.toArray = function toArray(endian) { + this.strip(); + var res = new Array(this.byteLength()); + res[0] = 0; -var TriangleCache = new weakMap() + var q = this.clone(); + if (endian !== 'le') { + // Assume big-endian + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); -function createABigTriangle(gl) { + res[res.length - i - 1] = b; + } + } else { + // Assume little-endian + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); - var triangleVAO = TriangleCache.get(gl) - if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) { - var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) - triangleVAO = createVAO(gl, [ - { buffer: buf, - type: gl.FLOAT, - size: 2 - } - ]) - triangleVAO._triangleBuffer = buf - TriangleCache.set(gl, triangleVAO) + res[i] = b; + } } - triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, 3) - triangleVAO.unbind() -} - -module.exports = createABigTriangle - -},{"gl-buffer":118,"gl-vao":226,"weak-map":168}],170:[function(require,module,exports){ -'use strict' - -module.exports = createAxes - -var createText = require('./lib/text.js') -var createLines = require('./lib/lines.js') -var createBackground = require('./lib/background.js') -var getCubeProperties = require('./lib/cube.js') -var Ticks = require('./lib/ticks.js') -var identity = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]) + return res; +}; -function copyVec3(a, b) { - a[0] = b[0] - a[1] = b[1] - a[2] = b[2] - return a +if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; +} else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; + } + if (t >= 0x40) { + r += 7; + t >>>= 7; + } + if (t >= 0x8) { + r += 4; + t >>>= 4; + } + if (t >= 0x02) { + r += 2; + t >>>= 2; + } + return r + t; + }; } -function Axes(gl) { - this.gl = gl - - this.pixelRatio = 1 - - this.bounds = [ [-10, -10, -10], - [ 10, 10, 10] ] - this.ticks = [ [], [], [] ] - this.autoTicks = true - this.tickSpacing = [ 1, 1, 1 ] - - this.tickEnable = [ true, true, true ] - this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ] - this.tickSize = [ 12, 12, 12 ] - this.tickAngle = [ 0, 0, 0 ] - this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.tickPad = [ 10, 10, 10 ] +BN.prototype._zeroBits = function _zeroBits(w) { + // Short-cut + if (w === 0) + return 26; - this.lastCubeProps = { - cubeEdges: [0,0,0], - axis: [0,0,0] + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; } + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 0x1) === 0) + r++; + return r; +}; - this.labels = [ 'x', 'y', 'z' ] - this.labelEnable = [ true, true, true ] - this.labelFont = 'sans-serif' - this.labelSize = [ 20, 20, 20 ] - this.labelAngle = [ 0, 0, 0 ] - this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.labelPad = [ 10, 10, 10 ] - - this.lineEnable = [ true, true, true ] - this.lineMirror = [ false, false, false ] - this.lineWidth = [ 1, 1, 1 ] - this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - - this.lineTickEnable = [ true, true, true ] - this.lineTickMirror = [ false, false, false ] - this.lineTickLength = [ 0, 0, 0 ] - this.lineTickWidth = [ 1, 1, 1 ] - this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - - this.gridEnable = [ true, true, true ] - this.gridWidth = [ 1, 1, 1 ] - this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - - this.zeroEnable = [ true, true, true ] - this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.zeroLineWidth = [ 2, 2, 2 ] - - this.backgroundEnable = [ false, false, false ] - this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5], - [0.8, 0.8, 0.8, 0.5], - [0.8, 0.8, 0.8, 0.5] ] +// Return number of used bits in a BN +BN.prototype.bitLength = function bitLength() { + var hi = 0; + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; +}; - this._firstInit = true - this._text = null - this._lines = null - this._background = createBackground(gl) -} +// Number of trailing zero bits +BN.prototype.zeroBits = function zeroBits() { + if (this.cmpn(0) === 0) + return 0; -var proto = Axes.prototype + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) + break; + } + return r; +}; -proto.update = function(options) { - options = options || {} +BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); +}; - //Option parsing helper functions - function parseOption(nest, cons, name) { - if(name in options) { - var opt = options[name] - var prev = this[name] - var next - if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : - Array.isArray(opt) ) { - this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] - } else { - this[name] = next = [ cons(opt), cons(opt), cons(opt) ] - } - for(var i=0; i<3; ++i) { - if(next[i] !== prev[i]) { - return true - } - } - } - return false - } +// Return negative clone of `this` +BN.prototype.neg = function neg() { + if (this.cmpn(0) === 0) + return this.clone(); - var NUMBER = parseOption.bind(this, false, Number) - var BOOLEAN = parseOption.bind(this, false, Boolean) - var STRING = parseOption.bind(this, false, String) - var COLOR = parseOption.bind(this, true, function(v) { - if(Array.isArray(v)) { - if(v.length === 3) { - return [ +v[0], +v[1], +v[2], 1.0 ] - } else if(v.length === 4) { - return [ +v[0], +v[1], +v[2], +v[3] ] - } - } - return [ 0, 0, 0, 1 ] - }) + var r = this.clone(); + r.sign = !this.sign; + return r; +}; - //Tick marks and bounds - var nextTicks - var ticksUpdate = false - var boundsChanged = false - if('bounds' in options) { - var bounds = options.bounds -i_loop: - for(var i=0; i<2; ++i) { - for(var j=0; j<3; ++j) { - if(bounds[i][j] !== this.bounds[i][j]) { - boundsChanged = true - } - this.bounds[i][j] = bounds[i][j] - } - } - } - if('ticks' in options) { - nextTicks = options.ticks - ticksUpdate = true - this.autoTicks = false - for(var i=0; i<3; ++i) { - this.tickSpacing[i] = 0.0 - } - } else if(NUMBER('tickSpacing')) { - this.autoTicks = true - boundsChanged = true - } - if(this._firstInit) { - if(!('ticks' in options || 'tickSpacing' in options)) { - this.autoTicks = true - } +// Or `num` with `this` in-place +BN.prototype.ior = function ior(num) { + this.sign = this.sign || num.sign; - //Force tick recomputation on first update - boundsChanged = true - ticksUpdate = true - this._firstInit = false - } + while (this.length < num.length) + this.words[this.length++] = 0; - if(boundsChanged && this.autoTicks) { - nextTicks = Ticks.create(this.bounds, this.tickSpacing) - ticksUpdate = true - } + for (var i = 0; i < num.length; i++) + this.words[i] = this.words[i] | num.words[i]; - //Compare next ticks to previous ticks, only update if needed - if(ticksUpdate) { - for(var i=0; i<3; ++i) { - nextTicks[i].sort(function(a,b) { - return a.x-b.x - }) - } - if(Ticks.equal(nextTicks, this.ticks)) { - ticksUpdate = false - } else { - this.ticks = nextTicks - } - } + return this.strip(); +}; - //Parse tick properties - BOOLEAN('tickEnable') - if(STRING('tickFont')) { - ticksUpdate = true //If font changes, must rebuild vbo - } - NUMBER('tickSize') - NUMBER('tickAngle') - NUMBER('tickPad') - COLOR('tickColor') - //Axis labels - var labelUpdate = STRING('labels') - if(STRING('labelFont')) { - labelUpdate = true - } - BOOLEAN('labelEnable') - NUMBER('labelSize') - NUMBER('labelPad') - COLOR('labelColor') +// Or `num` with `this` +BN.prototype.or = function or(num) { + if (this.length > num.length) + return this.clone().ior(num); + else + return num.clone().ior(this); +}; - //Axis lines - BOOLEAN('lineEnable') - BOOLEAN('lineMirror') - NUMBER('lineWidth') - COLOR('lineColor') - //Axis line ticks - BOOLEAN('lineTickEnable') - BOOLEAN('lineTickMirror') - NUMBER('lineTickLength') - NUMBER('lineTickWidth') - COLOR('lineTickColor') +// And `num` with `this` in-place +BN.prototype.iand = function iand(num) { + this.sign = this.sign && num.sign; - //Grid lines - BOOLEAN('gridEnable') - NUMBER('gridWidth') - COLOR('gridColor') + // b = min-length(num, this) + var b; + if (this.length > num.length) + b = num; + else + b = this; - //Zero line - BOOLEAN('zeroEnable') - COLOR('zeroLineColor') - NUMBER('zeroLineWidth') + for (var i = 0; i < b.length; i++) + this.words[i] = this.words[i] & num.words[i]; - //Background - BOOLEAN('backgroundEnable') - COLOR('backgroundColor') + this.length = b.length; - //Update text if necessary - if(!this._text) { - this._text = createText( - this.gl, - this.bounds, - this.labels, - this.labelFont, - this.ticks, - this.tickFont) - } else if(this._text && (labelUpdate || ticksUpdate)) { - this._text.update( - this.bounds, - this.labels, - this.labelFont, - this.ticks, - this.tickFont) - } + return this.strip(); +}; - //Update lines if necessary - if(this._lines && ticksUpdate) { - this._lines.dispose() - this._lines = null - } - if(!this._lines) { - this._lines = createLines(this.gl, this.bounds, this.ticks) - } -} -function OffsetInfo() { - this.primalOffset = [0,0,0] - this.primalMinor = [0,0,0] - this.mirrorOffset = [0,0,0] - this.mirrorMinor = [0,0,0] -} +// And `num` with `this` +BN.prototype.and = function and(num) { + if (this.length > num.length) + return this.clone().iand(num); + else + return num.clone().iand(this); +}; -var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ] -function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) { - var primalOffset = result.primalOffset - var primalMinor = result.primalMinor - var dualOffset = result.mirrorOffset - var dualMinor = result.mirrorMinor - var e = cubeEdges[i] +// Xor `num` with `this` in-place +BN.prototype.ixor = function ixor(num) { + this.sign = this.sign || num.sign; - //Calculate offsets - for(var j=0; j<3; ++j) { - if(i === j) { - continue - } - var a = primalOffset, - b = dualOffset, - c = primalMinor, - d = dualMinor - if(e & (1< 0) { - c[j] = -1 - d[j] = 0 - } else { - c[j] = 0 - d[j] = +1 - } + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } -} -var CUBE_ENABLE = [0,0,0] -var DEFAULT_PARAMS = { - model: identity, - view: identity, - projection: identity -} + for (var i = 0; i < b.length; i++) + this.words[i] = a.words[i] ^ b.words[i]; -proto.isOpaque = function() { - return true -} + if (this !== a) + for (; i < a.length; i++) + this.words[i] = a.words[i]; -proto.isTransparent = function() { - return false -} + this.length = a.length; -proto.drawTransparent = function(params) {} + return this.strip(); +}; -var PRIMAL_MINOR = [0,0,0] -var MIRROR_MINOR = [0,0,0] -var PRIMAL_OFFSET = [0,0,0] +// Xor `num` with `this` +BN.prototype.xor = function xor(num) { + if (this.length > num.length) + return this.clone().ixor(num); + else + return num.clone().ixor(this); +}; -proto.draw = function(params) { - params = params || DEFAULT_PARAMS - var gl = this.gl +// Set `bit` of `this` +BN.prototype.setn = function setn(bit, val) { + assert(typeof bit === 'number' && bit >= 0); - //Geometry for camera and axes - var model = params.model || identity - var view = params.view || identity - var projection = params.projection || identity - var bounds = this.bounds + var off = (bit / 26) | 0; + var wbit = bit % 26; - //Unpack axis info - var cubeParams = getCubeProperties(model, view, projection, bounds) - var cubeEdges = cubeParams.cubeEdges - var cubeAxis = cubeParams.axis + while (this.length <= off) + this.words[this.length++] = 0; - var cx = view[12] - var cy = view[13] - var cz = view[14] - var cw = view[15] + if (val) + this.words[off] = this.words[off] | (1 << wbit); + else + this.words[off] = this.words[off] & ~(1 << wbit); - var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight + return this.strip(); +}; - for(var i=0; i<3; ++i) { - this.lastCubeProps.cubeEdges[i] = cubeEdges[i] - this.lastCubeProps.axis[i] = cubeAxis[i] + +// Add `num` to `this` in-place +BN.prototype.iadd = function iadd(num) { + // negative + positive + if (this.sign && !num.sign) { + this.sign = false; + var r = this.isub(num); + this.sign = !this.sign; + return this._normSign(); + + // positive + negative + } else if (!this.sign && num.sign) { + num.sign = false; + var r = this.isub(num); + num.sign = true; + return r._normSign(); } - //Compute axis info - var lineOffset = LINE_OFFSET - for(var i=0; i<3; ++i) { - computeLineOffset( - LINE_OFFSET[i], - i, - this.bounds, - cubeEdges, - cubeAxis) + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - //Set up state parameters - var gl = this.gl + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] + b.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; + } - //Draw background first - var cubeEnable = CUBE_ENABLE - for(var i=0; i<3; ++i) { - if(this.backgroundEnable[i]) { - cubeEnable[i] = cubeAxis[i] - } else { - cubeEnable[i] = 0 - } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) + this.words[i] = a.words[i]; } - this._background.draw( - model, - view, - projection, - bounds, - cubeEnable, - this.backgroundColor) + return this; +}; - //Draw lines - this._lines.bind( - model, - view, - projection, - this) +// Add `num` to `this` +BN.prototype.add = function add(num) { + if (num.sign && !this.sign) { + num.sign = false; + var res = this.sub(num); + num.sign = true; + return res; + } else if (!num.sign && this.sign) { + this.sign = false; + var res = num.sub(this); + this.sign = true; + return res; + } - //First draw grid lines and zero lines - for(var i=0; i<3; ++i) { - var x = [0,0,0] - if(cubeAxis[i] > 0) { - x[i] = bounds[1][i] - } else { - x[i] = bounds[0][i] - } + if (this.length > num.length) + return this.clone().iadd(num); + else + return num.clone().iadd(this); +}; - //Draw grid lines - for(var j=0; j<2; ++j) { - var u = (i + 1 + j) % 3 - var v = (i + 1 + (j^1)) % 3 - if(this.gridEnable[u]) { - this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio) - } - } +// Subtract `num` from `this` in-place +BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.sign) { + num.sign = false; + var r = this.iadd(num); + num.sign = true; + return r._normSign(); - //Draw zero lines (need to do this AFTER all grid lines are drawn) - for(var j=0; j<2; ++j) { - var u = (i + 1 + j) % 3 - var v = (i + 1 + (j^1)) % 3 - if(this.zeroEnable[v]) { - //Check if zero line in bounds - if(bounds[0][v] <= 0 && bounds[1][v] >= 0) { - this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio) - } - } - } + // -this - num = -(this + num) + } else if (this.sign) { + this.sign = false; + this.iadd(num); + this.sign = true; + return this._normSign(); } - //Then draw axis lines and tick marks - for(var i=0; i<3; ++i) { + // At this point both numbers are positive + var cmp = this.cmp(num); - //Draw axis lines - if(this.lineEnable[i]) { - this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) - } - if(this.lineMirror[i]) { - this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) - } + // Optimization - zeroify + if (cmp === 0) { + this.sign = false; + this.length = 1; + this.words[0] = 0; + return this; + } - //Compute minor axes - var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor) - var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor) - var tickLength = this.lineTickLength - var op = 0 - for(var j=0; j<3; ++j) { - var scaleFactor = pixelScaleF / model[5*j] - primalMinor[j] *= tickLength[j] * scaleFactor - mirrorMinor[j] *= tickLength[j] * scaleFactor - } + // a > b + var a; + var b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } - //Draw axis line ticks - if(this.lineTickEnable[i]) { - this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) - } - if(this.lineTickMirror[i]) { - this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) - } + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] - b.words[i] + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; } - //Draw text sprites - this._text.bind( - model, - view, - projection, - this.pixelRatio) + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) + for (; i < a.length; i++) + this.words[i] = a.words[i]; + this.length = Math.max(this.length, i); - for(var i=0; i<3; ++i) { + if (a !== this) + this.sign = true; - var minor = lineOffset[i].primalMinor - var offset = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset) + return this.strip(); +}; - for(var j=0; j<3; ++j) { - if(this.lineTickEnable[i]) { - offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0) / model[5*j] +// Subtract `num` from `this` +BN.prototype.sub = function sub(num) { + return this.clone().isub(num); +}; + +/* +// NOTE: This could be potentionally used to generate loop-less multiplications +function _genCombMulTo(alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + + 'mask = 0x3ffffff, shift = 0x4000000;', + 'out.length = ' + len + ';' + ]; + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + for (var j = minJ; j <= maxJ; j++) { + var i = k - j; + var mul = 'a[' + i + '] * b[' + j + ']'; + + if (j === minJ) { + src.push('w = ' + mul + ' + c;'); + src.push('c = (w / shift) | 0;'); + } else { + src.push('w += ' + mul + ';'); + src.push('c += (w / shift) | 0;'); } + src.push('w &= mask;'); } + src.push('o[' + k + '] = w;'); + } + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); - //Draw tick text - if(this.tickEnable[i]) { + return src.join('\n'); +} +*/ - //Add tick padding - for(var j=0; j<3; ++j) { - offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j] - } +BN.prototype._smallMulTo = function _smallMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; - //Draw axis - this._text.drawTicks( - i, - this.tickSize[i], - this.tickAngle[i], - offset, - this.tickColor[i]) + var carry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; } + out.words[k] = rword; + carry = ncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } - //Draw labels - if(this.labelEnable[i]) { + return out.strip(); +}; - //Add label padding - for(var j=0; j<3; ++j) { - offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j] - } - offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]) +BN.prototype._bigMulTo = function _bigMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; - //Draw axis - this._text.drawLabel( - i, - this.labelSize[i], - this.labelAngle[i], - offset, - this.labelColor[i]) + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; } -} -proto.dispose = function() { - this._text.dispose() - this._lines.dispose() - this._background.dispose() - this._lines = null - this._text = null - this._background = null - this.gl = null -} + return out.strip(); +}; -function createAxes(gl, options) { - var axes = new Axes(gl) - axes.update(options) - return axes -} +BN.prototype.mulTo = function mulTo(num, out) { + var res; + if (this.length + num.length < 63) + res = this._smallMulTo(num, out); + else + res = this._bigMulTo(num, out); + return res; +}; -},{"./lib/background.js":171,"./lib/cube.js":172,"./lib/lines.js":173,"./lib/text.js":175,"./lib/ticks.js":176}],171:[function(require,module,exports){ -'use strict' +// Multiply `this` by `num` +BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); +}; -module.exports = createBackgroundCube +// In-place Multiplication +BN.prototype.imul = function imul(num) { + if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { + this.words[0] = 0; + this.length = 1; + return this; + } -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders').bg + var tlen = this.length; + var nlen = num.length; -function BackgroundCube(gl, buffer, vao, shader) { - this.gl = gl - this.buffer = buffer - this.vao = vao - this.shader = shader -} + this.sign = num.sign !== this.sign; + this.length = this.length + num.length; + this.words[this.length - 1] = 0; -var proto = BackgroundCube.prototype + for (var k = this.length - 2; k >= 0; k--) { + // Sum all words with the same `i + j = k` and accumulate `carry`, + // note that carry could be >= 0x3ffffff + var carry = 0; + var rword = 0; + var maxJ = Math.min(k, nlen - 1); + for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i]; + var b = num.words[j]; + var r = a * b; -proto.draw = function(model, view, projection, bounds, enable, colors) { - var needsBG = false - for(var i=0; i<3; ++i) { - needsBG = needsBG || enable[i] + var lo = r & 0x3ffffff; + carry += (r / 0x4000000) | 0; + lo += rword; + rword = lo & 0x3ffffff; + carry += lo >>> 26; + } + this.words[k] = rword; + this.words[k + 1] += carry; + carry = 0; + } + + // Propagate overflows + var carry = 0; + for (var i = 1; i < this.length; i++) { + var w = this.words[i] + carry; + this.words[i] = w & 0x3ffffff; + carry = w >>> 26; + } + + return this.strip(); +}; + +BN.prototype.imuln = function imuln(num) { + assert(typeof num === 'number'); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i] * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; } - if(!needsBG) { - return + + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - var gl = this.gl + return this; +}; - gl.enable(gl.POLYGON_OFFSET_FILL) - gl.polygonOffset(1, 2) +BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); +}; - this.shader.bind() - this.shader.uniforms = { - model: model, - view: view, - projection: projection, - bounds: bounds, - enable: enable, - colors: colors - } - this.vao.bind() - this.vao.draw(this.gl.TRIANGLES, 36) +// `this` * `this` +BN.prototype.sqr = function sqr() { + return this.mul(this); +}; - gl.disable(gl.POLYGON_OFFSET_FILL) -} +// `this` * `this` in-place +BN.prototype.isqr = function isqr() { + return this.mul(this); +}; -proto.dispose = function() { - this.vao.dispose() - this.buffer.dispose() - this.shader.dispose() -} +// Shift-left in-place +BN.prototype.ishln = function ishln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); -function createBackgroundCube(gl) { - //Create cube vertices - var vertices = [] - var indices = [] - var ptr = 0 - for(var d=0; d<3; ++d) { - var u = (d+1) % 3 - var v = (d+2) % 3 - var x = [0,0,0] - var c = [0,0,0] - for(var s=-1; s<=1; s+=2) { - indices.push(ptr, ptr+2, ptr+1, - ptr+1, ptr+2, ptr+3) - x[d] = s - c[d] = s - for(var i=-1; i<=1; i+=2) { - x[u] = i - for(var j=-1; j<=1; j+=2) { - x[v] = j - vertices.push(x[0], x[1], x[2], - c[0], c[1], c[2]) - ptr += 1 - } - } - //Swap u and v - var tt = u - u = v - v = tt + if (r !== 0) { + var carry = 0; + for (var i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); + } + if (carry) { + this.words[i] = carry; + this.length++; } } - //Allocate buffer and vertex array - var buffer = createBuffer(gl, new Float32Array(vertices)) - var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) - var vao = createVAO(gl, [ - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 0, - stride: 24 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 12, - stride: 24 - } - ], elements) - - //Create shader object - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.normal.location = 1 - - return new BackgroundCube(gl, buffer, vao, shader) -} + if (s !== 0) { + for (var i = this.length - 1; i >= 0; i--) + this.words[i + s] = this.words[i]; + for (var i = 0; i < s; i++) + this.words[i] = 0; + this.length += s; + } -},{"./shaders":174,"gl-buffer":118,"gl-vao":226}],172:[function(require,module,exports){ -"use strict" + return this.strip(); +}; -module.exports = getCubeEdges +// Shift-right in-place +// NOTE: `hint` is a lowest bit before trailing zeroes +// NOTE: if `extended` is present - it will be filled with destroyed bits +BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) + h = (hint - (hint % 26)) / 26; + else + h = 0; -var bits = require('bit-twiddle') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var splitPoly = require('split-polygon') -var orient = require('robust-orientation') + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; -var mvp = new Array(16) -var imvp = new Array(16) -var pCubeVerts = new Array(8) -var cubeVerts = new Array(8) -var x = new Array(3) -var zero3 = [0,0,0] + h -= s; + h = Math.max(0, h); -;(function() { - for(var i=0; i<8; ++i) { - pCubeVerts[i] =[1,1,1,1] - cubeVerts[i] = [1,1,1] + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) + maskedWords.words[i] = this.words[i]; + maskedWords.length = s; } -})() + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (var i = 0; i < this.length; i++) + this.words[i] = this.words[i + s]; + } else { + this.words[0] = 0; + this.length = 1; + } -function transformHg(result, x, mat) { - for(var i=0; i<4; ++i) { - result[i] = mat[12+i] - for(var j=0; j<3; ++j) { - result[i] += x[j]*mat[4*j+i] - } + var carry = 0; + for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i]; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; } -} -var FRUSTUM_PLANES = [ - [ 0, 0, 1, 0, 0], - [ 0, 0,-1, 1, 0], - [ 0,-1, 0, 1, 0], - [ 0, 1, 0, 1, 0], - [-1, 0, 0, 1, 0], - [ 1, 0, 0, 1, 0] -] + // Push carried bits as a mask + if (maskedWords && carry !== 0) + maskedWords.words[maskedWords.length++] = carry; -function polygonArea(p) { - for(var i=0; i= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + return false; } - return area -} + // Check bit and return + var w = this.words[s]; -var CUBE_EDGES = [1,1,1] -var CUBE_AXIS = [0,0,0] -var CUBE_RESULT = { - cubeEdges: CUBE_EDGES, - axis: CUBE_AXIS -} + return !!(w & q); +}; -function getCubeEdges(model, view, projection, bounds) { +// Return only lowers bits of number (in-place) +BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; - //Concatenate matrices - multiply(mvp, view, model) - multiply(mvp, projection, mvp) - - //First project cube vertices - var ptr = 0 - for(var i=0; i<2; ++i) { - x[2] = bounds[i][2] - for(var j=0; j<2; ++j) { - x[1] = bounds[j][1] - for(var k=0; k<2; ++k) { - x[0] = bounds[k][0] - transformHg(pCubeVerts[ptr], x, mvp) - ptr += 1 - } - } - } + assert(!this.sign, 'imaskn works only with positive numbers'); - //Classify camera against cube faces - var closest = -1 + if (r !== 0) + s++; + this.length = Math.min(s, this.length); - for(var i=0; i<8; ++i) { - var w = pCubeVerts[i][3] - for(var l=0; l<3; ++l) { - cubeVerts[i][l] = pCubeVerts[i][l] / w - } - if(w < 0) { - if(closest < 0) { - closest = i - } else if(cubeVerts[i][2] < cubeVerts[closest][2]) { - closest = i - } - } + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; } - if(closest < 0) { - closest = 0 - for(var d=0; d<3; ++d) { - var u = (d+2) % 3 - var v = (d+1) % 3 - var o0 = -1 - var o1 = -1 - for(var s=0; s<2; ++s) { - var f0 = (s< o0) { - closest |= 1< o0) { - closest |= 1< cubeVerts[i][1]) { - bottom = i - } - } +// Add plain number `num` to `this` +BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.isubn(-num); - //Find left/right neighbors of bottom vertex - var left = -1 - for(var i=0; i<3; ++i) { - var idx = bottom ^ (1< cubeVerts[right][0]) { - right = idx + // Possible sign change + if (this.sign) { + if (this.length === 1 && this.words[0] < num) { + this.words[0] = num - this.words[0]; + this.sign = false; + return this; } - } - //Determine edge axis coordinates - var cubeEdges = CUBE_EDGES - cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0 - cubeEdges[bits.log2(left^bottom)] = bottom&left - cubeEdges[bits.log2(bottom^right)] = bottom&right - var top = right ^ 7 - if(top === closest || top === farthest) { - top = left ^ 7 - cubeEdges[bits.log2(right^top)] = top&right - } else { - cubeEdges[bits.log2(left^top)] = top&left + this.sign = false; + this.isubn(num); + this.sign = true; + return this; } - //Determine visible faces - var axis = CUBE_AXIS - var cutCorner = closest - for(var d=0; d<3; ++d) { - if(cutCorner & (1<= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) + this.words[i + 1] = 1; + else + this.words[i + 1]++; } + this.length = Math.max(this.length, i + 1); - //Return result - return CUBE_RESULT -} -},{"bit-twiddle":50,"gl-mat4/invert":137,"gl-mat4/multiply":139,"robust-orientation":259,"split-polygon":178}],173:[function(require,module,exports){ -'use strict' + return this; +}; -module.exports = createLines +// Subtract plain number `num` from `this` +BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.iaddn(-num); -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders').line + if (this.sign) { + this.sign = false; + this.iaddn(num); + this.sign = true; + return this; + } -var MAJOR_AXIS = [0,0,0] -var MINOR_AXIS = [0,0,0] -var SCREEN_AXIS = [0,0,0] -var OFFSET_VEC = [0,0,0] -var SHAPE = [1,1] + this.words[0] -= num; -function zeroVec(a) { - a[0] = a[1] = a[2] = 0 - return a -} + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; + } -function copyVec(a,b) { - a[0] = b[0] - a[1] = b[1] - a[2] = b[2] - return a -} + return this.strip(); +}; -function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) { - this.gl = gl - this.vertBuffer = vertBuffer - this.vao = vao - this.shader = shader - this.tickCount = tickCount - this.tickOffset = tickOffset - this.gridCount = gridCount - this.gridOffset = gridOffset -} +BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); +}; -var proto = Lines.prototype +BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); +}; -proto.bind = function(model, view, projection) { - this.shader.bind() - this.shader.uniforms.model = model - this.shader.uniforms.view = view - this.shader.uniforms.projection = projection +BN.prototype.iabs = function iabs() { + this.sign = false; + + return this; +}; - SHAPE[0] = this.gl.drawingBufferWidth - SHAPE[1] = this.gl.drawingBufferHeight +BN.prototype.abs = function abs() { + return this.clone().iabs(); +}; - this.shader.uniforms.screenShape = SHAPE - this.vao.bind() -} +BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + // Bigger storage is needed + var len = num.length + shift; + var i; + if (this.words.length < len) { + var t = new Array(len); + for (var i = 0; i < this.length; i++) + t[i] = this.words[i]; + this.words = t; + } else { + i = this.length; + } -proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) { - var minorAxis = zeroVec(MINOR_AXIS) - this.shader.uniforms.majorAxis = MINOR_AXIS + // Zeroify rest + this.length = Math.max(this.length, len); + for (; i < this.length; i++) + this.words[i] = 0; - minorAxis[j] = bounds[1][j] - bounds[0][j] - this.shader.uniforms.minorAxis = minorAxis + var carry = 0; + for (var i = 0; i < num.length; i++) { + var w = this.words[i + shift] + carry; + var right = num.words[i] * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; + } + for (; i < this.length - shift; i++) { + var w = this.words[i + shift] + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; + } - var noffset = copyVec(OFFSET_VEC, offset) - noffset[j] += bounds[0][j] - this.shader.uniforms.offset = noffset + if (carry === 0) + return this.strip(); - this.shader.uniforms.lineWidth = lineWidth + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (var i = 0; i < this.length; i++) { + var w = -this.words[i] + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; + } + this.sign = true; - this.shader.uniforms.color = color + return this.strip(); +}; - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[(j+2)%3] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.vao.draw(this.gl.TRIANGLES, 6) +BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[(j+1)%3] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.vao.draw(this.gl.TRIANGLES, 6) -} + var a = this.clone(); + var b = num; -proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) { - if(!this.tickCount[j]) { - return + // Normalize + var bhi = b.words[b.length - 1]; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.shln(shift); + a.ishln(shift); + bhi = b.words[b.length - 1]; } - var majorAxis = zeroVec(MAJOR_AXIS) - majorAxis[j] = 1 - this.shader.uniforms.majorAxis = majorAxis - this.shader.uniforms.offset = offset - this.shader.uniforms.minorAxis = minorAxis - this.shader.uniforms.color = color - this.shader.uniforms.lineWidth = lineWidth - - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[j] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j]) -} + // Initialize quotient + var m = a.length - b.length; + var q; + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) + q.words[i] = 0; + } -proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) { - if(!this.gridCount[i]) { - return + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (!diff.sign) { + a = diff; + if (q) + q.words[m] = 1; } - var minorAxis = zeroVec(MINOR_AXIS) - minorAxis[j] = bounds[1][j] - bounds[0][j] - this.shader.uniforms.minorAxis = minorAxis + for (var j = m - 1; j >= 0; j--) { + var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1]; - var noffset = copyVec(OFFSET_VEC, offset) - noffset[j] += bounds[0][j] - this.shader.uniforms.offset = noffset + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); - var majorAxis = zeroVec(MAJOR_AXIS) - majorAxis[i] = 1 - this.shader.uniforms.majorAxis = majorAxis + a._ishlnsubmul(b, qj, j); + while (a.sign) { + qj--; + a.sign = false; + a._ishlnsubmul(b, 1, j); + if (a.cmpn(0) !== 0) + a.sign = !a.sign; + } + if (q) + q.words[j] = qj; + } + if (q) + q.strip(); + a.strip(); - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[i] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.shader.uniforms.lineWidth = lineWidth + // Denormalize + if (mode !== 'div' && shift !== 0) + a.ishrn(shift); + return { div: q ? q : null, mod: a }; +}; - this.shader.uniforms.color = color - this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i]) -} +BN.prototype.divmod = function divmod(num, mode) { + assert(num.cmpn(0) !== 0); -proto.drawZero = function(j, i, bounds, offset, color, lineWidth) { - var minorAxis = zeroVec(MINOR_AXIS) - this.shader.uniforms.majorAxis = minorAxis + if (this.sign && !num.sign) { + var res = this.neg().divmod(num, mode); + var div; + var mod; + if (mode !== 'mod') + div = res.div.neg(); + if (mode !== 'div') + mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); + return { + div: div, + mod: mod + }; + } else if (!this.sign && num.sign) { + var res = this.divmod(num.neg(), mode); + var div; + if (mode !== 'mod') + div = res.div.neg(); + return { div: div, mod: res.mod }; + } else if (this.sign && num.sign) { + return this.neg().divmod(num.neg(), mode); + } - minorAxis[j] = bounds[1][j] - bounds[0][j] - this.shader.uniforms.minorAxis = minorAxis + // Both numbers are positive at this point - var noffset = copyVec(OFFSET_VEC, offset) - noffset[j] += bounds[0][j] - this.shader.uniforms.offset = noffset + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) + return { div: new BN(0), mod: this }; - var screenAxis = zeroVec(SCREEN_AXIS) - screenAxis[i] = 1 - this.shader.uniforms.screenAxis = screenAxis - this.shader.uniforms.lineWidth = lineWidth + // Very short reduction + if (num.length === 1) { + if (mode === 'div') + return { div: this.divn(num.words[0]), mod: null }; + else if (mode === 'mod') + return { div: null, mod: new BN(this.modn(num.words[0])) }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } - this.shader.uniforms.color = color - this.vao.draw(this.gl.TRIANGLES, 6) -} + return this._wordDiv(num, mode); +}; -proto.dispose = function() { - this.vao.dispose() - this.vertBuffer.dispose() - this.shader.dispose() -} +// Find `this` / `num` +BN.prototype.div = function div(num) { + return this.divmod(num, 'div').div; +}; -function createLines(gl, bounds, ticks) { - var vertices = [] - var tickOffset = [0,0,0] - var tickCount = [0,0,0] +// Find `this` % `num` +BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod').mod; +}; - //Create grid lines for each axis/direction - var gridOffset = [0,0,0] - var gridCount = [0,0,0] +// Find Round(`this` / `num`) +BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); - //Add zero line - vertices.push( - 0,0,1, 0,1,1, 0,0,-1, - 0,0,-1, 0,1,1, 0,1,-1) + // Fast case - exact division + if (dm.mod.cmpn(0) === 0) + return dm.div; - for(var i=0; i<3; ++i) { - //Axis tick marks - var start = ((vertices.length / 3)|0) - for(var j=0; j= 0; i--) + acc = (p * acc + this.words[i]) % num; -var lineVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n" -var lineFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" -exports.line = function(gl) { - return createShader(gl, lineVert, lineFrag, null, [ - {name: 'position', type: 'vec3'} - ]) -} + return acc; +}; -var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}" -var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" -exports.text = function(gl) { - return createShader(gl, textVert, textFrag, null, [ - {name: 'position', type: 'vec3'} - ]) -} +// In-place division by number +BN.prototype.idivn = function idivn(num) { + assert(num <= 0x3ffffff); -var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}" -var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}" -exports.bg = function(gl) { - return createShader(gl, bgVert, bgFrag, null, [ - {name: 'position', type: 'vec3'}, - {name: 'normal', type: 'vec3'} - ]) -} + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = this.words[i] + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } -},{"gl-shader":197}],175:[function(require,module,exports){ -(function (process){ -"use strict" + return this.strip(); +}; -module.exports = createTextSprites +BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); +}; -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var vectorizeText = require('vectorize-text') -var createShader = require('./shaders').text +BN.prototype.egcd = function egcd(p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); -var globals = window || process.global || {} -var __TEXT_CACHE = globals.__TEXT_CACHE || {} -globals.__TEXT_CACHE = {} + var x = this; + var y = p.clone(); -//Vertex buffer format for text is: -// -/// [x,y,z] = Spatial coordinate -// + if (x.sign) + x = x.mod(p); + else + x = x.clone(); -var VERTEX_SIZE = 3 -var VERTEX_STRIDE = VERTEX_SIZE * 4 + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); -function TextSprites( - gl, - shader, - buffer, - vao) { - this.gl = gl - this.shader = shader - this.buffer = buffer - this.vao = vao - this.tickOffset = - this.tickCount = - this.labelOffset = - this.labelCount = null -} + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); -var proto = TextSprites.prototype + var g = 0; -//Bind textures for rendering -var SHAPE = [0,0] -proto.bind = function(model, view, projection, pixelScale) { - this.vao.bind() - this.shader.bind() - var uniforms = this.shader.uniforms - uniforms.model = model - uniforms.view = view - uniforms.projection = projection - uniforms.pixelScale = pixelScale - SHAPE[0] = this.gl.drawingBufferWidth - SHAPE[1] = this.gl.drawingBufferHeight - this.shader.uniforms.resolution = SHAPE -} + while (x.isEven() && y.isEven()) { + x.ishrn(1); + y.ishrn(1); + ++g; + } -proto.update = function(bounds, labels, labelFont, ticks, tickFont) { - var gl = this.gl - var data = [] + var yp = y.clone(); + var xp = x.clone(); - function addItem(t, text, font, size) { - var fontcache = __TEXT_CACHE[font] - if(!fontcache) { - fontcache = __TEXT_CACHE[font] = {} - } - var mesh = fontcache[text] - if(!mesh) { - mesh = fontcache[text] = tryVectorizeText(text, { - triangles: true, - font: font, - textAlign: 'center', - textBaseline: 'middle' - }) + while (x.cmpn(0) !== 0) { + while (x.isEven()) { + x.ishrn(1); + if (A.isEven() && B.isEven()) { + A.ishrn(1); + B.ishrn(1); + } else { + A.iadd(yp).ishrn(1); + B.isub(xp).ishrn(1); + } } - var scale = (size || 12) / 12 - var positions = mesh.positions - var cells = mesh.cells - var lo = [ Infinity, Infinity] - var hi = [-Infinity,-Infinity] - for(var i=0, nc=cells.length; i=0; --j) { - var p = positions[c[j]] - data.push(scale*p[0], -scale*p[1], t) + + while (y.isEven()) { + y.ishrn(1); + if (C.isEven() && D.isEven()) { + C.ishrn(1); + D.ishrn(1); + } else { + C.iadd(yp).ishrn(1); + D.isub(xp).ishrn(1); } } + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } } - //Generate sprites for all 3 axes, store data in texture atlases - var tickOffset = [0,0,0] - var tickCount = [0,0,0] - var labelOffset = [0,0,0] - var labelCount = [0,0,0] - for(var d=0; d<3; ++d) { + return { + a: C, + b: D, + gcd: y.ishln(g) + }; +}; - //Generate label - labelOffset[d] = (data.length/VERTEX_SIZE)|0 - addItem(0.5*(bounds[0][d]+bounds[1][d]), labels[d], labelFont) - labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d] +// This is reduced incarnation of the binary EEA +// above, designated to invert members of the +// _prime_ fields F(p) at a maximal speed +BN.prototype._invmp = function _invmp(p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); - //Generate sprites for tick marks - tickOffset[d] = (data.length/VERTEX_SIZE)|0 - for(var i=0; i 0 && b.cmpn(1) > 0) { + while (a.isEven()) { + a.ishrn(1); + if (x1.isEven()) + x1.ishrn(1); + else + x1.iadd(delta).ishrn(1); + } + while (b.isEven()) { + b.ishrn(1); + if (x2.isEven()) + x2.ishrn(1); + else + x2.iadd(delta).ishrn(1); + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); } - tickCount[d] = ((data.length/VERTEX_SIZE)|0) - tickOffset[d] } + if (a.cmpn(1) === 0) + return x1; + else + return x2; +}; - this.buffer.update(data) - this.tickOffset = tickOffset - this.tickCount = tickCount - this.labelOffset = labelOffset - this.labelCount = labelCount -} - -//Draws the tick marks for an axis -var AXIS = [0,0,0] -proto.drawTicks = function(d, scale, angle, offset, color) { - if(!this.tickCount[d]) { - return - } +BN.prototype.gcd = function gcd(num) { + if (this.cmpn(0) === 0) + return num.clone(); + if (num.cmpn(0) === 0) + return this.clone(); - var v = AXIS - v[0] = v[1] = v[2] = 0 - v[d] = 1 - this.shader.uniforms.axis = v - this.shader.uniforms.color = color - this.shader.uniforms.angle = angle - this.shader.uniforms.scale = scale - this.shader.uniforms.offset = offset - this.vao.draw(this.gl.TRIANGLES, this.tickCount[d], this.tickOffset[d]) -} + var a = this.clone(); + var b = num.clone(); + a.sign = false; + b.sign = false; -//Draws the text label for an axis -var ZERO = [0,0,0] -proto.drawLabel = function(d, scale, angle, offset, color) { - if(!this.labelCount[d]) { - return + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.ishrn(1); + b.ishrn(1); } - this.shader.uniforms.axis = ZERO - this.shader.uniforms.color = color - this.shader.uniforms.angle = angle - this.shader.uniforms.scale = scale - this.shader.uniforms.offset = offset - this.vao.draw(this.gl.TRIANGLES, this.labelCount[d], this.labelOffset[d]) -} -//Releases all resources attached to this object -proto.dispose = function() { - this.shader.dispose() - this.vao.dispose() - this.buffer.dispose() -} + do { + while (a.isEven()) + a.ishrn(1); + while (b.isEven()) + b.ishrn(1); -function tryVectorizeText(text, options) { - try { - return vectorizeText(text, options) - } catch(e) { - console.warn('error vectorizing text:', e) - return { - cells: [], - positions: [] + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; } - } -} - -function createTextSprites( - gl, - bounds, - labels, - labelFont, - ticks, - tickFont) { - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { "buffer": buffer, - "size": 3 - } - ]) + a.isub(b); + } while (true); - var shader = createShader(gl) - shader.attributes.position.location = 0 + return b.ishln(shift); +}; - var result = new TextSprites( - gl, - shader, - buffer, - vao) +// Invert number in the field F(num) +BN.prototype.invm = function invm(num) { + return this.egcd(num).a.mod(num); +}; - result.update(bounds, labels, labelFont, ticks, tickFont) +BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; +}; - return result -} +BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; +}; -}).call(this,require('_process')) -},{"./shaders":174,"_process":56,"gl-buffer":118,"gl-vao":226,"vectorize-text":280}],176:[function(require,module,exports){ -'use strict' +// And first word and num +BN.prototype.andln = function andln(num) { + return this.words[0] & num; +}; -exports.create = defaultTicks -exports.equal = ticksEqual +// Increment at the bit position in-line +BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; -function prettyPrint(spacing, i) { - var stepStr = spacing + "" - var u = stepStr.indexOf(".") - var sigFigs = 0 - if(u >= 0) { - sigFigs = stepStr.length - u - 1 - } - var shift = Math.pow(10, sigFigs) - var x = Math.round(spacing * i * shift) - var xstr = x + "" - if(xstr.indexOf("e") >= 0) { - return xstr + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + for (var i = this.length; i < s + 1; i++) + this.words[i] = 0; + this.words[s] |= q; + this.length = s + 1; + return this; } - var xi = x / shift, xf = x % shift - if(x < 0) { - xi = -Math.ceil(xi)|0 - xf = (-xf)|0 - } else { - xi = Math.floor(xi)|0 - xf = xf|0 + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i]; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; } - var xis = "" + xi - if(x < 0) { - xis = "-" + xis + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - if(sigFigs) { - var xs = "" + xf - while(xs.length < sigFigs) { - xs = "0" + xs - } - return xis + "." + xs + return this; +}; + +BN.prototype.cmpn = function cmpn(num) { + var sign = num < 0; + if (sign) + num = -num; + + if (this.sign && !sign) + return -1; + else if (!this.sign && sign) + return 1; + + num &= 0x3ffffff; + this.strip(); + + var res; + if (this.length > 1) { + res = 1; } else { - return xis + var w = this.words[0]; + res = w === num ? 0 : w < num ? -1 : 1; } -} + if (this.sign) + res = -res; + return res; +}; -function defaultTicks(bounds, tickSpacing) { - var array = [] - for(var d=0; d<3; ++d) { - var ticks = [] - var m = 0.5*(bounds[0][d]+bounds[1][d]) - for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) { - ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) - } - for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) { - ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) - } - array.push(ticks) - } - return array -} +// Compare two numbers and return: +// 1 - if `this` > `num` +// 0 - if `this` == `num` +// -1 - if `this` < `num` +BN.prototype.cmp = function cmp(num) { + if (this.sign && !num.sign) + return -1; + else if (!this.sign && num.sign) + return 1; -function ticksEqual(ticksA, ticksB) { - for(var i=0; i<3; ++i) { - if(ticksA[i].length !== ticksB[i].length) { - return false - } - for(var j=0; j num.length) + return 1; + else if (this.length < num.length) + return -1; -function extractPlanes(M, zNear, zFar) { - var z = zNear || 0.0 - var zf = zFar || 1.0 - return [ - [ M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3] ], - [ M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3] ], - [ M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7] ], - [ M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7] ], - [ z*M[12] + M[8], z*M[13] + M[9], z*M[14] + M[10], z*M[15] + M[11] ], - [ zf*M[12] - M[8], zf*M[13] - M[9], zf*M[14] - M[10], zf*M[15] - M[11] ] - ] -} -},{}],178:[function(require,module,exports){ -"use strict" + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i]; + var b = num.words[i]; -var robustDot = require("robust-dot-product") -var robustSum = require("robust-sum") + if (a === b) + continue; + if (a < b) + res = -1; + else if (a > b) + res = 1; + break; + } + return res; +}; -module.exports = splitPolygon -module.exports.positive = positive -module.exports.negative = negative +// +// A reduce context, could be using montgomery or something better, depending +// on the `m` itself. +// +BN.red = function red(num) { + return new Red(num); +}; -function planeT(p, plane) { - var r = robustSum(robustDot(p, plane), [plane[plane.length-1]]) - return r[r.length-1] -} +BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(!this.sign, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); +}; +BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); +}; -//Can't do this exactly and emit a floating point result -function lerpW(a, wa, b, wb) { - var d = wb - wa - var t = -wa / d - if(t < 0.0) { - t = 0.0 - } else if(t > 1.0) { - t = 1.0 - } - var ti = 1.0 - t - var n = a.length - var r = new Array(n) - for(var i=0; i 0) || (a > 0 && b < 0)) { - var p = lerpW(s, b, t, a) - pos.push(p) - neg.push(p.slice()) - } - if(b < 0) { - neg.push(t.slice()) - } else if(b > 0) { - pos.push(t.slice()) - } else { - pos.push(t.slice()) - neg.push(t.slice()) - } - a = b - } - return { positive: pos, negative: neg } -} +BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); +}; -function positive(points, plane) { - var pos = [] - var a = planeT(points[points.length-1], plane) - for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { - pos.push(lerpW(s, b, t, a)) - } - if(b >= 0) { - pos.push(t.slice()) - } - a = b - } - return pos -} +BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); +}; -function negative(points, plane) { - var neg = [] - var a = planeT(points[points.length-1], plane) - for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { - neg.push(lerpW(s, b, t, a)) - } - if(b <= 0) { - neg.push(t.slice()) - } - a = b - } - return neg -} -},{"robust-dot-product":179,"robust-sum":262}],179:[function(require,module,exports){ -"use strict" +BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); +}; -var twoProduct = require("two-product") -var robustSum = require("robust-sum") +BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); +}; -module.exports = robustDotProduct +BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); +}; -function robustDotProduct(a, b) { - var r = twoProduct(a[0], b[0]) - for(var i=1; i this.n); - //Calculate the following properties for each axis: - // - // * lo - start of visible range for each axis in tick coordinates - // * hi - end of visible range for each axis in tick coordinates - // * ticksPerPixel - pixel density of tick marks for the axis - // - var ranges = RANGES - for(var i=0; i<3; ++i) { - ranges[i].lo = Infinity - ranges[i].hi = -Infinity - ranges[i].pixelsPerDataUnit = Infinity + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); } - //Compute frustum planes, intersect with box - var frustum = getPlanes(m4transpose(mvp, mvp)) - m4transpose(mvp, mvp) - - //Loop over vertices of viewable box - for(var d=0; d<3; ++d) { - var u = (d+1)%3 - var v = (d+2)%3 - var x = SCRATCH_X -i_loop: - for(var i=0; i<2; ++i) { - var poly = [] - - if((axis[d] < 0) === !!i) { - continue - } + return r; +}; - x[d] = bounds[i][d] - for(var j=0; j<2; ++j) { - x[u] = bounds[j^i][u] - for(var k=0; k<2; ++k) { - x[v] = bounds[k^j^i][v] - poly.push(x.slice()) - } - } - for(var j=0; j>> 22); + prev = next; + } + input.words[i - 10] = prev >>> 22; + input.length -= 9; +}; -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders/index') +K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; -module.exports = createSpikes + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var hi; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i]; + hi = w * 0x40; + lo += w * 0x3d1; + hi += (lo / 0x4000000) | 0; + lo &= 0x3ffffff; -var identity = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] + num.words[i] = lo; -function AxisSpikes(gl, buffer, vao, shader) { - this.gl = gl - this.buffer = buffer - this.vao = vao - this.shader = shader - this.pixelRatio = 1 - this.bounds = [[-1000,-1000,-1000], [1000,1000,1000]] - this.position = [0,0,0] - this.lineWidth = [2,2,2] - this.colors = [[0,0,0,1], [0,0,0,1], [0,0,0,1]] - this.enabled = [true,true,true] - this.drawSides = [true,true,true] - this.axes = null -} + lo = hi; + } -var proto = AxisSpikes.prototype + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) + num.length--; + } + return num; +}; -var OUTER_FACE = [0,0,0] -var INNER_FACE = [0,0,0] +function P224() { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); +} +inherits(P224, MPrime); -var SHAPE = [0,0] +function P192() { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +} +inherits(P192, MPrime); -proto.isTransparent = function() { - return false +function P25519() { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } +inherits(P25519, MPrime); -proto.drawTransparent = function(camera) {} +P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = num.words[i] * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; -proto.draw = function(camera) { - var gl = this.gl - var vao = this.vao - var shader = this.shader + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) + num.words[num.length++] = carry; + return num; +}; - vao.bind() - shader.bind() +// Exported mostly for testing purposes, use plain name instead +BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) + return primes[name]; - var model = camera.model || identity - var view = camera.view || identity - var projection = camera.projection || identity + var prime; + if (name === 'k256') + prime = new K256(); + else if (name === 'p224') + prime = new P224(); + else if (name === 'p192') + prime = new P192(); + else if (name === 'p25519') + prime = new P25519(); + else + throw new Error('Unknown prime ' + name); + primes[name] = prime; - var axis - if(this.axes) { - axis = this.axes.lastCubeProps.axis - } + return prime; +}; - var outerFace = OUTER_FACE - var innerFace = INNER_FACE - for(var i=0; i<3; ++i) { - if(axis && axis[i] < 0) { - outerFace[i] = this.bounds[0][i] - innerFace[i] = this.bounds[1][i] - } else { - outerFace[i] = this.bounds[1][i] - innerFace[i] = this.bounds[0][i] - } +// +// Base reduction engine +// +function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; } +} - SHAPE[0] = gl.drawingBufferWidth - SHAPE[1] = gl.drawingBufferHeight +Red.prototype._verify1 = function _verify1(a) { + assert(!a.sign, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); +}; - shader.uniforms.model = model - shader.uniforms.view = view - shader.uniforms.projection = projection - shader.uniforms.coordinates = [this.position, outerFace, innerFace] - shader.uniforms.colors = this.colors - shader.uniforms.screenShape = SHAPE +Red.prototype._verify2 = function _verify2(a, b) { + assert(!a.sign && !b.sign, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); +}; - for(var i=0; i<3; ++i) { - shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio - if(this.enabled[i]) { - vao.draw(gl.TRIANGLES, 6, 6*i) - if(this.drawSides[i]) { - vao.draw(gl.TRIANGLES, 12, 18+12*i) - } - } - } +Red.prototype.imod = function imod(a) { + if (this.prime) + return this.prime.ireduce(a)._forceRed(this); + return a.mod(this.m)._forceRed(this); +}; - vao.unbind() -} +Red.prototype.neg = function neg(a) { + var r = a.clone(); + r.sign = !r.sign; + return r.iadd(this.m)._forceRed(this); +}; -proto.update = function(options) { - if(!options) { - return - } - if("bounds" in options) { - this.bounds = options.bounds - } - if("position" in options) { - this.position = options.position - } - if("lineWidth" in options) { - this.lineWidth = options.lineWidth - } - if("colors" in options) { - this.colors = options.colors - } - if("enabled" in options) { - this.enabled = options.enabled - } - if("drawSides" in options) { - this.drawSides = options.drawSides - } -} +Red.prototype.add = function add(a, b) { + this._verify2(a, b); -proto.dispose = function() { - this.vao.dispose() - this.buffer.dispose() - this.shader.dispose() -} + var res = a.add(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res._forceRed(this); +}; +Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res; +}; -function createSpikes(gl, options) { - //Create buffers - var data = [ ] +Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); - function line(x,y,z,i,l,h) { - var row = [x,y,z, 0,0,0, 1] - row[i+3] = 1 - row[i] = l - data.push.apply(data, row) - row[6] = -1 - data.push.apply(data, row) - row[i] = h - data.push.apply(data, row) - data.push.apply(data, row) - row[6] = 1 - data.push.apply(data, row) - row[i] = l - data.push.apply(data, row) - } + var res = a.sub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res._forceRed(this); +}; - line(0,0,0, 0, 0, 1) - line(0,0,0, 1, 0, 1) - line(0,0,0, 2, 0, 1) +Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); - line(1,0,0, 1, -1,1) - line(1,0,0, 2, -1,1) + var res = a.isub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res; +}; - line(0,1,0, 0, -1,1) - line(0,1,0, 2, -1,1) +Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.shln(num)); +}; - line(0,0,1, 0, -1,1) - line(0,0,1, 1, -1,1) +Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); +}; - var buffer = createBuffer(gl, data) - var vao = createVAO(gl, [{ - type: gl.FLOAT, - buffer: buffer, - size: 3, - offset: 0, - stride: 28 - }, { - type: gl.FLOAT, - buffer: buffer, - size: 3, - offset: 12, - stride: 28 - }, { - type: gl.FLOAT, - buffer: buffer, - size: 1, - offset: 24, - stride: 28 - }]) +Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); +}; - //Create shader - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.color.location = 1 - shader.attributes.weight.location = 2 +Red.prototype.isqr = function isqr(a) { + return this.imul(a, a); +}; - //Create spike object - var spikes = new AxisSpikes(gl, buffer, vao, shader) +Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); +}; - //Set parameters - spikes.update(options) +Red.prototype.sqrt = function sqrt(a) { + if (a.cmpn(0) === 0) + return a.clone(); - //Return resulting object - return spikes -} + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); -},{"./shaders/index":181,"gl-buffer":118,"gl-vao":226}],183:[function(require,module,exports){ -'use strict' + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).ishrn(2); + var r = this.pow(a, pow); + return r; + } + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (q.cmpn(0) !== 0 && q.andln(1) === 0) { + s++; + q.ishrn(1); + } + assert(q.cmpn(0) !== 0); -module.exports = createScene + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); -var createCamera = require('3d-view-controls') -var createAxes = require('gl-axes3d') -var axesRanges = require('gl-axes3d/properties') -var createSpikes = require('gl-spikes3d') -var createSelect = require('gl-select-static') -var createFBO = require('gl-fbo') -var drawTriangle = require('a-big-triangle') -var mouseChange = require('mouse-change') -var perspective = require('gl-mat4/perspective') -var createShader = require('./lib/shader') + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).ishrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) + z.redIAdd(nOne); -function MouseSelect() { - this.mouse = [-1,-1] - this.screen = null - this.distance = Infinity - this.index = null - this.dataCoordinate = null - this.dataPosition = null - this.object = null - this.data = null -} + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).ishrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) + tmp = tmp.redSqr(); + assert(i < m); + var b = this.pow(c, new BN(1).ishln(m - i - 1)); -function getContext(canvas, options) { - var gl = null - try { - gl = canvas.getContext('webgl', options) - if(!gl) { - gl = canvas.getContext('experimental-webgl', options) - } - } catch(e) { - return null + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; } - return gl -} -function roundUpPow10(x) { - var y = Math.round(Math.log(Math.abs(x)) / Math.log(10)) - if(y < 0) { - var base = Math.round(Math.pow(10, -y)) - return Math.ceil(x*base) / base - } else if(y > 0) { - var base = Math.round(Math.pow(10, y)) - return Math.ceil(x/base) * base - } - return Math.ceil(x) -} + return r; +}; -function defaultBool(x) { - if(typeof x === 'boolean') { - return x +Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.sign) { + inv.sign = false; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); } - return true -} +}; -function createScene(options) { - options = options || {} +Red.prototype.pow = function pow(a, num) { + var w = []; - var stopped = false + if (num.cmpn(0) === 0) + return new BN(1); - var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio) + var q = num.clone(); - var canvas = options.canvas - if(!canvas) { - canvas = document.createElement('canvas') - if(options.container) { - var container = options.container - container.appendChild(canvas) - } else { - document.body.appendChild(canvas) - } + while (q.cmpn(0) !== 0) { + w.push(q.andln(1)); + q.ishrn(1); } - var gl = options.gl - if(!gl) { - gl = getContext(canvas, - options.glOptions || { - premultipliedAlpha: true, - antialias: true - }) - } - if(!gl) { - throw new Error('webgl not supported') + // Skip leading zeroes + var res = a; + for (var i = 0; i < w.length; i++, res = this.sqr(res)) + if (w[i] !== 0) + break; + + if (++i < w.length) { + for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { + if (w[i] === 0) + continue; + res = this.mul(res, q); + } } - //Initial bounds - var bounds = options.bounds || [[-10,-10,-10], [10,10,10]] + return res; +}; - //Create selection - var selection = new MouseSelect() +Red.prototype.convertTo = function convertTo(num) { + var r = num.mod(this.m); + if (r === num) + return r.clone(); + else + return r; +}; - //Accumulation buffer - var accumBuffer = createFBO(gl, - [gl.drawingBufferWidth, gl.drawingBufferHeight], { - preferFloat: true - }) +Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; +}; - var accumShader = createShader(gl) +// +// Montgomery method engine +// - //Create a camera - var cameraOptions = options.camera || { - eye: [2,0,0], - center: [0,0,0], - up: [0,1,0], - zoomMin: 0.1, - zoomMax: 100, - mode: 'turntable' - } +BN.mont = function mont(num) { + return new Mont(num); +}; - //Create axes - var axesOptions = options.axes || {} - var axes = createAxes(gl, axesOptions) - axes.enable = !axesOptions.disable +function Mont(m) { + Red.call(this, m); - //Create spikes - var spikeOptions = options.spikes || {} - var spikes = createSpikes(gl, spikeOptions) + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) + this.shift += 26 - (this.shift % 26); + this.r = new BN(1).ishln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); - //Object list is empty initially - var objects = [] - var pickBufferIds = [] - var pickBufferCount = [] - var pickBuffers = [] + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv.sign = true; + this.minv = this.minv.mod(this.r); +} +inherits(Mont, Red); - //Dirty flag, skip redraw if scene static - var dirty = true - var pickDirty = true +Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.shln(this.shift)); +}; - var projection = new Array(16) - var model = new Array(16) +Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; +}; - var cameraParams = { - view: null, - projection: projection, - model: model +Mont.prototype.imul = function imul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { + a.words[0] = 0; + a.length = 1; + return a; } - var pickDirty = true + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); - var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ] + return res._forceRed(this); +}; - //Create scene object - var scene = { - gl: gl, - contextLost: false, - pixelRatio: options.pixelRatio || parseFloat(window.devicePixelRatio), - canvas: canvas, - selection: selection, - camera: createCamera(canvas, cameraOptions), - axes: axes, - axesPixels: null, - spikes: spikes, - bounds: bounds, - objects: objects, - shape: viewShape, - aspect: options.aspectRatio || [1,1,1], - pickRadius: options.pickRadius || 10, - zNear: options.zNear || 0.01, - zFar: options.zFar || 1000, - fovy: options.fovy || Math.PI/4, - clearColor: options.clearColor || [0,0,0,0], - autoResize: defaultBool(options.autoResize), - autoBounds: defaultBool(options.autoBounds), - autoScale: !!options.autoScale, - autoCenter: defaultBool(options.autoCenter), - clipToBounds: defaultBool(options.clipToBounds), - snapToData: !!options.snapToData, - onselect: options.onselect || null, - onrender: options.onrender || null, - onclick: options.onclick || null, - cameraParams: cameraParams, - oncontextloss: null, - mouseListener: null - } +Mont.prototype.mul = function mul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) + return new BN(0)._forceRed(this); - var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ] + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); - function resizeListener() { - if(stopped) { - return + return res._forceRed(this); +}; + +Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); +}; + +})(typeof module === 'undefined' || module, this); + +},{}],384:[function(require,module,exports){ +(function (Buffer){ +var hasTypedArrays = false +if(typeof Float64Array !== "undefined") { + var DOUBLE_VIEW = new Float64Array(1) + , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) + DOUBLE_VIEW[0] = 1.0 + hasTypedArrays = true + if(UINT_VIEW[1] === 0x3ff00000) { + //Use little endian + module.exports = function doubleBitsLE(n) { + DOUBLE_VIEW[0] = n + return [ UINT_VIEW[0], UINT_VIEW[1] ] } - if(!scene.autoResize) { - return + function toDoubleLE(lo, hi) { + UINT_VIEW[0] = lo + UINT_VIEW[1] = hi + return DOUBLE_VIEW[0] } - var parent = canvas.parentNode - var width = 1 - var height = 1 - if(parent && parent !== document.body) { - width = parent.clientWidth - height = parent.clientHeight - } else { - width = window.innerWidth - height = window.innerHeight + module.exports.pack = toDoubleLE + function lowUintLE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[0] } - var nextWidth = Math.ceil(width * scene.pixelRatio)|0 - var nextHeight = Math.ceil(height * scene.pixelRatio)|0 - if(nextWidth !== canvas.width || nextHeight !== canvas.height) { - canvas.width = nextWidth - canvas.height = nextHeight - var style = canvas.style - style.position = style.position || 'absolute' - style.left = '0px' - style.top = '0px' - style.width = width + 'px' - style.height = height + 'px' - dirty = true + module.exports.lo = lowUintLE + function highUintLE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[1] } - } - if(scene.autoResize) { - resizeListener() - } - window.addEventListener('resize', resizeListener) - - function reallocPickIds() { - var numObjs = objects.length - var numPick = pickBuffers.length - for(var i=0; i 0 && pickBufferCount[numPick-1] === 0) { - pickBufferCount.pop() - pickBuffers.pop().dispose() + module.exports.pack = toDoubleBE + function lowUintBE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[1] } - } - - scene.update = function(options) { - if(stopped) { - return + module.exports.lo = lowUintBE + function highUintBE(n) { + DOUBLE_VIEW[0] = n + return UINT_VIEW[0] } - options = options || {} - dirty = true - pickDirty = true + module.exports.hi = highUintBE + } else { + hasTypedArrays = false } - - scene.add = function(obj) { - if(stopped) { - return - } - obj.axes = axes - objects.push(obj) - pickBufferIds.push(-1) - dirty = true - pickDirty = true - reallocPickIds() +} +if(!hasTypedArrays) { + var buffer = new Buffer(8) + module.exports = function doubleBits(n) { + buffer.writeDoubleLE(n, 0, true) + return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] } - - scene.remove = function(obj) { - if(stopped) { - return - } - var idx = objects.indexOf(obj) - if(idx < 0) { - return - } - objects.splice(idx, 1) - pickBufferIds.pop() - dirty = true - pickDirty = true - reallocPickIds() + function toDouble(lo, hi) { + buffer.writeUInt32LE(lo, 0, true) + buffer.writeUInt32LE(hi, 4, true) + return buffer.readDoubleLE(0, true) + } + module.exports.pack = toDouble + function lowUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(0, true) + } + module.exports.lo = lowUint + function highUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(4, true) } + module.exports.hi = highUint +} - scene.dispose = function() { - if(stopped) { - return - } +module.exports.sign = function(n) { + return module.exports.hi(n) >>> 31 +} - stopped = true +module.exports.exponent = function(n) { + var b = module.exports.hi(n) + return ((b<<1) >>> 21) - 1023 +} - window.removeEventListener('resize', resizeListener) - canvas.removeEventListener('webglcontextlost', checkContextLoss) - scene.mouseListener.enabled = false +module.exports.fraction = function(n) { + var lo = module.exports.lo(n) + var hi = module.exports.hi(n) + var b = hi & ((1<<20) - 1) + if(hi & 0x7ff00000) { + b += (1<<20) + } + return [lo, b] +} - if(scene.contextLost) { - return - } +module.exports.denormalized = function(n) { + var hi = module.exports.hi(n) + return !(hi & 0x7ff00000) +} +}).call(this,require("buffer").Buffer) +},{"buffer":65}],385:[function(require,module,exports){ +'use strict' - //Destroy objects - axes.dispose() - spikes.dispose() - for(var i=0; i selection.distance) { - continue - } - for(var j=0; j>>1 + if(d <= 0) { + return + } - //Tick camera - var cameraMoved = scene.camera.tick() - cameraParams.view = scene.camera.matrix - dirty = dirty || cameraMoved - pickDirty = pickDirty || cameraMoved + var retval - //Set pixel ratio - axes.pixelRatio = scene.pixelRatio - spikes.pixelRatio = scene.pixelRatio + //Convert red boxes + var redList = pool.mallocDouble(2*d*n) + var redIds = pool.mallocInt32(n) + n = convertBoxes(red, d, redList, redIds) - //Check if any objects changed, recalculate bounds - var numObjs = objects.length - var lo = nBounds[0] - var hi = nBounds[1] - lo[0] = lo[1] = lo[2] = Infinity - hi[0] = hi[1] = hi[2] = -Infinity - for(var i=0; i 0) { + if(d === 1 && full) { + //Special case: 1d complete + sweep.init(n) + retval = sweep.sweepComplete( + d, visit, + 0, n, redList, redIds, + 0, n, redList, redIds) + } else { - //Set the axes properties for each object - obj.pixelRatio = scene.pixelRatio - obj.axes = scene.axes + //Convert blue boxes + var blueList = pool.mallocDouble(2*d*m) + var blueIds = pool.mallocInt32(m) + m = convertBoxes(blue, d, blueList, blueIds) - dirty = dirty || !!obj.dirty - pickDirty = pickDirty || !!obj.dirty - var obb = obj.bounds - if(obb) { - var olo = obb[0] - var ohi = obb[1] - for(var j=0; j<3; ++j) { - lo[j] = Math.min(lo[j], olo[j]) - hi[j] = Math.max(hi[j], ohi[j]) - } - } - } + if(m > 0) { + sweep.init(n+m) - //Recalculate bounds - var bounds = scene.bounds - if(scene.autoBounds) { - for(var j=0; j<3; ++j) { - if(hi[j] < lo[j]) { - lo[j] = -1 - hi[j] = 1 + if(d === 1) { + //Special case: 1d bipartite + retval = sweep.sweepBipartite( + d, visit, + 0, n, redList, redIds, + 0, m, blueList, blueIds) } else { - if(lo[j] === hi[j]) { - lo[j] -= 1 - hi[j] += 1 - } - var padding = 0.05 * (hi[j] - lo[j]) - lo[j] = lo[j] - padding - hi[j] = hi[j] + padding + //General case: d>1 + retval = boxIntersectIter( + d, visit, full, + n, redList, redIds, + m, blueList, blueIds) } - bounds[0][j] = lo[j] - bounds[1][j] = hi[j] - } - } - - var boundsChanged = false - for(var j=0; j<3; ++j) { - boundsChanged = boundsChanged || - (prevBounds[0][j] !== bounds[0][j]) || - (prevBounds[1][j] !== bounds[1][j]) - prevBounds[0][j] = bounds[0][j] - prevBounds[1][j] = bounds[1][j] - } - if(boundsChanged) { - var tickSpacing = [0,0,0] - for(var i=0; i<3; ++i) { - tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0) - } - if(axes.autoTicks) { - axes.update({ - bounds: bounds, - tickSpacing: tickSpacing - }) - } else { - axes.update({ - bounds: bounds - }) + pool.free(blueList) + pool.free(blueIds) } } - //Recalculate bounds - pickDirty = pickDirty || boundsChanged - dirty = dirty || boundsChanged - - //Get scene - var width = gl.drawingBufferWidth - var height = gl.drawingBufferHeight - viewShape[0] = width - viewShape[1] = height - pickShape[0] = Math.max(width/scene.pixelRatio, 1)|0 - pickShape[1] = Math.max(height/scene.pixelRatio, 1)|0 - - //Compute camera parameters - perspective(projection, - scene.fovy, - width/height, - scene.zNear, - scene.zFar) + pool.free(redList) + pool.free(redIds) + } - //Compute model matrix - for(var i=0; i<16; ++i) { - model[i] = 0 - } - model[15] = 1 + return retval +} - var maxS = 0 - for(var i=0; i<3; ++i) { - maxS = Math.max(maxS, bounds[1][i] - bounds[0][i]) - } - for(var i=0; i<3; ++i) { - if(scene.autoScale) { - model[5*i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i]) - } else { - model[5*i] = 1 / maxS - } - if(scene.autoCenter) { - model[12+i] = -model[5*i] * 0.5 * (bounds[0][i] + bounds[1][i]) - } - } +var RESULT - //Apply axes/clip bounds - for(var i=0; i' + + BLUE_END + '-' + BLUE_START + '){') + if(full) { + invoke(true, false) + code.push('}else{') + invoke(false, false) + } else { + code.push('if(' + FLIP + '){') + invoke(true, true) + code.push('}else{') + invoke(true, false) + code.push('}}else{if(' + FLIP + '){') + invoke(false, true) + code.push('}else{') + invoke(false, false) + code.push('}') + } + code.push('}}return ' + funcName) -module.exports = { - vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", - fragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n", - pickVertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", - pickFragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n" + var codeStr = prefix.join('') + code.join('') + var proc = new Function(codeStr) + return proc() } -},{}],185:[function(require,module,exports){ + +exports.partial = bruteForcePlanner(false) +exports.full = bruteForcePlanner(true) +},{}],390:[function(require,module,exports){ 'use strict' -module.exports = createFancyScatter2D +module.exports = boxIntersectIter -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var textCache = require('text-cache') var pool = require('typedarray-pool') -var vectorizeText = require('vectorize-text') -var shaders = require('./lib/shaders') - -var BOUNDARIES = {} - -function getBoundary(glyph) { - if(glyph in BOUNDARIES) { - return BOUNDARIES[glyph] - } +var bits = require('bit-twiddle') +var bruteForce = require('./brute') +var bruteForcePartial = bruteForce.partial +var bruteForceFull = bruteForce.full +var sweep = require('./sweep') +var findMedian = require('./median') +var genPartition = require('./partition') - var polys = vectorizeText(glyph, { - polygons: true, - font: 'sans-serif', - textAlign: 'left', - textBaseline: 'alphabetic' - }) +//Twiddle parameters +var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search +var SCAN_CUTOFF = (1<<22) //Cut off for two way scan +var SCAN_COMPLETE_CUTOFF = (1<<22) - var coords = [] - var normals = [] +//Partition functions +var partitionInteriorContainsInterval = genPartition( + '!(lo>=p0)&&!(p1>=hi)', + ['p0', 'p1']) - polys.forEach(function(loops) { - loops.forEach(function(loop) { - for(var i=0; i 0) { + top -= 1 - proto.drawPick = function(offset) { - var plot = this.plot - var shader = this.pickShader - var numVertices = this.numVertices + var iptr = top * IFRAME_SIZE + var axis = BOX_ISTACK[iptr] + var redStart = BOX_ISTACK[iptr+1] + var redEnd = BOX_ISTACK[iptr+2] + var blueStart = BOX_ISTACK[iptr+3] + var blueEnd = BOX_ISTACK[iptr+4] + var state = BOX_ISTACK[iptr+5] - var gl = plot.gl + var dptr = top * DFRAME_SIZE + var lo = BOX_DSTACK[dptr] + var hi = BOX_DSTACK[dptr+1] - this.pickOffset = offset + //Unpack state info + var flip = (state & 1) + var full = !!(state & 16) - if(!numVertices) { - return offset + //Unpack indices + var red = xBoxes + var redIndex = xIndex + var blue = yBoxes + var blueIndex = yIndex + if(flip) { + red = yBoxes + redIndex = yIndex + blue = xBoxes + blueIndex = xIndex } - for(var i=0; i<4; ++i) { - PICK_OFFSET[i] = ((offset>>(i*8)) & 0xff) + if(state & 2) { + redEnd = partitionStartLessThan( + d, axis, + redStart, redEnd, red, redIndex, + hi) + if(redStart >= redEnd) { + continue + } + } + if(state & 4) { + redStart = partitionEndLessThanEqual( + d, axis, + redStart, redEnd, red, redIndex, + lo) + if(redStart >= redEnd) { + continue + } + } + + var redCount = redEnd - redStart + var blueCount = blueEnd - blueStart + + if(full) { + if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { + retval = sweep.scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } + } else { + if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { + //If input small, then use brute force + retval = bruteForcePartial( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } else if(d * redCount * blueCount < SCAN_CUTOFF) { + //If input medium sized, then use sweep and prune + retval = sweep.scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue + } } + + //First, find all red intervals whose interior contains (lo,hi) + var red0 = partitionInteriorContainsInterval( + d, axis, + redStart, redEnd, red, redIndex, + lo, hi) - calcScales.call(this) - - shader.bind() + //Lower dimensional case + if(redStart < red0) { - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.viewTransform = MATRIX - shader.uniforms.pickOffset = PICK_OFFSET + if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { + //Special case for small inputs: use brute force + retval = bruteForceFull( + d, axis+1, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } else if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blueStart, blueEnd, blue, blueIndex, + redStart, red0, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + } + if(retval !== void 0) { + return retval + } + } else { + iterPush(top++, + axis+1, + redStart, red0, + blueStart, blueEnd, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blueStart, blueEnd, + redStart, red0, + flip^1, + -Infinity, Infinity) + } + } - this.positionBuffer.bind() - shader.attributes.position.pointer() + //Divide and conquer phase + if(red0 < redEnd) { - this.offsetBuffer.bind() - shader.attributes.offset.pointer() + //Cut blue into 3 parts: + // + // Points < mid point + // Points = mid point + // Points > mid point + // + var blue0 = findMedian( + d, axis, + blueStart, blueEnd, blue, blueIndex) + var mid = blue[elemSize * blue0 + axis] + var blue1 = partitionStartEqual( + d, axis, + blue0, blueEnd, blue, blueIndex, + mid) - this.idBuffer.bind() - shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false) + //Right case + if(blue1 < blueEnd) { + iterPush(top++, + axis, + red0, redEnd, + blue1, blueEnd, + (flip|4) + (full ? 16 : 0), + mid, hi) + } - gl.drawArrays(gl.TRIANGLES, 0, numVertices) + //Left case + if(blueStart < blue0) { + iterPush(top++, + axis, + red0, redEnd, + blueStart, blue0, + (flip|2) + (full ? 16 : 0), + lo, mid) + } - return offset + this.numPoints - } -})() + //Center case (the hard part) + if(blue0 + 1 === blue1) { + //Optimization: Range with exactly 1 point, use a brute force scan + if(full) { + retval = onePointFull( + d, axis, visit, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) + } else { + retval = onePointPartial( + d, axis, visit, flip, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) + } + if(retval !== void 0) { + return retval + } + } else if(blue0 < blue1) { + var red1 + if(full) { + //If full intersection, need to handle special case + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + if(red0 < red1) { + var redX = partitionStartEqual( + d, axis, + red0, red1, red, redIndex, + mid) + if(axis === d-2) { + //Degenerate sweep intersection: + // [red0, redX] with [blue0, blue1] + if(red0 < redX) { + retval = sweep.sweepComplete( + d, visit, + red0, redX, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.numPoints - if(value < pickOffset || value >= pickOffset + pointCount) { - return null - } - var pointId = value - pickOffset - var points = this.points - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + //Normal sweep intersection: + // [redX, red1] with [blue0, blue1] + if(redX < red1) { + retval = sweep.sweepBipartite( + d, visit, + redX, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } + } else { + if(red0 < redX) { + iterPush(top++, + axis+1, + red0, redX, + blue0, blue1, + 16, + -Infinity, Infinity) + } + if(redX < red1) { + iterPush(top++, + axis+1, + redX, red1, + blue0, blue1, + 0, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + redX, red1, + 1, + -Infinity, Infinity) + } + } + } + } else { + if(flip) { + red1 = partitionContainsPointProper( + d, axis, + red0, redEnd, red, redIndex, + mid) + } else { + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + } + if(red0 < red1) { + if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blue0, blue1, blue, blueIndex, + red0, red1, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + red0, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + } + } else { + iterPush(top++, + axis+1, + red0, red1, + blue0, blue1, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + red0, red1, + flip^1, + -Infinity, Infinity) + } + } + } + } + } } } +},{"./brute":389,"./median":391,"./partition":392,"./sweep":394,"bit-twiddle":395,"typedarray-pool":397}],391:[function(require,module,exports){ +'use strict' -proto.update = function(options) { - options = options || {} +module.exports = findMedian - var positions = options.positions || [] - var colors = options.colors || [] - var glyphs = options.glyphs || [] - var sizes = options.sizes || [] - var borderWidths = options.borderWidths || [] - var borderColors = options.borderColors || [] +var genPartition = require('./partition') - this.points = positions +var partitionStartLessThan = genPartition('lo> 1 - for(var j=0; j<2; ++j) { - bounds[j] = Math.min(bounds[j], positions[2*i+j]) - bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j]) +var PARTITION_THRESHOLD = 8 //Cut off for using insertion sort in findMedian + +//Base case for median finding: Use insertion sort +function insertionSort(d, axis, start, end, boxes, ids) { + var elemSize = 2 * d + var boxPtr = elemSize * (start+1) + axis + for(var i=start+1; istart && boxes[ptr+axis] > x; + --j, ptr-=elemSize) { + //Swap + var aPtr = ptr + var bPtr = ptr+elemSize + for(var k=0; k>> 1) + var elemSize = 2*d + var pivot = mid + var value = boxes[elemSize*mid+axis] + + while(lo < hi) { + if(hi - lo < PARTITION_THRESHOLD) { + insertionSort(d, axis, lo, hi, boxes, ids) + value = boxes[elemSize*mid+axis] + break + } + + //Select pivot using median-of-3 + var count = hi - lo + var pivot0 = (Math.random()*count+lo)|0 + var value0 = boxes[elemSize*pivot0 + axis] + var pivot1 = (Math.random()*count+lo)|0 + var value1 = boxes[elemSize*pivot1 + axis] + var pivot2 = (Math.random()*count+lo)|0 + var value2 = boxes[elemSize*pivot2 + axis] + if(value0 <= value1) { + if(value2 >= value1) { + pivot = pivot1 + value = value1 + } else if(value0 >= value2) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } + } else { + if(value1 >= value2) { + pivot = pivot1 + value = value1 + } else if(value2 >= value0) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } + } - ptr += 1 + //Swap pivot to end of array + var aPtr = elemSize * (hi-1) + var bPtr = elemSize * pivot + for(var i=0; i= 0) { + reads.push('lo=e[k+n]') + } + if(predicate.indexOf('hi') >= 0) { + reads.push('hi=e[k+o]') + } + fargs.push( + code.replace('_', reads.join()) + .replace('$', predicate)) + return Function.apply(void 0, fargs) } +},{}],393:[function(require,module,exports){ +'use strict'; -},{"./lib/shaders":184,"gl-buffer":118,"gl-shader":197,"text-cache":273,"typedarray-pool":278,"vectorize-text":280}],186:[function(require,module,exports){ - - -exports.pointVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute float weight;\n\nuniform mat3 matrix;\nuniform float pointSize, useWeight;\n\nvarying float fragWeight;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n fragWeight = mix(1.0, weight, useWeight);\n}\n" -exports.pointFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\n\nvarying float fragWeight;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, fragWeight);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n" -exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n" -exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n" - -},{}],187:[function(require,module,exports){ -arguments[4][62][0].apply(exports,arguments) -},{"dup":62}],188:[function(require,module,exports){ -'use strict' +//This code is extracted from ndarray-sort +//It is inlined here as a temporary workaround -module.exports = sortLevels +module.exports = wrapper; var INSERT_SORT_CUTOFF = 32 -function sortLevels(data_levels, data_points, data_ids, data_weights, n0) { +function wrapper(data, n0) { if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) + insertionSort(0, n0 - 1, data); } else { - quickSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) + quickSort(0, n0 - 1, data); } } -function insertionSort(left, right, data_levels, data_points, data_ids, data_weights) { +function insertionSort(left, right, data) { + var ptr = 2*(left+1) for(var i=left+1; i<=right; ++i) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - + var a = data[ptr++] + var b = data[ptr++] var j = i - while(j > left) { - var b_level = data_levels[j-1] - var b_x = data_points[2*(j-1)] - if(((b_level - a_level) || (a_x - b_x)) >= 0) { + var jptr = ptr-2 + while(j-- > left) { + var x = data[jptr-2] + var y = data[jptr-1] + if(x < a) { + break + } else if(x === a && y < b) { break } - data_levels[j] = b_level - data_points[2*j] = b_x - data_points[2*j+1] = data_points[2*j-1] - data_ids[j] = data_ids[j-1] - data_weights[j] = data_weights[j-1] - j -= 1 + data[jptr] = x + data[jptr+1] = y + jptr -= 2 } - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight + data[jptr] = a + data[jptr+1] = b } } -function swap(i, j, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight +function swap(i, j, data) { + i *= 2 + j *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = x + data[j+1] = y } -function move(i, j, data_levels, data_points, data_ids, data_weights) { - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] +function move(i, j, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[i+1] = data[j+1] } -function rotate(i, j, k, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = data_levels[k] - data_points[2*j] = data_points[2*k] - data_points[2*j+1] = data_points[2*k+1] - data_ids[j] = data_ids[k] - data_weights[j] = data_weights[k] - - data_levels[k] = a_level - data_points[2*k] = a_x - data_points[2*k+1] = a_y - data_ids[k] = a_id - data_weights[k] = a_weight +function rotate(i, j, k, data) { + i *= 2 + j *= 2 + k *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = data[k] + data[j+1] = data[k+1] + data[k] = x + data[k+1] = y } -function shufflePivot( - i, j, - a_level, a_x, a_y, a_id, a_weight, - data_levels, data_points, data_ids, data_weights) { - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight +function shufflePivot(i, j, px, py, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[j] = px + data[i+1] = data[j+1] + data[j+1] = py } -function compare(i, j, data_levels, data_points, data_ids) { - return ((data_levels[i] - data_levels[j]) || - (data_points[2*j] - data_points[2*i]) || - (data_ids[i] - data_ids[j])) < 0 +function compare(i, j, data) { + i *= 2 + j *= 2 + var x = data[i], + y = data[j] + if(x < y) { + return false + } else if(x === y) { + return data[i+1] > data[j+1] + } + return true } -function comparePivot(i, level, x, y, id, data_levels, data_points, data_ids) { - return ((level - data_levels[i]) || - (data_points[2*i] - x) || - (id - data_ids[i])) < 0 +function comparePivot(i, y, b, data) { + i *= 2 + var x = data[i] + if(x < y) { + return true + } else if(x === y) { + return data[i+1] < b + } + return false } -function quickSort(left, right, data_levels, data_points, data_ids, data_weights) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, +function quickSort(left, right, data) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, tmp = 0 - if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) { + if(compare(el1, el2, data)) { tmp = el1 el1 = el2 el2 = tmp } - if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + if(compare(el4, el5, data)) { tmp = el4 el4 = el5 el5 = tmp } - if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) { + if(compare(el1, el3, data)) { tmp = el1 el1 = el3 el3 = tmp } - if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + if(compare(el2, el3, data)) { tmp = el2 el2 = el3 el3 = tmp } - if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) { + if(compare(el1, el4, data)) { tmp = el1 el1 = el4 el4 = tmp } - if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) { + if(compare(el3, el4, data)) { tmp = el3 el3 = el4 el4 = tmp } - if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) { + if(compare(el2, el5, data)) { tmp = el2 el2 = el5 el5 = tmp } - if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + if(compare(el2, el3, data)) { tmp = el2 el2 = el3 el3 = tmp } - if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + if(compare(el4, el5, data)) { tmp = el4 el4 = el5 el5 = tmp } - var pivot1_level = data_levels[el2] - var pivot1_x = data_points[2*el2] - var pivot1_y = data_points[2*el2+1] - var pivot1_id = data_ids[el2] - var pivot1_weight = data_weights[el2] + var pivot1X = data[2*el2] + var pivot1Y = data[2*el2+1] + var pivot2X = data[2*el4] + var pivot2Y = data[2*el4+1] - var pivot2_level = data_levels[el4] - var pivot2_x = data_points[2*el4] - var pivot2_y = data_points[2*el4+1] - var pivot2_id = data_ids[el4] - var pivot2_weight = data_weights[el4] + var ptr0 = 2 * el1; + var ptr2 = 2 * el3; + var ptr4 = 2 * el5; + var ptr5 = 2 * index1; + var ptr6 = 2 * index3; + var ptr7 = 2 * index5; + for (var i1 = 0; i1 < 2; ++i1) { + var x = data[ptr0+i1]; + var y = data[ptr2+i1]; + var z = data[ptr4+i1]; + data[ptr5+i1] = x; + data[ptr6+i1] = y; + data[ptr7+i1] = z; + } - var ptr0 = el1 - var ptr2 = el3 - var ptr4 = el5 - var ptr5 = index1 - var ptr6 = index3 - var ptr7 = index5 + move(index2, left, data) + move(index4, right, data) + for (var k = less; k <= great; ++k) { + if (comparePivot(k, pivot1X, pivot1Y, data)) { + if (k !== less) { + swap(k, less, data) + } + ++less; + } else { + if (!comparePivot(k, pivot2X, pivot2Y, data)) { + while (true) { + if (!comparePivot(great, pivot2X, pivot2Y, data)) { + if (--great < k) { + break; + } + continue; + } else { + if (comparePivot(great, pivot1X, pivot1Y, data)) { + rotate(k, less, great, data) + ++less; + --great; + } else { + swap(k, great, data) + --great; + } + break; + } + } + } + } + } + shufflePivot(left, less-1, pivot1X, pivot1Y, data) + shufflePivot(right, great+1, pivot2X, pivot2Y, data) + if (less - 2 - left <= INSERT_SORT_CUTOFF) { + insertionSort(left, less - 2, data); + } else { + quickSort(left, less - 2, data); + } + if (right - (great + 2) <= INSERT_SORT_CUTOFF) { + insertionSort(great + 2, right, data); + } else { + quickSort(great + 2, right, data); + } + if (great - less <= INSERT_SORT_CUTOFF) { + insertionSort(less, great, data); + } else { + quickSort(less, great, data); + } +} +},{}],394:[function(require,module,exports){ +'use strict' - var level_x = data_levels[ptr0] - var level_y = data_levels[ptr2] - var level_z = data_levels[ptr4] - data_levels[ptr5] = level_x - data_levels[ptr6] = level_y - data_levels[ptr7] = level_z +module.exports = { + init: sqInit, + sweepBipartite: sweepBipartite, + sweepComplete: sweepComplete, + scanBipartite: scanBipartite, + scanComplete: scanComplete +} - for (var i1 = 0; i1 < 2; ++i1) { - var x = data_points[2*ptr0+i1] - var y = data_points[2*ptr2+i1] - var z = data_points[2*ptr4+i1] - data_points[2*ptr5+i1] = x - data_points[2*ptr6+i1] = y - data_points[2*ptr7+i1] = z +var pool = require('typedarray-pool') +var bits = require('bit-twiddle') +var isort = require('./sort') + +//Flag for blue +var BLUE_FLAG = (1<<28) + +//1D sweep event queue stuff (use pool to save space) +var INIT_CAPACITY = 1024 +var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) + +//Reserves memory for the 1D sweep data structures +function sqInit(count) { + var rcount = bits.nextPow2(count) + if(RED_SWEEP_QUEUE.length < rcount) { + pool.free(RED_SWEEP_QUEUE) + RED_SWEEP_QUEUE = pool.mallocInt32(rcount) + } + if(RED_SWEEP_INDEX.length < rcount) { + pool.free(RED_SWEEP_INDEX) + RED_SWEEP_INDEX = pool.mallocInt32(rcount) + } + if(BLUE_SWEEP_QUEUE.length < rcount) { + pool.free(BLUE_SWEEP_QUEUE) + BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) + } + if(BLUE_SWEEP_INDEX.length < rcount) { + pool.free(BLUE_SWEEP_INDEX) + BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) + } + if(COMMON_SWEEP_QUEUE.length < rcount) { + pool.free(COMMON_SWEEP_QUEUE) + COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) + } + if(COMMON_SWEEP_INDEX.length < rcount) { + pool.free(COMMON_SWEEP_INDEX) + COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) + } + var eventLength = 8 * rcount + if(SWEEP_EVENTS.length < eventLength) { + pool.free(SWEEP_EVENTS) + SWEEP_EVENTS = pool.mallocDouble(eventLength) } +} - var id_x = data_ids[ptr0] - var id_y = data_ids[ptr2] - var id_z = data_ids[ptr4] - data_ids[ptr5] = id_x - data_ids[ptr6] = id_y - data_ids[ptr7] = id_z +//Remove an item from the active queue in O(1) +function sqPop(queue, index, count, item) { + var idx = index[item] + var top = queue[count-1] + queue[idx] = top + index[top] = idx +} - var weight_x = data_weights[ptr0] - var weight_y = data_weights[ptr2] - var weight_z = data_weights[ptr4] - data_weights[ptr5] = weight_x - data_weights[ptr6] = weight_y - data_weights[ptr7] = weight_z +//Insert an item into the active queue in O(1) +function sqPush(queue, index, count, item) { + queue[count] = item + index[item] = count +} + +//Recursion base case: use 1D sweep algorithm +function sweepBipartite( + d, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + //store events as pairs [coordinate, idx] + // + // red create: -(idx+1) + // red destroy: idx + // blue create: -(idx+BLUE_FLAG) + // blue destroy: idx+BLUE_FLAG + // + var ptr = 0 + var elemSize = 2*d + var istart = d-1 + var iend = elemSize-1 + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + for(var i=0; i= BLUE_FLAG) { + //blue destroy event + e = (e-BLUE_FLAG)|0 + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) + } else if(e >= 0) { + //red destroy event + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) + } else if(e <= -BLUE_FLAG) { + //blue create event + e = (-e-BLUE_FLAG)|0 + for(var j=0; jright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + var commonActive = 0 + for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { + color = 2 + i += 1 + } + + if(e < 0) { + //Create event + var id = -(e>>1) - 1 - move(index2, left, data_levels, data_points, data_ids, data_weights) - move(index4, right, data_levels, data_points, data_ids, data_weights) - for (var k = less; k <= great; ++k) { - if (comparePivot(k, - pivot1_level, pivot1_x, pivot1_y, pivot1_id, - data_levels, data_points, data_ids)) { - if (k !== less) { - swap(k, less, data_levels, data_points, data_ids, data_weights) + //Intersect with common + for(var j=0; j>1) - 1 + if(color === 0) { + //Red + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) + } else if(color === 1) { + //Blue + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) + } else if(color === 2) { + //Both + sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) + } } } - shufflePivot(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) - shufflePivot(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) - if (less - 2 - left <= INSERT_SORT_CUTOFF) { - insertionSort(left, less - 2, data_levels, data_points, data_ids, data_weights) +} + +//Sweep and prune/scanline algorithm: +// Scan along axis, detect intersections +// Brute force all boxes along axis +function scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = axis + var iend = axis+d + + var redShift = 1 + var blueShift = 1 + if(flip) { + blueShift = BLUE_FLAG } else { - quickSort(left, less - 2, data_levels, data_points, data_ids, data_weights) + redShift = BLUE_FLAG } - if (right - (great + 2) <= INSERT_SORT_CUTOFF) { - insertionSort(great + 2, right, data_levels, data_points, data_ids, data_weights) - } else { - quickSort(great + 2, right, data_levels, data_points, data_ids, data_weights) + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + isRed = !flip + idx -= BLUE_FLAG + } else { + isRed = !!flip + idx -= 1 + } + if(isRed) { + sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) + } else { + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] -var pool = require('typedarray-pool') +red_loop: + for(var j=0; j>> 1 - if(n < 1) { - return [] - } +function scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { - var lox = Infinity, loy = Infinity - var hix = -Infinity, hiy = -Infinity - for(var i=0; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG + } else { + idx -= 1 + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx - bounds = bounds || [0,0,0,0] + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] - bounds[0] = lox - bounds[1] = loy - bounds[2] = hix - bounds[3] = hiy +red_loop: + for(var j=0; j= Math.max(0.9 * count, 32)) { - var mid = (end + start)>>>1 - snapRec(nx, ny, diam_2, offset, mid, level+1) - offset = mid + } + } else { + var idx = e - BLUE_FLAG + for(var j=redActive-1; j>=0; --j) { + if(RED_SWEEP_QUEUE[j] === idx) { + for(var k=j+1; k=0; --ptr) { - points[2*ptr] = (points[2*ptr] - lox) * scaleX - points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY +var doubleBits = require("double-bits") - var level = levels[ptr] - if(level === lastLevel) { - continue - } +var SMALLEST_DENORM = Math.pow(2, -1074) +var UINT_MAX = (-1)>>>0 - lod.push(new SnapInterval( - diam * Math.pow(0.5, level), - ptr+1, - prevOffset - (ptr+1) - )) - prevOffset = ptr+1 +module.exports = nextafter - lastLevel = level +function nextafter(x, y) { + if(isNaN(x) || isNaN(y)) { + return NaN } - - lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) - pool.free(levels) - - return lod + if(x === y) { + return x + } + if(x === 0) { + if(y < 0) { + return -SMALLEST_DENORM + } else { + return SMALLEST_DENORM + } + } + var hi = doubleBits.hi(x) + var lo = doubleBits.lo(x) + if((y > x) === (x > 0)) { + if(lo === UINT_MAX) { + hi += 1 + lo = 0 + } else { + lo += 1 + } + } else { + if(lo === 0) { + lo = UINT_MAX + hi -= 1 + } else { + lo -= 1 + } + } + return doubleBits.pack(lo, hi) } - -},{"./lib/sort":188,"typedarray-pool":278}],190:[function(require,module,exports){ +},{"double-bits":400}],400:[function(require,module,exports){ +arguments[4][384][0].apply(exports,arguments) +},{"buffer":65,"dup":384}],401:[function(require,module,exports){ 'use strict' -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var bsearch = require('binary-search-bounds') -var snapPoints = require('snap-points-2d') - -var pool = require('typedarray-pool') - -var SHADERS = require('./lib/shader') - -module.exports = createScatter2D - -function Scatter2D(plot, offsetBuffer, pickBuffer, weightBuffer, shader, pickShader) { - this.plot = plot - this.offsetBuffer = offsetBuffer - this.pickBuffer = pickBuffer - this.weightBuffer = weightBuffer - this.shader = shader - this.pickShader = pickShader - this.scales = [] - this.size = 12.0 - this.borderSize = 1.0 - this.pointCount = 0 - this.color = [1,0,0,1] - this.borderColor = [0,0,0,1] - this.bounds = [Infinity,Infinity,-Infinity,-Infinity] - this.pickOffset = 0 - this.points = null - this.xCoords = null -} +var bnadd = require('big-rat/add') -var proto = Scatter2D.prototype +module.exports = add -proto.dispose = function() { - this.shader.dispose() - this.pickShader.dispose() - this.offsetBuffer.dispose() - this.pickBuffer.dispose() - if(this.xCoords) { - pool.free(this.xCoords) +function add(a, b) { + var n = a.length + var r = new Array(n) + for(var i=0; i>>1) - packed.set(data) - var packedW = pool.mallocFloat32(data.length) - this.points = data - this.scales = snapPoints(packed, packedId, packedW, this.bounds) - this.offsetBuffer.update(packed) - this.pickBuffer.update(packedId) - this.weightBuffer.update(packedW) - var xCoords = pool.mallocFloat32(data.length>>>1) - for(var i=0,j=0; i>> 1 - this.pickOffset = 0 + return result } -proto.drawPick = (function() { - var MATRIX = [1,0,0, - 0,1,0, - 0,0,1] - var PICK_VEC4 = [0,0,0,0] -return function(pickOffset) { - var plot = this.plot - var shader = this.pickShader - var scales = this.scales - var offsetBuffer = this.offsetBuffer - var pickBuffer = this.pickBuffer - var bounds = this.bounds - var size = this.size - var borderSize = this.borderSize - var gl = plot.gl - var pixelRatio = plot.pickPixelRatio - var viewBox = plot.viewBox - var dataBox = plot.dataBox +},{"big-rat":372}],403:[function(require,module,exports){ +'use strict' + +var rat = require('big-rat') +var mul = require('big-rat/mul') - if(this.pointCount === 0) { - return pickOffset +module.exports = muls + +function muls(a, x) { + var s = rat(x) + var n = a.length + var r = new Array(n) + for(var i=0; i>8) & 0xff) - PICK_VEC4[2] = ((pickOffset>>16) & 0xff) - PICK_VEC4[3] = ((pickOffset>>24) & 0xff) +},{"big-rat/sub":386}],405:[function(require,module,exports){ +"use strict" - shader.bind() - shader.uniforms.matrix = MATRIX - shader.uniforms.color = this.color - shader.uniforms.borderColor = this.borderColor - shader.uniforms.pointSize = pixelRatio * (size + borderSize) - shader.uniforms.pickOffset = PICK_VEC4 +module.exports = segmentsIntersect - if(this.borderSize === 0) { - shader.uniforms.centerFraction = 2.0; - } else { - shader.uniforms.centerFraction = size / (size + borderSize + 1.25) - } +var orient = require("robust-orientation")[3] - offsetBuffer.bind() - shader.attributes.position.pointer() - pickBuffer.bind() - shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE) +function checkCollinear(a0, a1, b0, b1) { - var xCoords = this.xCoords - var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX - var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX + for(var d=0; d<2; ++d) { + var x0 = a0[d] + var y0 = a1[d] + var l0 = Math.min(x0, y0) + var h0 = Math.max(x0, y0) - for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { - var lod = scales[scaleNum] - if(lod.pixelSize < pixelSize && scaleNum > 1) { - continue + var x1 = b0[d] + var y1 = b1[d] + var l1 = Math.min(x1, y1) + var h1 = Math.max(x1, y1) + + if(h1 < l0 || h0 < l1) { + return false } + } - var intervalStart = lod.offset - var intervalEnd = lod.count + intervalStart + return true +} - var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) - var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 +function segmentsIntersect(a0, a1, b0, b1) { + var x0 = orient(a0, b0, b1) + var y0 = orient(a1, b0, b1) + if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { + return false + } - if(endOffset > startOffset) { - gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) - } + var x1 = orient(b0, a0, a1) + var y1 = orient(b1, a0, a1) + if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { + return false } - return pickOffset + this.pointCount + //Check for degenerate collinear case + if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { + return checkCollinear(a0, a1, b0, b1) + } + + return true } -})() +},{"robust-orientation":1040}],406:[function(require,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],407:[function(require,module,exports){ +'use strict' -proto.draw = (function() { - var MATRIX = [1, 0, 0, - 0, 1, 0, - 0, 0, 1] +module.exports = trimLeaves - return function() { - var plot = this.plot - var shader = this.shader - var scales = this.scales - var offsetBuffer = this.offsetBuffer - var bounds = this.bounds - var size = this.size - var borderSize = this.borderSize - var gl = plot.gl - var pixelRatio = plot.pixelRatio - var viewBox = plot.viewBox - var dataBox = plot.dataBox +var e2a = require('edges-to-adjacency-list') - if(this.pointCount === 0) { - return +function trimLeaves(edges, positions) { + var adj = e2a(edges, positions.length) + var live = new Array(positions.length) + var nbhd = new Array(positions.length) + + var dead = [] + for(var i=0; i 0) { + var v = dead.pop() + live[v] = false + var n = adj[v] + for(var i=0; i= 0; --scaleNum) { - var lod = scales[scaleNum] - if(lod.pixelSize < pixelSize && scaleNum > 1) { - continue - } + var cycles = [] - var intervalStart = lod.offset - var intervalEnd = lod.count + intervalStart + //Add isolated vertices as trivial case + for(var i=0; i startOffset) { - gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + //Find next vertex and cut edge + function next(a, b, noCut) { + var nextCell, nextVertex, nextDir + for(var i=0; i<2; ++i) { + if(adj[i][b].length > 0) { + nextCell = adj[i][b][0] + nextDir = i + break } + } + nextVertex = nextCell[nextDir^1] - if(firstLevel) { - firstLevel = false - shader.uniforms.useWeight = 0 + for(var dir=0; dir<2; ++dir) { + var nbhd = adj[dir][b] + for(var k=0; k 0) { + nextCell = e + nextVertex = p + nextDir = dir + } } } + if(noCut) { + return nextVertex + } + if(nextCell) { + cut(nextCell, nextDir) + } + return nextVertex } -})() -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.pointCount - if(value < pickOffset || value >= pickOffset + pointCount) { - return null + function extractCycle(v, dir) { + var e0 = adj[dir][v][0] + var cycle = [v] + cut(e0, dir) + var u = e0[dir^1] + var d0 = dir + while(true) { + while(u !== v) { + cycle.push(u) + u = next(cycle[cycle.length-2], u, false) + } + if(adj[0][v].length + adj[1][v].length === 0) { + break + } + var a = cycle[cycle.length-1] + var b = v + var c = cycle[1] + var d = next(a, b, true) + if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) { + break + } + cycle.push(v) + u = next(a, b) + } + return cycle } - var pointId = value - pickOffset - var points = this.points - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + + function shouldGlue(pcycle, ncycle) { + return (ncycle[1] === ncycle[ncycle.length-1]) + } + + for(var i=0; i 0) { + var ni = adj[0][i].length + var ncycle = extractCycle(i,j) + if(shouldGlue(pcycle, ncycle)) { + //Glue together trivial cycles + pcycle.push.apply(pcycle, ncycle) + } else { + if(pcycle.length > 0) { + cycles.push(pcycle) + } + pcycle = ncycle + } + } + if(pcycle.length > 0) { + cycles.push(pcycle) + } + } } + + //Combine paths and loops together + return cycles } +},{"compare-angle":410}],410:[function(require,module,exports){ +"use strict" -function createScatter2D(plot, options) { - var gl = plot.gl - var buffer = createBuffer(gl) - var pickBuffer = createBuffer(gl) - var weightBuffer = createBuffer(gl) - var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment) - var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) +module.exports = compareAngle - var result = new Scatter2D( - plot, buffer, pickBuffer, weightBuffer, shader, pickShader) - result.update(options) +var orient = require("robust-orientation") +var sgn = require("signum") +var twoSum = require("two-sum") +var robustProduct = require("robust-product") +var robustSum = require("robust-sum") - //Register with plot - plot.addObject(result) +function testInterior(a, b, c) { + var x0 = twoSum(a[0], -b[0]) + var y0 = twoSum(a[1], -b[1]) + var x1 = twoSum(c[0], -b[0]) + var y1 = twoSum(c[1], -b[1]) - return result + var d = robustSum( + robustProduct(x0, x1), + robustProduct(y0, y1)) + + return d[d.length-1] >= 0 } -},{"./lib/shader":186,"binary-search-bounds":187,"gl-buffer":118,"gl-shader":197,"snap-points-2d":189,"typedarray-pool":278}],191:[function(require,module,exports){ +function compareAngle(a, b, c, d) { + var bcd = orient(b, c, d) + if(bcd === 0) { + //Handle degenerate cases + var sabc = sgn(orient(a, b, c)) + var sabd = sgn(orient(a, b, d)) + if(sabc === sabd) { + if(sabc === 0) { + var ic = testInterior(a, b, c) + var id = testInterior(a, b, d) + if(ic === id) { + return 0 + } else if(ic) { + return 1 + } else { + return -1 + } + } + return 0 + } else if(sabd === 0) { + if(sabc > 0) { + return -1 + } else if(testInterior(a, b, d)) { + return -1 + } else { + return 1 + } + } else if(sabc === 0) { + if(sabd > 0) { + return 1 + } else if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } + } + return sgn(sabd - sabc) + } + var abc = orient(a, b, c) + if(abc > 0) { + if(bcd > 0 && orient(a, b, d) > 0) { + return 1 + } + return -1 + } else if(abc < 0) { + if(bcd > 0 || orient(a, b, d) > 0) { + return 1 + } + return -1 + } else { + var abd = orient(a, b, d) + if(abd > 0) { + return 1 + } else { + if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } + } + } +} +},{"robust-orientation":1040,"robust-product":412,"robust-sum":421,"signum":413,"two-sum":414}],411:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54,"two-product":422,"two-sum":414}],412:[function(require,module,exports){ "use strict" -var vectorizeText = require("vectorize-text") - -module.exports = getGlyph +var robustSum = require("robust-sum") +var robustScale = require("robust-scale") -var GLYPH_CACHE = {} +module.exports = robustProduct -function getGlyph(symbol, font) { - var fontCache = GLYPH_CACHE[font] - if(!fontCache) { - fontCache = GLYPH_CACHE[font] = {} +function robustProduct(a, b) { + if(a.length === 1) { + return robustScale(b, a[0]) } - if(symbol in fontCache) { - return fontCache[symbol] + if(b.length === 1) { + return robustScale(a, b[0]) } - - //Get line and triangle meshes for glyph - var lineSymbol = vectorizeText(symbol, { - textAlign: "center", - textBaseline: "middle", - lineHeight: 1.0, - font: font - }) - var triSymbol = vectorizeText(symbol, { - triangles: true, - textAlign: "center", - textBaseline: "middle", - lineHeight: 1.0, - font: font - }) - - //Calculate bounding box - var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]] - for(var i=0; i 0) { return 1 } + return 0.0 +} +},{}],414:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"dup":53}],415:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],416:[function(require,module,exports){ +"use strict" -var ATTRIBUTES = [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'glyph', type: 'vec2'}, - {name: 'id', type: 'vec4'} -] +var bounds = require("binary-search-bounds") -var perspective = { - vertex: perspectiveVertSrc, - fragment: drawFragSrc, - attributes: ATTRIBUTES - }, - ortho = { - vertex: orthographicVertSrc, - fragment: drawFragSrc, - attributes: ATTRIBUTES - }, - project = { - vertex: projectionVertSrc, - fragment: drawFragSrc, - attributes: ATTRIBUTES - }, - pickPerspective = { - vertex: perspectiveVertSrc, - fragment: pickFragSrc, - attributes: ATTRIBUTES - }, - pickOrtho = { - vertex: orthographicVertSrc, - fragment: pickFragSrc, - attributes: ATTRIBUTES - }, - pickProject = { - vertex: projectionVertSrc, - fragment: pickFragSrc, - attributes: ATTRIBUTES - } +var NOT_FOUND = 0 +var SUCCESS = 1 +var EMPTY = 2 -function createShader(gl, src) { - var shader = createShaderWrapper(gl, src) - var attr = shader.attributes - attr.position.location = 0 - attr.color.location = 1 - attr.glyph.location = 2 - attr.id.location = 3 - return shader -} +module.exports = createWrapper -exports.createPerspective = function(gl) { - return createShader(gl, perspective) -} -exports.createOrtho = function(gl) { - return createShader(gl, ortho) -} -exports.createProject = function(gl) { - return createShader(gl, project) -} -exports.createPickPerspective = function(gl) { - return createShader(gl, pickPerspective) -} -exports.createPickOrtho = function(gl) { - return createShader(gl, pickOrtho) -} -exports.createPickProject = function(gl) { - return createShader(gl, pickProject) +function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { + this.mid = mid + this.left = left + this.right = right + this.leftPoints = leftPoints + this.rightPoints = rightPoints + this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length } -},{"gl-shader":197}],193:[function(require,module,exports){ -'use strict' - -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var pool = require('typedarray-pool') -var mat4mult = require('gl-mat4/multiply') -var shaders = require('./lib/shaders') -var getGlyph = require('./lib/glyphs') +var proto = IntervalTreeNode.prototype -var IDENTITY = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] +function copy(a, b) { + a.mid = b.mid + a.left = b.left + a.right = b.right + a.leftPoints = b.leftPoints + a.rightPoints = b.rightPoints + a.count = b.count +} -module.exports = createPointCloud +function rebuild(node, intervals) { + var ntree = createIntervalTree(intervals) + node.mid = ntree.mid + node.left = ntree.left + node.right = ntree.right + node.leftPoints = ntree.leftPoints + node.rightPoints = ntree.rightPoints + node.count = ntree.count +} -function transformMat4(x, m) { - var x0 = x[0] - var x1 = x[1] - var x2 = x[2] - var x3 = x[3] - x[0] = m[0] * x0 + m[4] * x1 + m[8] * x2 + m[12] * x3 - x[1] = m[1] * x0 + m[5] * x1 + m[9] * x2 + m[13] * x3 - x[2] = m[2] * x0 + m[6] * x1 + m[10] * x2 + m[14] * x3 - x[3] = m[3] * x0 + m[7] * x1 + m[11] * x2 + m[15] * x3 - return x +function rebuildWithInterval(node, interval) { + var intervals = node.intervals([]) + intervals.push(interval) + rebuild(node, intervals) } -function project(p, v, m, x) { - transformMat4(x, x, m) - transformMat4(x, x, v) - return transformMat4(x, x, p) +function rebuildWithoutInterval(node, interval) { + var intervals = node.intervals([]) + var idx = intervals.indexOf(interval) + if(idx < 0) { + return NOT_FOUND + } + intervals.splice(idx, 1) + rebuild(node, intervals) + return SUCCESS } -function clampVec(v) { - var result = new Array(3) - for(var i=0; i<3; ++i) { - result[i] = Math.min(Math.max(v[i], -1e8), 1e8) +proto.intervals = function(result) { + result.push.apply(result, this.leftPoints) + if(this.left) { + this.left.intervals(result) + } + if(this.right) { + this.right.intervals(result) } return result } -function ScatterPlotPickResult(index, position) { - this.index = index - this.dataCoordinate = this.position = position +proto.insert = function(interval) { + var weight = this.count - this.leftPoints.length + this.count += 1 + if(interval[1] < this.mid) { + if(this.left) { + if(4*(this.left.count+1) > 3*(weight+1)) { + rebuildWithInterval(this, interval) + } else { + this.left.insert(interval) + } + } else { + this.left = createIntervalTree([interval]) + } + } else if(interval[0] > this.mid) { + if(this.right) { + if(4*(this.right.count+1) > 3*(weight+1)) { + rebuildWithInterval(this, interval) + } else { + this.right.insert(interval) + } + } else { + this.right = createIntervalTree([interval]) + } + } else { + var l = bounds.ge(this.leftPoints, interval, compareBegin) + var r = bounds.ge(this.rightPoints, interval, compareEnd) + this.leftPoints.splice(l, 0, interval) + this.rightPoints.splice(r, 0, interval) + } } -function PointCloud( - gl, - shader, - orthoShader, - projectShader, - pointBuffer, - colorBuffer, - glyphBuffer, - idBuffer, - vao, - pickPerspectiveShader, - pickOrthoShader, - pickProjectShader) { +proto.remove = function(interval) { + var weight = this.count - this.leftPoints + if(interval[1] < this.mid) { + if(!this.left) { + return NOT_FOUND + } + var rw = this.right ? this.right.count : 0 + if(4 * rw > 3 * (weight-1)) { + return rebuildWithoutInterval(this, interval) + } + var r = this.left.remove(interval) + if(r === EMPTY) { + this.left = null + this.count -= 1 + return SUCCESS + } else if(r === SUCCESS) { + this.count -= 1 + } + return r + } else if(interval[0] > this.mid) { + if(!this.right) { + return NOT_FOUND + } + var lw = this.left ? this.left.count : 0 + if(4 * lw > 3 * (weight-1)) { + return rebuildWithoutInterval(this, interval) + } + var r = this.right.remove(interval) + if(r === EMPTY) { + this.right = null + this.count -= 1 + return SUCCESS + } else if(r === SUCCESS) { + this.count -= 1 + } + return r + } else { + if(this.count === 1) { + if(this.leftPoints[0] === interval) { + return EMPTY + } else { + return NOT_FOUND + } + } + if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { + if(this.left && this.right) { + var p = this + var n = this.left + while(n.right) { + p = n + n = n.right + } + if(p === this) { + n.right = this.right + } else { + var l = this.left + var r = this.right + p.count -= n.count + p.right = n.left + n.left = l + n.right = r + } + copy(this, n) + this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length + } else if(this.left) { + copy(this, this.left) + } else { + copy(this, this.right) + } + return SUCCESS + } + for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { + var r = cb(arr[i]) + if(r) { return r } + } +} - this.shader = shader - this.orthoShader = orthoShader - this.projectShader = projectShader +function reportRange(arr, cb) { + for(var i=0; i this.mid) { + if(this.right) { + var r = this.right.queryPoint(x, cb) + if(r) { return r } + } + return reportRightRange(this.rightPoints, x, cb) + } else { + return reportRange(this.leftPoints, cb) + } +} - this.opacity = 1.0 +proto.queryInterval = function(lo, hi, cb) { + if(lo < this.mid && this.left) { + var r = this.left.queryInterval(lo, hi, cb) + if(r) { return r } + } + if(hi > this.mid && this.right) { + var r = this.right.queryInterval(lo, hi, cb) + if(r) { return r } + } + if(hi < this.mid) { + return reportLeftRange(this.leftPoints, hi, cb) + } else if(lo > this.mid) { + return reportRightRange(this.rightPoints, lo, cb) + } else { + return reportRange(this.leftPoints, cb) + } +} - this.lineWidth = 0 - this.projectScale = [2.0/3.0, 2.0/3.0, 2.0/3.0] - this.projectOpacity = [1,1,1] +function compareNumbers(a, b) { + return a - b +} - this.pickId = 0 - this.pickPerspectiveShader = pickPerspectiveShader - this.pickOrthoShader = pickOrthoShader - this.pickProjectShader = pickProjectShader - this.points = [] +function compareBegin(a, b) { + var d = a[0] - b[0] + if(d) { return d } + return a[1] - b[1] +} - this._selectResult = new ScatterPlotPickResult(0, [0,0,0]) +function compareEnd(a, b) { + var d = a[1] - b[1] + if(d) { return d } + return a[0] - b[0] +} - this.useOrtho = true - this.bounds = [[ Infinity,Infinity,Infinity], - [-Infinity,-Infinity,-Infinity]] +function createIntervalTree(intervals) { + if(intervals.length === 0) { + return null + } + var pts = [] + for(var i=0; i>1] - this.highlightId = [1,1,1,1] - this.highlightScale = 2 + var leftIntervals = [] + var rightIntervals = [] + var centerIntervals = [] + for(var i=0; i= 1) { - return true - } - for(var i=0; i<3; ++i) { - if(this.axesProject[i] && this.projectOpacity[i] >= 1) { - return true +tproto.remove = function(interval) { + if(this.root) { + var r = this.root.remove(interval) + if(r === EMPTY) { + this.root = null } + return r !== NOT_FOUND } return false } -var VIEW_SHAPE = [0,0] -var U_VEC = [0,0,0] -var V_VEC = [0,0,0] -var MU_VEC = [0,0,0,1] -var MV_VEC = [0,0,0,1] -var SCRATCH_MATRIX = IDENTITY.slice() -var SCRATCH_VEC = [0,0,0] -var CLIP_BOUNDS = [[0,0,0], [0,0,0]] - -function zeroVec(a) { - a[0] = a[1] = a[2] = 0 - return a -} - -function augment(hg, af) { - hg[0] = af[0] - hg[1] = af[1] - hg[2] = af[2] - hg[3] = 1 - return hg -} - -function setComponent(out, v, i, x) { - out[0] = v[0] - out[1] = v[1] - out[2] = v[2] - out[i] = x - return out +tproto.queryPoint = function(p, cb) { + if(this.root) { + return this.root.queryPoint(p, cb) + } } -function getClipBounds(bounds) { - var result = CLIP_BOUNDS - for(var i=0; i<2; ++i) { - for(var j=0; j<3; ++j) { - result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8) - } +tproto.queryInterval = function(lo, hi, cb) { + if(lo <= hi && this.root) { + return this.root.queryInterval(lo, hi, cb) } - return result } -function drawProject(shader, points, camera, transparent, forceDraw) { - var axesProject = points.axesProject - - var gl = points.gl - var uniforms = shader.uniforms - var model = camera.model || IDENTITY - var view = camera.view || IDENTITY - var projection = camera.projection || IDENTITY - var bounds = points.axesBounds - var clipBounds = getClipBounds(points.clipBounds) +Object.defineProperty(tproto, "count", { + get: function() { + if(this.root) { + return this.root.count + } + return 0 + } +}) - var cubeAxis - if(points.axes) { - cubeAxis = points.axes.lastCubeProps.axis - } else { - cubeAxis = [1,1,1] +Object.defineProperty(tproto, "intervals", { + get: function() { + if(this.root) { + return this.root.intervals([]) + } + return [] } +}) - VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth - VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight +function createWrapper(intervals) { + if(!intervals || intervals.length === 0) { + return new IntervalTree(null) + } + return new IntervalTree(createIntervalTree(intervals)) +} - shader.bind() - uniforms.view = view - uniforms.projection = projection - uniforms.screenSize = VIEW_SHAPE - uniforms.highlightId = points.highlightId - uniforms.highlightScale = points.highlightScale - uniforms.clipBounds = clipBounds - uniforms.pickGroup = points.pickId / 255.0 - uniforms.pixelRatio = points.pixelRatio +},{"binary-search-bounds":415}],417:[function(require,module,exports){ +"use strict" - for(var i=0; i<3; ++i) { - if(!axesProject[i]) { - continue - } - if((points.projectOpacity[i] < 1) !== transparent) { - continue - } +module.exports = orderSegments - uniforms.scale = points.projectScale[i] - uniforms.opacity = points.projectOpacity[i] +var orient = require("robust-orientation") - //Project model matrix - var pmodel = SCRATCH_MATRIX - for(var j=0; j<16; ++j) { - pmodel[j] = 0 - } - for(var j=0; j<4; ++j) { - pmodel[5*j] = 1 +function horizontalOrder(a, b) { + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + var alo = Math.min(a[0][1], a[1][1]) + var ahi = Math.max(a[0][1], a[1][1]) + var blo = Math.min(b[0][1], b[1][1]) + var bhi = Math.max(b[0][1], b[1][1]) + if(ahi < blo) { + return ahi - blo } - pmodel[5*i] = 0 - if(cubeAxis[i] < 0) { - pmodel[12+i] = bounds[0][i] - } else { - pmodel[12+i] = bounds[1][i] + if(alo > bhi) { + return alo - bhi } - mat4mult(pmodel, model, pmodel) - uniforms.model = pmodel - - //Compute initial axes - var u = (i+1)%3 - var v = (i+2)%3 - var du = zeroVec(U_VEC) - var dv = zeroVec(V_VEC) - du[u] = 1 - dv[v] = 1 + return ahi - bhi + } + var al, ar + if(a[0][1] < a[1][1]) { + al = a[0] + ar = a[1] + } else { + al = a[1] + ar = a[0] + } + var d = orient(br, bl, al) + if(d) { + return d + } + d = orient(br, bl, ar) + if(d) { + return d + } + return ar - br +} - //Align orientation relative to viewer - var mdu = project(projection, view, model, augment(MU_VEC, du)) - var mdv = project(projection, view, model, augment(MV_VEC, dv)) - if(Math.abs(mdu[1]) > Math.abs(mdv[1])) { - var tmp = mdu - mdu = mdv - mdv = tmp - tmp = du - du = dv - dv = tmp - var t = u - u = v - v = t - } - if(mdu[0] < 0) { - du[u] = -1 +function orderSegments(b, a) { + var al, ar + if(a[0][0] < a[1][0]) { + al = a[0] + ar = a[1] + } else if(a[0][0] > a[1][0]) { + al = a[1] + ar = a[0] + } else { + return horizontalOrder(a, b) + } + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + return -horizontalOrder(b, a) + } + var d1 = orient(al, ar, br) + var d2 = orient(al, ar, bl) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } - if(mdv[1] > 0) { - dv[v] = -1 + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } - var su = 0.0 - var sv = 0.0 - for(var j=0; j<4; ++j) { - su += Math.pow(model[4*u+j], 2) - sv += Math.pow(model[4*v+j], 2) + } else if(d2) { + return d2 + } + d1 = orient(br, bl, ar) + d2 = orient(br, bl, al) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } - du[u] /= Math.sqrt(su) - dv[v] /= Math.sqrt(sv) - uniforms.axes[0] = du - uniforms.axes[1] = dv - - //Update fragment clip bounds - uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8) - uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8) - - //Draw interior - points.vao.draw(gl.TRIANGLES, points.vertexCount) - - //Draw edges - if(points.lineWidth > 0) { - gl.lineWidth(points.lineWidth) - points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } + } else if(d2) { + return d2 } + return ar[0] - br[0] } +},{"robust-orientation":1040}],418:[function(require,module,exports){ +"use strict" +module.exports = createRBTree -var NEG_INFINITY3 = [-1e8, -1e8, -1e8] -var POS_INFINITY3 = [1e8, 1e8, 1e8] -var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] - -function drawFull(shader, pshader, points, camera, transparent, forceDraw) { - var gl = points.gl - - points.vao.bind() +var RED = 0 +var BLACK = 1 - if(transparent === (points.opacity < 1) || forceDraw) { - shader.bind() - var uniforms = shader.uniforms +function RBNode(color, key, value, left, right, count) { + this._color = color + this.key = key + this.value = value + this.left = left + this.right = right + this._count = count +} - uniforms.model = camera.model || IDENTITY - uniforms.view = camera.view || IDENTITY - uniforms.projection = camera.projection || IDENTITY +function cloneNode(node) { + return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) +} - VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth - VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight - uniforms.screenSize = VIEW_SHAPE +function repaint(color, node) { + return new RBNode(color, node.key, node.value, node.left, node.right, node._count) +} - uniforms.highlightId = points.highlightId - uniforms.highlightScale = points.highlightScale +function recount(node) { + node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) +} - uniforms.fragClipBounds = CLIP_GROUP - uniforms.clipBounds = points.axes.bounds +function RedBlackTree(compare, root) { + this._compare = compare + this.root = root +} - uniforms.opacity = points.opacity - uniforms.pickGroup = points.pickId / 255.0 +var proto = RedBlackTree.prototype - uniforms.pixelRatio = points.pixelRatio +Object.defineProperty(proto, "keys", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(k) + }) + return result + } +}) - //Draw interior - points.vao.draw(gl.TRIANGLES, points.vertexCount) +Object.defineProperty(proto, "values", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(v) + }) + return result + } +}) - //Draw edges - if(points.lineWidth > 0) { - gl.lineWidth(points.lineWidth) - points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) +//Returns the number of nodes in the tree +Object.defineProperty(proto, "length", { + get: function() { + if(this.root) { + return this.root._count } + return 0 } +}) - drawProject(pshader, points, camera, transparent, forceDraw) - - points.vao.unbind() -} - -proto.draw = function(camera) { - var shader = this.useOrtho ? this.orthoShader : this.shader - drawFull(shader, this.projectShader, this, camera, false, false) +//Insert a new item into the tree +proto.insert = function(key, value) { + var cmp = this._compare + //Find point to insert new node at + var n = this.root + var n_stack = [] + var d_stack = [] + while(n) { + var d = cmp(key, n.key) + n_stack.push(n) + d_stack.push(d) + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + //Rebuild path to leaf node + n_stack.push(new RBNode(RED, key, value, null, null, 1)) + for(var s=n_stack.length-2; s>=0; --s) { + var n = n_stack[s] + if(d_stack[s] <= 0) { + n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) + } else { + n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) + } + } + //Rebalance tree using rotations + //console.log("start insert", key, d_stack) + for(var s=n_stack.length-1; s>1; --s) { + var p = n_stack[s-1] + var n = n_stack[s] + if(p._color === BLACK || n._color === BLACK) { + break + } + var pp = n_stack[s-2] + if(pp.left === p) { + if(p.left === n) { + var y = pp.right + if(y && y._color === RED) { + //console.log("LLr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LLb") + pp._color = RED + pp.left = p.right + p._color = BLACK + p.right = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = p + } else { + ppp.right = p + } + } + break + } + } else { + var y = pp.right + if(y && y._color === RED) { + //console.log("LRr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LRb") + p.right = n.left + pp._color = RED + pp.left = n.right + n._color = BLACK + n.left = p + n.right = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = n + } else { + ppp.right = n + } + } + break + } + } + } else { + if(p.right === n) { + var y = pp.left + if(y && y._color === RED) { + //console.log("RRr", y.key) + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RRb") + pp._color = RED + pp.right = p.left + p._color = BLACK + p.left = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = p + } else { + ppp.left = p + } + } + break + } + } else { + var y = pp.left + if(y && y._color === RED) { + //console.log("RLr") + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RLb") + p.left = n.right + pp._color = RED + pp.right = n.left + n._color = BLACK + n.right = p + n.left = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = n + } else { + ppp.left = n + } + } + break + } + } + } + } + //Return new tree + n_stack[0]._color = BLACK + return new RedBlackTree(cmp, n_stack[0]) } -proto.drawTransparent = function(camera) { - var shader = this.useOrtho ? this.orthoShader : this.shader - drawFull(shader, this.projectShader, this, camera, true, false) -} -proto.drawPick = function(camera) { - var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader - drawFull(shader, this.pickProjectShader, this, camera, false, true) +//Visit all nodes inorder +function doVisitFull(visit, node) { + if(node.left) { + var v = doVisitFull(visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + if(node.right) { + return doVisitFull(visit, node.right) + } } -proto.pick = function(selected) { - if(!selected) { - return null - } - if(selected.id !== this.pickId) { - return null +//Visit half nodes in order +function doVisitHalf(lo, compare, visit, node) { + var l = compare(lo, node.key) + if(l <= 0) { + if(node.left) { + var v = doVisitHalf(lo, compare, visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } } - var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) - if(x >= this.pointCount || x < 0) { - return null + if(node.right) { + return doVisitHalf(lo, compare, visit, node.right) } +} - //Unpack result - var coord = this.points[x] - var result = this._selectResult - result.index = x - for(var i=0; i<3; ++i) { - result.position[i] = result.dataCoordinate[i] = coord[i] +//Visit all nodes within a range +function doVisit(lo, hi, compare, visit, node) { + var l = compare(lo, node.key) + var h = compare(hi, node.key) + var v + if(l <= 0) { + if(node.left) { + v = doVisit(lo, hi, compare, visit, node.left) + if(v) { return v } + } + if(h > 0) { + v = visit(node.key, node.value) + if(v) { return v } + } + } + if(h > 0 && node.right) { + return doVisit(lo, hi, compare, visit, node.right) } - return result } -proto.highlight = function(selection) { - if(!selection) { - this.highlightId = [1,1,1,1] - } else { - var pointId = selection.index - var a0 = pointId &0xff - var a1 = (pointId>>8) &0xff - var a2 = (pointId>>16)&0xff - this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0] + +proto.forEach = function rbTreeForEach(visit, lo, hi) { + if(!this.root) { + return } -} + switch(arguments.length) { + case 1: + return doVisitFull(visit, this.root) + break -proto.update = function(options) { + case 2: + return doVisitHalf(lo, this._compare, visit, this.root) + break - options = options || {} + case 3: + if(this._compare(lo, hi) >= 0) { + return + } + return doVisit(lo, hi, this._compare, visit, this.root) + break + } +} - if('perspective' in options) { - this.useOrtho = !options.perspective +//First item in list +Object.defineProperty(proto, "begin", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.left + } + return new RedBlackTreeIterator(this, stack) } - if('orthographic' in options) { - this.useOrtho = !!options.orthographic +}) + +//Last item in list +Object.defineProperty(proto, "end", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.right + } + return new RedBlackTreeIterator(this, stack) } - if('lineWidth' in options) { - this.lineWidth = options.lineWidth +}) + +//Find the ith item in the tree +proto.at = function(idx) { + if(idx < 0) { + return new RedBlackTreeIterator(this, []) } - if('project' in options) { - if(Array.isArray(options.project)) { - this.axesProject = options.project + var n = this.root + var stack = [] + while(true) { + stack.push(n) + if(n.left) { + if(idx < n.left._count) { + n = n.left + continue + } + idx -= n.left._count + } + if(!idx) { + return new RedBlackTreeIterator(this, stack) + } + idx -= 1 + if(n.right) { + if(idx >= n.right._count) { + break + } + n = n.right } else { - var v = !!options.project - this.axesProject = [v,v,v] + break } } - if('projectScale' in options) { - if(Array.isArray(options.projectScale)) { - this.projectScale = options.projectScale.slice() + return new RedBlackTreeIterator(this, []) +} + +proto.ge = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d <= 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left } else { - var s = +options.projectScale - this.projectScale = [s,s,s] + n = n.right } } - if('projectOpacity' in options) { - if(Array.isArray(options.projectOpacity)) { - this.projectOpacity = options.projectOpacity.slice() + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} + +proto.gt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d < 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left } else { - var s = +options.projectOpacity - this.projectOpacity = [s,s,s] + n = n.right } } - if('opacity' in options) { - this.opacity = options.opacity - } - - //Set dirty flag - this.dirty = true + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - //Create new buffers - var points = options.position - if(!points) { - return +proto.lt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d > 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - //Text font - var font = options.font || 'normal' - var alignment = options.alignment || [0,0] - - //Bounds - var lowerBound = [ Infinity, Infinity, Infinity] - var upperBound = [-Infinity,-Infinity,-Infinity] - - //Unpack options - var glyphs = options.glyph - var colors = options.color - var sizes = options.size - var angles = options.angle - var lineColors = options.lineColor - - //Picking geometry - var pickCounter = 0 +proto.le = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d >= 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) +} - //First do pass to compute buffer sizes - var triVertexCount = 0 - var lineVertexCount = 0 +//Finds the item with key if it exists +proto.find = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d === 0) { + return new RedBlackTreeIterator(this, stack) + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + return new RedBlackTreeIterator(this, []) +} - //Count number of points and buffer size - var numPoints = points.length +//Removes item with key from tree +proto.remove = function(key) { + var iter = this.find(key) + if(iter) { + return iter.remove() + } + return this +} -count_loop: - for(var i=0; i 0 + } +}) - var triOffset = 0 - var lineOffset = triVertexCount - var color = [0,0,0,1] - var lineColor = [0,0,0,1] +//Node of the iterator +Object.defineProperty(iproto, "node", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1] + } + return null + }, + enumerable: true +}) - var isColorArray = Array.isArray(colors) && Array.isArray(colors[0]) - var isLineColorArray = Array.isArray(lineColors) && Array.isArray(lineColors[0]) +//Makes a copy of an iterator +iproto.clone = function() { + return new RedBlackTreeIterator(this.tree, this._stack.slice()) +} -fill_loop: - for(var i=0; i=0; --i) { + n = stack[i] + if(i === 0) { + n._color = BLACK + return } - - var glyphData - if(Array.isArray(glyphs)) { - glyphData = getGlyph(glyphs[i], font) - } else if(glyphs) { - glyphData = getGlyph(glyphs, font) + //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) + p = stack[i-1] + if(p.left === n) { + //console.log("left child") + s = p.right + if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.right = cloneNode(s) + z = s.right = cloneNode(s.right) + p.right = s.left + s.left = p + s.right = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + return + } else if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red") + s = p.right = cloneNode(s) + z = s.left = cloneNode(s.left) + p.right = z.left + s.left = z.right + z.left = p + z.right = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = z + } else { + pp.right = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent", p.right.value) + p._color = BLACK + p.right = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent", p.right.value) + p.right = repaint(RED, s) + continue + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.right = s.left + s.left = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } } else { - glyphData = getGlyph('●', font) - } - var glyphMesh = glyphData[0] - var glyphLines = glyphData[1] - var glyphBounds = glyphData[2] - - - //Get color - if(Array.isArray(colors)) { - var c - if(isColorArray) { - c = colors[i] + //console.log("right child") + s = p.left + if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red", p.value, p._color) + s = p.left = cloneNode(s) + z = s.left = cloneNode(s.left) + p.left = s.right + s.right = p + s.left = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + return + } else if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.left = cloneNode(s) + z = s.right = cloneNode(s.right) + p.left = z.right + s.right = z.left + z.right = p + z.left = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = z + } else { + pp.left = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent") + p._color = BLACK + p.left = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent") + p.left = repaint(RED, s) + continue + } } else { - c = colors - } - if(c.length === 3) { - for(var j=0; j<3; ++j) { - color[j] = c[j] + //console.log("case 3: red sibling") + s = cloneNode(s) + p.left = s.right + s.right = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } } - color[3] = 1 - } else if(c.length === 4) { - for(var j=0; j<4; ++j) { - color[j] = c[j] + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) } + i = i+2 } - } else { - color[0] = color[1] = color[2] = 0 - color[3] = 1 } + } +} - //Get lineColor - if(Array.isArray(lineColors)) { - var c - if(isLineColorArray) { - c = lineColors[i] - } else { - c = lineColors - } - if(c.length === 3) { - for(var j=0; j<3; ++j) { - lineColor[j] = c[j] - } - lineColor[j] = 1 - } else if(c.length === 4) { - for(var j=0; j<4; ++j) { - lineColor[j] = c[j] - } - } +//Removes item at iterator from tree +iproto.remove = function() { + var stack = this._stack + if(stack.length === 0) { + return this.tree + } + //First copy path to node + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + var n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) } else { - lineColor[0] = lineColor[1] = lineColor[2] = 0 - lineColor[3] = 1 + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } + } - var size = 0.5 - if(Array.isArray(sizes)) { - size = +sizes[i] - } else if(sizes) { - size = +sizes - } else if(this.useOrtho) { - size = 12 + //Get node + n = cstack[cstack.length-1] + //console.log("start remove: ", n.value) + + //If not leaf, then swap with previous node + if(n.left && n.right) { + //console.log("moving to leaf") + + //First walk to previous leaf + var split = cstack.length + n = n.left + while(n.right) { + cstack.push(n) + n = n.right } + //Copy path to leaf + var v = cstack[split-1] + cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) + cstack[split-1].key = n.key + cstack[split-1].value = n.value - var angle = 0 - if(Array.isArray(angles)) { - angle = +angles[i] - } else if(angles) { - angle = +angles + //Fix up stack + for(var i=cstack.length-2; i>=split; --i) { + n = cstack[i] + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } + cstack[split-1].left = cstack[split] + } + //console.log("stack=", cstack.map(function(v) { return v.value })) - //Loop through markers and append to buffers - var cos = Math.cos(angle) - var sin = Math.sin(angle) + //Remove leaf node + n = cstack[cstack.length-1] + if(n._color === RED) { + //Easy case: removing red leaf + //console.log("RED leaf") + var p = cstack[cstack.length-2] + if(p.left === n) { + p.left = null + } else if(p.right === n) { + p.right = null + } + cstack.pop() + for(var i=0; i 0) { + return this._stack[this._stack.length-1].key } + return + }, + enumerable: true +}) - //Calculate text offset - if(alignment[0] < 0) { - textOffset[0] = alignment[0] * (1+glyphBounds[1][0]) - } else if(alignment[0] > 0) { - textOffset[0] = -alignment[0] * (1+glyphBounds[0][0]) +//Returns value +Object.defineProperty(iproto, "value", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1].value } + return + }, + enumerable: true +}) - //Write out inner marker - var cells = glyphMesh.cells - var verts = glyphMesh.positions - for(var j=0; j=0; --s) { + if(stack[s+1] === stack[s].right) { + ++idx + if(stack[s].left) { + idx += stack[s].left._count } - idArray[lineOffset] = pickCounter - var p = verts[cell[k]] - glyphArray[2*lineOffset] = size * (cos*p[0] - sin*p[1] + textOffset[0]) - glyphArray[2*lineOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1]) - lineOffset += 1 } } + return idx + }, + enumerable: true +}) - //Increment pickCounter - pickCounter += 1 +//Advances iterator to next element in list +iproto.next = function() { + var stack = this._stack + if(stack.length === 0) { + return } - - - //Update vertex counts - this.vertexCount = triVertexCount - this.lineVertexCount = lineVertexCount - - //Update buffers - this.pointBuffer.update(positionArray) - this.colorBuffer.update(colorArray) - this.glyphBuffer.update(glyphArray) - this.idBuffer.update(new Uint32Array(idArray)) - - pool.free(positionArray) - pool.free(colorArray) - pool.free(glyphArray) - pool.free(idArray) - - //Update bounds - this.bounds = [lowerBound, upperBound] - - //Save points - this.points = points - - //Save number of points - this.pointCount = points.length -} - -proto.dispose = function() { - //Shaders - this.shader.dispose() - this.orthoShader.dispose() - this.pickPerspectiveShader.dispose() - this.pickOrthoShader.dispose() - - //Vertex array - this.vao.dispose() - - //Buffers - this.pointBuffer.dispose() - this.colorBuffer.dispose() - this.glyphBuffer.dispose() - this.idBuffer.dispose() -} - -function createPointCloud(options) { - var gl = options.gl - - var shader = shaders.createPerspective(gl) - var orthoShader = shaders.createOrtho(gl) - var projectShader = shaders.createProject(gl) - var pickPerspectiveShader = shaders.createPickPerspective(gl) - var pickOrthoShader = shaders.createPickOrtho(gl) - var pickProjectShader = shaders.createPickProject(gl) - - var pointBuffer = createBuffer(gl) - var colorBuffer = createBuffer(gl) - var glyphBuffer = createBuffer(gl) - var idBuffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - buffer: pointBuffer, - size: 3, - type: gl.FLOAT - }, - { - buffer: colorBuffer, - size: 4, - type: gl.FLOAT - }, - { - buffer: glyphBuffer, - size: 2, - type: gl.FLOAT - }, - { - buffer: idBuffer, - size: 4, - type: gl.UNSIGNED_BYTE, - normalized: true + var n = stack[stack.length-1] + if(n.right) { + n = n.right + while(n) { + stack.push(n) + n = n.left } - ]) - - var pointCloud = new PointCloud( - gl, - shader, - orthoShader, - projectShader, - pointBuffer, - colorBuffer, - glyphBuffer, - idBuffer, - vao, - pickPerspectiveShader, - pickOrthoShader, - pickProjectShader) - - pointCloud.update(options) - - return pointCloud + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].right === n) { + n = stack[stack.length-1] + stack.pop() + } + } } -},{"./lib/glyphs":191,"./lib/shaders":192,"gl-buffer":118,"gl-mat4/multiply":139,"gl-vao":226,"typedarray-pool":278}],194:[function(require,module,exports){ -'use strict' - - - -exports.boxVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n" -exports.boxFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n" - -},{}],195:[function(require,module,exports){ -'use strict' - -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') - -var SHADERS = require('./lib/shaders') - -module.exports = createSelectBox - -function SelectBox(plot, boxBuffer, boxShader) { - this.plot = plot - this.boxBuffer = boxBuffer - this.boxShader = boxShader - - this.enabled = true - - this.selectBox = [Infinity,Infinity,-Infinity,-Infinity] +//Checks if iterator is at end of tree +Object.defineProperty(iproto, "hasNext", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].right) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].left === stack[s]) { + return true + } + } + return false + } +}) - this.borderColor = [0,0,0,1] - this.innerFill = false - this.innerColor = [0,0,0,0.25] - this.outerFill = true - this.outerColor = [0,0,0,0.5] - this.borderWidth = 10 +//Update value +iproto.update = function(value) { + var stack = this._stack + if(stack.length === 0) { + throw new Error("Can't update empty node!") + } + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + } + return new RedBlackTree(this.tree._compare, cstack[0]) } -var proto = SelectBox.prototype - -proto.draw = function() { - if(!this.enabled) { +//Moves iterator backward one element +iproto.prev = function() { + var stack = this._stack + if(stack.length === 0) { return } - - var plot = this.plot - var selectBox = this.selectBox - var lineWidth = this.borderWidth - - var innerFill = this.innerFill - var innerColor = this.innerColor - var outerFill = this.outerFill - var outerColor = this.outerColor - var borderColor = this.borderColor - - var boxes = plot.box - var screenBox = plot.screenBox - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - - //Map select box into pixel coordinates - var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] - var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] - var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] - var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] - - loX = Math.max(loX, viewBox[0]) - loY = Math.max(loY, viewBox[1]) - hiX = Math.min(hiX, viewBox[2]) - hiY = Math.min(hiY, viewBox[3]) - - if(hiX < loX || hiY < loY) { - return + var n = stack[stack.length-1] + if(n.left) { + n = n.left + while(n) { + stack.push(n) + n = n.right + } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].left === n) { + n = stack[stack.length-1] + stack.pop() + } } +} - boxes.bind() - - //Draw box - var screenWidth = screenBox[2] - screenBox[0] - var screenHeight = screenBox[3] - screenBox[1] - - if(this.outerFill) { - boxes.drawBox(0, 0, screenWidth, loY, outerColor) - boxes.drawBox(0, loY, loX, hiY, outerColor) - boxes.drawBox(0, hiY, screenWidth, screenHeight, outerColor) - boxes.drawBox(hiX, loY, screenWidth, hiY, outerColor) +//Checks if iterator is at start of tree +Object.defineProperty(iproto, "hasPrev", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].left) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].right === stack[s]) { + return true + } + } + return false } +}) - if(this.innerFill) { - boxes.drawBox(loX, loY, hiX, hiY, innerColor) +//Default comparison function +function defaultCompare(a, b) { + if(a < b) { + return -1 } - - //Draw border - if(lineWidth > 0) { - - //Draw border - var w = lineWidth * pixelRatio - boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) - boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) - boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) - boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) + if(a > b) { + return 1 } + return 0 } -proto.update = function(options) { - options = options || {} - - this.innerFill = !!options.innerFill - this.outerFill = !!options.outerFill - this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() - this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() - this.borderColor = (options.borderColor || [0,0,0,1]).slice() - this.borderWidth = options.borderWidth || 0 - this.selectBox = (options.selectBox || this.selectBox).slice() -} - -proto.dispose = function() { - this.boxBuffer.dispose() - this.boxShader.dispose() - this.plot.removeOverlay(this) -} - -function createSelectBox(plot, options) { - var gl = plot.gl - var buffer = createBuffer(gl, [ - 0, 0, - 0, 1, - 1, 0, - 1, 1 ]) - var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment) - var selectBox = new SelectBox(plot, buffer, shader) - selectBox.update(options) - plot.addOverlay(selectBox) - return selectBox +//Build a tree +function createRBTree(compare) { + return new RedBlackTree(compare || defaultCompare, null) } +},{}],419:[function(require,module,exports){ +"use strict" -},{"./lib/shaders":194,"gl-buffer":118,"gl-shader":197}],196:[function(require,module,exports){ -'use strict' - -module.exports = createSelectBuffer +module.exports = createSlabDecomposition -var createFBO = require('gl-fbo') -var pool = require('typedarray-pool') -var ndarray = require('ndarray') +var bounds = require("binary-search-bounds") +var createRBTree = require("functional-red-black-tree") +var orient = require("robust-orientation") +var orderSegments = require("./lib/order-segments") -var nextPow2 = require('bit-twiddle').nextPow2 +function SlabDecomposition(slabs, coordinates, horizontal) { + this.slabs = slabs + this.coordinates = coordinates + this.horizontal = horizontal +} -var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_34_arg0_||255>_inline_34_arg1_||255>_inline_34_arg2_||255>_inline_34_arg3_){var _inline_34_l=_inline_34_arg4_-_inline_34_arg6_[0],_inline_34_a=_inline_34_arg5_-_inline_34_arg6_[1],_inline_34_f=_inline_34_l*_inline_34_l+_inline_34_a*_inline_34_a;_inline_34_f 0) { + if(p[0] !== seg[1][0]) { + lastNode = root + root = root.right + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } + } else { + if(p[0] !== seg[1][0]) { + return root + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } } - fbo.bind() - gl.readPixels(0,0,fbo.shape[0],fbo.shape[1],gl.RGBA,gl.UNSIGNED_BYTE,self.buffer) - self._readTimeout = null } + return lastNode } -var proto = SelectBuffer.prototype - -Object.defineProperty(proto, 'shape', { - get: function() { - if(!this.gl) { - return [0,0] +proto.castUp = function(p) { + var bucket = bounds.le(this.coordinates, p[0]) + if(bucket < 0) { + return -1 + } + var root = this.slabs[bucket] + var hitNode = searchBucket(this.slabs[bucket], p) + var lastHit = -1 + if(hitNode) { + lastHit = hitNode.value + } + //Edge case: need to handle horizontal segments (sucks) + if(this.coordinates[bucket] === p[0]) { + var lastSegment = null + if(hitNode) { + lastSegment = hitNode.key } - return this.fbo.shape.slice() - }, - set: function(v) { - if(!this.gl) { - return + if(bucket > 0) { + var otherHitNode = searchBucket(this.slabs[bucket-1], p) + if(otherHitNode) { + if(lastSegment) { + if(orderSegments(otherHitNode.key, lastSegment) > 0) { + lastSegment = otherHitNode.key + lastHit = otherHitNode.value + } + } else { + lastHit = otherHitNode.value + lastSegment = otherHitNode.key + } + } } - this.fbo.shape = v - var c = this.fbo.shape[0] - var r = this.fbo.shape[1] - if(r*c*4 > this.buffer.length) { - pool.free(this.buffer) - var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) - for(var i=0; i 0) { + var hbucket = bounds.ge(horiz, p[1], compareHorizontal) + if(hbucket < horiz.length) { + var e = horiz[hbucket] + if(p[1] === e.y) { + if(e.closed) { + return e.index + } else { + while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { + hbucket = hbucket+1 + e = horiz[hbucket] + if(e.closed) { + return e.index + } + } + if(e.y === p[1] && !e.start) { + hbucket = hbucket+1 + if(hbucket >= horiz.length) { + return lastHit + } + e = horiz[hbucket] + } + } + } + //Check if e is above/below last segment + if(e.start) { + if(lastSegment) { + var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) + if(lastSegment[0][0] > lastSegment[1][0]) { + o = -o + } + if(o > 0) { + lastHit = e.index + } + } else { + lastHit = e.index + } + } else if(e.y !== p[1]) { + lastHit = e.index + } } } - return v } -}) + return lastHit +} -proto.begin = function() { - var gl = this.gl - var shape = this.shape - if(!gl) { - return - } +function IntervalSegment(y, index, start, closed) { + this.y = y + this.index = index + this.start = start + this.closed = closed +} - this.fbo.bind() - gl.clearColor(1,1,1,1) - gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) +function Event(x, segment, create, index) { + this.x = x + this.segment = segment + this.create = create + this.index = index } -proto.end = function() { - var gl = this.gl - if(!gl) { - return + +function createSlabDecomposition(segments) { + var numSegments = segments.length + var numEvents = 2 * numSegments + var events = new Array(numEvents) + for(var i=0; i 0 && coordinates[bucket] === p[0]) { + root = slabs[bucket-1] + } else { + return 1 + } + } + var lastOrientation = 1 + while(root) { + var s = root.key + var o = orient(p, s[0], s[1]) + if(s[0][0] < s[1][0]) { + if(o < 0) { + root = root.left + } else if(o > 0) { + lastOrientation = -1 + root = root.right + } else { + return 0 + } + } else { + if(o > 0) { + root = root.left + } else if(o < 0) { + lastOrientation = 1 + root = root.right + } else { + return 0 + } + } + } + return lastOrientation + } +} - return new SelectResult( - (dx + x0)|0, - (dy + y0)|0, - c0, - [c1, c2, c3], - Math.sqrt(closest[2])) +function classifyEmpty(p) { + return 1 } -proto.dispose = function() { - if(!this.gl) { - return - } - this.fbo.dispose() - pool.free(this.buffer) - this.gl = null - if(this._readTimeout) { - clearTimeout(this._readTimeout) +function createClassifyVertical(testVertical) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return 1 } } -function createSelectBuffer(gl, shape) { - var fbo = createFBO(gl, shape) - var buffer = pool.mallocUint8(shape[0]*shape[1]*4) - return new SelectBuffer(gl, fbo, buffer) +function createClassifyPointDegen(testVertical, testNormal) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return testNormal(p) + } } -},{"bit-twiddle":50,"cwise/lib/wrapper":112,"gl-fbo":123,"ndarray":253,"typedarray-pool":278}],197:[function(require,module,exports){ -'use strict' - -var createUniformWrapper = require('./lib/create-uniforms') -var createAttributeWrapper = require('./lib/create-attributes') -var makeReflect = require('./lib/reflect') -var shaderCache = require('./lib/shader-cache') -var runtime = require('./lib/runtime-reflect') -var GLError = require("./lib/GLError") +function preprocessPolygon(loops) { + //Compute number of loops + var numLoops = loops.length -//Shader object -function Shader(gl) { - this.gl = gl + //Unpack segments + var segments = [] + var vsegments = [] + var ptr = 0 + for(var i=0; i 0 } - //Sort attributes lexicographically - // overrides undefined WebGL behavior for attribute locations - attributes = attributes.slice() - attributes.sort(compareAttributes) + //Extract all clockwise faces + faces = faces.filter(ccw) - //Convert attribute types, read out locations - var attributeUnpacked = [] - var attributeNames = [] - var attributeLocations = [] - for(var i=0; i= 0) { - var size = attr.type.charAt(attr.type.length-1)|0 - var locVector = new Array(size) - for(var j=0; j= 0) { - curLocation += 1 + containment.sort(function(a,b) { + return b[0] - a[0] + }) + for(var i=0; i 0) { + var top = toVisit.pop() + var nbhd = fadj[top] + uniq(nbhd, function(a,b) { + return a-b + }) + var nnbhr = nbhd.length + var p = parity[top] + var polyline + if(p === 0) { + var c = faces[top] + polyline = [c] + } + for(var i=0; i= 0) { + continue + } + parity[f] = p^1 + toVisit.push(f) + if(p === 0) { + var c = faces[f] + if(!sharedBoundary(c)) { + c.reverse() + polyline.push(c) + } + } + } + if(p === 0) { + result.push(polyline) + } + } - //Generate uniform wrappers - Object.defineProperty(wrapper, 'uniforms', createUniformWrapper( - gl - , wrapper - , uniforms - , uniformLocations)) + return result } +},{"./lib/trim-leaves":407,"edges-to-adjacency-list":408,"planar-dual":409,"point-in-big-polygon":420,"robust-sum":421,"two-product":422,"uniq":423}],425:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],426:[function(require,module,exports){ +"use strict"; "use restrict"; -//Compiles and links a shader program with the given attribute and vertex list -function createShader( - gl - , vertSource - , fragSource - , uniforms - , attributes) { +module.exports = UnionFind; - var shader = new Shader(gl) +function UnionFind(count) { + this.roots = new Array(count); + this.ranks = new Array(count); + + for(var i=0; i> 1 + } + return (i >> 1) - 1 + } -Object.defineProperty(proto, 'location', { - get: function() { - return this._locations[this._index] + //Bubble element i down the heap + function heapDown(i) { + var w = heapWeight(i) + while(true) { + var tw = w + var left = 2*i + 1 + var right = 2*(i + 1) + var next = i + if(left < heapCount) { + var lw = heapWeight(left) + if(lw < tw) { + next = left + tw = lw + } + } + if(right < heapCount) { + var rw = heapWeight(right) + if(rw < tw) { + next = right + } + } + if(next === i) { + return i + } + heapSwap(i, next) + i = next + } } - , set: function(v) { - if(v !== this._locations[this._index]) { - this._locations[this._index] = v|0 - this._wrapper.program = null + + //Bubbles element i up the heap + function heapUp(i) { + var w = heapWeight(i) + while(i > 0) { + var parent = heapParent(i) + if(parent >= 0) { + var pw = heapWeight(parent) + if(w < pw) { + heapSwap(i, parent) + i = parent + continue + } + } + return i } - return v|0 } -}) -//Adds a vector attribute to obj -function addVectorAttribute( - gl - , wrapper - , index - , locations - , dimension - , obj - , name) { + //Pop minimum element + function heapPop() { + if(heapCount > 0) { + var head = heap[0] + heapSwap(0, heapCount-1) + heapCount -= 1 + heapDown(0) + return head + } + return -1 + } - //Construct constant function - var constFuncArgs = [ 'gl', 'v' ] - var varNames = [] - for(var i=0; i= 0) { + inv[t] = s + } + if(outv[s] >= 0) { + outv[s] = t + } - //Create accessor - Object.defineProperty(obj, name, { - set: function(x) { - gl.disableVertexAttribArray(locations[index]) - constFunc(gl, locations[index], x) - return x + //Update weights on s and t + if(index[s] >= 0) { + heapUpdate(index[s], computeWeight(s)) } - , get: function() { - return attr + if(index[t] >= 0) { + heapUpdate(index[t], computeWeight(t)) } - , enumerable: true - }) -} + } -function addMatrixAttribute( - gl - , wrapper - , index - , locations - , dimension - , obj - , name) { + //Initialize weights and heap + var heap = [] + var index = new Array(n) + for(var i=0; i>1; i>=0; --i) { + heapDown(i) + } + + //Kill vertices + while(true) { + var hmin = heapPop() + if((hmin < 0) || (weights[hmin] > minArea)) { + break + } + kill(hmin) + } - var parts = new Array(dimension) - var attrs = new Array(dimension) - for(var i=0; i= 0 && tout >= 0 && tin !== tout) { + var cin = index[tin] + var cout = index[tout] + if(cin !== cout) { + ncells.push([ cin, cout ]) } - return x - } - , get: function() { - return parts } - , enumerable: true }) -} -//Create shims for attributes -function createAttributeWrapper( - gl - , wrapper - , attributes - , locations) { + //Normalize result + sc.unique(sc.normalize(ncells)) - var obj = {} - for(var i=0, n=attributes.length; i= 0) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addVectorAttribute( - gl - , wrapper - , locs[0] - , locations - , d - , obj - , name) - } else if(type.indexOf('mat') >= 0) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addMatrixAttribute( - gl - , wrapper - , locs - , locations - , d - , obj - , name) - } else { - throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type) - } - break +//Helper macros +function array(i) { + return "a" + i +} +function data(i) { + return "d" + i +} +function cube(i,bitmask) { + return "c" + i + "_" + bitmask +} +function shape(i) { + return "s" + i +} +function stride(i,j) { + return "t" + i + "_" + j +} +function offset(i) { + return "o" + i +} +function scalar(i) { + return "x" + i +} +function pointer(i) { + return "p" + i +} +function delta(i,bitmask) { + return "d" + i + "_" + bitmask +} +function index(i) { + return "i" + i +} +function step(i,j) { + return "u" + i + "_" + j +} +function pcube(bitmask) { + return "b" + bitmask +} +function qcube(bitmask) { + return "y" + bitmask +} +function pdelta(bitmask) { + return "e" + bitmask +} +function vert(i) { + return "v" + i +} +var VERTEX_IDS = "V" +var PHASES = "P" +var VERTEX_COUNT = "N" +var POOL_SIZE = "Q" +var POINTER = "X" +var TEMPORARY = "T" + +function permBitmask(dimension, mask, order) { + var r = 0 + for(var i=0; i 0) { + stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) + } + vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + } + } + //Create index variables + for(var i=0; i=0; --i) { + sizeVariable.push(shape(order[i])) + } + //Previous phases and vertex_ids + vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", + PHASES + "=mallocUint32(" + POOL_SIZE + ")", + VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", + POINTER + "=0") + //Create cube variables for phases + vars.push(pcube(0) + "=0") + for(var j=1; j<(1< 4) { - throw new GLError('', 'Invalid data type') - } - switch(type.charAt(0)) { - case 'b': - case 'i': - return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' - case 'v': - return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' - default: - throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type) - } - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) - } - return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' - } else { - throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) - } - break + function forLoopEnd(i) { + for(var j=0; j=0; --i) { + forLoopBegin(i, 0) } - var indices = [] - for(var id in type) { - var prop = type[id] - var tprefix = prefix - if(parseInt(id) + '' === id) { - tprefix += '[' + id + ']' + var phaseFuncArgs = [] + for(var i=0; i 4) { - throw new GLError('', 'Invalid data type') - } - if(type.charAt(0) === 'b') { - return makeVector(d, false) - } - return makeVector(d, 0) - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + //Generate vertex + code.push("vertex(", vertexArgs.join(), ");", + vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;") + + //Check for face crossings + var base = (1<0; k=(k-1)&subset) { + faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") + } + faceArgs.push(vert(0)) + for(var k=0; k0){", + index(order[i]), "=1;") + createLoop(i-1, mask|(1< 0") + } + if(typeof args.vertex !== "function") { + error("Must specify vertex creation function") + } + if(typeof args.cell !== "function") { + error("Must specify cell creation function") + } + if(typeof args.phase !== "function") { + error("Must specify phase function") + } + var getters = args.getters || [] + var typesig = new Array(arrays) + for(var i=0; i= 0) { + typesig[i] = true + } else { + typesig[i] = false + } } + return compileSurfaceProcedure( + args.vertex, + args.cell, + args.phase, + scalars, + order, + typesig) } +},{"typedarray-pool":432}],430:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],431:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],432:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":430,"buffer":65,"dup":122}],433:[function(require,module,exports){ +// transliterated from the python snippet here: +// http://en.wikipedia.org/wiki/Lanczos_approximation -},{"./GLError":198,"./reflect":201}],201:[function(require,module,exports){ -'use strict' +var g = 7; +var p = [ + 0.99999999999980993, + 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 +]; -module.exports = makeReflectTypes +var g_ln = 607/128; +var p_ln = [ + 0.99999999999999709182, + 57.156235665862923517, + -59.597960355475491248, + 14.136097974741747174, + -0.49191381609762019978, + 0.33994649984811888699e-4, + 0.46523628927048575665e-4, + -0.98374475304879564677e-4, + 0.15808870322491248884e-3, + -0.21026444172410488319e-3, + 0.21743961811521264320e-3, + -0.16431810653676389022e-3, + 0.84418223983852743293e-4, + -0.26190838401581408670e-4, + 0.36899182659531622704e-5 +]; -//Construct type info for reflection. -// -// This iterates over the flattened list of uniform type values and smashes them into a JSON object. -// -// The leaves of the resulting object are either indices or type strings representing primitive glslify types -function makeReflectTypes(uniforms, useIndex) { - var obj = {} - for(var i=0; i 1) { - if(!(x[0] in o)) { - o[x[0]] = [] +// Spouge approximation (suitable for large arguments) +function lngamma(z) { + + if(z < 0) return Number('0/0'); + var x = p_ln[0]; + for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); + var t = z + g_ln + 0.5; + return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); +} + +module.exports = function gamma (z) { + if (z < 0.5) { + return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); + } + else if(z > 100) return Math.exp(lngamma(z)); + else { + z -= 1; + var x = p[0]; + for (var i = 1; i < g + 2; i++) { + x += p[i] / (z + i); } - o = o[x[0]] - for(var k=1; k0; --i) { + t = pinv[i] + s = p[i] + p[i] = p[t] + p[t] = s + pinv[i] = pinv[s] + pinv[s] = t + r = (r + s) * i + } + pool.freeUint32(pinv) + pool.freeUint32(p) + return r } -function runtimeUniforms(gl, program) { - var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS) - var result = [] - for(var i=0; i 1) { - for(var j=0; j0; --i) { + s = (r / nf)|0 + r = (r - s * nf)|0 + nf = (nf / i)|0 + t = p[i]|0 + p[i] = p[s]|0 + p[s] = t|0 + } + return p } -function runtimeAttributes(gl, program) { - var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES) - var result = [] - for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", + "args": [{ + "name": "_inline_1_arg0_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg1_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg2_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg3_", + "lvalue": false, + "rvalue": true, + "count": 2 + }, { + "name": "_inline_1_arg4_", + "lvalue": false, + "rvalue": true, + "count": 1 + }], + "thisVars": [], + "localVars": ["_inline_1_da", "_inline_1_db"] + }, + funcName: 'zeroCrossings' +}) -ShaderReference.prototype.dispose = function() { - if(--this.count === 0) { - var cache = this.cache - var gl = cache.gl +},{"cwise-compiler":445}],445:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./lib/thunk.js":447,"dup":319}],446:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320,"uniq":448}],447:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"./compile.js":446,"dup":321}],448:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],449:[function(require,module,exports){ +"use strict" - //Remove program references - var programs = this.programs - for(var i=0, n=programs.length; i c)|0 },") + if(dtype === "generic") { + code.push("getters:[0],") } - return shader -} -proto.getShaderReference = function(type, src) { - var gl = this.gl - var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0] - var shader = shaders[src] - if(!shader || !gl.isShader(shader.shader)) { - var shaderObj = compileShader(gl, type, src) - shader = shaders[src] = new ShaderReference( - SHADER_COUNTER++, - src, - type, - shaderObj, - [], - 1, - this) + //Generate vertex function + var cubeArgs = [] + var extraArgs = [] + for(var i=0; i>>7){") } - return shader -} - -function linkProgram(gl, vshader, fshader, attribs, locations) { - var program = gl.createProgram() - gl.attachShader(program, vshader) - gl.attachShader(program, fshader) - for(var i=0; i 128) { + if((i%128)===0) { + if(extraFuncs.length > 0) { + currentFunc.push("}}") + } + var efName = "vExtra" + extraFuncs.length + code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") + currentFunc = [ + "function ", efName, "(m,", extraArgs.join(), "){switch(m){" + ] + extraFuncs.push(currentFunc) + } + } + currentFunc.push("case ", (i&0x7f), ":") + var crossings = new Array(dimension) + var denoms = new Array(dimension) + var crossingCount = new Array(dimension) + var bias = new Array(dimension) + var totalCrossings = 0 + for(var j=0; j j) { + continue + } + if(!(i&(1< 0) { + cStr = "+" + crossingCount[k] + "*c" + } + var weight = 0.5 * (crossings[k].length / totalCrossings) + var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) + vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") + + } + } + currentFunc.push("a.push([", vertexStr.join(), "]);", + "break;") } - gl.linkProgram(program) - if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { - var errLog = gl.getProgramInfoLog(program) - throw new GLError(errLog, 'Error linking program: ' + errLog) + code.push("}},") + if(extraFuncs.length > 0) { + currentFunc.push("}}") } - return program -} -proto.getProgram = function(vref, fref, attribs, locations) { - var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@') - var prog = this.programs[token] - if(!prog || !this.gl.isProgram(prog)) { - this.programs[token] = prog = linkProgram( - this.gl, - vref.shader, - fref.shader, - attribs, - locations) - vref.programs.push(token) - fref.programs.push(token) + //Create face function + var faceArgs = [] + for(var i=0; i<(1<<(dimension-1)); ++i) { + faceArgs.push("v" + i) } - return prog -} + faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c") + code.push("cell:function cellFunc(", faceArgs.join(), "){") -function getCache(gl) { - var ctxCache = CACHE.get(gl) - if(!ctxCache) { - ctxCache = new ContextCache(gl) - CACHE.set(gl, ctxCache) + var facets = triangulateCube(dimension-1) + code.push("if(p0){b.push(", + facets.map(function(f) { + return "[" + f.map(function(v) { + return "v" + v + }) + "]" + }).join(), ")}else{b.push(", + facets.map(function(f) { + var e = f.slice() + e.reverse() + return "[" + e.map(function(v) { + return "v" + v + }) + "]" + }).join(), + ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";") + + for(var i=0; i0) { + shapeX += 0.02 + } + } - var errorStrings = errLog.split('\n'); - var errors = {}; + var data = new Float32Array(bufferSize) + var ptr = 0 + var xOffset = -0.5 * shapeX + for(var i=0; i - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ + this.gridLineEnable = [true,true] + this.gridLineWidth = [1,1] + this.gridLineColor = [[0,0,0,1], + [0,0,0,1]] -'use strict'; + this.pixelRatio = 1 -var repeat = require('repeat-string'); + this.tickMarkLength = [0,0,0,0] + this.tickMarkWidth = [0,0,0,0] + this.tickMarkColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -module.exports = function padLeft(str, num, ch) { - ch = typeof ch !== 'undefined' ? (ch + '') : ' '; - return repeat(ch, num) + str; -}; -},{"repeat-string":254}],207:[function(require,module,exports){ -module.exports = { - 0: 'NONE', - 1: 'ONE', - 2: 'LINE_LOOP', - 3: 'LINE_STRIP', - 4: 'TRIANGLES', - 5: 'TRIANGLE_STRIP', - 6: 'TRIANGLE_FAN', - 256: 'DEPTH_BUFFER_BIT', - 512: 'NEVER', - 513: 'LESS', - 514: 'EQUAL', - 515: 'LEQUAL', - 516: 'GREATER', - 517: 'NOTEQUAL', - 518: 'GEQUAL', - 519: 'ALWAYS', - 768: 'SRC_COLOR', - 769: 'ONE_MINUS_SRC_COLOR', - 770: 'SRC_ALPHA', - 771: 'ONE_MINUS_SRC_ALPHA', - 772: 'DST_ALPHA', - 773: 'ONE_MINUS_DST_ALPHA', - 774: 'DST_COLOR', - 775: 'ONE_MINUS_DST_COLOR', - 776: 'SRC_ALPHA_SATURATE', - 1024: 'STENCIL_BUFFER_BIT', - 1028: 'FRONT', - 1029: 'BACK', - 1032: 'FRONT_AND_BACK', - 1280: 'INVALID_ENUM', - 1281: 'INVALID_VALUE', - 1282: 'INVALID_OPERATION', - 1285: 'OUT_OF_MEMORY', - 1286: 'INVALID_FRAMEBUFFER_OPERATION', - 2304: 'CW', - 2305: 'CCW', - 2849: 'LINE_WIDTH', - 2884: 'CULL_FACE', - 2885: 'CULL_FACE_MODE', - 2886: 'FRONT_FACE', - 2928: 'DEPTH_RANGE', - 2929: 'DEPTH_TEST', - 2930: 'DEPTH_WRITEMASK', - 2931: 'DEPTH_CLEAR_VALUE', - 2932: 'DEPTH_FUNC', - 2960: 'STENCIL_TEST', - 2961: 'STENCIL_CLEAR_VALUE', - 2962: 'STENCIL_FUNC', - 2963: 'STENCIL_VALUE_MASK', - 2964: 'STENCIL_FAIL', - 2965: 'STENCIL_PASS_DEPTH_FAIL', - 2966: 'STENCIL_PASS_DEPTH_PASS', - 2967: 'STENCIL_REF', - 2968: 'STENCIL_WRITEMASK', - 2978: 'VIEWPORT', - 3024: 'DITHER', - 3042: 'BLEND', - 3088: 'SCISSOR_BOX', - 3089: 'SCISSOR_TEST', - 3106: 'COLOR_CLEAR_VALUE', - 3107: 'COLOR_WRITEMASK', - 3317: 'UNPACK_ALIGNMENT', - 3333: 'PACK_ALIGNMENT', - 3379: 'MAX_TEXTURE_SIZE', - 3386: 'MAX_VIEWPORT_DIMS', - 3408: 'SUBPIXEL_BITS', - 3410: 'RED_BITS', - 3411: 'GREEN_BITS', - 3412: 'BLUE_BITS', - 3413: 'ALPHA_BITS', - 3414: 'DEPTH_BITS', - 3415: 'STENCIL_BITS', - 3553: 'TEXTURE_2D', - 4352: 'DONT_CARE', - 4353: 'FASTEST', - 4354: 'NICEST', - 5120: 'BYTE', - 5121: 'UNSIGNED_BYTE', - 5122: 'SHORT', - 5123: 'UNSIGNED_SHORT', - 5124: 'INT', - 5125: 'UNSIGNED_INT', - 5126: 'FLOAT', - 5386: 'INVERT', - 5890: 'TEXTURE', - 6401: 'STENCIL_INDEX', - 6402: 'DEPTH_COMPONENT', - 6406: 'ALPHA', - 6407: 'RGB', - 6408: 'RGBA', - 6409: 'LUMINANCE', - 6410: 'LUMINANCE_ALPHA', - 7680: 'KEEP', - 7681: 'REPLACE', - 7682: 'INCR', - 7683: 'DECR', - 7936: 'VENDOR', - 7937: 'RENDERER', - 7938: 'VERSION', - 9728: 'NEAREST', - 9729: 'LINEAR', - 9984: 'NEAREST_MIPMAP_NEAREST', - 9985: 'LINEAR_MIPMAP_NEAREST', - 9986: 'NEAREST_MIPMAP_LINEAR', - 9987: 'LINEAR_MIPMAP_LINEAR', - 10240: 'TEXTURE_MAG_FILTER', - 10241: 'TEXTURE_MIN_FILTER', - 10242: 'TEXTURE_WRAP_S', - 10243: 'TEXTURE_WRAP_T', - 10497: 'REPEAT', - 10752: 'POLYGON_OFFSET_UNITS', - 16384: 'COLOR_BUFFER_BIT', - 32769: 'CONSTANT_COLOR', - 32770: 'ONE_MINUS_CONSTANT_COLOR', - 32771: 'CONSTANT_ALPHA', - 32772: 'ONE_MINUS_CONSTANT_ALPHA', - 32773: 'BLEND_COLOR', - 32774: 'FUNC_ADD', - 32777: 'BLEND_EQUATION_RGB', - 32778: 'FUNC_SUBTRACT', - 32779: 'FUNC_REVERSE_SUBTRACT', - 32819: 'UNSIGNED_SHORT_4_4_4_4', - 32820: 'UNSIGNED_SHORT_5_5_5_1', - 32823: 'POLYGON_OFFSET_FILL', - 32824: 'POLYGON_OFFSET_FACTOR', - 32854: 'RGBA4', - 32855: 'RGB5_A1', - 32873: 'TEXTURE_BINDING_2D', - 32926: 'SAMPLE_ALPHA_TO_COVERAGE', - 32928: 'SAMPLE_COVERAGE', - 32936: 'SAMPLE_BUFFERS', - 32937: 'SAMPLES', - 32938: 'SAMPLE_COVERAGE_VALUE', - 32939: 'SAMPLE_COVERAGE_INVERT', - 32968: 'BLEND_DST_RGB', - 32969: 'BLEND_SRC_RGB', - 32970: 'BLEND_DST_ALPHA', - 32971: 'BLEND_SRC_ALPHA', - 33071: 'CLAMP_TO_EDGE', - 33170: 'GENERATE_MIPMAP_HINT', - 33189: 'DEPTH_COMPONENT16', - 33306: 'DEPTH_STENCIL_ATTACHMENT', - 33635: 'UNSIGNED_SHORT_5_6_5', - 33648: 'MIRRORED_REPEAT', - 33901: 'ALIASED_POINT_SIZE_RANGE', - 33902: 'ALIASED_LINE_WIDTH_RANGE', - 33984: 'TEXTURE0', - 33985: 'TEXTURE1', - 33986: 'TEXTURE2', - 33987: 'TEXTURE3', - 33988: 'TEXTURE4', - 33989: 'TEXTURE5', - 33990: 'TEXTURE6', - 33991: 'TEXTURE7', - 33992: 'TEXTURE8', - 33993: 'TEXTURE9', - 33994: 'TEXTURE10', - 33995: 'TEXTURE11', - 33996: 'TEXTURE12', - 33997: 'TEXTURE13', - 33998: 'TEXTURE14', - 33999: 'TEXTURE15', - 34000: 'TEXTURE16', - 34001: 'TEXTURE17', - 34002: 'TEXTURE18', - 34003: 'TEXTURE19', - 34004: 'TEXTURE20', - 34005: 'TEXTURE21', - 34006: 'TEXTURE22', - 34007: 'TEXTURE23', - 34008: 'TEXTURE24', - 34009: 'TEXTURE25', - 34010: 'TEXTURE26', - 34011: 'TEXTURE27', - 34012: 'TEXTURE28', - 34013: 'TEXTURE29', - 34014: 'TEXTURE30', - 34015: 'TEXTURE31', - 34016: 'ACTIVE_TEXTURE', - 34024: 'MAX_RENDERBUFFER_SIZE', - 34041: 'DEPTH_STENCIL', - 34055: 'INCR_WRAP', - 34056: 'DECR_WRAP', - 34067: 'TEXTURE_CUBE_MAP', - 34068: 'TEXTURE_BINDING_CUBE_MAP', - 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', - 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', - 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', - 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', - 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', - 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', - 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', - 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', - 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', - 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', - 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', - 34342: 'CURRENT_VERTEX_ATTRIB', - 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', - 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', - 34467: 'COMPRESSED_TEXTURE_FORMATS', - 34660: 'BUFFER_SIZE', - 34661: 'BUFFER_USAGE', - 34816: 'STENCIL_BACK_FUNC', - 34817: 'STENCIL_BACK_FAIL', - 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', - 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', - 34877: 'BLEND_EQUATION_ALPHA', - 34921: 'MAX_VERTEX_ATTRIBS', - 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', - 34930: 'MAX_TEXTURE_IMAGE_UNITS', - 34962: 'ARRAY_BUFFER', - 34963: 'ELEMENT_ARRAY_BUFFER', - 34964: 'ARRAY_BUFFER_BINDING', - 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', - 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', - 35040: 'STREAM_DRAW', - 35044: 'STATIC_DRAW', - 35048: 'DYNAMIC_DRAW', - 35632: 'FRAGMENT_SHADER', - 35633: 'VERTEX_SHADER', - 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', - 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', - 35663: 'SHADER_TYPE', - 35664: 'FLOAT_VEC2', - 35665: 'FLOAT_VEC3', - 35666: 'FLOAT_VEC4', - 35667: 'INT_VEC2', - 35668: 'INT_VEC3', - 35669: 'INT_VEC4', - 35670: 'BOOL', - 35671: 'BOOL_VEC2', - 35672: 'BOOL_VEC3', - 35673: 'BOOL_VEC4', - 35674: 'FLOAT_MAT2', - 35675: 'FLOAT_MAT3', - 35676: 'FLOAT_MAT4', - 35678: 'SAMPLER_2D', - 35680: 'SAMPLER_CUBE', - 35712: 'DELETE_STATUS', - 35713: 'COMPILE_STATUS', - 35714: 'LINK_STATUS', - 35715: 'VALIDATE_STATUS', - 35716: 'INFO_LOG_LENGTH', - 35717: 'ATTACHED_SHADERS', - 35718: 'ACTIVE_UNIFORMS', - 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', - 35720: 'SHADER_SOURCE_LENGTH', - 35721: 'ACTIVE_ATTRIBUTES', - 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', - 35724: 'SHADING_LANGUAGE_VERSION', - 35725: 'CURRENT_PROGRAM', - 36003: 'STENCIL_BACK_REF', - 36004: 'STENCIL_BACK_VALUE_MASK', - 36005: 'STENCIL_BACK_WRITEMASK', - 36006: 'FRAMEBUFFER_BINDING', - 36007: 'RENDERBUFFER_BINDING', - 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', - 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', - 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', - 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', - 36053: 'FRAMEBUFFER_COMPLETE', - 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', - 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', - 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', - 36061: 'FRAMEBUFFER_UNSUPPORTED', - 36064: 'COLOR_ATTACHMENT0', - 36096: 'DEPTH_ATTACHMENT', - 36128: 'STENCIL_ATTACHMENT', - 36160: 'FRAMEBUFFER', - 36161: 'RENDERBUFFER', - 36162: 'RENDERBUFFER_WIDTH', - 36163: 'RENDERBUFFER_HEIGHT', - 36164: 'RENDERBUFFER_INTERNAL_FORMAT', - 36168: 'STENCIL_INDEX8', - 36176: 'RENDERBUFFER_RED_SIZE', - 36177: 'RENDERBUFFER_GREEN_SIZE', - 36178: 'RENDERBUFFER_BLUE_SIZE', - 36179: 'RENDERBUFFER_ALPHA_SIZE', - 36180: 'RENDERBUFFER_DEPTH_SIZE', - 36181: 'RENDERBUFFER_STENCIL_SIZE', - 36194: 'RGB565', - 36336: 'LOW_FLOAT', - 36337: 'MEDIUM_FLOAT', - 36338: 'HIGH_FLOAT', - 36339: 'LOW_INT', - 36340: 'MEDIUM_INT', - 36341: 'HIGH_INT', - 36346: 'SHADER_COMPILER', - 36347: 'MAX_VERTEX_UNIFORM_VECTORS', - 36348: 'MAX_VARYING_VECTORS', - 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', - 37440: 'UNPACK_FLIP_Y_WEBGL', - 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', - 37442: 'CONTEXT_LOST_WEBGL', - 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', - 37444: 'BROWSER_DEFAULT_WEBGL' -} + this.tickPad = [15,15,15,15] + this.tickAngle = [0,0,0,0] + this.tickEnable = [true,true,true,true] + this.tickColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -},{}],208:[function(require,module,exports){ -var gl10 = require('./1.0/numbers') + this.labelPad = [15,15,15,15] + this.labelAngle = [0,Math.PI/2,0,3.0*Math.PI/2] + this.labelEnable = [true,true,true,true] + this.labelColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -module.exports = function lookupConstant (number) { - return gl10[number] -} + this.titleCenter = [0,0] + this.titleEnable = true + this.titleAngle = 0 + this.titleColor = [0,0,0,1] -},{"./1.0/numbers":207}],209:[function(require,module,exports){ -var tokenize = require('glsl-tokenizer') -var atob = require('atob-lite') + this.borderColor = [0,0,0,0] + this.backgroundColor = [0,0,0,0] -module.exports = getName + this.zeroLineEnable = [true, true] + this.zeroLineWidth = [4, 4] + this.zeroLineColor = [[0, 0, 0, 1],[0, 0, 0, 1]] -function getName(src) { - var tokens = Array.isArray(src) - ? src - : tokenize(src) + this.borderLineEnable = [true,true,true,true] + this.borderLineWidth = [2,2,2,2] + this.borderLineColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i] - if (token.type !== 'preprocessor') continue - var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) - if (!match) continue - if (!match[2]) continue + //Drawing parameters + this.grid = null + this.text = null + this.line = null + this.box = null + this.objects = [] + this.overlays = [] - var b64 = match[1] - var name = match[2] + this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] - return (b64 ? atob(name) : name).trim() - } -} + this.dirty = false + this.pickDirty = false + this.pickDelay = 120 + this.pickRadius = 10 + this._pickTimeout = null + this._drawPick = this.drawPick.bind(this) -},{"atob-lite":210,"glsl-tokenizer":234}],210:[function(require,module,exports){ -module.exports = function _atob(str) { - return atob(str) + this._depthCounter = 0 } -},{}],211:[function(require,module,exports){ -(function(window) { - var re = { - not_string: /[^s]/, - number: /[diefg]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[\+\-]/ - } - - function sprintf() { - var key = arguments[0], cache = sprintf.cache - if (!(cache[key] && cache.hasOwnProperty(key))) { - cache[key] = sprintf.parse(key) - } - return sprintf.format.call(null, cache[key], arguments) - } +var proto = GLPlot2D.prototype - sprintf.format = function(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]) - if (node_type === "string") { - output[output.length] = parse_tree[i] - } - else if (node_type === "array") { - match = parse_tree[i] // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor] - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) - } - arg = arg[match[2][k]] - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } +proto.setDirty = function() { + this.dirty = this.pickDirty = true +} - if (get_type(arg) == "function") { - arg = arg() - } +proto.setOverlayDirty = function() { + this.dirty = true +} - if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { - throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) - } +proto.nextDepthValue = function() { + return (this._depthCounter++) / 65536.0 +} - if (re.number.test(match[8])) { - is_positive = arg >= 0 - } +function lerp(a, b, t) { + var s = 0.5 * (t + 1.0) + return Math.floor((1.0-s)*a + s*b)|0 +} - switch (match[8]) { - case "b": - arg = arg.toString(2) - break - case "c": - arg = String.fromCharCode(arg) - break - case "d": - case "i": - arg = parseInt(arg, 10) - break - case "j": - arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) - break - case "e": - arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() - break - case "f": - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) - break - case "g": - arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) - break - case "o": - arg = arg.toString(8) - break - case "s": - arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) - break - case "u": - arg = arg >>> 0 - break - case "x": - arg = arg.toString(16) - break - case "X": - arg = arg.toString(16).toUpperCase() - break - } - if (re.json.test(match[8])) { - output[output.length] = arg - } - else { - if (re.number.test(match[8]) && (!is_positive || match[3])) { - sign = is_positive ? "+" : "-" - arg = arg.toString().replace(re.sign, "") - } - else { - sign = "" - } - pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " - pad_length = match[6] - (sign + arg).length - pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" - output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) - } - } - } - return output.join("") - } +proto.draw = (function() { +var TICK_MARK_BOX = [0,0,0,0] +return function() { + var gl = this.gl + var screenBox = this.screenBox + var viewPixels = this.viewBox + var dataBox = this.dataBox + var pixelRatio = this.pixelRatio + var grid = this.grid + var line = this.line + var text = this.text + var objects = this.objects - sprintf.cache = {} + this._depthCounter = 0 - sprintf.parse = function(fmt) { - var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = match[0] - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = "%" - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - } - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") - } - parse_tree[parse_tree.length] = match - } - else { - throw new SyntaxError("[sprintf] unexpected placeholder") - } - _fmt = _fmt.substring(match[0].length) - } - return parse_tree + if(this.pickDirty) { + if(this._pickTimeout) { + clearTimeout(this._pickTimeout) } + this.pickDirty = false + this._pickTimeout = setTimeout(this._drawPick, this.pickDelay) + } - var vsprintf = function(fmt, argv, _argv) { - _argv = (argv || []).slice(0) - _argv.splice(0, 0, fmt) - return sprintf.apply(null, _argv) - } + if(!this.dirty) { + return + } + this.dirty = false - /** - * helpers - */ - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() - } + gl.bindFramebuffer(gl.FRAMEBUFFER, null) - function str_repeat(input, multiplier) { - return Array(multiplier + 1).join(input) - } + //Turn on scissor + gl.enable(gl.SCISSOR_TEST) - /** - * export to either browser or node.js - */ - if (typeof exports !== "undefined") { - exports.sprintf = sprintf - exports.vsprintf = vsprintf - } - else { - window.sprintf = sprintf - window.vsprintf = vsprintf + //Turn off depth buffer + gl.disable(gl.DEPTH_TEST) + gl.depthFunc(gl.LESS) + gl.depthMask(false) - if (typeof define === "function" && define.amd) { - define(function() { - return { - sprintf: sprintf, - vsprintf: vsprintf - } - }) - } - } -})(typeof window === "undefined" ? this : window); + //Configure premultiplied alpha blending + gl.enable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); -},{}],212:[function(require,module,exports){ -var hiddenStore = require('./hidden-store.js'); + //Draw border + gl.scissor( + screenBox[0], + screenBox[1], + screenBox[2]-screenBox[0], + screenBox[3]-screenBox[1]) + var borderColor = this.borderColor + gl.clearColor( + borderColor[0]*borderColor[3], + borderColor[1]*borderColor[3], + borderColor[2]*borderColor[3], + borderColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) -module.exports = createStore; + //Draw center pane + gl.scissor( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + gl.viewport( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + var backgroundColor = this.backgroundColor + gl.clearColor( + backgroundColor[0]*backgroundColor[3], + backgroundColor[1]*backgroundColor[3], + backgroundColor[2]*backgroundColor[3], + backgroundColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT) -function createStore() { - var key = {}; + //Draw grid + grid.draw() - return function (obj) { - if ((typeof obj !== 'object' || obj === null) && - typeof obj !== 'function' - ) { - throw new Error('Weakmap-shim: Key must be object') - } + //Draw zero lines separately + var zeroLineEnable = this.zeroLineEnable + var zeroLineColor = this.zeroLineColor + var zeroLineWidth = this.zeroLineWidth + if(zeroLineEnable[0] || zeroLineEnable[1]) { + line.bind() + for(var i=0; i<2; ++i) { + if(!zeroLineEnable[i] || + !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) { + continue + } - var store = obj.valueOf(key); - return store && store.identity === key ? - store : hiddenStore(obj, key); - }; -} + var zeroIntercept = screenBox[i] - + dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) -},{"./hidden-store.js":213}],213:[function(require,module,exports){ -module.exports = hiddenStore; + if(i === 0) { + line.drawLine( + zeroIntercept, screenBox[1], zeroIntercept, screenBox[3], + zeroLineWidth[i], + zeroLineColor[i]) + } else { + line.drawLine( + screenBox[0], zeroIntercept, screenBox[2], zeroIntercept, + zeroLineWidth[i], + zeroLineColor[i]) + } + } + } -function hiddenStore(obj, key) { - var store = { identity: key }; - var valueOf = obj.valueOf; + //Draw traces + for(var i=0; i= 0) { - pickStr.push('0') - } else if(facet.indexOf(-(i+1)) >= 0) { - pickStr.push('s['+i+']-1') - } else { - pickStr.push('-1') - loStr.push('1') - hiStr.push('s['+i+']-2') - } - } - var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')' - if(loStr.length === 0) { - boundStr = '' - } - - if(cod > 0) { - code.push('if(1') - for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { - continue - } - code.push('&&s[', i, ']>2') - } - code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) - for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { - continue - } - code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr) - } - code.push(');') - } + var gl = this.gl - for(var i=0; i1){dst.set(', - pickStr.join(), ',', bnd, ',0.5*(src.get(', - cPickStr.join(), ')-src.get(', - dPickStr.join(), ')))}else{dst.set(', - pickStr.join(), ',', bnd, ',0)};') - } else { - code.push('if(s[', bnd, ']>1){diff(', outStr, - ',src.pick(', cPickStr.join(), ')', boundStr, - ',src.pick(', dPickStr.join(), ')', boundStr, - ');}else{zero(', outStr, ');};') - } - break + var pixelRatio = this.pixelRatio + this.pickPixelRatio = Math.max(pixelRatio, 1) - case 'mirror': - if(cod === 0) { - code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') - } else { - code.push('zero(', outStr, ');') - } - break + this.setScreenBox(options.screenBox || + [0, 0, gl.drawingBufferWidth/pixelRatio, gl.drawingBufferHeight/pixelRatio]) - case 'wrap': - var aPickStr = pickStr.slice() - var bPickStr = pickStr.slice() - if(facet[i] < 0) { - aPickStr[bnd] = 's[' + bnd + ']-2' - bPickStr[bnd] = '0' - - } else { - aPickStr[bnd] = 's[' + bnd + ']-1' - bPickStr[bnd] = '1' - } - if(cod === 0) { - code.push('if(s[', bnd, ']>2){dst.set(', - pickStr.join(), ',', bnd, ',0.5*(src.get(', - aPickStr.join(), ')-src.get(', - bPickStr.join(), ')))}else{dst.set(', - pickStr.join(), ',', bnd, ',0)};') - } else { - code.push('if(s[', bnd, ']>2){diff(', outStr, - ',src.pick(', aPickStr.join(), ')', boundStr, - ',src.pick(', bPickStr.join(), ')', boundStr, - ');}else{zero(', outStr, ');};') - } - break + var screenBox = this.screenBox + this.setViewBox(options.viewBox || + [0.125*(this.screenBox[2]-this.screenBox[0])/pixelRatio, + 0.125*(this.screenBox[3]-this.screenBox[1])/pixelRatio, + 0.875*(this.screenBox[2]-this.screenBox[0])/pixelRatio, + 0.875*(this.screenBox[3]-this.screenBox[1])/pixelRatio]) - default: - throw new Error('ndarray-gradient: Invalid boundary condition') - } - } + var viewBox = this.viewBox + var aspectRatio = (viewBox[2] - viewBox[0]) / (viewBox[3] - viewBox[1]) + this.setDataBox(options.dataBox || [-10, -10/aspectRatio, 10, 10/aspectRatio]) - if(cod > 0) { - code.push('};') - } - } + this.borderColor = (options.borderColor || [0,0,0,0]).slice() + this.backgroundColor = (options.backgroundColor || [0,0,0,0]).slice() - //Enumerate ridges, facets, etc. of hypercube - for(var i=0; i<(1<=0; --i) { + this.objects[i].dispose() + } + this.objects.length = 0 + for(var i=this.overlays.length-1; i>=0; --i) { + this.overlays[i].dispose() + } + this.overlays.length = 0 -var IDENTITY = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 ] + this.gl = null +} -var QUAD = [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - [1, 0], - [0, 1] -] +proto.addObject = function(object) { + if(this.objects.indexOf(object) < 0) { + this.objects.push(object) + this.setDirty() + } +} -var PERMUTATIONS = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0] -] +proto.removeObject = function(object) { + var objects = this.objects + for(var i=0; i Math.abs(dy)) { + view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) + } else { + var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0 + view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) + } + }, true) - this.dirty = true + return camera } +},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],455:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":458}],456:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],457:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],458:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":456,"buffer":65,"dup":122}],459:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],460:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":459,"dup":155}],461:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":459,"dup":156}],462:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":460,"./lib/vao-native.js":461,"dup":157}],463:[function(require,module,exports){ +// Copyright (C) 2011 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. -var proto = SurfacePlot.prototype +/** + * @fileoverview Install a leaky WeakMap emulation on platforms that + * don't provide a built-in one. + * + *

Assumes that an ES5 platform where, if {@code WeakMap} is + * already present, then it conforms to the anticipated ES6 + * specification. To run this file on an ES5 or almost ES5 + * implementation where the {@code WeakMap} specification does not + * quite conform, run repairES5.js first. + * + *

Even though WeakMapModule is not global, the linter thinks it + * is, which is why it is in the overrides list below. + * + *

NOTE: Before using this WeakMap emulation in a non-SES + * environment, see the note below about hiddenRecord. + * + * @author Mark S. Miller + * @requires crypto, ArrayBuffer, Uint8Array, navigator, console + * @overrides WeakMap, ses, Proxy + * @overrides WeakMapModule + */ + +/** + * This {@code WeakMap} emulation is observably equivalent to the + * ES-Harmony WeakMap, but with leakier garbage collection properties. + * + *

As with true WeakMaps, in this emulation, a key does not + * retain maps indexed by that key and (crucially) a map does not + * retain the keys it indexes. A map by itself also does not retain + * the values associated with that map. + * + *

However, the values associated with a key in some map are + * retained so long as that key is retained and those associations are + * not overridden. For example, when used to support membranes, all + * values exported from a given membrane will live for the lifetime + * they would have had in the absence of an interposed membrane. Even + * when the membrane is revoked, all objects that would have been + * reachable in the absence of revocation will still be reachable, as + * far as the GC can tell, even though they will no longer be relevant + * to ongoing computation. + * + *

The API implemented here is approximately the API as implemented + * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, + * rather than the offially approved proposal page. TODO(erights): + * upgrade the ecmascript WeakMap proposal page to explain this API + * change and present to EcmaScript committee for their approval. + * + *

The first difference between the emulation here and that in + * FF6.0a1 is the presence of non enumerable {@code get___, has___, + * set___, and delete___} methods on WeakMap instances to represent + * what would be the hidden internal properties of a primitive + * implementation. Whereas the FF6.0a1 WeakMap.prototype methods + * require their {@code this} to be a genuine WeakMap instance (i.e., + * an object of {@code [[Class]]} "WeakMap}), since there is nothing + * unforgeable about the pseudo-internal method names used here, + * nothing prevents these emulated prototype methods from being + * applied to non-WeakMaps with pseudo-internal methods of the same + * names. + * + *

Another difference is that our emulated {@code + * WeakMap.prototype} is not itself a WeakMap. A problem with the + * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap + * providing ambient mutability and an ambient communications + * channel. Thus, if a WeakMap is already present and has this + * problem, repairES5.js wraps it in a safe wrappper in order to + * prevent access to this channel. (See + * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). + */ -proto.isTransparent = function () { - return this.opacity < 1 -} +/** + * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is + * absent, install an approximate emulation. + * + *

If WeakMap is present but cannot store some objects, use our approximate + * emulation as a wrapper. + * + *

If this is almost a secureable ES5 platform, then WeakMap.js + * should be run after repairES5.js. + * + *

See {@code WeakMap} for documentation of the garbage collection + * properties of this WeakMap emulation. + */ +(function WeakMapModule() { + "use strict"; -proto.isOpaque = function () { - if (this.opacity >= 1) { - return true + if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { + // already too broken, so give up + return; } - for (var i = 0; i < 3; ++i) { - if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) { - return true + + /** + * In some cases (current Firefox), we must make a choice betweeen a + * WeakMap which is capable of using all varieties of host objects as + * keys and one which is capable of safely using proxies as keys. See + * comments below about HostWeakMap and DoubleWeakMap for details. + * + * This function (which is a global, not exposed to guests) marks a + * WeakMap as permitted to do what is necessary to index all host + * objects, at the cost of making it unsafe for proxies. + * + * Do not apply this function to anything which is not a genuine + * fresh WeakMap. + */ + function weakMapPermitHostObjects(map) { + // identity of function used as a secret -- good enough and cheap + if (map.permitHostObjects___) { + map.permitHostObjects___(weakMapPermitHostObjects); } } - return false -} + if (typeof ses !== 'undefined') { + ses.weakMapPermitHostObjects = weakMapPermitHostObjects; + } -proto.pickSlots = 1 + // IE 11 has no Proxy but has a broken WeakMap such that we need to patch + // it using DoubleWeakMap; this flag tells DoubleWeakMap so. + var doubleWeakMapCheckSilentFailure = false; -proto.setPickBase = function (id) { - this.pickId = id -} + // Check if there is already a good-enough WeakMap implementation, and if so + // exit without replacing it. + if (typeof WeakMap === 'function') { + var HostWeakMap = WeakMap; + // There is a WeakMap -- is it good enough? + if (typeof navigator !== 'undefined' && + /Firefox/.test(navigator.userAgent)) { + // We're now *assuming not*, because as of this writing (2013-05-06) + // Firefox's WeakMaps have a miscellany of objects they won't accept, and + // we don't want to make an exhaustive list, and testing for just one + // will be a problem if that one is fixed alone (as they did for Event). -var ZERO_VEC = [0, 0, 0] + // If there is a platform that we *can* reliably test on, here's how to + // do it: + // var problematic = ... ; + // var testHostMap = new HostWeakMap(); + // try { + // testHostMap.set(problematic, 1); // Firefox 20 will throw here + // if (testHostMap.get(problematic) === 1) { + // return; + // } + // } catch (e) {} -var PROJECT_DATA = { - showSurface: false, - showContour: false, - projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()], - clipBounds: [ - [[0, 0, 0], [0, 0, 0]], - [[0, 0, 0], [0, 0, 0]], - [[0, 0, 0], [0, 0, 0]]] -} + } else { + // IE 11 bug: WeakMaps silently fail to store frozen objects. + var testMap = new HostWeakMap(); + var testObject = Object.freeze({}); + testMap.set(testObject, 1); + if (testMap.get(testObject) !== 1) { + doubleWeakMapCheckSilentFailure = true; + // Fall through to installing our WeakMap. + } else { + module.exports = WeakMap; + return; + } + } + } -function computeProjectionData (camera, obj) { - var i, j, k + var hop = Object.prototype.hasOwnProperty; + var gopn = Object.getOwnPropertyNames; + var defProp = Object.defineProperty; + var isExtensible = Object.isExtensible; - // Compute cube properties - var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC + /** + * Security depends on HIDDEN_NAME being both unguessable and + * undiscoverable by untrusted code. + * + *

Given the known weaknesses of Math.random() on existing + * browsers, it does not generate unguessability we can be confident + * of. + * + *

It is the monkey patching logic in this file that is intended + * to ensure undiscoverability. The basic idea is that there are + * three fundamental means of discovering properties of an object: + * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), + * as well as some proposed ES6 extensions that appear on our + * whitelist. The first two only discover enumerable properties, and + * we only use HIDDEN_NAME to name a non-enumerable property, so the + * only remaining threat should be getOwnPropertyNames and some + * proposed ES6 extensions that appear on our whitelist. We monkey + * patch them to remove HIDDEN_NAME from the list of properties they + * returns. + * + *

TODO(erights): On a platform with built-in Proxies, proxies + * could be used to trap and thereby discover the HIDDEN_NAME, so we + * need to monkey patch Proxy.create, Proxy.createFunction, etc, in + * order to wrap the provided handler with the real handler which + * filters out all traps using HIDDEN_NAME. + * + *

TODO(erights): Revisit Mike Stay's suggestion that we use an + * encapsulated function at a not-necessarily-secret name, which + * uses the Stiegler shared-state rights amplification pattern to + * reveal the associated value only to the WeakMap in which this key + * is associated with that value. Since only the key retains the + * function, the function can also remember the key without causing + * leakage of the key, so this doesn't violate our general gc + * goals. In addition, because the name need not be a guarded + * secret, we could efficiently handle cross-frame frozen keys. + */ + var HIDDEN_NAME_PREFIX = 'weakmap:'; + var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; - var showSurface = obj.showSurface - var showContour = obj.showContour + if (typeof crypto !== 'undefined' && + typeof crypto.getRandomValues === 'function' && + typeof ArrayBuffer === 'function' && + typeof Uint8Array === 'function') { + var ab = new ArrayBuffer(25); + var u8s = new Uint8Array(ab); + crypto.getRandomValues(u8s); + HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + + Array.prototype.map.call(u8s, function(u8) { + return (u8 % 36).toString(36); + }).join('') + '___'; + } - for (i = 0; i < 3; ++i) { - showSurface = showSurface || obj.surfaceProject[i] - for (j = 0; j < 3; ++j) { - showContour = showContour || obj.contourProject[i][j] - } + function isNotHiddenName(name) { + return !( + name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && + name.substr(name.length - 3) === '___'); } - for (i = 0; i < 3; ++i) { - // Construct projection onto axis - var axisSquish = PROJECT_DATA.projections[i] - for (j = 0; j < 16; ++j) { - axisSquish[j] = 0 - } - for (j = 0; j < 4; ++j) { - axisSquish[5 * j] = 1 + /** + * Monkey patch getOwnPropertyNames to avoid revealing the + * HIDDEN_NAME. + * + *

The ES5.1 spec requires each name to appear only once, but as + * of this writing, this requirement is controversial for ES6, so we + * made this code robust against this case. If the resulting extra + * search turns out to be expensive, we can probably relax this once + * ES6 is adequately supported on all major browsers, iff no browser + * versions we support at that time have relaxed this constraint + * without providing built-in ES6 WeakMaps. + */ + defProp(Object, 'getOwnPropertyNames', { + value: function fakeGetOwnPropertyNames(obj) { + return gopn(obj).filter(isNotHiddenName); } - axisSquish[5 * i] = 0 - axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] - multiply(axisSquish, camera.model, axisSquish) + }); - var nclipBounds = PROJECT_DATA.clipBounds[i] - for (k = 0; k < 2; ++k) { - for (j = 0; j < 3; ++j) { - nclipBounds[k][j] = camera.clipBounds[k][j] + /** + * getPropertyNames is not in ES5 but it is proposed for ES6 and + * does appear in our whitelist, so we need to clean it too. + */ + if ('getPropertyNames' in Object) { + var originalGetPropertyNames = Object.getPropertyNames; + defProp(Object, 'getPropertyNames', { + value: function fakeGetPropertyNames(obj) { + return originalGetPropertyNames(obj).filter(isNotHiddenName); } - } - nclipBounds[0][i] = -1e8 - nclipBounds[1][i] = 1e8 + }); } - PROJECT_DATA.showSurface = showSurface - PROJECT_DATA.showContour = showContour - - return PROJECT_DATA -} - -var UNIFORMS = { - model: IDENTITY, - view: IDENTITY, - projection: IDENTITY, - inverseModel: IDENTITY.slice(), - lowerBound: [0, 0, 0], - upperBound: [0, 0, 0], - colorMap: 0, - clipBounds: [[0, 0, 0], [0, 0, 0]], - height: 0.0, - contourTint: 0, - contourColor: [0, 0, 0, 1], - permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], - zOffset: -1e-4, - kambient: 1, - kdiffuse: 1, - kspecular: 1, - lightPosition: [1000, 1000, 1000], - eyePosition: [0, 0, 0], - roughness: 1, - fresnel: 1, - opacity: 1 -} + /** + *

To treat objects as identity-keys with reasonable efficiency + * on ES5 by itself (i.e., without any object-keyed collections), we + * need to add a hidden property to such key objects when we + * can. This raises several issues: + *

    + *
  • Arranging to add this property to objects before we lose the + * chance, and + *
  • Hiding the existence of this new property from most + * JavaScript code. + *
  • Preventing certification theft, where one object is + * created falsely claiming to be the key of an association + * actually keyed by another object. + *
  • Preventing value theft, where untrusted code with + * access to a key object but not a weak map nevertheless + * obtains access to the value associated with that key in that + * weak map. + *
+ * We do so by + *
    + *
  • Making the name of the hidden property unguessable, so "[]" + * indexing, which we cannot intercept, cannot be used to access + * a property without knowing the name. + *
  • Making the hidden property non-enumerable, so we need not + * worry about for-in loops or {@code Object.keys}, + *
  • monkey patching those reflective methods that would + * prevent extensions, to add this hidden property first, + *
  • monkey patching those methods that would reveal this + * hidden property. + *
+ * Unfortunately, because of same-origin iframes, we cannot reliably + * add this hidden property before an object becomes + * non-extensible. Instead, if we encounter a non-extensible object + * without a hidden record that we can detect (whether or not it has + * a hidden record stored under a name secret to us), then we just + * use the key object itself to represent its identity in a brute + * force leaky map stored in the weak map, losing all the advantages + * of weakness for these. + */ + function getHiddenRecord(key) { + if (key !== Object(key)) { + throw new TypeError('Not an object: ' + key); + } + var hiddenRecord = key[HIDDEN_NAME]; + if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } + if (!isExtensible(key)) { + // Weak map must brute force, as explained in doc-comment above. + return void 0; + } -var MATRIX_INVERSE = IDENTITY.slice() -var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] + // The hiddenRecord and the key point directly at each other, via + // the "key" and HIDDEN_NAME properties respectively. The key + // field is for quickly verifying that this hidden record is an + // own property, not a hidden record from up the prototype chain. + // + // NOTE: Because this WeakMap emulation is meant only for systems like + // SES where Object.prototype is frozen without any numeric + // properties, it is ok to use an object literal for the hiddenRecord. + // This has two advantages: + // * It is much faster in a performance critical place + // * It avoids relying on Object.create(null), which had been + // problematic on Chrome 28.0.1480.0. See + // https://code.google.com/p/google-caja/issues/detail?id=1687 + hiddenRecord = { key: key }; -function drawCore (params, transparent) { - params = params || {} - var gl = this.gl + // When using this WeakMap emulation on platforms where + // Object.prototype might not be frozen and Object.create(null) is + // reliable, use the following two commented out lines instead. + // hiddenRecord = Object.create(null); + // hiddenRecord.key = key; - gl.disable(gl.CULL_FACE) + // Please contact us if you need this to work on platforms where + // Object.prototype might not be frozen and + // Object.create(null) might not be reliable. - this._colorMap.bind(0) + try { + defProp(key, HIDDEN_NAME, { + value: hiddenRecord, + writable: false, + enumerable: false, + configurable: false + }); + return hiddenRecord; + } catch (error) { + // Under some circumstances, isExtensible seems to misreport whether + // the HIDDEN_NAME can be defined. + // The circumstances have not been isolated, but at least affect + // Node.js v0.10.26 on TravisCI / Linux, but not the same version of + // Node.js on OS X. + return void 0; + } + } - var uniforms = UNIFORMS - uniforms.model = params.model || IDENTITY - uniforms.view = params.view || IDENTITY - uniforms.projection = params.projection || IDENTITY - uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] - uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] - uniforms.contourColor = this.contourColor[0] + /** + * Monkey patch operations that would make their argument + * non-extensible. + * + *

The monkey patched versions throw a TypeError if their + * argument is not an object, so it should only be done to functions + * that should throw a TypeError anyway if their argument is not an + * object. + */ + (function(){ + var oldFreeze = Object.freeze; + defProp(Object, 'freeze', { + value: function identifyingFreeze(obj) { + getHiddenRecord(obj); + return oldFreeze(obj); + } + }); + var oldSeal = Object.seal; + defProp(Object, 'seal', { + value: function identifyingSeal(obj) { + getHiddenRecord(obj); + return oldSeal(obj); + } + }); + var oldPreventExtensions = Object.preventExtensions; + defProp(Object, 'preventExtensions', { + value: function identifyingPreventExtensions(obj) { + getHiddenRecord(obj); + return oldPreventExtensions(obj); + } + }); + })(); - uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model) + function constFunc(func) { + func.prototype = null; + return Object.freeze(func); + } - for (var i = 0; i < 2; ++i) { - var clipClamped = uniforms.clipBounds[i] - for (var j = 0; j < 3; ++j) { - clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) + var calledAsFunctionWarningDone = false; + function calledAsFunctionWarning() { + // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() + // but we used to permit it and do it ourselves, so warn only. + if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { + calledAsFunctionWarningDone = true; + console.warn('WeakMap should be invoked as new WeakMap(), not ' + + 'WeakMap(). This will be an error in the future.'); } } - uniforms.kambient = this.ambientLight - uniforms.kdiffuse = this.diffuseLight - uniforms.kspecular = this.specularLight + var nextId = 0; - uniforms.roughness = this.roughness - uniforms.fresnel = this.fresnel - uniforms.opacity = this.opacity + var OurWeakMap = function() { + if (!(this instanceof OurWeakMap)) { // approximate test for new ...() + calledAsFunctionWarning(); + } - uniforms.height = 0.0 - uniforms.permutation = DEFAULT_PERM + // We are currently (12/25/2012) never encountering any prematurely + // non-extensible keys. + var keys = []; // brute force for prematurely non-extensible keys. + var values = []; // brute force for corresponding values. + var id = nextId++; - // Compute camera matrix inverse - var invCameraMatrix = MATRIX_INVERSE - multiply(invCameraMatrix, uniforms.view, uniforms.model) - multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) - invert(invCameraMatrix, invCameraMatrix) + function get___(key, opt_default) { + var index; + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + return id in hiddenRecord ? hiddenRecord[id] : opt_default; + } else { + index = keys.indexOf(key); + return index >= 0 ? values[index] : opt_default; + } + } - for (i = 0; i < 3; ++i) { - uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15] - } + function has___(key) { + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + return id in hiddenRecord; + } else { + return keys.indexOf(key) >= 0; + } + } - var w = invCameraMatrix[15] - for (i = 0; i < 3; ++i) { - w += this.lightPosition[i] * invCameraMatrix[4 * i + 3] - } - for (i = 0; i < 3; ++i) { - var s = invCameraMatrix[12 + i] - for (j = 0; j < 3; ++j) { - s += invCameraMatrix[4 * j + i] * this.lightPosition[j] + function set___(key, value) { + var index; + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + hiddenRecord[id] = value; + } else { + index = keys.indexOf(key); + if (index >= 0) { + values[index] = value; + } else { + // Since some browsers preemptively terminate slow turns but + // then continue computing with presumably corrupted heap + // state, we here defensively get keys.length first and then + // use it to update both the values and keys arrays, keeping + // them in sync. + index = keys.length; + values[index] = value; + // If we crash here, values will be one longer than keys. + keys[index] = key; + } + } + return this; + } + + function delete___(key) { + var hiddenRecord = getHiddenRecord(key); + var index, lastIndex; + if (hiddenRecord) { + return id in hiddenRecord && delete hiddenRecord[id]; + } else { + index = keys.indexOf(key); + if (index < 0) { + return false; + } + // Since some browsers preemptively terminate slow turns but + // then continue computing with potentially corrupted heap + // state, we here defensively get keys.length first and then use + // it to update both the keys and the values array, keeping + // them in sync. We update the two with an order of assignments, + // such that any prefix of these assignments will preserve the + // key/value correspondence, either before or after the delete. + // Note that this needs to work correctly when index === lastIndex. + lastIndex = keys.length - 1; + keys[index] = void 0; + // If we crash here, there's a void 0 in the keys array, but + // no operation will cause a "keys.indexOf(void 0)", since + // getHiddenRecord(void 0) will always throw an error first. + values[index] = values[lastIndex]; + // If we crash here, values[index] cannot be found here, + // because keys[index] is void 0. + keys[index] = keys[lastIndex]; + // If index === lastIndex and we crash here, then keys[index] + // is still void 0, since the aliasing killed the previous key. + keys.length = lastIndex; + // If we crash here, keys will be one shorter than values. + values.length = lastIndex; + return true; + } } - uniforms.lightPosition[i] = s / w - } - var projectData = computeProjectionData(uniforms, this) + return Object.create(OurWeakMap.prototype, { + get___: { value: constFunc(get___) }, + has___: { value: constFunc(has___) }, + set___: { value: constFunc(set___) }, + delete___: { value: constFunc(delete___) } + }); + }; - if (projectData.showSurface && (transparent === (this.opacity < 1))) { - // Set up uniforms - this._shader.bind() - this._shader.uniforms = uniforms + OurWeakMap.prototype = Object.create(Object.prototype, { + get: { + /** + * Return the value most recently associated with key, or + * opt_default if none. + */ + value: function get(key, opt_default) { + return this.get___(key, opt_default); + }, + writable: true, + configurable: true + }, - // Draw it - this._vao.bind() + has: { + /** + * Is there a value associated with key in this WeakMap? + */ + value: function has(key) { + return this.has___(key); + }, + writable: true, + configurable: true + }, - if (this.showSurface && this._vertexCount) { - this._vao.draw(gl.TRIANGLES, this._vertexCount) - } + set: { + /** + * Associate value with key in this WeakMap, overwriting any + * previous association if present. + */ + value: function set(key, value) { + return this.set___(key, value); + }, + writable: true, + configurable: true + }, - // Draw projections of surface - for (i = 0; i < 3; ++i) { - if (!this.surfaceProject[i] || !this.vertexCount) { - continue - } - this._shader.uniforms.model = projectData.projections[i] - this._shader.uniforms.clipBounds = projectData.clipBounds[i] - this._vao.draw(gl.TRIANGLES, this._vertexCount) + 'delete': { + /** + * Remove any association for key in this WeakMap, returning + * whether there was one. + * + *

Note that the boolean return here does not work like the + * {@code delete} operator. The {@code delete} operator returns + * whether the deletion succeeds at bringing about a state in + * which the deleted property is absent. The {@code delete} + * operator therefore returns true if the property was already + * absent, whereas this {@code delete} method returns false if + * the association was already absent. + */ + value: function remove(key) { + return this.delete___(key); + }, + writable: true, + configurable: true } + }); - this._vao.unbind() - } + if (typeof HostWeakMap === 'function') { + (function() { + // If we got here, then the platform has a WeakMap but we are concerned + // that it may refuse to store some key types. Therefore, make a map + // implementation which makes use of both as possible. - if (projectData.showContour && !transparent) { - var shader = this._contourShader + // In this mode we are always using double maps, so we are not proxy-safe. + // This combination does not occur in any known browser, but we had best + // be safe. + if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { + Proxy = undefined; + } - // Don't apply lighting to contours - uniforms.kambient = 1.0 - uniforms.kdiffuse = 0.0 - uniforms.kspecular = 0.0 - uniforms.opacity = 1.0 + function DoubleWeakMap() { + if (!(this instanceof OurWeakMap)) { // approximate test for new ...() + calledAsFunctionWarning(); + } - shader.bind() - shader.uniforms = uniforms + // Preferable, truly weak map. + var hmap = new HostWeakMap(); - // Draw contour lines - var vao = this._contourVAO - vao.bind() + // Our hidden-property-based pseudo-weak-map. Lazily initialized in the + // 'set' implementation; thus we can avoid performing extra lookups if + // we know all entries actually stored are entered in 'hmap'. + var omap = undefined; - // Draw contour levels - for (i = 0; i < 3; ++i) { - shader.uniforms.permutation = PERMUTATIONS[i] - gl.lineWidth(this.contourWidth[i]) + // Hidden-property maps are not compatible with proxies because proxies + // can observe the hidden name and either accidentally expose it or fail + // to allow the hidden property to be set. Therefore, we do not allow + // arbitrary WeakMaps to switch to using hidden properties, but only + // those which need the ability, and unprivileged code is not allowed + // to set the flag. + // + // (Except in doubleWeakMapCheckSilentFailure mode in which case we + // disable proxies.) + var enableSwitching = false; - for (j = 0; j < this.contourLevels[i].length; ++j) { - if (!this._contourCounts[i][j]) { - continue - } - if (j === this.highlightLevel[i]) { - shader.uniforms.contourColor = this.highlightColor[i] - shader.uniforms.contourTint = this.highlightTint[i] - } else if (j === 0 || (j - 1) === this.highlightLevel[i]) { - shader.uniforms.contourColor = this.contourColor[i] - shader.uniforms.contourTint = this.contourTint[i] + function dget(key, opt_default) { + if (omap) { + return hmap.has(key) ? hmap.get(key) + : omap.get___(key, opt_default); + } else { + return hmap.get(key, opt_default); + } } - shader.uniforms.height = this.contourLevels[i][j] - vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j]) - } - } - // Draw projections of surface - for (i = 0; i < 3; ++i) { - shader.uniforms.model = projectData.projections[i] - shader.uniforms.clipBounds = projectData.clipBounds[i] - for (j = 0; j < 3; ++j) { - if (!this.contourProject[i][j]) { - continue + function dhas(key) { + return hmap.has(key) || (omap ? omap.has___(key) : false); } - shader.uniforms.permutation = PERMUTATIONS[j] - gl.lineWidth(this.contourWidth[j]) - for (var k = 0; k < this.contourLevels[j].length; ++k) { - if (k === this.highlightLevel[j]) { - shader.uniforms.contourColor = this.highlightColor[j] - shader.uniforms.contourTint = this.highlightTint[j] - } else if (k === 0 || (k - 1) === this.highlightLevel[j]) { - shader.uniforms.contourColor = this.contourColor[j] - shader.uniforms.contourTint = this.contourTint[j] - } - shader.uniforms.height = this.contourLevels[j][k] - vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) + + var dset; + if (doubleWeakMapCheckSilentFailure) { + dset = function(key, value) { + hmap.set(key, value); + if (!hmap.has(key)) { + if (!omap) { omap = new OurWeakMap(); } + omap.set(key, value); + } + return this; + }; + } else { + dset = function(key, value) { + if (enableSwitching) { + try { + hmap.set(key, value); + } catch (e) { + if (!omap) { omap = new OurWeakMap(); } + omap.set___(key, value); + } + } else { + hmap.set(key, value); + } + return this; + }; } - } - } - // Draw dynamic contours - vao = this._dynamicVAO - vao.bind() + function ddelete(key) { + var result = !!hmap['delete'](key); + if (omap) { return omap.delete___(key) || result; } + return result; + } - // Draw contour levels - for (i = 0; i < 3; ++i) { - if (this._dynamicCounts[i] === 0) { - continue + return Object.create(OurWeakMap.prototype, { + get___: { value: constFunc(dget) }, + has___: { value: constFunc(dhas) }, + set___: { value: constFunc(dset) }, + delete___: { value: constFunc(ddelete) }, + permitHostObjects___: { value: constFunc(function(token) { + if (token === weakMapPermitHostObjects) { + enableSwitching = true; + } else { + throw new Error('bogus call to permitHostObjects___'); + } + })} + }); } + DoubleWeakMap.prototype = OurWeakMap.prototype; + module.exports = DoubleWeakMap; - shader.uniforms.model = uniforms.model - shader.uniforms.clipBounds = uniforms.clipBounds - shader.uniforms.permutation = PERMUTATIONS[i] - gl.lineWidth(this.dynamicWidth[i]) - - shader.uniforms.contourColor = this.dynamicColor[i] - shader.uniforms.contourTint = this.dynamicTint[i] - shader.uniforms.height = this.dynamicLevel[i] - vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - - for (j = 0; j < 3; ++j) { - if (!this.contourProject[j][i]) { - continue - } + // define .constructor to hide OurWeakMap ctor + Object.defineProperty(WeakMap.prototype, 'constructor', { + value: WeakMap, + enumerable: false, // as default .constructor is + configurable: true, + writable: true + }); + })(); + } else { + // There is no host WeakMap, so we must use the emulation. - shader.uniforms.model = projectData.projections[j] - shader.uniforms.clipBounds = projectData.clipBounds[j] - vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - } + // Emulated WeakMaps are incompatible with native proxies (because proxies + // can observe the hidden name), so we must disable Proxy usage (in + // ArrayLike and Domado, currently). + if (typeof Proxy !== 'undefined') { + Proxy = undefined; } - vao.unbind() + module.exports = OurWeakMap; } -} - -proto.draw = function (params) { - return drawCore.call(this, params, false) -} +})(); -proto.drawTransparent = function (params) { - return drawCore.call(this, params, true) -} +},{}],464:[function(require,module,exports){ +'use strict' -var PICK_UNIFORMS = { - model: IDENTITY, - view: IDENTITY, - projection: IDENTITY, - inverseModel: IDENTITY, - clipBounds: [[0, 0, 0], [0, 0, 0]], - height: 0.0, - shape: [0, 0], - pickId: 0, - lowerBound: [0, 0, 0], - upperBound: [0, 0, 0], - zOffset: 0.0, - permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], - lightPosition: [0, 0, 0], - eyePosition: [0, 0, 0] -} +var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') -proto.drawPick = function (params) { - params = params || {} - var gl = this.gl - gl.disable(gl.CULL_FACE) +var TriangleCache = new weakMap() - var uniforms = PICK_UNIFORMS - uniforms.model = params.model || IDENTITY - uniforms.view = params.view || IDENTITY - uniforms.projection = params.projection || IDENTITY - uniforms.shape = this._field[2].shape - uniforms.pickId = this.pickId / 255.0 - uniforms.lowerBound = this.bounds[0] - uniforms.upperBound = this.bounds[1] - uniforms.permutation = DEFAULT_PERM +function createABigTriangle(gl) { - for (var i = 0; i < 2; ++i) { - var clipClamped = uniforms.clipBounds[i] - for (var j = 0; j < 3; ++j) { - clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) - } + var triangleVAO = TriangleCache.get(gl) + if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) { + var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) + triangleVAO = createVAO(gl, [ + { buffer: buf, + type: gl.FLOAT, + size: 2 + } + ]) + triangleVAO._triangleBuffer = buf + TriangleCache.set(gl, triangleVAO) } + triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, 3) + triangleVAO.unbind() +} - var projectData = computeProjectionData(uniforms, this) +module.exports = createABigTriangle - if (projectData.showSurface) { - // Set up uniforms - this._pickShader.bind() - this._pickShader.uniforms = uniforms +},{"gl-buffer":455,"gl-vao":462,"weak-map":463}],465:[function(require,module,exports){ +'use strict' - // Draw it - this._vao.bind() - this._vao.draw(gl.TRIANGLES, this._vertexCount) +module.exports = createAxes - // Draw projections of surface - for (i = 0; i < 3; ++i) { - if (!this.surfaceProject[i]) { - continue - } - this._pickShader.uniforms.model = projectData.projections[i] - this._pickShader.uniforms.clipBounds = projectData.clipBounds[i] - this._vao.draw(gl.TRIANGLES, this._vertexCount) - } +var createText = require('./lib/text.js') +var createLines = require('./lib/lines.js') +var createBackground = require('./lib/background.js') +var getCubeProperties = require('./lib/cube.js') +var Ticks = require('./lib/ticks.js') - this._vao.unbind() - } +var identity = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]) - if (projectData.showContour) { - var shader = this._contourPickShader +function copyVec3(a, b) { + a[0] = b[0] + a[1] = b[1] + a[2] = b[2] + return a +} - shader.bind() - shader.uniforms = uniforms +function Axes(gl) { + this.gl = gl - var vao = this._contourVAO - vao.bind() + this.pixelRatio = 1 - for (j = 0; j < 3; ++j) { - gl.lineWidth(this.contourWidth[j]) - shader.uniforms.permutation = PERMUTATIONS[j] - for (i = 0; i < this.contourLevels[j].length; ++i) { - if (this._contourCounts[j][i]) { - shader.uniforms.height = this.contourLevels[j][i] - vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i]) - } - } - } + this.bounds = [ [-10, -10, -10], + [ 10, 10, 10] ] + this.ticks = [ [], [], [] ] + this.autoTicks = true + this.tickSpacing = [ 1, 1, 1 ] - // Draw projections of surface - for (i = 0; i < 3; ++i) { - shader.uniforms.model = projectData.projections[i] - shader.uniforms.clipBounds = projectData.clipBounds[i] + this.tickEnable = [ true, true, true ] + this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ] + this.tickSize = [ 12, 12, 12 ] + this.tickAngle = [ 0, 0, 0 ] + this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.tickPad = [ 10, 10, 10 ] - for (j = 0; j < 3; ++j) { - if (!this.contourProject[i][j]) { - continue - } + this.lastCubeProps = { + cubeEdges: [0,0,0], + axis: [0,0,0] + } - shader.uniforms.permutation = PERMUTATIONS[j] - gl.lineWidth(this.contourWidth[j]) - for (var k = 0; k < this.contourLevels[j].length; ++k) { - if (this._contourCounts[j][k]) { - shader.uniforms.height = this.contourLevels[j][k] - vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) - } - } - } - } + this.labels = [ 'x', 'y', 'z' ] + this.labelEnable = [ true, true, true ] + this.labelFont = 'sans-serif' + this.labelSize = [ 20, 20, 20 ] + this.labelAngle = [ 0, 0, 0 ] + this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.labelPad = [ 10, 10, 10 ] - vao.unbind() - } -} + this.lineEnable = [ true, true, true ] + this.lineMirror = [ false, false, false ] + this.lineWidth = [ 1, 1, 1 ] + this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] -proto.pick = function (selection) { - if (!selection) { - return null - } + this.lineTickEnable = [ true, true, true ] + this.lineTickMirror = [ false, false, false ] + this.lineTickLength = [ 0, 0, 0 ] + this.lineTickWidth = [ 1, 1, 1 ] + this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - if (selection.id !== this.pickId) { - return null - } + this.gridEnable = [ true, true, true ] + this.gridWidth = [ 1, 1, 1 ] + this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - var shape = this._field[2].shape + this.zeroEnable = [ true, true, true ] + this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.zeroLineWidth = [ 2, 2, 2 ] - var result = this._pickResult + this.backgroundEnable = [ false, false, false ] + this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5], + [0.8, 0.8, 0.8, 0.5], + [0.8, 0.8, 0.8, 0.5] ] - // Compute uv coordinate - var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0 - var ix = Math.floor(x) - var fx = x - ix + this._firstInit = true + this._text = null + this._lines = null + this._background = createBackground(gl) +} - var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0 - var iy = Math.floor(y) - var fy = y - iy +var proto = Axes.prototype - ix += 1 - iy += 1 +proto.update = function(options) { + options = options || {} - // Compute xyz coordinate - var pos = result.position - pos[0] = pos[1] = pos[2] = 0 - for (var dx = 0; dx < 2; ++dx) { - var s = dx ? fx : 1.0 - fx - for (var dy = 0; dy < 2; ++dy) { - var t = dy ? fy : 1.0 - fy + //Option parsing helper functions + function parseOption(nest, cons, name) { + if(name in options) { + var opt = options[name] + var prev = this[name] + var next + if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : + Array.isArray(opt) ) { + this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] + } else { + this[name] = next = [ cons(opt), cons(opt), cons(opt) ] + } + for(var i=0; i<3; ++i) { + if(next[i] !== prev[i]) { + return true + } + } + } + return false + } - var r = ix + dx - var c = iy + dy - var w = s * t + var NUMBER = parseOption.bind(this, false, Number) + var BOOLEAN = parseOption.bind(this, false, Boolean) + var STRING = parseOption.bind(this, false, String) + var COLOR = parseOption.bind(this, true, function(v) { + if(Array.isArray(v)) { + if(v.length === 3) { + return [ +v[0], +v[1], +v[2], 1.0 ] + } else if(v.length === 4) { + return [ +v[0], +v[1], +v[2], +v[3] ] + } + } + return [ 0, 0, 0, 1 ] + }) - for (var i = 0; i < 3; ++i) { - pos[i] += this._field[i].get(r, c) * w + //Tick marks and bounds + var nextTicks + var ticksUpdate = false + var boundsChanged = false + if('bounds' in options) { + var bounds = options.bounds +i_loop: + for(var i=0; i<2; ++i) { + for(var j=0; j<3; ++j) { + if(bounds[i][j] !== this.bounds[i][j]) { + boundsChanged = true + } + this.bounds[i][j] = bounds[i][j] } } } - - // Find closest level - var levelIndex = this._pickResult.level - for (var j = 0; j < 3; ++j) { - levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j]) - if (levelIndex[j] < 0) { - if (this.contourLevels[j].length > 0) { - levelIndex[j] = 0 - } - } else if (levelIndex[j] < this.contourLevels[j].length - 1) { - var a = this.contourLevels[j][levelIndex[j]] - var b = this.contourLevels[j][levelIndex[j] + 1] - if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) { - levelIndex[j] += 1 - } + if('ticks' in options) { + nextTicks = options.ticks + ticksUpdate = true + this.autoTicks = false + for(var i=0; i<3; ++i) { + this.tickSpacing[i] = 0.0 } + } else if(NUMBER('tickSpacing')) { + this.autoTicks = true + boundsChanged = true } - result.index[0] = fx < 0.5 ? ix : (ix + 1) - result.index[1] = fy < 0.5 ? iy : (iy + 1) - - result.uv[0] = x / shape[0] - result.uv[1] = y / shape[1] + if(this._firstInit) { + if(!('ticks' in options || 'tickSpacing' in options)) { + this.autoTicks = true + } - for (i = 0; i < 3; ++i) { - result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]) + //Force tick recomputation on first update + boundsChanged = true + ticksUpdate = true + this._firstInit = false } - return result -} - -function padField (nfield, field) { - var shape = field.shape.slice() - var nshape = nfield.shape.slice() - - // Center - ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) - - // Edges - ops.assign(nfield.lo(1).hi(shape[0], 1), - field.hi(shape[0], 1)) - ops.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), - field.lo(0, shape[1] - 1).hi(shape[0], 1)) - ops.assign(nfield.lo(0, 1).hi(1, shape[1]), - field.hi(1)) - ops.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), - field.lo(shape[0] - 1)) - // Corners - nfield.set(0, 0, field.get(0, 0)) - nfield.set(0, nshape[1] - 1, field.get(0, shape[1] - 1)) - nfield.set(nshape[0] - 1, 0, field.get(shape[0] - 1, 0)) - nfield.set(nshape[0] - 1, nshape[1] - 1, field.get(shape[0] - 1, shape[1] - 1)) -} - -function handleArray (param, ctor) { - if (Array.isArray(param)) { - return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ] + if(boundsChanged && this.autoTicks) { + nextTicks = Ticks.create(this.bounds, this.tickSpacing) + ticksUpdate = true } - return [ ctor(param), ctor(param), ctor(param) ] -} -function toColor (x) { - if (Array.isArray(x)) { - if (x.length === 3) { - return [x[0], x[1], x[2], 1] + //Compare next ticks to previous ticks, only update if needed + if(ticksUpdate) { + for(var i=0; i<3; ++i) { + nextTicks[i].sort(function(a,b) { + return a.x-b.x + }) } - return [x[0], x[1], x[2], x[3]] - } - return [0, 0, 0, 1] -} - -function handleColor (param) { - if (Array.isArray(param)) { - if (Array.isArray(param)) { - return [ - toColor(param[0]), - toColor(param[1]), - toColor(param[2]) ] + if(Ticks.equal(nextTicks, this.ticks)) { + ticksUpdate = false } else { - var c = toColor(param) - return [ - c.slice(), - c.slice(), - c.slice() ] + this.ticks = nextTicks } } -} - -proto.update = function (params) { - params = params || {} - - this.dirty = true - if ('contourWidth' in params) { - this.contourWidth = handleArray(params.contourWidth, Number) - } - if ('showContour' in params) { - this.showContour = handleArray(params.showContour, Boolean) - } - if ('showSurface' in params) { - this.showSurface = !!params.showSurface - } - if ('contourTint' in params) { - this.contourTint = handleArray(params.contourTint, Boolean) - } - if ('contourColor' in params) { - this.contourColor = handleColor(params.contourColor) - } - if ('contourProject' in params) { - this.contourProject = handleArray(params.contourProject, function (x) { - return handleArray(x, Boolean) - }) - } - if ('surfaceProject' in params) { - this.surfaceProject = params.surfaceProject - } - if ('dynamicColor' in params) { - this.dynamicColor = handleColor(params.dynamicColor) - } - if ('dynamicTint' in params) { - this.dynamicTint = handleArray(params.dynamicTint, Number) - } - if ('dynamicWidth' in params) { - this.dynamicWidth = handleArray(params.dynamicWidth, Number) - } - if ('opacity' in params) { - this.opacity = params.opacity + //Parse tick properties + BOOLEAN('tickEnable') + if(STRING('tickFont')) { + ticksUpdate = true //If font changes, must rebuild vbo } - if ('colorBounds' in params) { - this.colorBounds = params.colorBounds + NUMBER('tickSize') + NUMBER('tickAngle') + NUMBER('tickPad') + COLOR('tickColor') + + //Axis labels + var labelUpdate = STRING('labels') + if(STRING('labelFont')) { + labelUpdate = true } + BOOLEAN('labelEnable') + NUMBER('labelSize') + NUMBER('labelPad') + COLOR('labelColor') - var field = params.field || (params.coords && params.coords[2]) || null - var levelsChanged = false + //Axis lines + BOOLEAN('lineEnable') + BOOLEAN('lineMirror') + NUMBER('lineWidth') + COLOR('lineColor') - if (!field) { - if (this._field[2].shape[0] || this._field[2].shape[2]) { - field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2) - } else { - field = this._field[2].hi(0, 0) - } - } + //Axis line ticks + BOOLEAN('lineTickEnable') + BOOLEAN('lineTickMirror') + NUMBER('lineTickLength') + NUMBER('lineTickWidth') + COLOR('lineTickColor') - // Update field - if ('field' in params || 'coords' in params) { - var fsize = (field.shape[0] + 2) * (field.shape[1] + 2) + //Grid lines + BOOLEAN('gridEnable') + NUMBER('gridWidth') + COLOR('gridColor') - // Resize if necessary - if (fsize > this._field[2].data.length) { - pool.freeFloat(this._field[2].data) - this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize)) - } + //Zero line + BOOLEAN('zeroEnable') + COLOR('zeroLineColor') + NUMBER('zeroLineWidth') - // Pad field - this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) - padField(this._field[2], field) + //Background + BOOLEAN('backgroundEnable') + COLOR('backgroundColor') - // Save shape of field - this.shape = field.shape.slice() - var shape = this.shape + //Update text if necessary + if(!this._text) { + this._text = createText( + this.gl, + this.bounds, + this.labels, + this.labelFont, + this.ticks, + this.tickFont) + } else if(this._text && (labelUpdate || ticksUpdate)) { + this._text.update( + this.bounds, + this.labels, + this.labelFont, + this.ticks, + this.tickFont) + } - // Resize coordinate fields if necessary - for (var i = 0; i < 2; ++i) { - if (this._field[2].size > this._field[i].data.length) { - pool.freeFloat(this._field[i].data) - this._field[i].data = pool.mallocFloat(this._field[2].size) - } - this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]) - } + //Update lines if necessary + if(this._lines && ticksUpdate) { + this._lines.dispose() + this._lines = null + } + if(!this._lines) { + this._lines = createLines(this.gl, this.bounds, this.ticks) + } +} - // Generate x/y coordinates - if (params.coords) { - var coords = params.coords - if (!Array.isArray(coords) || coords.length !== 3) { - throw new Error('gl-surface: invalid coordinates for x/y') - } - for (i = 0; i < 2; ++i) { - var coord = coords[i] - for (j = 0; j < 2; ++j) { - if (coord.shape[j] !== shape[j]) { - throw new Error('gl-surface: coords have incorrect shape') - } - } - padField(this._field[i], coord) - } - } else if (params.ticks) { - var ticks = params.ticks - if (!Array.isArray(ticks) || ticks.length !== 2) { - throw new Error('gl-surface: invalid ticks') - } - for (i = 0; i < 2; ++i) { - var tick = ticks[i] - if (Array.isArray(tick) || tick.length) { - tick = ndarray(tick) - } - if (tick.shape[0] !== shape[i]) { - throw new Error('gl-surface: invalid tick length') - } - // Make a copy view of the tick array - var tick2 = ndarray(tick.data, shape) - tick2.stride[i] = tick.stride[0] - tick2.stride[i ^ 1] = 0 +function OffsetInfo() { + this.primalOffset = [0,0,0] + this.primalMinor = [0,0,0] + this.mirrorOffset = [0,0,0] + this.mirrorMinor = [0,0,0] +} - // Fill in field array - padField(this._field[i], tick2) - } - } else { - for (i = 0; i < 2; ++i) { - var offset = [0, 0] - offset[i] = 1 - this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) - } - this._field[0].set(0, 0, 0) - for (var j = 0; j < shape[0]; ++j) { - this._field[0].set(j + 1, 0, j) - } - this._field[0].set(shape[0] + 1, 0, shape[0] - 1) - this._field[1].set(0, 0, 0) - for (j = 0; j < shape[1]; ++j) { - this._field[1].set(0, j + 1, j) - } - this._field[1].set(0, shape[1] + 1, shape[1] - 1) - } +var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ] - // Save shape - var fields = this._field +function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) { + var primalOffset = result.primalOffset + var primalMinor = result.primalMinor + var dualOffset = result.mirrorOffset + var dualMinor = result.mirrorMinor + var e = cubeEdges[i] - // Compute surface normals - var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) - for (i = 0; i < 3; ++i) { - gradient(dfields.pick(i), fields[i], 'mirror') + //Calculate offsets + for(var j=0; j<3; ++j) { + if(i === j) { + continue } - var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) - for (i = 0; i < shape[0] + 2; ++i) { - for (j = 0; j < shape[1] + 2; ++j) { - var dxdu = dfields.get(0, i, j, 0) - var dxdv = dfields.get(0, i, j, 1) - var dydu = dfields.get(1, i, j, 0) - var dydv = dfields.get(1, i, j, 1) - var dzdu = dfields.get(2, i, j, 0) - var dzdv = dfields.get(2, i, j, 1) + var a = primalOffset, + b = dualOffset, + c = primalMinor, + d = dualMinor + if(e & (1< 0) { + c[j] = -1 + d[j] = 0 + } else { + c[j] = 0 + d[j] = +1 + } + } +} - var nx = dydu * dzdv - dydv * dzdu - var ny = dzdu * dxdv - dzdv * dxdu - var nz = dxdu * dydv - dxdv * dydu +var CUBE_ENABLE = [0,0,0] +var DEFAULT_PARAMS = { + model: identity, + view: identity, + projection: identity +} - var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) - if (nl < 1e-8) { - nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz)) - if (nl < 1e-8) { - nz = 1.0 - ny = nx = 0.0 - nl = 1.0 - } else { - nl = 1.0 / nl - } - } else { - nl = 1.0 / Math.sqrt(nl) - } +proto.isOpaque = function() { + return true +} - normals.set(i, j, 0, nx * nl) - normals.set(i, j, 1, ny * nl) - normals.set(i, j, 2, nz * nl) - } - } - pool.free(dfields.data) +proto.isTransparent = function() { + return false +} - // Initialize surface - var lo = [ Infinity, Infinity, Infinity ] - var hi = [ -Infinity, -Infinity, -Infinity ] - var lo_intensity = Infinity - var hi_intensity = -Infinity - var count = (shape[0] - 1) * (shape[1] - 1) * 6 - var tverts = pool.mallocFloat(bits.nextPow2(10 * count)) - var tptr = 0 - var vertexCount = 0 - for (i = 0; i < shape[0] - 1; ++i) { - j_loop: - for (j = 0; j < shape[1] - 1; ++j) { - // Test for NaNs - for (var dx = 0; dx < 2; ++dx) { - for (var dy = 0; dy < 2; ++dy) { - for (var k = 0; k < 3; ++k) { - var f = this._field[k].get(1 + i + dx, 1 + j + dy) - if (isNaN(f) || !isFinite(f)) { - continue j_loop - } - } - } - } - for (k = 0; k < 6; ++k) { - var r = i + QUAD[k][0] - var c = j + QUAD[k][1] +proto.drawTransparent = function(params) {} - var tx = this._field[0].get(r + 1, c + 1) - var ty = this._field[1].get(r + 1, c + 1) - f = this._field[2].get(r + 1, c + 1) - var vf = f - nx = normals.get(r + 1, c + 1, 0) - ny = normals.get(r + 1, c + 1, 1) - nz = normals.get(r + 1, c + 1, 2) - if (params.intensity) { - vf = params.intensity.get(r, c) - } +var PRIMAL_MINOR = [0,0,0] +var MIRROR_MINOR = [0,0,0] +var PRIMAL_OFFSET = [0,0,0] - tverts[tptr++] = r - tverts[tptr++] = c - tverts[tptr++] = tx - tverts[tptr++] = ty - tverts[tptr++] = f - tverts[tptr++] = 0 - tverts[tptr++] = vf - tverts[tptr++] = nx - tverts[tptr++] = ny - tverts[tptr++] = nz +proto.draw = function(params) { + params = params || DEFAULT_PARAMS - lo[0] = Math.min(lo[0], tx) - lo[1] = Math.min(lo[1], ty) - lo[2] = Math.min(lo[2], f) - lo_intensity = Math.min(lo_intensity, vf) + var gl = this.gl - hi[0] = Math.max(hi[0], tx) - hi[1] = Math.max(hi[1], ty) - hi[2] = Math.max(hi[2], f) - hi_intensity = Math.max(hi_intensity, vf) + //Geometry for camera and axes + var model = params.model || identity + var view = params.view || identity + var projection = params.projection || identity + var bounds = this.bounds - vertexCount += 1 - } - } - } + //Unpack axis info + var cubeParams = getCubeProperties(model, view, projection, bounds) + var cubeEdges = cubeParams.cubeEdges + var cubeAxis = cubeParams.axis - if (params.intensityBounds) { - lo_intensity = +params.intensityBounds[0] - hi_intensity = +params.intensityBounds[1] - } + var cx = view[12] + var cy = view[13] + var cz = view[14] + var cw = view[15] - // Scale all vertex intensities - for (i = 6; i < tptr; i += 10) { - tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity) - } + var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight - this._vertexCount = vertexCount - this._coordinateBuffer.update(tverts.subarray(0, tptr)) - pool.freeFloat(tverts) - pool.free(normals.data) + for(var i=0; i<3; ++i) { + this.lastCubeProps.cubeEdges[i] = cubeEdges[i] + this.lastCubeProps.axis[i] = cubeAxis[i] + } - // Update bounds - this.bounds = [lo, hi] + //Compute axis info + var lineOffset = LINE_OFFSET + for(var i=0; i<3; ++i) { + computeLineOffset( + LINE_OFFSET[i], + i, + this.bounds, + cubeEdges, + cubeAxis) + } - // Save intensity - this.intensity = params.intensity || this._field[2] + //Set up state parameters + var gl = this.gl - if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) { - levelsChanged = true + //Draw background first + var cubeEnable = CUBE_ENABLE + for(var i=0; i<3; ++i) { + if(this.backgroundEnable[i]) { + cubeEnable[i] = cubeAxis[i] + } else { + cubeEnable[i] = 0 } - - // Save intensity bound - this.intensityBounds = [lo_intensity, hi_intensity] } - // Update level crossings - if ('levels' in params) { - var levels = params.levels - if (!Array.isArray(levels[0])) { - levels = [ [], [], levels ] + this._background.draw( + model, + view, + projection, + bounds, + cubeEnable, + this.backgroundColor) + + //Draw lines + this._lines.bind( + model, + view, + projection, + this) + + //First draw grid lines and zero lines + for(var i=0; i<3; ++i) { + var x = [0,0,0] + if(cubeAxis[i] > 0) { + x[i] = bounds[1][i] } else { - levels = levels.slice() - } - for (i = 0; i < 3; ++i) { - levels[i] = levels[i].slice() - levels.sort(function (a, b) { - return a - b - }) + x[i] = bounds[0][i] } - change_test: - for (i = 0; i < 3; ++i) { - if (levels[i].length !== this.contourLevels[i].length) { - levelsChanged = true - break + + //Draw grid lines + for(var j=0; j<2; ++j) { + var u = (i + 1 + j) % 3 + var v = (i + 1 + (j^1)) % 3 + if(this.gridEnable[u]) { + this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio) } - for (j = 0; j < levels[i].length; ++j) { - if (levels[i][j] !== this.contourLevels[i][j]) { - levelsChanged = true - break change_test + } + + //Draw zero lines (need to do this AFTER all grid lines are drawn) + for(var j=0; j<2; ++j) { + var u = (i + 1 + j) % 3 + var v = (i + 1 + (j^1)) % 3 + if(this.zeroEnable[v]) { + //Check if zero line in bounds + if(bounds[0][v] <= 0 && bounds[1][v] >= 0) { + this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio) } } } - this.contourLevels = levels } - if (levelsChanged) { - fields = this._field - shape = this.shape - - // Update contour lines - var contourVerts = [] - - for (var dim = 0; dim < 3; ++dim) { - levels = this.contourLevels[dim] - var levelOffsets = [] - var levelCounts = [] + //Then draw axis lines and tick marks + for(var i=0; i<3; ++i) { - var parts = [0, 0, 0] + //Draw axis lines + if(this.lineEnable[i]) { + this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) + } + if(this.lineMirror[i]) { + this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) + } - for (i = 0; i < levels.length; ++i) { - var graph = surfaceNets(this._field[dim], levels[i]) - levelOffsets.push((contourVerts.length / 5) | 0) - vertexCount = 0 + //Compute minor axes + var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor) + var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor) + var tickLength = this.lineTickLength + var op = 0 + for(var j=0; j<3; ++j) { + var scaleFactor = pixelScaleF / model[5*j] + primalMinor[j] *= tickLength[j] * scaleFactor + mirrorMinor[j] *= tickLength[j] * scaleFactor + } - edge_loop: - for (j = 0; j < graph.cells.length; ++j) { - var e = graph.cells[j] - for (k = 0; k < 2; ++k) { - var p = graph.positions[e[k]] + //Draw axis line ticks + if(this.lineTickEnable[i]) { + this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) + } + if(this.lineTickMirror[i]) { + this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) + } + } - var x = p[0] - var ix = Math.floor(x) | 0 - var fx = x - ix + //Draw text sprites + this._text.bind( + model, + view, + projection, + this.pixelRatio) - var y = p[1] - var iy = Math.floor(y) | 0 - var fy = y - iy + for(var i=0; i<3; ++i) { - var hole = false - dd_loop: - for (var dd = 0; dd < 3; ++dd) { - parts[dd] = 0.0 - var iu = (dim + dd + 1) % 3 - for (dx = 0; dx < 2; ++dx) { - var s = dx ? fx : 1.0 - fx - r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0 - for (dy = 0; dy < 2; ++dy) { - var t = dy ? fy : 1.0 - fy - c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0 + var minor = lineOffset[i].primalMinor + var offset = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset) - if (dd < 2) { - f = this._field[iu].get(r, c) - } else { - f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]) - } - if (!isFinite(f) || isNaN(f)) { - hole = true - break dd_loop - } + for(var j=0; j<3; ++j) { + if(this.lineTickEnable[i]) { + offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0) / model[5*j] + } + } - var w = s * t - parts[dd] += w * f - } - } - } + //Draw tick text + if(this.tickEnable[i]) { - if (!hole) { - contourVerts.push(parts[0], parts[1], p[0], p[1], parts[2]) - vertexCount += 1 - } else { - if (k > 0) { - // If we already added first edge, pop off verts - for (var l = 0; l < 5; ++l) { - contourVerts.pop() - } - vertexCount -= 1 - } - continue edge_loop - } - } - } - levelCounts.push(vertexCount) + //Add tick padding + for(var j=0; j<3; ++j) { + offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j] } - // Store results - this._contourOffsets[dim] = levelOffsets - this._contourCounts[dim] = levelCounts - } - - var floatBuffer = pool.mallocFloat(contourVerts.length) - for (i = 0; i < contourVerts.length; ++i) { - floatBuffer[i] = contourVerts[i] + //Draw axis + this._text.drawTicks( + i, + this.tickSize[i], + this.tickAngle[i], + offset, + this.tickColor[i]) } - this._contourBuffer.update(floatBuffer) - pool.freeFloat(floatBuffer) - } - - if (params.colormap) { - this._colorMap.setPixels(genColormap(params.colormap)) - } -} -proto.dispose = function () { - this._shader.dispose() - this._vao.dispose() - this._coordinateBuffer.dispose() - this._colorMap.dispose() - this._contourBuffer.dispose() - this._contourVAO.dispose() - this._contourShader.dispose() - this._contourPickShader.dispose() - this._dynamicBuffer.dispose() - this._dynamicVAO.dispose() - for (var i = 0; i < 3; ++i) { - pool.freeFloat(this._field[i].data) - } -} + //Draw labels + if(this.labelEnable[i]) { -proto.highlight = function (selection) { - if (!selection) { - this._dynamicCounts = [0, 0, 0] - this.dyanamicLevel = [NaN, NaN, NaN] - this.highlightLevel = [-1, -1, -1] - return - } + //Add label padding + for(var j=0; j<3; ++j) { + offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j] + } + offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]) - for (var i = 0; i < 3; ++i) { - if (this.enableHighlight[i]) { - this.highlightLevel[i] = selection.level[i] - } else { - this.highlightLevel[i] = -1 + //Draw axis + this._text.drawLabel( + i, + this.labelSize[i], + this.labelAngle[i], + offset, + this.labelColor[i]) } } +} - var levels - if (this.snapToData) { - levels = selection.dataCoordinate - } else { - levels = selection.position - } - if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) && - (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) && - (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) { - return - } - - var vertexCount = 0 - var shape = this.shape - var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1]) +proto.dispose = function() { + this._text.dispose() + this._lines.dispose() + this._background.dispose() + this._lines = null + this._text = null + this._background = null + this.gl = null +} - for (var d = 0; d < 3; ++d) { - if (!this.enableDynamic[d]) { - this.dynamicLevel[d] = NaN - this._dynamicCounts[d] = 0 - continue - } +function createAxes(gl, options) { + var axes = new Axes(gl) + axes.update(options) + return axes +} - this.dynamicLevel[d] = levels[d] +},{"./lib/background.js":466,"./lib/cube.js":467,"./lib/lines.js":468,"./lib/text.js":470,"./lib/ticks.js":471}],466:[function(require,module,exports){ +'use strict' - var u = (d + 1) % 3 - var v = (d + 2) % 3 +module.exports = createBackgroundCube - var f = this._field[d] - var g = this._field[u] - var h = this._field[v] - var intensity = this.intensity +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders').bg - var graph = surfaceNets(f, levels[d]) - var edges = graph.cells - var positions = graph.positions +function BackgroundCube(gl, buffer, vao, shader) { + this.gl = gl + this.buffer = buffer + this.vao = vao + this.shader = shader +} - this._dynamicOffsets[d] = vertexCount +var proto = BackgroundCube.prototype - for (i = 0; i < edges.length; ++i) { - var e = edges[i] - for (var j = 0; j < 2; ++j) { - var p = positions[e[j]] +proto.draw = function(model, view, projection, bounds, enable, colors) { + var needsBG = false + for(var i=0; i<3; ++i) { + needsBG = needsBG || enable[i] + } + if(!needsBG) { + return + } - var x = +p[0] - var ix = x | 0 - var jx = Math.min(ix + 1, shape[0]) | 0 - var fx = x - ix - var hx = 1.0 - fx + var gl = this.gl - var y = +p[1] - var iy = y | 0 - var jy = Math.min(iy + 1, shape[1]) | 0 - var fy = y - iy - var hy = 1.0 - fy + gl.enable(gl.POLYGON_OFFSET_FILL) + gl.polygonOffset(1, 2) - var w00 = hx * hy - var w01 = hx * fy - var w10 = fx * hy - var w11 = fx * fy + this.shader.bind() + this.shader.uniforms = { + model: model, + view: view, + projection: projection, + bounds: bounds, + enable: enable, + colors: colors + } + this.vao.bind() + this.vao.draw(this.gl.TRIANGLES, 36) - var cu = w00 * g.get(ix, iy) + - w01 * g.get(ix, jy) + - w10 * g.get(jx, iy) + - w11 * g.get(jx, jy) + gl.disable(gl.POLYGON_OFFSET_FILL) +} - var cv = w00 * h.get(ix, iy) + - w01 * h.get(ix, jy) + - w10 * h.get(jx, iy) + - w11 * h.get(jx, jy) +proto.dispose = function() { + this.vao.dispose() + this.buffer.dispose() + this.shader.dispose() +} - if (isNaN(cu) || isNaN(cv)) { - if (j) { - vertexCount -= 1 - } - break +function createBackgroundCube(gl) { + //Create cube vertices + var vertices = [] + var indices = [] + var ptr = 0 + for(var d=0; d<3; ++d) { + var u = (d+1) % 3 + var v = (d+2) % 3 + var x = [0,0,0] + var c = [0,0,0] + for(var s=-1; s<=1; s+=2) { + indices.push(ptr, ptr+2, ptr+1, + ptr+1, ptr+2, ptr+3) + x[d] = s + c[d] = s + for(var i=-1; i<=1; i+=2) { + x[u] = i + for(var j=-1; j<=1; j+=2) { + x[v] = j + vertices.push(x[0], x[1], x[2], + c[0], c[1], c[2]) + ptr += 1 } - - scratchBuffer[2 * vertexCount + 0] = cu - scratchBuffer[2 * vertexCount + 1] = cv - - vertexCount += 1 } + //Swap u and v + var tt = u + u = v + v = tt } - - this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d] } - this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) - pool.freeFloat(scratchBuffer) -} + //Allocate buffer and vertex array + var buffer = createBuffer(gl, new Float32Array(vertices)) + var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) + var vao = createVAO(gl, [ + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 0, + stride: 24 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 12, + stride: 24 + } + ], elements) -function createSurfacePlot (params) { - var gl = params.gl + //Create shader object var shader = createShader(gl) - var pickShader = createPickShader(gl) - var contourShader = createContourShader(gl) - var contourPickShader = createPickContourShader(gl) + shader.attributes.position.location = 0 + shader.attributes.normal.location = 1 - var coordinateBuffer = createBuffer(gl) - var vao = createVAO(gl, [ - { buffer: coordinateBuffer, - size: 4, - stride: SURFACE_VERTEX_SIZE, - offset: 0 - }, - { buffer: coordinateBuffer, - size: 3, - stride: SURFACE_VERTEX_SIZE, - offset: 16 - }, - { - buffer: coordinateBuffer, - size: 3, - stride: SURFACE_VERTEX_SIZE, - offset: 28 - } - ]) + return new BackgroundCube(gl, buffer, vao, shader) +} - var contourBuffer = createBuffer(gl) - var contourVAO = createVAO(gl, [ - { - buffer: contourBuffer, - size: 4, - stride: 20, - offset: 0 - }, - { - buffer: contourBuffer, - size: 1, - stride: 20, - offset: 16 - } - ]) +},{"./shaders":469,"gl-buffer":475,"gl-vao":480}],467:[function(require,module,exports){ +"use strict" - var dynamicBuffer = createBuffer(gl) - var dynamicVAO = createVAO(gl, [ - { - buffer: dynamicBuffer, - size: 2, - type: gl.FLOAT - }]) +module.exports = getCubeEdges - var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) - cmap.minFilter = gl.LINEAR - cmap.magFilter = gl.LINEAR +var bits = require('bit-twiddle') +var multiply = require('gl-mat4/multiply') +var invert = require('gl-mat4/invert') +var splitPoly = require('split-polygon') +var orient = require('robust-orientation') - var surface = new SurfacePlot( - gl, - [0, 0], - [[0, 0, 0], [0, 0, 0]], - shader, - pickShader, - coordinateBuffer, - vao, - cmap, - contourShader, - contourPickShader, - contourBuffer, - contourVAO, - dynamicBuffer, - dynamicVAO) +var mvp = new Array(16) +var imvp = new Array(16) +var pCubeVerts = new Array(8) +var cubeVerts = new Array(8) +var x = new Array(3) +var zero3 = [0,0,0] - var nparams = { - levels: [[], [], []] +;(function() { + for(var i=0; i<8; ++i) { + pCubeVerts[i] =[1,1,1,1] + cubeVerts[i] = [1,1,1] } - for (var id in params) { - nparams[id] = params[id] +})() + + +function transformHg(result, x, mat) { + for(var i=0; i<4; ++i) { + result[i] = mat[12+i] + for(var j=0; j<3; ++j) { + result[i] += x[j]*mat[4*j+i] + } } - nparams.colormap = nparams.colormap || 'jet' +} - surface.update(nparams) +var FRUSTUM_PLANES = [ + [ 0, 0, 1, 0, 0], + [ 0, 0,-1, 1, 0], + [ 0,-1, 0, 1, 0], + [ 0, 1, 0, 1, 0], + [-1, 0, 0, 1, 0], + [ 1, 0, 0, 1, 0] +] - return surface -} +function polygonArea(p) { + for(var i=0; i maxSize || h < 0 || h > maxSize) { - throw new Error('gl-texture2d: Invalid texture size') - } - tex._shape = [w, h] - tex.bind() - gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) - tex._mipLevels = [0] - return tex +var CUBE_EDGES = [1,1,1] +var CUBE_AXIS = [0,0,0] +var CUBE_RESULT = { + cubeEdges: CUBE_EDGES, + axis: CUBE_AXIS } -function Texture2D(gl, handle, width, height, format, type) { - this.gl = gl - this.handle = handle - this.format = format - this.type = type - this._shape = [width, height] - this._mipLevels = [0] - this._magFilter = gl.NEAREST - this._minFilter = gl.NEAREST - this._wrapS = gl.CLAMP_TO_EDGE - this._wrapT = gl.CLAMP_TO_EDGE - this._anisoSamples = 1 +function getCubeEdges(model, view, projection, bounds) { - var parent = this - var wrapVector = [this._wrapS, this._wrapT] - Object.defineProperties(wrapVector, [ - { - get: function() { - return parent._wrapS - }, - set: function(v) { - return parent.wrapS = v - } - }, - { - get: function() { - return parent._wrapT - }, - set: function(v) { - return parent.wrapT = v + //Concatenate matrices + multiply(mvp, view, model) + multiply(mvp, projection, mvp) + + //First project cube vertices + var ptr = 0 + for(var i=0; i<2; ++i) { + x[2] = bounds[i][2] + for(var j=0; j<2; ++j) { + x[1] = bounds[j][1] + for(var k=0; k<2; ++k) { + x[0] = bounds[k][0] + transformHg(pCubeVerts[ptr], x, mvp) + ptr += 1 } } - ]) - this._wrapVector = wrapVector + } - var shapeVector = [this._shape[0], this._shape[1]] - Object.defineProperties(shapeVector, [ - { - get: function() { - return parent._shape[0] - }, - set: function(v) { - return parent.width = v - } - }, - { - get: function() { - return parent._shape[1] - }, - set: function(v) { - return parent.height = v - } - } - ]) - this._shapeVector = shapeVector -} + //Classify camera against cube faces + var closest = -1 -var proto = Texture2D.prototype + for(var i=0; i<8; ++i) { + var w = pCubeVerts[i][3] + for(var l=0; l<3; ++l) { + cubeVerts[i][l] = pCubeVerts[i][l] / w + } + if(w < 0) { + if(closest < 0) { + closest = i + } else if(cubeVerts[i][2] < cubeVerts[closest][2]) { + closest = i + } + } + } -Object.defineProperties(proto, { - minFilter: { - get: function() { - return this._minFilter - }, - set: function(v) { - this.bind() - var gl = this.gl - if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { - if(!gl.getExtension('OES_texture_float_linear')) { - v = gl.NEAREST + if(closest < 0) { + closest = 0 + for(var d=0; d<3; ++d) { + var u = (d+2) % 3 + var v = (d+1) % 3 + var o0 = -1 + var o1 = -1 + for(var s=0; s<2; ++s) { + var f0 = (s<= 0) { - if(!gl.getExtension('OES_texture_float_linear')) { - v = gl.NEAREST + if(s) { + o0 = 1 + } else { + o1 = 1 } } - if(filterTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown filter mode ' + v) - } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) - return this._magFilter = v - } - }, - mipSamples: { - get: function() { - return this._anisoSamples - }, - set: function(i) { - var psamples = this._anisoSamples - this._anisoSamples = Math.max(i, 1)|0 - if(psamples !== this._anisoSamples) { - var ext = gl.getExtension('EXT_texture_filter_anisotropic') - if(ext) { - this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) + if(o0 < 0 || o1 < 0) { + if(o1 > o0) { + closest |= 1< o0) { + closest |= 1< cubeVerts[i][1]) { + bottom = i } - }, - width: { - get: function() { - return this._shape[0] - }, - set: function(w) { - w = w|0 - reshapeTexture(this, w, this._shape[1]) - return w + } + + //Find left/right neighbors of bottom vertex + var left = -1 + for(var i=0; i<3; ++i) { + var idx = bottom ^ (1< cubeVerts[right][0]) { + right = idx } } -}) -proto.bind = function(unit) { - var gl = this.gl - if(unit !== undefined) { - gl.activeTexture(gl.TEXTURE0 + (unit|0)) + //Determine edge axis coordinates + var cubeEdges = CUBE_EDGES + cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0 + cubeEdges[bits.log2(left^bottom)] = bottom&left + cubeEdges[bits.log2(bottom^right)] = bottom&right + var top = right ^ 7 + if(top === closest || top === farthest) { + top = left ^ 7 + cubeEdges[bits.log2(right^top)] = top&right + } else { + cubeEdges[bits.log2(left^top)] = top&left } - gl.bindTexture(gl.TEXTURE_2D, this.handle) - if(unit !== undefined) { - return (unit|0) + + //Determine visible faces + var axis = CUBE_AXIS + var cutCorner = closest + for(var d=0; d<3; ++d) { + if(cutCorner & (1<0; ++i, l>>>=1) { - if(this._mipLevels.indexOf(i) < 0) { - this._mipLevels.push(i) - } - } -} + //Create grid lines for each axis/direction + var gridOffset = [0,0,0] + var gridCount = [0,0,0] -proto.setPixels = function(data, x_off, y_off, mip_level) { - var gl = this.gl - this.bind() - if(Array.isArray(x_off)) { - mip_level = y_off - y_off = x_off[1]|0 - x_off = x_off[0]|0 - } else { - x_off = x_off || 0 - y_off = y_off || 0 - } - mip_level = mip_level || 0 - if(data instanceof HTMLCanvasElement || - data instanceof ImageData || - data instanceof HTMLImageElement || - data instanceof HTMLVideoElement) { - var needsMip = this._mipLevels.indexOf(mip_level) < 0 - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data) - this._mipLevels.push(mip_level) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data) + //Add zero line + vertices.push( + 0,0,1, 0,1,1, 0,0,-1, + 0,0,-1, 0,1,1, 0,1,-1) + + for(var i=0; i<3; ++i) { + //Axis tick marks + var start = ((vertices.length / 3)|0) + for(var j=0; j this._shape[1]>>>mip_level || - y_off + data.shape[0] > this._shape[0]>>>mip_level || - x_off < 0 || - y_off < 0) { - throw new Error('gl-texture2d: Texture dimensions are out of bounds') + var end = ((vertices.length / 3)|0) + tickOffset[i] = start + tickCount[i] = end - start + + //Grid lines + var start = ((vertices.length / 3)|0) + for(var k=0; k 3) { - throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') - } - var type = 0, format = 0 - var packed = isPacked(shape, array.stride.slice()) - if(dtype === 'float32') { - type = gl.FLOAT - } else if(dtype === 'float64') { - type = gl.FLOAT - packed = false - dtype = 'float32' - } else if(dtype === 'uint8') { - type = gl.UNSIGNED_BYTE - } else { - type = gl.UNSIGNED_BYTE - packed = false - dtype = 'uint8' - } - var channels = 1 - if(shape.length === 2) { - format = gl.LUMINANCE - shape = [shape[0], shape[1], 1] - array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) - } else if(shape.length === 3) { - if(shape[2] === 1) { - format = gl.ALPHA - } else if(shape[2] === 2) { - format = gl.LUMINANCE_ALPHA - } else if(shape[2] === 3) { - format = gl.RGB - } else if(shape[2] === 4) { - format = gl.RGBA - } else { - throw new Error('gl-texture2d: Invalid shape for pixel coords') - } - channels = shape[2] - } else { - throw new Error('gl-texture2d: Invalid shape for texture') - } - //For 1-channel textures allow conversion between formats - if((format === gl.LUMINANCE || format === gl.ALPHA) && - (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { - format = cformat - } - if(format !== cformat) { - throw new Error('gl-texture2d: Incompatible texture format for setPixels') - } - var size = array.size - var needsMip = mipLevels.indexOf(mip_level) < 0 - if(needsMip) { - mipLevels.push(mip_level) - } - if(type === ctype && packed) { - //Array data types are compatible, can directly copy into texture - if(array.offset === 0 && array.data.length === size) { - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) - } - } else { - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) - } - } - } else { - //Need to do type conversion to pack data into buffer - var pack_buffer - if(ctype === gl.FLOAT) { - pack_buffer = pool.mallocFloat32(size) - } else { - pack_buffer = pool.mallocUint8(size) - } - var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) - if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { - convertFloatToUint8(pack_view, array) - } else { - ops.assign(pack_view, array) - } - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) - } - if(ctype === gl.FLOAT) { - pool.freeFloat32(pack_buffer) - } else { - pool.freeUint8(pack_buffer) - } - } +var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}" +var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" +exports.text = function(gl) { + return createShader(gl, textVert, textFrag, null, [ + {name: 'position', type: 'vec3'} + ]) } -function initTexture(gl) { - var tex = gl.createTexture() - gl.bindTexture(gl.TEXTURE_2D, tex) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) - return tex +var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}" +var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}" +exports.bg = function(gl) { + return createShader(gl, bgVert, bgFrag, null, [ + {name: 'position', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) } -function createTextureShape(gl, width, height, format, type) { - var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { - throw new Error('gl-texture2d: Invalid texture shape') - } - if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { - throw new Error('gl-texture2d: Floating point textures not supported on this platform') - } - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) - return new Texture2D(gl, tex, width, height, format, type) +},{"gl-shader":590}],470:[function(require,module,exports){ +(function (process){ +"use strict" + +module.exports = createTextSprites + +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var vectorizeText = require('vectorize-text') +var createShader = require('./shaders').text + +var globals = window || process.global || {} +var __TEXT_CACHE = globals.__TEXT_CACHE || {} +globals.__TEXT_CACHE = {} + +//Vertex buffer format for text is: +// +/// [x,y,z] = Spatial coordinate +// + +var VERTEX_SIZE = 3 +var VERTEX_STRIDE = VERTEX_SIZE * 4 + +function TextSprites( + gl, + shader, + buffer, + vao) { + this.gl = gl + this.shader = shader + this.buffer = buffer + this.vao = vao + this.tickOffset = + this.tickCount = + this.labelOffset = + this.labelCount = null } -function createTextureDOM(gl, element, format, type) { - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element) - return new Texture2D(gl, tex, element.width|0, element.height|0, format, type) +var proto = TextSprites.prototype + +//Bind textures for rendering +var SHAPE = [0,0] +proto.bind = function(model, view, projection, pixelScale) { + this.vao.bind() + this.shader.bind() + var uniforms = this.shader.uniforms + uniforms.model = model + uniforms.view = view + uniforms.projection = projection + uniforms.pixelScale = pixelScale + SHAPE[0] = this.gl.drawingBufferWidth + SHAPE[1] = this.gl.drawingBufferHeight + this.shader.uniforms.resolution = SHAPE } -//Creates a texture from an ndarray -function createTextureArray(gl, array) { - var dtype = array.dtype - var shape = array.shape.slice() - var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { - throw new Error('gl-texture2d: Invalid texture size') - } - var packed = isPacked(shape, array.stride.slice()) - var type = 0 - if(dtype === 'float32') { - type = gl.FLOAT - } else if(dtype === 'float64') { - type = gl.FLOAT - packed = false - dtype = 'float32' - } else if(dtype === 'uint8') { - type = gl.UNSIGNED_BYTE - } else { - type = gl.UNSIGNED_BYTE - packed = false - dtype = 'uint8' - } - var format = 0 - if(shape.length === 2) { - format = gl.LUMINANCE - shape = [shape[0], shape[1], 1] - array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) - } else if(shape.length === 3) { - if(shape[2] === 1) { - format = gl.ALPHA - } else if(shape[2] === 2) { - format = gl.LUMINANCE_ALPHA - } else if(shape[2] === 3) { - format = gl.RGB - } else if(shape[2] === 4) { - format = gl.RGBA - } else { - throw new Error('gl-texture2d: Invalid shape for pixel coords') +proto.update = function(bounds, labels, labelFont, ticks, tickFont) { + var gl = this.gl + var data = [] + + function addItem(t, text, font, size) { + var fontcache = __TEXT_CACHE[font] + if(!fontcache) { + fontcache = __TEXT_CACHE[font] = {} } - } else { - throw new Error('gl-texture2d: Invalid shape for texture') - } - if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { - type = gl.UNSIGNED_BYTE - packed = false - } - var buffer, buf_store - var size = array.size - if(!packed) { - var stride = [shape[2], shape[2]*shape[0], 1] - buf_store = pool.malloc(size, dtype) - var buf_array = ndarray(buf_store, shape, stride, 0) - if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { - convertFloatToUint8(buf_array, array) - } else { - ops.assign(buf_array, array) + var mesh = fontcache[text] + if(!mesh) { + mesh = fontcache[text] = tryVectorizeText(text, { + triangles: true, + font: font, + textAlign: 'center', + textBaseline: 'middle' + }) } - buffer = buf_store.subarray(0, size) - } else if (array.offset === 0 && array.data.length === size) { - buffer = array.data - } else { - buffer = array.data.subarray(array.offset, array.offset + size) - } - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) - if(!packed) { - pool.free(buf_store) - } - return new Texture2D(gl, tex, shape[0], shape[1], format, type) -} - -function createTexture2D(gl) { - if(arguments.length <= 1) { - throw new Error('gl-texture2d: Missing arguments for texture2d constructor') - } - if(!linearTypes) { - lazyInitLinearTypes(gl) - } - if(typeof arguments[1] === 'number') { - return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) - } - if(Array.isArray(arguments[1])) { - return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) - } - if(typeof arguments[1] === 'object') { - var obj = arguments[1] - if(obj instanceof HTMLCanvasElement || - obj instanceof HTMLImageElement || - obj instanceof HTMLVideoElement || - obj instanceof ImageData) { - return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) - } else if(obj.shape && obj.data && obj.stride) { - return createTextureArray(gl, obj) + var scale = (size || 12) / 12 + var positions = mesh.positions + var cells = mesh.cells + var lo = [ Infinity, Infinity] + var hi = [-Infinity,-Infinity] + for(var i=0, nc=cells.length; i=0; --j) { + var p = positions[c[j]] + data.push(scale*p[0], -scale*p[1], t) + } } } - throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') -} -},{"ndarray":253,"ndarray-ops":252,"typedarray-pool":278}],223:[function(require,module,exports){ -"use strict" + //Generate sprites for all 3 axes, store data in texture atlases + var tickOffset = [0,0,0] + var tickCount = [0,0,0] + var labelOffset = [0,0,0] + var labelCount = [0,0,0] + for(var d=0; d<3; ++d) { -function doBind(gl, elements, attributes) { - if(elements) { - elements.bind() - } else { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) - } - var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0 - if(attributes) { - if(attributes.length > nattribs) { - throw new Error("gl-vao: Too many vertex attributes") - } - for(var i=0; i= 0) { + sigFigs = stepStr.length - u - 1 + } + var shift = Math.pow(10, sigFigs) + var x = Math.round(spacing * i * shift) + var xstr = x + "" + if(xstr.indexOf("e") >= 0) { + return xstr + } + var xi = x / shift, xf = x % shift + if(x < 0) { + xi = -Math.ceil(xi)|0 + xf = (-xf)|0 + } else { + xi = Math.floor(xi)|0 + xf = xf|0 + } + var xis = "" + xi + if(x < 0) { + xis = "-" + xis + } + if(sigFigs) { + var xs = "" + xf + while(xs.length < sigFigs) { + xs = "0" + xs } + return xis + "." + xs + } else { + return xis } - this._useElements = !!elements - this._elementsType = elementsType || this.gl.UNSIGNED_SHORT } -VAONative.prototype.draw = function(mode, count, offset) { - offset = offset || 0 - var gl = this.gl - if(this._useElements) { - gl.drawElements(mode, count, this._elementsType, offset) - } else { - gl.drawArrays(mode, offset, count) +function defaultTicks(bounds, tickSpacing) { + var array = [] + for(var d=0; d<3; ++d) { + var ticks = [] + var m = 0.5*(bounds[0][d]+bounds[1][d]) + for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) { + ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) + } + for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) { + ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) + } + array.push(ticks) } + return array } -function createVAONative(gl, ext) { - return new VAONative(gl, ext, ext.createVertexArrayOES()) +function ticksEqual(ticksA, ticksB) { + for(var i=0; i<3; ++i) { + if(ticksA[i].length !== ticksB[i].length) { + return false + } + for(var j=0; j 1.0) { + t = 1.0 + } + var ti = 1.0 - t + var n = a.length + var r = new Array(n) + for(var i=0; i 0) || (a > 0 && b < 0)) { + var p = lerpW(s, b, t, a) + pos.push(p) + neg.push(p.slice()) + } + if(b < 0) { + neg.push(t.slice()) + } else if(b > 0) { + pos.push(t.slice()) + } else { + pos.push(t.slice()) + neg.push(t.slice()) + } + a = b + } + return { positive: pos, negative: neg } +} + +function positive(points, plane) { + var pos = [] + var a = planeT(points[points.length-1], plane) + for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { + pos.push(lerpW(s, b, t, a)) + } + if(b >= 0) { + pos.push(t.slice()) + } + a = b } + return pos +} - function token(data) { - if (data.length) { - tokens.push({ - type: map[mode] - , data: data - , position: start - , line: line - , column: col - }) +function negative(points, plane) { + var neg = [] + var a = planeT(points[points.length-1], plane) + for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { + neg.push(lerpW(s, b, t, a)) + } + if(b <= 0) { + neg.push(t.slice()) + } + a = b + } + return neg +} +},{"robust-dot-product":483,"robust-sum":485}],483:[function(require,module,exports){ +"use strict" + +var twoProduct = require("two-product") +var robustSum = require("robust-sum") + +module.exports = robustDotProduct + +function robustDotProduct(a, b) { + var r = twoProduct(a[0], b[0]) + for(var i=1; i_inline_4_arg0_||255>_inline_4_arg1_||255>_inline_4_arg2_||255>_inline_4_arg3_){var _inline_4_l=_inline_4_arg4_-_inline_4_arg6_[0],_inline_4_a=_inline_4_arg5_-_inline_4_arg6_[1],_inline_4_f=_inline_4_l*_inline_4_l+_inline_4_a*_inline_4_a;_inline_4_f this.buffer.length) { + pool.free(this.buffer) + var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) + for(var i=0; i 0) continue - res = buf.slice(0, 1).join('') - } +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders/index') - token(res) +module.exports = createSpikes - start += res.length - content = content.slice(res.length) - return content.length - } while(1) - } +var identity = [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] - function hex() { - if(/[^a-fA-F0-9]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } +function AxisSpikes(gl, buffer, vao, shader) { + this.gl = gl + this.buffer = buffer + this.vao = vao + this.shader = shader + this.pixelRatio = 1 + this.bounds = [[-1000,-1000,-1000], [1000,1000,1000]] + this.position = [0,0,0] + this.lineWidth = [2,2,2] + this.colors = [[0,0,0,1], [0,0,0,1], [0,0,0,1]] + this.enabled = [true,true,true] + this.drawSides = [true,true,true] + this.axes = null +} - content.push(c) - last = c - return i + 1 - } +var proto = AxisSpikes.prototype - function integer() { - if(c === '.') { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } +var OUTER_FACE = [0,0,0] +var INNER_FACE = [0,0,0] - if(/[eE]/.test(c)) { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } +var SHAPE = [0,0] - if(c === 'x' && content.length === 1 && content[0] === '0') { - mode = HEX - content.push(c) - last = c - return i + 1 - } +proto.isTransparent = function() { + return false +} - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } +proto.drawTransparent = function(camera) {} - content.push(c) - last = c - return i + 1 - } +proto.draw = function(camera) { + var gl = this.gl + var vao = this.vao + var shader = this.shader - function decimal() { - if(c === 'f') { - content.push(c) - last = c - i += 1 - } + vao.bind() + shader.bind() - if(/[eE]/.test(c)) { - content.push(c) - last = c - return i + 1 - } + var model = camera.model || identity + var view = camera.view || identity + var projection = camera.projection || identity - if (c === '-' && /[eE]/.test(last)) { - content.push(c) - last = c - return i + 1 - } + var axis + if(this.axes) { + axis = this.axes.lastCubeProps.axis + } - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i + var outerFace = OUTER_FACE + var innerFace = INNER_FACE + for(var i=0; i<3; ++i) { + if(axis && axis[i] < 0) { + outerFace[i] = this.bounds[0][i] + innerFace[i] = this.bounds[1][i] + } else { + outerFace[i] = this.bounds[1][i] + innerFace[i] = this.bounds[0][i] } - - content.push(c) - last = c - return i + 1 } - function readtoken() { - if(/[^\d\w_]/.test(c)) { - var contentstr = content.join('') - if(allLiterals.indexOf(contentstr) > -1) { - mode = KEYWORD - } else if(allBuiltins.indexOf(contentstr) > -1) { - mode = BUILTIN - } else { - mode = IDENT + SHAPE[0] = gl.drawingBufferWidth + SHAPE[1] = gl.drawingBufferHeight + + shader.uniforms.model = model + shader.uniforms.view = view + shader.uniforms.projection = projection + shader.uniforms.coordinates = [this.position, outerFace, innerFace] + shader.uniforms.colors = this.colors + shader.uniforms.screenShape = SHAPE + + for(var i=0; i<3; ++i) { + shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio + if(this.enabled[i]) { + vao.draw(gl.TRIANGLES, 6, 6*i) + if(this.drawSides[i]) { + vao.draw(gl.TRIANGLES, 12, 18+12*i) } - token(content.join('')) - mode = NORMAL - return i } - content.push(c) - last = c - return i + 1 + } + + vao.unbind() +} + +proto.update = function(options) { + if(!options) { + return + } + if("bounds" in options) { + this.bounds = options.bounds + } + if("position" in options) { + this.position = options.position + } + if("lineWidth" in options) { + this.lineWidth = options.lineWidth + } + if("colors" in options) { + this.colors = options.colors + } + if("enabled" in options) { + this.enabled = options.enabled + } + if("drawSides" in options) { + this.drawSides = options.drawSides } } -},{"./lib/builtins":230,"./lib/builtins-300es":229,"./lib/literals":232,"./lib/literals-300es":231,"./lib/operators":233}],229:[function(require,module,exports){ -// 300es builtins/reserved words that were previously valid in v100 -var v100 = require('./builtins') - -// The texture2D|Cube functions have been removed -// And the gl_ features are updated -v100 = v100.slice().filter(function (b) { - return !/^(gl\_|texture)/.test(b) -}) +proto.dispose = function() { + this.vao.dispose() + this.buffer.dispose() + this.shader.dispose() +} -module.exports = v100.concat([ - // the updated gl_ constants - 'gl_VertexID' - , 'gl_InstanceID' - , 'gl_Position' - , 'gl_PointSize' - , 'gl_FragCoord' - , 'gl_FrontFacing' - , 'gl_FragDepth' - , 'gl_PointCoord' - , 'gl_MaxVertexAttribs' - , 'gl_MaxVertexUniformVectors' - , 'gl_MaxVertexOutputVectors' - , 'gl_MaxFragmentInputVectors' - , 'gl_MaxVertexTextureImageUnits' - , 'gl_MaxCombinedTextureImageUnits' - , 'gl_MaxTextureImageUnits' - , 'gl_MaxFragmentUniformVectors' - , 'gl_MaxDrawBuffers' - , 'gl_MinProgramTexelOffset' - , 'gl_MaxProgramTexelOffset' - , 'gl_DepthRangeParameters' - , 'gl_DepthRange' - // other builtins - , 'trunc' - , 'round' - , 'roundEven' - , 'isnan' - , 'isinf' - , 'floatBitsToInt' - , 'floatBitsToUint' - , 'intBitsToFloat' - , 'uintBitsToFloat' - , 'packSnorm2x16' - , 'unpackSnorm2x16' - , 'packUnorm2x16' - , 'unpackUnorm2x16' - , 'packHalf2x16' - , 'unpackHalf2x16' - , 'outerProduct' - , 'transpose' - , 'determinant' - , 'inverse' - , 'texture' - , 'textureSize' - , 'textureProj' - , 'textureLod' - , 'textureOffset' - , 'texelFetch' - , 'texelFetchOffset' - , 'textureProjOffset' - , 'textureLodOffset' - , 'textureProjLod' - , 'textureProjLodOffset' - , 'textureGrad' - , 'textureGradOffset' - , 'textureProjGrad' - , 'textureProjGradOffset' -]) -},{"./builtins":230}],230:[function(require,module,exports){ -module.exports = [ - // Keep this list sorted - 'abs' - , 'acos' - , 'all' - , 'any' - , 'asin' - , 'atan' - , 'ceil' - , 'clamp' - , 'cos' - , 'cross' - , 'dFdx' - , 'dFdy' - , 'degrees' - , 'distance' - , 'dot' - , 'equal' - , 'exp' - , 'exp2' - , 'faceforward' - , 'floor' - , 'fract' - , 'gl_BackColor' - , 'gl_BackLightModelProduct' - , 'gl_BackLightProduct' - , 'gl_BackMaterial' - , 'gl_BackSecondaryColor' - , 'gl_ClipPlane' - , 'gl_ClipVertex' - , 'gl_Color' - , 'gl_DepthRange' - , 'gl_DepthRangeParameters' - , 'gl_EyePlaneQ' - , 'gl_EyePlaneR' - , 'gl_EyePlaneS' - , 'gl_EyePlaneT' - , 'gl_Fog' - , 'gl_FogCoord' - , 'gl_FogFragCoord' - , 'gl_FogParameters' - , 'gl_FragColor' - , 'gl_FragCoord' - , 'gl_FragData' - , 'gl_FragDepth' - , 'gl_FragDepthEXT' - , 'gl_FrontColor' - , 'gl_FrontFacing' - , 'gl_FrontLightModelProduct' - , 'gl_FrontLightProduct' - , 'gl_FrontMaterial' - , 'gl_FrontSecondaryColor' - , 'gl_LightModel' - , 'gl_LightModelParameters' - , 'gl_LightModelProducts' - , 'gl_LightProducts' - , 'gl_LightSource' - , 'gl_LightSourceParameters' - , 'gl_MaterialParameters' - , 'gl_MaxClipPlanes' - , 'gl_MaxCombinedTextureImageUnits' - , 'gl_MaxDrawBuffers' - , 'gl_MaxFragmentUniformComponents' - , 'gl_MaxLights' - , 'gl_MaxTextureCoords' - , 'gl_MaxTextureImageUnits' - , 'gl_MaxTextureUnits' - , 'gl_MaxVaryingFloats' - , 'gl_MaxVertexAttribs' - , 'gl_MaxVertexTextureImageUnits' - , 'gl_MaxVertexUniformComponents' - , 'gl_ModelViewMatrix' - , 'gl_ModelViewMatrixInverse' - , 'gl_ModelViewMatrixInverseTranspose' - , 'gl_ModelViewMatrixTranspose' - , 'gl_ModelViewProjectionMatrix' - , 'gl_ModelViewProjectionMatrixInverse' - , 'gl_ModelViewProjectionMatrixInverseTranspose' - , 'gl_ModelViewProjectionMatrixTranspose' - , 'gl_MultiTexCoord0' - , 'gl_MultiTexCoord1' - , 'gl_MultiTexCoord2' - , 'gl_MultiTexCoord3' - , 'gl_MultiTexCoord4' - , 'gl_MultiTexCoord5' - , 'gl_MultiTexCoord6' - , 'gl_MultiTexCoord7' - , 'gl_Normal' - , 'gl_NormalMatrix' - , 'gl_NormalScale' - , 'gl_ObjectPlaneQ' - , 'gl_ObjectPlaneR' - , 'gl_ObjectPlaneS' - , 'gl_ObjectPlaneT' - , 'gl_Point' - , 'gl_PointCoord' - , 'gl_PointParameters' - , 'gl_PointSize' - , 'gl_Position' - , 'gl_ProjectionMatrix' - , 'gl_ProjectionMatrixInverse' - , 'gl_ProjectionMatrixInverseTranspose' - , 'gl_ProjectionMatrixTranspose' - , 'gl_SecondaryColor' - , 'gl_TexCoord' - , 'gl_TextureEnvColor' - , 'gl_TextureMatrix' - , 'gl_TextureMatrixInverse' - , 'gl_TextureMatrixInverseTranspose' - , 'gl_TextureMatrixTranspose' - , 'gl_Vertex' - , 'greaterThan' - , 'greaterThanEqual' - , 'inversesqrt' - , 'length' - , 'lessThan' - , 'lessThanEqual' - , 'log' - , 'log2' - , 'matrixCompMult' - , 'max' - , 'min' - , 'mix' - , 'mod' - , 'normalize' - , 'not' - , 'notEqual' - , 'pow' - , 'radians' - , 'reflect' - , 'refract' - , 'sign' - , 'sin' - , 'smoothstep' - , 'sqrt' - , 'step' - , 'tan' - , 'texture2D' - , 'texture2DLod' - , 'texture2DProj' - , 'texture2DProjLod' - , 'textureCube' - , 'textureCubeLod' - , 'texture2DLodEXT' - , 'texture2DProjLodEXT' - , 'textureCubeLodEXT' - , 'texture2DGradEXT' - , 'texture2DProjGradEXT' - , 'textureCubeGradEXT' -] +function createSpikes(gl, options) { + //Create buffers + var data = [ ] -},{}],231:[function(require,module,exports){ -var v100 = require('./literals') + function line(x,y,z,i,l,h) { + var row = [x,y,z, 0,0,0, 1] + row[i+3] = 1 + row[i] = l + data.push.apply(data, row) + row[6] = -1 + data.push.apply(data, row) + row[i] = h + data.push.apply(data, row) + data.push.apply(data, row) + row[6] = 1 + data.push.apply(data, row) + row[i] = l + data.push.apply(data, row) + } -module.exports = v100.slice().concat([ - 'layout' - , 'centroid' - , 'smooth' - , 'case' - , 'mat2x2' - , 'mat2x3' - , 'mat2x4' - , 'mat3x2' - , 'mat3x3' - , 'mat3x4' - , 'mat4x2' - , 'mat4x3' - , 'mat4x4' - , 'uint' - , 'uvec2' - , 'uvec3' - , 'uvec4' - , 'samplerCubeShadow' - , 'sampler2DArray' - , 'sampler2DArrayShadow' - , 'isampler2D' - , 'isampler3D' - , 'isamplerCube' - , 'isampler2DArray' - , 'usampler2D' - , 'usampler3D' - , 'usamplerCube' - , 'usampler2DArray' - , 'coherent' - , 'restrict' - , 'readonly' - , 'writeonly' - , 'resource' - , 'atomic_uint' - , 'noperspective' - , 'patch' - , 'sample' - , 'subroutine' - , 'common' - , 'partition' - , 'active' - , 'filter' - , 'image1D' - , 'image2D' - , 'image3D' - , 'imageCube' - , 'iimage1D' - , 'iimage2D' - , 'iimage3D' - , 'iimageCube' - , 'uimage1D' - , 'uimage2D' - , 'uimage3D' - , 'uimageCube' - , 'image1DArray' - , 'image2DArray' - , 'iimage1DArray' - , 'iimage2DArray' - , 'uimage1DArray' - , 'uimage2DArray' - , 'image1DShadow' - , 'image2DShadow' - , 'image1DArrayShadow' - , 'image2DArrayShadow' - , 'imageBuffer' - , 'iimageBuffer' - , 'uimageBuffer' - , 'sampler1DArray' - , 'sampler1DArrayShadow' - , 'isampler1D' - , 'isampler1DArray' - , 'usampler1D' - , 'usampler1DArray' - , 'isampler2DRect' - , 'usampler2DRect' - , 'samplerBuffer' - , 'isamplerBuffer' - , 'usamplerBuffer' - , 'sampler2DMS' - , 'isampler2DMS' - , 'usampler2DMS' - , 'sampler2DMSArray' - , 'isampler2DMSArray' - , 'usampler2DMSArray' -]) + line(0,0,0, 0, 0, 1) + line(0,0,0, 1, 0, 1) + line(0,0,0, 2, 0, 1) -},{"./literals":232}],232:[function(require,module,exports){ -module.exports = [ - // current - 'precision' - , 'highp' - , 'mediump' - , 'lowp' - , 'attribute' - , 'const' - , 'uniform' - , 'varying' - , 'break' - , 'continue' - , 'do' - , 'for' - , 'while' - , 'if' - , 'else' - , 'in' - , 'out' - , 'inout' - , 'float' - , 'int' - , 'void' - , 'bool' - , 'true' - , 'false' - , 'discard' - , 'return' - , 'mat2' - , 'mat3' - , 'mat4' - , 'vec2' - , 'vec3' - , 'vec4' - , 'ivec2' - , 'ivec3' - , 'ivec4' - , 'bvec2' - , 'bvec3' - , 'bvec4' - , 'sampler1D' - , 'sampler2D' - , 'sampler3D' - , 'samplerCube' - , 'sampler1DShadow' - , 'sampler2DShadow' - , 'struct' + line(1,0,0, 1, -1,1) + line(1,0,0, 2, -1,1) - // future - , 'asm' - , 'class' - , 'union' - , 'enum' - , 'typedef' - , 'template' - , 'this' - , 'packed' - , 'goto' - , 'switch' - , 'default' - , 'inline' - , 'noinline' - , 'volatile' - , 'public' - , 'static' - , 'extern' - , 'external' - , 'interface' - , 'long' - , 'short' - , 'double' - , 'half' - , 'fixed' - , 'unsigned' - , 'input' - , 'output' - , 'hvec2' - , 'hvec3' - , 'hvec4' - , 'dvec2' - , 'dvec3' - , 'dvec4' - , 'fvec2' - , 'fvec3' - , 'fvec4' - , 'sampler2DRect' - , 'sampler3DRect' - , 'sampler2DRectShadow' - , 'sizeof' - , 'cast' - , 'namespace' - , 'using' -] + line(0,1,0, 0, -1,1) + line(0,1,0, 2, -1,1) -},{}],233:[function(require,module,exports){ -module.exports = [ - '<<=' - , '>>=' - , '++' - , '--' - , '<<' - , '>>' - , '<=' - , '>=' - , '==' - , '!=' - , '&&' - , '||' - , '+=' - , '-=' - , '*=' - , '/=' - , '%=' - , '&=' - , '^^' - , '^=' - , '|=' - , '(' - , ')' - , '[' - , ']' - , '.' - , '!' - , '~' - , '*' - , '/' - , '%' - , '+' - , '-' - , '<' - , '>' - , '&' - , '^' - , '|' - , '?' - , ':' - , '=' - , ',' - , ';' - , '{' - , '}' -] + line(0,0,1, 0, -1,1) + line(0,0,1, 1, -1,1) -},{}],234:[function(require,module,exports){ -var tokenize = require('./index') + var buffer = createBuffer(gl, data) + var vao = createVAO(gl, [{ + type: gl.FLOAT, + buffer: buffer, + size: 3, + offset: 0, + stride: 28 + }, { + type: gl.FLOAT, + buffer: buffer, + size: 3, + offset: 12, + stride: 28 + }, { + type: gl.FLOAT, + buffer: buffer, + size: 1, + offset: 24, + stride: 28 + }]) -module.exports = tokenizeString + //Create shader + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.color.location = 1 + shader.attributes.weight.location = 2 -function tokenizeString(str, opt) { - var generator = tokenize(opt) - var tokens = [] + //Create spike object + var spikes = new AxisSpikes(gl, buffer, vao, shader) - tokens = tokens.concat(generator(str)) - tokens = tokens.concat(generator(null)) + //Set parameters + spikes.update(options) - return tokens + //Return resulting object + return spikes } -},{"./index":228}],235:[function(require,module,exports){ -"use strict" - -//High level idea: -// 1. Use Clarkson's incremental construction to find convex hull -// 2. Point location in triangulation by jump and walk +},{"./shaders/index":624,"gl-buffer":616,"gl-vao":623}],626:[function(require,module,exports){ +'use strict' -module.exports = incrementalConvexHull +module.exports = createScene -var orient = require("robust-orientation") -var compareCell = require("simplicial-complex").compareCells +var createCamera = require('3d-view-controls') +var createAxes = require('gl-axes3d') +var axesRanges = require('gl-axes3d/properties') +var createSpikes = require('gl-spikes3d') +var createSelect = require('gl-select-static') +var createFBO = require('gl-fbo') +var drawTriangle = require('a-big-triangle') +var mouseChange = require('mouse-change') +var perspective = require('gl-mat4/perspective') +var createShader = require('./lib/shader') -function compareInt(a, b) { - return a - b +function MouseSelect() { + this.mouse = [-1,-1] + this.screen = null + this.distance = Infinity + this.index = null + this.dataCoordinate = null + this.dataPosition = null + this.object = null + this.data = null } -function Simplex(vertices, adjacent, boundary) { - this.vertices = vertices - this.adjacent = adjacent - this.boundary = boundary - this.lastVisited = -1 +function getContext(canvas, options) { + var gl = null + try { + gl = canvas.getContext('webgl', options) + if(!gl) { + gl = canvas.getContext('experimental-webgl', options) + } + } catch(e) { + return null + } + return gl } -Simplex.prototype.flip = function() { - var t = this.vertices[0] - this.vertices[0] = this.vertices[1] - this.vertices[1] = t - var u = this.adjacent[0] - this.adjacent[0] = this.adjacent[1] - this.adjacent[1] = u +function roundUpPow10(x) { + var y = Math.round(Math.log(Math.abs(x)) / Math.log(10)) + if(y < 0) { + var base = Math.round(Math.pow(10, -y)) + return Math.ceil(x*base) / base + } else if(y > 0) { + var base = Math.round(Math.pow(10, y)) + return Math.ceil(x/base) * base + } + return Math.ceil(x) } -function GlueFacet(vertices, cell, index) { - this.vertices = vertices - this.cell = cell - this.index = index +function defaultBool(x) { + if(typeof x === 'boolean') { + return x + } + return true } -function compareGlue(a, b) { - return compareCell(a.vertices, b.vertices) -} +function createScene(options) { + options = options || {} -function bakeOrient(d) { - var code = ["function orient(){var tuple=this.tuple;return test("] - for(var i=0; i<=d; ++i) { - if(i > 0) { - code.push(",") + var stopped = false + + var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio) + + var canvas = options.canvas + if(!canvas) { + canvas = document.createElement('canvas') + if(options.container) { + var container = options.container + container.appendChild(canvas) + } else { + document.body.appendChild(canvas) } - code.push("tuple[", i, "]") } - code.push(")}return orient") - var proc = new Function("test", code.join("")) - var test = orient[d+1] - if(!test) { - test = orient + + var gl = options.gl + if(!gl) { + gl = getContext(canvas, + options.glOptions || { + premultipliedAlpha: true, + antialias: true + }) + } + if(!gl) { + throw new Error('webgl not supported') } - return proc(test) -} -var BAKED = [] + //Initial bounds + var bounds = options.bounds || [[-10,-10,-10], [10,10,10]] -function Triangulation(dimension, vertices, simplices) { - this.dimension = dimension - this.vertices = vertices - this.simplices = simplices - this.interior = simplices.filter(function(c) { - return !c.boundary - }) + //Create selection + var selection = new MouseSelect() - this.tuple = new Array(dimension+1) - for(var i=0; i<=dimension; ++i) { - this.tuple[i] = this.vertices[i] + //Accumulation buffer + var accumBuffer = createFBO(gl, + [gl.drawingBufferWidth, gl.drawingBufferHeight], { + preferFloat: true + }) + + var accumShader = createShader(gl) + + //Create a camera + var cameraOptions = options.camera || { + eye: [2,0,0], + center: [0,0,0], + up: [0,1,0], + zoomMin: 0.1, + zoomMax: 100, + mode: 'turntable' } - var o = BAKED[dimension] - if(!o) { - o = BAKED[dimension] = bakeOrient(dimension) + //Create axes + var axesOptions = options.axes || {} + var axes = createAxes(gl, axesOptions) + axes.enable = !axesOptions.disable + + //Create spikes + var spikeOptions = options.spikes || {} + var spikes = createSpikes(gl, spikeOptions) + + //Object list is empty initially + var objects = [] + var pickBufferIds = [] + var pickBufferCount = [] + var pickBuffers = [] + + //Dirty flag, skip redraw if scene static + var dirty = true + var pickDirty = true + + var projection = new Array(16) + var model = new Array(16) + + var cameraParams = { + view: null, + projection: projection, + model: model } - this.orient = o -} -var proto = Triangulation.prototype + var pickDirty = true -//Degenerate situation where we are on boundary, but coplanar to face -proto.handleBoundaryDegeneracy = function(cell, point) { - var d = this.dimension - var n = this.vertices.length - 1 - var tuple = this.tuple - var verts = this.vertices + var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ] - //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate - var toVisit = [ cell ] - cell.lastVisited = -n - while(toVisit.length > 0) { - cell = toVisit.pop() - var cellVerts = cell.vertices - var cellAdj = cell.adjacent - for(var i=0; i<=d; ++i) { - var neighbor = cellAdj[i] - if(!neighbor.boundary || neighbor.lastVisited <= -n) { + //Create scene object + var scene = { + gl: gl, + contextLost: false, + pixelRatio: options.pixelRatio || parseFloat(window.devicePixelRatio), + canvas: canvas, + selection: selection, + camera: createCamera(canvas, cameraOptions), + axes: axes, + axesPixels: null, + spikes: spikes, + bounds: bounds, + objects: objects, + shape: viewShape, + aspect: options.aspectRatio || [1,1,1], + pickRadius: options.pickRadius || 10, + zNear: options.zNear || 0.01, + zFar: options.zFar || 1000, + fovy: options.fovy || Math.PI/4, + clearColor: options.clearColor || [0,0,0,0], + autoResize: defaultBool(options.autoResize), + autoBounds: defaultBool(options.autoBounds), + autoScale: !!options.autoScale, + autoCenter: defaultBool(options.autoCenter), + clipToBounds: defaultBool(options.clipToBounds), + snapToData: !!options.snapToData, + onselect: options.onselect || null, + onrender: options.onrender || null, + onclick: options.onclick || null, + cameraParams: cameraParams, + oncontextloss: null, + mouseListener: null + } + + var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ] + + function resizeListener() { + if(stopped) { + return + } + if(!scene.autoResize) { + return + } + var parent = canvas.parentNode + var width = 1 + var height = 1 + if(parent && parent !== document.body) { + width = parent.clientWidth + height = parent.clientHeight + } else { + width = window.innerWidth + height = window.innerHeight + } + var nextWidth = Math.ceil(width * scene.pixelRatio)|0 + var nextHeight = Math.ceil(height * scene.pixelRatio)|0 + if(nextWidth !== canvas.width || nextHeight !== canvas.height) { + canvas.width = nextWidth + canvas.height = nextHeight + var style = canvas.style + style.position = style.position || 'absolute' + style.left = '0px' + style.top = '0px' + style.width = width + 'px' + style.height = height + 'px' + dirty = true + } + } + if(scene.autoResize) { + resizeListener() + } + window.addEventListener('resize', resizeListener) + + function reallocPickIds() { + var numObjs = objects.length + var numPick = pickBuffers.length + for(var i=0; i 0) { - return neighbor - } - neighbor.lastVisited = -n - if(o === 0) { - toVisit.push(neighbor) - } + //Create new pick buffer + var nbuffer = createSelect(gl, viewShape) + pickBufferIds[i] = numPick + pickBuffers.push(nbuffer) + pickBufferCount.push(pickCount) + obj.setPickBase(1) + numPick += 1 + } + while(numPick > 0 && pickBufferCount[numPick-1] === 0) { + pickBufferCount.pop() + pickBuffers.pop().dispose() } } - return null -} -proto.walk = function(point, random) { - //Alias local properties - var n = this.vertices.length - 1 - var d = this.dimension - var verts = this.vertices - var tuple = this.tuple + scene.update = function(options) { + if(stopped) { + return + } + options = options || {} + dirty = true + pickDirty = true + } - //Compute initial jump cell - var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1) - var cell = this.interior[ initIndex ] + scene.add = function(obj) { + if(stopped) { + return + } + obj.axes = axes + objects.push(obj) + pickBufferIds.push(-1) + dirty = true + pickDirty = true + reallocPickIds() + } - //Start walking -outerLoop: - while(!cell.boundary) { - var cellVerts = cell.vertices - var cellAdj = cell.adjacent + scene.remove = function(obj) { + if(stopped) { + return + } + var idx = objects.indexOf(obj) + if(idx < 0) { + return + } + objects.splice(idx, 1) + pickBufferIds.pop() + dirty = true + pickDirty = true + reallocPickIds() + } - for(var i=0; i<=d; ++i) { - tuple[i] = verts[cellVerts[i]] + scene.dispose = function() { + if(stopped) { + return } - cell.lastVisited = n - //Find farthest adjacent cell - for(var i=0; i<=d; ++i) { - var neighbor = cellAdj[i] - if(neighbor.lastVisited >= n) { - continue - } - var prev = tuple[i] - tuple[i] = point - var o = this.orient() - tuple[i] = prev - if(o < 0) { - cell = neighbor - continue outerLoop - } else { - if(!neighbor.boundary) { - neighbor.lastVisited = n - } else { - neighbor.lastVisited = -n - } - } + stopped = true + + window.removeEventListener('resize', resizeListener) + canvas.removeEventListener('webglcontextlost', checkContextLoss) + scene.mouseListener.enabled = false + + if(scene.contextLost) { + return } - return - } - return cell -} + //Destroy objects + axes.dispose() + spikes.dispose() + for(var i=0; i 0) { - //Pop off peak and walk over adjacent cells - var cell = tovisit.pop() - var cellVerts = cell.vertices - var cellAdj = cell.adjacent - var indexOfN = cellVerts.indexOf(n) - if(indexOfN < 0) { - continue + var prevButtons = 0 + + scene.mouseListener = mouseChange(canvas, function(buttons, x, y) { + if(stopped) { + return } - for(var i=0; i<=d; ++i) { - if(i === indexOfN) { - continue - } + var numPick = pickBuffers.length + var numObjs = objects.length + var prevObj = selection.object - //For each boundary neighbor of the cell - var neighbor = cellAdj[i] - if(!neighbor.boundary || neighbor.lastVisited >= n) { - continue - } + selection.distance = Infinity + selection.mouse[0] = x + selection.mouse[1] = y + selection.object = null + selection.screen = null + selection.dataCoordinate = selection.dataPosition = null - var nv = neighbor.vertices + var change = false - //Test if neighbor is a peak - if(neighbor.lastVisited !== -n) { - //Compute orientation of p relative to each boundary peak - var indexOfNeg1 = 0 - for(var j=0; j<=d; ++j) { - if(nv[j] < 0) { - indexOfNeg1 = j - tuple[j] = point - } else { - tuple[j] = verts[nv[j]] + if(buttons && prevButtons) { + mouseRotating = true + } else { + if(mouseRotating) { + pickDirty = true + } + mouseRotating = false + + for(var i=0; i selection.distance) { + continue + } + for(var j=0; j 0) { - nv[indexOfNeg1] = n - neighbor.boundary = false - interior.push(neighbor) - tovisit.push(neighbor) - neighbor.lastVisited = n - continue - } else { - neighbor.lastVisited = -n - } + if(prevObj && prevObj !== selection.object) { + if(prevObj.highlight) { + prevObj.highlight(null) + } + dirty = true + } + if(selection.object) { + if(selection.object.highlight) { + selection.object.highlight(selection.data) } + dirty = true + } - var na = neighbor.adjacent + change = change || (selection.object !== prevObj) + if(change && scene.onselect) { + scene.onselect(selection) + } - //Otherwise, replace neighbor with new face - var vverts = cellVerts.slice() - var vadj = cellAdj.slice() - var ncell = new Simplex(vverts, vadj, true) - simplices.push(ncell) + if((buttons & 1) && !(prevButtons & 1) && scene.onclick) { + scene.onclick(selection) + } + prevButtons = buttons + }) - //Connect to neighbor - var opposite = na.indexOf(cell) - if(opposite < 0) { - continue + function checkContextLoss() { + if(scene.contextLost) { + return true + } + if(gl.isContextLost()) { + scene.contextLost = true + scene.mouseListener.enabled = false + scene.selection.object = null + if(scene.oncontextloss) { + scene.oncontextloss() } - na[opposite] = ncell - vadj[indexOfN] = neighbor + } + } - //Connect to cell - vverts[i] = -1 - vadj[i] = cell - cellAdj[i] = ncell + canvas.addEventListener('webglcontextlost', checkContextLoss) - //Flip facet - ncell.flip() + //Render the scene for mouse picking + function renderPick() { + if(checkContextLoss()) { + return + } - //Add to glue list - for(var j=0; j<=d; ++j) { - var uu = vverts[j] - if(uu < 0 || uu === n) { + gl.colorMask(true, true, true, true) + gl.depthMask(true) + gl.disable(gl.BLEND) + gl.enable(gl.DEPTH_TEST) + + var numObjs = objects.length + var numPick = pickBuffers.length + for(var j=0; j= 0) { - bcell[ptr++] = cv[j] - } else { - parity = j&1 + dirty = dirty || !!obj.dirty + pickDirty = pickDirty || !!obj.dirty + var obb = obj.bounds + if(obb) { + var olo = obb[0] + var ohi = obb[1] + for(var j=0; j<3; ++j) { + lo[j] = Math.min(lo[j], olo[j]) + hi[j] = Math.max(hi[j], ohi[j]) } } - if(parity === (d&1)) { - var t = bcell[0] - bcell[0] = bcell[1] - bcell[1] = t - } - boundary.push(bcell) } - } - return boundary -} - -function incrementalConvexHull(points, randomSearch) { - var n = points.length - if(n === 0) { - throw new Error("Must have at least d+1 points") - } - var d = points[0].length - if(n <= d) { - throw new Error("Must input at least d+1 points") - } - - //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process - var initialSimplex = points.slice(0, d+1) - - //Make sure initial simplex is positively oriented - var o = orient.apply(void 0, initialSimplex) - if(o === 0) { - throw new Error("Input not in general position") - } - var initialCoords = new Array(d+1) - for(var i=0; i<=d; ++i) { - initialCoords[i] = i - } - if(o < 0) { - initialCoords[0] = 1 - initialCoords[1] = 0 - } - //Create initial topological index, glue pointers together (kind of messy) - var initialCell = new Simplex(initialCoords, new Array(d+1), false) - var boundary = initialCell.adjacent - var list = new Array(d+2) - for(var i=0; i<=d; ++i) { - var verts = initialCoords.slice() - for(var j=0; j<=d; ++j) { - if(j === i) { - verts[j] = -1 + //Recalculate bounds + var bounds = scene.bounds + if(scene.autoBounds) { + for(var j=0; j<3; ++j) { + if(hi[j] < lo[j]) { + lo[j] = -1 + hi[j] = 1 + } else { + if(lo[j] === hi[j]) { + lo[j] -= 1 + hi[j] += 1 + } + var padding = 0.05 * (hi[j] - lo[j]) + lo[j] = lo[j] - padding + hi[j] = hi[j] + padding + } + bounds[0][j] = lo[j] + bounds[1][j] = hi[j] } } - var t = verts[0] - verts[0] = verts[1] - verts[1] = t - var cell = new Simplex(verts, new Array(d+1), true) - boundary[i] = cell - list[i] = cell - } - list[d+1] = initialCell - for(var i=0; i<=d; ++i) { - var verts = boundary[i].vertices - var adj = boundary[i].adjacent - for(var j=0; j<=d; ++j) { - var v = verts[j] - if(v < 0) { - adj[j] = initialCell - continue + + var boundsChanged = false + for(var j=0; j<3; ++j) { + boundsChanged = boundsChanged || + (prevBounds[0][j] !== bounds[0][j]) || + (prevBounds[1][j] !== bounds[1][j]) + prevBounds[0][j] = bounds[0][j] + prevBounds[1][j] = bounds[1][j] + } + + if(boundsChanged) { + var tickSpacing = [0,0,0] + for(var i=0; i<3; ++i) { + tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0) } - for(var k=0; k<=d; ++k) { - if(boundary[k].vertices.indexOf(v) < 0) { - adj[j] = boundary[k] - } + if(axes.autoTicks) { + axes.update({ + bounds: bounds, + tickSpacing: tickSpacing + }) + } else { + axes.update({ + bounds: bounds + }) } } - } - - //Initialize triangles - var triangles = new Triangulation(d, initialSimplex, list) - //Insert remaining points - var useRandom = !!randomSearch - for(var i=d+1; i> 1 - , s = compareCells(cells[mid], c) - if(s <= 0) { - if(s === 0) { - r = mid - } - lo = mid + 1 - } else if(s > 0) { - hi = mid - 1 + spikes.axes = axes + if(selection.object) { + spikes.draw(cameraParams) } - } - return r -} -exports.findCell = findCell; -//Builds an index for an n-cell. This is more general than dual, but less efficient -function incidence(from_cells, to_cells) { - var index = new Array(from_cells.length) - for(var i=0, il=index.length; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { - break - } + if(obj.isTransparent && obj.isTransparent()) { + hasTransparent = true } } - } - return index -} -exports.incidence = incidence -//Computes the dual of the mesh. This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices -function dual(cells, vertex_count) { - if(!vertex_count) { - return incidence(unique(skeleton(cells, 0)), cells, 0) - } - var res = new Array(vertex_count) - for(var i=0; i>> k) & 1) { - b.push(c[k]) + //Render forward facing objects + if(axes.enable && axes.isTransparent()) { + axes.drawTransparent(cameraParams) + } + for(var i=0; i - * License: MIT - * - * `npm install is-buffer` - */ -module.exports = function (obj) { - return !!(obj != null && - (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) - (obj.constructor && - typeof obj.constructor.isBuffer === 'function' && - obj.constructor.isBuffer(obj)) - )) +module.exports = { + vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", + fragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n", + pickVertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", + pickFragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n" } -},{}],241:[function(require,module,exports){ +},{}],628:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":658}],629:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":630,"./lib/create-attributes":631,"./lib/create-uniforms":632,"./lib/reflect":633,"./lib/runtime-reflect":634,"./lib/shader-cache":635,"dup":94}],630:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],631:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":630,"dup":96}],632:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":630,"./reflect":633,"dup":97}],633:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],634:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],635:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":630,"dup":100,"gl-format-compiler-error":636,"weakmap-shim":654}],636:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":637,"dup":101,"gl-constants/lookup":641,"glsl-shader-name":642,"sprintf-js":651}],637:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":638}],638:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":639}],639:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],640:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],641:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":640,"dup":106}],642:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":643,"dup":107,"glsl-tokenizer":650}],643:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],644:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":646,"./lib/builtins-300es":645,"./lib/literals":648,"./lib/literals-300es":647,"./lib/operators":649,"dup":109}],645:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":646,"dup":110}],646:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],647:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":648,"dup":112}],648:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],649:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],650:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":644,"dup":115}],651:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],652:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":653,"dup":117}],653:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],654:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":652,"dup":119}],655:[function(require,module,exports){ +arguments[4][451][0].apply(exports,arguments) +},{"_process":70,"dup":451,"vectorize-text":659}],656:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],657:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],658:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":656,"buffer":65,"dup":122}],659:[function(require,module,exports){ +arguments[4][354][0].apply(exports,arguments) +},{"./lib/vtext":660,"dup":354}],660:[function(require,module,exports){ +arguments[4][355][0].apply(exports,arguments) +},{"cdt2d":661,"clean-pslg":673,"dup":355,"ndarray":1031,"planar-graph-to-polyline":728,"simplify-planar-graph":732,"surface-nets":745}],661:[function(require,module,exports){ +arguments[4][356][0].apply(exports,arguments) +},{"./lib/delaunay":662,"./lib/filter":663,"./lib/monotone":664,"./lib/triangulation":665,"dup":356}],662:[function(require,module,exports){ +arguments[4][357][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":357,"robust-in-sphere":667}],663:[function(require,module,exports){ +arguments[4][358][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":358}],664:[function(require,module,exports){ +arguments[4][359][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":359,"robust-orientation":1040}],665:[function(require,module,exports){ +arguments[4][360][0].apply(exports,arguments) +},{"binary-search-bounds":666,"dup":360}],666:[function(require,module,exports){ +arguments[4][312][0].apply(exports,arguments) +},{"dup":312}],667:[function(require,module,exports){ +arguments[4][361][0].apply(exports,arguments) +},{"dup":361,"robust-scale":669,"robust-subtract":670,"robust-sum":671,"two-product":672}],668:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"dup":53}],669:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54,"two-product":672,"two-sum":668}],670:[function(require,module,exports){ +arguments[4][364][0].apply(exports,arguments) +},{"dup":364}],671:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],672:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56}],673:[function(require,module,exports){ +arguments[4][367][0].apply(exports,arguments) +},{"./lib/rat-seg-intersect":674,"big-rat":678,"big-rat/cmp":676,"big-rat/to-float":693,"box-intersect":694,"compare-cell":702,"dup":367,"nextafter":703,"rat-vec":706,"robust-segment-intersect":709,"union-find":710}],674:[function(require,module,exports){ +arguments[4][368][0].apply(exports,arguments) +},{"big-rat/div":677,"big-rat/mul":687,"big-rat/sign":691,"big-rat/sub":692,"big-rat/to-float":693,"dup":368,"rat-vec/add":705,"rat-vec/muls":707,"rat-vec/sub":708}],675:[function(require,module,exports){ +arguments[4][369][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":369}],676:[function(require,module,exports){ +arguments[4][370][0].apply(exports,arguments) +},{"dup":370}],677:[function(require,module,exports){ +arguments[4][371][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":371}],678:[function(require,module,exports){ +arguments[4][372][0].apply(exports,arguments) +},{"./div":677,"./is-rat":679,"./lib/is-bn":683,"./lib/num-to-bn":684,"./lib/rationalize":685,"./lib/str-to-bn":686,"dup":372}],679:[function(require,module,exports){ +arguments[4][373][0].apply(exports,arguments) +},{"./lib/is-bn":683,"dup":373}],680:[function(require,module,exports){ +arguments[4][374][0].apply(exports,arguments) +},{"bn.js":689,"dup":374}],681:[function(require,module,exports){ +arguments[4][375][0].apply(exports,arguments) +},{"dup":375}],682:[function(require,module,exports){ +arguments[4][376][0].apply(exports,arguments) +},{"bit-twiddle":688,"double-bits":690,"dup":376}],683:[function(require,module,exports){ +arguments[4][377][0].apply(exports,arguments) +},{"bn.js":689,"dup":377}],684:[function(require,module,exports){ +arguments[4][378][0].apply(exports,arguments) +},{"bn.js":689,"double-bits":690,"dup":378}],685:[function(require,module,exports){ +arguments[4][379][0].apply(exports,arguments) +},{"./bn-sign":680,"./num-to-bn":684,"dup":379}],686:[function(require,module,exports){ +arguments[4][380][0].apply(exports,arguments) +},{"bn.js":689,"dup":380}],687:[function(require,module,exports){ +arguments[4][381][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":381}],688:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],689:[function(require,module,exports){ +arguments[4][383][0].apply(exports,arguments) +},{"dup":383}],690:[function(require,module,exports){ +arguments[4][384][0].apply(exports,arguments) +},{"buffer":65,"dup":384}],691:[function(require,module,exports){ +arguments[4][385][0].apply(exports,arguments) +},{"./lib/bn-sign":680,"dup":385}],692:[function(require,module,exports){ +arguments[4][386][0].apply(exports,arguments) +},{"./lib/rationalize":685,"dup":386}],693:[function(require,module,exports){ +arguments[4][387][0].apply(exports,arguments) +},{"./lib/bn-to-num":681,"./lib/ctz":682,"dup":387}],694:[function(require,module,exports){ +arguments[4][388][0].apply(exports,arguments) +},{"./lib/intersect":696,"./lib/sweep":700,"dup":388,"typedarray-pool":658}],695:[function(require,module,exports){ +arguments[4][389][0].apply(exports,arguments) +},{"dup":389}],696:[function(require,module,exports){ +arguments[4][390][0].apply(exports,arguments) +},{"./brute":695,"./median":697,"./partition":698,"./sweep":700,"bit-twiddle":701,"dup":390,"typedarray-pool":658}],697:[function(require,module,exports){ +arguments[4][391][0].apply(exports,arguments) +},{"./partition":698,"dup":391}],698:[function(require,module,exports){ +arguments[4][392][0].apply(exports,arguments) +},{"dup":392}],699:[function(require,module,exports){ +arguments[4][393][0].apply(exports,arguments) +},{"dup":393}],700:[function(require,module,exports){ +arguments[4][394][0].apply(exports,arguments) +},{"./sort":699,"bit-twiddle":701,"dup":394,"typedarray-pool":658}],701:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],702:[function(require,module,exports){ +arguments[4][61][0].apply(exports,arguments) +},{"dup":61}],703:[function(require,module,exports){ +arguments[4][399][0].apply(exports,arguments) +},{"double-bits":704,"dup":399}],704:[function(require,module,exports){ +arguments[4][384][0].apply(exports,arguments) +},{"buffer":65,"dup":384}],705:[function(require,module,exports){ +arguments[4][401][0].apply(exports,arguments) +},{"big-rat/add":675,"dup":401}],706:[function(require,module,exports){ +arguments[4][402][0].apply(exports,arguments) +},{"big-rat":678,"dup":402}],707:[function(require,module,exports){ +arguments[4][403][0].apply(exports,arguments) +},{"big-rat":678,"big-rat/mul":687,"dup":403}],708:[function(require,module,exports){ +arguments[4][404][0].apply(exports,arguments) +},{"big-rat/sub":692,"dup":404}],709:[function(require,module,exports){ +arguments[4][405][0].apply(exports,arguments) +},{"dup":405,"robust-orientation":1040}],710:[function(require,module,exports){ +arguments[4][78][0].apply(exports,arguments) +},{"dup":78}],711:[function(require,module,exports){ +arguments[4][407][0].apply(exports,arguments) +},{"dup":407,"edges-to-adjacency-list":712}],712:[function(require,module,exports){ +arguments[4][408][0].apply(exports,arguments) +},{"dup":408,"uniq":727}],713:[function(require,module,exports){ +arguments[4][409][0].apply(exports,arguments) +},{"compare-angle":714,"dup":409}],714:[function(require,module,exports){ +arguments[4][410][0].apply(exports,arguments) +},{"dup":410,"robust-orientation":1040,"robust-product":716,"robust-sum":725,"signum":717,"two-sum":718}],715:[function(require,module,exports){ +arguments[4][54][0].apply(exports,arguments) +},{"dup":54,"two-product":726,"two-sum":718}],716:[function(require,module,exports){ +arguments[4][412][0].apply(exports,arguments) +},{"dup":412,"robust-scale":715,"robust-sum":725}],717:[function(require,module,exports){ +arguments[4][413][0].apply(exports,arguments) +},{"dup":413}],718:[function(require,module,exports){ +arguments[4][53][0].apply(exports,arguments) +},{"dup":53}],719:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],720:[function(require,module,exports){ +arguments[4][416][0].apply(exports,arguments) +},{"binary-search-bounds":719,"dup":416}],721:[function(require,module,exports){ +arguments[4][417][0].apply(exports,arguments) +},{"dup":417,"robust-orientation":1040}],722:[function(require,module,exports){ +arguments[4][418][0].apply(exports,arguments) +},{"dup":418}],723:[function(require,module,exports){ +arguments[4][419][0].apply(exports,arguments) +},{"./lib/order-segments":721,"binary-search-bounds":719,"dup":419,"functional-red-black-tree":722,"robust-orientation":1040}],724:[function(require,module,exports){ +arguments[4][420][0].apply(exports,arguments) +},{"binary-search-bounds":719,"dup":420,"interval-tree-1d":720,"robust-orientation":1040,"slab-decomposition":723}],725:[function(require,module,exports){ +arguments[4][55][0].apply(exports,arguments) +},{"dup":55}],726:[function(require,module,exports){ +arguments[4][56][0].apply(exports,arguments) +},{"dup":56}],727:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],728:[function(require,module,exports){ +arguments[4][424][0].apply(exports,arguments) +},{"./lib/trim-leaves":711,"dup":424,"edges-to-adjacency-list":712,"planar-dual":713,"point-in-big-polygon":724,"robust-sum":725,"two-product":726,"uniq":727}],729:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],730:[function(require,module,exports){ +arguments[4][426][0].apply(exports,arguments) +},{"dup":426}],731:[function(require,module,exports){ +arguments[4][79][0].apply(exports,arguments) +},{"bit-twiddle":729,"dup":79,"union-find":730}],732:[function(require,module,exports){ +arguments[4][428][0].apply(exports,arguments) +},{"dup":428,"robust-orientation":1040,"simplicial-complex":731}],733:[function(require,module,exports){ +arguments[4][429][0].apply(exports,arguments) +},{"dup":429,"typedarray-pool":658}],734:[function(require,module,exports){ +arguments[4][433][0].apply(exports,arguments) +},{"dup":433}],735:[function(require,module,exports){ +arguments[4][437][0].apply(exports,arguments) +},{"dup":437,"typedarray-pool":658}],736:[function(require,module,exports){ +arguments[4][438][0].apply(exports,arguments) +},{"dup":438,"invert-permutation":737,"typedarray-pool":658}],737:[function(require,module,exports){ +arguments[4][439][0].apply(exports,arguments) +},{"dup":439}],738:[function(require,module,exports){ +arguments[4][443][0].apply(exports,arguments) +},{"dup":443,"gamma":734,"permutation-parity":735,"permutation-rank":736}],739:[function(require,module,exports){ +arguments[4][444][0].apply(exports,arguments) +},{"cwise-compiler":740,"dup":444}],740:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./lib/thunk.js":742,"dup":319}],741:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320,"uniq":743}],742:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"./compile.js":741,"dup":321}],743:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],744:[function(require,module,exports){ +arguments[4][449][0].apply(exports,arguments) +},{"./lib/zc-core":739,"dup":449}],745:[function(require,module,exports){ +arguments[4][450][0].apply(exports,arguments) +},{"dup":450,"ndarray-extract-contour":733,"triangulate-hypercube":738,"zero-crossings":744}],746:[function(require,module,exports){ 'use strict' -module.exports = mouseListen +module.exports = createFancyScatter2D -var mouse = require('mouse-event') +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var textCache = require('text-cache') +var pool = require('typedarray-pool') +var vectorizeText = require('vectorize-text') +var shaders = require('./lib/shaders') -function mouseListen(element, callback) { +var BOUNDARIES = {} - if(!callback) { - callback = element - element = window +function getBoundary(glyph) { + if(glyph in BOUNDARIES) { + return BOUNDARIES[glyph] } - var buttonState = 0 - var x = 0 - var y = 0 - var mods = { - shift: false, - alt: false, - control: false, - meta: false - } - var attached = false + var polys = vectorizeText(glyph, { + polygons: true, + font: 'sans-serif', + textAlign: 'left', + textBaseline: 'alphabetic' + }) - function updateMods(ev) { - var changed = false - if('altKey' in ev) { - changed = changed || ev.altKey !== mods.alt - mods.alt = !!ev.altKey - } - if('shiftKey' in ev) { - changed = changed || ev.shiftKey !== mods.shift - mods.shift = !!ev.shiftKey - } - if('ctrlKey' in ev) { - changed = changed || ev.ctrlKey !== mods.control - mods.control = !!ev.ctrlKey - } - if('metaKey' in ev) { - changed = changed || ev.metaKey !== mods.meta - mods.meta = !!ev.metaKey - } - return changed - } + var coords = [] + var normals = [] - function handleEvent(nextButtons, ev) { - var nextX = mouse.x(ev) - var nextY = mouse.y(ev) - if('buttons' in ev) { - nextButtons = ev.buttons|0 - } - if(nextButtons !== buttonState || - nextX !== x || - nextY !== y || - updateMods(ev)) { - buttonState = nextButtons|0 - x = nextX||0 - y = nextY||0 - callback(buttonState, x, y, mods) - } - } + polys.forEach(function(loops) { + loops.forEach(function(loop) { + for(var i=0; i 0) { - return 1<<(b-1) - } - } else if('button' in ev) { - var b = ev.button - if(b === 1) { - return 4 - } else if(b === 2) { - return 2 - } else if(b >= 0) { - return 1<>(i*8)) & 0xff) } - var target = mouseElement(ev) - var bounds = target.getBoundingClientRect() - return ev.clientY - bounds.top - } - return 0 -} -exports.y = mouseRelativeY -},{}],243:[function(require,module,exports){ -module.exports = function parseUnit(str, out) { - if (!out) - out = [ 0, '' ] + calcScales.call(this) - str = String(str) - var num = parseFloat(str, 10) - out[0] = num - out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || '' - return out -} -},{}],244:[function(require,module,exports){ -'use strict' + shader.bind() -var parseUnit = require('parse-unit') + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.viewTransform = MATRIX + shader.uniforms.pickOffset = PICK_OFFSET -module.exports = toPX + this.positionBuffer.bind() + shader.attributes.position.pointer() -var PIXELS_PER_INCH = 96 + this.offsetBuffer.bind() + shader.attributes.offset.pointer() -function getPropertyInPX(element, prop) { - var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop)) - return parts[0] * toPX(parts[1], element) -} + this.idBuffer.bind() + shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false) -//This brutal hack is needed -function getSizeBrutal(unit, element) { - var testDIV = document.createElement('div') - testDIV.style['font-size'] = '128' + unit - element.appendChild(testDIV) - var size = getPropertyInPX(testDIV, 'font-size') / 128 - element.removeChild(testDIV) - return size -} + gl.drawArrays(gl.TRIANGLES, 0, numVertices) -function toPX(str, element) { - element = element || document.body - str = (str || 'px').trim().toLowerCase() - if(element === window || element === document) { - element = document.body - } - switch(str) { - case '%': //Ambiguous, not sure if we should use width or height - return element.clientHeight / 100.0 - case 'ch': - case 'ex': - return getSizeBrutal(str, element) - case 'em': - return getPropertyInPX(element, 'font-size') - case 'rem': - return getPropertyInPX(document.body, 'font-size') - case 'vw': - return window.innerWidth/100 - case 'vh': - return window.innerHeight/100 - case 'vmin': - return Math.min(window.innerWidth, window.innerHeight) / 100 - case 'vmax': - return Math.max(window.innerWidth, window.innerHeight) / 100 - case 'in': - return PIXELS_PER_INCH - case 'cm': - return PIXELS_PER_INCH / 2.54 - case 'mm': - return PIXELS_PER_INCH / 25.4 - case 'pt': - return PIXELS_PER_INCH / 72 - case 'pc': - return PIXELS_PER_INCH / 6 + return offset + this.numPoints } - return 1 -} -},{"parse-unit":243}],245:[function(require,module,exports){ -'use strict' - -var toPX = require('to-px') - -module.exports = mouseWheelListen +})() -function mouseWheelListen(element, callback, noScroll) { - if(typeof element === 'function') { - noScroll = !!callback - callback = element - element = window +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.numPoints + if(value < pickOffset || value >= pickOffset + pointCount) { + return null } - var lineHeight = toPX('ex', element) - var listener = function(ev) { - if(noScroll) { - ev.preventDefault() - } - var dx = ev.deltaX || 0 - var dy = ev.deltaY || 0 - var dz = ev.deltaZ || 0 - var mode = ev.deltaMode - var scale = 1 - switch(mode) { - case 1: - scale = lineHeight - break - case 2: - scale = window.innerHeight - break - } - dx *= scale - dy *= scale - dz *= scale - if(dx || dy || dz) { - return callback(dx, dy, dz) - } + var pointId = value - pickOffset + var points = this.points + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] } - element.addEventListener('wheel', listener) - return listener -} - -},{"to-px":244}],246:[function(require,module,exports){ -"use strict" - - - -var fill = require('cwise/lib/wrapper')({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_4_arg1_=_inline_4_arg2_.apply(void 0,_inline_4_arg0_)}","args":[{"name":"_inline_4_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_4_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) - -module.exports = function(array, f) { - fill(array, f) - return array } -},{"cwise/lib/wrapper":112}],247:[function(require,module,exports){ -'use strict' +proto.update = function(options) { + options = options || {} -module.exports = invert + var positions = options.positions || [] + var colors = options.colors || [] + var glyphs = options.glyphs || [] + var sizes = options.sizes || [] + var borderWidths = options.borderWidths || [] + var borderColors = options.borderColors || [] -var invert2 = require('gl-mat2/invert') -var invert3 = require('gl-mat3/invert') -var invert4 = require('gl-mat4/invert') + this.points = positions -function invert(out, M) { - switch(M.length) { - case 0: - break - case 1: - out[0] = 1.0 / M[0] - break - case 4: - invert2(out, M) - break - case 9: - invert3(out, M) - break - case 16: - invert4(out, M) - break - default: - throw new Error('currently supports matrices up to 4x4') - break + var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + var numVertices = 0 + for(var i=0; i> 1 + for(var j=0; j<2; ++j) { + bounds[j] = Math.min(bounds[j], positions[2*i+j]) + bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j]) + } } - return out -} -},{"gl-mat2/invert":248,"gl-mat3/invert":130,"gl-mat4/invert":137}],248:[function(require,module,exports){ -module.exports = invert -/** - * Inverts a mat2 - * - * @alias mat2.invert - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ -function invert(out, a) { - var a0 = a[0] - var a1 = a[1] - var a2 = a[2] - var a3 = a[3] - var det = a0 * a3 - a2 * a1 + if(bounds[0] === bounds[2]) { + bounds[2] += 1 + } + if(bounds[3] === bounds[1]) { + bounds[3] += 1 + } - if (!det) return null - det = 1.0 / det + var sx = 1/(bounds[2] - bounds[0]) + var sy = 1/(bounds[3] - bounds[1]) + var tx = bounds[0] + var ty = bounds[1] - out[0] = a3 * det - out[1] = -a1 * det - out[2] = -a2 * det - out[3] = a0 * det + var v_position = pool.mallocFloat32(2 * numVertices) + var v_offset = pool.mallocFloat32(2 * numVertices) + var v_color = pool.mallocUint8(4 * numVertices) + var v_ids = pool.mallocUint32(numVertices) + var ptr = 0 - return out -} + for(var i=0; i left) { + var b_level = data_levels[j-1] + var b_x = data_points[2*(j-1)] + if(((b_level - a_level) || (a_x - b_x)) >= 0) { + break + } + data_levels[j] = b_level + data_points[2*j] = b_x + data_points[2*j+1] = data_points[2*j-1] + data_ids[j] = data_ids[j-1] + data_weights[j] = data_weights[j-1] + j -= 1 + } + + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } - var wrapper = new Function("P", [ - "return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}" - ].join("")) - return wrapper(pcompile(user_args)) } -var assign_ops = { - add: "+", - sub: "-", - mul: "*", - div: "/", - mod: "%", - band: "&", - bor: "|", - bxor: "^", - lshift: "<<", - rshift: ">>", - rrshift: ">>>" -} -;(function(){ - for(var id in assign_ops) { - var op = assign_ops[id] - exports[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a","b","c"], - body: "a=b"+op+"c"}, - funcName: id - }) - exports[id+"eq"] = makeOp({ - args: ["array","array"], - body: {args:["a","b"], - body:"a"+op+"=b"}, - rvalue: true, - funcName: id+"eq" - }) - exports[id+"s"] = makeOp({ - args: ["array", "array", "scalar"], - body: {args:["a","b","s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - exports[id+"seq"] = makeOp({ - args: ["array","scalar"], - body: {args:["a","s"], - body:"a"+op+"=s"}, - rvalue: true, - funcName: id+"seq" - }) - } -})(); +function swap(i, j, data_levels, data_points, data_ids, data_weights) { + var a_level = data_levels[i] + var a_x = data_points[2*i] + var a_y = data_points[2*i+1] + var a_id = data_ids[i] + var a_weight = data_weights[i] -var unary_ops = { - not: "!", - bnot: "~", - neg: "-", - recip: "1.0/" -} -;(function(){ - for(var id in unary_ops) { - var op = unary_ops[id] - exports[id] = makeOp({ - args: ["array", "array"], - body: {args:["a","b"], - body:"a="+op+"b"}, - funcName: id - }) - exports[id+"eq"] = makeOp({ - args: ["array"], - body: {args:["a"], - body:"a="+op+"a"}, - rvalue: true, - count: 2, - funcName: id+"eq" - }) - } -})(); + data_levels[i] = data_levels[j] + data_points[2*i] = data_points[2*j] + data_points[2*i+1] = data_points[2*j+1] + data_ids[i] = data_ids[j] + data_weights[i] = data_weights[j] -var binary_ops = { - and: "&&", - or: "||", - eq: "===", - neq: "!==", - lt: "<", - gt: ">", - leq: "<=", - geq: ">=" + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } -;(function() { - for(var id in binary_ops) { - var op = binary_ops[id] - exports[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a", "b", "c"], - body:"a=b"+op+"c"}, - funcName: id - }) - exports[id+"s"] = makeOp({ - args: ["array","array","scalar"], - body: {args:["a", "b", "s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - exports[id+"eq"] = makeOp({ - args: ["array", "array"], - body: {args:["a", "b"], - body:"a=a"+op+"b"}, - rvalue:true, - count:2, - funcName: id+"eq" - }) - exports[id+"seq"] = makeOp({ - args: ["array", "scalar"], - body: {args:["a","s"], - body:"a=a"+op+"s"}, - rvalue:true, - count:2, - funcName: id+"seq" - }) - } -})(); -var math_unary = [ - "abs", - "acos", - "asin", - "atan", - "ceil", - "cos", - "exp", - "floor", - "log", - "round", - "sin", - "sqrt", - "tan" -] -;(function() { - for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norminf" -}) +function compare(i, j, data_levels, data_points, data_ids) { + return ((data_levels[i] - data_levels[j]) || + (data_points[2*j] - data_points[2*i]) || + (data_ids[i] - data_ids[j])) < 0 +} -exports.norm1 = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norm1" -}) +function comparePivot(i, level, x, y, id, data_levels, data_points, data_ids) { + return ((level - data_levels[i]) || + (data_points[2*i] - x) || + (id - data_ids[i])) < 0 +} -exports.sup = compile({ - args: [ "array" ], - pre: - { body: "this_h=-Infinity", - args: [], - thisVars: [ "this_h" ], - localVars: [] }, - body: - { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", - args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], - thisVars: [ "this_h" ], - localVars: [] }, - post: - { body: "return this_h", - args: [], - thisVars: [ "this_h" ], - localVars: [] } - }) +function quickSort(left, right, data_levels, data_points, data_ids, data_weights) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, + tmp = 0 + if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el2 + el2 = tmp + } + if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el4 + el4 = el5 + el5 = tmp + } + if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el3 + el3 = tmp + } + if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el4 + el4 = tmp + } + if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) { + tmp = el3 + el3 = el4 + el4 = tmp + } + if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el5 + el5 = tmp + } + if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el4 + el4 = el5 + el5 = tmp + } -exports.inf = compile({ - args: [ "array" ], - pre: - { body: "this_h=Infinity", - args: [], - thisVars: [ "this_h" ], - localVars: [] }, - body: - { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", - args:[ - {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, - {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], - thisVars:["this_i","this_v"], - localVars:["_inline_1_k"]}, - post:{ - body:"{return this_i}", - args:[], - thisVars:["this_i"], - localVars:[]} -}) + var ptr0 = el1 + var ptr2 = el3 + var ptr4 = el5 + var ptr5 = index1 + var ptr6 = index3 + var ptr7 = index5 -exports.random = makeOp({ - args: ["array"], - pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, - body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, - funcName: "random" -}) + var level_x = data_levels[ptr0] + var level_y = data_levels[ptr2] + var level_z = data_levels[ptr4] + data_levels[ptr5] = level_x + data_levels[ptr6] = level_y + data_levels[ptr7] = level_z -exports.assign = makeOp({ - args:["array", "array"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assign" }) + for (var i1 = 0; i1 < 2; ++i1) { + var x = data_points[2*ptr0+i1] + var y = data_points[2*ptr2+i1] + var z = data_points[2*ptr4+i1] + data_points[2*ptr5+i1] = x + data_points[2*ptr6+i1] = y + data_points[2*ptr7+i1] = z + } -exports.assigns = makeOp({ - args:["array", "scalar"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assigns" }) + var id_x = data_ids[ptr0] + var id_y = data_ids[ptr2] + var id_z = data_ids[ptr4] + data_ids[ptr5] = id_x + data_ids[ptr6] = id_y + data_ids[ptr7] = id_z + var weight_x = data_weights[ptr0] + var weight_y = data_weights[ptr2] + var weight_z = data_weights[ptr4] + data_weights[ptr5] = weight_x + data_weights[ptr6] = weight_y + data_weights[ptr7] = weight_z -exports.equals = compile({ - args:["array", "array"], - pre: EmptyProc, - body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, - {name:"y", lvalue:false, rvalue:true, count:1}], - body: "if(x!==y){return false}", - localVars: [], - thisVars: []}, - post: {args:[], localVars:[], thisVars:[], body:"return true"}, - funcName: "equals" -}) + move(index2, left, data_levels, data_points, data_ids, data_weights) + move(index4, right, data_levels, data_points, data_ids, data_weights) + for (var k = less; k <= great; ++k) { + if (comparePivot(k, + pivot1_level, pivot1_x, pivot1_y, pivot1_id, + data_levels, data_points, data_ids)) { + if (k !== less) { + swap(k, less, data_levels, data_points, data_ids, data_weights) + } + ++less; + } else { + if (!comparePivot(k, + pivot2_level, pivot2_x, pivot2_y, pivot2_id, + data_levels, data_points, data_ids)) { + while (true) { + if (!comparePivot(great, + pivot2_level, pivot2_x, pivot2_y, pivot2_id, + data_levels, data_points, data_ids)) { + if (--great < k) { + break; + } + continue; + } else { + if (comparePivot(great, + pivot1_level, pivot1_x, pivot1_y, pivot1_id, + data_levels, data_points, data_ids)) { + rotate(k, less, great, data_levels, data_points, data_ids, data_weights) + ++less; + --great; + } else { + swap(k, great, data_levels, data_points, data_ids, data_weights) + --great; + } + break; + } + } + } + } + } + shufflePivot(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights) + shufflePivot(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights) + if (less - 2 - left <= INSERT_SORT_CUTOFF) { + insertionSort(left, less - 2, data_levels, data_points, data_ids, data_weights) + } else { + quickSort(left, less - 2, data_levels, data_points, data_ids, data_weights) + } + if (right - (great + 2) <= INSERT_SORT_CUTOFF) { + insertionSort(great + 2, right, data_levels, data_points, data_ids, data_weights) + } else { + quickSort(great + 2, right, data_levels, data_points, data_ids, data_weights) + } + if (great - less <= INSERT_SORT_CUTOFF) { + insertionSort(less, great, data_levels, data_points, data_ids, data_weights) + } else { + quickSort(less, great, data_levels, data_points, data_ids, data_weights) + } +} +},{}],777:[function(require,module,exports){ +'use strict' +var pool = require('typedarray-pool') -},{"cwise-compiler":109}],253:[function(require,module,exports){ -var iota = require("iota-array") -var isBuffer = require("is-buffer") +var sortLevels = require('./lib/sort') -var hasTypedArrays = ((typeof Float64Array) !== "undefined") +module.exports = snapPoints -function compare1st(a, b) { - return a[0] - b[0] +function partition(points, ids, start, end, lox, loy, hix, hiy) { + var mid = start + for(var i=start; i>> 1 + if(n < 1) { + return [] } - var useGetters = (dtype === "generic") - if(dimension === -1) { - //Special case for trivial arrays - var code = - "function "+className+"(a){this.data=a;};\ -var proto="+className+".prototype;\ -proto.dtype='"+dtype+"';\ -proto.index=function(){return -1};\ -proto.size=0;\ -proto.dimension=-1;\ -proto.shape=proto.stride=proto.order=[];\ -proto.lo=proto.hi=proto.transpose=proto.step=\ -function(){return new "+className+"(this.data);};\ -proto.get=proto.set=function(){};\ -proto.pick=function(){return null};\ -return function construct_"+className+"(a){return new "+className+"(a);}" - var procedure = new Function(code) - return procedure() - } else if(dimension === 0) { - //Special case for 0d arrays - var code = - "function "+className+"(a,d) {\ -this.data = a;\ -this.offset = d\ -};\ -var proto="+className+".prototype;\ -proto.dtype='"+dtype+"';\ -proto.index=function(){return this.offset};\ -proto.dimension=0;\ -proto.size=1;\ -proto.shape=\ -proto.stride=\ -proto.order=[];\ -proto.lo=\ -proto.hi=\ -proto.transpose=\ -proto.step=function "+className+"_copy() {\ -return new "+className+"(this.data,this.offset)\ -};\ -proto.pick=function "+className+"_pick(){\ -return TrivialArray(this.data);\ -};\ -proto.valueOf=proto.get=function "+className+"_get(){\ -return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ -"};\ -proto.set=function "+className+"_set(v){\ -return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ -};\ -return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" - var procedure = new Function("TrivialArray", code) - return procedure(CACHED_CONSTRUCTORS[dtype][0]) + var lox = Infinity, loy = Infinity + var hix = -Infinity, hiy = -Infinity + for(var i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") - } else if(dimension === 3) { - code.push( -"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ -if(s0>s1){\ -if(s1>s2){\ -return [2,1,0];\ -}else if(s0>s2){\ -return [1,2,0];\ -}else{\ -return [1,0,2];\ -}\ -}else if(s0>s2){\ -return [2,0,1];\ -}else if(s2>s1){\ -return [0,1,2];\ -}else{\ -return [0,2,1];\ -}}})") + bounds[0] = lox + bounds[1] = loy + bounds[2] = hix + bounds[3] = hiy + + var levels = pool.mallocInt32(n) + var ptr = 0 + + function snapRec(x, y, diam, start, end, level) { + var diam_2 = diam * 0.5 + var offset = start + 1 + var count = end - start + weights[ptr] = count + levels[ptr++] = level + for(var i=0; i<2; ++i) { + for(var j=0; j<2; ++j) { + var nx = x+i*diam_2 + var ny = y+j*diam_2 + var nextOffset = partition( + points + , ids + , offset + , end + , nx, ny + , nx+diam_2, ny+diam_2) + if(nextOffset === offset) { + continue + } + if(nextOffset - offset >= Math.max(0.9 * count, 32)) { + var mid = (end + start)>>>1 + snapRec(nx, ny, diam_2, offset, mid, level+1) + offset = mid + } + snapRec(nx, ny, diam_2, offset, nextOffset, level+1) + offset = nextOffset } - } else { - code.push("ORDER})") } } + snapRec(lox, loy, diam, 0, n, 0) + sortLevels(levels, points, ids, weights, n) - //view.set(i0, ..., v): - code.push( -"proto.set=function "+className+"_set("+args.join(",")+",v){") - if(useGetters) { - code.push("return this.data.set("+index_str+",v)}") - } else { - code.push("return this.data["+index_str+"]=v}") - } + var lod = [] + var lastLevel = 0 + var prevOffset = n + for(var ptr=n-1; ptr>=0; --ptr) { + points[2*ptr] = (points[2*ptr] - lox) * scaleX + points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY - //view.get(i0, ...): - code.push("proto.get=function "+className+"_get("+args.join(",")+"){") - if(useGetters) { - code.push("return this.data.get("+index_str+")}") - } else { - code.push("return this.data["+index_str+"]}") + var level = levels[ptr] + if(level === lastLevel) { + continue + } + + lod.push(new SnapInterval( + diam * Math.pow(0.5, level), + ptr+1, + prevOffset - (ptr+1) + )) + prevOffset = ptr+1 + + lastLevel = level } - //view.index: - code.push( - "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") + lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) + pool.free(levels) - //view.hi(): - code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ - indices.map(function(i) { - return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") - }).join(",")+","+ - indices.map(function(i) { - return "this.stride["+i + "]" - }).join(",")+",this.offset)}") + return lod +} - //view.lo(): - var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) - var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) - code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) - for(var i=0; i=0){\ -d=i"+i+"|0;\ -b+=c"+i+"*d;\ -a"+i+"-=d}") - } - code.push("return new "+className+"(this.data,"+ - indices.map(function(i) { - return "a"+i - }).join(",")+","+ - indices.map(function(i) { - return "c"+i - }).join(",")+",b)}") +},{"./lib/sort":776,"typedarray-pool":780}],778:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],779:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],780:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":778,"buffer":65,"dup":122}],781:[function(require,module,exports){ +'use strict' - //view.step(): - code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ - indices.map(function(i) { - return "a"+i+"=this.shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "b"+i+"=this.stride["+i+"]" - }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") - for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") - } - code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") +var SHADERS = require('./lib/shader') - //Add return statement - code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ - indices.map(function(i) { - return "shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "stride["+i+"]" - }).join(",")+",offset)}") +module.exports = createScatter2D - //Compile procedure - var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) - return procedure(CACHED_CONSTRUCTORS[dtype], order) +function Scatter2D(plot, offsetBuffer, pickBuffer, weightBuffer, shader, pickShader) { + this.plot = plot + this.offsetBuffer = offsetBuffer + this.pickBuffer = pickBuffer + this.weightBuffer = weightBuffer + this.shader = shader + this.pickShader = pickShader + this.scales = [] + this.size = 12.0 + this.borderSize = 1.0 + this.pointCount = 0 + this.color = [1,0,0,1] + this.borderColor = [0,0,0,1] + this.bounds = [Infinity,Infinity,-Infinity,-Infinity] + this.pickOffset = 0 + this.points = null + this.xCoords = null } -function arrayDType(data) { - if(isBuffer(data)) { - return "buffer" - } - if(hasTypedArrays) { - switch(Object.prototype.toString.call(data)) { - case "[object Float64Array]": - return "float64" - case "[object Float32Array]": - return "float32" - case "[object Int8Array]": - return "int8" - case "[object Int16Array]": - return "int16" - case "[object Int32Array]": - return "int32" - case "[object Uint8Array]": - return "uint8" - case "[object Uint16Array]": - return "uint16" - case "[object Uint32Array]": - return "uint32" - case "[object Uint8ClampedArray]": - return "uint8_clamped" - } - } - if(Array.isArray(data)) { - return "array" - } - return "generic" -} +var proto = Scatter2D.prototype -var CACHED_CONSTRUCTORS = { - "float32":[], - "float64":[], - "int8":[], - "int16":[], - "int32":[], - "uint8":[], - "uint16":[], - "uint32":[], - "array":[], - "uint8_clamped":[], - "buffer":[], - "generic":[] +proto.dispose = function() { + this.shader.dispose() + this.pickShader.dispose() + this.offsetBuffer.dispose() + this.pickBuffer.dispose() + if(this.xCoords) { + pool.free(this.xCoords) + } + this.plot.removeObject(this) } -;(function() { - for(var id in CACHED_CONSTRUCTORS) { - CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) - } -}); +proto.update = function(options) { + options = options || {} -function wrappedNDArrayCtor(data, shape, stride, offset) { - if(data === undefined) { - var ctor = CACHED_CONSTRUCTORS.array[0] - return ctor([]) - } else if(typeof data === "number") { - data = [data] - } - if(shape === undefined) { - shape = [ data.length ] - } - var d = shape.length - if(stride === undefined) { - stride = new Array(d) - for(var i=d-1, sz=1; i>=0; --i) { - stride[i] = sz - sz *= shape[i] + function dflt(opt, value) { + if(opt in options) { + return options[opt] } + return value } - if(offset === undefined) { - offset = 0 - for(var i=0; i>>1) + packed.set(data) + var packedW = pool.mallocFloat32(data.length) + this.points = data + this.scales = snapPoints(packed, packedId, packedW, this.bounds) + this.offsetBuffer.update(packed) + this.pickBuffer.update(packedId) + this.weightBuffer.update(packedW) + var xCoords = pool.mallocFloat32(data.length>>>1) + for(var i=0,j=0; i>> 1 + this.pickOffset = 0 } -module.exports = wrappedNDArrayCtor +proto.drawPick = (function() { + var MATRIX = [1,0,0, + 0,1,0, + 0,0,1] + var PICK_VEC4 = [0,0,0,0] +return function(pickOffset) { + var plot = this.plot + var shader = this.pickShader + var scales = this.scales + var offsetBuffer = this.offsetBuffer + var pickBuffer = this.pickBuffer + var bounds = this.bounds + var size = this.size + var borderSize = this.borderSize + var gl = plot.gl + var pixelRatio = plot.pickPixelRatio + var viewBox = plot.viewBox + var dataBox = plot.dataBox -},{"iota-array":239,"is-buffer":240}],254:[function(require,module,exports){ -/*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + if(this.pointCount === 0) { + return pickOffset + } -'use strict'; + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = (viewBox[2] - viewBox[0]) * pixelRatio / plot.pixelRatio + var screenY = (viewBox[3] - viewBox[1]) * pixelRatio / plot.pixelRatio -/** - * Results cache - */ + var pixelSize = Math.min(dataX / screenX, dataY / screenY) + var targetScale = pixelSize -var res = ''; -var cache; -/** - * Expose `repeat` - */ + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 -module.exports = repeat; + this.pickOffset = pickOffset + PICK_VEC4[0] = ( pickOffset & 0xff) + PICK_VEC4[1] = ((pickOffset>>8) & 0xff) + PICK_VEC4[2] = ((pickOffset>>16) & 0xff) + PICK_VEC4[3] = ((pickOffset>>24) & 0xff) -/** - * Repeat the given `string` the specified `number` - * of times. - * - * **Example:** - * - * ```js - * var repeat = require('repeat-string'); - * repeat('A', 5); - * //=> AAAAA - * ``` - * - * @param {String} `string` The string to repeat - * @param {Number} `number` The number of times to repeat the string - * @return {String} Repeated string - * @api public - */ + shader.bind() + shader.uniforms.matrix = MATRIX + shader.uniforms.color = this.color + shader.uniforms.borderColor = this.borderColor + shader.uniforms.pointSize = pixelRatio * (size + borderSize) + shader.uniforms.pickOffset = PICK_VEC4 -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('repeat-string expects a string.'); + if(this.borderSize === 0) { + shader.uniforms.centerFraction = 2.0; + } else { + shader.uniforms.centerFraction = size / (size + borderSize + 1.25) } - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; + offsetBuffer.bind() + shader.attributes.position.pointer() + pickBuffer.bind() + shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE) - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } + var xCoords = this.xCoords + var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX + var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX - while (max > res.length && num > 0) { - if (num & 1) { - res += str; + for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { + var lod = scales[scaleNum] + if(lod.pixelSize < pixelSize && scaleNum > 1) { + continue } - num >>= 1; - if (!num) break; - str += str; + var intervalStart = lod.offset + var intervalEnd = lod.count + intervalStart + + var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) + var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + + if(endOffset > startOffset) { + gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + } } - return res.substr(0, max); + return pickOffset + this.pointCount } +})() +proto.draw = (function() { + var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] -},{}],255:[function(require,module,exports){ -(function (global){ -module.exports = - global.performance && - global.performance.now ? function now() { - return performance.now() - } : Date.now || function now() { - return +new Date - } + return function() { + var plot = this.plot + var shader = this.shader + var scales = this.scales + var offsetBuffer = this.offsetBuffer + var bounds = this.bounds + var size = this.size + var borderSize = this.borderSize + var gl = plot.gl + var pixelRatio = plot.pixelRatio + var viewBox = plot.viewBox + var dataBox = plot.dataBox -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],256:[function(require,module,exports){ -"use strict" + if(this.pointCount === 0) { + return + } -var determinant = require("robust-determinant") + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] -var NUM_EXPAND = 6 + var pixelSize = Math.min(dataX / screenX, dataY / screenY) + var targetScale = pixelSize -function generateSolver(n) { - var funcName = "robustLinearSolve" + n + "d" - var code = ["function ", funcName, "(A,b){return ["] - for(var i=0; i 0) { - code.push(",") + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + shader.bind() + shader.uniforms.matrix = MATRIX + shader.uniforms.color = this.color + shader.uniforms.borderColor = this.borderColor + shader.uniforms.pointSize = pixelRatio * (size + borderSize) + shader.uniforms.useWeight = 1 + + if(this.borderSize === 0) { + shader.uniforms.centerFraction = 2.0; + } else { + shader.uniforms.centerFraction = size / (size + borderSize + 1.25) + } + + offsetBuffer.bind() + shader.attributes.position.pointer() + + this.weightBuffer.bind() + shader.attributes.weight.pointer() + + var xCoords = this.xCoords + var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX + var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX + + var firstLevel = true + + for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { + var lod = scales[scaleNum] + if(lod.pixelSize < pixelSize && scaleNum > 1) { + continue } - code.push("[") - for(var k=0; k 0) { - code.push(",") - } - if(k === i) { - code.push("+b[", j, "]") - } else { - code.push("+A[", j, "][", k, "]") - } + + var intervalStart = lod.offset + var intervalEnd = lod.count + intervalStart + + var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) + var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + + if(endOffset > startOffset) { + gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + } + + if(firstLevel) { + firstLevel = false + shader.uniforms.useWeight = 0 } - code.push("]") } - code.push("]),") } - code.push("det(A)]}return ", funcName) - var proc = new Function("det", code.join("")) - if(n < 6) { - return proc(determinant[n]) +})() + +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.pointCount + if(value < pickOffset || value >= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var points = this.points + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] } - return proc(determinant) } -function robustLinearSolve0d() { - return [ 0 ] -} +function createScatter2D(plot, options) { + var gl = plot.gl + var buffer = createBuffer(gl) + var pickBuffer = createBuffer(gl) + var weightBuffer = createBuffer(gl) + var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment) + var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) -function robustLinearSolve1d(A, b) { - return [ [ b[0] ], [ A[0][0] ] ] -} + var result = new Scatter2D( + plot, buffer, pickBuffer, weightBuffer, shader, pickShader) + result.update(options) -var CACHE = [ - robustLinearSolve0d, - robustLinearSolve1d -] + //Register with plot + plot.addObject(result) -function generateDispatch() { - while(CACHE.length < NUM_EXPAND) { - CACHE.push(generateSolver(CACHE.length)) - } - var procArgs = [] - var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] - for(var i=0; i=0; --i) { - var a = Q - var b = e[i] - Q = a + b - var bv = Q - a - var q = b - bv - if(q) { - e[--bottom] = Q - Q = q - } +module.exports = getGlyph + +var GLYPH_CACHE = {} + +function getGlyph(symbol, font) { + var fontCache = GLYPH_CACHE[font] + if(!fontCache) { + fontCache = GLYPH_CACHE[font] = {} } - var top = 0 - for(var i=bottom; i>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } -} +var perspectiveVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n \n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}" +var orthographicVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n \n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}" +var projectionVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * view * model * vec4(position, 1);\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n" +var drawFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n" +var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}" -function determinant(m) { - if(m.length === 2) { - return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") - } else { - var expr = [] - for(var i=0; i>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } +function ScatterPlotPickResult(index, position) { + this.index = index + this.dataCoordinate = this.position = position } -function determinant(m) { - if(m.length === 2) { - return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] - } else { - var expr = [] - for(var i=0; i 0) { - if(r <= 0) { - return det - } else { - s = l + r - } - } else if(l < 0) { - if(r >= 0) { - return det - } else { - s = -(l + r) - } - } else { - return det - } - var tol = ERRBOUND3 * s - if(det >= tol || det <= -tol) { - return det - } - return orientation3Exact(a, b, c) - }, - function orientation4(a,b,c,d) { - var adx = a[0] - d[0] - var bdx = b[0] - d[0] - var cdx = c[0] - d[0] - var ady = a[1] - d[1] - var bdy = b[1] - d[1] - var cdy = c[1] - d[1] - var adz = a[2] - d[2] - var bdz = b[2] - d[2] - var cdz = c[2] - d[2] - var bdxcdy = bdx * cdy - var cdxbdy = cdx * bdy - var cdxady = cdx * ady - var adxcdy = adx * cdy - var adxbdy = adx * bdy - var bdxady = bdx * ady - var det = adz * (bdxcdy - cdxbdy) - + bdz * (cdxady - adxcdy) - + cdz * (adxbdy - bdxady) - var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) - + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) - + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) - var tol = ERRBOUND4 * permanent - if ((det > tol) || (-det > tol)) { - return det - } - return orientation4Exact(a,b,c,d) - } -] + this.shader = shader + this.orthoShader = orthoShader + this.projectShader = projectShader -function slowOrient(args) { - var proc = CACHED[args.length] - if(!proc) { - proc = CACHED[args.length] = orientation(args.length) - } - return proc.apply(undefined, args) -} + this.pointBuffer = pointBuffer + this.colorBuffer = colorBuffer + this.glyphBuffer = glyphBuffer + this.idBuffer = idBuffer + this.vao = vao + this.vertexCount = 0 + this.lineVertexCount = 0 -function generateOrientationProc() { - while(CACHED.length <= NUM_EXPAND) { - CACHED.push(orientation(CACHED.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=NUM_EXPAND; ++i) { - args.push("a" + i) - procArgs.push("o" + i) - } - var code = [ - "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=NUM_EXPAND; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") - } - code.push("}var s=new Array(arguments.length);for(var i=0;i= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } +proto.isTransparent = function() { + if(this.opacity < 1) { + return true } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + for(var i=0; i<3; ++i) { + if(this.axesProject[i] && this.projectOpacity[i] < 1) { + return true } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - } + return false +} + +proto.isOpaque = function() { + if(this.opacity >= 1) { + return true } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] + for(var i=0; i<3; ++i) { + if(this.axesProject[i] && this.projectOpacity[i] >= 1) { + return true } } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g + return false } -},{}],262:[function(require,module,exports){ -"use strict" -module.exports = linearExpansionSum +var VIEW_SHAPE = [0,0] +var U_VEC = [0,0,0] +var V_VEC = [0,0,0] +var MU_VEC = [0,0,0,1] +var MV_VEC = [0,0,0,1] +var SCRATCH_MATRIX = IDENTITY.slice() +var SCRATCH_VEC = [0,0,0] +var CLIP_BOUNDS = [[0,0,0], [0,0,0]] -//Easy case: Add two scalars -function scalarScalar(a, b) { - var x = a + b - var bv = x - a - var av = x - bv - var br = b - bv - var ar = a - av - var y = ar + br - if(y) { - return [y, x] - } - return [x] +function zeroVec(a) { + a[0] = a[1] = a[2] = 0 + return a } -function linearExpansionSum(e, f) { - var ne = e.length|0 - var nf = f.length|0 - if(ne === 1 && nf === 1) { - return scalarScalar(e[0], f[0]) - } - var n = ne + nf - var g = new Array(n) - var count = 0 - var eptr = 0 - var fptr = 0 - var abs = Math.abs - var ei = e[eptr] - var ea = abs(ei) - var fi = f[fptr] - var fa = abs(fi) - var a, b - if(ea < fa) { - b = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - b = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) +function augment(hg, af) { + hg[0] = af[0] + hg[1] = af[1] + hg[2] = af[2] + hg[3] = 1 + return hg +} + +function setComponent(out, v, i, x) { + out[0] = v[0] + out[1] = v[1] + out[2] = v[2] + out[i] = x + return out +} + +function getClipBounds(bounds) { + var result = CLIP_BOUNDS + for(var i=0; i<2; ++i) { + for(var j=0; j<3; ++j) { + result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8) } } - if((eptr < ne && ea < fa) || (fptr >= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } + return result +} + +function drawProject(shader, points, camera, transparent, forceDraw) { + var axesProject = points.axesProject + + var gl = points.gl + var uniforms = shader.uniforms + var model = camera.model || IDENTITY + var view = camera.view || IDENTITY + var projection = camera.projection || IDENTITY + var bounds = points.axesBounds + var clipBounds = getClipBounds(points.clipBounds) + + var cubeAxis + if(points.axes) { + cubeAxis = points.axes.lastCubeProps.axis } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } + cubeAxis = [1,1,1] } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } + + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + + shader.bind() + uniforms.view = view + uniforms.projection = projection + uniforms.screenSize = VIEW_SHAPE + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + uniforms.clipBounds = clipBounds + uniforms.pickGroup = points.pickId / 255.0 + uniforms.pixelRatio = points.pixelRatio + + for(var i=0; i<3; ++i) { + if(!axesProject[i]) { + continue } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + if((points.projectOpacity[i] < 1) !== transparent) { + continue } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + + uniforms.scale = points.projectScale[i] + uniforms.opacity = points.projectOpacity[i] + + //Project model matrix + var pmodel = SCRATCH_MATRIX + for(var j=0; j<16; ++j) { + pmodel[j] = 0 } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] + for(var j=0; j<4; ++j) { + pmodel[5*j] = 1 } - } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = f[fptr] + pmodel[5*i] = 0 + if(cubeAxis[i] < 0) { + pmodel[12+i] = bounds[0][i] + } else { + pmodel[12+i] = bounds[1][i] } - } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g -} -},{}],263:[function(require,module,exports){ -'use strict' + mat4mult(pmodel, model, pmodel) + uniforms.model = pmodel -module.exports = toSuperScript + //Compute initial axes + var u = (i+1)%3 + var v = (i+2)%3 + var du = zeroVec(U_VEC) + var dv = zeroVec(V_VEC) + du[u] = 1 + dv[v] = 1 -var SUPERSCRIPTS = { - ' ': ' ', - '0': '⁰', - '1': '¹', - '2': '²', - '3': '³', - '4': '⁴', - '5': '⁵', - '6': '⁶', - '7': '⁷', - '8': '⁸', - '9': '⁹', - '+': '⁺', - '-': '⁻', - 'a': 'ᵃ', - 'b': 'ᵇ', - 'c': 'ᶜ', - 'd': 'ᵈ', - 'e': 'ᵉ', - 'f': 'ᶠ', - 'g': 'ᵍ', - 'h': 'ʰ', - 'i': 'ⁱ', - 'j': 'ʲ', - 'k': 'ᵏ', - 'l': 'ˡ', - 'm': 'ᵐ', - 'n': 'ⁿ', - 'o': 'ᵒ', - 'p': 'ᵖ', - 'r': 'ʳ', - 's': 'ˢ', - 't': 'ᵗ', - 'u': 'ᵘ', - 'v': 'ᵛ', - 'w': 'ʷ', - 'x': 'ˣ', - 'y': 'ʸ', - 'z': 'ᶻ' -} + //Align orientation relative to viewer + var mdu = project(projection, view, model, augment(MU_VEC, du)) + var mdv = project(projection, view, model, augment(MV_VEC, dv)) + if(Math.abs(mdu[1]) > Math.abs(mdv[1])) { + var tmp = mdu + mdu = mdv + mdv = tmp + tmp = du + du = dv + dv = tmp + var t = u + u = v + v = t + } + if(mdu[0] < 0) { + du[u] = -1 + } + if(mdv[1] > 0) { + dv[v] = -1 + } + var su = 0.0 + var sv = 0.0 + for(var j=0; j<4; ++j) { + su += Math.pow(model[4*u+j], 2) + sv += Math.pow(model[4*v+j], 2) + } + du[u] /= Math.sqrt(su) + dv[v] /= Math.sqrt(sv) + uniforms.axes[0] = du + uniforms.axes[1] = dv -function toSuperScript(x) { - return x.split('').map(function(c) { - if(c in SUPERSCRIPTS) { - return SUPERSCRIPTS[c] + //Update fragment clip bounds + uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8) + uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8) + + //Draw interior + points.vao.draw(gl.TRIANGLES, points.vertexCount) + + //Draw edges + if(points.lineWidth > 0) { + gl.lineWidth(points.lineWidth) + points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) } - return '' - }).join('') + } } -},{}],264:[function(require,module,exports){ -"use strict" -var pool = require("typedarray-pool") +var NEG_INFINITY3 = [-1e8, -1e8, -1e8] +var POS_INFINITY3 = [1e8, 1e8, 1e8] +var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] -module.exports = createSurfaceExtractor +function drawFull(shader, pshader, points, camera, transparent, forceDraw) { + var gl = points.gl -//Helper macros -function array(i) { - return "a" + i -} -function data(i) { - return "d" + i -} -function cube(i,bitmask) { - return "c" + i + "_" + bitmask -} -function shape(i) { - return "s" + i -} -function stride(i,j) { - return "t" + i + "_" + j -} -function offset(i) { - return "o" + i -} -function scalar(i) { - return "x" + i -} -function pointer(i) { - return "p" + i -} -function delta(i,bitmask) { - return "d" + i + "_" + bitmask -} -function index(i) { - return "i" + i -} -function step(i,j) { - return "u" + i + "_" + j -} -function pcube(bitmask) { - return "b" + bitmask + points.vao.bind() + + if(transparent === (points.opacity < 1) || forceDraw) { + shader.bind() + var uniforms = shader.uniforms + + uniforms.model = camera.model || IDENTITY + uniforms.view = camera.view || IDENTITY + uniforms.projection = camera.projection || IDENTITY + + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + uniforms.screenSize = VIEW_SHAPE + + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale + + uniforms.fragClipBounds = CLIP_GROUP + uniforms.clipBounds = points.axes.bounds + + uniforms.opacity = points.opacity + uniforms.pickGroup = points.pickId / 255.0 + + uniforms.pixelRatio = points.pixelRatio + + //Draw interior + points.vao.draw(gl.TRIANGLES, points.vertexCount) + + //Draw edges + if(points.lineWidth > 0) { + gl.lineWidth(points.lineWidth) + points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) + } + } + + drawProject(pshader, points, camera, transparent, forceDraw) + + points.vao.unbind() } -function qcube(bitmask) { - return "y" + bitmask + +proto.draw = function(camera) { + var shader = this.useOrtho ? this.orthoShader : this.shader + drawFull(shader, this.projectShader, this, camera, false, false) } -function pdelta(bitmask) { - return "e" + bitmask + +proto.drawTransparent = function(camera) { + var shader = this.useOrtho ? this.orthoShader : this.shader + drawFull(shader, this.projectShader, this, camera, true, false) } -function vert(i) { - return "v" + i + +proto.drawPick = function(camera) { + var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader + drawFull(shader, this.pickProjectShader, this, camera, false, true) } -var VERTEX_IDS = "V" -var PHASES = "P" -var VERTEX_COUNT = "N" -var POOL_SIZE = "Q" -var POINTER = "X" -var TEMPORARY = "T" -function permBitmask(dimension, mask, order) { - var r = 0 - for(var i=0; i= this.pointCount || x < 0) { + return null } - return r -} -//Generates the surface procedure -function compileSurfaceProcedure(vertexFunc, faceFunc, phaseFunc, scalarArgs, order, typesig) { - var arrayArgs = typesig.length - var dimension = order.length + //Unpack result + var coord = this.points[x] + var result = this._selectResult + result.index = x + for(var i=0; i<3; ++i) { + result.position[i] = result.dataCoordinate[i] = coord[i] + } + return result +} - if(dimension < 2) { - throw new Error("ndarray-extract-contour: Dimension must be at least 2") +proto.highlight = function(selection) { + if(!selection) { + this.highlightId = [1,1,1,1] + } else { + var pointId = selection.index + var a0 = pointId &0xff + var a1 = (pointId>>8) &0xff + var a2 = (pointId>>16)&0xff + this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0] } +} - var funcName = "extractContour" + order.join("_") - var code = [] - var vars = [] - var args = [] +proto.update = function(options) { - //Assemble arguments - for(var i=0; i 0) { - stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) - } - vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + if('projectOpacity' in options) { + if(Array.isArray(options.projectOpacity)) { + this.projectOpacity = options.projectOpacity.slice() + } else { + var s = +options.projectOpacity + this.projectOpacity = [s,s,s] } } - //Create index variables - for(var i=0; i=0; --i) { - sizeVariable.push(shape(order[i])) + + //Set dirty flag + this.dirty = true + + //Create new buffers + var points = options.position + if(!points) { + return } - //Previous phases and vertex_ids - vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", - PHASES + "=mallocUint32(" + POOL_SIZE + ")", - VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", - POINTER + "=0") - //Create cube variables for phases - vars.push(pcube(0) + "=0") - for(var j=1; j<(1<=0; --i) { - forLoopBegin(i, 0) + var glyphData + if(Array.isArray(glyphs)) { + glyphData = getGlyph(glyphs[i], font) + } else if(glyphs) { + glyphData = getGlyph(glyphs, font) + } else { + glyphData = getGlyph('●', font) } - var phaseFuncArgs = [] - for(var i=0; i 0) { + textOffset[0] = -alignment[0] * (1+glyphBounds[0][0]) } - //Generate vertex - code.push("vertex(", vertexArgs.join(), ");", - vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;") + //Write out inner marker + var cells = glyphMesh.cells + var verts = glyphMesh.positions - //Check for face crossings - var base = (1<0; k=(k-1)&subset) { - faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") + for(var j=0; j0){", - index(order[i]), "=1;") - createLoop(i-1, mask|(1< 0") - } - if(typeof args.vertex !== "function") { - error("Must specify vertex creation function") - } - if(typeof args.cell !== "function") { - error("Must specify cell creation function") - } - if(typeof args.phase !== "function") { - error("Must specify phase function") - } - var getters = args.getters || [] - var typesig = new Array(arrays) - for(var i=0; i= 0) { - typesig[i] = true - } else { - typesig[i] = false - } - } - return compileSurfaceProcedure( - args.vertex, - args.cell, - args.phase, - scalars, - order, - typesig) +proto.dispose = function() { + //Shaders + this.shader.dispose() + this.orthoShader.dispose() + this.pickPerspectiveShader.dispose() + this.pickOrthoShader.dispose() + + //Vertex array + this.vao.dispose() + + //Buffers + this.pointBuffer.dispose() + this.colorBuffer.dispose() + this.glyphBuffer.dispose() + this.idBuffer.dispose() } -},{"typedarray-pool":278}],265:[function(require,module,exports){ -// transliterated from the python snippet here: -// http://en.wikipedia.org/wiki/Lanczos_approximation -var g = 7; -var p = [ - 0.99999999999980993, - 676.5203681218851, - -1259.1392167224028, - 771.32342877765313, - -176.61502916214059, - 12.507343278686905, - -0.13857109526572012, - 9.9843695780195716e-6, - 1.5056327351493116e-7 -]; +function createPointCloud(options) { + var gl = options.gl -var g_ln = 607/128; -var p_ln = [ - 0.99999999999999709182, - 57.156235665862923517, - -59.597960355475491248, - 14.136097974741747174, - -0.49191381609762019978, - 0.33994649984811888699e-4, - 0.46523628927048575665e-4, - -0.98374475304879564677e-4, - 0.15808870322491248884e-3, - -0.21026444172410488319e-3, - 0.21743961811521264320e-3, - -0.16431810653676389022e-3, - 0.84418223983852743293e-4, - -0.26190838401581408670e-4, - 0.36899182659531622704e-5 -]; + var shader = shaders.createPerspective(gl) + var orthoShader = shaders.createOrtho(gl) + var projectShader = shaders.createProject(gl) + var pickPerspectiveShader = shaders.createPickPerspective(gl) + var pickOrthoShader = shaders.createPickOrtho(gl) + var pickProjectShader = shaders.createPickProject(gl) -// Spouge approximation (suitable for large arguments) -function lngamma(z) { + var pointBuffer = createBuffer(gl) + var colorBuffer = createBuffer(gl) + var glyphBuffer = createBuffer(gl) + var idBuffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + buffer: pointBuffer, + size: 3, + type: gl.FLOAT + }, + { + buffer: colorBuffer, + size: 4, + type: gl.FLOAT + }, + { + buffer: glyphBuffer, + size: 2, + type: gl.FLOAT + }, + { + buffer: idBuffer, + size: 4, + type: gl.UNSIGNED_BYTE, + normalized: true + } + ]) - if(z < 0) return Number('0/0'); - var x = p_ln[0]; - for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); - var t = z + g_ln + 0.5; - return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); + var pointCloud = new PointCloud( + gl, + shader, + orthoShader, + projectShader, + pointBuffer, + colorBuffer, + glyphBuffer, + idBuffer, + vao, + pickPerspectiveShader, + pickOrthoShader, + pickProjectShader) + + pointCloud.update(options) + + return pointCloud } -module.exports = function gamma (z) { - if (z < 0.5) { - return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); - } - else if(z > 100) return Math.exp(lngamma(z)); - else { - z -= 1; - var x = p[0]; - for (var i = 1; i < g + 2; i++) { - x += p[i] / (z + i); - } - var t = z + g + 0.5; +},{"./lib/glyphs":782,"./lib/shaders":783,"gl-buffer":784,"gl-mat4/multiply":242,"gl-vao":814,"typedarray-pool":817}],906:[function(require,module,exports){ +'use strict' - return Math.sqrt(2 * Math.PI) - * Math.pow(t, z + 0.5) - * Math.exp(-t) - * x - ; - } -}; -module.exports.log = lngamma; -},{}],266:[function(require,module,exports){ -"use strict" +exports.boxVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n" +exports.boxFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n" -module.exports = permutationSign +},{}],907:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":910}],908:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],909:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],910:[function(require,module,exports){ +arguments[4][122][0].apply(exports,arguments) +},{"bit-twiddle":908,"buffer":65,"dup":122}],911:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":912,"./lib/create-attributes":913,"./lib/create-uniforms":914,"./lib/reflect":915,"./lib/runtime-reflect":916,"./lib/shader-cache":917,"dup":94}],912:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],913:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":912,"dup":96}],914:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":912,"./reflect":915,"dup":97}],915:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],916:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],917:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":912,"dup":100,"gl-format-compiler-error":918,"weakmap-shim":936}],918:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":919,"dup":101,"gl-constants/lookup":923,"glsl-shader-name":924,"sprintf-js":933}],919:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":920}],920:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":921}],921:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],922:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],923:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":922,"dup":106}],924:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":925,"dup":107,"glsl-tokenizer":932}],925:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],926:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":928,"./lib/builtins-300es":927,"./lib/literals":930,"./lib/literals-300es":929,"./lib/operators":931,"dup":109}],927:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":928,"dup":110}],928:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],929:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":930,"dup":112}],930:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],931:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],932:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":926,"dup":115}],933:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],934:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":935,"dup":117}],935:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],936:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":934,"dup":119}],937:[function(require,module,exports){ +'use strict' -var BRUTE_FORCE_CUTOFF = 32 +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') -var pool = require("typedarray-pool") +var SHADERS = require('./lib/shaders') -function permutationSign(p) { - var n = p.length - if(n < BRUTE_FORCE_CUTOFF) { - //Use quadratic algorithm for small n - var sgn = 1 - for(var i=0; i0; --i) { - t = pinv[i] - s = p[i] - p[i] = p[t] - p[t] = s - pinv[i] = pinv[s] - pinv[s] = t - r = (r + s) * i +proto.draw = function() { + if(!this.enabled) { + return } - pool.freeUint32(pinv) - pool.freeUint32(p) - return r -} -function unrank(n, r, p) { - switch(n) { - case 0: - if(p) { return p } - return [] - case 1: - if(p) { - p[0] = 0 - return p - } else { - return [0] - } - case 2: - if(p) { - if(r) { - p[0] = 0 - p[1] = 1 - } else { - p[0] = 1 - p[1] = 0 - } - return p - } else { - return r ? [0,1] : [1,0] - } - default: - break + var plot = this.plot + var selectBox = this.selectBox + var lineWidth = this.borderWidth + + var innerFill = this.innerFill + var innerColor = this.innerColor + var outerFill = this.outerFill + var outerColor = this.outerColor + var borderColor = this.borderColor + + var boxes = plot.box + var screenBox = plot.screenBox + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + + //Map select box into pixel coordinates + var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] + var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] + var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0] + var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1] + + loX = Math.max(loX, viewBox[0]) + loY = Math.max(loY, viewBox[1]) + hiX = Math.min(hiX, viewBox[2]) + hiY = Math.min(hiY, viewBox[3]) + + if(hiX < loX || hiY < loY) { + return } - p = p || new Array(n) - var s, t, i, nf=1 - p[0] = 0 - for(i=1; i0; --i) { - s = (r / nf)|0 - r = (r - s * nf)|0 - nf = (nf / i)|0 - t = p[i]|0 - p[i] = p[s]|0 - p[s] = t|0 + + if(this.innerFill) { + boxes.drawBox(loX, loY, hiX, hiY, innerColor) + } + + //Draw border + if(lineWidth > 0) { + + //Draw border + var w = lineWidth * pixelRatio + boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) + boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) + boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) + boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) } - return p } -exports.rank = rank -exports.unrank = unrank +proto.update = function(options) { + options = options || {} -},{"invert-permutation":268,"typedarray-pool":278}],268:[function(require,module,exports){ -"use strict" + this.innerFill = !!options.innerFill + this.outerFill = !!options.outerFill + this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() + this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() + this.borderColor = (options.borderColor || [0,0,0,1]).slice() + this.borderWidth = options.borderWidth || 0 + this.selectBox = (options.selectBox || this.selectBox).slice() +} -function invertPermutation(pi, result) { - result = result || new Array(pi.length) - for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", - "args": [{ - "name": "_inline_1_arg0_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg1_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg2_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg3_", - "lvalue": false, - "rvalue": true, - "count": 2 - }, { - "name": "_inline_1_arg4_", - "lvalue": false, - "rvalue": true, - "count": 1 - }], - "thisVars": [], - "localVars": ["_inline_1_da", "_inline_1_db"] - }, - funcName: 'zeroCrossings' -}) -},{"cwise-compiler":109}],271:[function(require,module,exports){ -"use strict" +proto.dispose = function() { + this.plot.removeOverlay(this) +} -module.exports = findZeroCrossings +function createSpikes2D(plot, options) { + var spikes = new GLSpikes2D(plot) + spikes.update(options) + plot.addOverlay(spikes) + return spikes +} -var core = require("./lib/zc-core") +},{}],939:[function(require,module,exports){ +var createShader = require('gl-shader') -function findZeroCrossings(array, level) { - var cross = [] - level = +level || 0.0 - core(array.hi(array.shape[0]-1), cross, level) - return cross + +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n" +var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n" +var pickSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n" + +exports.createShader = function (gl) { + var shader = createShader(gl, vertSrc, fragSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + shader.attributes.normal.location = 2 + return shader +} +exports.createPickShader = function (gl) { + var shader = createShader(gl, vertSrc, pickSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + shader.attributes.normal.location = 2 + return shader +} +exports.createContourShader = function (gl) { + var shader = createShader(gl, contourVertSrc, fragSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'float'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + return shader +} +exports.createPickContourShader = function (gl) { + var shader = createShader(gl, contourVertSrc, pickSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'float'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + return shader } -},{"./lib/zc-core":270}],272:[function(require,module,exports){ -"use strict" -module.exports = surfaceNets +},{"gl-shader":947}],940:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],941:[function(require,module,exports){ +arguments[4][77][0].apply(exports,arguments) +},{"dup":77}],942:[function(require,module,exports){ +arguments[4][262][0].apply(exports,arguments) +},{"dup":262}],943:[function(require,module,exports){ +arguments[4][263][0].apply(exports,arguments) +},{"./colorScales":942,"arraytools":64,"clone":944,"dup":263}],944:[function(require,module,exports){ +arguments[4][264][0].apply(exports,arguments) +},{"buffer":65,"dup":264}],945:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],946:[function(require,module,exports){ +arguments[4][93][0].apply(exports,arguments) +},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":1002}],947:[function(require,module,exports){ +arguments[4][94][0].apply(exports,arguments) +},{"./lib/GLError":948,"./lib/create-attributes":949,"./lib/create-uniforms":950,"./lib/reflect":951,"./lib/runtime-reflect":952,"./lib/shader-cache":953,"dup":94}],948:[function(require,module,exports){ +arguments[4][95][0].apply(exports,arguments) +},{"dup":95}],949:[function(require,module,exports){ +arguments[4][96][0].apply(exports,arguments) +},{"./GLError":948,"dup":96}],950:[function(require,module,exports){ +arguments[4][97][0].apply(exports,arguments) +},{"./GLError":948,"./reflect":951,"dup":97}],951:[function(require,module,exports){ +arguments[4][98][0].apply(exports,arguments) +},{"dup":98}],952:[function(require,module,exports){ +arguments[4][99][0].apply(exports,arguments) +},{"dup":99}],953:[function(require,module,exports){ +arguments[4][100][0].apply(exports,arguments) +},{"./GLError":948,"dup":100,"gl-format-compiler-error":954,"weakmap-shim":972}],954:[function(require,module,exports){ +arguments[4][101][0].apply(exports,arguments) +},{"add-line-numbers":955,"dup":101,"gl-constants/lookup":959,"glsl-shader-name":960,"sprintf-js":969}],955:[function(require,module,exports){ +arguments[4][102][0].apply(exports,arguments) +},{"dup":102,"pad-left":956}],956:[function(require,module,exports){ +arguments[4][103][0].apply(exports,arguments) +},{"dup":103,"repeat-string":957}],957:[function(require,module,exports){ +arguments[4][104][0].apply(exports,arguments) +},{"dup":104}],958:[function(require,module,exports){ +arguments[4][105][0].apply(exports,arguments) +},{"dup":105}],959:[function(require,module,exports){ +arguments[4][106][0].apply(exports,arguments) +},{"./1.0/numbers":958,"dup":106}],960:[function(require,module,exports){ +arguments[4][107][0].apply(exports,arguments) +},{"atob-lite":961,"dup":107,"glsl-tokenizer":968}],961:[function(require,module,exports){ +arguments[4][108][0].apply(exports,arguments) +},{"dup":108}],962:[function(require,module,exports){ +arguments[4][109][0].apply(exports,arguments) +},{"./lib/builtins":964,"./lib/builtins-300es":963,"./lib/literals":966,"./lib/literals-300es":965,"./lib/operators":967,"dup":109}],963:[function(require,module,exports){ +arguments[4][110][0].apply(exports,arguments) +},{"./builtins":964,"dup":110}],964:[function(require,module,exports){ +arguments[4][111][0].apply(exports,arguments) +},{"dup":111}],965:[function(require,module,exports){ +arguments[4][112][0].apply(exports,arguments) +},{"./literals":966,"dup":112}],966:[function(require,module,exports){ +arguments[4][113][0].apply(exports,arguments) +},{"dup":113}],967:[function(require,module,exports){ +arguments[4][114][0].apply(exports,arguments) +},{"dup":114}],968:[function(require,module,exports){ +arguments[4][115][0].apply(exports,arguments) +},{"./index":962,"dup":115}],969:[function(require,module,exports){ +arguments[4][116][0].apply(exports,arguments) +},{"dup":116}],970:[function(require,module,exports){ +arguments[4][117][0].apply(exports,arguments) +},{"./hidden-store.js":971,"dup":117}],971:[function(require,module,exports){ +arguments[4][118][0].apply(exports,arguments) +},{"dup":118}],972:[function(require,module,exports){ +arguments[4][119][0].apply(exports,arguments) +},{"./create-store.js":970,"dup":119}],973:[function(require,module,exports){ +arguments[4][188][0].apply(exports,arguments) +},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":1002}],974:[function(require,module,exports){ +arguments[4][154][0].apply(exports,arguments) +},{"dup":154}],975:[function(require,module,exports){ +arguments[4][155][0].apply(exports,arguments) +},{"./do-bind.js":974,"dup":155}],976:[function(require,module,exports){ +arguments[4][156][0].apply(exports,arguments) +},{"./do-bind.js":974,"dup":156}],977:[function(require,module,exports){ +arguments[4][157][0].apply(exports,arguments) +},{"./lib/vao-emulated.js":975,"./lib/vao-native.js":976,"dup":157}],978:[function(require,module,exports){ +'use strict' -var generateContourExtractor = require("ndarray-extract-contour") -var triangulateCube = require("triangulate-hypercube") -var zeroCrossings = require("zero-crossings") +module.exports = gradient -function buildSurfaceNets(order, dtype) { - var dimension = order.length - var code = ["'use strict';"] - var funcName = "surfaceNets" + order.join("_") + "d" + dtype +var dup = require('dup') +var cwiseCompiler = require('cwise-compiler') - //Contour extraction function - code.push( - "var contour=genContour({", - "order:[", order.join(), "],", - "scalarArguments: 3,", - "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },") - if(dtype === "generic") { - code.push("getters:[0],") - } +var TEMPLATE_CACHE = {} +var GRADIENT_CACHE = {} - //Generate vertex function - var cubeArgs = [] - var extraArgs = [] - for(var i=0; i>>7){") + var args = [ 'array' ] + var names = ['junk'] + for(var i=0; i 128) { - if((i%128)===0) { - if(extraFuncs.length > 0) { - currentFunc.push("}}") + return TEMPLATE_CACHE[d] = cwiseCompiler({ + args: args, + pre: EmptyProc, + post: EmptyProc, + body: { + body: code.join(''), + args: names.map(function(n) { + return { + name: n, + lvalue: n.indexOf('out') === 0, + rvalue: n.indexOf('inp') === 0, + count: (n!=='junk')|0 } - var efName = "vExtra" + extraFuncs.length - code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") - currentFunc = [ - "function ", efName, "(m,", extraArgs.join(), "){switch(m){" - ] - extraFuncs.push(currentFunc) - } + }), + thisVars: [], + localVars: [] + }, + funcName: 'fdTemplate' + d + }) +} + +function generateGradient(boundaryConditions) { + var token = boundaryConditions.join() + var proc = GRADIENT_CACHE[token] + if(proc) { + return proc + } + + var d = boundaryConditions.length + var code = ['function gradient(dst,src){var s=src.shape.slice();' ] + + function handleBoundary(facet) { + var cod = d - facet.length + + var loStr = [] + var hiStr = [] + var pickStr = [] + for(var i=0; i= 0) { + pickStr.push('0') + } else if(facet.indexOf(-(i+1)) >= 0) { + pickStr.push('s['+i+']-1') + } else { + pickStr.push('-1') + loStr.push('1') + hiStr.push('s['+i+']-2') + } } - currentFunc.push("case ", (i&0x7f), ":") - var crossings = new Array(dimension) - var denoms = new Array(dimension) - var crossingCount = new Array(dimension) - var bias = new Array(dimension) - var totalCrossings = 0 - for(var j=0; j j) { + + if(cod > 0) { + code.push('if(1') + for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { continue } - if(!(i&(1<2') + } + code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) + for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { + continue + } + code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr) + } + code.push(');') + } + + for(var i=0; i1){dst.set(', + pickStr.join(), ',', bnd, ',0.5*(src.get(', + cPickStr.join(), ')-src.get(', + dPickStr.join(), ')))}else{dst.set(', + pickStr.join(), ',', bnd, ',0)};') } else { - denoms[k].push("v" + j + "-v" + u) - sign = -sign + code.push('if(s[', bnd, ']>1){diff(', outStr, + ',src.pick(', cPickStr.join(), ')', boundStr, + ',src.pick(', dPickStr.join(), ')', boundStr, + ');}else{zero(', outStr, ');};') } - if(sign < 0) { - crossings[k].push("-v" + j + "-v" + u) - crossingCount[k] += 2 + break + + case 'mirror': + if(cod === 0) { + code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') } else { - crossings[k].push("v" + j + "+v" + u) - crossingCount[k] -= 2 + code.push('zero(', outStr, ');') } - totalCrossings += 1 - for(var l=0; l2){dst.set(', + pickStr.join(), ',', bnd, ',0.5*(src.get(', + aPickStr.join(), ')-src.get(', + bPickStr.join(), ')))}else{dst.set(', + pickStr.join(), ',', bnd, ',0)};') + } else { + code.push('if(s[', bnd, ']>2){diff(', outStr, + ',src.pick(', aPickStr.join(), ')', boundStr, + ',src.pick(', bPickStr.join(), ')', boundStr, + ');}else{zero(', outStr, ');};') + } + break + + default: + throw new Error('ndarray-gradient: Invalid boundary condition') } } - var vertexStr = [] - for(var k=0; k 0) { - cStr = "+" + crossingCount[k] + "*c" - } - var weight = 0.5 * (crossings[k].length / totalCrossings) - var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) - vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") - - } + + if(cod > 0) { + code.push('};') } - currentFunc.push("a.push([", vertexStr.join(), "]);", - "break;") - } - code.push("}},") - if(extraFuncs.length > 0) { - currentFunc.push("}}") } - //Create face function - var faceArgs = [] - for(var i=0; i<(1<<(dimension-1)); ++i) { - faceArgs.push("v" + i) + //Enumerate ridges, facets, etc. of hypercube + for(var i=0; i<(1<0) { - shapeX += 0.02 - } - } +},{"./doConvert.js":984,"ndarray":1031}],984:[function(require,module,exports){ +module.exports=require('cwise-compiler')({"args":["array","scalar","index"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}","args":[{"name":"_inline_1_arg0_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":4}],"thisVars":[],"localVars":["_inline_1_i","_inline_1_v"]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"funcName":"convert","blockSize":64}) - var data = new Float32Array(bufferSize) - var ptr = 0 - var xOffset = -0.5 * shapeX - for(var i=0; i= 0; - var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); + this.showContour = true + this.showSurface = true - if (needsAlphaFormat) { - // Special case for "transparent", all other non-alpha formats - // will return rgba when there is transparency. - if (format === "name" && this._a === 0) { - return this.toName(); - } - return this.toRgbString(); - } - if (format === "rgb") { - formattedString = this.toRgbString(); - } - if (format === "prgb") { - formattedString = this.toPercentageRgbString(); - } - if (format === "hex" || format === "hex6") { - formattedString = this.toHexString(); - } - if (format === "hex3") { - formattedString = this.toHexString(true); - } - if (format === "hex8") { - formattedString = this.toHex8String(); - } - if (format === "name") { - formattedString = this.toName(); - } - if (format === "hsl") { - formattedString = this.toHslString(); - } - if (format === "hsv") { - formattedString = this.toHsvString(); - } + this.enableHighlight = [true, true, true] + this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]] + this.highlightTint = [ 1, 1, 1 ] + this.highlightLevel = [-1, -1, -1] - return formattedString || this.toHexString(); - }, - clone: function() { - return tinycolor(this.toString()); - }, + // Dynamic contour options + this.enableDynamic = [ true, true, true ] + this.dynamicLevel = [ NaN, NaN, NaN ] + this.dynamicColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ] + this.dynamicTint = [ 1, 1, 1 ] + this.dynamicWidth = [ 1, 1, 1 ] - _applyModification: function(fn, args) { - var color = fn.apply(null, [this].concat([].slice.call(args))); - this._r = color._r; - this._g = color._g; - this._b = color._b; - this.setAlpha(color._a); - return this; - }, - lighten: function() { - return this._applyModification(lighten, arguments); - }, - brighten: function() { - return this._applyModification(brighten, arguments); - }, - darken: function() { - return this._applyModification(darken, arguments); - }, - desaturate: function() { - return this._applyModification(desaturate, arguments); - }, - saturate: function() { - return this._applyModification(saturate, arguments); - }, - greyscale: function() { - return this._applyModification(greyscale, arguments); - }, - spin: function() { - return this._applyModification(spin, arguments); - }, + this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]] + this.surfaceProject = [ false, false, false ] + this.contourProject = [[ false, false, false ], + [ false, false, false ], + [ false, false, false ]] - _applyCombination: function(fn, args) { - return fn.apply(null, [this].concat([].slice.call(args))); - }, - analogous: function() { - return this._applyCombination(analogous, arguments); - }, - complement: function() { - return this._applyCombination(complement, arguments); - }, - monochromatic: function() { - return this._applyCombination(monochromatic, arguments); - }, - splitcomplement: function() { - return this._applyCombination(splitcomplement, arguments); - }, - triad: function() { - return this._applyCombination(triad, arguments); - }, - tetrad: function() { - return this._applyCombination(tetrad, arguments); - } -}; + this.colorBounds = [ false, false ] -// If input is an object, force 1 into "1.0" to handle ratios properly -// String input requires "1.0" as input, so 1 will be treated as 1 -tinycolor.fromRatio = function(color, opts) { - if (typeof color == "object") { - var newColor = {}; - for (var i in color) { - if (color.hasOwnProperty(i)) { - if (i === "a") { - newColor[i] = color[i]; - } - else { - newColor[i] = convertToPercentage(color[i]); - } - } - } - color = newColor; + // Store xyz fields, need this for picking + this._field = [ + ndarray(pool.mallocFloat(1024), [0, 0]), + ndarray(pool.mallocFloat(1024), [0, 0]), + ndarray(pool.mallocFloat(1024), [0, 0]) ] + + this.pickId = 1 + this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]] + + this.snapToData = false + + this.opacity = 1.0 + + this.lightPosition = [10, 10000, 0] + this.ambientLight = 0.8 + this.diffuseLight = 0.8 + this.specularLight = 2.0 + this.roughness = 0.5 + this.fresnel = 1.5 + + this.dirty = true +} + +var proto = SurfacePlot.prototype + +proto.isTransparent = function () { + return this.opacity < 1 +} + +proto.isOpaque = function () { + if (this.opacity >= 1) { + return true + } + for (var i = 0; i < 3; ++i) { + if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) { + return true } + } + return false +} - return tinycolor(color, opts); -}; +proto.pickSlots = 1 -// Given a string or object, convert that input to RGB -// Possible string inputs: -// -// "red" -// "#f00" or "f00" -// "#ff0000" or "ff0000" -// "#ff000000" or "ff000000" -// "rgb 255 0 0" or "rgb (255, 0, 0)" -// "rgb 1.0 0 0" or "rgb (1, 0, 0)" -// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" -// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" -// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" -// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" -// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" -// -function inputToRGB(color) { +proto.setPickBase = function (id) { + this.pickId = id +} - var rgb = { r: 0, g: 0, b: 0 }; - var a = 1; - var ok = false; - var format = false; +var ZERO_VEC = [0, 0, 0] - if (typeof color == "string") { - color = stringInputToObject(color); +var PROJECT_DATA = { + showSurface: false, + showContour: false, + projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()], + clipBounds: [ + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]]] +} + +function computeProjectionData (camera, obj) { + var i, j, k + + // Compute cube properties + var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC + + var showSurface = obj.showSurface + var showContour = obj.showContour + + for (i = 0; i < 3; ++i) { + showSurface = showSurface || obj.surfaceProject[i] + for (j = 0; j < 3; ++j) { + showContour = showContour || obj.contourProject[i][j] } + } - if (typeof color == "object") { - if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { - rgb = rgbToRgb(color.r, color.g, color.b); - ok = true; - format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; - } - else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { - color.s = convertToPercentage(color.s); - color.v = convertToPercentage(color.v); - rgb = hsvToRgb(color.h, color.s, color.v); - ok = true; - format = "hsv"; - } - else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { - color.s = convertToPercentage(color.s); - color.l = convertToPercentage(color.l); - rgb = hslToRgb(color.h, color.s, color.l); - ok = true; - format = "hsl"; - } + for (i = 0; i < 3; ++i) { + // Construct projection onto axis + var axisSquish = PROJECT_DATA.projections[i] + for (j = 0; j < 16; ++j) { + axisSquish[j] = 0 + } + for (j = 0; j < 4; ++j) { + axisSquish[5 * j] = 1 + } + axisSquish[5 * i] = 0 + axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] + multiply(axisSquish, camera.model, axisSquish) - if (color.hasOwnProperty("a")) { - a = color.a; - } + var nclipBounds = PROJECT_DATA.clipBounds[i] + for (k = 0; k < 2; ++k) { + for (j = 0; j < 3; ++j) { + nclipBounds[k][j] = camera.clipBounds[k][j] + } } + nclipBounds[0][i] = -1e8 + nclipBounds[1][i] = 1e8 + } - a = boundAlpha(a); + PROJECT_DATA.showSurface = showSurface + PROJECT_DATA.showContour = showContour - return { - ok: ok, - format: color.format || format, - r: mathMin(255, mathMax(rgb.r, 0)), - g: mathMin(255, mathMax(rgb.g, 0)), - b: mathMin(255, mathMax(rgb.b, 0)), - a: a - }; + return PROJECT_DATA } +var UNIFORMS = { + model: IDENTITY, + view: IDENTITY, + projection: IDENTITY, + inverseModel: IDENTITY.slice(), + lowerBound: [0, 0, 0], + upperBound: [0, 0, 0], + colorMap: 0, + clipBounds: [[0, 0, 0], [0, 0, 0]], + height: 0.0, + contourTint: 0, + contourColor: [0, 0, 0, 1], + permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], + zOffset: -1e-4, + kambient: 1, + kdiffuse: 1, + kspecular: 1, + lightPosition: [1000, 1000, 1000], + eyePosition: [0, 0, 0], + roughness: 1, + fresnel: 1, + opacity: 1 +} -// Conversion Functions -// -------------------- +var MATRIX_INVERSE = IDENTITY.slice() +var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] -// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: -// +function drawCore (params, transparent) { + params = params || {} + var gl = this.gl -// `rgbToRgb` -// Handle bounds / percentage checking to conform to CSS color spec -// -// *Assumes:* r, g, b in [0, 255] or [0, 1] -// *Returns:* { r, g, b } in [0, 255] -function rgbToRgb(r, g, b){ - return { - r: bound01(r, 255) * 255, - g: bound01(g, 255) * 255, - b: bound01(b, 255) * 255 - }; -} + gl.disable(gl.CULL_FACE) -// `rgbToHsl` -// Converts an RGB color value to HSL. -// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] -// *Returns:* { h, s, l } in [0,1] -function rgbToHsl(r, g, b) { + this._colorMap.bind(0) - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); + var uniforms = UNIFORMS + uniforms.model = params.model || IDENTITY + uniforms.view = params.view || IDENTITY + uniforms.projection = params.projection || IDENTITY + uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] + uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] + uniforms.contourColor = this.contourColor[0] - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, l = (max + min) / 2; + uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model) - if(max == min) { - h = s = 0; // achromatic + for (var i = 0; i < 2; ++i) { + var clipClamped = uniforms.clipBounds[i] + for (var j = 0; j < 3; ++j) { + clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) } - else { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } + } - h /= 6; + uniforms.kambient = this.ambientLight + uniforms.kdiffuse = this.diffuseLight + uniforms.kspecular = this.specularLight + + uniforms.roughness = this.roughness + uniforms.fresnel = this.fresnel + uniforms.opacity = this.opacity + + uniforms.height = 0.0 + uniforms.permutation = DEFAULT_PERM + + // Compute camera matrix inverse + var invCameraMatrix = MATRIX_INVERSE + multiply(invCameraMatrix, uniforms.view, uniforms.model) + multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) + invert(invCameraMatrix, invCameraMatrix) + + for (i = 0; i < 3; ++i) { + uniforms.eyePosition[i] = invCameraMatrix[12 + i] / invCameraMatrix[15] + } + + var w = invCameraMatrix[15] + for (i = 0; i < 3; ++i) { + w += this.lightPosition[i] * invCameraMatrix[4 * i + 3] + } + for (i = 0; i < 3; ++i) { + var s = invCameraMatrix[12 + i] + for (j = 0; j < 3; ++j) { + s += invCameraMatrix[4 * j + i] * this.lightPosition[j] } + uniforms.lightPosition[i] = s / w + } - return { h: h, s: s, l: l }; -} + var projectData = computeProjectionData(uniforms, this) -// `hslToRgb` -// Converts an HSL color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] -function hslToRgb(h, s, l) { - var r, g, b; + if (projectData.showSurface && (transparent === (this.opacity < 1))) { + // Set up uniforms + this._shader.bind() + this._shader.uniforms = uniforms - h = bound01(h, 360); - s = bound01(s, 100); - l = bound01(l, 100); + // Draw it + this._vao.bind() - function hue2rgb(p, q, t) { - if(t < 0) t += 1; - if(t > 1) t -= 1; - if(t < 1/6) return p + (q - p) * 6 * t; - if(t < 1/2) return q; - if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; + if (this.showSurface && this._vertexCount) { + this._vao.draw(gl.TRIANGLES, this._vertexCount) } - if(s === 0) { - r = g = b = l; // achromatic + // Draw projections of surface + for (i = 0; i < 3; ++i) { + if (!this.surfaceProject[i] || !this.vertexCount) { + continue + } + this._shader.uniforms.model = projectData.projections[i] + this._shader.uniforms.clipBounds = projectData.clipBounds[i] + this._vao.draw(gl.TRIANGLES, this._vertexCount) } - else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); + + this._vao.unbind() + } + + if (projectData.showContour && !transparent) { + var shader = this._contourShader + + // Don't apply lighting to contours + uniforms.kambient = 1.0 + uniforms.kdiffuse = 0.0 + uniforms.kspecular = 0.0 + uniforms.opacity = 1.0 + + shader.bind() + shader.uniforms = uniforms + + // Draw contour lines + var vao = this._contourVAO + vao.bind() + + // Draw contour levels + for (i = 0; i < 3; ++i) { + shader.uniforms.permutation = PERMUTATIONS[i] + gl.lineWidth(this.contourWidth[i]) + + for (j = 0; j < this.contourLevels[i].length; ++j) { + if (!this._contourCounts[i][j]) { + continue + } + if (j === this.highlightLevel[i]) { + shader.uniforms.contourColor = this.highlightColor[i] + shader.uniforms.contourTint = this.highlightTint[i] + } else if (j === 0 || (j - 1) === this.highlightLevel[i]) { + shader.uniforms.contourColor = this.contourColor[i] + shader.uniforms.contourTint = this.contourTint[i] + } + shader.uniforms.height = this.contourLevels[i][j] + vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j]) + } + } + + // Draw projections of surface + for (i = 0; i < 3; ++i) { + shader.uniforms.model = projectData.projections[i] + shader.uniforms.clipBounds = projectData.clipBounds[i] + for (j = 0; j < 3; ++j) { + if (!this.contourProject[i][j]) { + continue + } + shader.uniforms.permutation = PERMUTATIONS[j] + gl.lineWidth(this.contourWidth[j]) + for (var k = 0; k < this.contourLevels[j].length; ++k) { + if (k === this.highlightLevel[j]) { + shader.uniforms.contourColor = this.highlightColor[j] + shader.uniforms.contourTint = this.highlightTint[j] + } else if (k === 0 || (k - 1) === this.highlightLevel[j]) { + shader.uniforms.contourColor = this.contourColor[j] + shader.uniforms.contourTint = this.contourTint[j] + } + shader.uniforms.height = this.contourLevels[j][k] + vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) + } + } } - return { r: r * 255, g: g * 255, b: b * 255 }; -} - -// `rgbToHsv` -// Converts an RGB color value to HSV -// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] -// *Returns:* { h, s, v } in [0,1] -function rgbToHsv(r, g, b) { + // Draw dynamic contours + vao = this._dynamicVAO + vao.bind() - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); + // Draw contour levels + for (i = 0; i < 3; ++i) { + if (this._dynamicCounts[i] === 0) { + continue + } - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, v = max; + shader.uniforms.model = uniforms.model + shader.uniforms.clipBounds = uniforms.clipBounds + shader.uniforms.permutation = PERMUTATIONS[i] + gl.lineWidth(this.dynamicWidth[i]) - var d = max - min; - s = max === 0 ? 0 : d / max; + shader.uniforms.contourColor = this.dynamicColor[i] + shader.uniforms.contourTint = this.dynamicTint[i] + shader.uniforms.height = this.dynamicLevel[i] + vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - if(max == min) { - h = 0; // achromatic - } - else { - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; + for (j = 0; j < 3; ++j) { + if (!this.contourProject[j][i]) { + continue } - h /= 6; + + shader.uniforms.model = projectData.projections[j] + shader.uniforms.clipBounds = projectData.clipBounds[j] + vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) + } } - return { h: h, s: s, v: v }; -} -// `hsvToRgb` -// Converts an HSV color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] - function hsvToRgb(h, s, v) { + vao.unbind() + } +} - h = bound01(h, 360) * 6; - s = bound01(s, 100); - v = bound01(v, 100); +proto.draw = function (params) { + return drawCore.call(this, params, false) +} - var i = math.floor(h), - f = h - i, - p = v * (1 - s), - q = v * (1 - f * s), - t = v * (1 - (1 - f) * s), - mod = i % 6, - r = [v, q, p, p, t, v][mod], - g = [t, v, v, q, p, p][mod], - b = [p, p, t, v, v, q][mod]; +proto.drawTransparent = function (params) { + return drawCore.call(this, params, true) +} - return { r: r * 255, g: g * 255, b: b * 255 }; +var PICK_UNIFORMS = { + model: IDENTITY, + view: IDENTITY, + projection: IDENTITY, + inverseModel: IDENTITY, + clipBounds: [[0, 0, 0], [0, 0, 0]], + height: 0.0, + shape: [0, 0], + pickId: 0, + lowerBound: [0, 0, 0], + upperBound: [0, 0, 0], + zOffset: 0.0, + permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], + lightPosition: [0, 0, 0], + eyePosition: [0, 0, 0] } -// `rgbToHex` -// Converts an RGB color to hex -// Assumes r, g, and b are contained in the set [0, 255] -// Returns a 3 or 6 character hex -function rgbToHex(r, g, b, allow3Char) { +proto.drawPick = function (params) { + params = params || {} + var gl = this.gl + gl.disable(gl.CULL_FACE) - var hex = [ - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + var uniforms = PICK_UNIFORMS + uniforms.model = params.model || IDENTITY + uniforms.view = params.view || IDENTITY + uniforms.projection = params.projection || IDENTITY + uniforms.shape = this._field[2].shape + uniforms.pickId = this.pickId / 255.0 + uniforms.lowerBound = this.bounds[0] + uniforms.upperBound = this.bounds[1] + uniforms.permutation = DEFAULT_PERM - // Return a 3 character hex if possible - if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { - return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + for (var i = 0; i < 2; ++i) { + var clipClamped = uniforms.clipBounds[i] + for (var j = 0; j < 3; ++j) { + clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) } + } - return hex.join(""); -} + var projectData = computeProjectionData(uniforms, this) -// `rgbaToHex` -// Converts an RGBA color plus alpha transparency to hex -// Assumes r, g, b and a are contained in the set [0, 255] -// Returns an 8 character hex -function rgbaToHex(r, g, b, a) { + if (projectData.showSurface) { + // Set up uniforms + this._pickShader.bind() + this._pickShader.uniforms = uniforms - var hex = [ - pad2(convertDecimalToHex(a)), - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + // Draw it + this._vao.bind() + this._vao.draw(gl.TRIANGLES, this._vertexCount) - return hex.join(""); -} + // Draw projections of surface + for (i = 0; i < 3; ++i) { + if (!this.surfaceProject[i]) { + continue + } + this._pickShader.uniforms.model = projectData.projections[i] + this._pickShader.uniforms.clipBounds = projectData.clipBounds[i] + this._vao.draw(gl.TRIANGLES, this._vertexCount) + } -// `equals` -// Can be called with any tinycolor input -tinycolor.equals = function (color1, color2) { - if (!color1 || !color2) { return false; } - return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); -}; + this._vao.unbind() + } -tinycolor.random = function() { - return tinycolor.fromRatio({ - r: mathRandom(), - g: mathRandom(), - b: mathRandom() - }); -}; + if (projectData.showContour) { + var shader = this._contourPickShader + shader.bind() + shader.uniforms = uniforms -// Modification Functions -// ---------------------- -// Thanks to less.js for some of the basics here -// + var vao = this._contourVAO + vao.bind() -function desaturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s -= amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} + for (j = 0; j < 3; ++j) { + gl.lineWidth(this.contourWidth[j]) + shader.uniforms.permutation = PERMUTATIONS[j] + for (i = 0; i < this.contourLevels[j].length; ++i) { + if (this._contourCounts[j][i]) { + shader.uniforms.height = this.contourLevels[j][i] + vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i]) + } + } + } -function saturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s += amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} + // Draw projections of surface + for (i = 0; i < 3; ++i) { + shader.uniforms.model = projectData.projections[i] + shader.uniforms.clipBounds = projectData.clipBounds[i] -function greyscale(color) { - return tinycolor(color).desaturate(100); -} + for (j = 0; j < 3; ++j) { + if (!this.contourProject[i][j]) { + continue + } -function lighten (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l += amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); -} + shader.uniforms.permutation = PERMUTATIONS[j] + gl.lineWidth(this.contourWidth[j]) + for (var k = 0; k < this.contourLevels[j].length; ++k) { + if (this._contourCounts[j][k]) { + shader.uniforms.height = this.contourLevels[j][k] + vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) + } + } + } + } -function brighten(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var rgb = tinycolor(color).toRgb(); - rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); - rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); - rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); - return tinycolor(rgb); + vao.unbind() + } } -function darken (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l -= amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); -} +proto.pick = function (selection) { + if (!selection) { + return null + } -// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. -// Values outside of this range will be wrapped into this range. -function spin(color, amount) { - var hsl = tinycolor(color).toHsl(); - var hue = (mathRound(hsl.h) + amount) % 360; - hsl.h = hue < 0 ? 360 + hue : hue; - return tinycolor(hsl); -} + if (selection.id !== this.pickId) { + return null + } -// Combination Functions -// --------------------- -// Thanks to jQuery xColor for some of the ideas behind these -// + var shape = this._field[2].shape -function complement(color) { - var hsl = tinycolor(color).toHsl(); - hsl.h = (hsl.h + 180) % 360; - return tinycolor(hsl); -} + var result = this._pickResult -function triad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) - ]; -} + // Compute uv coordinate + var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0 + var ix = Math.floor(x) + var fx = x - ix -function tetrad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) - ]; -} + var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0 + var iy = Math.floor(y) + var fy = y - iy -function splitcomplement(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), - tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) - ]; -} + ix += 1 + iy += 1 -function analogous(color, results, slices) { - results = results || 6; - slices = slices || 30; + // Compute xyz coordinate + var pos = result.position + pos[0] = pos[1] = pos[2] = 0 + for (var dx = 0; dx < 2; ++dx) { + var s = dx ? fx : 1.0 - fx + for (var dy = 0; dy < 2; ++dy) { + var t = dy ? fy : 1.0 - fy - var hsl = tinycolor(color).toHsl(); - var part = 360 / slices; - var ret = [tinycolor(color)]; + var r = ix + dx + var c = iy + dy + var w = s * t - for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { - hsl.h = (hsl.h + part) % 360; - ret.push(tinycolor(hsl)); + for (var i = 0; i < 3; ++i) { + pos[i] += this._field[i].get(r, c) * w + } } - return ret; -} - -function monochromatic(color, results) { - results = results || 6; - var hsv = tinycolor(color).toHsv(); - var h = hsv.h, s = hsv.s, v = hsv.v; - var ret = []; - var modification = 1 / results; + } - while (results--) { - ret.push(tinycolor({ h: h, s: s, v: v})); - v = (v + modification) % 1; + // Find closest level + var levelIndex = this._pickResult.level + for (var j = 0; j < 3; ++j) { + levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j]) + if (levelIndex[j] < 0) { + if (this.contourLevels[j].length > 0) { + levelIndex[j] = 0 + } + } else if (levelIndex[j] < this.contourLevels[j].length - 1) { + var a = this.contourLevels[j][levelIndex[j]] + var b = this.contourLevels[j][levelIndex[j] + 1] + if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) { + levelIndex[j] += 1 + } } + } - return ret; -} - -// Utility Functions -// --------------------- + result.index[0] = fx < 0.5 ? ix : (ix + 1) + result.index[1] = fy < 0.5 ? iy : (iy + 1) -tinycolor.mix = function(color1, color2, amount) { - amount = (amount === 0) ? 0 : (amount || 50); + result.uv[0] = x / shape[0] + result.uv[1] = y / shape[1] - var rgb1 = tinycolor(color1).toRgb(); - var rgb2 = tinycolor(color2).toRgb(); + for (i = 0; i < 3; ++i) { + result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]) + } - var p = amount / 100; - var w = p * 2 - 1; - var a = rgb2.a - rgb1.a; + return result +} - var w1; +function padField (nfield, field) { + var shape = field.shape.slice() + var nshape = nfield.shape.slice() - if (w * a == -1) { - w1 = w; - } else { - w1 = (w + a) / (1 + w * a); - } + // Center + ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) - w1 = (w1 + 1) / 2; + // Edges + ops.assign(nfield.lo(1).hi(shape[0], 1), + field.hi(shape[0], 1)) + ops.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), + field.lo(0, shape[1] - 1).hi(shape[0], 1)) + ops.assign(nfield.lo(0, 1).hi(1, shape[1]), + field.hi(1)) + ops.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), + field.lo(shape[0] - 1)) + // Corners + nfield.set(0, 0, field.get(0, 0)) + nfield.set(0, nshape[1] - 1, field.get(0, shape[1] - 1)) + nfield.set(nshape[0] - 1, 0, field.get(shape[0] - 1, 0)) + nfield.set(nshape[0] - 1, nshape[1] - 1, field.get(shape[0] - 1, shape[1] - 1)) +} - var w2 = 1 - w1; +function handleArray (param, ctor) { + if (Array.isArray(param)) { + return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ] + } + return [ ctor(param), ctor(param), ctor(param) ] +} - var rgba = { - r: rgb2.r * w1 + rgb1.r * w2, - g: rgb2.g * w1 + rgb1.g * w2, - b: rgb2.b * w1 + rgb1.b * w2, - a: rgb2.a * p + rgb1.a * (1 - p) - }; +function toColor (x) { + if (Array.isArray(x)) { + if (x.length === 3) { + return [x[0], x[1], x[2], 1] + } + return [x[0], x[1], x[2], x[3]] + } + return [0, 0, 0, 1] +} - return tinycolor(rgba); -}; +function handleColor (param) { + if (Array.isArray(param)) { + if (Array.isArray(param)) { + return [ + toColor(param[0]), + toColor(param[1]), + toColor(param[2]) ] + } else { + var c = toColor(param) + return [ + c.slice(), + c.slice(), + c.slice() ] + } + } +} +proto.update = function (params) { + params = params || {} -// Readability Functions -// --------------------- -// false -// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false -tinycolor.isReadable = function(color1, color2, wcag2) { - var readability = tinycolor.readability(color1, color2); - var wcag2Parms, out; + if (!field) { + if (this._field[2].shape[0] || this._field[2].shape[2]) { + field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2) + } else { + field = this._field[2].hi(0, 0) + } + } - out = false; + // Update field + if ('field' in params || 'coords' in params) { + var fsize = (field.shape[0] + 2) * (field.shape[1] + 2) - wcag2Parms = validateWCAG2Parms(wcag2); - switch (wcag2Parms.level + wcag2Parms.size) { - case "AAsmall": - case "AAAlarge": - out = readability >= 4.5; - break; - case "AAlarge": - out = readability >= 3; - break; - case "AAAsmall": - out = readability >= 7; - break; + // Resize if necessary + if (fsize > this._field[2].data.length) { + pool.freeFloat(this._field[2].data) + this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize)) } - return out; -}; + // Pad field + this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) + padField(this._field[2], field) -// `mostReadable` -// Given a base color and a list of possible foreground or background -// colors for that base, returns the most readable color. -// Optionally returns Black or White if the most readable color is unreadable. -// *Example* -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" -tinycolor.mostReadable = function(baseColor, colorList, args) { - var bestColor = null; - var bestScore = 0; - var readability; - var includeFallbackColors, level, size ; - args = args || {}; - includeFallbackColors = args.includeFallbackColors ; - level = args.level; - size = args.size; + // Save shape of field + this.shape = field.shape.slice() + var shape = this.shape - for (var i= 0; i < colorList.length ; i++) { - readability = tinycolor.readability(baseColor, colorList[i]); - if (readability > bestScore) { - bestScore = readability; - bestColor = tinycolor(colorList[i]); - } + // Resize coordinate fields if necessary + for (var i = 0; i < 2; ++i) { + if (this._field[2].size > this._field[i].data.length) { + pool.freeFloat(this._field[i].data) + this._field[i].data = pool.mallocFloat(this._field[2].size) + } + this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]) } - if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { - return bestColor; - } - else { - args.includeFallbackColors=false; - return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); + // Generate x/y coordinates + if (params.coords) { + var coords = params.coords + if (!Array.isArray(coords) || coords.length !== 3) { + throw new Error('gl-surface: invalid coordinates for x/y') + } + for (i = 0; i < 2; ++i) { + var coord = coords[i] + for (j = 0; j < 2; ++j) { + if (coord.shape[j] !== shape[j]) { + throw new Error('gl-surface: coords have incorrect shape') + } + } + padField(this._field[i], coord) + } + } else if (params.ticks) { + var ticks = params.ticks + if (!Array.isArray(ticks) || ticks.length !== 2) { + throw new Error('gl-surface: invalid ticks') + } + for (i = 0; i < 2; ++i) { + var tick = ticks[i] + if (Array.isArray(tick) || tick.length) { + tick = ndarray(tick) + } + if (tick.shape[0] !== shape[i]) { + throw new Error('gl-surface: invalid tick length') + } + // Make a copy view of the tick array + var tick2 = ndarray(tick.data, shape) + tick2.stride[i] = tick.stride[0] + tick2.stride[i ^ 1] = 0 + + // Fill in field array + padField(this._field[i], tick2) + } + } else { + for (i = 0; i < 2; ++i) { + var offset = [0, 0] + offset[i] = 1 + this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) + } + this._field[0].set(0, 0, 0) + for (var j = 0; j < shape[0]; ++j) { + this._field[0].set(j + 1, 0, j) + } + this._field[0].set(shape[0] + 1, 0, shape[0] - 1) + this._field[1].set(0, 0, 0) + for (j = 0; j < shape[1]; ++j) { + this._field[1].set(0, j + 1, j) + } + this._field[1].set(0, shape[1] + 1, shape[1] - 1) } -}; + // Save shape + var fields = this._field -// Big List of Colors -// ------------------ -// -var names = tinycolor.names = { - aliceblue: "f0f8ff", - antiquewhite: "faebd7", - aqua: "0ff", - aquamarine: "7fffd4", - azure: "f0ffff", - beige: "f5f5dc", - bisque: "ffe4c4", - black: "000", - blanchedalmond: "ffebcd", - blue: "00f", - blueviolet: "8a2be2", - brown: "a52a2a", - burlywood: "deb887", - burntsienna: "ea7e5d", - cadetblue: "5f9ea0", - chartreuse: "7fff00", - chocolate: "d2691e", - coral: "ff7f50", - cornflowerblue: "6495ed", - cornsilk: "fff8dc", - crimson: "dc143c", - cyan: "0ff", - darkblue: "00008b", - darkcyan: "008b8b", - darkgoldenrod: "b8860b", - darkgray: "a9a9a9", - darkgreen: "006400", - darkgrey: "a9a9a9", - darkkhaki: "bdb76b", - darkmagenta: "8b008b", - darkolivegreen: "556b2f", - darkorange: "ff8c00", - darkorchid: "9932cc", - darkred: "8b0000", - darksalmon: "e9967a", - darkseagreen: "8fbc8f", - darkslateblue: "483d8b", - darkslategray: "2f4f4f", - darkslategrey: "2f4f4f", - darkturquoise: "00ced1", - darkviolet: "9400d3", - deeppink: "ff1493", - deepskyblue: "00bfff", - dimgray: "696969", - dimgrey: "696969", - dodgerblue: "1e90ff", - firebrick: "b22222", - floralwhite: "fffaf0", - forestgreen: "228b22", - fuchsia: "f0f", - gainsboro: "dcdcdc", - ghostwhite: "f8f8ff", - gold: "ffd700", - goldenrod: "daa520", - gray: "808080", - green: "008000", - greenyellow: "adff2f", - grey: "808080", - honeydew: "f0fff0", - hotpink: "ff69b4", - indianred: "cd5c5c", - indigo: "4b0082", - ivory: "fffff0", - khaki: "f0e68c", - lavender: "e6e6fa", - lavenderblush: "fff0f5", - lawngreen: "7cfc00", - lemonchiffon: "fffacd", - lightblue: "add8e6", - lightcoral: "f08080", - lightcyan: "e0ffff", - lightgoldenrodyellow: "fafad2", - lightgray: "d3d3d3", - lightgreen: "90ee90", - lightgrey: "d3d3d3", - lightpink: "ffb6c1", - lightsalmon: "ffa07a", - lightseagreen: "20b2aa", - lightskyblue: "87cefa", - lightslategray: "789", - lightslategrey: "789", - lightsteelblue: "b0c4de", - lightyellow: "ffffe0", - lime: "0f0", - limegreen: "32cd32", - linen: "faf0e6", - magenta: "f0f", - maroon: "800000", - mediumaquamarine: "66cdaa", - mediumblue: "0000cd", - mediumorchid: "ba55d3", - mediumpurple: "9370db", - mediumseagreen: "3cb371", - mediumslateblue: "7b68ee", - mediumspringgreen: "00fa9a", - mediumturquoise: "48d1cc", - mediumvioletred: "c71585", - midnightblue: "191970", - mintcream: "f5fffa", - mistyrose: "ffe4e1", - moccasin: "ffe4b5", - navajowhite: "ffdead", - navy: "000080", - oldlace: "fdf5e6", - olive: "808000", - olivedrab: "6b8e23", - orange: "ffa500", - orangered: "ff4500", - orchid: "da70d6", - palegoldenrod: "eee8aa", - palegreen: "98fb98", - paleturquoise: "afeeee", - palevioletred: "db7093", - papayawhip: "ffefd5", - peachpuff: "ffdab9", - peru: "cd853f", - pink: "ffc0cb", - plum: "dda0dd", - powderblue: "b0e0e6", - purple: "800080", - rebeccapurple: "663399", - red: "f00", - rosybrown: "bc8f8f", - royalblue: "4169e1", - saddlebrown: "8b4513", - salmon: "fa8072", - sandybrown: "f4a460", - seagreen: "2e8b57", - seashell: "fff5ee", - sienna: "a0522d", - silver: "c0c0c0", - skyblue: "87ceeb", - slateblue: "6a5acd", - slategray: "708090", - slategrey: "708090", - snow: "fffafa", - springgreen: "00ff7f", - steelblue: "4682b4", - tan: "d2b48c", - teal: "008080", - thistle: "d8bfd8", - tomato: "ff6347", - turquoise: "40e0d0", - violet: "ee82ee", - wheat: "f5deb3", - white: "fff", - whitesmoke: "f5f5f5", - yellow: "ff0", - yellowgreen: "9acd32" -}; + // Compute surface normals + var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) + for (i = 0; i < 3; ++i) { + gradient(dfields.pick(i), fields[i], 'mirror') + } + var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) + for (i = 0; i < shape[0] + 2; ++i) { + for (j = 0; j < shape[1] + 2; ++j) { + var dxdu = dfields.get(0, i, j, 0) + var dxdv = dfields.get(0, i, j, 1) + var dydu = dfields.get(1, i, j, 0) + var dydv = dfields.get(1, i, j, 1) + var dzdu = dfields.get(2, i, j, 0) + var dzdv = dfields.get(2, i, j, 1) -// Make it easy to access colors via `hexNames[hex]` -var hexNames = tinycolor.hexNames = flip(names); + var nx = dydu * dzdv - dydv * dzdu + var ny = dzdu * dxdv - dzdv * dxdu + var nz = dxdu * dydv - dxdv * dydu + var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) + if (nl < 1e-8) { + nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz)) + if (nl < 1e-8) { + nz = 1.0 + ny = nx = 0.0 + nl = 1.0 + } else { + nl = 1.0 / nl + } + } else { + nl = 1.0 / Math.sqrt(nl) + } -// Utilities -// --------- + normals.set(i, j, 0, nx * nl) + normals.set(i, j, 1, ny * nl) + normals.set(i, j, 2, nz * nl) + } + } + pool.free(dfields.data) -// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` -function flip(o) { - var flipped = { }; - for (var i in o) { - if (o.hasOwnProperty(i)) { - flipped[o[i]] = i; + // Initialize surface + var lo = [ Infinity, Infinity, Infinity ] + var hi = [ -Infinity, -Infinity, -Infinity ] + var lo_intensity = Infinity + var hi_intensity = -Infinity + var count = (shape[0] - 1) * (shape[1] - 1) * 6 + var tverts = pool.mallocFloat(bits.nextPow2(10 * count)) + var tptr = 0 + var vertexCount = 0 + for (i = 0; i < shape[0] - 1; ++i) { + j_loop: + for (j = 0; j < shape[1] - 1; ++j) { + // Test for NaNs + for (var dx = 0; dx < 2; ++dx) { + for (var dy = 0; dy < 2; ++dy) { + for (var k = 0; k < 3; ++k) { + var f = this._field[k].get(1 + i + dx, 1 + j + dy) + if (isNaN(f) || !isFinite(f)) { + continue j_loop + } + } + } } - } - return flipped; -} + for (k = 0; k < 6; ++k) { + var r = i + QUAD[k][0] + var c = j + QUAD[k][1] -// Return a valid alpha value [0,1] with all invalid values being set to 1 -function boundAlpha(a) { - a = parseFloat(a); + var tx = this._field[0].get(r + 1, c + 1) + var ty = this._field[1].get(r + 1, c + 1) + f = this._field[2].get(r + 1, c + 1) + var vf = f + nx = normals.get(r + 1, c + 1, 0) + ny = normals.get(r + 1, c + 1, 1) + nz = normals.get(r + 1, c + 1, 2) - if (isNaN(a) || a < 0 || a > 1) { - a = 1; - } + if (params.intensity) { + vf = params.intensity.get(r, c) + } - return a; -} + tverts[tptr++] = r + tverts[tptr++] = c + tverts[tptr++] = tx + tverts[tptr++] = ty + tverts[tptr++] = f + tverts[tptr++] = 0 + tverts[tptr++] = vf + tverts[tptr++] = nx + tverts[tptr++] = ny + tverts[tptr++] = nz -// Take input from [0, n] and return it as [0, 1] -function bound01(n, max) { - if (isOnePointZero(n)) { n = "100%"; } + lo[0] = Math.min(lo[0], tx) + lo[1] = Math.min(lo[1], ty) + lo[2] = Math.min(lo[2], f) + lo_intensity = Math.min(lo_intensity, vf) - var processPercent = isPercentage(n); - n = mathMin(max, mathMax(0, parseFloat(n))); + hi[0] = Math.max(hi[0], tx) + hi[1] = Math.max(hi[1], ty) + hi[2] = Math.max(hi[2], f) + hi_intensity = Math.max(hi_intensity, vf) - // Automatically convert percentage into number - if (processPercent) { - n = parseInt(n * max, 10) / 100; + vertexCount += 1 + } + } } - // Handle floating point rounding errors - if ((math.abs(n - max) < 0.000001)) { - return 1; + if (params.intensityBounds) { + lo_intensity = +params.intensityBounds[0] + hi_intensity = +params.intensityBounds[1] } - // Convert into [0, 1] range if it isn't already - return (n % max) / parseFloat(max); -} + // Scale all vertex intensities + for (i = 6; i < tptr; i += 10) { + tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity) + } -// Force a number between 0 and 1 -function clamp01(val) { - return mathMin(1, mathMax(0, val)); -} + this._vertexCount = vertexCount + this._coordinateBuffer.update(tverts.subarray(0, tptr)) + pool.freeFloat(tverts) + pool.free(normals.data) -// Parse a base-16 hex value into a base-10 integer -function parseIntFromHex(val) { - return parseInt(val, 16); -} + // Update bounds + this.bounds = [lo, hi] -// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 -// -function isOnePointZero(n) { - return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; -} + // Save intensity + this.intensity = params.intensity || this._field[2] -// Check to see if string passed in is a percentage -function isPercentage(n) { - return typeof n === "string" && n.indexOf('%') != -1; -} + if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) { + levelsChanged = true + } -// Force a hex value to have 2 characters -function pad2(c) { - return c.length == 1 ? '0' + c : '' + c; -} + // Save intensity bound + this.intensityBounds = [lo_intensity, hi_intensity] + } -// Replace a decimal with it's percentage value -function convertToPercentage(n) { - if (n <= 1) { - n = (n * 100) + "%"; + // Update level crossings + if ('levels' in params) { + var levels = params.levels + if (!Array.isArray(levels[0])) { + levels = [ [], [], levels ] + } else { + levels = levels.slice() + } + for (i = 0; i < 3; ++i) { + levels[i] = levels[i].slice() + levels.sort(function (a, b) { + return a - b + }) + } + change_test: + for (i = 0; i < 3; ++i) { + if (levels[i].length !== this.contourLevels[i].length) { + levelsChanged = true + break + } + for (j = 0; j < levels[i].length; ++j) { + if (levels[i][j] !== this.contourLevels[i][j]) { + levelsChanged = true + break change_test + } + } } + this.contourLevels = levels + } + + if (levelsChanged) { + fields = this._field + shape = this.shape + + // Update contour lines + var contourVerts = [] + + for (var dim = 0; dim < 3; ++dim) { + levels = this.contourLevels[dim] + var levelOffsets = [] + var levelCounts = [] - return n; -} + var parts = [0, 0, 0] -// Converts a decimal to a hex value -function convertDecimalToHex(d) { - return Math.round(parseFloat(d) * 255).toString(16); -} -// Converts a hex value to a decimal -function convertHexToDecimal(h) { - return (parseIntFromHex(h) / 255); -} + for (i = 0; i < levels.length; ++i) { + var graph = surfaceNets(this._field[dim], levels[i]) + levelOffsets.push((contourVerts.length / 5) | 0) + vertexCount = 0 -var matchers = (function() { + edge_loop: + for (j = 0; j < graph.cells.length; ++j) { + var e = graph.cells[j] + for (k = 0; k < 2; ++k) { + var p = graph.positions[e[k]] - // - var CSS_INTEGER = "[-\\+]?\\d+%?"; + var x = p[0] + var ix = Math.floor(x) | 0 + var fx = x - ix - // - var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + var y = p[1] + var iy = Math.floor(y) | 0 + var fy = y - iy - // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. - var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + var hole = false + dd_loop: + for (var dd = 0; dd < 3; ++dd) { + parts[dd] = 0.0 + var iu = (dim + dd + 1) % 3 + for (dx = 0; dx < 2; ++dx) { + var s = dx ? fx : 1.0 - fx + r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0 + for (dy = 0; dy < 2; ++dy) { + var t = dy ? fy : 1.0 - fy + c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0 - // Actual matching. - // Parentheses and commas are optional, but not required. - // Whitespace can take the place of commas or opening paren - var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + if (dd < 2) { + f = this._field[iu].get(r, c) + } else { + f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]) + } + if (!isFinite(f) || isNaN(f)) { + hole = true + break dd_loop + } - return { - rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), - rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), - hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), - hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), - hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), - hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), - hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, - hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ - }; -})(); + var w = s * t + parts[dd] += w * f + } + } + } -// `stringInputToObject` -// Permissive string parsing. Take in a number of formats, and output an object -// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` -function stringInputToObject(color) { + if (!hole) { + contourVerts.push(parts[0], parts[1], p[0], p[1], parts[2]) + vertexCount += 1 + } else { + if (k > 0) { + // If we already added first edge, pop off verts + for (var l = 0; l < 5; ++l) { + contourVerts.pop() + } + vertexCount -= 1 + } + continue edge_loop + } + } + } + levelCounts.push(vertexCount) + } - color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); - var named = false; - if (names[color]) { - color = names[color]; - named = true; - } - else if (color == 'transparent') { - return { r: 0, g: 0, b: 0, a: 0, format: "name" }; + // Store results + this._contourOffsets[dim] = levelOffsets + this._contourCounts[dim] = levelCounts } - // Try to match string input using regular expressions. - // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] - // Just return an object and let the conversion functions handle that. - // This way the result will be the same whether the tinycolor is initialized with string or object. - var match; - if ((match = matchers.rgb.exec(color))) { - return { r: match[1], g: match[2], b: match[3] }; - } - if ((match = matchers.rgba.exec(color))) { - return { r: match[1], g: match[2], b: match[3], a: match[4] }; - } - if ((match = matchers.hsl.exec(color))) { - return { h: match[1], s: match[2], l: match[3] }; - } - if ((match = matchers.hsla.exec(color))) { - return { h: match[1], s: match[2], l: match[3], a: match[4] }; - } - if ((match = matchers.hsv.exec(color))) { - return { h: match[1], s: match[2], v: match[3] }; - } - if ((match = matchers.hsva.exec(color))) { - return { h: match[1], s: match[2], v: match[3], a: match[4] }; - } - if ((match = matchers.hex8.exec(color))) { - return { - a: convertHexToDecimal(match[1]), - r: parseIntFromHex(match[2]), - g: parseIntFromHex(match[3]), - b: parseIntFromHex(match[4]), - format: named ? "name" : "hex8" - }; - } - if ((match = matchers.hex6.exec(color))) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - format: named ? "name" : "hex" - }; - } - if ((match = matchers.hex3.exec(color))) { - return { - r: parseIntFromHex(match[1] + '' + match[1]), - g: parseIntFromHex(match[2] + '' + match[2]), - b: parseIntFromHex(match[3] + '' + match[3]), - format: named ? "name" : "hex" - }; + var floatBuffer = pool.mallocFloat(contourVerts.length) + for (i = 0; i < contourVerts.length; ++i) { + floatBuffer[i] = contourVerts[i] } + this._contourBuffer.update(floatBuffer) + pool.freeFloat(floatBuffer) + } - return false; + if (params.colormap) { + this._colorMap.setPixels(genColormap(params.colormap)) + } } -function validateWCAG2Parms(parms) { - // return valid WCAG2 parms for isReadable. - // If input parms are invalid, return {"level":"AA", "size":"small"} - var level, size; - parms = parms || {"level":"AA", "size":"small"}; - level = (parms.level || "AA").toUpperCase(); - size = (parms.size || "small").toLowerCase(); - if (level !== "AA" && level !== "AAA") { - level = "AA"; +proto.dispose = function () { + this._shader.dispose() + this._vao.dispose() + this._coordinateBuffer.dispose() + this._colorMap.dispose() + this._contourBuffer.dispose() + this._contourVAO.dispose() + this._contourShader.dispose() + this._contourPickShader.dispose() + this._dynamicBuffer.dispose() + this._dynamicVAO.dispose() + for (var i = 0; i < 3; ++i) { + pool.freeFloat(this._field[i].data) + } +} + +proto.highlight = function (selection) { + if (!selection) { + this._dynamicCounts = [0, 0, 0] + this.dyanamicLevel = [NaN, NaN, NaN] + this.highlightLevel = [-1, -1, -1] + return + } + + for (var i = 0; i < 3; ++i) { + if (this.enableHighlight[i]) { + this.highlightLevel[i] = selection.level[i] + } else { + this.highlightLevel[i] = -1 } - if (size !== "small" && size !== "large") { - size = "small"; + } + + var levels + if (this.snapToData) { + levels = selection.dataCoordinate + } else { + levels = selection.position + } + if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) && + (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) && + (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) { + return + } + + var vertexCount = 0 + var shape = this.shape + var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1]) + + for (var d = 0; d < 3; ++d) { + if (!this.enableDynamic[d]) { + this.dynamicLevel[d] = NaN + this._dynamicCounts[d] = 0 + continue } - return {"level":level, "size":size}; -} -// Node: Export function -if (typeof module !== "undefined" && module.exports) { - module.exports = tinycolor; -} -// AMD/requirejs: Define the module -else if (typeof define === 'function' && define.amd) { - define(function () {return tinycolor;}); -} -// Browser: Expose to window -else { - window.tinycolor = tinycolor; -} + this.dynamicLevel[d] = levels[d] -})(); + var u = (d + 1) % 3 + var v = (d + 2) % 3 -},{}],275:[function(require,module,exports){ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.topojson = {}))); -}(this, function (exports) { 'use strict'; + var f = this._field[d] + var g = this._field[u] + var h = this._field[v] + var intensity = this.intensity - function noop() {} + var graph = surfaceNets(f, levels[d]) + var edges = graph.cells + var positions = graph.positions - function absolute(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - point[0] = (x0 += point[0]) * kx + dx; - point[1] = (y0 += point[1]) * ky + dy; - }; - } + this._dynamicOffsets[d] = vertexCount - function relative(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - var x1 = (point[0] - dx) / kx | 0, - y1 = (point[1] - dy) / ky | 0; - point[0] = x1 - x0; - point[1] = y1 - y0; - x0 = x1; - y0 = y1; - }; - } + for (i = 0; i < edges.length; ++i) { + var e = edges[i] + for (var j = 0; j < 2; ++j) { + var p = positions[e[j]] - function reverse(array, n) { - var t, j = array.length, i = j - n; - while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; - } + var x = +p[0] + var ix = x | 0 + var jx = Math.min(ix + 1, shape[0]) | 0 + var fx = x - ix + var hx = 1.0 - fx - function bisect(a, x) { - var lo = 0, hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (a[mid] < x) lo = mid + 1; - else hi = mid; - } - return lo; - } + var y = +p[1] + var iy = y | 0 + var jy = Math.min(iy + 1, shape[1]) | 0 + var fy = y - iy + var hy = 1.0 - fy - function feature(topology, o) { - return o.type === "GeometryCollection" ? { - type: "FeatureCollection", - features: o.geometries.map(function(o) { return feature$1(topology, o); }) - } : feature$1(topology, o); - } + var w00 = hx * hy + var w01 = hx * fy + var w10 = fx * hy + var w11 = fx * fy - function feature$1(topology, o) { - var f = { - type: "Feature", - id: o.id, - properties: o.properties || {}, - geometry: object(topology, o) - }; - if (o.id == null) delete f.id; - return f; - } + var cu = w00 * g.get(ix, iy) + + w01 * g.get(ix, jy) + + w10 * g.get(jx, iy) + + w11 * g.get(jx, jy) - function object(topology, o) { - var absolute$$ = absolute(topology.transform), - arcs = topology.arcs; + var cv = w00 * h.get(ix, iy) + + w01 * h.get(ix, jy) + + w10 * h.get(jx, iy) + + w11 * h.get(jx, jy) - function arc(i, points) { - if (points.length) points.pop(); - for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { - points.push(p = a[k].slice()); - absolute$$(p, k); + if (isNaN(cu) || isNaN(cv)) { + if (j) { + vertexCount -= 1 + } + break + } + + scratchBuffer[2 * vertexCount + 0] = cu + scratchBuffer[2 * vertexCount + 1] = cv + + vertexCount += 1 } - if (i < 0) reverse(points, n); } - function point(p) { - p = p.slice(); - absolute$$(p, 0); - return p; - } + this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d] + } - function line(arcs) { - var points = []; - for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); - if (points.length < 2) points.push(points[0].slice()); - return points; - } + this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) + pool.freeFloat(scratchBuffer) +} - function ring(arcs) { - var points = line(arcs); - while (points.length < 4) points.push(points[0].slice()); - return points; - } +function createSurfacePlot (params) { + var gl = params.gl + var shader = createShader(gl) + var pickShader = createPickShader(gl) + var contourShader = createContourShader(gl) + var contourPickShader = createPickContourShader(gl) - function polygon(arcs) { - return arcs.map(ring); + var coordinateBuffer = createBuffer(gl) + var vao = createVAO(gl, [ + { buffer: coordinateBuffer, + size: 4, + stride: SURFACE_VERTEX_SIZE, + offset: 0 + }, + { buffer: coordinateBuffer, + size: 3, + stride: SURFACE_VERTEX_SIZE, + offset: 16 + }, + { + buffer: coordinateBuffer, + size: 3, + stride: SURFACE_VERTEX_SIZE, + offset: 28 } + ]) - function geometry(o) { - var t = o.type; - return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} - : t in geometryType ? {type: t, coordinates: geometryType[t](o)} - : null; + var contourBuffer = createBuffer(gl) + var contourVAO = createVAO(gl, [ + { + buffer: contourBuffer, + size: 4, + stride: 20, + offset: 0 + }, + { + buffer: contourBuffer, + size: 1, + stride: 20, + offset: 16 } + ]) - var geometryType = { - Point: function(o) { return point(o.coordinates); }, - MultiPoint: function(o) { return o.coordinates.map(point); }, - LineString: function(o) { return line(o.arcs); }, - MultiLineString: function(o) { return o.arcs.map(line); }, - Polygon: function(o) { return polygon(o.arcs); }, - MultiPolygon: function(o) { return o.arcs.map(polygon); } - }; + var dynamicBuffer = createBuffer(gl) + var dynamicVAO = createVAO(gl, [ + { + buffer: dynamicBuffer, + size: 2, + type: gl.FLOAT + }]) - return geometry(o); - } + var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) + cmap.minFilter = gl.LINEAR + cmap.magFilter = gl.LINEAR - function stitchArcs(topology, arcs) { - var stitchedArcs = {}, - fragmentByStart = {}, - fragmentByEnd = {}, - fragments = [], - emptyIndex = -1; + var surface = new SurfacePlot( + gl, + [0, 0], + [[0, 0, 0], [0, 0, 0]], + shader, + pickShader, + coordinateBuffer, + vao, + cmap, + contourShader, + contourPickShader, + contourBuffer, + contourVAO, + dynamicBuffer, + dynamicVAO) - // Stitch empty arcs first, since they may be subsumed by other arcs. - arcs.forEach(function(i, j) { - var arc = topology.arcs[i < 0 ? ~i : i], t; - if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { - t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; - } - }); + var nparams = { + levels: [[], [], []] + } + for (var id in params) { + nparams[id] = params[id] + } + nparams.colormap = nparams.colormap || 'jet' - arcs.forEach(function(i) { - var e = ends(i), - start = e[0], - end = e[1], - f, g; + surface.update(nparams) - if (f = fragmentByEnd[start]) { - delete fragmentByEnd[f.end]; - f.push(i); - f.end = end; - if (g = fragmentByStart[end]) { - delete fragmentByStart[g.start]; - var fg = g === f ? f : f.concat(g); - fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else if (f = fragmentByStart[end]) { - delete fragmentByStart[f.start]; - f.unshift(i); - f.start = start; - if (g = fragmentByEnd[start]) { - delete fragmentByEnd[g.end]; - var gf = g === f ? f : g.concat(f); - fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; - } else { - fragmentByStart[f.start] = fragmentByEnd[f.end] = f; - } - } else { - f = [i]; - fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; - } - }); + return surface +} - function ends(i) { - var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; - if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); - else p1 = arc[arc.length - 1]; - return i < 0 ? [p1, p0] : [p0, p1]; - } +},{"./lib/shaders":939,"binary-search-bounds":940,"bit-twiddle":941,"colormap":943,"gl-buffer":946,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-texture2d":973,"gl-vao":977,"ndarray":1031,"ndarray-gradient":978,"ndarray-ops":1026,"ndarray-pack":983,"surface-nets":1001,"typedarray-pool":1002}],1004:[function(require,module,exports){ +'use strict' - function flush(fragmentByEnd, fragmentByStart) { - for (var k in fragmentByEnd) { - var f = fragmentByEnd[k]; - delete fragmentByStart[f.start]; - delete f.start; - delete f.end; - f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); - fragments.push(f); - } - } +module.exports = mouseListen - flush(fragmentByEnd, fragmentByStart); - flush(fragmentByStart, fragmentByEnd); - arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); +var mouse = require('mouse-event') - return fragments; +function mouseListen(element, callback) { + if(!callback) { + callback = element + element = window } - function mesh(topology) { - return object(topology, meshArcs.apply(this, arguments)); + var buttonState = 0 + var x = 0 + var y = 0 + var mods = { + shift: false, + alt: false, + control: false, + meta: false } + var attached = false - function meshArcs(topology, o, filter) { - var arcs = []; - - function arc(i) { - var j = i < 0 ? ~i : i; - (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); + function updateMods(ev) { + var changed = false + if('altKey' in ev) { + changed = changed || ev.altKey !== mods.alt + mods.alt = !!ev.altKey } - - function line(arcs) { - arcs.forEach(arc); + if('shiftKey' in ev) { + changed = changed || ev.shiftKey !== mods.shift + mods.shift = !!ev.shiftKey } - - function polygon(arcs) { - arcs.forEach(line); + if('ctrlKey' in ev) { + changed = changed || ev.ctrlKey !== mods.control + mods.control = !!ev.ctrlKey } - - function geometry(o) { - if (o.type === "GeometryCollection") o.geometries.forEach(geometry); - else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs); + if('metaKey' in ev) { + changed = changed || ev.metaKey !== mods.meta + mods.meta = !!ev.metaKey } + return changed + } - if (arguments.length > 1) { - var geomsByArc = [], - geom; - - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs) { arcs.forEach(polygon); } - }; - - geometry(o); - - geomsByArc.forEach(arguments.length < 3 - ? function(geoms) { arcs.push(geoms[0].i); } - : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); - } else { - for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); + function handleEvent(nextButtons, ev) { + var nextX = mouse.x(ev) + var nextY = mouse.y(ev) + if('buttons' in ev) { + nextButtons = ev.buttons|0 + } + if(nextButtons !== buttonState || + nextX !== x || + nextY !== y || + updateMods(ev)) { + buttonState = nextButtons|0 + x = nextX||0 + y = nextY||0 + callback && callback(buttonState, x, y, mods) } - - return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)}; } - function triangle(triangle) { - var a = triangle[0], b = triangle[1], c = triangle[2]; - return Math.abs((a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1])); + function clearState(ev) { + handleEvent(0, ev) } - function ring(ring) { - var i = -1, - n = ring.length, - a, - b = ring[n - 1], - area = 0; + function handleBlur() { + if(buttonState || + x || + y || + mods.shift || + mods.alt || + mods.meta || + mods.control) { - while (++i < n) { - a = b; - b = ring[i]; - area += a[0] * b[1] - a[1] * b[0]; + x = y = 0 + buttonState = 0 + mods.shift = mods.alt = mods.control = mods.meta = false + callback && callback(0, 0, 0, mods) } - - return area / 2; - } - - function merge(topology) { - return object(topology, mergeArcs.apply(this, arguments)); } - function mergeArcs(topology, objects) { - var polygonsByArc = {}, - polygons = [], - components = []; - - objects.forEach(function(o) { - if (o.type === "Polygon") register(o.arcs); - else if (o.type === "MultiPolygon") o.arcs.forEach(register); - }); - - function register(polygon) { - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon); - }); - }); - polygons.push(polygon); + function handleMods(ev) { + if(updateMods(ev)) { + callback && callback(buttonState, x, y, mods) } + } - function exterior(ring$$) { - return ring(object(topology, {type: "Polygon", arcs: [ring$$]}).coordinates[0]) > 0; // TODO allow spherical? + function handleMouseMove(ev) { + if(mouse.buttons(ev) === 0) { + handleEvent(0, ev) + } else { + handleEvent(buttonState, ev) } + } - polygons.forEach(function(polygon) { - if (!polygon._) { - var component = [], - neighbors = [polygon]; - polygon._ = 1; - components.push(component); - while (polygon = neighbors.pop()) { - component.push(polygon); - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { - if (!polygon._) { - polygon._ = 1; - neighbors.push(polygon); - } - }); - }); - }); - } - } - }); + function handleMouseDown(ev) { + handleEvent(buttonState | mouse.buttons(ev), ev) + } - polygons.forEach(function(polygon) { - delete polygon._; - }); + function handleMouseUp(ev) { + handleEvent(buttonState & ~mouse.buttons(ev), ev) + } - return { - type: "MultiPolygon", - arcs: components.map(function(polygons) { - var arcs = [], n; + function attachListeners() { + if(attached) { + return + } + attached = true - // Extract the exterior (unique) arcs. - polygons.forEach(function(polygon) { - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { - arcs.push(arc); - } - }); - }); - }); + element.addEventListener('mousemove', handleMouseMove) - // Stitch the arcs into one or more rings. - arcs = stitchArcs(topology, arcs); + element.addEventListener('mousedown', handleMouseDown) - // If more than one ring is returned, - // at most one of these rings can be the exterior; - // this exterior ring has the same winding order - // as any exterior ring in the original polygons. - if ((n = arcs.length) > 1) { - var sgn = exterior(polygons[0][0]); - for (var i = 0, t; i < n; ++i) { - if (sgn === exterior(arcs[i])) { - t = arcs[0], arcs[0] = arcs[i], arcs[i] = t; - break; - } - } - } + element.addEventListener('mouseup', handleMouseUp) - return arcs; - }) - }; - } + element.addEventListener('mouseleave', clearState) + element.addEventListener('mouseenter', clearState) + element.addEventListener('mouseout', clearState) + element.addEventListener('mouseover', clearState) - function neighbors(objects) { - var indexesByArc = {}, // arc index -> array of object indexes - neighbors = objects.map(function() { return []; }); + element.addEventListener('blur', handleBlur) - function line(arcs, i) { - arcs.forEach(function(a) { - if (a < 0) a = ~a; - var o = indexesByArc[a]; - if (o) o.push(i); - else indexesByArc[a] = [i]; - }); - } + element.addEventListener('keyup', handleMods) + element.addEventListener('keydown', handleMods) + element.addEventListener('keypress', handleMods) - function polygon(arcs, i) { - arcs.forEach(function(arc) { line(arc, i); }); - } + if(element !== window) { + window.addEventListener('blur', handleBlur) - function geometry(o, i) { - if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); - else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + window.addEventListener('keyup', handleMods) + window.addEventListener('keydown', handleMods) + window.addEventListener('keypress', handleMods) } + } - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } - }; - - objects.forEach(geometry); - - for (var i in indexesByArc) { - for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { - for (var k = j + 1; k < m; ++k) { - var ij = indexes[j], ik = indexes[k], n; - if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); - if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); - } - } + function detachListeners() { + if(!attached) { + return } + attached = false - return neighbors; - } + element.removeEventListener('mousemove', handleMouseMove) - function compareArea(a, b) { - return a[1][2] - b[1][2]; - } + element.removeEventListener('mousedown', handleMouseDown) - function minAreaHeap() { - var heap = {}, - array = [], - size = 0; + element.removeEventListener('mouseup', handleMouseUp) - heap.push = function(object) { - up(array[object._ = size] = object, size++); - return size; - }; + element.removeEventListener('mouseleave', clearState) + element.removeEventListener('mouseenter', clearState) + element.removeEventListener('mouseout', clearState) + element.removeEventListener('mouseover', clearState) - heap.pop = function() { - if (size <= 0) return; - var removed = array[0], object; - if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); - return removed; - }; + element.removeEventListener('blur', handleBlur) - heap.remove = function(removed) { - var i = removed._, object; - if (array[i] !== removed) return; // invalid request - if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); - return i; - }; + element.removeEventListener('keyup', handleMods) + element.removeEventListener('keydown', handleMods) + element.removeEventListener('keypress', handleMods) - function up(object, i) { - while (i > 0) { - var j = ((i + 1) >> 1) - 1, - parent = array[j]; - if (compareArea(object, parent) >= 0) break; - array[parent._ = i] = parent; - array[object._ = i = j] = object; - } - } + if(element !== window) { + window.removeEventListener('blur', handleBlur) - function down(object, i) { - while (true) { - var r = (i + 1) << 1, - l = r - 1, - j = i, - child = array[j]; - if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; - if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; - if (j === i) break; - array[child._ = i] = child; - array[object._ = i = j] = object; - } + window.removeEventListener('keyup', handleMods) + window.removeEventListener('keydown', handleMods) + window.removeEventListener('keypress', handleMods) } - - return heap; } - function presimplify(topology, triangleArea) { - var absolute$$ = absolute(topology.transform), - relative$$ = relative(topology.transform), - heap = minAreaHeap(); + //Attach listeners + attachListeners() - if (!triangleArea) triangleArea = triangle; + var result = { + element: element + } - topology.arcs.forEach(function(arc) { - var triangles = [], - maxArea = 0, - triangle, - i, - n, - p; + Object.defineProperties(result, { + enabled: { + get: function() { return attached }, + set: function(f) { + if(f) { + attachListeners() + } else { + detachListeners + } + }, + enumerable: true + }, + buttons: { + get: function() { return buttonState }, + enumerable: true + }, + x: { + get: function() { return x }, + enumerable: true + }, + y: { + get: function() { return y }, + enumerable: true + }, + mods: { + get: function() { return mods }, + enumerable: true + } + }) - // To store each point’s effective area, we create a new array rather than - // extending the passed-in point to workaround a Chrome/V8 bug (getting - // stuck in smi mode). For midpoints, the initial effective area of - // Infinity will be computed in the next step. - for (i = 0, n = arc.length; i < n; ++i) { - p = arc[i]; - absolute$$(arc[i] = [p[0], p[1], Infinity], i); - } + return result +} - for (i = 1, n = arc.length - 1; i < n; ++i) { - triangle = arc.slice(i - 1, i + 2); - triangle[1][2] = triangleArea(triangle); - triangles.push(triangle); - heap.push(triangle); - } +},{"mouse-event":1005}],1005:[function(require,module,exports){ +'use strict' - for (i = 0, n = triangles.length; i < n; ++i) { - triangle = triangles[i]; - triangle.previous = triangles[i - 1]; - triangle.next = triangles[i + 1]; +function mouseButtons(ev) { + if(typeof ev === 'object') { + if('buttons' in ev) { + return ev.buttons + } else if('which' in ev) { + var b = ev.which + if(b === 2) { + return 4 + } else if(b === 3) { + return 2 + } else if(b > 0) { + return 1<<(b-1) } - - while (triangle = heap.pop()) { - var previous = triangle.previous, - next = triangle.next; - - // If the area of the current point is less than that of the previous point - // to be eliminated, use the latter's area instead. This ensures that the - // current point cannot be eliminated without eliminating previously- - // eliminated points. - if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; - else maxArea = triangle[1][2]; - - if (previous) { - previous.next = next; - previous[2] = triangle[2]; - update(previous); - } - - if (next) { - next.previous = previous; - next[0] = triangle[0]; - update(next); - } + } else if('button' in ev) { + var b = ev.button + if(b === 1) { + return 4 + } else if(b === 2) { + return 2 + } else if(b >= 0) { + return 1< 0) { - return d.pop() +var invert2 = require('gl-mat2/invert') +var invert3 = require('gl-mat3/invert') +var invert4 = require('gl-mat4/invert') + +function invert(out, M) { + switch(M.length) { + case 0: + break + case 1: + out[0] = 1.0 / M[0] + break + case 4: + invert2(out, M) + break + case 9: + invert3(out, M) + break + case 16: + invert4(out, M) + break + default: + throw new Error('currently supports matrices up to 4x4') + break } - return new ArrayBuffer(n) + return out } -exports.mallocArrayBuffer = mallocArrayBuffer +},{"gl-mat2/invert":1016,"gl-mat3/invert":1017,"gl-mat4/invert":240}],1016:[function(require,module,exports){ +module.exports = invert -function mallocUint8(n) { - return new Uint8Array(mallocArrayBuffer(n), 0, n) -} -exports.mallocUint8 = mallocUint8 +/** + * Inverts a mat2 + * + * @alias mat2.invert + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +function invert(out, a) { + var a0 = a[0] + var a1 = a[1] + var a2 = a[2] + var a3 = a[3] + var det = a0 * a3 - a2 * a1 -function mallocUint16(n) { - return new Uint16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocUint16 = mallocUint16 + if (!det) return null + det = 1.0 / det -function mallocUint32(n) { - return new Uint32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocUint32 = mallocUint32 + out[0] = a3 * det + out[1] = -a1 * det + out[2] = -a2 * det + out[3] = a0 * det -function mallocInt8(n) { - return new Int8Array(mallocArrayBuffer(n), 0, n) + return out } -exports.mallocInt8 = mallocInt8 -function mallocInt16(n) { - return new Int16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocInt16 = mallocInt16 +},{}],1017:[function(require,module,exports){ +module.exports = invert -function mallocInt32(n) { - return new Int32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocInt32 = mallocInt32 +/** + * Inverts a mat3 + * + * @alias mat3.invert + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2] + var a10 = a[3], a11 = a[4], a12 = a[5] + var a20 = a[6], a21 = a[7], a22 = a[8] -function mallocFloat(n) { - return new Float32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocFloat32 = exports.mallocFloat = mallocFloat + var b01 = a22 * a11 - a12 * a21 + var b11 = -a22 * a10 + a12 * a20 + var b21 = a21 * a10 - a11 * a20 -function mallocDouble(n) { - return new Float64Array(mallocArrayBuffer(8*n), 0, n) -} -exports.mallocFloat64 = exports.mallocDouble = mallocDouble + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21 -function mallocUint8Clamped(n) { - if(hasUint8C) { - return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) - } else { - return mallocUint8(n) - } -} -exports.mallocUint8Clamped = mallocUint8Clamped + if (!det) return null + det = 1.0 / det -function mallocDataView(n) { - return new DataView(mallocArrayBuffer(n), 0, n) -} -exports.mallocDataView = mallocDataView + out[0] = b01 * det + out[1] = (-a22 * a01 + a02 * a21) * det + out[2] = (a12 * a01 - a02 * a11) * det + out[3] = b11 * det + out[4] = (a22 * a00 - a02 * a20) * det + out[5] = (-a12 * a00 + a02 * a10) * det + out[6] = b21 * det + out[7] = (-a21 * a00 + a01 * a20) * det + out[8] = (a11 * a00 - a01 * a10) * det -function mallocBuffer(n) { - n = bits.nextPow2(n) - var log_n = bits.log2(n) - var cache = BUFFER[log_n] - if(cache.length > 0) { - return cache.pop() - } - return new Buffer(n) + return out } -exports.mallocBuffer = mallocBuffer -exports.clearCache = function clearCache() { - for(var i=0; i<32; ++i) { - POOL.UINT8[i].length = 0 - POOL.UINT16[i].length = 0 - POOL.UINT32[i].length = 0 - POOL.INT8[i].length = 0 - POOL.INT16[i].length = 0 - POOL.INT32[i].length = 0 - POOL.FLOAT[i].length = 0 - POOL.DOUBLE[i].length = 0 - POOL.UINT8C[i].length = 0 - DATA[i].length = 0 - BUFFER[i].length = 0 - } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"bit-twiddle":50,"buffer":51,"dup":115}],279:[function(require,module,exports){ +},{}],1018:[function(require,module,exports){ +arguments[4][318][0].apply(exports,arguments) +},{"cwise-compiler":1019,"dup":318}],1019:[function(require,module,exports){ +arguments[4][319][0].apply(exports,arguments) +},{"./lib/thunk.js":1021,"dup":319}],1020:[function(require,module,exports){ +arguments[4][320][0].apply(exports,arguments) +},{"dup":320,"uniq":1022}],1021:[function(require,module,exports){ +arguments[4][321][0].apply(exports,arguments) +},{"./compile.js":1020,"dup":321}],1022:[function(require,module,exports){ +arguments[4][87][0].apply(exports,arguments) +},{"dup":87}],1023:[function(require,module,exports){ "use strict" -function unique_pred(list, compare) { - var ptr = 1 - , len = list.length - , a=list[0], b=list[0] - for(var i=1; i 8192) { - throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") - } - var height = 3 * size - if(canvas.height < height) { - canvas.height = height - } - - context.fillStyle = "#000" - context.fillRect(0, 0, canvas.width, canvas.height) - - context.fillStyle = "#fff" - context.fillText(str, size, 2*size) - - //Cut pixels from image - var pixelData = context.getImageData(0, 0, width, height) - var pixels = ndarray(pixelData.data, [height, width, 4]) +var compile = require("cwise-compiler") - return pixels.pick(-1,-1,0).transpose(1,0) +var EmptyProc = { + body: "", + args: [], + thisVars: [], + localVars: [] } -function getContour(pixels, doSimplify) { - var contour = surfaceNets(pixels, 128) - if(doSimplify) { - return simplify(contour.cells, contour.positions, 0.25) +function fixup(x) { + if(!x) { + return EmptyProc } - return { - edges: contour.cells, - positions: contour.positions + for(var i=0; i>", + rrshift: ">>>" +} +;(function(){ + for(var id in assign_ops) { + var op = assign_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a","b","c"], + body: "a=b"+op+"c"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array","array"], + body: {args:["a","b"], + body:"a"+op+"=b"}, + rvalue: true, + funcName: id+"eq" + }) + exports[id+"s"] = makeOp({ + args: ["array", "array", "scalar"], + body: {args:["a","b","s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"seq"] = makeOp({ + args: ["array","scalar"], + body: {args:["a","s"], + body:"a"+op+"=s"}, + rvalue: true, + funcName: id+"seq" + }) } - return { - edges: [], - positions: [] +})(); + +var unary_ops = { + not: "!", + bnot: "~", + neg: "-", + recip: "1.0/" +} +;(function(){ + for(var id in unary_ops) { + var op = unary_ops[id] + exports[id] = makeOp({ + args: ["array", "array"], + body: {args:["a","b"], + body:"a="+op+"b"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array"], + body: {args:["a"], + body:"a="+op+"a"}, + rvalue: true, + count: 2, + funcName: id+"eq" + }) } +})(); + +var binary_ops = { + and: "&&", + or: "||", + eq: "===", + neq: "!==", + lt: "<", + gt: ">", + leq: "<=", + geq: ">=" } +;(function() { + for(var id in binary_ops) { + var op = binary_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a", "b", "c"], + body:"a=b"+op+"c"}, + funcName: id + }) + exports[id+"s"] = makeOp({ + args: ["array","array","scalar"], + body: {args:["a", "b", "s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"eq"] = makeOp({ + args: ["array", "array"], + body: {args:["a", "b"], + body:"a=a"+op+"b"}, + rvalue:true, + count:2, + funcName: id+"eq" + }) + exports[id+"seq"] = makeOp({ + args: ["array", "scalar"], + body: {args:["a","s"], + body:"a=a"+op+"s"}, + rvalue:true, + count:2, + funcName: id+"seq" + }) + } +})(); -function vectorizeText(str, canvas, context, options) { - var size = options.size || 64 - var family = options.font || "normal" +var math_unary = [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan" +] +;(function() { + for(var i=0; ithis_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norminf" +}) - var dead = [] - for(var i=0; i 0) { - var v = dead.pop() - live[v] = false - var n = adj[v] - for(var i=0; ithis_h)this_h=_inline_1_arg0_", + args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], + thisVars: [ "this_h" ], + localVars: [] }, + post: + { body: "return this_h", + args: [], + thisVars: [ "this_h" ], + localVars: [] } + }) - var newIndex = new Array(positions.length) - var npositions = [] - for(var i=0; ithis_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", + args:[ + {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, + {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], + thisVars:["this_i","this_v"], + localVars:["_inline_1_k"]}, + post:{ + body:"{return this_i}", + args:[], + thisVars:["this_i"], + localVars:[]} +}) -var uniq = require("uniq") +exports.random = makeOp({ + args: ["array"], + pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, + body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, + funcName: "random" +}) -function edgeToAdjacency(edges, numVertices) { - var numEdges = edges.length - if(typeof numVertices !== "number") { - numVertices = 0 - for(var i=0; i 0) { - nextCell = adj[i][b][0] - nextDir = i - break - } - } - nextVertex = nextCell[nextDir^1] +function compare1st(a, b) { + return a[0] - b[0] +} - for(var dir=0; dir<2; ++dir) { - var nbhd = adj[dir][b] - for(var k=0; k 0) { - nextCell = e - nextVertex = p - nextDir = dir - } - } - } - if(noCut) { - return nextVertex - } - if(nextCell) { - cut(nextCell, nextDir) - } - return nextVertex +function order() { + var stride = this.stride + var terms = new Array(stride.length) + var i + for(i=0; i 0) { - var ni = adj[0][i].length - var ncycle = extractCycle(i,j) - if(shouldGlue(pcycle, ncycle)) { - //Glue together trivial cycles - pcycle.push.apply(pcycle, ncycle) - } else { - if(pcycle.length > 0) { - cycles.push(pcycle) - } - pcycle = ncycle - } - } - if(pcycle.length > 0) { - cycles.push(pcycle) - } - } + if(dimension === -1) { + //Special case for trivial arrays + var code = + "function "+className+"(a){this.data=a;};\ +var proto="+className+".prototype;\ +proto.dtype='"+dtype+"';\ +proto.index=function(){return -1};\ +proto.size=0;\ +proto.dimension=-1;\ +proto.shape=proto.stride=proto.order=[];\ +proto.lo=proto.hi=proto.transpose=proto.step=\ +function(){return new "+className+"(this.data);};\ +proto.get=proto.set=function(){};\ +proto.pick=function(){return null};\ +return function construct_"+className+"(a){return new "+className+"(a);}" + var procedure = new Function(code) + return procedure() + } else if(dimension === 0) { + //Special case for 0d arrays + var code = + "function "+className+"(a,d) {\ +this.data = a;\ +this.offset = d\ +};\ +var proto="+className+".prototype;\ +proto.dtype='"+dtype+"';\ +proto.index=function(){return this.offset};\ +proto.dimension=0;\ +proto.size=1;\ +proto.shape=\ +proto.stride=\ +proto.order=[];\ +proto.lo=\ +proto.hi=\ +proto.transpose=\ +proto.step=function "+className+"_copy() {\ +return new "+className+"(this.data,this.offset)\ +};\ +proto.pick=function "+className+"_pick(){\ +return TrivialArray(this.data);\ +};\ +proto.valueOf=proto.get=function "+className+"_get(){\ +return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ +"};\ +proto.set=function "+className+"_set(v){\ +return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ +};\ +return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" + var procedure = new Function("TrivialArray", code) + return procedure(CACHED_CONSTRUCTORS[dtype][0]) } - //Combine paths and loops together - return cycles -} -},{"compare-angle":285}],285:[function(require,module,exports){ -"use strict" - -module.exports = compareAngle - -var orient = require("robust-orientation") -var sgn = require("signum") -var twoSum = require("two-sum") -var robustProduct = require("robust-product") -var robustSum = require("robust-sum") - -function testInterior(a, b, c) { - var x0 = twoSum(a[0], -b[0]) - var y0 = twoSum(a[1], -b[1]) - var x1 = twoSum(c[0], -b[0]) - var y1 = twoSum(c[1], -b[1]) - - var d = robustSum( - robustProduct(x0, x1), - robustProduct(y0, y1)) - - return d[d.length-1] >= 0 -} + var code = ["'use strict'"] -function compareAngle(a, b, c, d) { - var bcd = orient(b, c, d) - if(bcd === 0) { - //Handle degenerate cases - var sabc = sgn(orient(a, b, c)) - var sabd = sgn(orient(a, b, d)) - if(sabc === sabd) { - if(sabc === 0) { - var ic = testInterior(a, b, c) - var id = testInterior(a, b, d) - if(ic === id) { - return 0 - } else if(ic) { - return 1 - } else { - return -1 - } - } - return 0 - } else if(sabd === 0) { - if(sabc > 0) { - return -1 - } else if(testInterior(a, b, d)) { - return -1 - } else { - return 1 - } - } else if(sabc === 0) { - if(sabd > 0) { - return 1 - } else if(testInterior(a, b, c)) { - return 1 - } else { - return -1 - } - } - return sgn(sabd - sabc) - } - var abc = orient(a, b, c) - if(abc > 0) { - if(bcd > 0 && orient(a, b, d) > 0) { - return 1 - } - return -1 - } else if(abc < 0) { - if(bcd > 0 || orient(a, b, d) > 0) { - return 1 - } - return -1 + //Create constructor for view + var indices = iota(dimension) + var args = indices.map(function(i) { return "i"+i }) + var index_str = "this.offset+" + indices.map(function(i) { + return "this.stride[" + i + "]*i" + i + }).join("+") + var shapeArg = indices.map(function(i) { + return "b"+i + }).join(",") + var strideArg = indices.map(function(i) { + return "c"+i + }).join(",") + code.push( + "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a", + "this.shape=[" + shapeArg + "]", + "this.stride=[" + strideArg + "]", + "this.offset=d|0}", + "var proto="+className+".prototype", + "proto.dtype='"+dtype+"'", + "proto.dimension="+dimension) + + //view.size: + code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\ +return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"), +"}})") + + //view.order: + if(dimension === 1) { + code.push("proto.order=[0]") } else { - var abd = orient(a, b, d) - if(abd > 0) { - return 1 - } else { - if(testInterior(a, b, c)) { - return 1 - } else { - return -1 + code.push("Object.defineProperty(proto,'order',{get:") + if(dimension < 4) { + code.push("function "+className+"_order(){") + if(dimension === 2) { + code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})") + } else if(dimension === 3) { + code.push( +"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ +if(s0>s1){\ +if(s1>s2){\ +return [2,1,0];\ +}else if(s0>s2){\ +return [1,2,0];\ +}else{\ +return [1,0,2];\ +}\ +}else if(s0>s2){\ +return [2,0,1];\ +}else if(s2>s1){\ +return [0,1,2];\ +}else{\ +return [0,2,1];\ +}}})") } + } else { + code.push("ORDER})") } } -} -},{"robust-orientation":259,"robust-product":286,"robust-sum":262,"signum":287,"two-sum":277}],286:[function(require,module,exports){ -"use strict" - -var robustSum = require("robust-sum") -var robustScale = require("robust-scale") - -module.exports = robustProduct -function robustProduct(a, b) { - if(a.length === 1) { - return robustScale(b, a[0]) - } - if(b.length === 1) { - return robustScale(a, b[0]) - } - if(a.length === 0 || b.length === 0) { - return [0] - } - var r = [0] - if(a.length < b.length) { - for(var i=0; i 0) { return 1 } - return 0.0 -} -},{}],288:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],289:[function(require,module,exports){ -"use strict" -var bounds = require("binary-search-bounds") + //view.get(i0, ...): + code.push("proto.get=function "+className+"_get("+args.join(",")+"){") + if(useGetters) { + code.push("return this.data.get("+index_str+")}") + } else { + code.push("return this.data["+index_str+"]}") + } -var NOT_FOUND = 0 -var SUCCESS = 1 -var EMPTY = 2 + //view.index: + code.push( + "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") -module.exports = createWrapper + //view.hi(): + code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ + indices.map(function(i) { + return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") + }).join(",")+","+ + indices.map(function(i) { + return "this.stride["+i + "]" + }).join(",")+",this.offset)}") -function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { - this.mid = mid - this.left = left - this.right = right - this.leftPoints = leftPoints - this.rightPoints = rightPoints - this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length -} + //view.lo(): + var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) + var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) + code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) + for(var i=0; i=0){\ +d=i"+i+"|0;\ +b+=c"+i+"*d;\ +a"+i+"-=d}") + } + code.push("return new "+className+"(this.data,"+ + indices.map(function(i) { + return "a"+i + }).join(",")+","+ + indices.map(function(i) { + return "c"+i + }).join(",")+",b)}") -var proto = IntervalTreeNode.prototype + //view.step(): + code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ + indices.map(function(i) { + return "a"+i+"=this.shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "b"+i+"=this.stride["+i+"]" + }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") + for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + } + code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") -function rebuildWithInterval(node, interval) { - var intervals = node.intervals([]) - intervals.push(interval) - rebuild(node, intervals) -} + //Add return statement + code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ + indices.map(function(i) { + return "shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "stride["+i+"]" + }).join(",")+",offset)}") -function rebuildWithoutInterval(node, interval) { - var intervals = node.intervals([]) - var idx = intervals.indexOf(interval) - if(idx < 0) { - return NOT_FOUND - } - intervals.splice(idx, 1) - rebuild(node, intervals) - return SUCCESS + //Compile procedure + var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) + return procedure(CACHED_CONSTRUCTORS[dtype], order) } -proto.intervals = function(result) { - result.push.apply(result, this.leftPoints) - if(this.left) { - this.left.intervals(result) - } - if(this.right) { - this.right.intervals(result) +function arrayDType(data) { + if(isBuffer(data)) { + return "buffer" } - return result -} - -proto.insert = function(interval) { - var weight = this.count - this.leftPoints.length - this.count += 1 - if(interval[1] < this.mid) { - if(this.left) { - if(4*(this.left.count+1) > 3*(weight+1)) { - rebuildWithInterval(this, interval) - } else { - this.left.insert(interval) - } - } else { - this.left = createIntervalTree([interval]) - } - } else if(interval[0] > this.mid) { - if(this.right) { - if(4*(this.right.count+1) > 3*(weight+1)) { - rebuildWithInterval(this, interval) - } else { - this.right.insert(interval) - } - } else { - this.right = createIntervalTree([interval]) + if(hasTypedArrays) { + switch(Object.prototype.toString.call(data)) { + case "[object Float64Array]": + return "float64" + case "[object Float32Array]": + return "float32" + case "[object Int8Array]": + return "int8" + case "[object Int16Array]": + return "int16" + case "[object Int32Array]": + return "int32" + case "[object Uint8Array]": + return "uint8" + case "[object Uint16Array]": + return "uint16" + case "[object Uint32Array]": + return "uint32" + case "[object Uint8ClampedArray]": + return "uint8_clamped" } - } else { - var l = bounds.ge(this.leftPoints, interval, compareBegin) - var r = bounds.ge(this.rightPoints, interval, compareEnd) - this.leftPoints.splice(l, 0, interval) - this.rightPoints.splice(r, 0, interval) } -} - -proto.remove = function(interval) { - var weight = this.count - this.leftPoints - if(interval[1] < this.mid) { - if(!this.left) { - return NOT_FOUND - } - var rw = this.right ? this.right.count : 0 - if(4 * rw > 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) - } - var r = this.left.remove(interval) - if(r === EMPTY) { - this.left = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 - } - return r - } else if(interval[0] > this.mid) { - if(!this.right) { - return NOT_FOUND - } - var lw = this.left ? this.left.count : 0 - if(4 * lw > 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) - } - var r = this.right.remove(interval) - if(r === EMPTY) { - this.right = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 - } - return r - } else { - if(this.count === 1) { - if(this.leftPoints[0] === interval) { - return EMPTY - } else { - return NOT_FOUND - } - } - if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { - if(this.left && this.right) { - var p = this - var n = this.left - while(n.right) { - p = n - n = n.right - } - if(p === this) { - n.right = this.right - } else { - var l = this.left - var r = this.right - p.count -= n.count - p.right = n.left - n.left = l - n.right = r - } - copy(this, n) - this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length - } else if(this.left) { - copy(this, this.left) - } else { - copy(this, this.right) - } - return SUCCESS - } - for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { - var r = cb(arr[i]) - if(r) { return r } +;(function() { + for(var id in CACHED_CONSTRUCTORS) { + CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) } -} +}); -function reportRange(arr, cb) { - for(var i=0; i this.mid) { - if(this.right) { - var r = this.right.queryPoint(x, cb) - if(r) { return r } - } - return reportRightRange(this.rightPoints, x, cb) - } else { - return reportRange(this.leftPoints, cb) + if(shape === undefined) { + shape = [ data.length ] } -} - -proto.queryInterval = function(lo, hi, cb) { - if(lo < this.mid && this.left) { - var r = this.left.queryInterval(lo, hi, cb) - if(r) { return r } + var d = shape.length + if(stride === undefined) { + stride = new Array(d) + for(var i=d-1, sz=1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] + } } - if(hi > this.mid && this.right) { - var r = this.right.queryInterval(lo, hi, cb) - if(r) { return r } + if(offset === undefined) { + offset = 0 + for(var i=0; i this.mid) { - return reportRightRange(this.rightPoints, lo, cb) - } else { - return reportRange(this.leftPoints, cb) + var dtype = arrayDType(data) + var ctor_list = CACHED_CONSTRUCTORS[dtype] + while(ctor_list.length <= d+1) { + ctor_list.push(compileConstructor(dtype, ctor_list.length-1)) } + var ctor = ctor_list[d+1] + return ctor(data, shape, stride, offset) } -function compareNumbers(a, b) { - return a - b -} +module.exports = wrappedNDArrayCtor -function compareBegin(a, b) { - var d = a[0] - b[0] - if(d) { return d } - return a[1] - b[1] -} +},{"iota-array":1032,"is-buffer":1033}],1032:[function(require,module,exports){ +"use strict" -function compareEnd(a, b) { - var d = a[1] - b[1] - if(d) { return d } - return a[0] - b[0] +function iota(n) { + var result = new Array(n) + for(var i=0; i + * License: MIT + * + * `npm install is-buffer` + */ - var mid = pts[pts.length>>1] +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) +} - var leftIntervals = [] - var rightIntervals = [] - var centerIntervals = [] - for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") } } -Object.defineProperty(tproto, "count", { - get: function() { - if(this.root) { - return this.root.count +function determinant(m) { + if(m.length === 2) { + return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] + } else { + var expr = [] + for(var i=0; i b[1][0]) { - bl = b[1] - br = b[0] - } else { - var alo = Math.min(a[0][1], a[1][1]) - var ahi = Math.max(a[0][1], a[1][1]) - var blo = Math.min(b[0][1], b[1][1]) - var bhi = Math.max(b[0][1], b[1][1]) - if(ahi < blo) { - return ahi - blo +var CACHED = [ + function orientation0() { return 0 }, + function orientation1() { return 0 }, + function orientation2(a, b) { + return b[0] - a[0] + }, + function orientation3(a, b, c) { + var l = (a[1] - c[1]) * (b[0] - c[0]) + var r = (a[0] - c[0]) * (b[1] - c[1]) + var det = l - r + var s + if(l > 0) { + if(r <= 0) { + return det + } else { + s = l + r + } + } else if(l < 0) { + if(r >= 0) { + return det + } else { + s = -(l + r) + } + } else { + return det } - if(alo > bhi) { - return alo - bhi + var tol = ERRBOUND3 * s + if(det >= tol || det <= -tol) { + return det } - return ahi - bhi - } - var al, ar - if(a[0][1] < a[1][1]) { - al = a[0] - ar = a[1] - } else { - al = a[1] - ar = a[0] - } - var d = orient(br, bl, al) - if(d) { - return d + return orientation3Exact(a, b, c) + }, + function orientation4(a,b,c,d) { + var adx = a[0] - d[0] + var bdx = b[0] - d[0] + var cdx = c[0] - d[0] + var ady = a[1] - d[1] + var bdy = b[1] - d[1] + var cdy = c[1] - d[1] + var adz = a[2] - d[2] + var bdz = b[2] - d[2] + var cdz = c[2] - d[2] + var bdxcdy = bdx * cdy + var cdxbdy = cdx * bdy + var cdxady = cdx * ady + var adxcdy = adx * cdy + var adxbdy = adx * bdy + var bdxady = bdx * ady + var det = adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady) + var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) + var tol = ERRBOUND4 * permanent + if ((det > tol) || (-det > tol)) { + return det + } + return orientation4Exact(a,b,c,d) } - d = orient(br, bl, ar) - if(d) { - return d +] + +function slowOrient(args) { + var proc = CACHED[args.length] + if(!proc) { + proc = CACHED[args.length] = orientation(args.length) } - return ar - br + return proc.apply(undefined, args) } -function orderSegments(b, a) { - var al, ar - if(a[0][0] < a[1][0]) { - al = a[0] - ar = a[1] - } else if(a[0][0] > a[1][0]) { - al = a[1] - ar = a[0] - } else { - return horizontalOrder(a, b) +function generateOrientationProc() { + while(CACHED.length <= NUM_EXPAND) { + CACHED.push(orientation(CACHED.length)) } - var bl, br - if(b[0][0] < b[1][0]) { - bl = b[0] - br = b[1] - } else if(b[0][0] > b[1][0]) { - bl = b[1] - br = b[0] - } else { - return -horizontalOrder(b, a) + var args = [] + var procArgs = ["slow"] + for(var i=0; i<=NUM_EXPAND; ++i) { + args.push("a" + i) + procArgs.push("o" + i) } - var d1 = orient(al, ar, br) - var d2 = orient(al, ar, bl) - if(d1 < 0) { - if(d2 <= 0) { - return d1 - } - } else if(d1 > 0) { - if(d2 >= 0) { - return d1 - } - } else if(d2) { - return d2 + var code = [ + "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" + ] + for(var i=2; i<=NUM_EXPAND; ++i) { + code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") } - d1 = orient(br, bl, ar) - d2 = orient(br, bl, al) - if(d1 < 0) { - if(d2 <= 0) { - return d1 - } - } else if(d1 > 0) { - if(d2 >= 0) { - return d1 - } - } else if(d2) { - return d2 + code.push("}var s=new Array(arguments.length);for(var i=0;i= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); -//Insert a new item into the tree -proto.insert = function(key, value) { - var cmp = this._compare - //Find point to insert new node at - var n = this.root - var n_stack = [] - var d_stack = [] - while(n) { - var d = cmp(key, n.key) - n_stack.push(n) - d_stack.push(d) - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - //Rebuild path to leaf node - n_stack.push(new RBNode(RED, key, value, null, null, 1)) - for(var s=n_stack.length-2; s>=0; --s) { - var n = n_stack[s] - if(d_stack[s] <= 0) { - n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) - } else { - n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) - } - } - //Rebalance tree using rotations - //console.log("start insert", key, d_stack) - for(var s=n_stack.length-1; s>1; --s) { - var p = n_stack[s-1] - var n = n_stack[s] - if(p._color === BLACK || n._color === BLACK) { - break - } - var pp = n_stack[s-2] - if(pp.left === p) { - if(p.left === n) { - var y = pp.right - if(y && y._color === RED) { - //console.log("LLr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LLb") - pp._color = RED - pp.left = p.right - p._color = BLACK - p.right = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = p - } else { - ppp.right = p + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); } - } - break + return this.toRgbString(); } - } else { - var y = pp.right - if(y && y._color === RED) { - //console.log("LRr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LRb") - p.right = n.left - pp._color = RED - pp.left = n.right - n._color = BLACK - n.left = p - n.right = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = n - } else { - ppp.right = n - } - } - break + if (format === "rgb") { + formattedString = this.toRgbString(); } - } - } else { - if(p.right === n) { - var y = pp.left - if(y && y._color === RED) { - //console.log("RRr", y.key) - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RRb") - pp._color = RED - pp.right = p.left - p._color = BLACK - p.left = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = p - } else { - ppp.left = p - } - } - break + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); } - } else { - var y = pp.left - if(y && y._color === RED) { - //console.log("RLr") - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RLb") - p.left = n.right - pp._color = RED - pp.right = n.left - n._color = BLACK - n.right = p - n.left = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = n - } else { - ppp.left = n - } - } - break + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); } - } - } - } - //Return new tree - n_stack[0]._color = BLACK - return new RedBlackTree(cmp, n_stack[0]) -} + return formattedString || this.toHexString(); + }, + clone: function() { + return tinycolor(this.toString()); + }, -//Visit all nodes inorder -function doVisitFull(visit, node) { - if(node.left) { - var v = doVisitFull(visit, node.left) - if(v) { return v } - } - var v = visit(node.key, node.value) - if(v) { return v } - if(node.right) { - return doVisitFull(visit, node.right) - } -} + _applyModification: function(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function() { + return this._applyModification(lighten, arguments); + }, + brighten: function() { + return this._applyModification(brighten, arguments); + }, + darken: function() { + return this._applyModification(darken, arguments); + }, + desaturate: function() { + return this._applyModification(desaturate, arguments); + }, + saturate: function() { + return this._applyModification(saturate, arguments); + }, + greyscale: function() { + return this._applyModification(greyscale, arguments); + }, + spin: function() { + return this._applyModification(spin, arguments); + }, -//Visit half nodes in order -function doVisitHalf(lo, compare, visit, node) { - var l = compare(lo, node.key) - if(l <= 0) { - if(node.left) { - var v = doVisitHalf(lo, compare, visit, node.left) - if(v) { return v } + _applyCombination: function(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function() { + return this._applyCombination(analogous, arguments); + }, + complement: function() { + return this._applyCombination(complement, arguments); + }, + monochromatic: function() { + return this._applyCombination(monochromatic, arguments); + }, + splitcomplement: function() { + return this._applyCombination(splitcomplement, arguments); + }, + triad: function() { + return this._applyCombination(triad, arguments); + }, + tetrad: function() { + return this._applyCombination(tetrad, arguments); } - var v = visit(node.key, node.value) - if(v) { return v } - } - if(node.right) { - return doVisitHalf(lo, compare, visit, node.right) - } -} +}; -//Visit all nodes within a range -function doVisit(lo, hi, compare, visit, node) { - var l = compare(lo, node.key) - var h = compare(hi, node.key) - var v - if(l <= 0) { - if(node.left) { - v = doVisit(lo, hi, compare, visit, node.left) - if(v) { return v } +// If input is an object, force 1 into "1.0" to handle ratios properly +// String input requires "1.0" as input, so 1 will be treated as 1 +tinycolor.fromRatio = function(color, opts) { + if (typeof color == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } + else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; } - if(h > 0) { - v = visit(node.key, node.value) - if(v) { return v } + + return tinycolor(color, opts); +}; + +// Given a string or object, convert that input to RGB +// Possible string inputs: +// +// "red" +// "#f00" or "f00" +// "#ff0000" or "ff0000" +// "#ff000000" or "ff000000" +// "rgb 255 0 0" or "rgb (255, 0, 0)" +// "rgb 1.0 0 0" or "rgb (1, 0, 0)" +// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" +// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" +// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" +// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" +// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" +// +function inputToRGB(color) { + + var rgb = { r: 0, g: 0, b: 0 }; + var a = 1; + var ok = false; + var format = false; + + if (typeof color == "string") { + color = stringInputToObject(color); } - } - if(h > 0 && node.right) { - return doVisit(lo, hi, compare, visit, node.right) - } -} + if (typeof color == "object") { + if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { + color.s = convertToPercentage(color.s); + color.v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, color.s, color.v); + ok = true; + format = "hsv"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { + color.s = convertToPercentage(color.s); + color.l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, color.s, color.l); + ok = true; + format = "hsl"; + } -proto.forEach = function rbTreeForEach(visit, lo, hi) { - if(!this.root) { - return - } - switch(arguments.length) { - case 1: - return doVisitFull(visit, this.root) - break + if (color.hasOwnProperty("a")) { + a = color.a; + } + } - case 2: - return doVisitHalf(lo, this._compare, visit, this.root) - break + a = boundAlpha(a); - case 3: - if(this._compare(lo, hi) >= 0) { - return - } - return doVisit(lo, hi, this._compare, visit, this.root) - break - } + return { + ok: ok, + format: color.format || format, + r: mathMin(255, mathMax(rgb.r, 0)), + g: mathMin(255, mathMax(rgb.g, 0)), + b: mathMin(255, mathMax(rgb.b, 0)), + a: a + }; } -//First item in list -Object.defineProperty(proto, "begin", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.left - } - return new RedBlackTreeIterator(this, stack) - } -}) -//Last item in list -Object.defineProperty(proto, "end", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.right - } - return new RedBlackTreeIterator(this, stack) - } -}) +// Conversion Functions +// -------------------- -//Find the ith item in the tree -proto.at = function(idx) { - if(idx < 0) { - return new RedBlackTreeIterator(this, []) - } - var n = this.root - var stack = [] - while(true) { - stack.push(n) - if(n.left) { - if(idx < n.left._count) { - n = n.left - continue - } - idx -= n.left._count - } - if(!idx) { - return new RedBlackTreeIterator(this, stack) - } - idx -= 1 - if(n.right) { - if(idx >= n.right._count) { - break - } - n = n.right - } else { - break - } - } - return new RedBlackTreeIterator(this, []) +// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: +// + +// `rgbToRgb` +// Handle bounds / percentage checking to conform to CSS color spec +// +// *Assumes:* r, g, b in [0, 255] or [0, 1] +// *Returns:* { r, g, b } in [0, 255] +function rgbToRgb(r, g, b){ + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; } -proto.ge = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d <= 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} +// `rgbToHsl` +// Converts an RGB color value to HSL. +// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] +// *Returns:* { h, s, l } in [0,1] +function rgbToHsl(r, g, b) { -proto.gt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d < 0) { - last_ptr = stack.length + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, l = (max + min) / 2; + + if(max == min) { + h = s = 0; // achromatic } - if(d < 0) { - n = n.left - } else { - n = n.right + else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + + h /= 6; } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + + return { h: h, s: s, l: l }; } -proto.lt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d > 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right +// `hslToRgb` +// Converts an HSL color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hslToRgb(h, s, l) { + var r, g, b; + + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + + function hue2rgb(p, q, t) { + if(t < 0) t += 1; + if(t > 1) t -= 1; + if(t < 1/6) return p + (q - p) * 6 * t; + if(t < 1/2) return q; + if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} -proto.le = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d >= 0) { - last_ptr = stack.length + if(s === 0) { + r = g = b = l; // achromatic } - if(d < 0) { - n = n.left - } else { - n = n.right + else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) + + return { r: r * 255, g: g * 255, b: b * 255 }; } -//Finds the item with key if it exists -proto.find = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d === 0) { - return new RedBlackTreeIterator(this, stack) +// `rgbToHsv` +// Converts an RGB color value to HSV +// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] +// *Returns:* { h, s, v } in [0,1] +function rgbToHsv(r, g, b) { + + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, v = max; + + var d = max - min; + s = max === 0 ? 0 : d / max; + + if(max == min) { + h = 0; // achromatic } - if(d <= 0) { - n = n.left - } else { - n = n.right + else { + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; } - } - return new RedBlackTreeIterator(this, []) + return { h: h, s: s, v: v }; } -//Removes item with key from tree -proto.remove = function(key) { - var iter = this.find(key) - if(iter) { - return iter.remove() - } - return this +// `hsvToRgb` +// Converts an HSV color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + + var i = math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + + return { r: r * 255, g: g * 255, b: b * 255 }; } -//Returns the item at `key` -proto.get = function(key) { - var cmp = this._compare - var n = this.root - while(n) { - var d = cmp(key, n.key) - if(d === 0) { - return n.value - } - if(d <= 0) { - n = n.left - } else { - n = n.right +// `rgbToHex` +// Converts an RGB color to hex +// Assumes r, g, and b are contained in the set [0, 255] +// Returns a 3 or 6 character hex +function rgbToHex(r, g, b, allow3Char) { + + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } - } - return + + return hex.join(""); } -//Iterator for red black tree -function RedBlackTreeIterator(tree, stack) { - this.tree = tree - this._stack = stack +// `rgbaToHex` +// Converts an RGBA color plus alpha transparency to hex +// Assumes r, g, b and a are contained in the set [0, 255] +// Returns an 8 character hex +function rgbaToHex(r, g, b, a) { + + var hex = [ + pad2(convertDecimalToHex(a)), + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + return hex.join(""); } -var iproto = RedBlackTreeIterator.prototype +// `equals` +// Can be called with any tinycolor input +tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) { return false; } + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); +}; -//Test if iterator is valid -Object.defineProperty(iproto, "valid", { - get: function() { - return this._stack.length > 0 - } -}) +tinycolor.random = function() { + return tinycolor.fromRatio({ + r: mathRandom(), + g: mathRandom(), + b: mathRandom() + }); +}; -//Node of the iterator -Object.defineProperty(iproto, "node", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1] - } - return null - }, - enumerable: true -}) -//Makes a copy of an iterator -iproto.clone = function() { - return new RedBlackTreeIterator(this.tree, this._stack.slice()) +// Modification Functions +// ---------------------- +// Thanks to less.js for some of the basics here +// + +function desaturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); } -//Swaps two nodes -function swapNode(n, v) { - n.key = v.key - n.value = v.value - n.left = v.left - n.right = v.right - n._color = v._color - n._count = v._count +function saturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); } -//Fix up a double black node in a tree -function fixDoubleBlack(stack) { - var n, p, s, z - for(var i=stack.length-1; i>=0; --i) { - n = stack[i] - if(i === 0) { - n._color = BLACK - return - } - //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) - p = stack[i-1] - if(p.left === n) { - //console.log("left child") - s = p.right - if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.right = cloneNode(s) - z = s.right = cloneNode(s.right) - p.right = s.left - s.left = p - s.right = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - return - } else if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red") - s = p.right = cloneNode(s) - z = s.left = cloneNode(s.left) - p.right = z.left - s.left = z.right - z.left = p - z.right = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = z - } else { - pp.right = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent", p.right.value) - p._color = BLACK - p.right = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent", p.right.value) - p.right = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.right = s.left - s.left = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } else { - //console.log("right child") - s = p.left - if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red", p.value, p._color) - s = p.left = cloneNode(s) - z = s.left = cloneNode(s.left) - p.left = s.right - s.right = p - s.left = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - return - } else if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.left = cloneNode(s) - z = s.right = cloneNode(s.right) - p.left = z.right - s.right = z.left - z.right = p - z.left = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = z - } else { - pp.left = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent") - p._color = BLACK - p.left = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent") - p.left = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.left = s.right - s.right = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } - } +function greyscale(color) { + return tinycolor(color).desaturate(100); +} + +function lighten (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); } -//Removes item at iterator from tree -iproto.remove = function() { - var stack = this._stack - if(stack.length === 0) { - return this.tree - } - //First copy path to node - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - var n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - } +function brighten(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var rgb = tinycolor(color).toRgb(); + rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); + rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); + rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); + return tinycolor(rgb); +} - //Get node - n = cstack[cstack.length-1] - //console.log("start remove: ", n.value) +function darken (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} - //If not leaf, then swap with previous node - if(n.left && n.right) { - //console.log("moving to leaf") +// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. +// Values outside of this range will be wrapped into this range. +function spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (mathRound(hsl.h) + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); +} - //First walk to previous leaf - var split = cstack.length - n = n.left - while(n.right) { - cstack.push(n) - n = n.right - } - //Copy path to leaf - var v = cstack[split-1] - cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) - cstack[split-1].key = n.key - cstack[split-1].value = n.value +// Combination Functions +// --------------------- +// Thanks to jQuery xColor for some of the ideas behind these +// - //Fix up stack - for(var i=cstack.length-2; i>=split; --i) { - n = cstack[i] - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - cstack[split-1].left = cstack[split] - } - //console.log("stack=", cstack.map(function(v) { return v.value })) +function complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); +} - //Remove leaf node - n = cstack[cstack.length-1] - if(n._color === RED) { - //Easy case: removing red leaf - //console.log("RED leaf") - var p = cstack[cstack.length-2] - if(p.left === n) { - p.left = null - } else if(p.right === n) { - p.right = null - } - cstack.pop() - for(var i=0; i> 1)) + 720) % 360; --results; ) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); } - } - return new RedBlackTree(this.tree._compare, cstack[0]) + return ret; } -//Returns key -Object.defineProperty(iproto, "key", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].key +function monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, s = hsv.s, v = hsv.v; + var ret = []; + var modification = 1 / results; + + while (results--) { + ret.push(tinycolor({ h: h, s: s, v: v})); + v = (v + modification) % 1; } - return - }, - enumerable: true -}) -//Returns value -Object.defineProperty(iproto, "value", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].value + return ret; +} + +// Utility Functions +// --------------------- + +tinycolor.mix = function(color1, color2, amount) { + amount = (amount === 0) ? 0 : (amount || 50); + + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + + var p = amount / 100; + var w = p * 2 - 1; + var a = rgb2.a - rgb1.a; + + var w1; + + if (w * a == -1) { + w1 = w; + } else { + w1 = (w + a) / (1 + w * a); } - return - }, - enumerable: true -}) + w1 = (w1 + 1) / 2; -//Returns the position of this iterator in the sorted list -Object.defineProperty(iproto, "index", { - get: function() { - var idx = 0 - var stack = this._stack - if(stack.length === 0) { - var r = this.tree.root - if(r) { - return r._count - } - return 0 - } else if(stack[stack.length-1].left) { - idx = stack[stack.length-1].left._count + var w2 = 1 - w1; + + var rgba = { + r: rgb2.r * w1 + rgb1.r * w2, + g: rgb2.g * w1 + rgb1.g * w2, + b: rgb2.b * w1 + rgb1.b * w2, + a: rgb2.a * p + rgb1.a * (1 - p) + }; + + return tinycolor(rgba); +}; + + +// Readability Functions +// --------------------- +// false +// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false +tinycolor.isReadable = function(color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + + out = false; + + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; } - for(var s=stack.length-2; s>=0; --s) { - if(stack[s+1] === stack[s].right) { - ++idx - if(stack[s].left) { - idx += stack[s].left._count + return out; + +}; + +// `mostReadable` +// Given a base color and a list of possible foreground or background +// colors for that base, returns the most readable color. +// Optionally returns Black or White if the most readable color is unreadable. +// *Example* +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" +tinycolor.mostReadable = function(baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size ; + args = args || {}; + includeFallbackColors = args.includeFallbackColors ; + level = args.level; + size = args.size; + + for (var i= 0; i < colorList.length ; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); } - } } - return idx - }, - enumerable: true -}) -//Advances iterator to next element in list -iproto.next = function() { - var stack = this._stack - if(stack.length === 0) { - return - } - var n = stack[stack.length-1] - if(n.right) { - n = n.right - while(n) { - stack.push(n) - n = n.left + if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { + return bestColor; } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].right === n) { - n = stack[stack.length-1] - stack.pop() + else { + args.includeFallbackColors=false; + return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); } - } -} +}; + + +// Big List of Colors +// ------------------ +// +var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; + +// Make it easy to access colors via `hexNames[hex]` +var hexNames = tinycolor.hexNames = flip(names); + -//Checks if iterator is at end of tree -Object.defineProperty(iproto, "hasNext", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].right) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].left === stack[s]) { - return true - } - } - return false - } -}) +// Utilities +// --------- -//Update value -iproto.update = function(value) { - var stack = this._stack - if(stack.length === 0) { - throw new Error("Can't update empty node!") - } - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) +// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` +function flip(o) { + var flipped = { }; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } } - } - return new RedBlackTree(this.tree._compare, cstack[0]) + return flipped; } -//Moves iterator backward one element -iproto.prev = function() { - var stack = this._stack - if(stack.length === 0) { - return - } - var n = stack[stack.length-1] - if(n.left) { - n = n.left - while(n) { - stack.push(n) - n = n.right - } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].left === n) { - n = stack[stack.length-1] - stack.pop() +// Return a valid alpha value [0,1] with all invalid values being set to 1 +function boundAlpha(a) { + a = parseFloat(a); + + if (isNaN(a) || a < 0 || a > 1) { + a = 1; } - } + + return a; } -//Checks if iterator is at start of tree -Object.defineProperty(iproto, "hasPrev", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].left) { - return true +// Take input from [0, n] and return it as [0, 1] +function bound01(n, max) { + if (isOnePointZero(n)) { n = "100%"; } + + var processPercent = isPercentage(n); + n = mathMin(max, mathMax(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].right === stack[s]) { - return true - } + + // Handle floating point rounding errors + if ((math.abs(n - max) < 0.000001)) { + return 1; } - return false - } -}) -//Default comparison function -function defaultCompare(a, b) { - if(a < b) { - return -1 - } - if(a > b) { - return 1 - } - return 0 + // Convert into [0, 1] range if it isn't already + return (n % max) / parseFloat(max); } -//Build a tree -function createRBTree(compare) { - return new RedBlackTree(compare || defaultCompare, null) +// Force a number between 0 and 1 +function clamp01(val) { + return mathMin(1, mathMax(0, val)); } -},{}],292:[function(require,module,exports){ -"use strict" -module.exports = createSlabDecomposition +// Parse a base-16 hex value into a base-10 integer +function parseIntFromHex(val) { + return parseInt(val, 16); +} -var bounds = require("binary-search-bounds") -var createRBTree = require("functional-red-black-tree") -var orient = require("robust-orientation") -var orderSegments = require("./lib/order-segments") +// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 +// +function isOnePointZero(n) { + return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; +} -function SlabDecomposition(slabs, coordinates, horizontal) { - this.slabs = slabs - this.coordinates = coordinates - this.horizontal = horizontal +// Check to see if string passed in is a percentage +function isPercentage(n) { + return typeof n === "string" && n.indexOf('%') != -1; } -var proto = SlabDecomposition.prototype +// Force a hex value to have 2 characters +function pad2(c) { + return c.length == 1 ? '0' + c : '' + c; +} -function compareHorizontal(e, y) { - return e.y - y +// Replace a decimal with it's percentage value +function convertToPercentage(n) { + if (n <= 1) { + n = (n * 100) + "%"; + } + + return n; } -function searchBucket(root, p) { - var lastNode = null - while(root) { - var seg = root.key - var l, r - if(seg[0][0] < seg[1][0]) { - l = seg[0] - r = seg[1] - } else { - l = seg[1] - r = seg[0] +// Converts a decimal to a hex value +function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); +} +// Converts a hex value to a decimal +function convertHexToDecimal(h) { + return (parseIntFromHex(h) / 255); +} + +var matchers = (function() { + + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + + return { + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; +})(); + +// `stringInputToObject` +// Permissive string parsing. Take in a number of formats, and output an object +// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` +function stringInputToObject(color) { + + color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; } - var o = orient(l, r, p) - if(o < 0) { - root = root.left - } else if(o > 0) { - if(p[0] !== seg[1][0]) { - lastNode = root - root = root.right - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } - } else { - if(p[0] !== seg[1][0]) { - return root - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } + else if (color == 'transparent') { + return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } - } - return lastNode -} -proto.castUp = function(p) { - var bucket = bounds.le(this.coordinates, p[0]) - if(bucket < 0) { - return -1 - } - var root = this.slabs[bucket] - var hitNode = searchBucket(this.slabs[bucket], p) - var lastHit = -1 - if(hitNode) { - lastHit = hitNode.value - } - //Edge case: need to handle horizontal segments (sucks) - if(this.coordinates[bucket] === p[0]) { - var lastSegment = null - if(hitNode) { - lastSegment = hitNode.key + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if ((match = matchers.rgb.exec(color))) { + return { r: match[1], g: match[2], b: match[3] }; } - if(bucket > 0) { - var otherHitNode = searchBucket(this.slabs[bucket-1], p) - if(otherHitNode) { - if(lastSegment) { - if(orderSegments(otherHitNode.key, lastSegment) > 0) { - lastSegment = otherHitNode.key - lastHit = otherHitNode.value - } - } else { - lastHit = otherHitNode.value - lastSegment = otherHitNode.key - } - } + if ((match = matchers.rgba.exec(color))) { + return { r: match[1], g: match[2], b: match[3], a: match[4] }; } - var horiz = this.horizontal[bucket] - if(horiz.length > 0) { - var hbucket = bounds.ge(horiz, p[1], compareHorizontal) - if(hbucket < horiz.length) { - var e = horiz[hbucket] - if(p[1] === e.y) { - if(e.closed) { - return e.index - } else { - while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { - hbucket = hbucket+1 - e = horiz[hbucket] - if(e.closed) { - return e.index - } - } - if(e.y === p[1] && !e.start) { - hbucket = hbucket+1 - if(hbucket >= horiz.length) { - return lastHit - } - e = horiz[hbucket] - } - } - } - //Check if e is above/below last segment - if(e.start) { - if(lastSegment) { - var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) - if(lastSegment[0][0] > lastSegment[1][0]) { - o = -o - } - if(o > 0) { - lastHit = e.index - } - } else { - lastHit = e.index - } - } else if(e.y !== p[1]) { - lastHit = e.index - } - } + if ((match = matchers.hsl.exec(color))) { + return { h: match[1], s: match[2], l: match[3] }; } - } - return lastHit + if ((match = matchers.hsla.exec(color))) { + return { h: match[1], s: match[2], l: match[3], a: match[4] }; + } + if ((match = matchers.hsv.exec(color))) { + return { h: match[1], s: match[2], v: match[3] }; + } + if ((match = matchers.hsva.exec(color))) { + return { h: match[1], s: match[2], v: match[3], a: match[4] }; + } + if ((match = matchers.hex8.exec(color))) { + return { + a: convertHexToDecimal(match[1]), + r: parseIntFromHex(match[2]), + g: parseIntFromHex(match[3]), + b: parseIntFromHex(match[4]), + format: named ? "name" : "hex8" + }; + } + if ((match = matchers.hex6.exec(color))) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if ((match = matchers.hex3.exec(color))) { + return { + r: parseIntFromHex(match[1] + '' + match[1]), + g: parseIntFromHex(match[2] + '' + match[2]), + b: parseIntFromHex(match[3] + '' + match[3]), + format: named ? "name" : "hex" + }; + } + + return false; } -function IntervalSegment(y, index, start, closed) { - this.y = y - this.index = index - this.start = start - this.closed = closed +function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || {"level":"AA", "size":"small"}; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return {"level":level, "size":size}; } -function Event(x, segment, create, index) { - this.x = x - this.segment = segment - this.create = create - this.index = index +// Node: Export function +if (typeof module !== "undefined" && module.exports) { + module.exports = tinycolor; +} +// AMD/requirejs: Define the module +else if (typeof define === 'function' && define.amd) { + define(function () {return tinycolor;}); +} +// Browser: Expose to window +else { + window.tinycolor = tinycolor; } +})(); -function createSlabDecomposition(segments) { - var numSegments = segments.length - var numEvents = 2 * numSegments - var events = new Array(numEvents) - for(var i=0; i>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; } - return false + return lo; } -} -function buildVerticalIndex(segments) { - var table = {} - for(var i=0; i 0 && coordinates[bucket] === p[0]) { - root = slabs[bucket-1] - } else { - return 1 + function object(topology, o) { + var absolute = transformAbsolute(topology.transform), + arcs = topology.arcs; + + function arc(i, points) { + if (points.length) points.pop(); + for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { + points.push(p = a[k].slice()); + absolute(p, k); } + if (i < 0) reverse(points, n); } - var lastOrientation = 1 - while(root) { - var s = root.key - var o = orient(p, s[0], s[1]) - if(s[0][0] < s[1][0]) { - if(o < 0) { - root = root.left - } else if(o > 0) { - lastOrientation = -1 - root = root.right - } else { - return 0 - } - } else { - if(o > 0) { - root = root.left - } else if(o < 0) { - lastOrientation = 1 - root = root.right - } else { - return 0 - } - } + + function point(p) { + p = p.slice(); + absolute(p, 0); + return p; } - return lastOrientation - } -} -function classifyEmpty(p) { - return 1 -} + function line(arcs) { + var points = []; + for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); + if (points.length < 2) points.push(points[0].slice()); + return points; + } -function createClassifyVertical(testVertical) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 + function ring(arcs) { + var points = line(arcs); + while (points.length < 4) points.push(points[0].slice()); + return points; } - return 1 - } -} -function createClassifyPointDegen(testVertical, testNormal) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 + function polygon(arcs) { + return arcs.map(ring); } - return testNormal(p) + + function geometry(o) { + var t = o.type; + return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} + : t in geometryType ? {type: t, coordinates: geometryType[t](o)} + : null; + } + + var geometryType = { + Point: function(o) { return point(o.coordinates); }, + MultiPoint: function(o) { return o.coordinates.map(point); }, + LineString: function(o) { return line(o.arcs); }, + MultiLineString: function(o) { return o.arcs.map(line); }, + Polygon: function(o) { return polygon(o.arcs); }, + MultiPolygon: function(o) { return o.arcs.map(polygon); } + }; + + return geometry(o); } -} -function preprocessPolygon(loops) { - //Compute number of loops - var numLoops = loops.length + function stitchArcs(topology, arcs) { + var stitchedArcs = {}, + fragmentByStart = {}, + fragmentByEnd = {}, + fragments = [], + emptyIndex = -1; - //Unpack segments - var segments = [] - var vsegments = [] - var ptr = 0 - for(var i=0; i 1) { + var geomsByArc = [], + geom; - //Check orientation of a polygon using exact arithmetic - function ccw(c) { - var n = c.length - var area = [0] - for(var j=0; j 0 - } + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs) { arcs.forEach(polygon); } + }; - //Extract all clockwise faces - faces = faces.filter(ccw) + geometry(o); - //Detect which loops are contained in one another to handle parent-of relation - var numFaces = faces.length - var parent = new Array(numFaces) - var containment = new Array(numFaces) - for(var i=0; i 0) { - var top = toVisit.pop() - var nbhd = fadj[top] - uniq(nbhd, function(a,b) { - return a-b - }) - var nnbhr = nbhd.length - var p = parity[top] - var polyline - if(p === 0) { - var c = faces[top] - polyline = [c] + function area(ring$$) { + return Math.abs(ring(object(topology, {type: "Polygon", arcs: [ring$$]}).coordinates[0])); } - for(var i=0; i= 0) { - continue - } - parity[f] = p^1 - toVisit.push(f) - if(p === 0) { - var c = faces[f] - if(!sharedBoundary(c)) { - c.reverse() - polyline.push(c) + + polygons.forEach(function(polygon) { + if (!polygon._) { + var component = [], + neighbors = [polygon]; + polygon._ = 1; + components.push(component); + while (polygon = neighbors.pop()) { + component.push(polygon); + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { + if (!polygon._) { + polygon._ = 1; + neighbors.push(polygon); + } + }); + }); + }); } } - } - if(p === 0) { - result.push(polyline) - } - } + }); - return result -} -},{"./lib/trim-leaves":282,"edges-to-adjacency-list":283,"planar-dual":284,"point-in-big-polygon":293,"robust-sum":262,"two-product":276,"uniq":279}],295:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],296:[function(require,module,exports){ -"use strict"; "use restrict"; + polygons.forEach(function(polygon) { + delete polygon._; + }); -module.exports = UnionFind; + return { + type: "MultiPolygon", + arcs: components.map(function(polygons) { + var arcs = [], n; -function UnionFind(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; i 1) { + for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { + if ((ki = area(arcs[i])) > k) { + t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; + } + } + } -UnionFind.prototype.find = function(x) { - var roots = this.roots; - while(roots[x] !== x) { - var y = roots[x]; - roots[x] = roots[y]; - x = y; + return arcs; + }) + }; } - return x; -} -UnionFind.prototype.link = function(x, y) { - var xr = this.find(x) - , yr = this.find(y); - if(xr === yr) { - return; - } - var ranks = this.ranks - , roots = this.roots - , xd = ranks[xr] - , yd = ranks[yr]; - if(xd < yd) { - roots[xr] = yr; - } else if(yd < xd) { - roots[yr] = xr; - } else { - roots[yr] = xr; - ++ranks[xr]; - } -} + function neighbors(objects) { + var indexesByArc = {}, // arc index -> array of object indexes + neighbors = objects.map(function() { return []; }); + function line(arcs, i) { + arcs.forEach(function(a) { + if (a < 0) a = ~a; + var o = indexesByArc[a]; + if (o) o.push(i); + else indexesByArc[a] = [i]; + }); + } -},{}],297:[function(require,module,exports){ -arguments[4][238][0].apply(exports,arguments) -},{"bit-twiddle":295,"dup":238,"union-find":296}],298:[function(require,module,exports){ -"use strict" + function polygon(arcs, i) { + arcs.forEach(function(arc) { line(arc, i); }); + } -module.exports = simplifyPolygon + function geometry(o, i) { + if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); + else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + } -var orient = require("robust-orientation") -var sc = require("simplicial-complex") + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } + }; -function errorWeight(base, a, b) { - var area = Math.abs(orient(base, a, b)) - var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2)) - return area / perim -} + objects.forEach(geometry); -function simplifyPolygon(cells, positions, minArea) { + for (var i in indexesByArc) { + for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { + for (var k = j + 1; k < m; ++k) { + var ij = indexes[j], ik = indexes[k], n; + if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); + if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); + } + } + } - var n = positions.length - var nc = cells.length - var inv = new Array(n) - var outv = new Array(n) - var weights = new Array(n) - var dead = new Array(n) - - //Initialize tables - for(var i=0; i 0) object = array[size], down(array[object._ = 0] = object, 0); + return removed; + }; - function heapParent(i) { - if(i & 1) { - return (i - 1) >> 1 - } - return (i >> 1) - 1 - } + heap.remove = function(removed) { + var i = removed._, object; + if (array[i] !== removed) return; // invalid request + if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); + return i; + }; - //Bubble element i down the heap - function heapDown(i) { - var w = heapWeight(i) - while(true) { - var tw = w - var left = 2*i + 1 - var right = 2*(i + 1) - var next = i - if(left < heapCount) { - var lw = heapWeight(left) - if(lw < tw) { - next = left - tw = lw - } - } - if(right < heapCount) { - var rw = heapWeight(right) - if(rw < tw) { - next = right - } - } - if(next === i) { - return i + function up(object, i) { + while (i > 0) { + var j = ((i + 1) >> 1) - 1, + parent = array[j]; + if (compareArea(object, parent) >= 0) break; + array[parent._ = i] = parent; + array[object._ = i = j] = object; } - heapSwap(i, next) - i = next } - } - //Bubbles element i up the heap - function heapUp(i) { - var w = heapWeight(i) - while(i > 0) { - var parent = heapParent(i) - if(parent >= 0) { - var pw = heapWeight(parent) - if(w < pw) { - heapSwap(i, parent) - i = parent - continue - } + function down(object, i) { + while (true) { + var r = (i + 1) << 1, + l = r - 1, + j = i, + child = array[j]; + if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; + if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; + if (j === i) break; + array[child._ = i] = child; + array[object._ = i = j] = object; } - return i } - } - //Pop minimum element - function heapPop() { - if(heapCount > 0) { - var head = heap[0] - heapSwap(0, heapCount-1) - heapCount -= 1 - heapDown(0) - return head - } - return -1 + return heap; } - //Update heap item i - function heapUpdate(i, w) { - var a = heap[i] - if(weights[a] === w) { - return i - } - weights[a] = -Infinity - heapUp(i) - heapPop() - weights[a] = w - heapCount += 1 - return heapUp(heapCount-1) - } + function presimplify(topology, triangleArea) { + var absolute = transformAbsolute(topology.transform), + relative = transformRelative(topology.transform), + heap = minAreaHeap(); - //Kills a vertex (assume vertex already removed from heap) - function kill(i) { - if(dead[i]) { - return - } - //Kill vertex - dead[i] = true - //Fixup topology - var s = inv[i] - var t = outv[i] - if(inv[t] >= 0) { - inv[t] = s - } - if(outv[s] >= 0) { - outv[s] = t - } + if (!triangleArea) triangleArea = cartesianTriangleArea; - //Update weights on s and t - if(index[s] >= 0) { - heapUpdate(index[s], computeWeight(s)) - } - if(index[t] >= 0) { - heapUpdate(index[t], computeWeight(t)) - } - } + topology.arcs.forEach(function(arc) { + var triangles = [], + maxArea = 0, + triangle, + i, + n, + p; - //Initialize weights and heap - var heap = [] - var index = new Array(n) - for(var i=0; i>1; i>=0; --i) { - heapDown(i) - } - - //Kill vertices - while(true) { - var hmin = heapPop() - if((hmin < 0) || (weights[hmin] > minArea)) { - break - } - kill(hmin) - } + // To store each point’s effective area, we create a new array rather than + // extending the passed-in point to workaround a Chrome/V8 bug (getting + // stuck in smi mode). For midpoints, the initial effective area of + // Infinity will be computed in the next step. + for (i = 0, n = arc.length; i < n; ++i) { + p = arc[i]; + absolute(arc[i] = [p[0], p[1], Infinity], i); + } - //Build collapsed vertex table - var npositions = [] - for(var i=0; i= 0 && tout >= 0 && tin !== tout) { - var cin = index[tin] - var cout = index[tout] - if(cin !== cout) { - ncells.push([ cin, cout ]) - } - } - }) + var version = "1.6.26"; - //Normalize result - sc.unique(sc.normalize(ncells)) + exports.version = version; + exports.mesh = mesh; + exports.meshArcs = meshArcs; + exports.merge = merge; + exports.mergeArcs = mergeArcs; + exports.feature = feature; + exports.neighbors = neighbors; + exports.presimplify = presimplify; - //Return final list of cells - return { - positions: npositions, - edges: ncells - } -} -},{"robust-orientation":259,"simplicial-complex":297}],299:[function(require,module,exports){ +})); +},{}],1044:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -50296,7 +52313,7 @@ module.exports = [ } ]; -},{}],300:[function(require,module,exports){ +},{}],1045:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -50469,7 +52486,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/cartesian/constants":410,"../../plots/font_attributes":423,"./arrow_paths":299}],301:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/cartesian/constants":1155,"../../plots/font_attributes":1168,"./arrow_paths":1044}],1046:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51398,7 +53415,7 @@ function lineIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { return {x: x1 + a * t, y: y1 + d * t}; } -},{"../../lib":382,"../../lib/setcursor":391,"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/cartesian/axes":405,"../color":303,"../dragelement":324,"../drawing":326,"./arrow_paths":299,"./attributes":300,"d3":113,"fast-isnumeric":117}],302:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../dragelement":1069,"../drawing":1071,"./arrow_paths":1044,"./attributes":1045,"d3":82,"fast-isnumeric":90}],1047:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51436,7 +53453,7 @@ exports.background = '#fff'; // gives back exactly lightLine if the other colors are defaults. exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); -},{}],303:[function(require,module,exports){ +},{}],1048:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51580,7 +53597,7 @@ function cleanOne(val) { return 'rgb(' + rgbStr + ')'; } -},{"./attributes":302,"fast-isnumeric":117,"tinycolor2":274}],304:[function(require,module,exports){ +},{"./attributes":1047,"fast-isnumeric":90,"tinycolor2":1042}],1049:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51735,7 +53752,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/cartesian/layout_attributes":414,"../../plots/font_attributes":423}],305:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/cartesian/layout_attributes":1159,"../../plots/font_attributes":1168}],1050:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -51802,7 +53819,7 @@ module.exports = function colorbarDefaults(containerIn, containerOut, layout) { coerce('titleside'); }; -},{"../../lib":382,"../../plots/cartesian/tick_label_defaults":420,"../../plots/cartesian/tick_mark_defaults":421,"../../plots/cartesian/tick_value_defaults":422,"./attributes":304}],306:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/tick_label_defaults":1165,"../../plots/cartesian/tick_mark_defaults":1166,"../../plots/cartesian/tick_value_defaults":1167,"./attributes":1049}],1051:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52432,7 +54449,7 @@ module.exports = function draw(gd, id) { return component; }; -},{"../../lib":382,"../../lib/extend":377,"../../lib/setcursor":391,"../../plotly":402,"../../plots/cartesian/axes":405,"../../plots/cartesian/axis_defaults":406,"../../plots/cartesian/layout_attributes":414,"../../plots/cartesian/position_defaults":417,"../../plots/plots":454,"../color":303,"../dragelement":324,"../drawing":326,"../titles":366,"./attributes":304,"d3":113,"tinycolor2":274}],307:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/extend":1122,"../../lib/setcursor":1136,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../../plots/cartesian/axis_defaults":1151,"../../plots/cartesian/layout_attributes":1159,"../../plots/cartesian/position_defaults":1162,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"../titles":1111,"./attributes":1049,"d3":82,"tinycolor2":1042}],1052:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52452,7 +54469,7 @@ module.exports = function hasColorbar(container) { ); }; -},{}],308:[function(require,module,exports){ +},{}],1053:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52473,7 +54490,7 @@ exports.draw = require('./draw'); exports.hasColorbar = require('./has_colorbar'); -},{"./attributes":304,"./defaults":305,"./draw":306,"./has_colorbar":307}],309:[function(require,module,exports){ +},{"./attributes":1049,"./defaults":1050,"./draw":1051,"./has_colorbar":1052}],1054:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52528,7 +54545,7 @@ module.exports = { } }; -},{}],310:[function(require,module,exports){ +},{}],1055:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52593,7 +54610,7 @@ module.exports = function calc(trace, vals, containerStr, cLetter) { } }; -},{"../../lib":382,"./flip_scale":314,"./scales":321}],311:[function(require,module,exports){ +},{"../../lib":1127,"./flip_scale":1059,"./scales":1066}],1056:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52636,7 +54653,7 @@ module.exports = function makeColorScaleAttributes(context) { }; }; -},{"../../lib/extend":377,"./attributes":309}],312:[function(require,module,exports){ +},{"../../lib/extend":1122,"./attributes":1054}],1057:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52652,7 +54669,7 @@ var scales = require('./scales'); module.exports = scales.RdBu; -},{"./scales":321}],313:[function(require,module,exports){ +},{"./scales":1066}],1058:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52716,7 +54733,7 @@ module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, if(showScale) colorbarDefaults(containerIn, containerOut, layout); }; -},{"../../lib":382,"../colorbar/defaults":305,"../colorbar/has_colorbar":307,"./flip_scale":314,"./is_valid_scale":318,"fast-isnumeric":117}],314:[function(require,module,exports){ +},{"../../lib":1127,"../colorbar/defaults":1050,"../colorbar/has_colorbar":1052,"./flip_scale":1059,"./is_valid_scale":1063,"fast-isnumeric":90}],1059:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52741,7 +54758,7 @@ module.exports = function flipScale(scl) { return sclNew; }; -},{}],315:[function(require,module,exports){ +},{}],1060:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52781,7 +54798,7 @@ module.exports = function getScale(scl, dflt) { return scl; }; -},{"./default_scale":312,"./is_valid_scale_array":319,"./scales":321}],316:[function(require,module,exports){ +},{"./default_scale":1057,"./is_valid_scale_array":1064,"./scales":1066}],1061:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52827,7 +54844,7 @@ module.exports = function hasColorscale(trace, containerStr) { ); }; -},{"../../lib":382,"./is_valid_scale":318,"fast-isnumeric":117}],317:[function(require,module,exports){ +},{"../../lib":1127,"./is_valid_scale":1063,"fast-isnumeric":90}],1062:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52859,7 +54876,7 @@ exports.flipScale = require('./flip_scale'); exports.makeScaleFunction = require('./make_scale_function'); -},{"./attributes":309,"./calc":310,"./default_scale":312,"./defaults":313,"./flip_scale":314,"./get_scale":315,"./has_colorscale":316,"./is_valid_scale":318,"./make_scale_function":320,"./scales":321}],318:[function(require,module,exports){ +},{"./attributes":1054,"./calc":1055,"./default_scale":1057,"./defaults":1058,"./flip_scale":1059,"./get_scale":1060,"./has_colorscale":1061,"./is_valid_scale":1063,"./make_scale_function":1065,"./scales":1066}],1063:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52880,7 +54897,7 @@ module.exports = function isValidScale(scl) { else return isValidScaleArray(scl); }; -},{"./is_valid_scale_array":319,"./scales":321}],319:[function(require,module,exports){ +},{"./is_valid_scale_array":1064,"./scales":1066}],1064:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52915,7 +54932,7 @@ module.exports = function isValidScaleArray(scl) { } }; -},{"tinycolor2":274}],320:[function(require,module,exports){ +},{"tinycolor2":1042}],1065:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52964,7 +54981,7 @@ module.exports = function makeScaleFunction(scl, cmin, cmax) { }; }; -},{"../../lib":382,"../color":303,"d3":113,"fast-isnumeric":117,"tinycolor2":274}],321:[function(require,module,exports){ +},{"../../lib":1127,"../color":1048,"d3":82,"fast-isnumeric":90,"tinycolor2":1042}],1066:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53095,7 +55112,7 @@ module.exports = { ] }; -},{}],322:[function(require,module,exports){ +},{}],1067:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53128,7 +55145,7 @@ module.exports = function align(v, dv, v0, v1, anchor) { return vc; }; -},{}],323:[function(require,module,exports){ +},{}],1068:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53166,7 +55183,7 @@ module.exports = function getCursor(x, y, xanchor, yanchor) { return cursorset[y][x]; }; -},{"../../lib":382}],324:[function(require,module,exports){ +},{"../../lib":1127}],1069:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53335,7 +55352,7 @@ function finishDrag(gd) { if(gd._replotPending) Plotly.plot(gd); } -},{"../../lib":382,"../../plotly":402,"../../plots/cartesian/constants":410,"./align":322,"./cursor":323,"./unhover":325}],325:[function(require,module,exports){ +},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/constants":1155,"./align":1067,"./cursor":1068,"./unhover":1070}],1070:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53386,7 +55403,7 @@ unhover.raw = function unhoverRaw(gd, evt) { gd._hoverdata = undefined; }; -},{"../../lib/events":376}],326:[function(require,module,exports){ +},{"../../lib/events":1121}],1071:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53435,16 +55452,61 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya) { - s.each(function(d) { +drawing.translatePoints = function(s, xa, ya, trace, transitionConfig, joinDirection) { + + var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; + + if (hasTransition) { + var size = s.size(); + } + + s.each(function(d, i) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), y = d.yp || ya.c2p(d.y), p = d3.select(this); if(isNumeric(x) && isNumeric(y)) { // for multiline text this works better - if(this.nodeName === 'text') p.attr('x', x).attr('y', y); - else p.attr('transform', 'translate(' + x + ',' + y + ')'); + if(this.nodeName==='text') { + p.attr('x',x).attr('y',y); + } else { + if (hasTransition) { + var trans; + if (!joinDirection) { + trans = p.transition() + .delay(transitionConfig.delay + transitionConfig.cascade / size * i) + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } + } else if (joinDirection === -1) { + trans = p.style('opacity', 1) + .transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .style('opacity', 0) + .remove(); + } else if (joinDirection === 1) { + trans = p.attr('transform', 'translate('+x+','+y+')') + + if (trace) { + trans.call(drawing.pointStyle, trace) + } + + trans.style('opacity', 0) + .transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .style('opacity', 1) + } + + } else { + p.attr('transform', 'translate('+x+','+y+')'); + } + } } else p.remove(); }); @@ -53607,7 +55669,7 @@ drawing.pointStyle = function(s, trace) { markerScale = drawing.tryColorscale(marker, markerIn, ''), lineScale = drawing.tryColorscale(marker, markerIn, 'line.'); - s.each(function(d) { + s.each(function(d, i) { // 'so' is suspected outliers, for box plots var fillColor, lineColor, @@ -53624,11 +55686,11 @@ drawing.pointStyle = function(s, trace) { if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(Array.isArray(markerLine.color)) lineColor = Color.defaultLine; + else if(Array.isArray(markerLine.color)) lineColor = marker.color[i]; else lineColor = markerLine.color; if('mc' in d) fillColor = d.mcc = markerScale(d.mc); - else if(Array.isArray(marker.color)) fillColor = Color.defaultLine; + else if(Array.isArray(marker.color)) fillColor = marker.color[i]; else fillColor = marker.color || 'rgba(0,0,0,0)'; } @@ -53949,7 +56011,7 @@ drawing.setClipUrl = function(s, localId) { s.attr('clip-path', 'url(' + url + ')'); }; -},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../../lib/svg_text_utils":395,"../../plots/plots":454,"../../traces/scatter/make_bubble_size_func":569,"../../traces/scatter/subtypes":575,"../color":303,"../colorscale":317,"./symbol_defs":327,"d3":113,"fast-isnumeric":117}],327:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plots/plots":1199,"../../traces/scatter/make_bubble_size_func":1315,"../../traces/scatter/subtypes":1322,"../color":1048,"../colorscale":1062,"./symbol_defs":1072,"d3":82,"fast-isnumeric":90}],1072:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54425,7 +56487,7 @@ module.exports = { } }; -},{"d3":113}],328:[function(require,module,exports){ +},{"d3":82}],1073:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54524,7 +56586,7 @@ module.exports = { } }; -},{}],329:[function(require,module,exports){ +},{}],1074:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54587,7 +56649,7 @@ function calcOneAxis(calcTrace, trace, axis, coord) { Axes.expand(axis, vals, {padded: true}); } -},{"../../plots/cartesian/axes":405,"../../plots/plots":454,"./compute_error":330,"fast-isnumeric":117}],330:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"./compute_error":1075,"fast-isnumeric":90}],1075:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54683,7 +56745,7 @@ function makeComputeErrorValue(type, value) { } } -},{}],331:[function(require,module,exports){ +},{}],1076:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54760,7 +56822,7 @@ module.exports = function(traceIn, traceOut, defaultColor, opts) { } }; -},{"../../lib":382,"../../plots/plots":454,"./attributes":328,"fast-isnumeric":117}],332:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1073,"fast-isnumeric":90}],1077:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54819,7 +56881,7 @@ errorBars.hoverInfo = function(calcPoint, trace, hoverPoint) { } }; -},{"./attributes":328,"./calc":329,"./defaults":331,"./plot":333,"./style":334}],333:[function(require,module,exports){ +},{"./attributes":1073,"./calc":1074,"./defaults":1076,"./plot":1078,"./style":1079}],1078:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54940,7 +57002,7 @@ function errorCoords(d, xa, ya) { return out; } -},{"../../lib":382,"../../traces/scatter/subtypes":575,"d3":113,"fast-isnumeric":117}],334:[function(require,module,exports){ +},{"../../lib":1127,"../../traces/scatter/subtypes":1322,"d3":82,"fast-isnumeric":90}],1079:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54977,7 +57039,7 @@ module.exports = function style(traces) { }); }; -},{"../color":303,"d3":113}],335:[function(require,module,exports){ +},{"../color":1048,"d3":82}],1080:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55092,7 +57154,7 @@ module.exports = { } }; -},{"../../plots/cartesian/constants":410}],336:[function(require,module,exports){ +},{"../../plots/cartesian/constants":1155}],1081:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55158,7 +57220,7 @@ function imageDefaults(imageIn, imageOut, fullLayout) { return imageOut; } -},{"../../lib":382,"../../plots/cartesian/axes":405,"./attributes":335}],337:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./attributes":1080}],1082:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55331,7 +57393,7 @@ module.exports = function draw(gd) { imagesAbove.each(applyAttributes); }; -},{"../../plots/cartesian/axes":405,"../drawing":326,"d3":113}],338:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../drawing":1071,"d3":82}],1083:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55354,7 +57416,7 @@ module.exports = { supplyLayoutDefaults: supplyLayoutDefaults }; -},{"./attributes":335,"./defaults":336,"./draw":337}],339:[function(require,module,exports){ +},{"./attributes":1080,"./defaults":1081,"./draw":1082}],1084:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55403,7 +57465,7 @@ exports.isMiddleAnchor = function isMiddleAnchor(opts) { ); }; -},{}],340:[function(require,module,exports){ +},{}],1085:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55494,7 +57556,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/font_attributes":423,"../color/attributes":302}],341:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047}],1086:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55512,7 +57574,7 @@ module.exports = { scrollBarMargin: 4 }; -},{}],342:[function(require,module,exports){ +},{}],1087:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55604,7 +57666,7 @@ module.exports = function legendDefaults(layoutIn, layoutOut, fullData) { Lib.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -},{"../../lib":382,"../../plots/plots":454,"./attributes":340,"./helpers":345}],343:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1085,"./helpers":1090}],1088:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56255,7 +58317,7 @@ function expandHorizontalMargin(gd) { }); } -},{"../../lib":382,"../../plotly":402,"../../plots/plots":454,"../color":303,"../dragelement":324,"../drawing":326,"./anchor_utils":339,"./constants":341,"./get_legend_data":344,"./helpers":345,"./style":347,"d3":113}],344:[function(require,module,exports){ +},{"../../lib":1127,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"./anchor_utils":1084,"./constants":1086,"./get_legend_data":1089,"./helpers":1090,"./style":1092,"d3":82}],1089:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56361,7 +58423,7 @@ module.exports = function getLegendData(calcdata, opts) { return legendData; }; -},{"../../plots/plots":454,"./helpers":345}],345:[function(require,module,exports){ +},{"../../plots/plots":1199,"./helpers":1090}],1090:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56392,7 +58454,7 @@ exports.isReversed = function isReversed(legendLayout) { return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; -},{"../../plots/plots":454}],346:[function(require,module,exports){ +},{"../../plots/plots":1199}],1091:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56415,7 +58477,7 @@ legend.draw = require('./draw'); legend.style = require('./style'); -},{"./attributes":340,"./defaults":342,"./draw":343,"./style":347}],347:[function(require,module,exports){ +},{"./attributes":1085,"./defaults":1087,"./draw":1088,"./style":1092}],1092:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56637,7 +58699,7 @@ function stylePies(d) { if(pts.size()) pts.call(stylePie, d[0], trace); } -},{"../../lib":382,"../../plots/plots":454,"../../traces/pie/style_one":554,"../../traces/scatter/subtypes":575,"../color":303,"../drawing":326,"d3":113}],348:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"../../traces/pie/style_one":1299,"../../traces/scatter/subtypes":1322,"../color":1048,"../drawing":1071,"d3":82}],1093:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57164,7 +59226,7 @@ modeBarButtons.resetViews = { } }; -},{"../../../build/ploticon":2,"../../lib":382,"../../lib/setcursor":391,"../../plotly":402,"../../snapshot/download":469}],349:[function(require,module,exports){ +},{"../../../build/ploticon":2,"../../lib":1127,"../../lib/setcursor":1136,"../../plotly":1147,"../../snapshot/download":1214}],1094:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57454,7 +59516,7 @@ function createModeBar(gd, buttons) { module.exports = createModeBar; -},{"../../../build/ploticon":2,"../../lib":382,"d3":113}],350:[function(require,module,exports){ +},{"../../../build/ploticon":2,"../../lib":1127,"d3":82}],1095:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57682,7 +59744,7 @@ function fillCustomButton(customButtons) { return customButtons; } -},{"../../plotly":402,"../../traces/scatter/subtypes":575,"./":349,"./buttons":348}],351:[function(require,module,exports){ +},{"../../plotly":1147,"../../traces/scatter/subtypes":1322,"./":1094,"./buttons":1093}],1096:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57766,7 +59828,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../plots/font_attributes":423,"../color/attributes":302,"./button_attributes":352}],352:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047,"./button_attributes":1097}],1097:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57807,7 +59869,7 @@ module.exports = { } }; -},{}],353:[function(require,module,exports){ +},{}],1098:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57835,7 +59897,7 @@ module.exports = { activeColor: '#d3d3d3' }; -},{}],354:[function(require,module,exports){ +},{}],1099:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57922,7 +59984,7 @@ function getPosDflt(containerOut, layout, counterAxes) { return [containerOut.domain[0], posY + constants.yPad]; } -},{"../../lib":382,"./attributes":351,"./button_attributes":352,"./constants":353}],355:[function(require,module,exports){ +},{"../../lib":1127,"./attributes":1096,"./button_attributes":1097,"./constants":1098}],1100:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58197,7 +60259,7 @@ function reposition(gd, buttons, opts, axName) { }); } -},{"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/cartesian/axis_ids":407,"../../plots/plots":454,"../color":303,"../drawing":326,"../legend/anchor_utils":339,"./constants":353,"./get_update_object":356,"d3":113}],356:[function(require,module,exports){ +},{"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axis_ids":1152,"../../plots/plots":1199,"../color":1048,"../drawing":1071,"../legend/anchor_utils":1084,"./constants":1098,"./get_update_object":1101,"d3":82}],1101:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58255,7 +60317,7 @@ function getXRange(axisLayout, buttonLayout) { return [range0, range1]; } -},{"d3":113}],357:[function(require,module,exports){ +},{"d3":82}],1102:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58273,7 +60335,7 @@ exports.supplyLayoutDefaults = require('./defaults'); exports.draw = require('./draw'); -},{"./attributes":351,"./defaults":354,"./draw":355}],358:[function(require,module,exports){ +},{"./attributes":1096,"./defaults":1099,"./draw":1100}],1103:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58331,7 +60393,7 @@ module.exports = { } }; -},{"../color/attributes":302}],359:[function(require,module,exports){ +},{"../color/attributes":1047}],1104:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58627,7 +60689,7 @@ module.exports = function createSlider(gd) { }); }; -},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../../plotly":402,"../../plots/cartesian/axes":405,"./helpers":361,"./range_plot":363}],360:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"./helpers":1106,"./range_plot":1108}],1105:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58681,7 +60743,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, axName, coun } }; -},{"../../lib":382,"./attributes":358}],361:[function(require,module,exports){ +},{"../../lib":1127,"./attributes":1103}],1106:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58707,7 +60769,7 @@ exports.appendChildren = function appendChildren(el, children) { } }; -},{}],362:[function(require,module,exports){ +},{}],1107:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58764,7 +60826,7 @@ function draw(gd) { }); } -},{"../../plots/plots":454,"./create_slider":359,"./defaults":360}],363:[function(require,module,exports){ +},{"../../plots/plots":1199,"./create_slider":1104,"./defaults":1105}],1108:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58945,7 +61007,7 @@ function makeScatter(trace, pointPairs, w, h) { return [line, markers, fill]; } -},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../drawing":326,"../drawing/symbol_defs":327,"./helpers":361,"d3":113}],364:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../drawing":1071,"../drawing/symbol_defs":1072,"./helpers":1106,"d3":82}],1109:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59036,7 +61098,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../../traces/scatter/attributes":556,"../annotations/attributes":300}],365:[function(require,module,exports){ +},{"../../lib/extend":1122,"../../traces/scatter/attributes":1301,"../annotations/attributes":1045}],1110:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59599,7 +61661,7 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { if(max >= min) return [min, max]; } -},{"../../lib":382,"../../plotly":402,"../../plots/cartesian/axes":405,"../color":303,"../drawing":326,"./attributes":364,"fast-isnumeric":117}],366:[function(require,module,exports){ +},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../drawing":1071,"./attributes":1109,"fast-isnumeric":90}],1111:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59829,7 +61891,7 @@ Titles.draw = function(gd, titleClass, options) { el.classed('js-placeholder', isplaceholder); }; -},{"../../lib":382,"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/plots":454,"../color":303,"../drawing":326,"d3":113,"fast-isnumeric":117}],367:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../drawing":1071,"d3":82,"fast-isnumeric":90}],1112:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59850,7 +61912,7 @@ module.exports = { longdashdot: [8, 1, 1, 1] }; -},{}],368:[function(require,module,exports){ +},{}],1113:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59871,7 +61933,7 @@ module.exports = { longdashdot: [[0.5, 0.7, 0.8, 1], 10] }; -},{}],369:[function(require,module,exports){ +},{}],1114:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59894,7 +61956,7 @@ module.exports = { x: '❌' }; -},{}],370:[function(require,module,exports){ +},{}],1115:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59918,7 +61980,7 @@ exports.svgAttrs = { 'xmlns:xlink': exports.xlink }; -},{}],371:[function(require,module,exports){ +},{}],1116:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59942,6 +62004,7 @@ exports.version = '1.13.0'; exports.plot = Plotly.plot; exports.newPlot = Plotly.newPlot; exports.restyle = Plotly.restyle; +exports.animate = Plotly.animate; exports.relayout = Plotly.relayout; exports.redraw = Plotly.redraw; exports.extendTraces = Plotly.extendTraces; @@ -59968,7 +62031,7 @@ exports.Queue = Plotly.Queue; // export d3 used in the bundle exports.d3 = require('d3'); -},{"../build/ploticon":2,"./plot_api/set_plot_config":400,"./plot_api/to_image":401,"./plotly":402,"./snapshot/download":469,"d3":113}],372:[function(require,module,exports){ +},{"../build/ploticon":2,"./plot_api/set_plot_config":1145,"./plot_api/to_image":1146,"./plotly":1147,"./snapshot/download":1214,"d3":82}],1117:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60001,7 +62064,7 @@ if(typeof MathJax !== 'undefined') { exports.MathJax = false; } -},{}],373:[function(require,module,exports){ +},{}],1118:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60018,7 +62081,7 @@ module.exports = function arrayToCalcItem(traceAttr, calcItem, calcAttr, i) { if(Array.isArray(traceAttr)) calcItem[calcAttr] = traceAttr[i]; }; -},{}],374:[function(require,module,exports){ +},{}],1119:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60282,7 +62345,7 @@ exports.coerceFont = function(coerce, attr, dfltObj) { return out; }; -},{"../components/colorscale/get_scale":315,"../components/colorscale/scales":321,"./nested_property":386,"fast-isnumeric":117,"tinycolor2":274}],375:[function(require,module,exports){ +},{"../components/colorscale/get_scale":1060,"../components/colorscale/scales":1066,"./nested_property":1131,"fast-isnumeric":90,"tinycolor2":1042}],1120:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60621,7 +62684,7 @@ exports.parseDate = function(v) { return out; }; -},{"../lib":382,"d3":113,"fast-isnumeric":117}],376:[function(require,module,exports){ +},{"../lib":1127,"d3":82,"fast-isnumeric":90}],1121:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60755,7 +62818,7 @@ var Events = { module.exports = Events; -},{"events":55}],377:[function(require,module,exports){ +},{"events":69}],1122:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60835,7 +62898,7 @@ function _extend(inputs, isDeep, keepAllKeys) { return target; } -},{"./is_plain_object.js":383}],378:[function(require,module,exports){ +},{"./is_plain_object.js":1128}],1123:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60859,7 +62922,7 @@ module.exports = function filterVisible(dataIn) { return dataOut; }; -},{}],379:[function(require,module,exports){ +},{}],1124:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60918,7 +62981,7 @@ function countryNameToISO3(countryName) { Lib.warn('Unrecognized country name: ' + countryName + '.'); } -},{"../lib":382,"country-regex":108}],380:[function(require,module,exports){ +},{"../lib":1127,"country-regex":81}],1125:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60997,7 +63060,7 @@ function formatColor(containerIn, opacityIn, len) { module.exports = formatColor; -},{"../components/color/attributes":302,"../components/colorscale/make_scale_function":320,"./str2rgbarray":394,"fast-isnumeric":117,"tinycolor2":274}],381:[function(require,module,exports){ +},{"../components/color/attributes":1047,"../components/colorscale/make_scale_function":1065,"./str2rgbarray":1139,"fast-isnumeric":90,"tinycolor2":1042}],1126:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61071,7 +63134,7 @@ function convertHTMLToUnicode(html) { module.exports = convertHTMLToUnicode; -},{"superscript-text":263}],382:[function(require,module,exports){ +},{"superscript-text":1041}],1127:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61660,7 +63723,93 @@ lib.numSeparate = function(value, separators) { return x1 + x2; }; -},{"./coerce":374,"./dates":375,"./extend":377,"./is_plain_object":383,"./loggers":384,"./matrix":385,"./nested_property":386,"./notifier":387,"./search":390,"./stats":393,"d3":113}],383:[function(require,module,exports){ +/* + * Deep copy of an object, subject to some caveats. Adapted from + * http://stackoverflow.com/questions/10728412/in-javascript-when-performing-a-deep-copy-how-do-i-avoid-a-cycle-due-to-a-pro#answer-10729242 + * + * It does some basics like avoiding infinite loops, but leaves some gaps + * regarding prototypes and functions. But those shouldn't be part of the + * layout anyway, which is the intended use. + * + * @param {object} object the object to be cloned + * @param {function} shallowFilter a callback executed on each attribute name + * @param {Array} path a stack representing the current attr path + * + * @return {object} the cloned object + */ +lib.deepClone = function deepClone (object, shallowFilter, path) { + var nextPath, isShallow; + var gdcc = "__getDeepCircularCopy__"; + if (object !== Object(object)) { + return object; // primitive value + } + + var set = gdcc in object; + var cache = object[gdcc]; + var result; + if (set && typeof cache == "function") { + return cache(); + } + // else + object[gdcc] = function () { return result; }; // overwrite + + if (object instanceof Array) { + result = []; + for (var i=0; i= 0; i--) { + if (gd.data[i][isClonedFlag]) continue; + + // Clone this trace if it's not already cloned. Otherwise the original input + // to Plotly.plot gets mangled and we can't use it again, which is inconvenient. + // Notably, this does *not* copy data arrays. + type = gd._fullData[i].type; + schema = Plotly.PlotSchema.get().traces[type] + gd.data[i] = Lib.deepCloneTrace(gd.data[i], schema); + gd.data[i][isClonedFlag] = true; + } +} + +},{"../components/color":1048,"../components/drawing":1071,"../components/errorbars":1077,"../components/images":1083,"../components/legend":1091,"../components/modebar/manage":1095,"../components/rangeselector":1102,"../components/rangeslider":1107,"../components/shapes":1110,"../components/titles":1111,"../constants/xmlns_namespaces":1115,"../lib":1127,"../lib/events":1121,"../lib/queue":1134,"../plotly":1147,"../plots/cartesian/graph_interact":1157,"../plots/plots":1199,"d3":82,"fast-isnumeric":90,"gl-mat4/fromQuat":237}],1143:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -66649,7 +68999,7 @@ function defaultSetBackground(gd, bgColor) { catch(e) { Lib.error(e); } } -},{"../lib":382}],399:[function(require,module,exports){ +},{"../lib":1127}],1144:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -66972,7 +69322,7 @@ function handleLinkedToArray(layoutAttributes) { PlotSchema.crawl(layoutAttributes, callback); } -},{"../lib":382,"../plotly":402,"../plots/plots":454,"../plots/polar/area_attributes":455,"../plots/polar/axis_attributes":456}],400:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147,"../plots/plots":1199,"../plots/polar/area_attributes":1200,"../plots/polar/axis_attributes":1201}],1145:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -66998,7 +69348,7 @@ module.exports = function setPlotConfig(configObj) { return Lib.extendFlat(Plotly.defaultConfig, configObj); }; -},{"../lib":382,"../plotly":402}],401:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147}],1146:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67111,7 +69461,7 @@ function toImage(gd, opts) { module.exports = toImage; -},{"../lib":382,"../plotly":402,"../snapshot":471,"fast-isnumeric":117}],402:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147,"../snapshot":1216,"fast-isnumeric":90}],1147:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67198,7 +69548,7 @@ exports.PlotSchema = require('./plot_api/plot_schema'); // imaging routines exports.Snapshot = require('./snapshot'); -},{"../build/plotcss":1,"./components/annotations":301,"./components/color":303,"./components/colorbar":308,"./components/colorscale":317,"./components/drawing":326,"./components/errorbars":332,"./components/images":338,"./components/legend":346,"./components/modebar":349,"./components/shapes":365,"./fonts/mathjax_config":372,"./lib":382,"./lib/queue":389,"./lib/svg_text_utils":395,"./plot_api/plot_api":397,"./plot_api/plot_config":398,"./plot_api/plot_schema":399,"./plots/cartesian/axes":405,"./plots/cartesian/graph_interact":412,"./plots/plots":454,"./plots/polar/micropolar":457,"./snapshot":471,"./traces/scatter":565,"es6-promise":116}],403:[function(require,module,exports){ +},{"../build/plotcss":1,"./components/annotations":1046,"./components/color":1048,"./components/colorbar":1053,"./components/colorscale":1062,"./components/drawing":1071,"./components/errorbars":1077,"./components/images":1083,"./components/legend":1091,"./components/modebar":1094,"./components/shapes":1110,"./fonts/mathjax_config":1117,"./lib":1127,"./lib/queue":1134,"./lib/svg_text_utils":1140,"./plot_api/plot_api":1142,"./plot_api/plot_config":1143,"./plot_api/plot_schema":1144,"./plots/cartesian/axes":1150,"./plots/cartesian/graph_interact":1157,"./plots/plots":1199,"./plots/polar/micropolar":1202,"./snapshot":1216,"./traces/scatter":1310,"es6-promise":89}],1148:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67279,7 +69629,7 @@ module.exports = { } }; -},{}],404:[function(require,module,exports){ +},{}],1149:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -67306,7 +69656,7 @@ module.exports = { } }; -},{}],405:[function(require,module,exports){ +},{}],1150:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69279,7 +71629,7 @@ function swapAxisAttrs(layout, key, xFullAxes, yFullAxes) { // rather than built-in % which gives a negative value for negative v function mod(v, d) { return ((v % d) + d) % d; } -},{"../../components/color":303,"../../components/drawing":326,"../../components/titles":366,"../../lib":382,"../../lib/svg_text_utils":395,"../../plotly":402,"./axis_ids":407,"./layout_attributes":414,"./layout_defaults":415,"./set_convert":419,"d3":113,"fast-isnumeric":117}],406:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"./axis_ids":1152,"./layout_attributes":1159,"./layout_defaults":1160,"./set_convert":1164,"d3":82,"fast-isnumeric":90}],1151:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69562,7 +71912,7 @@ function category(a) { return curvecats > curvenums * 2; } -},{"../../components/color/attributes":302,"../../lib":382,"../plots":454,"./axis_ids":407,"./category_order_defaults":408,"./clean_datum":409,"./layout_attributes":414,"./ordered_categories":416,"./set_convert":419,"./tick_label_defaults":420,"./tick_mark_defaults":421,"./tick_value_defaults":422,"fast-isnumeric":117,"tinycolor2":274}],407:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../lib":1127,"../plots":1199,"./axis_ids":1152,"./category_order_defaults":1153,"./clean_datum":1154,"./layout_attributes":1159,"./ordered_categories":1161,"./set_convert":1164,"./tick_label_defaults":1165,"./tick_mark_defaults":1166,"./tick_value_defaults":1167,"fast-isnumeric":90,"tinycolor2":1042}],1152:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69683,7 +72033,7 @@ exports.getFromTrace = function(gd, fullTrace, type) { return ax; }; -},{"../../lib":382,"../plots":454,"./constants":410}],408:[function(require,module,exports){ +},{"../../lib":1127,"../plots":1199,"./constants":1155}],1153:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69717,7 +72067,7 @@ module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, } }; -},{}],409:[function(require,module,exports){ +},{}],1154:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69756,7 +72106,7 @@ module.exports = function cleanDatum(c) { return c; }; -},{"../../lib":382,"fast-isnumeric":117}],410:[function(require,module,exports){ +},{"../../lib":1127,"fast-isnumeric":90}],1155:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69834,7 +72184,7 @@ module.exports = { REDRAWDELAY: 50 }; -},{}],411:[function(require,module,exports){ +},{}],1156:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -70506,7 +72856,7 @@ function removeZoombox(gd) { .remove(); } -},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../lib":382,"../../lib/setcursor":391,"../../lib/svg_text_utils":395,"../../plotly":402,"./axes":405,"./constants":410,"./select":418,"d3":113,"tinycolor2":274}],412:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"./axes":1150,"./constants":1155,"./select":1163,"d3":82,"tinycolor2":1042}],1157:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -71848,7 +74198,7 @@ fx.inbox = function(v0, v1) { return Infinity; }; -},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../lib":382,"../../lib/events":376,"../../lib/svg_text_utils":395,"./axes":405,"./constants":410,"./dragbox":411,"d3":113,"fast-isnumeric":117,"tinycolor2":274}],413:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/events":1121,"../../lib/svg_text_utils":1140,"./axes":1150,"./constants":1155,"./dragbox":1156,"d3":82,"fast-isnumeric":90,"tinycolor2":1042}],1158:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -71862,6 +74212,8 @@ fx.inbox = function(v0, v1) { var Plots = require('../plots'); +var d3 = require('d3'); + var constants = require('./constants'); exports.name = 'cartesian'; @@ -71876,7 +74228,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd) { +exports.plot = function(gd, traces, transitionOpts) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -71889,6 +74241,9 @@ exports.plot = function(gd) { var cd = calcdata[i]; var trace = cd[0].trace; + // Skip trace if whitelist provided and it's not whitelisted: + // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; + if(trace.xaxis + trace.yaxis === subplot) { cdSubplot.push(cd); } @@ -71918,9 +74273,13 @@ exports.plot = function(gd) { cdSubplot = getCdSubplot(calcdata, subplot); // remove old traces, then redraw everything - // TODO: use enter/exit appropriately in the plot functions - // so we don't need this - should sometimes be a big speedup - if(subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove(); + // TODO: scatterlayer is manually excluded from this since it knows how + // to update instead of fully removing and redrawing every time. The + // remaining plot traces should also be able to do this. Once implemented, + // we won't need this - which should sometimes be a big speedup. + if(subplotInfo.plot) { + subplotInfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); + } for(var j = 0; j < modules.length; j++) { var _module = modules[j]; @@ -71930,12 +74289,13 @@ exports.plot = function(gd) { // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); - _module.plot(gd, subplotInfo, cdModule); + + _module.plot(gd, subplotInfo, cdModule, traces, transitionOpts); } } }; -},{"../plots":454,"./attributes":404,"./constants":410}],414:[function(require,module,exports){ +},{"../plots":1199,"./attributes":1149,"./constants":1155,"d3":82}],1159:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72280,7 +74640,7 @@ module.exports = { } }; -},{"../../components/color/attributes":302,"../../components/rangeselector/attributes":351,"../../components/rangeslider/attributes":358,"../../lib/extend":377,"../font_attributes":423,"./constants":410}],415:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../components/rangeselector/attributes":1096,"../../components/rangeslider/attributes":1103,"../../lib/extend":1122,"../font_attributes":1168,"./constants":1155}],1160:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72453,7 +74813,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { }); }; -},{"../../components/color":303,"../../components/rangeselector":357,"../../components/rangeslider":362,"../../lib":382,"../plots":454,"./axis_defaults":406,"./axis_ids":407,"./constants":410,"./layout_attributes":414,"./position_defaults":417}],416:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/rangeselector":1102,"../../components/rangeslider":1107,"../../lib":1127,"../plots":1199,"./axis_defaults":1151,"./axis_ids":1152,"./constants":1155,"./layout_attributes":1159,"./position_defaults":1162}],1161:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72532,7 +74892,7 @@ module.exports = function orderedCategories(axisLetter, categoryorder, categorya } }; -},{"d3":113}],417:[function(require,module,exports){ +},{"d3":82}],1162:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72597,7 +74957,7 @@ module.exports = function handlePositionDefaults(containerIn, containerOut, coer return containerOut; }; -},{"../../lib":382,"fast-isnumeric":117}],418:[function(require,module,exports){ +},{"../../lib":1127,"fast-isnumeric":90}],1163:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72797,7 +75157,7 @@ module.exports = function prepSelect(e, startX, startY, dragOptions, mode) { }; }; -},{"../../components/color":303,"../../lib/polygon":388,"./axes":405,"./constants":410}],419:[function(require,module,exports){ +},{"../../components/color":1048,"../../lib/polygon":1133,"./axes":1150,"./constants":1155}],1164:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73041,7 +75401,7 @@ module.exports = function setConvert(ax) { ax._forceTick0 = null; }; -},{"../../lib":382,"./axis_ids":407,"./clean_datum":409,"./constants":410,"d3":113,"fast-isnumeric":117}],420:[function(require,module,exports){ +},{"../../lib":1127,"./axis_ids":1152,"./clean_datum":1154,"./constants":1155,"d3":82,"fast-isnumeric":90}],1165:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73124,7 +75484,7 @@ function getShowAttrDflt(containerIn) { } } -},{"../../lib":382}],421:[function(require,module,exports){ +},{"../../lib":1127}],1166:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73157,7 +75517,7 @@ module.exports = function handleTickDefaults(containerIn, containerOut, coerce, } }; -},{"../../lib":382,"./layout_attributes":414}],422:[function(require,module,exports){ +},{"../../lib":1127,"./layout_attributes":1159}],1167:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73198,7 +75558,7 @@ module.exports = function handleTickValueDefaults(containerIn, containerOut, coe } }; -},{"fast-isnumeric":117}],423:[function(require,module,exports){ +},{"fast-isnumeric":90}],1168:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73229,7 +75589,7 @@ module.exports = { } }; -},{}],424:[function(require,module,exports){ +},{}],1169:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73387,7 +75747,7 @@ params.layerNameToAdjective = { // base layers drawn over choropleth params.baseLayersOverChoropleth = ['rivers', 'lakes']; -},{}],425:[function(require,module,exports){ +},{}],1170:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73881,7 +76241,7 @@ function createMockAxis(fullLayout) { return mockAxis; } -},{"../../components/color":303,"../../components/drawing":326,"../../constants/xmlns_namespaces":370,"../../lib/filter_visible":378,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"./constants":424,"./projections":432,"./set_scale":433,"./zoom":434,"./zoom_reset":435,"d3":113,"topojson":275}],426:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../constants/xmlns_namespaces":1115,"../../lib/filter_visible":1123,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"./constants":1169,"./projections":1177,"./set_scale":1178,"./zoom":1179,"./zoom_reset":1180,"d3":82,"topojson":1043}],1171:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73987,7 +76347,7 @@ exports.toSVG = function(gd) { } }; -},{"../../plots/plots":454,"./geo":425,"./layout/attributes":427,"./layout/defaults":430,"./layout/layout_attributes":431}],427:[function(require,module,exports){ +},{"../../plots/plots":1199,"./geo":1170,"./layout/attributes":1172,"./layout/defaults":1175,"./layout/layout_attributes":1176}],1172:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74008,7 +76368,7 @@ module.exports = { } }; -},{}],428:[function(require,module,exports){ +},{}],1173:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74063,7 +76423,7 @@ module.exports = { } }; -},{"../../../components/color/attributes":302}],429:[function(require,module,exports){ +},{"../../../components/color/attributes":1047}],1174:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74137,7 +76497,7 @@ module.exports = function supplyGeoAxisLayoutDefaults(geoLayoutIn, geoLayoutOut) } }; -},{"../../../lib":382,"../constants":424,"./axis_attributes":428}],430:[function(require,module,exports){ +},{"../../../lib":1127,"../constants":1169,"./axis_attributes":1173}],1175:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74256,7 +76616,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { ]; } -},{"../../subplot_defaults":460,"../constants":424,"./axis_defaults":429,"./layout_attributes":431}],431:[function(require,module,exports){ +},{"../../subplot_defaults":1205,"../constants":1169,"./axis_defaults":1174,"./layout_attributes":1176}],1176:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74489,7 +76849,7 @@ module.exports = { lataxis: geoAxesAttrs }; -},{"../../../components/color/attributes":302,"../constants":424,"./axis_attributes":428}],432:[function(require,module,exports){ +},{"../../../components/color/attributes":1047,"../constants":1169,"./axis_attributes":1173}],1177:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74935,7 +77295,7 @@ function addProjectionsToD3(d3) { module.exports = addProjectionsToD3; -},{}],433:[function(require,module,exports){ +},{}],1178:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75086,7 +77446,7 @@ function getBounds(projection, rangeBox) { return d3.geo.path().projection(projection).bounds(rangeBox); } -},{"./constants":424,"d3":113}],434:[function(require,module,exports){ +},{"./constants":1169,"d3":82}],1179:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75513,7 +77873,7 @@ function d3_eventDispatch(target) { return dispatch; } -},{"d3":113}],435:[function(require,module,exports){ +},{"d3":82}],1180:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75548,7 +77908,7 @@ function createGeoZoomReset(geo, geoLayout) { module.exports = createGeoZoomReset; -},{"../cartesian/graph_interact":412}],436:[function(require,module,exports){ +},{"../cartesian/graph_interact":1157}],1181:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75703,7 +78063,7 @@ function createCamera(scene) { return result; } -},{"mouse-change":241,"mouse-wheel":245}],437:[function(require,module,exports){ +},{"mouse-change":1004,"mouse-wheel":1008}],1182:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75946,7 +78306,7 @@ function createAxes2D(scene) { module.exports = createAxes2D; -},{"../../lib/html2unicode":381,"../../lib/str2rgbarray":394,"../../plotly":402}],438:[function(require,module,exports){ +},{"../../lib/html2unicode":1126,"../../lib/str2rgbarray":1139,"../../plotly":1147}],1183:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76059,7 +78419,7 @@ exports.toSVG = function(gd) { } }; -},{"../../constants/xmlns_namespaces":370,"../cartesian/attributes":404,"../plots":454,"./scene2d":439}],439:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../cartesian/attributes":1149,"../plots":1199,"./scene2d":1184}],1184:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76596,7 +78956,7 @@ proto.hoverFormatter = function(axisName, val) { return Axes.tickText(axis, axis.c2l(val), 'hover').text; }; -},{"../../lib/html2unicode":381,"../../lib/show_no_webgl_msg":392,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"./camera":436,"./convert":437,"gl-plot2d":165,"gl-select-box":195,"gl-spikes2d":215}],440:[function(require,module,exports){ +},{"../../lib/html2unicode":1126,"../../lib/show_no_webgl_msg":1137,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"./camera":1181,"./convert":1182,"gl-plot2d":452,"gl-select-box":937,"gl-spikes2d":938}],1185:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76839,7 +79199,7 @@ function createCamera(element, options) { return camera; } -},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],441:[function(require,module,exports){ +},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],1186:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76973,7 +79333,7 @@ function initAxes(gd, sceneLayout) { } } -},{"../../constants/xmlns_namespaces":370,"../plots":454,"./layout/attributes":442,"./layout/defaults":446,"./layout/layout_attributes":447,"./scene":451,"./set_convert":452}],442:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":1115,"../plots":1199,"./layout/attributes":1187,"./layout/defaults":1191,"./layout/layout_attributes":1192,"./scene":1196,"./set_convert":1197}],1187:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76994,7 +79354,7 @@ module.exports = { } }; -},{}],443:[function(require,module,exports){ +},{}],1188:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77100,7 +79460,7 @@ module.exports = { zerolinewidth: axesAttrs.zerolinewidth }; -},{"../../../components/color":303,"../../../lib/extend":377,"../../cartesian/layout_attributes":414}],444:[function(require,module,exports){ +},{"../../../components/color":1048,"../../../lib/extend":1122,"../../cartesian/layout_attributes":1159}],1189:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77169,7 +79529,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) { } }; -},{"../../../lib":382,"../../cartesian/axis_defaults":406,"./axis_attributes":443,"tinycolor2":274}],445:[function(require,module,exports){ +},{"../../../lib":1127,"../../cartesian/axis_defaults":1151,"./axis_attributes":1188,"tinycolor2":1042}],1190:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77325,7 +79685,7 @@ function createAxesOptions(plotlyOptions) { module.exports = createAxesOptions; -},{"../../../lib/html2unicode":381,"../../../lib/str2rgbarray":394,"arraytools":49}],446:[function(require,module,exports){ +},{"../../../lib/html2unicode":1126,"../../../lib/str2rgbarray":1139,"arraytools":64}],1191:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77432,7 +79792,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { coerce('hovermode', opts.getDfltFromLayout('hovermode')); } -},{"../../../components/color":303,"../../subplot_defaults":460,"./axis_defaults":444,"./layout_attributes":447}],447:[function(require,module,exports){ +},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1189,"./layout_attributes":1192}],1192:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77560,7 +79920,7 @@ module.exports = { } }; -},{"../../../lib/extend":377,"./axis_attributes":443}],448:[function(require,module,exports){ +},{"../../../lib/extend":1122,"./axis_attributes":1188}],1193:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77606,7 +79966,7 @@ function createSpikeOptions(layout) { module.exports = createSpikeOptions; -},{"../../../lib/str2rgbarray":394}],449:[function(require,module,exports){ +},{"../../../lib/str2rgbarray":1139}],1194:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77701,7 +80061,7 @@ function computeTickMarks(scene) { scene.contourLevels = contourLevelsFromTicks(ticks); } -},{"../../../lib/html2unicode":381,"../../../plotly":402}],450:[function(require,module,exports){ +},{"../../../lib/html2unicode":1126,"../../../plotly":1147}],1195:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77735,7 +80095,7 @@ function project(camera, v) { module.exports = project; -},{}],451:[function(require,module,exports){ +},{}],1196:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78464,7 +80824,7 @@ proto.toImage = function(format) { module.exports = Scene; -},{"../../lib":382,"../../lib/show_no_webgl_msg":392,"../../lib/str2rgbarray":394,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../../plots/plots":454,"./camera":440,"./layout/convert":445,"./layout/spikes":448,"./layout/tick_marks":449,"./project":450,"./set_convert":452,"gl-plot3d":183}],452:[function(require,module,exports){ +},{"../../lib":1127,"../../lib/show_no_webgl_msg":1137,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/plots":1199,"./camera":1185,"./layout/convert":1190,"./layout/spikes":1193,"./layout/tick_marks":1194,"./project":1195,"./set_convert":1197,"gl-plot3d":626}],1197:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78486,7 +80846,7 @@ module.exports = function setConvert(containerOut) { containerOut.setScale = noop; }; -},{"../cartesian/axes":405}],453:[function(require,module,exports){ +},{"../cartesian/axes":1150}],1198:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78650,7 +81010,7 @@ module.exports = { } }; -},{"../components/color/attributes":302,"../plotly":402,"./font_attributes":423}],454:[function(require,module,exports){ +},{"../components/color/attributes":1047,"../plotly":1147,"./font_attributes":1168}],1199:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79756,7 +82116,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { return (output === 'object') ? obj : JSON.stringify(obj); }; -},{"../components/color":303,"../lib":382,"../plotly":402,"./attributes":403,"./font_attributes":423,"./layout_attributes":453,"d3":113,"fast-isnumeric":117}],455:[function(require,module,exports){ +},{"../components/color":1048,"../lib":1127,"../plotly":1147,"./attributes":1148,"./font_attributes":1168,"./layout_attributes":1198,"d3":82,"fast-isnumeric":90}],1200:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79781,7 +82141,7 @@ module.exports = { } }; -},{"../../traces/scatter/attributes":556}],456:[function(require,module,exports){ +},{"../../traces/scatter/attributes":1301}],1201:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79896,7 +82256,7 @@ module.exports = { } }; -},{"../../lib/extend":377,"../cartesian/layout_attributes":414}],457:[function(require,module,exports){ +},{"../../lib/extend":1122,"../cartesian/layout_attributes":1159}],1202:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81319,7 +83679,7 @@ var extendDeepAll = Plotly.Lib.extendDeepAll; return exports; }; -},{"../../plotly":402,"./micropolar_manager":458,"d3":113}],458:[function(require,module,exports){ +},{"../../plotly":1147,"./micropolar_manager":1203,"d3":82}],1203:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81402,7 +83762,7 @@ manager.fillLayout = function(_gd) { _gd._fullLayout = extendDeepAll(dflts, _gd.layout); }; -},{"../../plotly":402,"./undo_manager":459,"d3":113}],459:[function(require,module,exports){ +},{"../../plotly":1147,"./undo_manager":1204,"d3":82}],1204:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81468,7 +83828,7 @@ module.exports = function UndoManager() { }; }; -},{}],460:[function(require,module,exports){ +},{}],1205:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81543,7 +83903,7 @@ module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, o } }; -},{"../lib":382,"./plots":454}],461:[function(require,module,exports){ +},{"../lib":1127,"./plots":1199}],1206:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81617,7 +83977,7 @@ exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) } }; -},{"../../plots/plots":454,"./layout/attributes":462,"./layout/defaults":465,"./layout/layout_attributes":466,"./ternary":467}],462:[function(require,module,exports){ +},{"../../plots/plots":1199,"./layout/attributes":1207,"./layout/defaults":1210,"./layout/layout_attributes":1211,"./ternary":1212}],1207:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81638,7 +83998,7 @@ module.exports = { } }; -},{}],463:[function(require,module,exports){ +},{}],1208:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81697,7 +84057,7 @@ module.exports = { } }; -},{"../../../lib/extend":377,"../../cartesian/layout_attributes":414}],464:[function(require,module,exports){ +},{"../../../lib/extend":1122,"../../cartesian/layout_attributes":1159}],1209:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81781,7 +84141,7 @@ module.exports = function supplyLayoutDefaults(containerIn, containerOut, option } }; -},{"../../../lib":382,"../../cartesian/tick_label_defaults":420,"../../cartesian/tick_mark_defaults":421,"../../cartesian/tick_value_defaults":422,"./axis_attributes":463,"tinycolor2":274}],465:[function(require,module,exports){ +},{"../../../lib":1127,"../../cartesian/tick_label_defaults":1165,"../../cartesian/tick_mark_defaults":1166,"../../cartesian/tick_value_defaults":1167,"./axis_attributes":1208,"tinycolor2":1042}],1210:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81844,7 +84204,7 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option } } -},{"../../../components/color":303,"../../subplot_defaults":460,"./axis_defaults":464,"./layout_attributes":466}],466:[function(require,module,exports){ +},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1209,"./layout_attributes":1211}],1211:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81900,7 +84260,7 @@ module.exports = { caxis: ternaryAxesAttrs }; -},{"../../../components/color/attributes":302,"./axis_attributes":463}],467:[function(require,module,exports){ +},{"../../../components/color/attributes":1047,"./axis_attributes":1208}],1212:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82586,7 +84946,7 @@ function removeZoombox(gd) { .remove(); } -},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../components/titles":366,"../../lib":382,"../../lib/extend":377,"../../lib/filter_visible":378,"../../plotly":402,"../cartesian/axes":405,"../cartesian/constants":410,"../cartesian/graph_interact":412,"../cartesian/select":418,"../cartesian/set_convert":419,"d3":113,"tinycolor2":274}],468:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/extend":1122,"../../lib/filter_visible":1123,"../../plotly":1147,"../cartesian/axes":1150,"../cartesian/constants":1155,"../cartesian/graph_interact":1157,"../cartesian/select":1163,"../cartesian/set_convert":1164,"d3":82,"tinycolor2":1042}],1213:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82742,7 +85102,7 @@ module.exports = function clonePlot(graphObj, options) { return plotTile; }; -},{"../plotly":402}],469:[function(require,module,exports){ +},{"../plotly":1147}],1214:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82808,7 +85168,7 @@ function downloadImage(gd, opts) { module.exports = downloadImage; -},{"../lib":382,"../plot_api/to_image":401,"./filesaver":470}],470:[function(require,module,exports){ +},{"../lib":1127,"../plot_api/to_image":1146,"./filesaver":1215}],1215:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82876,7 +85236,7 @@ var fileSaver = function(url, name) { module.exports = fileSaver; -},{}],471:[function(require,module,exports){ +},{}],1216:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82921,7 +85281,7 @@ var Snapshot = { module.exports = Snapshot; -},{"./cloneplot":468,"./download":469,"./svgtoimg":472,"./toimage":473,"./tosvg":474}],472:[function(require,module,exports){ +},{"./cloneplot":1213,"./download":1214,"./svgtoimg":1217,"./toimage":1218,"./tosvg":1219}],1217:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83052,7 +85412,7 @@ function svgToImg(opts) { module.exports = svgToImg; -},{"../lib":382,"events":55}],473:[function(require,module,exports){ +},{"../lib":1127,"events":69}],1218:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83131,7 +85491,7 @@ function toImage(gd, opts) { module.exports = toImage; -},{"../lib":382,"../plotly":402,"events":55}],474:[function(require,module,exports){ +},{"../lib":1127,"../plotly":1147,"events":69}],1219:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83243,7 +85603,7 @@ module.exports = function toSVG(gd, format) { return s; }; -},{"../components/color":303,"../components/drawing":326,"../constants/xmlns_namespaces":370,"../lib/svg_text_utils":395,"d3":113}],475:[function(require,module,exports){ +},{"../components/color":1048,"../components/drawing":1071,"../constants/xmlns_namespaces":1115,"../lib/svg_text_utils":1140,"d3":82}],1220:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83271,7 +85631,7 @@ module.exports = function arraysToCalcdata(cd) { mergeArray(markerLine.width, cd, 'mlw'); }; -},{"../../lib":382}],476:[function(require,module,exports){ +},{"../../lib":1127}],1221:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83331,7 +85691,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../scatter/attributes":556}],477:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../scatter/attributes":1301}],1222:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83390,7 +85750,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":316,"../../plots/cartesian/axes":405,"fast-isnumeric":117}],478:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1223:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83432,7 +85792,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'}); }; -},{"../../components/color":303,"../../components/errorbars/defaults":331,"../../lib":382,"../bar/style_defaults":486,"../scatter/xy_defaults":577,"./attributes":476}],479:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"../scatter/xy_defaults":1324,"./attributes":1221}],1224:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83523,7 +85883,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return [pointData]; }; -},{"../../components/color":303,"../../components/errorbars":332,"../../plots/cartesian/graph_interact":412}],480:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157}],1225:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83559,7 +85919,7 @@ Bar.meta = { module.exports = Bar; -},{"../../plots/cartesian":413,"../scatter/colorbar":559,"./arrays_to_calcdata":475,"./attributes":476,"./calc":477,"./defaults":478,"./hover":479,"./layout_attributes":481,"./layout_defaults":482,"./plot":483,"./set_positions":484,"./style":485}],481:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../scatter/colorbar":1304,"./arrays_to_calcdata":1220,"./attributes":1221,"./calc":1222,"./defaults":1223,"./hover":1224,"./layout_attributes":1226,"./layout_defaults":1227,"./plot":1228,"./set_positions":1229,"./style":1230}],1226:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83603,7 +85963,7 @@ module.exports = { } }; -},{}],482:[function(require,module,exports){ +},{}],1227:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83661,7 +86021,7 @@ module.exports = function(layoutIn, layoutOut, fullData) { coerce('bargroupgap'); }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"./layout_attributes":481}],483:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"./layout_attributes":1226}],1228:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83773,7 +86133,7 @@ module.exports = function plot(gd, plotinfo, cdbar) { }; -},{"../../components/color":303,"../../components/errorbars":332,"../../lib":382,"./arrays_to_calcdata":475,"d3":113,"fast-isnumeric":117}],484:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1220,"d3":82,"fast-isnumeric":90}],1229:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83987,7 +86347,7 @@ module.exports = function setPositions(gd, plotinfo) { }); }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"fast-isnumeric":117}],485:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"fast-isnumeric":90}],1230:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84066,7 +86426,7 @@ module.exports = function style(gd) { s.call(ErrorBars.style); }; -},{"../../components/color":303,"../../components/drawing":326,"../../components/errorbars":332,"d3":113}],486:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../components/errorbars":1077,"d3":82}],1231:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84103,7 +86463,7 @@ module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, default coerce('marker.line.width'); }; -},{"../../components/color":303,"../../components/colorscale/defaults":313,"../../components/colorscale/has_colorscale":316}],487:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061}],1232:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84234,7 +86594,7 @@ module.exports = { fillcolor: scatterAttrs.fillcolor }; -},{"../../components/color/attributes":302,"../../lib/extend":377,"../scatter/attributes":556}],488:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../scatter/attributes":1301}],1233:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84383,7 +86743,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"fast-isnumeric":117}],489:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1234:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84452,7 +86812,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) { } }; -},{"../../components/color":303,"../../lib":382,"./attributes":487}],490:[function(require,module,exports){ +},{"../../components/color":1048,"../../lib":1127,"./attributes":1232}],1235:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84561,7 +86921,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return closeData; }; -},{"../../components/color":303,"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412}],491:[function(require,module,exports){ +},{"../../components/color":1048,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157}],1236:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84594,7 +86954,7 @@ Box.meta = { module.exports = Box; -},{"../../plots/cartesian":413,"./attributes":487,"./calc":488,"./defaults":489,"./hover":490,"./layout_attributes":492,"./layout_defaults":493,"./plot":494,"./set_positions":495,"./style":496}],492:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./attributes":1232,"./calc":1233,"./defaults":1234,"./hover":1235,"./layout_attributes":1237,"./layout_defaults":1238,"./plot":1239,"./set_positions":1240,"./style":1241}],1237:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84632,7 +86992,7 @@ module.exports = { } }; -},{}],493:[function(require,module,exports){ +},{}],1238:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84666,7 +87026,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { coerce('boxgroupgap'); }; -},{"../../lib":382,"../../plots/plots":454,"./layout_attributes":492}],494:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/plots":1199,"./layout_attributes":1237}],1239:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84893,7 +87253,7 @@ module.exports = function plot(gd, plotinfo, cdbox) { }); }; -},{"../../components/drawing":326,"../../lib":382,"d3":113}],495:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../lib":1127,"d3":82}],1240:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84986,7 +87346,7 @@ module.exports = function setPositions(gd, plotinfo) { } }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454}],496:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199}],1241:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85025,7 +87385,7 @@ module.exports = function style(gd) { }); }; -},{"../../components/color":303,"../../components/drawing":326,"d3":113}],497:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"d3":82}],1242:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85073,7 +87433,7 @@ module.exports = extendFlat({}, { colorscaleAttrs ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../../plots/attributes":403,"../scattergeo/attributes":584}],498:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../../plots/attributes":1148,"../scattergeo/attributes":1331}],1243:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85092,7 +87452,7 @@ module.exports = function calc(gd, trace) { colorscaleCalc(trace, trace.z, '', 'z'); }; -},{"../../components/colorscale/calc":310}],499:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055}],1244:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85147,7 +87507,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('hoverinfo', (layout._dataLength === 1) ? 'location+z+text' : undefined); }; -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":497}],500:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1242}],1245:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85177,7 +87537,7 @@ Choropleth.meta = { module.exports = Choropleth; -},{"../../plots/geo":426,"../heatmap/colorbar":514,"./attributes":497,"./calc":498,"./defaults":499,"./plot":501}],501:[function(require,module,exports){ +},{"../../plots/geo":1171,"../heatmap/colorbar":1259,"./attributes":1242,"./calc":1243,"./defaults":1244,"./plot":1246}],1246:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85398,7 +87758,7 @@ function makeEventDataFunc(trace) { }; } -},{"../../components/color":303,"../../components/colorscale/get_scale":315,"../../components/colorscale/make_scale_function":320,"../../components/drawing":326,"../../lib/array_to_calc_item":373,"../../lib/geo_location_utils":379,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../../plots/geo/constants":424,"./attributes":497,"d3":113}],502:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/get_scale":1060,"../../components/colorscale/make_scale_function":1065,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/geo/constants":1169,"./attributes":1242,"d3":82}],1247:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85498,7 +87858,7 @@ module.exports = extendFlat({}, {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../heatmap/attributes":512,"../scatter/attributes":556}],503:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../scatter/attributes":1301}],1248:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85551,7 +87911,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../plots/cartesian/axes":405,"../heatmap/calc":513}],504:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../heatmap/calc":1258}],1249:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85612,7 +87972,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../plots/plots":454,"./make_color_map":508}],505:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../plots/plots":1199,"./make_color_map":1253}],1250:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85656,7 +88016,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout handleStyleDefaults(traceIn, traceOut, coerce, layout); }; -},{"../../lib":382,"../contour/style_defaults":511,"../heatmap/has_columns":517,"../heatmap/xyz_defaults":523,"./attributes":502}],506:[function(require,module,exports){ +},{"../../lib":1127,"../contour/style_defaults":1256,"../heatmap/has_columns":1262,"../heatmap/xyz_defaults":1268,"./attributes":1247}],1251:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85675,7 +88035,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return heatmapHoverPoints(pointData, xval, yval, hovermode, true); }; -},{"../heatmap/hover":518}],507:[function(require,module,exports){ +},{"../heatmap/hover":1263}],1252:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85707,7 +88067,7 @@ Contour.meta = { module.exports = Contour; -},{"../../plots/cartesian":413,"./attributes":502,"./calc":503,"./colorbar":504,"./defaults":505,"./hover":506,"./plot":509,"./style":510}],508:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./attributes":1247,"./calc":1248,"./colorbar":1249,"./defaults":1250,"./hover":1251,"./plot":1254,"./style":1255}],1253:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85787,7 +88147,7 @@ module.exports = function makeColorMap(trace) { return colorMap; }; -},{"../../components/colorscale/get_scale":315,"d3":113}],509:[function(require,module,exports){ +},{"../../components/colorscale/get_scale":1060,"d3":82}],1254:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86497,7 +88857,7 @@ function makeClipMask(cd0) { return z; } -},{"../../components/drawing":326,"../../lib":382,"../heatmap/plot":521,"d3":113}],510:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../lib":1127,"../heatmap/plot":1266,"d3":82}],1255:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86554,7 +88914,7 @@ module.exports = function style(gd) { heatmapStyle(gd); }; -},{"../../components/drawing":326,"../heatmap/style":522,"./make_color_map":508,"d3":113}],511:[function(require,module,exports){ +},{"../../components/drawing":1071,"../heatmap/style":1267,"./make_color_map":1253,"d3":82}],1256:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86590,7 +88950,7 @@ module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout) } }; -},{"../../components/colorscale/defaults":313}],512:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058}],1257:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86662,7 +89022,7 @@ module.exports = extendFlat({}, {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../scatter/attributes":556}],513:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../scatter/attributes":1301}],1258:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87098,7 +89458,7 @@ function iterateInterp2d(z, emptyPoints, overshoot) { return maxFractionalChange; } -},{"../../components/colorscale/calc":310,"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"../histogram2d/calc":533,"./convert_column_xyz":515,"./has_columns":517,"./max_row_length":520,"fast-isnumeric":117}],514:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"../histogram2d/calc":1278,"./convert_column_xyz":1260,"./has_columns":1262,"./max_row_length":1265,"fast-isnumeric":90}],1259:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87144,7 +89504,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,"d3":113,"fast-isnumeric":117}],515:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1260:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87201,7 +89561,7 @@ module.exports = function convertColumnXYZ(trace, xa, ya) { if(hasColumnText) trace.text = text; }; -},{"../../lib":382}],516:[function(require,module,exports){ +},{"../../lib":1127}],1261:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87239,7 +89599,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":512,"./has_columns":517,"./xyz_defaults":523}],517:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1257,"./has_columns":1262,"./xyz_defaults":1268}],1262:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87255,7 +89615,7 @@ module.exports = function(trace) { return !Array.isArray(trace.z[0]); }; -},{}],518:[function(require,module,exports){ +},{}],1263:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87369,7 +89729,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode, contour) })]; }; -},{"../../lib":382,"../../plots/cartesian/graph_interact":412}],519:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/graph_interact":1157}],1264:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87401,7 +89761,7 @@ Heatmap.meta = { module.exports = Heatmap; -},{"../../plots/cartesian":413,"./attributes":512,"./calc":513,"./colorbar":514,"./defaults":516,"./hover":518,"./plot":521,"./style":522}],520:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./attributes":1257,"./calc":1258,"./colorbar":1259,"./defaults":1261,"./hover":1263,"./plot":1266,"./style":1267}],1265:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87423,7 +89783,7 @@ module.exports = function maxRowLength(z) { return len; }; -},{}],521:[function(require,module,exports){ +},{}],1266:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87813,7 +90173,7 @@ function plotOne(gd, plotinfo, cd) { }); } -},{"../../components/colorscale/get_scale":315,"../../constants/xmlns_namespaces":370,"../../lib":382,"../../plots/plots":454,"./max_row_length":520,"d3":113,"tinycolor2":274}],522:[function(require,module,exports){ +},{"../../components/colorscale/get_scale":1060,"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plots/plots":1199,"./max_row_length":1265,"d3":82,"tinycolor2":1042}],1267:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87834,7 +90194,7 @@ module.exports = function style(gd) { }); }; -},{"d3":113}],523:[function(require,module,exports){ +},{"d3":82}],1268:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87923,7 +90283,7 @@ function isValidZ(z) { return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); } -},{"./has_columns":517,"fast-isnumeric":117}],524:[function(require,module,exports){ +},{"./has_columns":1262,"fast-isnumeric":90}],1269:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88043,7 +90403,7 @@ function makeBinsAttr(axLetter) { }; } -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../bar/attributes":476}],525:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../bar/attributes":1221}],1270:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88069,7 +90429,7 @@ module.exports = function doAvg(size, counts) { return total; }; -},{}],526:[function(require,module,exports){ +},{}],1271:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88099,7 +90459,7 @@ module.exports = function handleBinDefaults(traceIn, traceOut, coerce, binDirect return traceOut; }; -},{}],527:[function(require,module,exports){ +},{}],1272:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88173,7 +90533,7 @@ module.exports = { } }; -},{"fast-isnumeric":117}],528:[function(require,module,exports){ +},{"fast-isnumeric":90}],1273:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88303,7 +90663,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"./average":525,"./bin_functions":527,"./norm_functions":531,"fast-isnumeric":117}],529:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./average":1270,"./bin_functions":1272,"./norm_functions":1276,"fast-isnumeric":90}],1274:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88355,7 +90715,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'}); }; -},{"../../components/color":303,"../../components/errorbars/defaults":331,"../../lib":382,"../bar/style_defaults":486,"./attributes":524,"./bin_defaults":526}],530:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"./attributes":1269,"./bin_defaults":1271}],1275:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88404,7 +90764,7 @@ Histogram.meta = { module.exports = Histogram; -},{"../../plots/cartesian":413,"../bar/hover":479,"../bar/layout_attributes":481,"../bar/layout_defaults":482,"../bar/plot":483,"../bar/set_positions":484,"../bar/style":485,"../scatter/colorbar":559,"./attributes":524,"./calc":528,"./defaults":529}],531:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../bar/hover":1224,"../bar/layout_attributes":1226,"../bar/layout_defaults":1227,"../bar/plot":1228,"../bar/set_positions":1229,"../bar/style":1230,"../scatter/colorbar":1304,"./attributes":1269,"./calc":1273,"./defaults":1274}],1276:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88439,7 +90799,7 @@ module.exports = { } }; -},{}],532:[function(require,module,exports){ +},{}],1277:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88491,7 +90851,7 @@ module.exports = extendFlat({}, {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../heatmap/attributes":512,"../histogram/attributes":524}],533:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../histogram/attributes":1269}],1278:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88657,7 +91017,7 @@ module.exports = function calc(gd, trace) { }; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../histogram/average":525,"../histogram/bin_functions":527,"../histogram/norm_functions":531}],534:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../histogram/average":1270,"../histogram/bin_functions":1272,"../histogram/norm_functions":1276}],1279:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88690,7 +91050,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, layout) { ); }; -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":532,"./sample_defaults":536}],535:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1277,"./sample_defaults":1281}],1280:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88723,7 +91083,7 @@ Histogram2D.meta = { module.exports = Histogram2D; -},{"../../plots/cartesian":413,"../heatmap/calc":513,"../heatmap/colorbar":514,"../heatmap/hover":518,"../heatmap/plot":521,"../heatmap/style":522,"./attributes":532,"./defaults":534}],536:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../heatmap/calc":1258,"../heatmap/colorbar":1259,"../heatmap/hover":1263,"../heatmap/plot":1266,"../heatmap/style":1267,"./attributes":1277,"./defaults":1279}],1281:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88759,7 +91119,7 @@ module.exports = function handleSampleDefaults(traceIn, traceOut, coerce) { handleBinDefaults(traceIn, traceOut, coerce, binDirections); }; -},{"../histogram/bin_defaults":526}],537:[function(require,module,exports){ +},{"../histogram/bin_defaults":1271}],1282:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88803,7 +91163,7 @@ module.exports = extendFlat({}, { colorscaleAttrs ); -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../contour/attributes":502,"../histogram2d/attributes":532}],538:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../contour/attributes":1247,"../histogram2d/attributes":1277}],1283:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88839,7 +91199,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout handleStyleDefaults(traceIn, traceOut, coerce, layout); }; -},{"../../lib":382,"../contour/style_defaults":511,"../histogram2d/sample_defaults":536,"./attributes":537}],539:[function(require,module,exports){ +},{"../../lib":1127,"../contour/style_defaults":1256,"../histogram2d/sample_defaults":1281,"./attributes":1282}],1284:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88872,7 +91232,7 @@ Histogram2dContour.meta = { module.exports = Histogram2dContour; -},{"../../plots/cartesian":413,"../contour/calc":503,"../contour/colorbar":504,"../contour/hover":506,"../contour/plot":509,"../contour/style":510,"./attributes":537,"./defaults":538}],540:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"../contour/calc":1248,"../contour/colorbar":1249,"../contour/hover":1251,"../contour/plot":1254,"../contour/style":1255,"./attributes":1282,"./defaults":1283}],1285:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89006,7 +91366,7 @@ module.exports = { } }; -},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../surface/attributes":601}],541:[function(require,module,exports){ +},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../surface/attributes":1348}],1286:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89168,7 +91528,7 @@ function createMesh3DTrace(scene, data) { module.exports = createMesh3DTrace; -},{"../../lib/str2rgbarray":394,"alpha-shape":40,"convex-hull":102,"delaunay-triangulate":114,"gl-mesh3d":150,"tinycolor2":274}],542:[function(require,module,exports){ +},{"../../lib/str2rgbarray":1139,"alpha-shape":46,"convex-hull":71,"delaunay-triangulate":88,"gl-mesh3d":253,"tinycolor2":1042}],1287:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89265,7 +91625,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout } }; -},{"../../components/colorbar/defaults":305,"../../lib":382,"./attributes":540}],543:[function(require,module,exports){ +},{"../../components/colorbar/defaults":1050,"../../lib":1127,"./attributes":1285}],1288:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89294,7 +91654,7 @@ Mesh3D.meta = { module.exports = Mesh3D; -},{"../../plots/gl3d":441,"../heatmap/colorbar":514,"./attributes":540,"./convert":541,"./defaults":542}],544:[function(require,module,exports){ +},{"../../plots/gl3d":1186,"../heatmap/colorbar":1259,"./attributes":1285,"./convert":1286,"./defaults":1287}],1289:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89514,7 +91874,7 @@ module.exports = { } }; -},{"../../components/color/attributes":302,"../../lib/extend":377,"../../plots/attributes":403,"../../plots/font_attributes":423}],545:[function(require,module,exports){ +},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../../plots/attributes":1148,"../../plots/font_attributes":1168}],1290:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89561,7 +91921,7 @@ function getCdModule(calcdata, _module) { return cdModule; } -},{"../../plots/plots":454}],546:[function(require,module,exports){ +},{"../../plots/plots":1199}],1291:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89713,7 +92073,7 @@ function nextDefaultColor(index) { return pieDefaultColors[index % pieDefaultColors.length]; } -},{"../../components/color":303,"./helpers":548,"fast-isnumeric":117,"tinycolor2":274}],547:[function(require,module,exports){ +},{"../../components/color":1048,"./helpers":1293,"fast-isnumeric":90,"tinycolor2":1042}],1292:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89797,7 +92157,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('pull'); }; -},{"../../lib":382,"./attributes":544}],548:[function(require,module,exports){ +},{"../../lib":1127,"./attributes":1289}],1293:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89826,7 +92186,7 @@ exports.formatPieValue = function formatPieValue(v, separators) { return Lib.numSeparate(vRounded, separators); }; -},{"../../lib":382}],549:[function(require,module,exports){ +},{"../../lib":1127}],1294:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89858,7 +92218,7 @@ Pie.meta = { module.exports = Pie; -},{"./attributes":544,"./base_plot":545,"./calc":546,"./defaults":547,"./layout_attributes":550,"./layout_defaults":551,"./plot":552,"./style":553,"./style_one":554}],550:[function(require,module,exports){ +},{"./attributes":1289,"./base_plot":1290,"./calc":1291,"./defaults":1292,"./layout_attributes":1295,"./layout_defaults":1296,"./plot":1297,"./style":1298,"./style_one":1299}],1295:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89878,7 +92238,7 @@ module.exports = { hiddenlabels: {valType: 'data_array'} }; -},{}],551:[function(require,module,exports){ +},{}],1296:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89900,7 +92260,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) { coerce('hiddenlabels'); }; -},{"../../lib":382,"./layout_attributes":550}],552:[function(require,module,exports){ +},{"../../lib":1127,"./layout_attributes":1295}],1297:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90595,7 +92955,7 @@ function maxExtent(tilt, tiltAxisFraction, depth) { 2 * Math.sqrt(1 - sinTilt * sinTilt * tiltAxisFraction * tiltAxisFraction)); } -},{"../../components/color":303,"../../components/drawing":326,"../../lib/svg_text_utils":395,"../../plots/cartesian/graph_interact":412,"./helpers":548,"d3":113}],553:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/svg_text_utils":1140,"../../plots/cartesian/graph_interact":1157,"./helpers":1293,"d3":82}],1298:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90624,7 +92984,7 @@ module.exports = function style(gd) { }); }; -},{"./style_one":554,"d3":113}],554:[function(require,module,exports){ +},{"./style_one":1299,"d3":82}],1299:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90651,7 +93011,7 @@ module.exports = function styleOne(s, pt, trace) { .call(Color.stroke, lineColor); }; -},{"../../components/color":303}],555:[function(require,module,exports){ +},{"../../components/color":1048}],1300:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90689,7 +93049,7 @@ module.exports = function arraysToCalcdata(cd) { } }; -},{"../../lib":382}],556:[function(require,module,exports){ +},{"../../lib":1127}],1301:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90740,6 +93100,10 @@ module.exports = { dflt: 1, + }, + key: { + valType: 'data_array', + }, text: { valType: 'string', @@ -90933,7 +93297,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../components/drawing":326,"../../lib/extend":377,"./constants":560}],557:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../components/drawing":1071,"../../lib/extend":1122,"./constants":1305}],1302:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91051,6 +93415,10 @@ module.exports = function calc(gd, trace) { for(i = 0; i < serieslen; i++) { cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ? {x: x[i], y: y[i]} : {x: false, y: false}; + + if (trace.key && trace.key[i] !== undefined) { + cd[i].key = trace.key[i]; + } } // this has migrated up from arraysToCalcdata as we have a reference to 's' here @@ -91060,7 +93428,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"./marker_colorscale_calc":570,"./subtypes":575,"fast-isnumeric":117}],558:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./marker_colorscale_calc":1316,"./subtypes":1322,"fast-isnumeric":90}],1303:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91101,7 +93469,7 @@ module.exports = function cleanData(fullData) { } }; -},{}],559:[function(require,module,exports){ +},{}],1304:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91154,7 +93522,7 @@ module.exports = function colorbar(gd, cd) { .options(marker.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,"d3":113,"fast-isnumeric":117}],560:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1305:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91170,7 +93538,7 @@ module.exports = { PTS_LINESONLY: 20 }; -},{}],561:[function(require,module,exports){ +},{}],1306:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91209,6 +93577,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout return; } + coerce('key'); coerce('text'); coerce('mode', defaultMode); @@ -91240,7 +93609,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); }; -},{"../../components/errorbars/defaults":331,"../../lib":382,"./attributes":556,"./constants":560,"./fillcolor_defaults":562,"./line_defaults":566,"./line_shape_defaults":568,"./marker_defaults":571,"./subtypes":575,"./text_defaults":576,"./xy_defaults":577}],562:[function(require,module,exports){ +},{"../../components/errorbars/defaults":1076,"../../lib":1127,"./attributes":1301,"./constants":1305,"./fillcolor_defaults":1307,"./line_defaults":1311,"./line_shape_defaults":1313,"./marker_defaults":1317,"./subtypes":1322,"./text_defaults":1323,"./xy_defaults":1324}],1307:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91279,7 +93648,7 @@ module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coe )); }; -},{"../../components/color":303}],563:[function(require,module,exports){ +},{"../../components/color":1048}],1308:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91332,7 +93701,7 @@ module.exports = function getTraceColor(trace, di) { } }; -},{"../../components/color":303,"./subtypes":575}],564:[function(require,module,exports){ +},{"../../components/color":1048,"./subtypes":1322}],1309:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91403,7 +93772,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return [pointData]; }; -},{"../../components/errorbars":332,"../../plots/cartesian/graph_interact":412,"./get_trace_color":563}],565:[function(require,module,exports){ +},{"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157,"./get_trace_color":1308}],1310:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91429,6 +93798,7 @@ Scatter.attributes = require('./attributes'); Scatter.supplyDefaults = require('./defaults'); Scatter.cleanData = require('./clean_data'); Scatter.calc = require('./calc'); +Scatter.setPositions = require('./set_positions'); Scatter.arraysToCalcdata = require('./arrays_to_calcdata'); Scatter.plot = require('./plot'); Scatter.colorbar = require('./colorbar'); @@ -91438,6 +93808,7 @@ Scatter.selectPoints = require('./select'); Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; +Scatter.animatable = true; Scatter.basePlotModule = require('../../plots/cartesian'); Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend']; Scatter.meta = { @@ -91446,7 +93817,7 @@ Scatter.meta = { module.exports = Scatter; -},{"../../plots/cartesian":413,"./arrays_to_calcdata":555,"./attributes":556,"./calc":557,"./clean_data":558,"./colorbar":559,"./defaults":561,"./hover":564,"./plot":572,"./select":573,"./style":574,"./subtypes":575}],566:[function(require,module,exports){ +},{"../../plots/cartesian":1158,"./arrays_to_calcdata":1300,"./attributes":1301,"./calc":1302,"./clean_data":1303,"./colorbar":1304,"./defaults":1306,"./hover":1309,"./plot":1318,"./select":1319,"./set_positions":1320,"./style":1321,"./subtypes":1322}],1311:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91470,7 +93841,7 @@ module.exports = function lineDefaults(traceIn, traceOut, defaultColor, coerce) coerce('line.dash'); }; -},{}],567:[function(require,module,exports){ +},{}],1312:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91533,7 +93904,7 @@ module.exports = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length, yFrac = pt[1] / ya._length; - return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; + return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance * 0; } function ptDist(pt1, pt2) { @@ -91639,7 +94010,7 @@ module.exports = function linePoints(d, opts) { return segments; }; -},{"../../plots/cartesian/axes":405}],568:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150}],1313:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91658,7 +94029,59 @@ module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) { if(shape === 'spline') coerce('line.smoothing'); }; -},{}],569:[function(require,module,exports){ +},{}],1314:[function(require,module,exports){ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); + +module.exports = function linkTraces(gd, plotinfo, cdscatter) { + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < cdscatter.length; ++i) { + cd = cdscatter[i]; + trace = cd[0].trace; + + // console.log('visible:', trace.uid, trace.visible); + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + trace._nexttrace = null; + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + + prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; + } + } + + /*for(i = 0; i < cdscatter.length; ++i) { + var trace = cdscatter[i][0].trace; + console.log('gd.cdscatter[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + }*/ +} + +},{"../../plots/plots":1199}],1315:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91700,7 +94123,7 @@ module.exports = function makeBubbleSizeFn(trace) { }; }; -},{"fast-isnumeric":117}],570:[function(require,module,exports){ +},{"fast-isnumeric":90}],1316:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91734,7 +94157,7 @@ module.exports = function calcMarkerColorscale(trace) { } }; -},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":316,"./subtypes":575}],571:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1317:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91797,7 +94220,7 @@ module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout } }; -},{"../../components/color":303,"../../components/colorscale/defaults":313,"../../components/colorscale/has_colorscale":316,"./subtypes":575}],572:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1318:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91818,74 +94241,176 @@ var ErrorBars = require('../../components/errorbars'); var subTypes = require('./subtypes'); var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); +var linkTraces = require('./link_traces'); +function cdscatterKey (d) { + return d[0].trace.uid; +} -module.exports = function plot(gd, plotinfo, cdscatter) { - selectMarkers(gd, plotinfo, cdscatter); +module.exports = function plot(gd, plotinfo, cdscatter, traces, transitionOpts) { + var i, uids, noremove; - var xa = plotinfo.x(), - ya = plotinfo.y(); + var transitionConfig = Lib.extendFlat({}, transitionOpts || {}); - // make the container for scatter plots - // (so error bars can find them along with bars) - var scattertraces = plotinfo.plot.select('.scatterlayer') - .selectAll('g.trace.scatter') - .data(cdscatter); + transitionConfig = Lib.extendFlat({ + duration: 0, + easing: 'in-out-cubic', + cascade: 0, + delay: 0, + }, transitionConfig); + + var hasTransition = transitionConfig.duration > 0; - scattertraces.enter().append('g') + if (!traces) { + // If no traces provided, redraw all: + for (i = 0, traces = []; i < cdscatter.length; i++) { + traces[i] = i; + } + noremove = false; + } else { + // If this is a partial update, then don't remove traces whose data is not updated + noremove = true; + } + + var scatterlayer = plotinfo.plot.select('g.scatterlayer'); + var traceJoin = scatterlayer.selectAll('g.trace').data(cdscatter, cdscatterKey); + + var traceEnter = traceJoin.enter().append('g') .attr('class', 'trace scatter') - .style('stroke-miterlimit', 2); + .style('stroke-miterlimit', 2) - // error bars are at the bottom - scattertraces.call(ErrorBars.plot, plotinfo); + // After the elements are created but before they've been draw, we have to do + // this extra step of linking the traces due to z-ordering + linkTraces(gd, plotinfo, cdscatter) + createFills(gd, scatterlayer, cdscatter, traces) - // BUILD LINES AND FILLS - var prevpath = '', - ownFillEl3, ownFillDir, tonext, nexttonext; + traceEnter.each(function(d) { + //console.log('enter:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); - scattertraces.each(function(d) { - var trace = d[0].trace, - line = trace.line, - tr = d3.select(this); - if(trace.visible !== true) return; + traceJoin.transition() + .duration(0) + .each(function(d) { + //console.log('transition:', d[0].trace.uid); + plotOne(gd, plotinfo, d, this, transitionConfig) + }); + + + if (!noremove) { + traceJoin.exit().remove(); + } - ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; + // Sort the traces, once created, so that the ordering is preserved even when + // traces are shown and hidden. This is now needed since we're not just wiping + // everything out and recreating on every update. + for (i = 0, uids = []; i < cdscatter.length; i++) { + uids[i] = cdscatter[i][0].trace.uid; + } + + scatterlayer.selectAll('g.trace').sort(function (a, b) { + var idx1 = uids.indexOf(a[0].trace.uid); + var idx2 = uids.indexOf(b[0].trace.uid); + return idx1 > idx2 ? 1 : -1; + }); - d[0].node3 = tr; // store node for tweaking by selectPoints + // remove paths that didn't get used + // scatterlayer.selectAll('path:not([d])').remove(); +}; - arraysToCalcdata(d); +function createFills (gd, scatterlayer, cdscatter, traces) { + var i, trace, prevtrace; - if(!subTypes.hasLines(trace) && trace.fill === 'none') return; + scatterlayer.selectAll('g.trace').each(function (d) { + var tr = d3.select(this); - var thispath, - thisrevpath, - // fullpath is all paths for this curve, joined together straight - // across gaps, for filling - fullpath = '', - // revpath is fullpath reversed, for fill-to-next - revpath = '', - // functions for converting a point array to a path - pathfn, revpathbase, revpathfn; + // Loop only over the traces being redrawn: + trace = d[0].trace; - // make the fill-to-zero path now, so it shows behind the line - // fill to next puts the fill associated with one trace - // grouped with the previous if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !prevpath)) { - ownFillEl3 = tr.append('path') - .classed('js-fill', true); + (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)) { + trace._ownFill = tr.select('.js-fill.js-tozero'); + if (!trace._ownFill.size()) { + trace._ownFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tozero'); + } + } else { + tr.selectAll('.js-fill.js-tozero').remove(); + trace._ownFill = null; } - else ownFillEl3 = null; // make the fill-to-next path now for the NEXT trace, so it shows // behind both lines. - // nexttonext was created last time, but give it - // this curve's data for fill color - if(nexttonext) tonext = nexttonext.datum(d); + if (trace._nexttrace) { + trace._nextFill = tr.select('.js-fill.js-tonext'); + if (!trace._nextFill.size()) { + trace._nextFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tonext'); + } + } else { + tr.selectAll('.js-fill.js-tonext').remove(); + trace._nextFill = null; + } + }); +} + - // now make a new nexttonext for next time - nexttonext = tr.append('path').classed('js-fill', true); +function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { + selectMarkers(gd, plotinfo, cdscatter); + + function transition (selection) { + return selection.transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing); + } + + var xa = plotinfo.x(), + ya = plotinfo.y(); + + var trace = cdscatter[0].trace, + line = trace.line, + tr = d3.select(group); + + // (so error bars can find them along with bars) + // error bars are at the bottom + tr.call(ErrorBars.plot, plotinfo); + + if(trace.visible !== true) return; + + // BUILD LINES AND FILLS + var ownFillEl3, tonext, nexttonext; + var ownFillDir = trace.fill.charAt(trace.fill.length - 1); + if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; + + // store node for tweaking by selectPoints + cdscatter[0].node3 = tr; + + arraysToCalcdata(cdscatter); + + var prevpath = ''; + var prevtrace = trace._prevtrace; + + if (prevtrace) { + prevpath = prevtrace._revpath || ''; + tonext = prevtrace._nextFill; + } + + var thispath, + thisrevpath, + // fullpath is all paths for this curve, joined together straight + // across gaps, for filling + fullpath = '', + // revpath is fullpath reversed, for fill-to-next + revpath = '', + // functions for converting a point array to a path + pathfn, revpathbase, revpathfn; + + ownFillEl3 = trace._ownFill; + + if(subTypes.hasLines(trace) || trace.fill !== 'none') { + + if (tonext) { + // This tells .style which trace to use for fill information: + tonext.datum(cdscatter); + } if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { pathfn = Drawing.steps(line.shape); @@ -91917,7 +94442,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { return revpathbase(pts.reverse()); }; - var segments = linePoints(d, { + var segments = linePoints(cdscatter, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -91947,7 +94472,12 @@ module.exports = function plot(gd, plotinfo, cdscatter) { revpath = thisrevpath + 'Z' + revpath; } if(subTypes.hasLines(trace) && pts.length > 1) { - tr.append('path').classed('js-line', true).attr('d', thispath); + var lineJoin = tr.selectAll('.js-line').data([cdscatter]); + + lineJoin.enter() + .append('path').classed('js-line', true).attr('d', thispath); + + transition(lineJoin).attr('d', thispath); } } if(ownFillEl3) { @@ -91962,10 +94492,11 @@ module.exports = function plot(gd, plotinfo, cdscatter) { // fill to zero: full trace path, plus extension of // the endpoints to the appropriate axis - ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + transition(ownFillEl3).attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); + } else { + // fill to self: just join the path to itself + transition(ownFillEl3).attr('d', fullpath + 'Z'); } - // fill to self: just join the path to itself - else ownFillEl3.attr('d', fullpath + 'Z'); } } else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { @@ -91975,7 +94506,7 @@ module.exports = function plot(gd, plotinfo, cdscatter) { // contours, we just add the two paths closed on themselves. // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. - tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); + transition(tonext).attr('d', fullpath + 'Z' + prevpath + 'Z'); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -91983,48 +94514,77 @@ module.exports = function plot(gd, plotinfo, cdscatter) { // y/x, but if they *aren't*, we should ideally do more complicated // things depending on whether the new endpoint projects onto the // existing curve or off the end of it - tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + transition(tonext).attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); } } - prevpath = revpath; } - }); - // remove paths that didn't get used - scattertraces.selectAll('path:not([d])').remove(); + trace._revpath = revpath; + } + function visFilter(d) { return d.filter(function(v) { return v.vis; }); } - scattertraces.append('g') - .attr('class', 'points') - .each(function(d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); + function keyFunc (d) { + return d.key; + } - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - .enter().append('path') - .classed('point', true) - .call(Drawing.translatePoints, xa, ya); - } - if(showText) { - s.selectAll('g') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - // each text needs to go in its own 'g' in case - // it gets converted to mathjax - .enter().append('g') - .append('text') - .call(Drawing.translatePoints, xa, ya); - } + function getKeyFunc(trace) { + if (trace.key) { + return keyFunc; + } + } + + + function makePoints (d) { + var trace = d[0].trace, + s = d3.select(this), + showMarkers = subTypes.hasMarkers(trace), + showText = subTypes.hasText(trace); + + if((!showMarkers && !showText) || trace.visible !== true) s.remove(); + else { + if(showMarkers) { + var join = s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) + + join.enter().append('path') + .classed('point', true) + .call(Drawing.pointStyle, trace) + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1) + + join.transition() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 0) + .call(Drawing.pointStyle, trace) + + join.exit() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); } - }); + if(showText) { + s.selectAll('g') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + // each text needs to go in its own 'g' in case + // it gets converted to mathjax + .enter().append('g') + .append('text') + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1); + } + } + } + + var pointJoin = tr.selectAll('.points').data([cdscatter]); + + pointJoin.enter().append('g') + .classed('points', true) + .each(makePoints); + + pointJoin.transition() + .duration(0) + .each(makePoints); + + pointJoin.exit().remove(); }; function selectMarkers(gd, plotinfo, cdscatter) { @@ -92033,45 +94593,46 @@ function selectMarkers(gd, plotinfo, cdscatter) { xr = d3.extent(xa.range.map(xa.l2c)), yr = d3.extent(ya.range.map(ya.l2c)); - cdscatter.forEach(function(d, i) { - var trace = d[0].trace; - if(!subTypes.hasMarkers(trace)) return; - // if marker.maxdisplayed is used, select a maximum of - // mnum markers to show, from the set that are in the viewport - var mnum = trace.marker.maxdisplayed; + // XXX: Not okay. Just makes it work for now. + var i = 0; - // TODO: remove some as we get away from the viewport? - if(mnum === 0) return; + var trace = cdscatter[0].trace; + if(!subTypes.hasMarkers(trace)) return; + // if marker.maxdisplayed is used, select a maximum of + // mnum markers to show, from the set that are in the viewport + var mnum = trace.marker.maxdisplayed; - var cd = d.filter(function(v) { - return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; - }), - inc = Math.ceil(cd.length / mnum), - tnum = 0; - cdscatter.forEach(function(cdj, j) { - var tracei = cdj[0].trace; - if(subTypes.hasMarkers(tracei) && - tracei.marker.maxdisplayed > 0 && j < i) { - tnum++; - } - }); + // TODO: remove some as we get away from the viewport? + if(mnum === 0) return; - // if multiple traces use maxdisplayed, stagger which markers we - // display this formula offsets successive traces by 1/3 of the - // increment, adding an extra small amount after each triplet so - // it's not quite periodic - var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); - - // for error bars: save in cd which markers to show - // so we don't have to repeat this - d.forEach(function(v) { delete v.vis; }); - cd.forEach(function(v, i) { - if(Math.round((i + i0) % inc) === 0) v.vis = true; - }); + var cd = cdscatter.filter(function(v) { + return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; + }), + inc = Math.ceil(cd.length / mnum), + tnum = 0; + cdscatter.forEach(function(cdj, j) { + var tracei = cdj[0].trace; + if(subTypes.hasMarkers(tracei) && + tracei.marker.maxdisplayed > 0 && j < i) { + tnum++; + } + }); + + // if multiple traces use maxdisplayed, stagger which markers we + // display this formula offsets successive traces by 1/3 of the + // increment, adding an extra small amount after each triplet so + // it's not quite periodic + var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); + + // for error bars: save in cd which markers to show + // so we don't have to repeat this + cdscatter.forEach(function(v) { delete v.vis; }); + cd.forEach(function(v, i) { + if(Math.round((i + i0) % inc) === 0) v.vis = true; }); } -},{"../../components/drawing":326,"../../components/errorbars":332,"../../lib":382,"./arrays_to_calcdata":555,"./line_points":567,"./subtypes":575,"d3":113}],573:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1300,"./line_points":1312,"./link_traces":1314,"./subtypes":1322,"d3":82}],1319:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92141,7 +94702,67 @@ module.exports = function selectPoints(searchInfo, polygon) { return selection; }; -},{"./subtypes":575}],574:[function(require,module,exports){ +},{"./subtypes":1322}],1320:[function(require,module,exports){ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + +'use strict'; + +var Plots = require('../../plots/plots'); +var Axes = require('../../plots/cartesian/axes'); +var Lib = require('../../lib'); + +/** + * setPositions is a bit of a misnomer here. It comes from the box plot + * type that actually does setting of positions. It's the hook though + * that we need to set up links between traces so that trace-level .plot + * doesn't require any links between traces. + */ +module.exports = function setPositions(gd, plotinfo) { + // console.log('setPositions:', plotinfo); + var i, cd, trace; + var fullLayout = gd._fullLayout; + var xa = plotinfo.x(); + var ya = plotinfo.y(); + + var prevtrace = null; + + for(i = 0; i < gd.calcdata.length; ++i) { + cd = gd.calcdata[i]; + trace = cd[0].trace; + + // console.log('visible:', trace.uid, trace.visible); + if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && + trace.xaxis === xa._id && + trace.yaxis === ya._id) { + + trace._nexttrace = null; + + if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { + trace._prevtrace = prevtrace; + + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + + prevtrace = trace; + } else { + trace._prevtrace = trace._nexttrace = null; + } + } + for(i = 0; i < gd.calcdata.length; ++i) { + var trace = gd.calcdata[i][0].trace; + // console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) + } +}; + +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199}],1321:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92183,7 +94804,7 @@ module.exports = function style(gd) { s.call(ErrorBars.style); }; -},{"../../components/drawing":326,"../../components/errorbars":332,"d3":113}],575:[function(require,module,exports){ +},{"../../components/drawing":1071,"../../components/errorbars":1077,"d3":82}],1322:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92217,7 +94838,7 @@ module.exports = { } }; -},{}],576:[function(require,module,exports){ +},{}],1323:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92238,7 +94859,7 @@ module.exports = function(traceIn, traceOut, layout, coerce) { Lib.coerceFont(coerce, 'textfont', layout.font); }; -},{"../../lib":382}],577:[function(require,module,exports){ +},{"../../lib":1127}],1324:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92283,7 +94904,7 @@ module.exports = function handleXYDefaults(traceIn, traceOut, coerce) { return len; }; -},{}],578:[function(require,module,exports){ +},{}],1325:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92407,7 +95028,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../constants/gl_markers":369,"../../lib/extend":377,"../scatter/attributes":556}],579:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1326:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92436,7 +95057,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../scatter/arrays_to_calcdata":555,"../scatter/marker_colorscale_calc":570}],580:[function(require,module,exports){ +},{"../scatter/arrays_to_calcdata":1300,"../scatter/marker_colorscale_calc":1316}],1327:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92507,7 +95128,7 @@ function calculateErrors(data, scaleFactor) { module.exports = calculateErrors; -},{"../../components/errorbars/compute_error":330}],581:[function(require,module,exports){ +},{"../../components/errorbars/compute_error":1075}],1328:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92966,7 +95587,7 @@ function createLineWithMarkers(scene, data) { module.exports = createLineWithMarkers; -},{"../../constants/gl3d_dashes":368,"../../constants/gl_markers":369,"../../lib":382,"../../lib/gl_format_color":380,"../../lib/str2rgbarray":394,"../scatter/make_bubble_size_func":569,"./calc_errors":580,"delaunay-triangulate":114,"gl-error3d":121,"gl-line3d":127,"gl-mesh3d":150,"gl-scatter3d":193}],582:[function(require,module,exports){ +},{"../../constants/gl3d_dashes":1113,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../scatter/make_bubble_size_func":1315,"./calc_errors":1327,"delaunay-triangulate":88,"gl-error3d":123,"gl-line3d":193,"gl-mesh3d":253,"gl-scatter3d":905}],1329:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93051,7 +95672,7 @@ function handleXYZDefaults(traceIn, traceOut, coerce) { return len; } -},{"../../components/errorbars/defaults":331,"../../lib":382,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":578}],583:[function(require,module,exports){ +},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1325}],1330:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93082,7 +95703,7 @@ Scatter3D.meta = { module.exports = Scatter3D; -},{"../../constants/gl_markers":369,"../../plots/gl3d":441,"../scatter/colorbar":559,"./attributes":578,"./calc":579,"./convert":581,"./defaults":582}],584:[function(require,module,exports){ +},{"../../constants/gl_markers":1114,"../../plots/gl3d":1186,"../scatter/colorbar":1304,"./attributes":1325,"./calc":1326,"./convert":1328,"./defaults":1329}],1331:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93157,7 +95778,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../../plots/attributes":403,"../scatter/attributes":556}],585:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1332:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93180,7 +95801,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../scatter/marker_colorscale_calc":570}],586:[function(require,module,exports){ +},{"../scatter/marker_colorscale_calc":1316}],1333:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93253,7 +95874,7 @@ function handleLonLatLocDefaults(traceIn, traceOut, coerce) { return len; } -},{"../../lib":382,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":584}],587:[function(require,module,exports){ +},{"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1331}],1334:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93284,7 +95905,7 @@ ScatterGeo.meta = { module.exports = ScatterGeo; -},{"../../plots/geo":426,"../scatter/colorbar":559,"./attributes":584,"./calc":585,"./defaults":586,"./plot":588}],588:[function(require,module,exports){ +},{"../../plots/geo":1171,"../scatter/colorbar":1304,"./attributes":1331,"./calc":1332,"./defaults":1333,"./plot":1335}],1335:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93584,7 +96205,7 @@ function makeEventDataFunc(trace) { }; } -},{"../../components/color":303,"../../components/drawing":326,"../../lib/array_to_calc_item":373,"../../lib/geo_location_utils":379,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../scatter/subtypes":575,"./attributes":584,"d3":113}],589:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../scatter/subtypes":1322,"./attributes":1331,"d3":82}],1336:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93666,7 +96287,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../constants/gl2d_dashes":367,"../../constants/gl_markers":369,"../../lib/extend":377,"../scatter/attributes":556}],590:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1337:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94258,7 +96879,7 @@ function createLineWithMarkers(scene, data) { module.exports = createLineWithMarkers; -},{"../../components/errorbars":332,"../../constants/gl2d_dashes":367,"../../constants/gl_markers":369,"../../lib":382,"../../lib/gl_format_color":380,"../../lib/str2rgbarray":394,"../../plots/cartesian/axes":405,"../scatter/get_trace_color":563,"../scatter/make_bubble_size_func":569,"../scatter/subtypes":575,"fast-isnumeric":117,"gl-error2d":119,"gl-line2d":125,"gl-scatter2d":190,"gl-scatter2d-fancy":185}],591:[function(require,module,exports){ +},{"../../components/errorbars":1077,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../scatter/get_trace_color":1308,"../scatter/make_bubble_size_func":1315,"../scatter/subtypes":1322,"fast-isnumeric":90,"gl-error2d":91,"gl-line2d":160,"gl-scatter2d":781,"gl-scatter2d-fancy":746}],1338:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94315,7 +96936,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); }; -},{"../../components/errorbars/defaults":331,"../../lib":382,"../scatter/constants":560,"../scatter/fillcolor_defaults":562,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/xy_defaults":577,"./attributes":589}],592:[function(require,module,exports){ +},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/constants":1305,"../scatter/fillcolor_defaults":1307,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/xy_defaults":1324,"./attributes":1336}],1339:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94346,7 +96967,7 @@ ScatterGl.meta = { module.exports = ScatterGl; -},{"../../plots/gl2d":438,"../scatter/colorbar":559,"../scatter3d/calc":579,"./attributes":589,"./convert":590,"./defaults":591}],593:[function(require,module,exports){ +},{"../../plots/gl2d":1183,"../scatter/colorbar":1304,"../scatter3d/calc":1326,"./attributes":1336,"./convert":1337,"./defaults":1338}],1340:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94431,7 +97052,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../../plots/attributes":403,"../scatter/attributes":556}],594:[function(require,module,exports){ +},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1341:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94530,7 +97151,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":382,"../../plots/cartesian/axes":405,"../scatter/marker_colorscale_calc":570,"../scatter/subtypes":575,"fast-isnumeric":117}],595:[function(require,module,exports){ +},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../scatter/marker_colorscale_calc":1316,"../scatter/subtypes":1322,"fast-isnumeric":90}],1342:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94627,7 +97248,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('hoverinfo', (layout._dataLength === 1) ? 'a+b+c+text' : undefined); }; -},{"../../lib":382,"../scatter/constants":560,"../scatter/fillcolor_defaults":562,"../scatter/line_defaults":566,"../scatter/line_shape_defaults":568,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":593}],596:[function(require,module,exports){ +},{"../../lib":1127,"../scatter/constants":1305,"../scatter/fillcolor_defaults":1307,"../scatter/line_defaults":1311,"../scatter/line_shape_defaults":1313,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1340}],1343:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94677,7 +97298,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return scatterPointData; }; -},{"../../plots/cartesian/axes":405,"../scatter/hover":564}],597:[function(require,module,exports){ +},{"../../plots/cartesian/axes":1150,"../scatter/hover":1309}],1344:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94710,7 +97331,7 @@ ScatterTernary.meta = { module.exports = ScatterTernary; -},{"../../plots/ternary":461,"../scatter/colorbar":559,"./attributes":593,"./calc":594,"./defaults":595,"./hover":596,"./plot":598,"./select":599,"./style":600}],598:[function(require,module,exports){ +},{"../../plots/ternary":1206,"../scatter/colorbar":1304,"./attributes":1340,"./calc":1341,"./defaults":1342,"./hover":1343,"./plot":1345,"./select":1346,"./style":1347}],1345:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94756,7 +97377,7 @@ module.exports = function plot(ternary, data) { scatterPlot(ternary.graphDiv, plotinfo, calcdata); }; -},{"../scatter/plot":572}],599:[function(require,module,exports){ +},{"../scatter/plot":1318}],1346:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94791,7 +97412,7 @@ module.exports = function selectPoints(searchInfo, polygon) { return selection; }; -},{"../scatter/select":573}],600:[function(require,module,exports){ +},{"../scatter/select":1319}],1347:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94820,7 +97441,7 @@ module.exports = function style(gd) { scatterStyle(gd); }; -},{"../scatter/style":574}],601:[function(require,module,exports){ +},{"../scatter/style":1321}],1348:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95040,7 +97661,7 @@ module.exports = { } }; -},{"../../components/color":303,"../../components/colorscale/attributes":309,"../../lib/extend":377}],602:[function(require,module,exports){ +},{"../../components/color":1048,"../../components/colorscale/attributes":1054,"../../lib/extend":1122}],1349:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95064,7 +97685,7 @@ module.exports = function calc(gd, trace) { } }; -},{"../../components/colorscale/calc":310}],603:[function(require,module,exports){ +},{"../../components/colorscale/calc":1055}],1350:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95111,7 +97732,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,"d3":113,"fast-isnumeric":117}],604:[function(require,module,exports){ +},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1351:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95474,7 +98095,7 @@ function createSurfaceTrace(scene, data) { module.exports = createSurfaceTrace; -},{"../../lib/str2rgbarray":394,"gl-surface3d":221,"ndarray":253,"ndarray-fill":246,"ndarray-homography":251,"ndarray-ops":252,"tinycolor2":274}],605:[function(require,module,exports){ +},{"../../lib/str2rgbarray":1139,"gl-surface3d":1003,"ndarray":1031,"ndarray-fill":1009,"ndarray-homography":1025,"ndarray-ops":1026,"tinycolor2":1042}],1352:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95591,7 +98212,7 @@ function mapLegacy(traceIn, oldAttr, newAttr) { } } -},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":601}],606:[function(require,module,exports){ +},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1348}],1353:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95621,5 +98242,5 @@ Surface.meta = { module.exports = Surface; -},{"../../plots/gl3d":441,"./attributes":601,"./calc":602,"./colorbar":603,"./convert":604,"./defaults":605}]},{},[12])(12) +},{"../../plots/gl3d":1186,"./attributes":1348,"./calc":1349,"./colorbar":1350,"./convert":1351,"./defaults":1352}]},{},[12])(12) }); \ No newline at end of file diff --git a/dist/plotly.min.js b/dist/plotly.min.js index 3dfca5ec0ac..d5f378c3112 100644 --- a/dist/plotly.min.js +++ b/dist/plotly.min.js @@ -4,41 +4,44 @@ * All rights reserved. * Licensed under the MIT license */ -!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.Plotly=t()}}(function(){var t;return function e(t,r,n){function i(o,s){if(!r[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[o]={exports:{}};t[o][0].call(u.exports,function(e){var r=t[o][1][e];return i(r?r:e)},u,u.exports,e,t,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;or;++r)e[r]=0;return e}function o(t,e,r){switch(arguments.length){case 0:return new i([0],[0],0);case 1:if("number"==typeof t){var n=a(t);return new i(n,n,0)}return new i(t,a(t.length),0);case 2:if("number"==typeof e){var n=a(t.length);return new i(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new i(t,e,r)}}e.exports=o;var s=t("cubic-hermite"),l=t("binary-search-bounds"),c=i.prototype;c.flush=function(t){var e=l.gt(this._time,t)-1;0>=e||(this._time.splice(0,e),this._state.splice(0,e*this.dimension),this._velocity.splice(0,e*this.dimension))},c.curve=function(t){var e=this._time,r=e.length,i=l.le(e,t),a=this._scratch[0],o=this._state,c=this._velocity,u=this.dimension,f=this.bounds;if(0>i)for(var h=u-1,d=0;u>d;++d,--h)a[d]=o[h];else if(i>=r-1)for(var h=o.length-1,p=t-e[r-1],d=0;u>d;++d,--h)a[d]=o[h]+p*c[h];else{for(var h=u*(i+1)-1,g=e[i],v=e[i+1],m=v-g||1,y=this._scratch[1],b=this._scratch[2],x=this._scratch[3],_=this._scratch[4],w=!0,d=0;u>d;++d,--h)y[d]=o[h],x[d]=c[h]*m,b[d]=o[h+u],_[d]=c[h+u]*m,w=w&&y[d]===b[d]&&x[d]===_[d]&&0===x[d];if(w)for(var d=0;u>d;++d)a[d]=y[d];else s(y,x,b,_,(t-g)/m,a)}for(var k=f[0],A=f[1],d=0;u>d;++d)a[d]=n(k[d],A[d],a[d]);return a},c.dcurve=function(t){var e=this._time,r=e.length,n=l.le(e,t),i=this._scratch[0],a=this._state,o=this._velocity,c=this.dimension;if(n>=r-1)for(var u=a.length-1,f=(t-e[r-1],0);c>f;++f,--u)i[f]=o[u];else{for(var u=c*(n+1)-1,h=e[n],d=e[n+1],p=d-h||1,g=this._scratch[1],v=this._scratch[2],m=this._scratch[3],y=this._scratch[4],b=!0,f=0;c>f;++f,--u)g[f]=a[u],m[f]=o[u]*p,v[f]=a[u+c],y[f]=o[u+c]*p,b=b&&g[f]===v[f]&&m[f]===y[f]&&0===m[f];if(b)for(var f=0;c>f;++f)i[f]=0;else{s.derivative(g,m,v,y,(t-h)/p,i);for(var f=0;c>f;++f)i[f]/=p}}return i},c.lastT=function(){var t=this._time;return t[t.length-1]},c.stable=function(){for(var t=this._velocity,e=t.length,r=this.dimension-1;r>=0;--r)if(t[--e])return!1;return!0},c.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],c=s[1];this._time.push(e,t);for(var u=0;2>u;++u)for(var f=0;r>f;++f)i.push(i[o++]),a.push(0);this._time.push(t);for(var f=r;f>0;--f)i.push(n(l[f-1],c[f-1],arguments[f])),a.push(0)}},c.push=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=t-e,l=this.bounds,c=l[0],u=l[1],f=s>1e-6?1/s:0;this._time.push(t);for(var h=r;h>0;--h){var d=n(c[h-1],u[h-1],arguments[h]);i.push(d),a.push((d-i[o++])*f)}}},c.set=function(t){var e=this.dimension;if(!(t0;--l)r.push(n(o[l-1],s[l-1],arguments[l])),i.push(0)}},c.move=function(t){var e=this.lastT(),r=this.dimension;if(!(e>=t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],c=s[1],u=t-e,f=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var d=arguments[h];i.push(n(l[h-1],c[h-1],i[o++]+d)),a.push(d*f)}}},c.idle=function(t){var e=this.lastT();if(!(e>t)){var r=this.dimension,i=this._state,a=this._velocity,o=i.length-r,s=this.bounds,l=s[0],c=s[1],u=t-e;this._time.push(t);for(var f=r-1;f>=0;--f)i.push(n(l[f],c[f],i[o]+u*a[o])),a.push(0),o+=1}}},{"binary-search-bounds":21,"cubic-hermite":22}],21:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],22:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,c=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var u=t.length-1;u>=0;--u)a[u]=o*t[u]+s*e[u]+l*r[u]+c*n[u];return a}return o*t+s*e+l*r[u]+c*n}function i(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,c=(1+2*i)*l,u=i*l,f=s*(3-2*i),h=s*o;if(t.length){a||(a=new Array(t.length));for(var d=t.length-1;d>=0;--d)a[d]=c*t[d]+u*e[d]+f*r[d]+h*n[d];return a}return c*t+u*e+f*r+h*n}e.exports=i,e.exports.derivative=n},{}],23:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t}e.exports=n},{}],24:[function(t,e,r){function n(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}e.exports=n},{}],25:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}e.exports=n},{}],26:[function(t,e,r){function n(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}e.exports=n},{}],27:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a),t}e.exports=n},{}],28:[function(t,e,r){"use strict";function n(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-(1/0),1/0]}function i(t){t=t||{};var e=t.matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return new n(e)}var a=t("binary-search-bounds"),o=t("mat4-interpolate"),s=t("gl-mat4/invert"),l=t("gl-mat4/rotateX"),c=t("gl-mat4/rotateY"),u=t("gl-mat4/rotateZ"),f=t("gl-mat4/lookAt"),h=t("gl-mat4/translate"),d=(t("gl-mat4/scale"),t("gl-vec3/normalize")),p=[0,0,0];e.exports=i;var g=n.prototype;g.recalcMatrix=function(t){var e=this._time,r=a.le(e,t),n=this.computedMatrix;if(!(0>r)){var i=this._components;if(r===e.length-1)for(var l=16*r,c=0;16>c;++c)n[c]=i[l++];else{for(var u=e[r+1]-e[r],l=16*r,f=this.prevMatrix,h=!0,c=0;16>c;++c)f[c]=i[l++];for(var p=this.nextMatrix,c=0;16>c;++c)p[c]=i[l++],h=h&&f[c]===p[c];if(1e-6>u||h)for(var c=0;16>c;++c)n[c]=f[c];else o(n,f,p,(t-e[r])/u)}var g=this.computedUp;g[0]=n[1],g[1]=n[5],g[2]=n[6],d(g,g);var v=this.computedInverse;s(v,n);var m=this.computedEye,y=v[15];m[0]=v[12]/y,m[1]=v[13]/y,m[2]=v[14]/y;for(var b=this.computedCenter,x=Math.exp(this.computedRadius[0]),c=0;3>c;++c)b[c]=m[c]-n[2+4*c]*x}},g.idle=function(t){if(!(tn;++n)e.push(e[r++]);this._time.push(t)}},g.flush=function(t){var e=a.gt(this._time,t)-2;0>e||(this._time.slice(0,e),this._components.slice(0,16*e))},g.lastT=function(){return this._time[this._time.length-1]},g.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||p,n=n||this.computedUp,this.setMatrix(t,f(this.computedMatrix,e,r,n));for(var i=0,a=0;3>a;++a)i+=Math.pow(r[a]-e[a],2);i=Math.log(Math.sqrt(i)),this.computedRadius[0]=i},g.rotate=function(t,e,r,n){this.recalcMatrix(t);var i=this.computedInverse;e&&c(i,i,e),r&&l(i,i,r),n&&u(i,i,n),this.setMatrix(t,s(this.computedMatrix,i))};var v=[0,0,0];g.pan=function(t,e,r,n){v[0]=-(e||0),v[1]=-(r||0),v[2]=-(n||0),this.recalcMatrix(t);var i=this.computedInverse;h(i,i,v),this.setMatrix(t,s(i,i))},g.translate=function(t,e,r,n){v[0]=e||0,v[1]=r||0,v[2]=n||0,this.recalcMatrix(t);var i=this.computedMatrix;h(i,i,v),this.setMatrix(t,i)},g.setMatrix=function(t,e){if(!(tr;++r)this._components.push(e[r])}},g.setDistance=function(t,e){this.computedRadius[0]=e},g.setDistanceLimits=function(t,e){var r=this._limits;r[0]=t,r[1]=e},g.getDistanceLimits=function(t){var e=this._limits;return t?(t[0]=e[0],t[1]=e[1],t):e}},{"binary-search-bounds":29,"gl-mat4/invert":137,"gl-mat4/lookAt":138,"gl-mat4/rotateX":142,"gl-mat4/rotateY":143,"gl-mat4/rotateZ":144,"gl-mat4/scale":145,"gl-mat4/translate":146,"gl-vec3/normalize":27,"mat4-interpolate":30}],29:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],30:[function(t,e,r){function n(t,e,r,n){if(0===u(e)||0===u(r))return!1;var i=c(e,h.translate,h.scale,h.skew,h.perspective,h.quaternion),a=c(r,d.translate,d.scale,d.skew,d.perspective,d.quaternion);return i&&a?(s(p.translate,h.translate,d.translate,n),s(p.skew,h.skew,d.skew,n),s(p.scale,h.scale,d.scale,n),s(p.perspective,h.perspective,d.perspective,n),f(p.quaternion,h.quaternion,d.quaternion,n),l(t,p.translate,p.scale,p.skew,p.perspective,p.quaternion),!0):!1}function i(){return{translate:a(),scale:a(1),skew:a(),perspective:o(),quaternion:o()}}function a(t){return[t||0,t||0,t||0]}function o(){return[0,0,0,1]}var s=t("gl-vec3/lerp"),l=t("mat4-recompose"),c=t("mat4-decompose"),u=t("gl-mat4/determinant"),f=t("quat-slerp"),h=i(),d=i(),p=i();e.exports=n},{"gl-mat4/determinant":133,"gl-vec3/lerp":26,"mat4-decompose":31,"mat4-recompose":33,"quat-slerp":34}],31:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function i(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}function a(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var o=t("./normalize"),s=t("gl-mat4/create"),l=t("gl-mat4/clone"),c=t("gl-mat4/determinant"),u=t("gl-mat4/invert"),f=t("gl-mat4/transpose"),h={length:t("gl-vec3/length"),normalize:t("gl-vec3/normalize"),dot:t("gl-vec3/dot"),cross:t("gl-vec3/cross")},d=s(),p=s(),g=[0,0,0,0],v=[[0,0,0],[0,0,0],[0,0,0]],m=[0,0,0];e.exports=function(t,e,r,s,y,b){if(e||(e=[0,0,0]),r||(r=[0,0,0]),s||(s=[0,0,0]),y||(y=[0,0,0,1]),b||(b=[0,0,0,1]),!o(d,t))return!1;if(l(p,d),p[3]=0,p[7]=0,p[11]=0,p[15]=1,Math.abs(c(p)<1e-8))return!1;var x=d[3],_=d[7],w=d[11],k=d[12],A=d[13],M=d[14],T=d[15];if(0!==x||0!==_||0!==w){g[0]=x,g[1]=_,g[2]=w,g[3]=T;var E=u(p,p);if(!E)return!1;f(p,p),n(y,g,p)}else y[0]=y[1]=y[2]=0,y[3]=1;if(e[0]=k,e[1]=A,e[2]=M,i(v,d),r[0]=h.length(v[0]),h.normalize(v[0],v[0]),s[0]=h.dot(v[0],v[1]),a(v[1],v[1],v[0],1,-s[0]),r[1]=h.length(v[1]),h.normalize(v[1],v[1]),s[0]/=r[1],s[1]=h.dot(v[0],v[2]),a(v[2],v[2],v[0],1,-s[1]),s[2]=h.dot(v[1],v[2]),a(v[2],v[2],v[1],1,-s[2]),r[2]=h.length(v[2]),h.normalize(v[2],v[2]),s[1]/=r[2],s[2]/=r[2],h.cross(m,v[1],v[2]),h.dot(v[0],m)<0)for(var L=0;3>L;L++)r[L]*=-1,v[L][0]*=-1,v[L][1]*=-1,v[L][2]*=-1;return b[0]=.5*Math.sqrt(Math.max(1+v[0][0]-v[1][1]-v[2][2],0)),b[1]=.5*Math.sqrt(Math.max(1-v[0][0]+v[1][1]-v[2][2],0)),b[2]=.5*Math.sqrt(Math.max(1-v[0][0]-v[1][1]+v[2][2],0)),b[3]=.5*Math.sqrt(Math.max(1+v[0][0]+v[1][1]+v[2][2],0)),v[2][1]>v[1][2]&&(b[0]=-b[0]),v[0][2]>v[2][0]&&(b[1]=-b[1]),v[1][0]>v[0][1]&&(b[2]=-b[2]),!0}},{"./normalize":32,"gl-mat4/clone":131,"gl-mat4/create":132,"gl-mat4/determinant":133,"gl-mat4/invert":137,"gl-mat4/transpose":147,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/length":25,"gl-vec3/normalize":27}],32:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;16>i;i++)t[i]=e[i]*n;return!0}},{}],33:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":132,"gl-mat4/fromRotationTranslation":135,"gl-mat4/identity":136,"gl-mat4/multiply":139,"gl-mat4/scale":145,"gl-mat4/translate":146}],34:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":35}],35:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,c=e[0],u=e[1],f=e[2],h=e[3],d=r[0],p=r[1],g=r[2],v=r[3];return a=c*d+u*p+f*g+h*v,0>a&&(a=-a,d=-d,p=-p,g=-g,v=-v),1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n),t[0]=s*c+l*d,t[1]=s*u+l*p,t[2]=s*f+l*g,t[3]=s*h+l*v,t}e.exports=n},{}],36:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,c){var u=e+a+c;if(f>0){var f=Math.sqrt(u+1);t[0]=.5*(o-l)/f,t[1]=.5*(s-n)/f,t[2]=.5*(r-a)/f,t[3]=.5*f}else{var h=Math.max(e,a,c),f=Math.sqrt(2*h-u+1);e>=h?(t[0]=.5*f,t[1]=.5*(i+r)/f,t[2]=.5*(s+n)/f,t[3]=.5*(o-l)/f):a>=h?(t[0]=.5*(r+i)/f,t[1]=.5*f,t[2]=.5*(l+o)/f,t[3]=.5*(s-n)/f):(t[0]=.5*(n+s)/f,t[1]=.5*(o+l)/f,t[2]=.5*f,t[3]=.5*(r-i)/f)}return t}e.exports=n},{}],37:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function a(t,e){var r=e[0],n=e[1],a=e[2],o=e[3],s=i(r,n,a,o);s>1e-6?(t[0]=r/s,t[1]=n/s,t[2]=a/s,t[3]=o/s):(t[0]=t[1]=t[2]=0,t[3]=1)}function o(t,e,r){this.radius=l([r]),this.center=l(e),this.rotation=l(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),r=[].slice.call(r,0,4),a(r,r);var i=new o(r,e,Math.log(n));return i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up),i}e.exports=s;var l=t("filtered-vector"),c=t("gl-mat4/lookAt"),u=t("gl-mat4/fromQuat"),f=t("gl-mat4/invert"),h=t("./lib/quatFromFrame"),d=o.prototype;d.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},d.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;a(e,e);var r=this.computedMatrix;u(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;3>l;++l){for(var c=0,f=0;3>f;++f)c+=r[l+4*f]*i[f];r[12+l]=-c}},d.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r},d.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},d.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},d.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=a[1],s=a[5],l=a[9],c=n(o,s,l);o/=c,s/=c,l/=c;var u=a[0],f=a[4],h=a[8],d=u*o+f*s+h*l;u-=o*d,f-=s*d,h-=l*d;var p=n(u,f,h);u/=p,f/=p,h/=p;var g=a[2],v=a[6],m=a[10],y=g*o+v*s+m*l,b=g*u+v*f+m*h;g-=y*o+b*u,v-=y*s+b*f,m-=y*l+b*h;var x=n(g,v,m);g/=x,v/=x,m/=x;var _=u*e+o*r,w=f*e+s*r,k=h*e+l*r;this.center.move(t,_,w,k);var A=Math.exp(this.computedRadius[0]);A=Math.max(1e-4,A+i),this.radius.set(t,Math.log(A))},d.rotate=function(t,e,r,a){this.recalcMatrix(t),e=e||0,r=r||0;var o=this.computedMatrix,s=o[0],l=o[4],c=o[8],u=o[1],f=o[5],h=o[9],d=o[2],p=o[6],g=o[10],v=e*s+r*u,m=e*l+r*f,y=e*c+r*h,b=-(p*y-g*m),x=-(g*v-d*y),_=-(d*m-p*v),w=Math.sqrt(Math.max(0,1-Math.pow(b,2)-Math.pow(x,2)-Math.pow(_,2))),k=i(b,x,_,w);k>1e-6?(b/=k,x/=k,_/=k,w/=k):(b=x=_=0,w=1);var A=this.computedRotation,M=A[0],T=A[1],E=A[2],L=A[3],S=M*w+L*b+T*_-E*x,C=T*w+L*x+E*b-M*_,z=E*w+L*_+M*x-T*b,P=L*w-M*b-T*x-E*_;if(a){b=d,x=p,_=g;var R=Math.sin(a)/n(b,x,_);b*=R,x*=R,_*=R,w=Math.cos(e),S=S*w+P*b+C*_-z*x,C=C*w+P*x+z*b-S*_,z=z*w+P*_+S*x-C*b,P=P*w-S*b-C*x-z*_}var O=i(S,C,z,P);O>1e-6?(S/=O,C/=O,z/=O,P/=O):(S=C=z=0,P=1),this.rotation.set(t,S,C,z,P)},d.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;c(i,e,r,n);var o=this.computedRotation;h(o,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),a(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var s=0,l=0;3>l;++l)s+=Math.pow(r[l]-e[l],2);this.radius.set(t,.5*Math.log(Math.max(s,1e-6))),this.center.set(t,r[0],r[1],r[2])},d.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},d.setMatrix=function(t,e){var r=this.computedRotation;h(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),a(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;f(n,e);var i=n[15];if(Math.abs(i)>1e-6){var o=n[12]/i,s=n[13]/i,l=n[14]/i;this.recalcMatrix(t);var c=Math.exp(this.computedRadius[0]);this.center.set(t,o-n[2]*c,s-n[6]*c,l-n[10]*c),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},d.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},d.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},d.getDistanceLimits=function(t){var e=this.radius.bounds; -return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},d.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},d.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":36,"filtered-vector":20,"gl-mat4/fromQuat":134,"gl-mat4/invert":137,"gl-mat4/lookAt":138}],38:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t){return Math.min(1,Math.max(-1,t))}function a(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;3>s;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(var s=0;3>s;++s)i[s]-=o/a*t[s];return h(i,i),i}function o(t,e,r,n,i,a,o,s){this.center=l(r),this.up=l(n),this.right=l(i),this.radius=l([a]),this.angle=l([o,s]),this.angle.bounds=[[-(1/0),-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var c=0;16>c;++c)this.computedMatrix[c]=.5;this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.up||[0,1,0],i=t.right||a(r),s=t.radius||1,l=t.theta||0,c=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),h(r,r),i=[].slice.call(i,0,3),h(i,i),"eye"in t){var u=t.eye,p=[u[0]-e[0],u[1]-e[1],u[2]-e[2]];f(i,p,r),n(i[0],i[1],i[2])<1e-6?i=a(r):h(i,i),s=n(p[0],p[1],p[2]);var g=d(r,p)/s,v=d(i,p)/s;c=Math.acos(g),l=Math.acos(v)}return s=Math.log(s),new o(t.zoomMin,t.zoomMax,e,r,i,s,l,c)}e.exports=s;var l=t("filtered-vector"),c=t("gl-mat4/invert"),u=t("gl-mat4/rotate"),f=t("gl-vec3/cross"),h=t("gl-vec3/normalize"),d=t("gl-vec3/dot"),p=o.prototype;p.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},p.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},p.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,i=0,a=0,o=0;3>o;++o)a+=e[o]*r[o],i+=e[o]*e[o];for(var s=Math.sqrt(i),l=0,o=0;3>o;++o)r[o]-=e[o]*a/i,l+=r[o]*r[o],e[o]/=s;for(var c=Math.sqrt(l),o=0;3>o;++o)r[o]/=c;var u=this.computedToward;f(u,e,r),h(u,u);for(var d=Math.exp(this.computedRadius[0]),p=this.computedAngle[0],g=this.computedAngle[1],v=Math.cos(p),m=Math.sin(p),y=Math.cos(g),b=Math.sin(g),x=this.computedCenter,_=v*y,w=m*y,k=b,A=-v*b,M=-m*b,T=y,E=this.computedEye,L=this.computedMatrix,o=0;3>o;++o){var S=_*r[o]+w*u[o]+k*e[o];L[4*o+1]=A*r[o]+M*u[o]+T*e[o],L[4*o+2]=S,L[4*o+3]=0}var C=L[1],z=L[5],P=L[9],R=L[2],O=L[6],I=L[10],N=z*I-P*O,j=P*R-C*I,F=C*O-z*R,D=n(N,j,F);N/=D,j/=D,F/=D,L[0]=N,L[4]=j,L[8]=F;for(var o=0;3>o;++o)E[o]=x[o]+L[2+4*o]*d;for(var o=0;3>o;++o){for(var l=0,B=0;3>B;++B)l+=L[o+4*B]*E[B];L[12+o]=-l}L[15]=1},p.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r};var g=[0,0,0];p.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;g[0]=i[2],g[1]=i[6],g[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;3>l;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];u(i,i,n,g);for(var l=0;3>l;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},p.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=(Math.exp(this.computedRadius[0]),a[1]),s=a[5],l=a[9],c=n(o,s,l);o/=c,s/=c,l/=c;var u=a[0],f=a[4],h=a[8],d=u*o+f*s+h*l;u-=o*d,f-=s*d,h-=l*d;var p=n(u,f,h);u/=p,f/=p,h/=p;var g=u*e+o*r,v=f*e+s*r,m=h*e+l*r;this.center.move(t,g,v,m);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+i),this.radius.set(t,Math.log(y))},p.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},p.setMatrix=function(t,e,r,a){var o=1;"number"==typeof r&&(o=0|r),(0>o||o>3)&&(o=1);var s=(o+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var l=e[o],u=e[o+4],f=e[o+8];if(a){var h=Math.abs(l),d=Math.abs(u),p=Math.abs(f),g=Math.max(h,d,p);h===g?(l=0>l?-1:1,u=f=0):p===g?(f=0>f?-1:1,l=u=0):(u=0>u?-1:1,l=f=0)}else{var v=n(l,u,f);l/=v,u/=v,f/=v}var m=e[s],y=e[s+4],b=e[s+8],x=m*l+y*u+b*f;m-=l*x,y-=u*x,b-=f*x;var _=n(m,y,b);m/=_,y/=_,b/=_;var w=u*b-f*y,k=f*m-l*b,A=l*y-u*m,M=n(w,k,A);w/=M,k/=M,A/=M,this.center.jump(t,H,G,Y),this.radius.idle(t),this.up.jump(t,l,u,f),this.right.jump(t,m,y,b);var T,E;if(2===o){var L=e[1],S=e[5],C=e[9],z=L*m+S*y+C*b,P=L*w+S*k+C*A;T=0>N?-Math.PI/2:Math.PI/2,E=Math.atan2(P,z)}else{var R=e[2],O=e[6],I=e[10],N=R*l+O*u+I*f,j=R*m+O*y+I*b,F=R*w+O*k+I*A;T=Math.asin(i(N)),E=Math.atan2(F,j)}this.angle.jump(t,E,T),this.recalcMatrix(t);var D=e[2],B=e[6],U=e[10],V=this.computedMatrix;c(V,e);var q=V[15],H=V[12]/q,G=V[13]/q,Y=V[14]/q,X=Math.exp(this.computedRadius[0]);this.center.jump(t,H-D*X,G-B*X,Y-U*X)},p.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},p.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},p.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},p.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},p.lookAt=function(t,e,r,a){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter,a=a||this.computedUp;var o=a[0],s=a[1],l=a[2],c=n(o,s,l);if(!(1e-6>c)){o/=c,s/=c,l/=c;var u=e[0]-r[0],f=e[1]-r[1],h=e[2]-r[2],d=n(u,f,h);if(!(1e-6>d)){u/=d,f/=d,h/=d;var p=this.computedRight,g=p[0],v=p[1],m=p[2],y=o*g+s*v+l*m;g-=y*o,v-=y*s,m-=y*l;var b=n(g,v,m);if(!(.01>b&&(g=s*h-l*f,v=l*u-o*h,m=o*f-s*u,b=n(g,v,m),1e-6>b))){g/=b,v/=b,m/=b,this.up.set(t,o,s,l),this.right.set(t,g,v,m),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(d));var x=s*m-l*v,_=l*g-o*m,w=o*v-s*g,k=n(x,_,w);x/=k,_/=k,w/=k;var A=o*u+s*f+l*h,M=g*u+v*f+m*h,T=x*u+_*f+w*h,E=Math.asin(i(A)),L=Math.atan2(T,M),S=this.angle._state,C=S[S.length-1],z=S[S.length-2];C%=2*Math.PI;var P=Math.abs(C+2*Math.PI-L),R=Math.abs(C-L),O=Math.abs(C-2*Math.PI-L);R>P&&(C+=2*Math.PI),R>O&&(C-=2*Math.PI),this.angle.jump(this.angle.lastT(),C,z),this.angle.set(t,L,E)}}}}},{"filtered-vector":20,"gl-mat4/invert":137,"gl-mat4/rotate":141,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/normalize":27}],39:[function(t,e,r){"use strict";function n(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}function i(t){t=t||{};var e=t.eye||[0,0,1],r=t.center||[0,0,0],i=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],c=t.mode||"turntable",u=a(),f=o(),h=s();return u.setDistanceLimits(l[0],l[1]),u.lookAt(0,e,r,i),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,i),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,i),new n({turntable:u,orbit:f,matrix:h},c)}e.exports=i;var a=t("turntable-camera-controller"),o=t("orbit-camera-controller"),s=t("matrix-camera-controller"),l=n.prototype,c=[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]];c.forEach(function(t){for(var e=t[0],r=[],n=0;ne)){var r=this._active,n=this._controllerList[e],i=Math.max(r.lastT(),n.lastT());r.recalcMatrix(i),n.setMatrix(i,r.computedMatrix),this._active=n,this._mode=t,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}}},l.getMode=function(){return this._mode}},{"matrix-camera-controller":28,"orbit-camera-controller":37,"turntable-camera-controller":38}],40:[function(t,e,r){function n(t,e){return a(i(t,e))}e.exports=n;var i=t("alpha-complex"),a=t("simplicial-complex-boundary")},{"alpha-complex":41,"simplicial-complex-boundary":44}],41:[function(t,e,r){"use strict";function n(t,e){return i(e).filter(function(r){for(var n=new Array(r.length),i=0;ii;++i)r+=t[i]*e[i];return r}function i(t){var e=t.length;if(0===e)return[];var r=(t[0].length,o([t.length+1,t.length+1],1)),i=o([t.length+1],1);r[e][e]=0;for(var a=0;e>a;++a){for(var l=0;a>=l;++l)r[l][a]=r[a][l]=2*n(t[a],t[l]);i[a]=n(t[a],t[a])}for(var c=s(r,i),u=0,f=c[e+1],a=0;aa;++a){for(var f=c[a],d=0,l=0;ls;++s)r[s]+=t[a][s]*n[a];return r}var o=t("dup"),s=t("robust-linear-solve");a.barycenetric=i,e.exports=a},{dup:115,"robust-linear-solve":256}],44:[function(t,e,r){"use strict";function n(t){return a(i(t))}e.exports=n;var i=t("boundary-cells"),a=t("reduce-simplicial-complex")},{"boundary-cells":45,"reduce-simplicial-complex":48}],45:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r+=t[n].length;for(var i=new Array(r),a=0,n=0;e>n;++n)for(var o=t[n],s=o.length,l=0;s>l;++l)for(var c=i[a++]=new Array(s-1),u=1;s>u;++u)c[u-1]=o[(l+u)%s];return i}e.exports=n},{}],46:[function(t,e,r){"use strict";function n(t){for(var e=1,r=1;rn;++n)if(t[r]n;++n){var s=t[n],l=o(s);if(0!==l){if(r>0){var c=t[r-1];if(0===i(s,c)&&o(c)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}var i=t("compare-cell"),a=t("compare-oriented-cell"),o=t("cell-orientation");e.exports=n},{"cell-orientation":46,"compare-cell":101,"compare-oriented-cell":47}],49:[function(t,e,r){"use strict";var n=function(){function t(t){return!Array.isArray(t)&&null!==t&&"object"==typeof t}function e(t,e,r){for(var n=(e-t)/Math.max(r-1,1),i=[],a=0;r>a;a++)i.push(t+a*n);return i}function r(){for(var t=[].slice.call(arguments),e=t.map(function(t){return t.length}),r=Math.min.apply(null,e),n=[],i=0;r>i;i++){n[i]=[];for(var a=0;aa;a++)i.push([t[a],e[a],r[a]]);return i}function i(t){function e(t){for(var n=0;n>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3])),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}function c(t,e){var r,n;if("string"!=typeof t)return t;if(r=[],"#"===t[0]?(t=t.substr(1),3===t.length&&(t+=t),n=parseInt(t,16),r[0]=n>>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3]),n[4]?r[3]=parseFloat(n[4]):r[3]=1),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}var u={},f=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/,h=/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/;return u.isPlainObject=t,u.linspace=e,u.zip3=n,u.sum=i,u.zip=r,u.isEqual=s,u.copy2D=a,u.copy1D=o,u.str2RgbArray=l,u.str2RgbaArray=c,u};e.exports=n()},{}],50:[function(t,e,r){"use strict";"use restrict";function n(t){var e=32;return t&=-t,t&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}var i=32;r.INT_BITS=i,r.INT_MAX=2147483647,r.INT_MIN=-1<0)-(0>t)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(e>t)},r.max=function(t,e){return t^(t^e)&-(e>t)},r.isPow2=function(t){return!(t&t-1||!t)},r.log2=function(t){var e,r;return e=(t>65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var a=new Array(256);!function(t){for(var e=0;256>e;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|a[t>>>16&255]<<8|a[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],51:[function(t,e,r){(function(e){"use strict";function n(){try{var t=new Uint8Array(1);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t){return this instanceof a?(a.TYPED_ARRAY_SUPPORT||(this.length=0,this.parent=void 0),"number"==typeof t?o(this,t):"string"==typeof t?s(this,t,arguments.length>1?arguments[1]:"utf8"):l(this,t)):arguments.length>1?new a(t,arguments[1]):new a(t)}function o(t,e){if(t=g(t,0>e?0:0|v(e)),!a.TYPED_ARRAY_SUPPORT)for(var r=0;e>r;r++)t[r]=0;return t}function s(t,e,r){"string"==typeof r&&""!==r||(r="utf8");var n=0|y(e,r);return t=g(t,n),t.write(e,r),t}function l(t,e){if(a.isBuffer(e))return c(t,e);if(K(e))return u(t,e);if(null==e)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(e.buffer instanceof ArrayBuffer)return f(t,e);if(e instanceof ArrayBuffer)return h(t,e)}return e.length?d(t,e):p(t,e)}function c(t,e){var r=0|v(e.length);return t=g(t,r),e.copy(t,0,0,r),t}function u(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function f(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function h(t,e){return e.byteLength,a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):t=f(t,new Uint8Array(e)),t}function d(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function p(t,e){var r,n=0;"Buffer"===e.type&&K(e.data)&&(r=e.data,n=0|v(r.length)),t=g(t,n);for(var i=0;n>i;i+=1)t[i]=255&r[i];return t}function g(t,e){a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):t.length=e;var r=0!==e&&e<=a.poolSize>>>1;return r&&(t.parent=$),t}function v(t){if(t>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function m(t,e){if(!(this instanceof m))return new m(t,e);var r=new a(t,e);return delete r.parent,r}function y(t,e){"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"binary":case"raw":case"raws":return r;case"utf8":case"utf-8":return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(n)return q(t).length;e=(""+e).toLowerCase(),n=!0}}function b(t,e,r){var n=!1;if(e=0|e,r=void 0===r||r===1/0?this.length:0|r,t||(t="utf8"),0>e&&(e=0),r>this.length&&(r=this.length),e>=r)return"";for(;;)switch(t){case"hex":return z(this,e,r);case"utf8":case"utf-8":return E(this,e,r);case"ascii":return S(this,e,r);case"binary":return C(this,e,r);case"base64":return T(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function x(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var a=e.length;if(a%2!==0)throw new Error("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;n>o;o++){var s=parseInt(e.substr(2*o,2),16);if(isNaN(s))throw new Error("Invalid hex string");t[r+o]=s}return o}function _(t,e,r,n){return X(q(e,t.length-r),t,r,n)}function w(t,e,r,n){return X(H(e),t,r,n)}function k(t,e,r,n){return w(t,e,r,n)}function A(t,e,r,n){return X(Y(e),t,r,n)}function M(t,e,r,n){return X(G(e,t.length-r),t,r,n)}function T(t,e,r){return 0===e&&r===t.length?W.fromByteArray(t):W.fromByteArray(t.slice(e,r))}function E(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;r>i;){var a=t[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(r>=i+s){var l,c,u,f;switch(s){case 1:128>a&&(o=a);break;case 2:l=t[i+1],128===(192&l)&&(f=(31&a)<<6|63&l,f>127&&(o=f));break;case 3:l=t[i+1],c=t[i+2],128===(192&l)&&128===(192&c)&&(f=(15&a)<<12|(63&l)<<6|63&c,f>2047&&(55296>f||f>57343)&&(o=f));break;case 4:l=t[i+1],c=t[i+2],u=t[i+3],128===(192&l)&&128===(192&c)&&128===(192&u)&&(f=(15&a)<<18|(63&l)<<12|(63&c)<<6|63&u,f>65535&&1114112>f&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return L(n)}function L(t){var e=t.length;if(Q>=e)return String.fromCharCode.apply(String,t);for(var r="",n=0;e>n;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Q));return r}function S(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(127&t[i]);return n}function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function z(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",a=e;r>a;a++)i+=V(t[a]);return i}function P(t,e,r){for(var n=t.slice(e,r),i="",a=0;at)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!a.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(e>i||o>e)throw new RangeError("value is out of bounds");if(r+n>t.length)throw new RangeError("index out of range")}function I(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,a=Math.min(t.length-r,2);a>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function N(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,a=Math.min(t.length-r,4);a>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function j(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("index out of range");if(0>r)throw new RangeError("index out of range")}function F(t,e,r,n,i){return i||j(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,i){return i||j(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(t,e,r,n,52,8),r+8}function B(t){if(t=U(t).replace(J,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function U(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function V(t){return 16>t?"0"+t.toString(16):t.toString(16)}function q(t,e){e=e||1/0;for(var r,n=t.length,i=null,a=[],o=0;n>o;o++){if(r=t.charCodeAt(o),r>55295&&57344>r){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(56320>r){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,128>r){if((e-=1)<0)break;a.push(r)}else if(2048>r){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(65536>r){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(1114112>r))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(t){for(var e=[],r=0;r>8,i=r%256,a.push(i),a.push(n);return a}function Y(t){return W.toByteArray(B(t))}function X(t,e,r,n){for(var i=0;n>i&&!(i+r>=e.length||i>=t.length);i++)e[i+r]=t[i];return i}var W=t("base64-js"),Z=t("ieee754"),K=t("isarray");r.Buffer=a,r.SlowBuffer=m,r.INSPECT_MAX_BYTES=50,a.poolSize=8192;var $={};a.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),a._augment=function(t){return t.__proto__=a.prototype,t},a.TYPED_ARRAY_SUPPORT?(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})):(a.prototype.length=void 0,a.prototype.parent=void 0),a.isBuffer=function(t){return!(null==t||!t._isBuffer)},a.compare=function(t,e){if(!a.isBuffer(t)||!a.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,o=Math.min(r,n);o>i&&t[i]===e[i];)++i;return i!==o&&(r=t[i],n=e[i]),n>r?-1:r>n?1:0},a.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(t,e){if(!K(t))throw new TypeError("list argument must be an Array of Buffers.");if(0===t.length)return new a(0);var r;if(void 0===e)for(e=0,r=0;r0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},a.prototype.compare=function(t){if(!a.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?0:a.compare(this,t)},a.prototype.indexOf=function(t,e){function r(t,e,r){for(var n=-1,i=0;r+i2147483647?e=2147483647:-2147483648>e&&(e=-2147483648),e>>=0,0===this.length)return-1;if(e>=this.length)return-1;if(0>e&&(e=Math.max(this.length+e,0)),"string"==typeof t)return 0===t.length?-1:String.prototype.indexOf.call(this,t,e);if(a.isBuffer(t))return r(this,t,e);if("number"==typeof t)return a.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,e):r(this,[t],e);throw new TypeError("val must be string, number or Buffer")},a.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else if(isFinite(e))e=0|e,isFinite(r)?(r=0|r,void 0===n&&(n="utf8")):(n=r,r=void 0);else{var i=n;n=e,e=0|r,r=i}var a=this.length-e;if((void 0===r||r>a)&&(r=a),t.length>0&&(0>r||0>e)||e>this.length)throw new RangeError("attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return x(this,t,e,r);case"utf8":case"utf-8":return _(this,t,e,r);case"ascii":return w(this,t,e,r);case"binary":return k(this,t,e,r);case"base64":return A(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;a.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(t,e),n.__proto__=a.prototype;else{var i=e-t;n=new a(i,void 0);for(var o=0;i>o;o++)n[o]=this[o+t]}return n.length&&(n.parent=this.parent||this),n},a.prototype.readUIntLE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t],i=1,a=0;++a0&&(i*=256);)n+=this[t+--e]*i;return n},a.prototype.readUInt8=function(t,e){return e||R(t,1,this.length),this[t]},a.prototype.readUInt16LE=function(t,e){return e||R(t,2,this.length),this[t]|this[t+1]<<8},a.prototype.readUInt16BE=function(t,e){return e||R(t,2,this.length),this[t]<<8|this[t+1]},a.prototype.readUInt32LE=function(t,e){return e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},a.prototype.readUInt32BE=function(t,e){return e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},a.prototype.readIntLE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t],i=1,a=0;++a=i&&(n-=Math.pow(2,8*e)),n},a.prototype.readIntBE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*e)),a},a.prototype.readInt8=function(t,e){return e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},a.prototype.readInt16LE=function(t,e){e||R(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(t,e){e||R(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(t,e){return e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},a.prototype.readInt32BE=function(t,e){return e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},a.prototype.readFloatLE=function(t,e){return e||R(t,4,this.length),Z.read(this,t,!0,23,4)},a.prototype.readFloatBE=function(t,e){return e||R(t,4,this.length),Z.read(this,t,!1,23,4)},a.prototype.readDoubleLE=function(t,e){return e||R(t,8,this.length),Z.read(this,t,!0,52,8)},a.prototype.readDoubleBE=function(t,e){return e||R(t,8,this.length),Z.read(this,t,!1,52,8)},a.prototype.writeUIntLE=function(t,e,r,n){t=+t,e=0|e,r=0|r,n||O(this,t,e,r,Math.pow(2,8*r),0);var i=1,a=0;for(this[e]=255&t;++a=0&&(a*=256);)this[e+i]=t/a&255;return e+r},a.prototype.writeUInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,255,0),a.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},a.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},a.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},a.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):N(this,t,e,!0),e+4},a.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},a.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=0,o=1,s=0>t?1:0;for(this[e]=255&t;++a>0)-s&255;return e+r},a.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0>t?1:0;for(this[e+a]=255&t;--a>=0&&(o*=256);)this[e+a]=(t/o>>0)-s&255;return e+r},a.prototype.writeInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,127,-128),a.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=255&t,e+1},a.prototype.writeInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},a.prototype.writeInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},a.prototype.writeInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):N(this,t,e,!0),e+4},a.prototype.writeInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},a.prototype.writeFloatLE=function(t,e,r){return F(this,t,e,!0,r)},a.prototype.writeFloatBE=function(t,e,r){return F(this,t,e,!1,r)},a.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},a.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},a.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(0>e)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length), -t.length-er&&n>e)for(i=o-1;i>=0;i--)t[i+e]=this[i+r];else if(1e3>o||!a.TYPED_ARRAY_SUPPORT)for(i=0;o>i;i++)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+o),e);return o},a.prototype.fill=function(t,e,r){if(t||(t=0),e||(e=0),r||(r=this.length),e>r)throw new RangeError("end < start");if(r!==e&&0!==this.length){if(0>e||e>=this.length)throw new RangeError("start out of bounds");if(0>r||r>this.length)throw new RangeError("end out of bounds");var n;if("number"==typeof t)for(n=e;r>n;n++)this[n]=t;else{var i=q(t.toString()),a=i.length;for(n=e;r>n;n++)this[n]=i[n%a]}return this}};var J=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":52,ieee754:53,isarray:54}],52:[function(t,e,r){"use strict";function n(){var t,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=e.length;for(t=0;r>t;t++)l[t]=e[t];for(t=0;r>t;++t)c[e.charCodeAt(t)]=t;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63}function i(t){var e,r,n,i,a,o,s=t.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===t[s-2]?2:"="===t[s-1]?1:0,o=new u(3*s/4-a),n=a>0?s-4:s;var l=0;for(e=0,r=0;n>e;e+=4,r+=3)i=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],o[l++]=(16711680&i)>>16,o[l++]=(65280&i)>>8,o[l++]=255&i;return 2===a?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,o[l++]=255&i):1===a&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,o[l++]=i>>8&255,o[l++]=255&i),o}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function o(t,e,r){for(var n,i=[],o=e;r>o;o+=3)n=(t[o]<<16)+(t[o+1]<<8)+t[o+2],i.push(a(n));return i.join("")}function s(t){for(var e,r=t.length,n=r%3,i="",a=[],s=16383,c=0,u=r-n;u>c;c+=s)a.push(o(t,c,c+s>u?u:c+s));return 1===n?(e=t[r-1],i+=l[e>>2],i+=l[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=l[e>>10],i+=l[e>>4&63],i+=l[e<<2&63],i+="="),a.push(i),a.join("")}r.toByteArray=i,r.fromByteArray=s;var l=[],c=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],53:[function(t,e,r){r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,u=-7,f=r?i-1:0,h=r?-1:1,d=t[e+f];for(f+=h,a=d&(1<<-u)-1,d>>=-u,u+=s;u>0;a=256*a+t[e+f],f+=h,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=n;u>0;o=256*o+t[e+f],f+=h,u-=8);if(0===a)a=1-c;else{if(a===l)return o?NaN:(d?-1:1)*(1/0);o+=Math.pow(2,n),a-=c}return(d?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,c=8*a-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:a-1,p=n?1:-1,g=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),e+=o+f>=1?h/l:h*Math.pow(2,1-f),e*l>=2&&(o++,l/=2),o+f>=u?(s=0,o=u):o+f>=1?(s=(e*l-1)*Math.pow(2,i),o+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&s,d+=p,s/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,c-=8);t[r+d-p]|=128*g}},{}],54:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],55:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!a(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,a,l,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(o(r))for(a=Array.prototype.slice.call(arguments,1),c=r.slice(),n=c.length,l=0;n>l;l++)c[l].apply(this,a);return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(r=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],56:[function(t,e,r){function n(){u=!1,s.length?c=s.concat(c):f=-1,c.length&&i()}function i(){if(!u){var t=setTimeout(n);u=!0;for(var e=c.length;e;){for(s=c,c=[];++f1)for(var r=1;rs)){if(n>i){var l=n;n=i,i=l,l=o,o=s,s=l}e.isConstraint(n,i)||a(t[n],t[i],t[o],t[s])<0&&r.push(n,i)}}function i(t,e){for(var r=[],i=t.length,o=e.stars,s=0;i>s;++s)for(var l=o[s],c=1;cu||e.isConstraint(s,u))){for(var f=l[c-1],h=-1,d=1;dh||a(t[s],t[u],t[f],t[h])<0&&r.push(s,u)}}for(;r.length>0;){for(var u=r.pop(),s=r.pop(),f=-1,h=-1,l=o[s],p=1;pf||0>h||a(t[s],t[u],t[f],t[h])>=0||(e.flip(s,u),n(t,e,r,f,s,h),n(t,e,r,s,h,f),n(t,e,r,h,u,f),n(t,e,r,u,f,h))}}var a=t("robust-in-sphere")[4];t("binary-search-bounds");e.exports=i},{"binary-search-bounds":62,"robust-in-sphere":63}],59:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function i(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}function a(t,e){for(var r=t.cells(),a=r.length,o=0;a>o;++o){var s=r[o],l=s[0],c=s[1],u=s[2];u>c?l>c&&(s[0]=c,s[1]=u,s[2]=l):l>u&&(s[0]=u,s[1]=l,s[2]=c)}r.sort(i);for(var f=new Array(a),o=0;oo;++o)for(var s=r[o],y=0;3>y;++y){var l=s[y],c=s[(y+1)%3],b=p[3*o+y]=m.locate(c,l,t.opposite(c,l)),x=g[3*o+y]=t.isConstraint(l,c);0>b&&(x?d.push(o):(h.push(o),f[o]=1),e&&v.push([c,l,-1]))}return m}function o(t,e,r){for(var n=0,i=0;i0||l.length>0;){for(;s.length>0;){var d=s.pop();if(c[d]!==-i){c[d]=i;for(var p=(u[d],0);3>p;++p){var g=h[3*d+p];g>=0&&0===c[g]&&(f[3*d+p]?l.push(g):(s.push(g),c[g]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var m=o(u,c,e);return r?m.concat(n.boundary):m}var l=t("binary-search-bounds");e.exports=s;var c=n.prototype;c.locate=function(){var t=[0,0,0];return function(e,r,n){var a=e,o=r,s=n;return n>r?e>r&&(a=r,o=n,s=e):e>n&&(a=n,o=e,s=r),0>a?-1:(t[0]=a,t[1]=o,t[2]=s,l.eq(this.cells,t,i))}}()},{"binary-search-bounds":62}],60:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.a=t,this.b=e,this.idx=r,this.lowerIds=n,this.upperIds=i}function i(t,e,r,n){this.a=t,this.b=e,this.type=r,this.idx=n}function a(t,e){var r=t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.type-e.type;return r?r:t.type!==p&&(r=d(t.a,t.b,e.b))?r:t.idx-e.idx}function o(t,e){return d(t.a,t.b,e)}function s(t,e,r,n,i){for(var a=h.lt(e,n,o),s=h.gt(e,n,o),l=a;s>l;++l){for(var c=e[l],u=c.lowerIds,f=u.length;f>1&&d(r[u[f-2]],r[u[f-1]],n)>0;)t.push([u[f-1],u[f-2],i]),f-=1;u.length=f,u.push(i);for(var p=c.upperIds,f=p.length;f>1&&d(r[p[f-2]],r[p[f-1]],n)<0;)t.push([p[f-2],p[f-1],i]),f-=1;p.length=f,p.push(i)}}function l(t,e){var r;return(r=t.a[0]f;++f)l.push(new i(t[f],null,p,f));for(var f=0;o>f;++f){var h=e[f],d=t[h[0]],m=t[h[1]];d[0]m[0]&&l.push(new i(m,d,v,f),new i(d,m,g,f))}l.sort(a);for(var y=l[0].a[0]-(1+Math.abs(l[0].a[0]))*Math.pow(2,-52),b=[new n([y,1],[y,0],-1,[],[],[],[])],x=[],f=0,_=l.length;_>f;++f){var w=l[f],k=w.type;k===p?s(x,b,t,w.a,w.idx):k===v?c(b,t,w):u(b,t,w)}return x}var h=t("binary-search-bounds"),d=t("robust-orientation")[3],p=0,g=1,v=2;e.exports=f},{"binary-search-bounds":62,"robust-orientation":259}],61:[function(t,e,r){"use strict";function n(t,e){this.stars=t,this.edges=e}function i(t,e,r){for(var n=1,i=t.length;i>n;n+=2)if(t[n-1]===e&&t[n]===r)return t[n-1]=t[i-2],t[n]=t[i-1],void(t.length=i-2)}function a(t,e){for(var r=new Array(t),i=0;t>i;++i)r[i]=[];return new n(r,e)}var o=t("binary-search-bounds");e.exports=a;var s=n.prototype;s.isConstraint=function(){function t(t,e){return t[0]-e[0]||t[1]-e[1]}var e=[0,0];return function(r,n){return e[0]=Math.min(r,n),e[1]=Math.max(r,n),o.eq(this.edges,e,t)>=0}}(),s.removeTriangle=function(t,e,r){var n=this.stars;i(n[t],e,r),i(n[e],r,t),i(n[r],t,e)},s.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},s.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;i>n;n+=2)if(r[n]===t)return r[n-1];return-1},s.flip=function(t,e){var r=this.opposite(t,e),n=this.opposite(e,t);this.removeTriangle(t,e,r),this.removeTriangle(e,t,n),this.addTriangle(t,n,r),this.addTriangle(e,r,n)},s.edges=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2)e.push([i[a],i[a+1]]);return e},s.cells=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2){var s=i[a],l=i[a+1];r>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],63:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-2,"]"].join("")}return e}function a(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",a(t.slice(0,e)),",",a(t.slice(e)),")"].join("")}function o(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return o(e,t)}function s(t){return t&!0?"-":""}function l(t){if(2===t.length)return[["diff(",o(t[0][0],t[1][1]),",",o(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;rn;++n)r.push(["prod(m",t,"[",n,"],m",t,"[",n,"])"].join(""));return a(r)}function u(t){for(var e=[],r=[],o=i(t),s=0;t>s;++s)o[0][s]="1",o[t-1][s]="w"+s;for(var s=0;t>s;++s)0===(1&s)?e.push.apply(e,l(n(o,s))):r.push.apply(r,l(n(o,s)));for(var u=a(e),f=a(r),h="exactInSphere"+t,d=[],s=0;t>s;++s)d.push("m"+s);for(var p=["function ",h,"(",d.join(),"){"],s=0;t>s;++s){p.push("var w",s,"=",c(s,t),";");for(var g=0;t>g;++g)g!==s&&p.push("var w",s,"m",g,"=scale(w",s,",m",g,"[0]);")}p.push("var p=",u,",n=",f,",d=diff(p,n);return d[d.length-1];}return ",h);var x=new Function("sum","diff","prod","scale",p.join(""));return x(m,y,v,b)}function f(){return 0}function h(){return 0}function d(){return 0}function p(t){var e=_[t.length];return e||(e=_[t.length]=u(t.length)),e.apply(void 0,t)}function g(){for(;_.length<=x;)_.push(u(_.length));for(var t=[],r=["slow"],n=0;x>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function testInSphere(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;x>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var v=t("two-product"),m=t("robust-sum"),y=t("robust-subtract"),b=t("robust-scale"),x=6,_=[f,h,d];g()},{"robust-scale":260,"robust-subtract":261,"robust-sum":262,"two-product":276}],64:[function(t,e,r){"use strict";function n(t){var e=x(t),r=b(y(e),t);return 0>r?[e,w(e,1/0)]:r>0?[w(e,-(1/0)),e]:[e,e]}function i(t,e){for(var r=new Array(e.length),n=0;n=t.length)return o[e-t.length];var r=t[e];return[y(r[0]),y(r[1])]}for(var o=[],s=0;s=0;--s){var g=n[s],c=g[0],v=e[c],m=v[0],x=v[1],w=t[m],A=t[x];if((w[0]-A[0]||w[1]-A[1])<0){var M=m;m=x,x=M}v[0]=m;var T,E=v[1]=g[1];for(i&&(T=v[2]);s>0&&n[s-1][0]===c;){var g=n[--s],L=g[1];i?e.push([E,L,T]):e.push([E,L]),E=L}i?e.push([E,x,T]):e.push([E,x])}return o}function c(t,e,r){for(var i=t.length+e.length,a=new g(i),o=r,s=0;ss;++s){var p=a.find(s);p===s?(d[s]=f,t[f++]=t[s]):(h=!1,d[s]=-1)}if(t.length=f,h)return null;for(var s=0;i>s;++s)d[s]<0&&(d[s]=d[a.find(s)]);return d}function u(t,e){return t[0]-e[0]||t[1]-e[1]}function f(t,e){var r=t[0]-e[0]||t[1]-e[1];return r?r:t[2]e[2]?1:0}function h(t,e,r){if(0!==t.length){if(e)for(var n=0;n0||d.length>0}function p(t,e,r){var n,i=!1;if(r){n=e;for(var a=new Array(e.length),o=0;o0?r=r.shln(f):0>f&&(u=u.shln(-f)),l(r,u)}var i=t("./is-rat"),a=t("./lib/is-bn"),o=t("./lib/num-to-bn"),s=t("./lib/str-to-bn"),l=t("./lib/rationalize"),c=t("./div");e.exports=n},{"./div":68,"./is-rat":70,"./lib/is-bn":74,"./lib/num-to-bn":75,"./lib/rationalize":76,"./lib/str-to-bn":77}],70:[function(t,e,r){"use strict";function n(t){return Array.isArray(t)&&2===t.length&&i(t[0])&&i(t[1])}var i=t("./lib/is-bn");e.exports=n},{"./lib/is-bn":74}],71:[function(t,e,r){"use strict";function n(t){return t.cmp(new i(0))}var i=t("bn.js");e.exports=n},{"bn.js":79}],72:[function(t,e,r){"use strict";function n(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var n=0,i=0;e>i;i++){var a=r[i];n+=a*Math.pow(67108864,i)}return t.sign?-n:n}e.exports=n},{}],73:[function(t,e,r){"use strict";function n(t){var e=a(i.lo(t));if(32>e)return e;var r=a(i.hi(t));return r>20?52:r+32}var i=t("double-bits"),a=t("bit-twiddle").countTrailingZeros;e.exports=n},{"bit-twiddle":50,"double-bits":90}],74:[function(t,e,r){"use strict";function n(t){return t&&"object"==typeof t&&Boolean(t.words)}t("bn.js");e.exports=n},{"bn.js":79}],75:[function(t,e,r){"use strict";function n(t){var e=a.exponent(t);return 52>e?new i(t):new i(t*Math.pow(2,52-e)).shln(e-52)}var i=t("bn.js"),a=t("double-bits");e.exports=n},{"bn.js":79,"double-bits":90}],76:[function(t,e,r){"use strict";function n(t,e){var r=a(t),n=a(e);if(0===r)return[i(0),i(1)];if(0===n)return[i(0),i(0)];0>n&&(t=t.neg(),e=e.neg());var o=t.gcd(e);return o.cmpn(1)?[t.div(o),e.div(o)]:[t,e]}var i=t("./num-to-bn"),a=t("./bn-sign");e.exports=n},{"./bn-sign":71,"./num-to-bn":75}],77:[function(t,e,r){"use strict";function n(t){return new i(t)}var i=t("bn.js");e.exports=n},{"bn.js":79}],78:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[0]),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":76}],79:[function(t,e,r){!function(t,e){"use strict";function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){return null!==t&&"object"==typeof t&&Array.isArray(t.words)?t:(this.sign=!1,this.words=null,this.length=0,this.red=null,"le"!==e&&"be"!==e||(r=e,e=10),void(null!==t&&this._init(t||0,e||10,r||"be")))}function a(t,e,r){for(var n=0,i=Math.min(t.length,r),a=e;i>a;a++){var o=t.charCodeAt(a)-48;n<<=4,n|=o>=49&&54>=o?o-49+10:o>=17&&22>=o?o-17+10:15&o}return n}function o(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;a>o;o++){var s=t.charCodeAt(o)-48;i*=n,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}function s(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).ishln(this.n).isub(this.p),this.tmp=this._tmp()}function l(){s.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function c(){s.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function u(){s.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function f(){s.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function h(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else this.m=t,this.prime=null}function d(t){h.call(this,t),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).ishln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv.sign=!0,this.minv=this.minv.mod(this.r)}"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26,i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&36>=e),t=t.toString().replace(/\s+/g,"");var i=0;"-"===t[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.sign=!0),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){0>t&&(this.sign=!0,t=-t),67108864>t?(this.words=[67108863&t],this.length=1):4503599627370496>t?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(9007199254740992>t),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3){var s=t[i]|t[i-1]<<8|t[i-2]<<16;this.words[o]|=s<>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}else if("le"===n)for(var i=0,o=0;i>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6){var o=a(t,r,r+6);this.words[i]|=o<>>26-n&4194303,n+=24,n>=26&&(n-=26,i++)}if(r+6!==e){var o=a(t,e,r+6);this.words[i]|=o<>>26-n&4194303}this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;67108863>=i;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,s=a%n,l=Math.min(a,a-s)+r,c=0,u=r;l>u;u+=n)c=o(t,u,u+n,e),this.imuln(i),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==s){for(var f=1,c=o(t,u,t.length,e),u=0;s>u;u++)f*=e;this.imuln(f),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}},i.prototype.copy=function(t){t.words=new Array(this.length);for(var e=0;e1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.sign=!1),this},i.prototype.inspect=function(){return(this.red?""};var p=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],v=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(t,e){if(t=t||10,16===t||"hex"===t){for(var n="",i=0,e=0|e||1,a=0,o=0;o>>24-i&16777215,n=0!==a||o!==this.length-1?p[6-l.length]+l+n:l+n,i+=2,i>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!==0;)n="0"+n;return this.sign&&(n="-"+n),n}if(t===(0|t)&&t>=2&&36>=t){var c=g[t],u=v[t],n="",f=this.clone();for(f.sign=!1;0!==f.cmpn(0);){var h=f.modn(u).toString(t);f=f.idivn(u),n=0!==f.cmpn(0)?p[c-h.length]+h+n:h+n}return 0===this.cmpn(0)&&(n="0"+n),this.sign&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toArray=function(t){this.strip();var e=new Array(this.byteLength());e[0]=0;var r=this.clone();if("le"!==t)for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[e.length-n-1]=i}else for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[n]=i}return e},Math.clz32?i.prototype._countBits=function(t){return 32-Math.clz32(t)}:i.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0===(8191&e)&&(r+=13,e>>>=13),0===(127&e)&&(r+=7,e>>>=7),0===(15&e)&&(r+=4,e>>>=4),0===(3&e)&&(r+=2,e>>>=2),0===(1&e)&&r++,r},i.prototype.bitLength=function(){var t=0,e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(0===this.cmpn(0))return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.iand=function(t){this.sign=this.sign&&t.sign;var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.ixor=function(t){this.sign=this.sign||t.sign;var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);for(var n=t/26|0,i=t%26;this.length<=n;)this.words[this.length++]=0;return e?this.words[n]=this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26}for(;0!==i&&a>>26}if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(t.sign){t.sign=!1;var e=this.iadd(t);return t.sign=!0,e._normSign()}if(this.sign)return this.sign=!1,this.iadd(t),this.sign=!0,this._normSign();var r=this.cmp(t);if(0===r)return this.sign=!1,this.length=1,this.words[0]=0,this;var n,i;r>0?(n=this,i=t):(n=t,i=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e}for(;0!==a&&o>26,this.words[o]=67108863&e}if(0===a&&o>>26,a=67108863&r,o=Math.min(n,t.length-1),s=Math.max(0,n-this.length+1);o>=s;s++){var l=n-s,c=0|this.words[l],u=0|t.words[s],f=c*u,h=67108863&f;i=i+(f/67108864|0)|0,h=h+a|0,a=67108863&h,i=i+(h>>>26)|0}e.words[n]=a,r=i}return 0!==r?e.words[n]=r:e.length--,e.strip()},i.prototype._bigMulTo=function(t,e){e.sign=t.sign!==this.sign,e.length=this.length+t.length;for(var r=0,n=0,i=0;i=l;l++){var c=i-l,u=0|this.words[c],f=0|t.words[l],h=u*f,d=67108863&h;a=a+(h/67108864|0)|0,d=d+o|0,o=67108863&d,a=a+(d>>>26)|0,n+=a>>>26,a&=67108863}e.words[i]=o,r=a,a=n}return 0!==r?e.words[i]=r:e.length--,e.strip()},i.prototype.mulTo=function(t,e){var r;return r=this.length+t.length<63?this._smallMulTo(t,e):this._bigMulTo(t,e)},i.prototype.mul=function(t){var e=new i(null);return e.words=new Array(this.length+t.length),this.mulTo(t,e)},i.prototype.imul=function(t){if(0===this.cmpn(0)||0===t.cmpn(0))return this.words[0]=0,this.length=1,this;var e=this.length,r=t.length;this.sign=t.sign!==this.sign,this.length=this.length+t.length,this.words[this.length-1]=0;for(var n=this.length-2;n>=0;n--){for(var i=0,a=0,o=Math.min(n,r-1),s=Math.max(0,n-e+1);o>=s;s++){var l=n-s,c=this.words[l],u=t.words[s],f=c*u,h=67108863&f;i+=f/67108864|0,h+=a,a=67108863&h,i+=h>>>26}this.words[n]=a,this.words[n+1]+=i,i=0}for(var i=0,l=1;l>>26}return this.strip()},i.prototype.imuln=function(t){r("number"==typeof t);for(var e=0,n=0;n>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.mul(this)},i.prototype.ishln=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=67108863>>>26-e<<26-e;if(0!==e){for(var a=0,o=0;o>>26-e}a&&(this.words[o]=a,this.length++)}if(0!==n){for(var o=this.length-1;o>=0;o--)this.words[o+n]=this.words[o];for(var o=0;n>o;o++)this.words[o]=0;this.length+=n}return this.strip()},i.prototype.ishrn=function(t,e,n){r("number"==typeof t&&t>=0);var i;i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<c;c++)l.words[c]=this.words[c];l.length=o}if(0===o);else if(this.length>o){this.length-=o;for(var c=0;c=0&&(0!==u||c>=i);c--){var f=this.words[c];this.words[c]=u<<26-a|f>>>a,u=f&s}return l&&0!==u&&(l.words[l.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip(),this},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(!this.sign,"imaskn works only with positive numbers"),0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<t?this.isubn(-t):this.sign?1===this.length&&this.words[0]=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),0>t)return this.iaddn(-t);if(this.sign)return this.sign=!1,this.iaddn(t),this.sign=!0,this;this.words[0]-=t;for(var e=0;e>26)-(c/67108864|0),this.words[i+n]=67108863&l}for(;i>26,this.words[i+n]=67108863&l}if(0===s)return this.strip();r(-1===s),s=0;for(var i=0;i>26,this.words[i]=67108863&l}return this.sign=!0,this.strip()},i.prototype._wordDiv=function(t,e){var r=this.length-t.length,n=this.clone(),a=t,o=a.words[a.length-1],s=this._countBits(o);r=26-s,0!==r&&(a=a.shln(r),n.ishln(r),o=a.words[a.length-1]);var l,c=n.length-a.length;if("mod"!==e){l=new i(null),l.length=c+1,l.words=new Array(l.length);for(var u=0;u=0;h--){var d=67108864*n.words[a.length+h]+n.words[a.length+h-1];for(d=Math.min(d/o|0,67108863),n._ishlnsubmul(a,d,h);n.sign;)d--,n.sign=!1,n._ishlnsubmul(a,1,h),0!==n.cmpn(0)&&(n.sign=!n.sign);l&&(l.words[h]=d)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.ishrn(r),{div:l?l:null,mod:n}},i.prototype.divmod=function(t,e){if(r(0!==t.cmpn(0)),this.sign&&!t.sign){var n,a,o=this.neg().divmod(t,e);return"mod"!==e&&(n=o.div.neg()),"div"!==e&&(a=0===o.mod.cmpn(0)?o.mod:t.sub(o.mod)),{div:n,mod:a}}if(!this.sign&&t.sign){var n,o=this.divmod(t.neg(),e);return"mod"!==e&&(n=o.div.neg()),{div:n,mod:o.mod}}return this.sign&&t.sign?this.neg().divmod(t.neg(),e):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e)},i.prototype.div=function(t){return this.divmod(t,"div").div},i.prototype.mod=function(t){return this.divmod(t,"mod").mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(0===e.mod.cmpn(0))return e.div;var r=e.div.sign?e.mod.isub(t):e.mod,n=t.shrn(1),i=t.andln(1),a=r.cmp(n);return 0>a||1===i&&0===a?e.div:e.div.sign?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(67108863>=t);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+this.words[i])%t;return n},i.prototype.idivn=function(t){r(67108863>=t);for(var e=0,n=this.length-1;n>=0;n--){var i=this.words[n]+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),c=0;e.isEven()&&n.isEven();)e.ishrn(1),n.ishrn(1),++c;for(var u=n.clone(),f=e.clone();0!==e.cmpn(0);){for(;e.isEven();)e.ishrn(1),a.isEven()&&o.isEven()?(a.ishrn(1),o.ishrn(1)):(a.iadd(u).ishrn(1),o.isub(f).ishrn(1));for(;n.isEven();)n.ishrn(1),s.isEven()&&l.isEven()?(s.ishrn(1),l.ishrn(1)):(s.iadd(u).ishrn(1),l.isub(f).ishrn(1));e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.ishln(c)}},i.prototype._invmp=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(;e.isEven();)e.ishrn(1),a.isEven()?a.ishrn(1):a.iadd(s).ishrn(1);for(;n.isEven();)n.ishrn(1),o.isEven()?o.ishrn(1):o.iadd(s).ishrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(o)):(n.isub(e),o.isub(a))}return 0===e.cmpn(1)?a:o},i.prototype.gcd=function(t){if(0===this.cmpn(0))return t.clone();if(0===t.cmpn(0))return this.clone();var e=this.clone(),r=t.clone();e.sign=!1,r.sign=!1;for(var n=0;e.isEven()&&r.isEven();n++)e.ishrn(1),r.ishrn(1);for(;;){for(;e.isEven();)e.ishrn(1);for(;r.isEven();)r.ishrn(1);var i=e.cmp(r);if(0>i){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.ishln(n)},i.prototype.invm=function(t){return this.egcd(t).a.mod(t)},i.prototype.isEven=function(){return 0===(1&this.words[0])},i.prototype.isOdd=function(){return 1===(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<a;a++)this.words[a]=0;return this.words[n]|=i,this.length=n+1,this}for(var o=i,a=n;0!==o&&a>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},i.prototype.cmpn=function(t){var e=0>t;if(e&&(t=-t),this.sign&&!e)return-1;if(!this.sign&&e)return 1;t&=67108863,this.strip();var r;if(this.length>1)r=1;else{var n=this.words[0];r=n===t?0:t>n?-1:1}return this.sign&&(r=-r),r},i.prototype.cmp=function(t){if(this.sign&&!t.sign)return-1;if(!this.sign&&t.sign)return 1;var e=this.ucmp(t);return this.sign?-e:e},i.prototype.ucmp=function(t){if(this.length>t.length)return 1;if(this.length=0;r--){var n=this.words[r],i=t.words[r];if(n!==i){i>n?e=-1:n>i&&(e=1);break}}return e},i.red=function(t){return new h(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(!this.sign,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};s.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},s.prototype.ireduce=function(t){var e,r=t;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength();while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},s.prototype.split=function(t,e){t.ishrn(this.n,0,e)},s.prototype.imulK=function(t){return t.imul(this.k)},n(l,s),l.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;n>i;i++)e.words[i]=t.words[i];if(e.length=n,t.length<=9)return t.words[0]=0,void(t.length=1);var a=t.words[9];e.words[e.length++]=a&r;for(var i=10;i>>22,a=o}t.words[i-10]=a>>>22,t.length-=9},l.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e,r=0,n=0;n>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function y(t){if(m[t])return m[t];var y;if("k256"===t)y=new l;else if("p224"===t)y=new c;else if("p192"===t)y=new u;else{if("p25519"!==t)throw new Error("Unknown prime "+t);y=new f}return m[t]=y,y},h.prototype._verify1=function(t){r(!t.sign,"red works only with positives"),r(t.red,"red works only with red numbers")},h.prototype._verify2=function(t,e){r(!t.sign&&!e.sign,"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},h.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.mod(this.m)._forceRed(this)},h.prototype.neg=function(t){var e=t.clone();return e.sign=!e.sign,e.iadd(this.m)._forceRed(this)},h.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},h.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},h.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},h.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},h.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.shln(e))},h.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},h.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},h.prototype.isqr=function(t){return this.imul(t,t)},h.prototype.sqr=function(t){return this.mul(t,t)},h.prototype.sqrt=function(t){if(0===t.cmpn(0))return t.clone();var e=this.m.andln(3);if(r(e%2===1),3===e){var n=this.m.add(new i(1)).ishrn(2),a=this.pow(t,n);return a}for(var o=this.m.subn(1),s=0;0!==o.cmpn(0)&&0===o.andln(1);)s++,o.ishrn(1);r(0!==o.cmpn(0));var l=new i(1).toRed(this),c=l.redNeg(),u=this.m.subn(1).ishrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,u).cmp(c);)f.redIAdd(c);for(var h=this.pow(f,o),a=this.pow(t,o.addn(1).ishrn(1)),d=this.pow(t,o),p=s;0!==d.cmp(l);){for(var g=d,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(p>v);var m=this.pow(h,new i(1).ishln(p-v-1));a=a.redMul(m),h=m.redSqr(),d=d.redMul(h),p=v}return a},h.prototype.invm=function(t){var e=t._invmp(this.m);return e.sign?(e.sign=!1,this.imod(e).redNeg()):this.imod(e)},h.prototype.pow=function(t,e){var r=[];if(0===e.cmpn(0))return new i(1);for(var n=e.clone();0!==n.cmpn(0);)r.push(n.andln(1)),n.ishrn(1);for(var a=t,o=0;o=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},d.prototype.mul=function(t,e){if(0===t.cmpn(0)||0===e.cmpn(0))return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).ishrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},d.prototype.invm=function(t){var e=this.imod(t._invmp(this.m).mul(this.r2));return e._forceRed(this)}}("undefined"==typeof e||e,this)},{}],80:[function(t,e,r){"use strict";function n(t){return i(t[0])*i(t[1])}var i=t("./lib/bn-sign");e.exports=n},{"./lib/bn-sign":71}],81:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":76}],82:[function(t,e,r){"use strict";function n(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.divmod(r),o=n.div,s=i(o),l=n.mod;if(0===l.cmpn(0))return s;if(s){var c=a(s)+4,u=i(l.shln(c).divRound(r));return 0>s&&(u=-u),s+u*Math.pow(2,-c)}var f=r.bitLength()-l.bitLength()+53,u=i(l.shln(f).divRound(r));return 1023>f?u*Math.pow(2,-f):(u*=Math.pow(2,-1023),u*Math.pow(2,1023-f))}var i=t("./lib/bn-to-num"),a=t("./lib/ctz");e.exports=n},{"./lib/bn-to-num":72,"./lib/ctz":73}],83:[function(t,e,r){"use strict";function n(t,e){for(var r=0;t>r;++r)if(!(e[r]<=e[r+t]))return!0;return!1}function i(t,e,r,i){for(var a=0,o=0,s=0,l=t.length;l>s;++s){var c=t[s];if(!n(e,c)){for(var u=0;2*e>u;++u)r[a++]=c[u];i[o++]=s}}return o}function a(t,e,r,n){var a=t.length,o=e.length;if(!(0>=a||0>=o)){var s=t[0].length>>>1;if(!(0>=s)){var l,c=f.mallocDouble(2*s*a),u=f.mallocInt32(a);if(a=i(t,s,c,u),a>0){if(1===s&&n)h.init(a),l=h.sweepComplete(s,r,0,a,c,u,0,a,c,u);else{var p=f.mallocDouble(2*s*o),g=f.mallocInt32(o);o=i(e,s,p,g),o>0&&(h.init(a+o),l=1===s?h.sweepBipartite(s,r,0,a,c,u,0,o,p,g):d(s,r,n,a,c,u,o,p,g),f.free(p),f.free(g))}f.free(c),f.free(u)}return l}}}function o(t,e){u.push([t,e])}function s(t){return u=[],a(t,t,o,!0),u}function l(t,e){return u=[],a(t,e,o,!1),u}function c(t,e,r){switch(arguments.length){case 1:return s(t);case 2:return"function"==typeof e?a(t,t,e,!0):l(t,e);case 3:return a(t,e,r,!1);default:throw new Error("box-intersect: Invalid arguments")}}e.exports=c;var u,f=t("typedarray-pool"),h=t("./lib/sweep"),d=t("./lib/intersect")},{"./lib/intersect":85,"./lib/sweep":89,"typedarray-pool":278}],84:[function(t,e,r){"use strict";function n(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",w.join(),"){","var ",c,"=2*",a,";"],l="for(var i="+u+","+p+"="+c+"*"+u+";i<"+f+";++i,"+p+"+="+c+"){var x0="+h+"["+o+"+"+p+"],x1="+h+"["+o+"+"+p+"+"+a+"],xi="+d+"[i];",k="for(var j="+g+","+b+"="+c+"*"+g+";j<"+v+";++j,"+b+"+="+c+"){var y0="+m+"["+o+"+"+b+"],"+(r?"y1="+m+"["+o+"+"+b+"+"+a+"],":"")+"yi="+y+"[j];";return t?i.push(l,_,":",k):i.push(k,_,":",l),r?i.push("if(y1"+v+"-"+g+"){"),t?(e(!0,!1),o.push("}else{"),e(!1,!1)):(o.push("if("+l+"){"),e(!0,!0),o.push("}else{"),e(!0,!1),o.push("}}else{if("+l+"){"),e(!1,!0),o.push("}else{"),e(!1,!1),o.push("}")),o.push("}}return "+r);var s=i.join("")+o.join(""),c=new Function(s);return c()}var a="d",o="ax",s="vv",l="fp",c="es",u="rs",f="re",h="rb",d="ri",p="rp",g="bs",v="be",m="bb",y="bi",b="bp",x="rv",_="Q",w=[a,o,s,u,f,h,d,g,v,m,y];r.partial=i(!1),r.full=i(!0)},{}],85:[function(t,e,r){"use strict";function n(t,e){var r=8*c.log2(e+1)*(t+1)|0,n=c.nextPow2(M*r);L.lengthS&&(l.free(S),S=l.mallocDouble(i))}function i(t,e,r,n,i,a,o,s,l){var c=M*t;L[c]=e,L[c+1]=r,L[c+2]=n,L[c+3]=i,L[c+4]=a,L[c+5]=o;var u=T*t;S[u]=s,S[u+1]=l}function a(t,e,r,n,i,a,o,s,l,c,u){var f=2*t,h=l*f,d=c[h+e];t:for(var p=i,g=i*f;a>p;++p,g+=f){var v=o[g+e],m=o[g+e+t];if(!(v>d||d>m||n&&d===v)){for(var y=s[p],b=e+1;t>b;++b){var v=o[g+b],m=o[g+b+t],x=c[h+b],_=c[h+b+t];if(x>m||v>_)continue t}var w;if(w=n?r(u,y):r(y,u),void 0!==w)return w}}}function o(t,e,r,n,i,a,o,s,l,c){var u=2*t,f=s*u,h=l[f+e];t:for(var d=n,p=n*u;i>d;++d,p+=u){var g=o[d];if(g!==c){var v=a[p+e],m=a[p+e+t];if(!(v>h||h>m)){for(var y=e+1;t>y;++y){var v=a[p+y],m=a[p+y+t],b=l[f+y],x=l[f+y+t];if(b>m||v>x)continue t}var _=r(g,c);if(void 0!==_)return _}}}}function s(t,e,r,s,l,c,u,g,E){n(t,s+u);var C,z=0,P=2*t;for(i(z++,0,0,s,0,u,r?16:0,-(1/0),1/0),r||i(z++,0,0,u,0,s,1,-(1/0),1/0);z>0;){z-=1;var R=z*M,O=L[R],I=L[R+1],N=L[R+2],j=L[R+3],F=L[R+4],D=L[R+5],B=z*T,U=S[B],V=S[B+1],q=1&D,H=!!(16&D),G=l,Y=c,X=g,W=E;if(q&&(G=g,Y=E,X=l,W=c),!(2&D&&(N=_(t,O,I,N,G,Y,V),I>=N)||4&D&&(I=w(t,O,I,N,G,Y,U),I>=N))){var Z=N-I,K=F-j;if(H){if(y>t*Z*(Z+K)){if(C=d.scanComplete(t,O,e,I,N,G,Y,j,F,X,W),void 0!==C)return C;continue}}else{if(t*Math.min(Z,K)t*Z*K){if(C=d.scanBipartite(t,O,e,q,I,N,G,Y,j,F,X,W),void 0!==C)return C;continue}}var $=b(t,O,I,N,G,Y,U,V);if($>I)if(v>t*($-I)){if(C=h(t,O+1,e,I,$,G,Y,j,F,X,W),void 0!==C)return C}else if(O===t-2){if(C=q?d.sweepBipartite(t,e,j,F,X,W,I,$,G,Y):d.sweepBipartite(t,e,I,$,G,Y,j,F,X,W),void 0!==C)return C}else i(z++,O+1,I,$,j,F,q,-(1/0),1/0),i(z++,O+1,j,F,I,$,1^q,-(1/0),1/0);if(N>$){var Q=p(t,O,j,F,X,W),J=X[P*Q+O],tt=x(t,O,Q,F,X,W,J);if(F>tt&&i(z++,O,$,N,tt,F,(4|q)+(H?16:0),J,V),Q>j&&i(z++,O,$,N,j,Q,(2|q)+(H?16:0),U,J),Q+1===tt){if(C=H?o(t,O,e,$,N,G,Y,Q,X,W[Q]):a(t,O,e,q,$,N,G,Y,Q,X,W[Q]),void 0!==C)return C}else if(tt>Q){var et;if(H){if(et=k(t,O,$,N,G,Y,J),et>$){var rt=x(t,O,$,et,G,Y,J);if(O===t-2){if(rt>$&&(C=d.sweepComplete(t,e,$,rt,G,Y,Q,tt,X,W),void 0!==C))return C;if(et>rt&&(C=d.sweepBipartite(t,e,rt,et,G,Y,Q,tt,X,W),void 0!==C))return C}else rt>$&&i(z++,O+1,$,rt,Q,tt,16,-(1/0),1/0),et>rt&&(i(z++,O+1,rt,et,Q,tt,0,-(1/0),1/0),i(z++,O+1,Q,tt,rt,et,1,-(1/0),1/0))}}else et=q?A(t,O,$,N,G,Y,J):k(t,O,$,N,G,Y,J),et>$&&(O===t-2?C=q?d.sweepBipartite(t,e,Q,tt,X,W,$,et,G,Y):d.sweepBipartite(t,e,$,et,G,Y,Q,tt,X,W):(i(z++,O+1,$,et,Q,tt,q,-(1/0),1/0),i(z++,O+1,Q,tt,$,et,1^q,-(1/0),1/0)))}}}}}e.exports=s;var l=t("typedarray-pool"),c=t("bit-twiddle"),u=t("./brute"),f=u.partial,h=u.full,d=t("./sweep"),p=t("./median"),g=t("./partition"),v=128,m=1<<22,y=1<<22,b=g("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]),x=g("lo===p0",["p0"]),_=g("lol;++l,s+=o)for(var c=i[s],u=l,f=o*(l-1);u>r&&i[f+e]>c;--u,f-=o){for(var h=f,d=f+o,p=0;o>p;++p,++h,++d){var g=i[h];i[h]=i[d],i[d]=g}var v=a[u];a[u]=a[u-1],a[u-1]=v}}function i(t,e,r,i,a,l){if(r+1>=i)return r;for(var c=r,u=i,f=i+r>>>1,h=2*t,d=f,p=a[h*f+e];u>c;){if(s>u-c){n(t,e,c,u,a,l),p=a[h*f+e];break}var g=u-c,v=Math.random()*g+c|0,m=a[h*v+e],y=Math.random()*g+c|0,b=a[h*y+e],x=Math.random()*g+c|0,_=a[h*x+e];b>=m?_>=b?(d=y,p=b):m>=_?(d=v,p=m):(d=x,p=_):b>=_?(d=y,p=b):_>=m?(d=v,p=m):(d=x,p=_);for(var w=h*(u-1),k=h*d,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[u-1];l[u-1]=l[d],l[d]=T,d=o(t,e,c,u-1,a,l,p);for(var w=h*(u-1),k=h*d,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[u-1];if(l[u-1]=l[d],l[d]=T,d>f){for(u=d-1;u>c&&a[h*(u-1)+e]===p;)u-=1;u+=1}else{if(!(f>d))break;for(c=d+1;u>c&&a[h*c+e]===p;)c+=1}}return o(t,e,r,f,a,l,a[h*f+e])}e.exports=i;var a=t("./partition"),o=a("lo=0&&n.push("lo=e[k+n]"),t.indexOf("hi")>=0&&n.push("hi=e[k+o]"),r.push(i.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)}e.exports=n;var i="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],88:[function(t,e,r){"use strict";function n(t,e){4*h>=e?i(0,e-1,t):f(0,e-1,t)}function i(t,e,r){for(var n=2*(t+1),i=t+1;e>=i;++i){for(var a=r[n++],o=r[n++],s=i,l=n-2;s-- >t;){var c=r[l-2],u=r[l-1];if(a>c)break;if(c===a&&o>u)break;r[l]=c,r[l+1]=u,l-=2}r[l]=a,r[l+1]=o}}function a(t,e,r){t*=2,e*=2;var n=r[t],i=r[t+1];r[t]=r[e],r[t+1]=r[e+1],r[e]=n,r[e+1]=i}function o(t,e,r){t*=2,e*=2,r[t]=r[e],r[t+1]=r[e+1]}function s(t,e,r,n){t*=2,e*=2,r*=2;var i=n[t],a=n[t+1];n[t]=n[e],n[t+1]=n[e+1],n[e]=n[r],n[e+1]=n[r+1],n[r]=i,n[r+1]=a}function l(t,e,r,n,i){t*=2,e*=2,i[t]=i[e],i[e]=r,i[t+1]=i[e+1],i[e+1]=n}function c(t,e,r){t*=2,e*=2;var n=r[t],i=r[e];return i>n?!1:n===i?r[t+1]>r[e+1]:!0}function u(t,e,r,n){t*=2;var i=n[t];return e>i?!0:i===e?n[t+1]>1,v=g-n,m=g+n,y=d,b=v,x=g,_=m,w=p,k=t+1,A=e-1,M=0;c(y,b,r)&&(M=y,y=b,b=M),c(_,w,r)&&(M=_,_=w,w=M),c(y,x,r)&&(M=y,y=x,x=M),c(b,x,r)&&(M=b,b=x,x=M),c(y,_,r)&&(M=y,y=_,_=M),c(x,_,r)&&(M=x,x=_,_=M),c(b,w,r)&&(M=b,b=w,w=M),c(b,x,r)&&(M=b,b=x,x=M),c(_,w,r)&&(M=_,_=w,w=M);for(var T=r[2*b],E=r[2*b+1],L=r[2*_],S=r[2*_+1],C=2*y,z=2*x,P=2*w,R=2*d,O=2*g,I=2*p,N=0;2>N;++N){var j=r[C+N],F=r[z+N],D=r[P+N];r[R+N]=j,r[O+N]=F,r[I+N]=D}o(v,t,r),o(m,e,r);for(var B=k;A>=B;++B)if(u(B,T,E,r))B!==k&&a(B,k,r),++k;else if(!u(B,L,S,r))for(;;){if(u(A,L,S,r)){u(A,T,E,r)?(s(B,k,A,r),++k,--A):(a(B,A,r),--A);break}if(--A=k-2-t?i(t,k-2,r):f(t,k-2,r),h>=e-(A+2)?i(A+2,e,r):f(A+2,e,r),h>=A-k?i(k,A,r):f(k,A,r)}e.exports=n;var h=32},{}],89:[function(t,e,r){"use strict";function n(t){var e=f.nextPow2(t);g.lengthk;++k){var A=s[k],M=b*k;_[p++]=o[M+x],_[p++]=-(A+1),_[p++]=o[M+w],_[p++]=A}for(var k=l;c>k;++k){var A=f[k]+d,T=b*k;_[p++]=u[T+x],_[p++]=-A,_[p++]=u[T+w],_[p++]=A}var E=p>>>1;h(_,E);for(var L=0,S=0,k=0;E>k;++k){var C=0|_[2*k+1];if(C>=d)C=C-d|0,i(m,y,S--,C);else if(C>=0)i(g,v,L--,C);else if(-d>=C){C=-C-d|0;for(var z=0;L>z;++z){var P=e(g[z],C);if(void 0!==P)return P}a(m,y,S++,C)}else{C=-C-1|0;for(var z=0;S>z;++z){var P=e(C,m[z]);if(void 0!==P)return P}a(g,v,L++,C)}}}function s(t,e,r,n,o,s,l,c,u,f){for(var d=0,p=2*t,w=t-1,k=p-1,A=r;n>A;++A){var M=s[A]+1<<1,T=p*A;_[d++]=o[T+w],_[d++]=-M,_[d++]=o[T+k],_[d++]=M}for(var A=l;c>A;++A){var M=f[A]+1<<1,E=p*A;_[d++]=u[E+w],_[d++]=1|-M,_[d++]=u[E+k],_[d++]=1|M}var L=d>>>1;h(_,L);for(var S=0,C=0,z=0,A=0;L>A;++A){var P=0|_[2*A+1],R=1&P;if(L-1>A&&P>>1===_[2*A+3]>>1&&(R=2,A+=1),0>P){for(var O=-(P>>1)-1,I=0;z>I;++I){var N=e(b[I],O);if(void 0!==N)return N}if(0!==R)for(var I=0;S>I;++I){var N=e(g[I],O);if(void 0!==N)return N}if(1!==R)for(var I=0;C>I;++I){var N=e(m[I],O);if(void 0!==N)return N}0===R?a(g,v,S++,O):1===R?a(m,y,C++,O):2===R&&a(b,x,z++,O)}else{var O=(P>>1)-1;0===R?i(g,v,S--,O):1===R?i(m,y,C--,O):2===R&&i(b,x,z--,O)}}}function l(t,e,r,n,o,s,l,c,u,f,p,m){var y=0,b=2*t,x=e,w=e+t,k=1,A=1;n?A=d:k=d;for(var M=o;s>M;++M){var T=M+k,E=b*M;_[y++]=l[E+x],_[y++]=-T,_[y++]=l[E+w],_[y++]=T}for(var M=u;f>M;++M){var T=M+A,L=b*M;_[y++]=p[L+x],_[y++]=-T}var S=y>>>1;h(_,S);for(var C=0,M=0;S>M;++M){var z=0|_[2*M+1];if(0>z){var T=-z,P=!1;if(T>=d?(P=!n,T-=d):(P=!!n,T-=1),P)a(g,v,C++,T);else{var R=m[T],O=b*T,I=p[O+e+1],N=p[O+e+1+t];t:for(var j=0;C>j;++j){var F=g[j],D=b*F;if(!(NB;++B)if(p[O+B+t]y;++y){var b=y+d,x=p*y;_[f++]=a[x+v],_[f++]=-b,_[f++]=a[x+m],_[f++]=b}for(var y=s;l>y;++y){var b=y+1,w=p*y;_[f++]=c[w+v],_[f++]=-b}var k=f>>>1;h(_,k);for(var A=0,y=0;k>y;++y){var M=0|_[2*y+1];if(0>M){var b=-M;if(b>=d)g[A++]=b-d;else{b-=1;var T=u[b],E=p*b,L=c[E+e+1],S=c[E+e+1+t];t:for(var C=0;A>C;++C){var z=g[C],P=o[z];if(P===T)break;var R=p*z;if(!(SO;++O)if(c[E+O+t]=0;--C)if(g[C]===b){for(var O=C+1;A>O;++O)g[O-1]=g[O];break}--A}}}e.exports={init:n,sweepBipartite:o,sweepComplete:s,scanBipartite:l,scanComplete:c};var u=t("typedarray-pool"),f=t("bit-twiddle"),h=t("./sort"),d=1<<28,p=1024,g=u.mallocInt32(p),v=u.mallocInt32(p),m=u.mallocInt32(p),y=u.mallocInt32(p),b=u.mallocInt32(p),x=u.mallocInt32(p),_=u.mallocDouble(8*p)},{"./sort":88,"bit-twiddle":50,"typedarray-pool":278}],90:[function(t,e,r){(function(t){function r(t,e){return d[0]=t,d[1]=e,h[0]}function n(t){return h[0]=t,d[0]}function i(t){return h[0]=t,d[1]}function a(t,e){return d[1]=t,d[0]=e,h[0]}function o(t){return h[0]=t,d[1]}function s(t){return h[0]=t,d[0]}function l(t,e){return p.writeUInt32LE(t,0,!0),p.writeUInt32LE(e,4,!0),p.readDoubleLE(0,!0)}function c(t){return p.writeDoubleLE(t,0,!0),p.readUInt32LE(0,!0)}function u(t){return p.writeDoubleLE(t,0,!0),p.readUInt32LE(4,!0)}var f=!1;if("undefined"!=typeof Float64Array){var h=new Float64Array(1),d=new Uint32Array(h.buffer);h[0]=1,f=!0,1072693248===d[1]?(e.exports=function(t){return h[0]=t,[d[0],d[1]]},e.exports.pack=r,e.exports.lo=n,e.exports.hi=i):1072693248===d[0]?(e.exports=function(t){return h[0]=t, -[d[1],d[0]]},e.exports.pack=a,e.exports.lo=o,e.exports.hi=s):f=!1}if(!f){var p=new t(8);e.exports=function(t){return p.writeDoubleLE(t,0,!0),[p.readUInt32LE(0,!0),p.readUInt32LE(4,!0)]},e.exports.pack=l,e.exports.lo=c,e.exports.hi=u}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){var r=e.exports.hi(t);return(r<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){var r=e.exports.hi(t);return!(2146435072&r)}}).call(this,t("buffer").Buffer)},{buffer:51}],91:[function(t,e,r){"use strict";function n(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return 0>e?-a:a;var r=i.hi(t),n=i.lo(t);return e>t==t>0?n===o?(r+=1,n=0):n+=1:0===n?(n=o,r-=1):n-=1,i.pack(n,r)}var i=t("double-bits"),a=Math.pow(2,-1074),o=-1>>>0;e.exports=n},{"double-bits":90}],92:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/add");e.exports=n},{"big-rat/add":66}],93:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t.length),r=0;rs;++s)o[s]=a(t[s],r);return o}var i=t("big-rat"),a=t("big-rat/mul");e.exports=n},{"big-rat":69,"big-rat/mul":78}],95:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/sub");e.exports=n},{"big-rat/sub":81}],96:[function(t,e,r){"use strict";function n(t,e,r,n){for(var i=0;2>i;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),c=r[i],u=n[i],f=Math.min(c,u),h=Math.max(c,u);if(s>h||f>l)return!1}return!0}function i(t,e,r,i){var o=a(t,r,i),s=a(e,r,i);if(o>0&&s>0||0>o&&0>s)return!1;var l=a(r,t,e),c=a(i,t,e);return l>0&&c>0||0>l&&0>c?!1:0===o&&0===s&&0===l&&0===c?n(t,e,r,i):!0}e.exports=i;var a=t("robust-orientation")[3]},{"robust-orientation":259}],97:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n;var i=n.prototype;Object.defineProperty(i,"length",{get:function(){return this.roots.length}}),i.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},i.find=function(t){for(var e=t,r=this.roots;r[t]!==t;)t=r[t];for(;r[e]!==t;){var n=r[e];r[e]=t,e=n}return t},i.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],98:[function(t,e,r){(function(t){var r=function(){"use strict";function e(r,n,i,a){function s(r,i){if(null===r)return null;if(0==i)return r;var l,h;if("object"!=typeof r)return r;if(e.__isArray(r))l=[];else if(e.__isRegExp(r))l=new RegExp(r.source,o(r)),r.lastIndex&&(l.lastIndex=r.lastIndex);else if(e.__isDate(r))l=new Date(r.getTime());else{if(f&&t.isBuffer(r))return l=new t(r.length),r.copy(l),l;"undefined"==typeof a?(h=Object.getPrototypeOf(r),l=Object.create(h)):(l=Object.create(a),h=a)}if(n){var d=c.indexOf(r);if(-1!=d)return u[d];c.push(r),u.push(l)}for(var p in r){var g;h&&(g=Object.getOwnPropertyDescriptor(h,p)),g&&null==g.set||(l[p]=s(r[p],i-1))}return l}var l;"object"==typeof n&&(i=n.depth,a=n.prototype,l=n.filter,n=n.circular);var c=[],u=[],f="undefined"!=typeof t;return"undefined"==typeof n&&(n=!0),"undefined"==typeof i&&(i=1/0),s(r,i)}function r(t){return Object.prototype.toString.call(t)}function n(t){return"object"==typeof t&&"[object Date]"===r(t)}function i(t){return"object"==typeof t&&"[object Array]"===r(t)}function a(t){return"object"==typeof t&&"[object RegExp]"===r(t)}function o(t){var e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),e}return e.clonePrototype=function(t){if(null===t)return null;var e=function(){};return e.prototype=t,new e},e.__objToStr=r,e.__isDate=n,e.__isArray=i,e.__isRegExp=a,e.__getRegExpFlags=o,e}();"object"==typeof e&&e.exports&&(e.exports=r)}).call(this,t("buffer").Buffer)},{buffer:51}],99:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:0,rgb:[255,255,255,1]}]}},{}],100:[function(t,e,r){"use strict";function n(t){for(var e,r="#",n=0;3>n;++n)e=t[n],e=e.toString(16),r+=("00"+e).substr(e.length);return r}function i(t){return"rgba("+t.join(",")+")"}var a=t("arraytools"),o=t("clone"),s=t("./colorScales");e.exports=function(t){var e,r,l,c,u,f,h,d,p,g,v,m,y,b=[],x=[],_=[],w=[];if(a.isPlainObject(t)||(t={}),p=t.nshades||72,d=t.format||"hex",h=t.colormap,h||(h="jet"),"string"==typeof h){if(h=h.toLowerCase(),!s[h])throw Error(h+" not a supported colorscale");f=o(s[h])}else{if(!Array.isArray(h))throw Error("unsupported colormap option",h);f=o(h)}if(f.length>p)throw new Error(h+" map requires nshades to be at least size "+f.length);for(v=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:o(t.alpha):"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1],e=f.map(function(t){return Math.round(t.index*p)}),v[0]<0&&(v[0]=0),v[1]<0&&(v[0]=0),v[0]>1&&(v[0]=1),v[1]>1&&(v[0]=1),y=0;y=0&&r[3]<=1||(r[3]=v[0]+(v[1]-v[0])*m);for(y=0;yx;++x)if(i=y[x]-b[x])return i;return 0}}e.exports=i;var a=Math.min},{}],102:[function(t,e,r){"use strict";function n(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;return 0===r?[]:1===r?i(t):2===r?a(t):o(t,r)}var i=t("./lib/ch1d"),a=t("./lib/ch2d"),o=t("./lib/chnd");e.exports=n},{"./lib/ch1d":103,"./lib/ch2d":104,"./lib/chnd":105}],103:[function(t,e,r){"use strict";function n(t){for(var e=0,r=0,n=1;nt[r][0]&&(r=n);return r>e?[[e],[r]]:e>r?[[r],[e]]:[[e]]}e.exports=n},{}],104:[function(t,e,r){"use strict";function n(t){var e=i(t),r=e.length;if(2>=r)return[];for(var n=new Array(r),a=e[r-1],o=0;r>o;++o){var s=e[o];n[o]=[a,s],a=s}return n}e.exports=n;var i=t("monotone-convex-hull-2d")},{"monotone-convex-hull-2d":107}],105:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),i=0;ii;++i)e.indexOf(i)<0&&(n[a++]=t[i]);return n}function i(t,e){for(var r=t.length,n=e.length,i=0;r>i;++i)for(var a=t[i],o=0;os)a[o]=e[s];else{s-=n;for(var l=0;n>l;++l)s>=e[l]&&(s+=1);a[o]=s}}return t}function a(t,e){try{return o(t,!0)}catch(r){var a=s(t);if(a.length<=e)return[];var l=n(t,a),c=o(l,!0);return i(c,a)}}e.exports=a;var o=t("incremental-convex-hull"),s=t("affine-hull")},{"affine-hull":106,"incremental-convex-hull":235}],106:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(e+1),n=0;n=i;++i){for(var o=new Array(e),s=0;e>s;++s)o[s]=Math.pow(i+1-n,s);r[i]=o}var l=a.apply(void 0,r);if(l)return!0}return!1}function i(t){var e=t.length;if(0===e)return[];if(1===e)return[0];for(var r=t[0].length,i=[t[0]],a=[0],o=1;e>o;++o)if(i.push(t[o]),n(i,r)){if(a.push(o),a.length===r+1)return a}else i.pop();return a}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":259}],107:[function(t,e,r){"use strict";function n(t){var e=t.length;if(3>e){for(var r=new Array(e),n=0;e>n;++n)r[n]=n;return 2===e&&t[0][0]===t[1][0]&&t[0][1]===t[1][1]?[0]:r}for(var a=new Array(e),n=0;e>n;++n)a[n]=n;a.sort(function(e,r){var n=t[e][0]-t[r][0];return n?n:t[e][1]-t[r][1]});for(var o=[a[0],a[1]],s=[a[0],a[1]],n=2;e>n;++n){for(var l=a[n],c=t[l],u=o.length;u>1&&i(t[o[u-2]],t[o[u-1]],c)<=0;)u-=1,o.pop();for(o.push(l),u=s.length;u>1&&i(t[s[u-2]],t[s[u-1]],c)>=0;)u-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),f=0,n=0,h=o.length;h>n;++n)r[f++]=o[n];for(var d=s.length-2;d>0;--d)r[f++]=s[d];return r}e.exports=n;var i=t("robust-orientation")[3]},{"robust-orientation":259}],108:[function(t,e,r){e.exports={AFG:"afghan",ALA:"\\b\\wland",ALB:"albania",DZA:"algeria",ASM:"^(?=.*americ).*samoa",AND:"andorra",AGO:"angola",AIA:"anguill?a",ATA:"antarctica",ATG:"antigua",ARG:"argentin",ARM:"armenia",ABW:"^(?!.*bonaire).*\\baruba",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baustri.*\\bemp",AZE:"azerbaijan",BHS:"bahamas",BHR:"bahrain",BGD:"bangladesh|^(?=.*east).*paki?stan",BRB:"barbados",BLR:"belarus|byelo",BEL:"^(?!.*luxem).*belgium",BLZ:"belize|^(?=.*british).*honduras",BEN:"benin|dahome",BMU:"bermuda",BTN:"bhutan",BOL:"bolivia",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",BIH:"herzegovina|bosnia",BWA:"botswana|bechuana",BVT:"bouvet",BRA:"brazil",IOT:"british.?indian.?ocean",BRN:"brunei",BGR:"bulgaria",BFA:"burkina|\\bfaso|upper.?volta",BDI:"burundi",KHM:"cambodia|kampuchea|khmer",CMR:"cameroon",CAN:"canada",CPV:"verde",CYM:"cayman",CAF:"\\bcentral.african.republic",TCD:"\\bchad",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china",CXR:"christmas",CCK:"\\bcocos|keeling",COL:"colombia",COM:"comoro",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",COG:"^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",COK:"\\bcook",CRI:"costa.?rica",CIV:"ivoire|ivory",HRV:"croatia",CUB:"\\bcuba",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",CYP:"cyprus",CZE:"^(?=.*rep).*czech|czechia|bohemia",CSK:"czechoslovakia",DNK:"denmark",DJI:"djibouti",DMA:"dominica(?!n)",DOM:"dominican.rep",ECU:"ecuador",EGY:"egypt",SLV:"el.?salvador",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",ERI:"eritrea",EST:"estonia",ETH:"ethiopia|abyssinia",FLK:"falkland|malvinas",FRO:"faroe|faeroe",FJI:"fiji",FIN:"finland",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",GUF:"^(?=.*french).*guiana",PYF:"french.?polynesia|tahiti",ATF:"french.?southern",GAB:"gabon",GMB:"gambia",GEO:"^(?!.*south).*georgia",DDR:"german.?democratic.?republic|democratic.?republic.*germany|east.germany",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GHA:"ghana|gold.?coast",GIB:"gibraltar",GRC:"greece|hellenic|hellas",GRL:"greenland",GRD:"grenada",GLP:"guadeloupe",GUM:"\\bguam",GTM:"guatemala",GGY:"guernsey",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",GNB:"bissau|^(?=.*portu).*guinea",GUY:"guyana|british.?guiana",HTI:"haiti",HMD:"heard.*mcdonald",VAT:"holy.?see|vatican|papal.?st",HND:"^(?!.*brit).*honduras",HKG:"hong.?kong",HUN:"^(?!.*austr).*hungary",ISL:"iceland",IND:"india(?!.*ocea)",IDN:"indonesia",IRN:"\\biran|persia",IRQ:"\\biraq|mesopotamia",IRL:"ireland",IMN:"^(?=.*isle).*\\bman",ISR:"israel",ITA:"italy",JAM:"jamaica",JPN:"japan",JEY:"jersey",JOR:"jordan",KAZ:"kazak",KEN:"kenya|british.?east.?africa|east.?africa.?prot",KIR:"kiribati",PRK:"^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk",KOR:"^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea",KWT:"kuwait",KGZ:"kyrgyz|kirghiz",LAO:"\\blaos?\\b",LVA:"latvia",LBN:"lebanon",LSO:"lesotho|basuto",LBR:"liberia",LBY:"libya",LIE:"liechtenstein",LTU:"lithuania",LUX:"^(?!.*belg).*luxem",MAC:"maca(o|u)",MKD:"macedonia|fyrom",MDG:"madagascar|malagasy",MWI:"malawi|nyasa",MYS:"malaysia",MDV:"maldive",MLI:"\\bmali\\b",MLT:"\\bmalta",MHL:"marshall",MTQ:"martinique",MRT:"mauritania",MUS:"mauritius",MYT:"\\bmayotte",MEX:"\\bmexic",FSM:"micronesia",MDA:"moldov|b(a|e)ssarabia",MCO:"monaco",MNG:"mongolia",MNE:"^(?!.*serbia).*montenegro",MSR:"montserrat",MAR:"morocco|\\bmaroc",MOZ:"mozambique",MMR:"myanmar|burma",NAM:"namibia",NRU:"nauru",NPL:"nepal",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",ANT:"^(?=.*\\bant).*(nether|dutch)",NCL:"new.?caledonia",NZL:"new.?zealand",NIC:"nicaragua",NER:"\\bniger(?!ia)",NGA:"nigeria",NIU:"niue",NFK:"norfolk",MNP:"mariana",NOR:"norway",OMN:"\\boman|trucial",PAK:"^(?!.*east).*paki?stan",PLW:"palau",PSE:"palestin|\\bgaza|west.?bank",PAN:"panama",PNG:"papua|new.?guinea",PRY:"paraguay",PER:"peru",PHL:"philippines",PCN:"pitcairn",POL:"poland",PRT:"portugal",PRI:"puerto.?rico",QAT:"qatar",REU:"r(e|\xe9)union",ROU:"r(o|u|ou)mania",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",RWA:"rwanda",BLM:"barth(e|\xe9)lemy",SHN:"helena",KNA:"kitts|\\bnevis",LCA:"\\blucia",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",SPM:"miquelon",VCT:"vincent",WSM:"^(?!.*amer).*samoa",SMR:"san.?marino",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SAU:"\\bsa\\w*.?arabia",SEN:"senegal",SRB:"^(?!.*monte).*serbia",SYC:"seychell",SLE:"sierra",SGP:"singapore",SXM:"^(?!.*martin)(?!.*saba).*maarten",SVK:"^(?!.*cze).*slovak",SVN:"slovenia",SLB:"solomon",SOM:"somali",ZAF:"\\bs\\w*.?africa",SGS:"south.?georgia|sandwich",SSD:"\\bs\\w*.?sudan",ESP:"spain",LKA:"sri.?lanka|ceylon",SDN:"^(?!.*\\bs(?!u)).*sudan",SUR:"surinam|dutch.?guiana",SJM:"svalbard",SWZ:"swaziland",SWE:"sweden",CHE:"switz|swiss",SYR:"syria",TWN:"taiwan|taipei|formosa",TJK:"tajik",TZA:"tanzania",THA:"thailand|\\bsiam",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TGO:"togo",TKL:"tokelau",TON:"tonga",TTO:"trinidad|tobago",TUN:"tunisia",TUR:"turkey",TKM:"turkmen",TCA:"turks",TUV:"tuvalu",UGA:"uganda",UKR:"ukrain",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",USA:"united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)",UMI:"minor.?outlying.?is",URY:"uruguay",UZB:"uzbek",VUT:"vanuatu|new.?hebrides",VEN:"venezuela",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",WLF:"futuna|wallis",ESH:"western.sahara",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",YUG:"yugoslavia",ZMB:"zambia|northern.?rhodesia",EAZ:"zanzibar",ZWE:"zimbabwe|^(?!.*northern).*rhodesia"}},{}],109:[function(t,e,r){"use strict";function n(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function i(t){var e=new n;e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var i=0;i0)throw new Error("cwise: pre() block may not reference array args");if(i0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if("index"===o){if(e.indexArgs.push(i),i0)throw new Error("cwise: pre() block may not reference array index");if(i0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(e.shapeArgs.push(i),ir.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,a(e)}var a=t("./lib/thunk.js");e.exports=i},{"./lib/thunk.js":111}],110:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],c=[],u=0,f=0;for(n=0;a>n;++n)c.push(["i",n,"=0"].join(""));for(i=0;o>i;++i)for(n=0;a>n;++n)f=u,u=t[n],0===n?c.push(["d",i,"s",n,"=t",i,"p",u].join("")):c.push(["d",i,"s",n,"=(t",i,"p",u,"-s",f,"*t",i,"p",f,")"].join(""));for(l.push("var "+c.join(",")),n=a-1;n>=0;--n)u=t[n],l.push(["for(i",n,"=0;i",n,"n;++n){for(f=u,u=t[n],i=0;o>i;++i)l.push(["p",i,"+=d",i,"s",n].join(""));s&&(n>0&&l.push(["index[",f,"]-=s",f].join("")),l.push(["++index[",u,"]"].join(""))),l.push("}")}return l.join("\n")}function i(t,e,r,i){for(var a=e.length,o=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,c=[],u=0;o>u;++u)c.push(["var offset",u,"=p",u].join(""));for(var u=t;a>u;++u)c.push(["for(var j"+u+"=SS[",e[u],"]|0;j",u,">0;){"].join("")),c.push(["if(j",u,"<",s,"){"].join("")),c.push(["s",e[u],"=j",u].join("")),c.push(["j",u,"=0"].join("")),c.push(["}else{s",e[u],"=",s].join("")),c.push(["j",u,"-=",s,"}"].join("")),l&&c.push(["index[",e[u],"]=j",u].join(""));for(var u=0;o>u;++u){for(var f=["offset"+u],h=t;a>h;++h)f.push(["j",h,"*t",u,"p",e[h]].join(""));c.push(["p",u,"=(",f.join("+"),")"].join(""))}c.push(n(e,r,i));for(var u=t;a>u;++u)c.push("}");return c.join("\n")}function a(t){for(var e=0,r=t[0].length;r>e;){for(var n=1;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}function l(t,e){for(var r=e[1].length-Math.abs(t.arrayBlockIndices[0])|0,l=new Array(t.arrayArgs.length),u=new Array(t.arrayArgs.length),f=0;fy;++y)_.push(["s",y,"=SS[",y,"]"].join(""));for(var f=0;fy;++y)_.push(["t",f,"p",y,"=t",f,"[",p[f]+y,"]"].join(""));for(var y=0;y0&&_.push("shape=SS.slice(0)"),t.indexArgs.length>0){for(var w=new Array(r),f=0;r>f;++f)w[f]="0";_.push(["index=[",w.join(","),"]"].join(""))}for(var f=0;f3&&x.push(o(t.pre,t,u));var T=o(t.body,t,u),E=a(v);r>E?x.push(i(E,v[0],t,T)):x.push(n(v[0],t,T)),t.post.body.length>3&&x.push(o(t.post,t,u)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+x.join("\n")+"\n----------");var L=[t.funcName||"unnamed","_cwise_loop_",l[0].join("s"),"m",E,s(u)].join(""),S=new Function(["function ",L,"(",b.join(","),"){",x.join("\n"),"} return ",L].join(""));return S()}var c=t("uniq");e.exports=l},{uniq:279}],111:[function(t,e,r){"use strict";function n(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],c=[],u=0;u0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),c.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),e.push("if (!("+c.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}"));for(var u=0;ut?-1:t>e?1:t>=e?0:NaN}function a(t){return null===t?NaN:+t}function o(t){return!isNaN(t)}function s(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}function l(t){return t.length}function c(t){for(var e=1;t*e%1;)e*=10;return e}function u(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function f(){this._=Object.create(null)}function h(t){return(t+="")===ko||t[0]===Ao?Ao+t:t}function d(t){return(t+="")[0]===Ao?t.slice(1):t}function p(t){return h(t)in this._}function g(t){return(t=h(t))in this._&&delete this._[t]}function v(){var t=[];for(var e in this._)t.push(d(e));return t}function m(){var t=0;for(var e in this._)++t;return t}function y(){for(var t in this._)return!1;return!0}function b(){this._=Object.create(null)}function x(t){return t}function _(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function w(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=Mo.length;n>r;++r){var i=Mo[r]+e;if(i in t)return i}}function k(){}function A(){}function M(t){function e(){for(var e,n=r,i=-1,a=n.length;++ir;r++)for(var i,a=t[r],o=0,s=a.length;s>o;o++)(i=a[o])&&e(i,o,r);return t}function Y(t){return Eo(t,Oo),t}function X(t){var e,r;return function(n,i,a){var o,s=t[a].update,l=s.length;for(a!=r&&(r=a,e=0),i>=e&&(e=i+1);!(o=s[e])&&++e0&&(t=t.slice(0,s));var c=Io.get(t);return c&&(t=c,l=K),s?e?i:n:e?k:a}function Z(t,e){return function(r){var n=co.event;co.event=r,e[0]=this.__data__;try{t.apply(this,e)}finally{co.event=n}}}function K(t,e){var r=Z(t,e);return function(t){var e=this,n=t.relatedTarget;n&&(n===e||8&n.compareDocumentPosition(e))||r.call(e,t)}}function $(t){var r=".dragsuppress-"+ ++jo,i="click"+r,a=co.select(n(t)).on("touchmove"+r,T).on("dragstart"+r,T).on("selectstart"+r,T);if(null==No&&(No="onselectstart"in t?!1:w(t.style,"userSelect")),No){var o=e(t).style,s=o[No];o[No]="none"}return function(t){if(a.on(r,null),No&&(o[No]=s),t){var e=function(){a.on(i,null)};a.on(i,function(){T(),e()},!0),setTimeout(e,0)}}}function Q(t,e){e.changedTouches&&(e=e.changedTouches[0]);var r=t.ownerSVGElement||t;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Fo){var a=n(t);if(a.scrollX||a.scrollY){r=co.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Fo=!(o.f||o.e),r.remove()}}return Fo?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}function J(){return co.event.changedTouches[0].identifier}function tt(t){return t>0?1:0>t?-1:0}function et(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function rt(t){return t>1?0:-1>t?Uo:Math.acos(t)}function nt(t){return t>1?Ho:-1>t?-Ho:Math.asin(t)}function it(t){return((t=Math.exp(t))-1/t)/2}function at(t){return((t=Math.exp(t))+1/t)/2}function ot(t){return((t=Math.exp(2*t))-1)/(t+1)}function st(t){return(t=Math.sin(t/2))*t}function lt(){}function ct(t,e,r){return this instanceof ct?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof ct?new ct(t.h,t.s,t.l):kt(""+t,At,ct):new ct(t,e,r)}function ut(t,e,r){function n(t){return t>360?t-=360:0>t&&(t+=360),60>t?a+(o-a)*t/60:180>t?o:240>t?a+(o-a)*(240-t)/60:a}function i(t){return Math.round(255*n(t))}var a,o;return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:0>e?0:e>1?1:e,r=0>r?0:r>1?1:r,o=.5>=r?r*(1+e):r+e-r*e,a=2*r-o,new bt(i(t+120),i(t),i(t-120))}function ft(t,e,r){return this instanceof ft?(this.h=+t,this.c=+e,void(this.l=+r)):arguments.length<2?t instanceof ft?new ft(t.h,t.c,t.l):t instanceof dt?gt(t.l,t.a,t.b):gt((t=Mt((t=co.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ft(t,e,r)}function ht(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new dt(r,Math.cos(t*=Go)*e,Math.sin(t)*e)}function dt(t,e,r){return this instanceof dt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof dt?new dt(t.l,t.a,t.b):t instanceof ft?ht(t.h,t.c,t.l):Mt((t=bt(t)).r,t.g,t.b):new dt(t,e,r)}function pt(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return i=vt(i)*rs,n=vt(n)*ns,a=vt(a)*is,new bt(yt(3.2404542*i-1.5371385*n-.4985314*a),yt(-.969266*i+1.8760108*n+.041556*a),yt(.0556434*i-.2040259*n+1.0572252*a))}function gt(t,e,r){return t>0?new ft(Math.atan2(r,e)*Yo,Math.sqrt(e*e+r*r),t):new ft(NaN,NaN,t)}function vt(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function mt(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function yt(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function bt(t,e,r){return this instanceof bt?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof bt?new bt(t.r,t.g,t.b):kt(""+t,bt,ut):new bt(t,e,r)}function xt(t){return new bt(t>>16,t>>8&255,255&t)}function _t(t){return xt(t)+""}function wt(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function kt(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(Et(i[0]),Et(i[1]),Et(i[2]))}return(a=ss.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o=o>>4|o,s=240&a,s=s>>4|s,l=15&a,l=l<<4|l):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function At(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=.5>l?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(r>e?6:0):e==o?(r-t)/s+2:(t-e)/s+4,n*=60):(n=NaN,i=l>0&&1>l?0:n),new ct(n,i,l)}function Mt(t,e,r){t=Tt(t),e=Tt(e),r=Tt(r);var n=mt((.4124564*t+.3575761*e+.1804375*r)/rs),i=mt((.2126729*t+.7151522*e+.072175*r)/ns),a=mt((.0193339*t+.119192*e+.9503041*r)/is);return dt(116*i-16,500*(n-i),200*(i-a))}function Tt(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Et(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Lt(t){return"function"==typeof t?t:function(){return t}}function St(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),Ct(e,r,t,n)}}function Ct(t,e,r,n){function i(){var t,e=l.status;if(!e&&Pt(l)||e>=200&&300>e||304===e){try{t=r.call(a,l)}catch(n){return void o.error.call(a,n)}o.load.call(a,t)}else o.error.call(a,l)}var a={},o=co.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,c=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(t){var e=co.event;co.event=t;try{o.progress.call(a,l)}finally{co.event=e}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(e=null==t?null:t+"",a):e},a.responseType=function(t){return arguments.length?(c=t,a):c},a.response=function(t){return r=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(fo(arguments)))}}),a.send=function(r,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),l.open(r,t,!0),null==e||"accept"in s||(s.accept=e+",*/*"),l.setRequestHeader)for(var u in s)l.setRequestHeader(u,s[u]);return null!=e&&l.overrideMimeType&&l.overrideMimeType(e),null!=c&&(l.responseType=c),null!=i&&a.on("error",i).on("load",function(t){i(null,t)}),o.beforesend.call(a,l),l.send(null==n?null:n),a},a.abort=function(){return l.abort(),a},co.rebind(a,o,"on"),null==n?a:a.get(zt(n))}function zt(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}function Pt(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function Rt(t,e,r){var n=arguments.length;2>n&&(e=0),3>n&&(r=Date.now());var i=r+e,a={c:t,t:i,n:null};return cs?cs.n=a:ls=a,cs=a,us||(fs=clearTimeout(fs),us=1,hs(Ot)),a}function Ot(){var t=It(),e=Nt()-t;e>24?(isFinite(e)&&(clearTimeout(fs),fs=setTimeout(Ot,e)),us=0):(us=1,hs(Ot))}function It(){for(var t=Date.now(),e=ls;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Nt(){for(var t,e=ls,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}}function Dt(t){var e=t.decimal,r=t.thousands,n=t.grouping,i=t.currency,a=n&&r?function(t,e){for(var i=t.length,a=[],o=0,s=n[0],l=0;i>0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(i-=s,i+s)),!((l+=s+1)>e));)s=n[o=(o+1)%n.length];return a.reverse().join(r)}:x;return function(t){var r=ps.exec(t),n=r[1]||" ",o=r[2]||">",s=r[3]||"-",l=r[4]||"",c=r[5],u=+r[6],f=r[7],h=r[8],d=r[9],p=1,g="",v="",m=!1,y=!0;switch(h&&(h=+h.substring(1)),(c||"0"===n&&"="===o)&&(c=n="0",o="="),d){case"n":f=!0,d="g";break;case"%":p=100,v="%",d="f";break;case"p":p=100,v="%",d="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+d.toLowerCase());case"c":y=!1;case"d":m=!0,h=0;break;case"s":p=-1,d="r"}"$"===l&&(g=i[0],v=i[1]),"r"!=d||h||(d="g"),null!=h&&("g"==d?h=Math.max(1,Math.min(21,h)):"e"!=d&&"f"!=d||(h=Math.max(0,Math.min(20,h)))),d=gs.get(d)||Bt;var b=c&&f;return function(t){var r=v;if(m&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>p){var l=co.formatPrefix(t,h);t=l.scale(t),r=l.symbol+v}else t*=p;t=d(t,h);var x,_,w=t.lastIndexOf(".");if(0>w){var k=y?t.lastIndexOf("e"):-1;0>k?(x=t,_=""):(x=t.substring(0,k),_=t.substring(k))}else x=t.substring(0,w),_=e+t.substring(w+1);!c&&f&&(x=a(x,1/0));var A=g.length+x.length+_.length+(b?0:i.length),M=u>A?new Array(A=u-A+1).join(n):"";return b&&(x=a(M+x,M.length?u-_.length:1/0)),i+=g,t=x+_,("<"===o?i+t+M:">"===o?M+i+t:"^"===o?M.substring(0,A>>=1)+i+t+M.substring(A):i+(b?t:M+t))+r}}}function Bt(t){return t+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Vt(t,e,r){function n(e){var r=t(e),n=a(r,1);return n-e>e-r?r:n}function i(r){return e(r=t(new ms(r-1)),1),r}function a(t,r){return e(t=new ms(+t),r),t}function o(t,n,a){var o=i(t),s=[];if(a>1)for(;n>o;)r(o)%a||s.push(new Date(+o)),e(o,1);else for(;n>o;)s.push(new Date(+o)),e(o,1);return s}function s(t,e,r){try{ms=Ut;var n=new Ut;return n._=t,o(n,e,r)}finally{ms=Date}}t.floor=t,t.round=n,t.ceil=i,t.offset=a,t.range=o;var l=t.utc=qt(t);return l.floor=l,l.round=qt(n),l.ceil=qt(i),l.offset=qt(a),l.range=s,t}function qt(t){return function(e,r){try{ms=Ut;var n=new Ut;return n._=e,t(n,r)._}finally{ms=Date}}}function Ht(t){function e(t){function e(e){for(var r,i,a,o=[],s=-1,l=0;++ss;){if(n>=c)return-1;if(i=e.charCodeAt(s++),37===i){if(o=e.charAt(s++),a=S[o in bs?e.charAt(s++):o],!a||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}function n(t,e,r){w.lastIndex=0;var n=w.exec(e.slice(r));return n?(t.w=k.get(n[0].toLowerCase()),r+n[0].length):-1}function i(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.w=_.get(n[0].toLowerCase()),r+n[0].length):-1}function a(t,e,r){T.lastIndex=0;var n=T.exec(e.slice(r));return n?(t.m=E.get(n[0].toLowerCase()),r+n[0].length):-1}function o(t,e,r){A.lastIndex=0;var n=A.exec(e.slice(r));return n?(t.m=M.get(n[0].toLowerCase()),r+n[0].length):-1}function s(t,e,n){return r(t,L.c.toString(),e,n)}function l(t,e,n){return r(t,L.x.toString(),e,n)}function c(t,e,n){return r(t,L.X.toString(),e,n)}function u(t,e,r){var n=b.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)}var f=t.dateTime,h=t.date,d=t.time,p=t.periods,g=t.days,v=t.shortDays,m=t.months,y=t.shortMonths;e.utc=function(t){function r(t){try{ms=Ut;var e=new ms;return e._=t,n(e)}finally{ms=Date}}var n=e(t);return r.parse=function(t){try{ms=Ut;var e=n.parse(t);return e&&e._}finally{ms=Date}},r.toString=n.toString,r},e.multi=e.utc.multi=ue;var b=co.map(),x=Yt(g),_=Xt(g),w=Yt(v),k=Xt(v),A=Yt(m),M=Xt(m),T=Yt(y),E=Xt(y);p.forEach(function(t,e){b.set(t.toLowerCase(),e)});var L={a:function(t){return v[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:e(f),d:function(t,e){return Gt(t.getDate(),e,2)},e:function(t,e){return Gt(t.getDate(),e,2)},H:function(t,e){return Gt(t.getHours(),e,2)},I:function(t,e){return Gt(t.getHours()%12||12,e,2)},j:function(t,e){return Gt(1+vs.dayOfYear(t),e,3)},L:function(t,e){return Gt(t.getMilliseconds(),e,3)},m:function(t,e){return Gt(t.getMonth()+1,e,2)},M:function(t,e){return Gt(t.getMinutes(),e,2)},p:function(t){return p[+(t.getHours()>=12)]},S:function(t,e){return Gt(t.getSeconds(),e,2)},U:function(t,e){return Gt(vs.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Gt(vs.mondayOfYear(t),e,2)},x:e(h),X:e(d),y:function(t,e){return Gt(t.getFullYear()%100,e,2)},Y:function(t,e){return Gt(t.getFullYear()%1e4,e,4)},Z:le,"%":function(){return"%"}},S={a:n,A:i,b:a,B:o,c:s,d:re,e:re,H:ie,I:ie,j:ne,L:se,m:ee,M:ae,p:u,S:oe,U:Zt,w:Wt,W:Kt,x:l,X:c,y:Qt,Y:$t,Z:Jt,"%":ce};return e}function Gt(t,e,r){var n=0>t?"-":"",i=(n?-t:t)+"",a=i.length;return n+(r>a?new Array(r-a+1).join(e)+i:i)}function Yt(t){return new RegExp("^(?:"+t.map(co.requote).join("|")+")","i")}function Xt(t){for(var e=new f,r=-1,n=t.length;++r68?1900:2e3)}function ee(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function re(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function ne(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function ie(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function ae(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function oe(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function se(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function le(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=wo(e)/60|0,i=wo(e)%60;return r+Gt(n,"0",2)+Gt(i,"0",2)}function ce(t,e,r){_s.lastIndex=0;var n=_s.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function ue(t){for(var e=t.length,r=-1;++r=0?1:-1,s=o*r,l=Math.cos(e),c=Math.sin(e),u=a*c,f=i*l+u*Math.cos(s),h=u*o*Math.sin(s);Es.add(Math.atan2(h,f)),n=t,i=l,a=c}var e,r,n,i,a;Ls.point=function(o,s){Ls.point=t,n=(e=o)*Go,i=Math.cos(s=(r=s)*Go/2+Uo/4),a=Math.sin(s)},Ls.lineEnd=function(){t(e,r)}}function me(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function ye(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function be(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xe(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function _e(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function we(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function ke(t){return[Math.atan2(t[1],t[0]),nt(t[2])]}function Ae(t,e){return wo(t[0]-e[0])s;++s)i.point((r=t[s])[0],r[1]);return void i.lineEnd()}var l=new Oe(r,t,null,!0),c=new Oe(r,null,l,!1);l.o=c,a.push(l),o.push(c),l=new Oe(n,t,null,!1),c=new Oe(n,null,l,!0),l.o=c,a.push(l),o.push(c)}}),o.sort(e),Re(a),Re(o),a.length){for(var s=0,l=r,c=o.length;c>s;++s)o[s].e=l=!l;for(var u,f,h=a[0];;){for(var d=h,p=!0;d.v;)if((d=d.n)===h)return;u=d.z,i.lineStart();do{if(d.v=d.o.v=!0,d.e){if(p)for(var s=0,c=u.length;c>s;++s)i.point((f=u[s])[0],f[1]);else n(d.x,d.n.x,1,i);d=d.n}else{if(p){u=d.p.z;for(var s=u.length-1;s>=0;--s)i.point((f=u[s])[0],f[1])}else n(d.x,d.p.x,-1,i);d=d.p}d=d.o,u=d.z,p=!p}while(!d.v);i.lineEnd()}}}function Re(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n0){for(_||(a.polygonStart(),_=!0),a.lineStart();++o1&&2&e&&r.push(r.pop().concat(r.shift())),d.push(r.filter(Ne))}var d,p,g,v=e(a),m=i.invert(n[0],n[1]),y={point:o,lineStart:l,lineEnd:c,polygonStart:function(){y.point=u,y.lineStart=f,y.lineEnd=h,d=[],p=[]},polygonEnd:function(){y.point=o,y.lineStart=l,y.lineEnd=c,d=co.merge(d);var t=Ve(m,p);d.length?(_||(a.polygonStart(),_=!0),Pe(d,Fe,t,r,a)):t&&(_||(a.polygonStart(),_=!0),a.lineStart(),r(null,null,1,a),a.lineEnd()),_&&(a.polygonEnd(),_=!1),d=p=null},sphere:function(){a.polygonStart(),a.lineStart(),r(null,null,1,a),a.lineEnd(),a.polygonEnd()}},b=je(),x=e(b),_=!1;return y}}function Ne(t){return t.length>1}function je(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:k,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Fe(t,e){return((t=t.x)[0]<0?t[1]-Ho-Do:Ho-t[1])-((e=e.x)[0]<0?e[1]-Ho-Do:Ho-e[1])}function De(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Uo:-Uo,l=wo(a-r);wo(l-Uo)0?Ho:-Ho),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Uo&&(wo(r-i)Do?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}function Ue(t,e,r,n){var i;if(null==t)i=r*Ho,n.point(-Uo,i),n.point(0,i),n.point(Uo,i),n.point(Uo,0),n.point(Uo,-i),n.point(0,-i),n.point(-Uo,-i),n.point(-Uo,0),n.point(-Uo,i);else if(wo(t[0]-e[0])>Do){var a=t[0]s;++s){var c=e[s],u=c.length;if(u)for(var f=c[0],h=f[0],d=f[1]/2+Uo/4,p=Math.sin(d),g=Math.cos(d),v=1;;){v===u&&(v=0),t=c[v];var m=t[0],y=t[1]/2+Uo/4,b=Math.sin(y),x=Math.cos(y),_=m-h,w=_>=0?1:-1,k=w*_,A=k>Uo,M=p*b;if(Es.add(Math.atan2(M*w*Math.sin(k),g*x+M*Math.cos(k))),a+=A?_+w*Vo:_,A^h>=r^m>=r){var T=be(me(f),me(t));we(T);var E=be(i,T);we(E);var L=(A^_>=0?-1:1)*nt(E[2]);(n>L||n===L&&(T[0]||T[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;h=m,p=b,g=x,f=t}}return(-Do>a||Do>a&&0>Es)^1&o}function qe(t){function e(t,e){return Math.cos(t)*Math.cos(e)>a}function r(t){var r,a,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(f,h){var d,p=[f,h],g=e(f,h),v=o?g?0:i(f,h):g?i(f+(0>f?Uo:-Uo),h):0;if(!r&&(c=l=g)&&t.lineStart(),g!==l&&(d=n(r,p),(Ae(r,d)||Ae(p,d))&&(p[0]+=Do,p[1]+=Do,g=e(p[0],p[1]))),g!==l)u=0,g?(t.lineStart(),d=n(p,r),t.point(d[0],d[1])):(d=n(r,p),t.point(d[0],d[1]),t.lineEnd()),r=d;else if(s&&r&&o^g){var m;v&a||!(m=n(p,r,!0))||(u=0,o?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||r&&Ae(r,p)||t.point(p[0],p[1]),r=p,l=g,a=v},lineEnd:function(){l&&t.lineEnd(),r=null},clean:function(){return u|(c&&l)<<1}}}function n(t,e,r){var n=me(t),i=me(e),o=[1,0,0],s=be(n,i),l=ye(s,s),c=s[0],u=l-c*c;if(!u)return!r&&t;var f=a*l/u,h=-a*c/u,d=be(o,s),p=_e(o,f),g=_e(s,h);xe(p,g);var v=d,m=ye(p,v),y=ye(v,v),b=m*m-y*(ye(p,p)-1);if(!(0>b)){var x=Math.sqrt(b),_=_e(v,(-m-x)/y);if(xe(_,p),_=ke(_),!r)return _;var w,k=t[0],A=e[0],M=t[1],T=e[1];k>A&&(w=k,k=A,A=w);var E=A-k,L=wo(E-Uo)E;if(!L&&M>T&&(w=M,M=T,T=w),S?L?M+T>0^_[1]<(wo(_[0]-k)Uo^(k<=_[0]&&_[0]<=A)){var C=_e(v,(-m+x)/y);return xe(C,p),[_,ke(C)]}}}function i(e,r){var n=o?t:Uo-t,i=0;return-n>e?i|=1:e>n&&(i|=2),-n>r?i|=4:r>n&&(i|=8),i}var a=Math.cos(t),o=a>0,s=wo(a)>Do,l=vr(t,6*Go);return Ie(e,r,l,o?[0,-t]:[-Uo,t-Uo])}function He(t,e,r,n){return function(i){var a,o=i.a,s=i.b,l=o.x,c=o.y,u=s.x,f=s.y,h=0,d=1,p=u-l,g=f-c;if(a=t-l,p||!(a>0)){if(a/=p,0>p){if(h>a)return;d>a&&(d=a)}else if(p>0){if(a>d)return;a>h&&(h=a)}if(a=r-l,p||!(0>a)){if(a/=p,0>p){if(a>d)return;a>h&&(h=a)}else if(p>0){if(h>a)return;d>a&&(d=a)}if(a=e-c,g||!(a>0)){if(a/=g,0>g){if(h>a)return;d>a&&(d=a)}else if(g>0){if(a>d)return;a>h&&(h=a)}if(a=n-c,g||!(0>a)){if(a/=g,0>g){if(a>d)return;a>h&&(h=a)}else if(g>0){if(h>a)return;d>a&&(d=a)}return h>0&&(i.a={x:l+h*p,y:c+h*g}),1>d&&(i.b={x:l+d*p,y:c+d*g}),i}}}}}}function Ge(t,e,r,n){function i(n,i){return wo(n[0]-t)0?0:3:wo(n[0]-r)0?2:1:wo(n[1]-e)0?1:0:i>0?3:2}function a(t,e){return o(t.x,e.x)}function o(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,r=v.length,n=t[1],i=0;r>i;++i)for(var a,o=1,s=v[i],l=s.length,c=s[0];l>o;++o)a=s[o],c[1]<=n?a[1]>n&&et(c,a,t)>0&&++e:a[1]<=n&&et(c,a,t)<0&&--e,c=a;return 0!==e}function c(a,s,l,c){var u=0,f=0;if(null==a||(u=i(a,l))!==(f=i(s,l))||o(a,s)<0^l>0){do c.point(0===u||3===u?t:r,u>1?n:e);while((u=(u+l+4)%4)!==f)}else c.point(s[0],s[1])}function u(i,a){return i>=t&&r>=i&&a>=e&&n>=a}function f(t,e){u(t,e)&&s.point(t,e)}function h(){S.point=p,v&&v.push(m=[]),A=!0,k=!1,_=w=NaN}function d(){g&&(p(y,b),x&&k&&E.rejoin(),g.push(E.buffer())),S.point=f,k&&s.lineEnd()}function p(t,e){t=Math.max(-Vs,Math.min(Vs,t)),e=Math.max(-Vs,Math.min(Vs,e));var r=u(t,e);if(v&&m.push([t,e]),A)y=t,b=e,x=r,A=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&k)s.point(t,e);else{var n={a:{x:_,y:w},b:{x:t,y:e}};L(n)?(k||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),M=!1):r&&(s.lineStart(),s.point(t,e),M=!1)}_=t,w=e,k=r}var g,v,m,y,b,x,_,w,k,A,M,T=s,E=je(),L=He(t,e,r,n),S={point:f,lineStart:h,lineEnd:d,polygonStart:function(){s=E,g=[],v=[],M=!0},polygonEnd:function(){s=T,g=co.merge(g);var e=l([t,n]),r=M&&e,i=g.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),c(null,null,1,s),s.lineEnd()),i&&Pe(g,a,e,c,s),s.polygonEnd()),g=v=m=null}};return S}}function Ye(t){var e=0,r=Uo/3,n=lr(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Uo/180,r=t[1]*Uo/180):[e/Uo*180,r/Uo*180]},i}function Xe(t,e){function r(t,e){var r=Math.sqrt(a-2*i*Math.sin(e))/i;return[r*Math.sin(t*=i),o-r*Math.cos(t)]}var n=Math.sin(t),i=(n+Math.sin(e))/2,a=1+n*(2*i-n),o=Math.sqrt(a)/i;return r.invert=function(t,e){var r=o-e;return[Math.atan2(t,r)/i,nt((a-(t*t+r*r)*i*i)/(2*i))]},r}function We(){function t(t,e){Hs+=i*t-n*e,n=t,i=e}var e,r,n,i;Zs.point=function(a,o){Zs.point=t,e=n=a,r=i=o},Zs.lineEnd=function(){t(e,r)}}function Ze(t,e){Gs>t&&(Gs=t),t>Xs&&(Xs=t),Ys>e&&(Ys=e),e>Ws&&(Ws=e)}function Ke(){function t(t,e){o.push("M",t,",",e,a)}function e(t,e){o.push("M",t,",",e),s.point=r}function r(t,e){o.push("L",t,",",e)}function n(){s.point=t}function i(){o.push("Z")}var a=$e(4.5),o=[],s={point:t,lineStart:function(){s.point=e},lineEnd:n,polygonStart:function(){s.lineEnd=i},polygonEnd:function(){s.lineEnd=n,s.point=t},pointRadius:function(t){return a=$e(t),s},result:function(){if(o.length){var t=o.join("");return o=[],t}}};return s}function $e(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Qe(t,e){zs+=t,Ps+=e,++Rs}function Je(){function t(t,n){var i=t-e,a=n-r,o=Math.sqrt(i*i+a*a);Os+=o*(e+t)/2,Is+=o*(r+n)/2,Ns+=o,Qe(e=t,r=n)}var e,r;$s.point=function(n,i){$s.point=t,Qe(e=n,r=i)}}function tr(){$s.point=Qe}function er(){function t(t,e){var r=t-n,a=e-i,o=Math.sqrt(r*r+a*a);Os+=o*(n+t)/2,Is+=o*(i+e)/2,Ns+=o,o=i*t-n*e,js+=o*(n+t),Fs+=o*(i+e),Ds+=3*o,Qe(n=t,i=e)}var e,r,n,i;$s.point=function(a,o){$s.point=t,Qe(e=n=a,r=i=o)},$s.lineEnd=function(){t(e,r)}}function rr(t){function e(e,r){t.moveTo(e+o,r),t.arc(e,r,o,0,Vo)}function r(e,r){t.moveTo(e,r),s.point=n}function n(e,r){t.lineTo(e,r)}function i(){s.point=e}function a(){t.closePath()}var o=4.5,s={point:e,lineStart:function(){s.point=r},lineEnd:i,polygonStart:function(){s.lineEnd=a},polygonEnd:function(){s.lineEnd=i,s.point=e},pointRadius:function(t){return o=t,s},result:k};return s}function nr(t){function e(t){return(s?n:r)(t)}function r(e){return or(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})}function n(e){function r(r,n){r=t(r,n),e.point(r[0],r[1])}function n(){b=NaN,A.point=a,e.lineStart()}function a(r,n){var a=me([r,n]),o=t(r,n);i(b,x,y,_,w,k,b=o[0],x=o[1],y=r,_=a[0],w=a[1],k=a[2],s,e),e.point(b,x)}function o(){A.point=r,e.lineEnd()}function l(){n(),A.point=c,A.lineEnd=u}function c(t,e){a(f=t,h=e),d=b,p=x,g=_,v=w,m=k,A.point=a}function u(){i(b,x,y,_,w,k,d,p,f,g,v,m,s,e),A.lineEnd=o,o()}var f,h,d,p,g,v,m,y,b,x,_,w,k,A={point:r,lineStart:n,lineEnd:o,polygonStart:function(){e.polygonStart(),A.lineStart=l},polygonEnd:function(){e.polygonEnd(),A.lineStart=n}};return A}function i(e,r,n,s,l,c,u,f,h,d,p,g,v,m){var y=u-e,b=f-r,x=y*y+b*b;if(x>4*a&&v--){var _=s+d,w=l+p,k=c+g,A=Math.sqrt(_*_+w*w+k*k),M=Math.asin(k/=A),T=wo(wo(k)-1)a||wo((y*C+b*z)/x-.5)>.3||o>s*d+l*p+c*g)&&(i(e,r,n,s,l,c,L,S,T,_/=A,w/=A,k,v,m),m.point(L,S),i(L,S,T,_,w,k,u,f,h,d,p,g,v,m))}}var a=.5,o=Math.cos(30*Go),s=16;return e.precision=function(t){return arguments.length?(s=(a=t*t)>0&&16,e):Math.sqrt(a)},e}function ir(t){var e=nr(function(e,r){return t([e*Yo,r*Yo])});return function(t){return cr(e(t))}}function ar(t){this.stream=t}function or(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){return t=s(t[0]*Go,t[1]*Go),[t[0]*h+l,c-t[1]*h]}function r(t){return t=s.invert((t[0]-l)/h,(c-t[1])/h),t&&[t[0]*Yo,t[1]*Yo]}function n(){s=Ce(o=hr(m,y,b),a);var t=a(g,v);return l=d-t[0]*h,c=p+t[1]*h,i()}function i(){return u&&(u.valid=!1,u=null),e}var a,o,s,l,c,u,f=nr(function(t,e){return t=a(t,e),[t[0]*h+l,c-t[1]*h]}),h=150,d=480,p=250,g=0,v=0,m=0,y=0,b=0,_=Us,w=x,k=null,A=null;return e.stream=function(t){return u&&(u.valid=!1),u=cr(_(o,f(w(t)))),u.valid=!0,u},e.clipAngle=function(t){return arguments.length?(_=null==t?(k=t,Us):qe((k=+t)*Go),i()):k},e.clipExtent=function(t){return arguments.length?(A=t,w=t?Ge(t[0][0],t[0][1],t[1][0],t[1][1]):x,i()):A},e.scale=function(t){return arguments.length?(h=+t,n()):h},e.translate=function(t){return arguments.length?(d=+t[0],p=+t[1],n()):[d,p]},e.center=function(t){return arguments.length?(g=t[0]%360*Go,v=t[1]%360*Go,n()):[g*Yo,v*Yo]},e.rotate=function(t){return arguments.length?(m=t[0]%360*Go,y=t[1]%360*Go,b=t.length>2?t[2]%360*Go:0,n()):[m*Yo,y*Yo,b*Yo]},co.rebind(e,f,"precision"),function(){return a=t.apply(this,arguments),e.invert=a.invert&&r,n()}}function cr(t){return or(t,function(e,r){t.point(e*Go,r*Go)})}function ur(t,e){return[t,e]}function fr(t,e){return[t>Uo?t-Vo:-Uo>t?t+Vo:t,e]}function hr(t,e,r){return t?e||r?Ce(pr(t),gr(e,r)):pr(t):e||r?gr(e,r):fr}function dr(t){return function(e,r){return e+=t,[e>Uo?e-Vo:-Uo>e?e+Vo:e,r]}}function pr(t){var e=dr(t);return e.invert=dr(-t),e}function gr(t,e){function r(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,c=Math.sin(e),u=c*n+s*i;return[Math.atan2(l*a-u*o,s*n-c*i),nt(u*a+l*o)]}var n=Math.cos(t),i=Math.sin(t),a=Math.cos(e),o=Math.sin(e);return r.invert=function(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,c=Math.sin(e),u=c*a-l*o;return[Math.atan2(l*a+c*o,s*n+u*i),nt(u*n-s*i)]},r}function vr(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=mr(r,i),a=mr(r,a),(o>0?a>i:i>a)&&(i+=o*Vo)):(i=t+o*Vo,a=t-.5*l);for(var c,u=i;o>0?u>a:a>u;u-=l)s.point((c=ke([r,-n*Math.cos(u),-n*Math.sin(u)]))[0],c[1])}}function mr(t,e){var r=me(e);r[0]-=t,we(r);var n=rt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-Do)%(2*Math.PI)}function yr(t,e,r){var n=co.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[t,e]})}}function br(t,e,r){var n=co.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[e,t]})}}function xr(t){return t.source}function _r(t){return t.target}function wr(t,e,r,n){var i=Math.cos(e),a=Math.sin(e),o=Math.cos(n),s=Math.sin(n),l=i*Math.cos(t),c=i*Math.sin(t),u=o*Math.cos(r),f=o*Math.sin(r),h=2*Math.asin(Math.sqrt(st(n-e)+i*o*st(r-t))),d=1/Math.sin(h),p=h?function(t){var e=Math.sin(t*=h)*d,r=Math.sin(h-t)*d,n=r*l+e*u,i=r*c+e*f,o=r*a+e*s;return[Math.atan2(i,n)*Yo,Math.atan2(o,Math.sqrt(n*n+i*i))*Yo]}:function(){return[t*Yo,e*Yo]};return p.distance=h,p}function kr(){function t(t,i){var a=Math.sin(i*=Go),o=Math.cos(i),s=wo((t*=Go)-e),l=Math.cos(s); -Qs+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=n*a-r*o*l)*s),r*a+n*o*l),e=t,r=a,n=o}var e,r,n;Js.point=function(i,a){e=i*Go,r=Math.sin(a*=Go),n=Math.cos(a),Js.point=t},Js.lineEnd=function(){Js.point=Js.lineEnd=k}}function Ar(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}function Mr(t,e){function r(t,e){o>0?-Ho+Do>e&&(e=-Ho+Do):e>Ho-Do&&(e=Ho-Do);var r=o/Math.pow(i(e),a);return[r*Math.sin(a*t),o-r*Math.cos(a*t)]}var n=Math.cos(t),i=function(t){return Math.tan(Uo/4+t/2)},a=t===e?Math.sin(t):Math.log(n/Math.cos(e))/Math.log(i(e)/i(t)),o=n*Math.pow(i(t),a)/a;return a?(r.invert=function(t,e){var r=o-e,n=tt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(o/n,1/a))-Ho]},r):Er}function Tr(t,e){function r(t,e){var r=a-e;return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}var n=Math.cos(t),i=t===e?Math.sin(t):(n-Math.cos(e))/(e-t),a=n/i+t;return wo(i)i;i++){for(;n>1&&et(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function Rr(t,e){return t[0]-e[0]||t[1]-e[1]}function Or(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function Ir(t,e,r,n){var i=t[0],a=r[0],o=e[0]-i,s=n[0]-a,l=t[1],c=r[1],u=e[1]-l,f=n[1]-c,h=(s*(l-c)-f*(i-a))/(f*o-s*u);return[i+h*o,l+h*u]}function Nr(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}function jr(){an(this),this.edge=this.site=this.circle=null}function Fr(t){var e=fl.pop()||new jr;return e.site=t,e}function Dr(t){Zr(t),ll.remove(t),fl.push(t),an(t)}function Br(t){var e=t.circle,r=e.x,n=e.cy,i={x:r,y:n},a=t.P,o=t.N,s=[t];Dr(t);for(var l=a;l.circle&&wo(r-l.circle.x)u;++u)c=s[u],l=s[u-1],en(c.edge,l.site,c.site,i);l=s[0],c=s[f-1],c.edge=Jr(l.site,c.site,null,i),Wr(l),Wr(c)}function Ur(t){for(var e,r,n,i,a=t.x,o=t.y,s=ll._;s;)if(n=Vr(s,o)-a,n>Do)s=s.L;else{if(i=a-qr(s,o),!(i>Do)){n>-Do?(e=s.P,r=s):i>-Do?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=Fr(t);if(ll.insert(e,l),e||r){if(e===r)return Zr(e),r=Fr(e.site),ll.insert(l,r),l.edge=r.edge=Jr(e.site,l.site),Wr(e),void Wr(r);if(!r)return void(l.edge=Jr(e.site,l.site));Zr(e),Zr(r);var c=e.site,u=c.x,f=c.y,h=t.x-u,d=t.y-f,p=r.site,g=p.x-u,v=p.y-f,m=2*(h*v-d*g),y=h*h+d*d,b=g*g+v*v,x={x:(v*y-d*b)/m+u,y:(h*b-g*y)/m+f};en(r.edge,c,p,x),l.edge=Jr(c,t,null,x),r.edge=Jr(t,p,null,x),Wr(e),Wr(r)}}function Vr(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-(1/0);r=o.site;var s=r.x,l=r.y,c=l-e;if(!c)return s;var u=s-n,f=1/a-1/c,h=u/c;return f?(-h+Math.sqrt(h*h-2*f*(u*u/(-2*c)-l+c/2+i-a/2)))/f+n:(n+s)/2}function qr(t,e){var r=t.N;if(r)return Vr(r,e);var n=t.site;return n.y===e?n.x:1/0}function Hr(t){this.site=t,this.edges=[]}function Gr(t){for(var e,r,n,i,a,o,s,l,c,u,f=t[0][0],h=t[1][0],d=t[0][1],p=t[1][1],g=sl,v=g.length;v--;)if(a=g[v],a&&a.prepare())for(s=a.edges,l=s.length,o=0;l>o;)u=s[o].end(),n=u.x,i=u.y,c=s[++o%l].start(),e=c.x,r=c.y,(wo(n-e)>Do||wo(i-r)>Do)&&(s.splice(o,0,new rn(tn(a.site,u,wo(n-f)Do?{x:f,y:wo(e-f)Do?{x:wo(r-p)Do?{x:h,y:wo(e-h)Do?{x:wo(r-d)=-Bo)){var d=l*l+c*c,p=u*u+f*f,g=(f*d-c*p)/h,v=(l*p-u*d)/h,f=v+s,m=hl.pop()||new Xr;m.arc=t,m.site=i,m.x=g+o,m.y=f+Math.sqrt(g*g+v*v),m.cy=f,t.circle=m;for(var y=null,b=ul._;b;)if(m.yv||v>=s)return;if(h>p){if(a){if(a.y>=c)return}else a={x:v,y:l};r={x:v,y:c}}else{if(a){if(a.yn||n>1)if(h>p){if(a){if(a.y>=c)return}else a={x:(l-i)/n,y:l};r={x:(c-i)/n,y:c}}else{if(a){if(a.yd){if(a){if(a.x>=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xa||f>o||n>h||i>d)){if(p=t.point){var p,g=e-t.x,v=r-t.y,m=g*g+v*v;if(l>m){var y=Math.sqrt(l=m);n=e-y,i=r-y,a=e+y,o=r+y,s=p}}for(var b=t.nodes,x=.5*(u+h),_=.5*(f+d),w=e>=x,k=r>=_,A=k<<1|w,M=A+4;M>A;++A)if(t=b[3&A])switch(3&A){case 0:c(t,u,f,x,_);break;case 1:c(t,x,f,h,_);break;case 2:c(t,u,_,x,d);break;case 3:c(t,x,_,h,d)}}}(t,n,i,a,o),s}function mn(t,e){t=co.rgb(t),e=co.rgb(e);var r=t.r,n=t.g,i=t.b,a=e.r-r,o=e.g-n,s=e.b-i;return function(t){return"#"+wt(Math.round(r+a*t))+wt(Math.round(n+o*t))+wt(Math.round(i+s*t))}}function yn(t,e){var r,n={},i={};for(r in t)r in e?n[r]=_n(t[r],e[r]):i[r]=t[r];for(r in e)r in t||(i[r]=e[r]);return function(t){for(r in n)i[r]=n[r](t);return i}}function bn(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function xn(t,e){var r,n,i,a=pl.lastIndex=gl.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=pl.exec(t))&&(n=gl.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:bn(r,n)})),a=gl.lastIndex;return an;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}function _n(t,e){for(var r,n=co.interpolators.length;--n>=0&&!(r=co.interpolators[n](t,e)););return r}function wn(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;s>r;++r)n.push(_n(t[r],e[r]));for(;a>r;++r)i[r]=t[r];for(;o>r;++r)i[r]=e[r];return function(t){for(r=0;s>r;++r)i[r]=n[r](t);return i}}function kn(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function An(t){return function(e){return 1-t(1-e)}}function Mn(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Tn(t){return t*t}function En(t){return t*t*t}function Ln(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(.5>t?r:3*(t-e)+r-.75)}function Sn(t){return function(e){return Math.pow(e,t)}}function Cn(t){return 1-Math.cos(t*Ho)}function zn(t){return Math.pow(2,10*(t-1))}function Pn(t){return 1-Math.sqrt(1-t*t)}function Rn(t,e){var r;return arguments.length<2&&(e=.45),arguments.length?r=e/Vo*Math.asin(1/t):(t=1,r=e/4),function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*Vo/e)}}function On(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}}function In(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function Nn(t,e){t=co.hcl(t),e=co.hcl(e);var r=t.h,n=t.c,i=t.l,a=e.h-r,o=e.c-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.c:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ht(r+a*t,n+o*t,i+s*t)+""}}function jn(t,e){t=co.hsl(t),e=co.hsl(e);var r=t.h,n=t.s,i=t.l,a=e.h-r,o=e.s-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.s:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ut(r+a*t,n+o*t,i+s*t)+""}}function Fn(t,e){t=co.lab(t),e=co.lab(e);var r=t.l,n=t.a,i=t.b,a=e.l-r,o=e.a-n,s=e.b-i;return function(t){return pt(r+a*t,n+o*t,i+s*t)+""}}function Dn(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function Bn(t){var e=[t.a,t.b],r=[t.c,t.d],n=Vn(e),i=Un(e,r),a=Vn(qn(r,e,-i))||0;e[0]*r[1]180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(Hn(r)+"rotate(",null,")")-2,x:bn(t,e)})):e&&r.push(Hn(r)+"rotate("+e+")")}function Xn(t,e,r,n){t!==e?n.push({i:r.push(Hn(r)+"skewX(",null,")")-2,x:bn(t,e)}):e&&r.push(Hn(r)+"skewX("+e+")")}function Wn(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(Hn(r)+"scale(",null,",",null,")");n.push({i:i-4,x:bn(t[0],e[0])},{i:i-2,x:bn(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(Hn(r)+"scale("+e+")")}function Zn(t,e){var r=[],n=[];return t=co.transform(t),e=co.transform(e),Gn(t.translate,e.translate,r,n),Yn(t.rotate,e.rotate,r,n),Xn(t.skew,e.skew,r,n),Wn(t.scale,e.scale,r,n),t=e=null,function(t){for(var e,i=-1,a=n.length;++i=0;)r.push(i[n])}function li(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++or;++r)(e=t[r][1])>i&&(n=r,i=e);return n}function bi(t){return t.reduce(xi,0)}function xi(t,e){return t+e[1]}function _i(t,e){return wi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function wi(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function ki(t){return[co.min(t),co.max(t)]}function Ai(t,e){return t.value-e.value}function Mi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ti(t,e){t._pack_next=e,e._pack_prev=t}function Ei(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Li(t){function e(t){u=Math.min(t.x-t.r,u),f=Math.max(t.x+t.r,f),h=Math.min(t.y-t.r,h),d=Math.max(t.y+t.r,d)}if((r=t.children)&&(c=r.length)){var r,n,i,a,o,s,l,c,u=1/0,f=-(1/0),h=1/0,d=-(1/0);if(r.forEach(Si),n=r[0],n.x=-n.r,n.y=0,e(n),c>1&&(i=r[1],i.x=i.r,i.y=0,e(i),c>2))for(a=r[2],Pi(n,i,a),e(a),Mi(n,a),n._pack_prev=a,Mi(a,i),i=n._pack_next,o=3;c>o;o++){Pi(n,i,a=r[o]);var p=0,g=1,v=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(Ei(s,a)){p=1;break}if(1==p)for(l=n._pack_prev;l!==s._pack_prev&&!Ei(l,a);l=l._pack_prev,v++);p?(v>g||g==v&&i.ro;o++)a=r[o],a.x-=m,a.y-=y,b=Math.max(b,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=b,r.forEach(Ci)}}function Si(t){t._pack_next=t._pack_prev=t}function Ci(t){delete t._pack_next,delete t._pack_prev}function zi(t,e,r,n){var i=t.children;if(t.x=e+=n*t.x,t.y=r+=n*t.y,t.r*=n,i)for(var a=-1,o=i.length;++a=0;)e=i[a],e.z+=r,e.m+=r,r+=e.s+(n+=e.c)}function Fi(t,e,r){return t.a.parent===e.parent?t.a:r}function Di(t){return 1+co.max(t,function(t){return t.y})}function Bi(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Ui(t){var e=t.children;return e&&e.length?Ui(e[0]):t}function Vi(t){var e,r=t.children;return r&&(e=r.length)?Vi(r[e-1]):t}function qi(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Hi(t,e){var r=t.x+e[3],n=t.y+e[0],i=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return 0>i&&(r+=i/2,i=0),0>a&&(n+=a/2,a=0),{x:r,y:n,dx:i,dy:a}}function Gi(t){var e=t[0],r=t[t.length-1];return r>e?[e,r]:[r,e]}function Yi(t){return t.rangeExtent?t.rangeExtent():Gi(t.range())}function Xi(t,e,r,n){var i=r(t[0],t[1]),a=n(e[0],e[1]);return function(t){return a(i(t))}}function Wi(t,e){var r,n=0,i=t.length-1,a=t[n],o=t[i];return a>o&&(r=n,n=i,i=r,r=a,a=o,o=r),t[n]=e.floor(a),t[i]=e.ceil(o),t}function Zi(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:Tl}function Ki(t,e,r,n){var i=[],a=[],o=0,s=Math.min(t.length,e.length)-1;for(t[s]2?Ki:Xi,l=n?$n:Kn;return o=i(t,e,l,r),s=i(e,t,l,_n),a}function a(t){return o(t)}var o,s;return a.invert=function(t){return s(t)},a.domain=function(e){return arguments.length?(t=e.map(Number),i()):t},a.range=function(t){return arguments.length?(e=t,i()):e},a.rangeRound=function(t){return a.range(t).interpolate(Dn)},a.clamp=function(t){return arguments.length?(n=t,i()):n},a.interpolate=function(t){return arguments.length?(r=t,i()):r},a.ticks=function(e){return ea(t,e)},a.tickFormat=function(e,r){return ra(t,e,r)},a.nice=function(e){return Ji(t,e),i()},a.copy=function(){return $i(t,e,r,n)},i()}function Qi(t,e){return co.rebind(t,e,"range","rangeRound","interpolate","clamp")}function Ji(t,e){return Wi(t,Zi(ta(t,e)[2])),Wi(t,Zi(ta(t,e)[2])),t}function ta(t,e){null==e&&(e=10);var r=Gi(t),n=r[1]-r[0],i=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),a=e/n*i;return.15>=a?i*=10:.35>=a?i*=5:.75>=a&&(i*=2),r[0]=Math.ceil(r[0]/i)*i,r[1]=Math.floor(r[1]/i)*i+.5*i,r[2]=i,r}function ea(t,e){return co.range.apply(co,ta(t,e))}function ra(t,e,r){var n=ta(t,e);if(r){var i=ps.exec(r);if(i.shift(),"s"===i[8]){var a=co.formatPrefix(Math.max(wo(n[0]),wo(n[1])));return i[7]||(i[7]="."+na(a.scale(n[2]))),i[8]="f",r=co.format(i.join("")),function(t){return r(a.scale(t))+a.symbol}}i[7]||(i[7]="."+ia(i[8],n)),r=i.join("")}else r=",."+na(n[2])+"f";return co.format(r)}function na(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function ia(t,e){var r=na(e[2]);return t in El?Math.abs(r-na(Math.max(wo(e[0]),wo(e[1]))))+ +("e"!==t):r-2*("%"===t)}function aa(t,e,r,n){function i(t){return(r?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function a(t){return r?Math.pow(e,t):-Math.pow(e,-t)}function o(e){return t(i(e))}return o.invert=function(e){return a(t.invert(e))},o.domain=function(e){return arguments.length?(r=e[0]>=0,t.domain((n=e.map(Number)).map(i)),o):n},o.base=function(r){return arguments.length?(e=+r,t.domain(n.map(i)),o):e},o.nice=function(){var e=Wi(n.map(i),r?Math:Sl);return t.domain(e),n=e.map(a),o},o.ticks=function(){var t=Gi(n),o=[],s=t[0],l=t[1],c=Math.floor(i(s)),u=Math.ceil(i(l)),f=e%1?2:e;if(isFinite(u-c)){if(r){for(;u>c;c++)for(var h=1;f>h;h++)o.push(a(c)*h);o.push(a(c))}else for(o.push(a(c));c++0;h--)o.push(a(c)*h);for(c=0;o[c]l;u--);o=o.slice(c,u)}return o},o.tickFormat=function(t,r){if(!arguments.length)return Ll;arguments.length<2?r=Ll:"function"!=typeof r&&(r=co.format(r));var n=Math.max(1,e*t/o.ticks().length);return function(t){var o=t/a(Math.round(i(t)));return e-.5>o*e&&(o*=e),n>=o?r(t):""}},o.copy=function(){return aa(t.copy(),e,r,n)},Qi(o,t)}function oa(t,e,r){function n(e){return t(i(e))}var i=sa(e),a=sa(1/e);return n.invert=function(e){return a(t.invert(e))},n.domain=function(e){return arguments.length?(t.domain((r=e.map(Number)).map(i)),n):r},n.ticks=function(t){return ea(r,t)},n.tickFormat=function(t,e){return ra(r,t,e)},n.nice=function(t){return n.domain(Ji(r,t))},n.exponent=function(o){return arguments.length?(i=sa(e=o),a=sa(1/e),t.domain(r.map(i)),n):e},n.copy=function(){return oa(t.copy(),e,r)},Qi(n,t)}function sa(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function la(t,e){function r(r){return a[((i.get(r)||("range"===e.t?i.set(r,t.push(r)):NaN))-1)%a.length]}function n(e,r){return co.range(t.length).map(function(t){return e+r*t})}var i,a,o;return r.domain=function(n){if(!arguments.length)return t;t=[],i=new f;for(var a,o=-1,s=n.length;++or?[NaN,NaN]:[r>0?s[r-1]:t[0],re?NaN:e/a+t,[e,e+1/a]},n.copy=function(){return ua(t,e,r)},i()}function fa(t,e){function r(r){return r>=r?e[co.bisect(t,r)]:void 0}return r.domain=function(e){return arguments.length?(t=e,r):t},r.range=function(t){return arguments.length?(e=t,r):e},r.invertExtent=function(r){return r=e.indexOf(r),[t[r-1],t[r]]},r.copy=function(){return fa(t,e)},r}function ha(t){function e(t){return+t}return e.invert=e,e.domain=e.range=function(r){return arguments.length?(t=r.map(e),e):t},e.ticks=function(e){return ea(t,e)},e.tickFormat=function(e,r){return ra(t,e,r)},e.copy=function(){return ha(t)},e}function da(){return 0}function pa(t){return t.innerRadius}function ga(t){return t.outerRadius}function va(t){return t.startAngle}function ma(t){return t.endAngle}function ya(t){return t&&t.padAngle}function ba(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function xa(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,c=-s*a,u=t[0]+l,f=t[1]+c,h=e[0]+l,d=e[1]+c,p=(u+h)/2,g=(f+d)/2,v=h-u,m=d-f,y=v*v+m*m,b=r-n,x=u*d-h*f,_=(0>m?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,k=(-x*v-m*_)/y,A=(x*m+v*_)/y,M=(-x*v+m*_)/y,T=w-p,E=k-g,L=A-p,S=M-g;return T*T+E*E>L*L+S*S&&(w=A,k=M),[[w-l,k-c],[w*r/b,k*r/b]]}function _a(t){function e(e){function o(){c.push("M",a(t(u),s))}for(var l,c=[],u=[],f=-1,h=e.length,d=Lt(r),p=Lt(n);++f1?t.join("L"):t+"Z"}function ka(t){return t.join("L")+"Z"}function Aa(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1&&i.push("H",n[0]),i.join("")}function Ma(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var c=2;c9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));for(s=-1;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}function Ua(t){return t.length<3?wa(t):t[0]+Ca(t,Ba(t))}function Va(t){for(var e,r,n,i=-1,a=t.length;++i=e?o(t-e):void(c.c=o)}function o(r){var i=p.active,a=p[i];a&&(a.timer.c=null,a.timer.t=NaN,--p.count,delete p[i],a.event&&a.event.interrupt.call(t,t.__data__,a.index));for(var o in p)if(n>+o){var f=p[o];f.timer.c=null,f.timer.t=NaN,--p.count,delete p[o]}c.c=s,Rt(function(){return c.c&&s(r||1)&&(c.c=null,c.t=NaN),1},0,l),p.active=n,g.event&&g.event.start.call(t,t.__data__,e),d=[],g.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&d.push(n)}),h=g.ease,u=g.duration}function s(i){for(var a=i/u,o=h(a),s=d.length;s>0;)d[--s].call(t,o);return a>=1?(g.event&&g.event.end.call(t,t.__data__,e),--p.count?delete p[n]:delete t[r],1):void 0}var l,c,u,h,d,p=t[r]||(t[r]={active:0,count:0}),g=p[n];g||(l=i.time,c=Rt(a,0,l),g=p[n]={tween:new f,time:l,timer:c,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++p.count)}function ro(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function no(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}function io(t){return t.toISOString()}function ao(t,e,r){function n(e){return t(e)}function i(t,r){var n=t[1]-t[0],i=n/r,a=co.bisect(tc,i);return a==tc.length?[e.year,ta(t.map(function(t){return t/31536e6}),r)[2]]:a?e[i/tc[a-1]1?{floor:function(e){for(;r(e=t.floor(e));)e=oo(e-1);return e},ceil:function(e){for(;r(e=t.ceil(e));)e=oo(+e+1);return e}}:t))},n.ticks=function(t,e){var r=Gi(n.domain()),a=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return a&&(t=a[0],e=a[1]),t.range(r[0],oo(+r[1]+1),1>e?1:e)},n.tickFormat=function(){return r},n.copy=function(){return ao(t.copy(),e,r)},Qi(n,t)}function oo(t){return new Date(t)}function so(t){return JSON.parse(t.responseText)}function lo(t){var e=ho.createRange();return e.selectNode(ho.body),e.createContextualFragment(t.responseText)}var co={version:"3.5.16"},uo=[].slice,fo=function(t){return uo.call(t); -},ho=this.document;if(ho)try{fo(ho.documentElement.childNodes)[0].nodeType}catch(po){fo=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),ho)try{ho.createElement("DIV").style.setProperty("opacity",0,"")}catch(go){var vo=this.Element.prototype,mo=vo.setAttribute,yo=vo.setAttributeNS,bo=this.CSSStyleDeclaration.prototype,xo=bo.setProperty;vo.setAttribute=function(t,e){mo.call(this,t,e+"")},vo.setAttributeNS=function(t,e,r){yo.call(this,t,e,r+"")},bo.setProperty=function(t,e,r){xo.call(this,t,e+"",r)}}co.ascending=i,co.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:NaN},co.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},co.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},co.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}else{for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}return[r,i]},co.sum=function(t,e){var r,n=0,i=t.length,a=-1;if(1===arguments.length)for(;++a1?l/(u-1):void 0},co.deviation=function(){var t=co.variance.apply(this,arguments);return t?Math.sqrt(t):t};var _o=s(i);co.bisectLeft=_o.left,co.bisect=co.bisectRight=_o.right,co.bisector=function(t){return s(1===t.length?function(e,r){return i(t(e),r)}:t)},co.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,2>a&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},co.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},co.pairs=function(t){for(var e,r=0,n=t.length-1,i=t[0],a=new Array(0>n?0:n);n>r;)a[r]=[e=i,i=t[++r]];return a},co.transpose=function(t){if(!(i=t.length))return[];for(var e=-1,r=co.min(t,l),n=new Array(r);++e=0;)for(n=t[i],e=n.length;--e>=0;)r[--o]=n[e];return r};var wo=Math.abs;co.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r===1/0)throw new Error("infinite range");var n,i=[],a=c(wo(r)),o=-1;if(t*=a,e*=a,r*=a,0>r)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=a.length)return n?n.call(i,o):r?o.sort(r):o;for(var l,c,u,h,d=-1,p=o.length,g=a[s++],v=new f;++d=a.length)return t;var n=[],i=o[r++];return t.forEach(function(t,i){n.push({key:t,values:e(i,r)})}),i?n.sort(function(t,e){return i(t.key,e.key)}):n}var r,n,i={},a=[],o=[];return i.map=function(e,r){return t(r,e,0)},i.entries=function(r){return e(t(co.map,r,0),0)},i.key=function(t){return a.push(t),i},i.sortKeys=function(t){return o[a.length-1]=t,i},i.sortValues=function(t){return r=t,i},i.rollup=function(t){return n=t,i},i},co.set=function(t){var e=new b;if(t)for(var r=0,n=t.length;n>r;++r)e.add(t[r]);return e},u(b,{has:p,add:function(t){return this._[h(t+="")]=!0,t},remove:g,values:v,size:m,empty:y,forEach:function(t){for(var e in this._)t.call(this,d(e))}}),co.behavior={},co.rebind=function(t,e){for(var r,n=1,i=arguments.length;++n=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},co.event=null,co.requote=function(t){return t.replace(To,"\\$&")};var To=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Eo={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]},Lo=function(t,e){return e.querySelector(t)},So=function(t,e){return e.querySelectorAll(t)},Co=function(t,e){var r=t.matches||t[w(t,"matchesSelector")];return(Co=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(Lo=function(t,e){return Sizzle(t,e)[0]||null},So=Sizzle,Co=Sizzle.matchesSelector),co.selection=function(){return co.select(ho.documentElement)};var zo=co.selection.prototype=[];zo.select=function(t){var e,r,n,i,a=[];t=C(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),Ro.hasOwnProperty(r)?{space:Ro[r],local:t}:t}},zo.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node();return t=co.ns.qualify(t),t.local?r.getAttributeNS(t.space,t.local):r.getAttribute(t)}for(e in t)this.each(P(e,t[e]));return this}return this.each(P(t,e))},zo.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=I(t)).length,i=-1;if(e=r.classList){for(;++ii){if("string"!=typeof t){2>i&&(e="");for(r in t)this.each(F(r,t[r],e));return this}if(2>i){var a=this.node();return n(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(F(t,e,r))},zo.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(D(e,t[e]));return this}return this.each(D(t,e))},zo.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},zo.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},zo.append=function(t){return t=B(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},zo.insert=function(t,e){return t=B(t),e=C(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},zo.remove=function(){return this.each(U)},zo.data=function(t,e){function r(t,r){var n,i,a,o=t.length,u=r.length,h=Math.min(o,u),d=new Array(u),p=new Array(u),g=new Array(o);if(e){var v,m=new f,y=new Array(o);for(n=-1;++nn;++n)p[n]=V(r[n]);for(;o>n;++n)g[n]=t[n]}p.update=d,p.parentNode=d.parentNode=g.parentNode=t.parentNode,s.push(p),l.push(d),c.push(g)}var n,i,a=-1,o=this.length;if(!arguments.length){for(t=new Array(o=(n=this[0]).length);++aa;a++){i.push(e=[]),e.parentNode=(r=this[a]).parentNode;for(var s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return S(i)},zo.order=function(){for(var t=-1,e=this.length;++t=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},zo.sort=function(t){t=H.apply(this,arguments);for(var e=-1,r=this.length;++et;t++)for(var r=this[t],n=0,i=r.length;i>n;n++){var a=r[n];if(a)return a}return null},zo.size=function(){var t=0;return G(this,function(){++t}),t};var Oo=[];co.selection.enter=Y,co.selection.enter.prototype=Oo,Oo.append=zo.append,Oo.empty=zo.empty,Oo.node=zo.node,Oo.call=zo.call,Oo.size=zo.size,Oo.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++sn){if("string"!=typeof t){2>n&&(e=!1);for(r in t)this.each(W(r,t[r],e));return this}if(2>n)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(W(t,e,r))};var Io=co.map({mouseenter:"mouseover",mouseleave:"mouseout"});ho&&Io.forEach(function(t){"on"+t in ho&&Io.remove(t)});var No,jo=0;co.mouse=function(t){return Q(t,E())};var Fo=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;co.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=E().changedTouches),e)for(var n,i=0,a=e.length;a>i;++i)if((n=e[i]).identifier===r)return Q(t,n)},co.behavior.drag=function(){function t(){this.on("mousedown.drag",a).on("touchstart.drag",o)}function e(t,e,n,a,o){return function(){function s(){var t,r,n=e(h,g);n&&(t=n[0]-b[0],r=n[1]-b[1],p|=t|r,b=n,d({type:"drag",x:n[0]+c[0],y:n[1]+c[1],dx:t,dy:r}))}function l(){e(h,g)&&(m.on(a+v,null).on(o+v,null),y(p),d({type:"dragend"}))}var c,u=this,f=co.event.target.correspondingElement||co.event.target,h=u.parentNode,d=r.of(u,arguments),p=0,g=t(),v=".drag"+(null==g?"":"-"+g),m=co.select(n(f)).on(a+v,s).on(o+v,l),y=$(f),b=e(h,g);i?(c=i.apply(u,arguments),c=[c.x-b[0],c.y-b[1]]):c=[0,0],d({type:"dragstart"})}}var r=L(t,"drag","dragstart","dragend"),i=null,a=e(k,co.mouse,n,"mousemove","mouseup"),o=e(J,co.touch,x,"touchmove","touchend");return t.origin=function(e){return arguments.length?(i=e,t):i},co.rebind(t,r,"on")},co.touches=function(t,e){return arguments.length<2&&(e=E().touches),e?fo(e).map(function(e){var r=Q(t,e);return r.identifier=e.identifier,r}):[]};var Do=1e-6,Bo=Do*Do,Uo=Math.PI,Vo=2*Uo,qo=Vo-Do,Ho=Uo/2,Go=Uo/180,Yo=180/Uo,Xo=Math.SQRT2,Wo=2,Zo=4;co.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],c=e[2],u=s-i,f=l-a,h=u*u+f*f;if(Bo>h)n=Math.log(c/o)/Xo,r=function(t){return[i+t*u,a+t*f,o*Math.exp(Xo*t*n)]};else{var d=Math.sqrt(h),p=(c*c-o*o+Zo*h)/(2*o*Wo*d),g=(c*c-o*o-Zo*h)/(2*c*Wo*d),v=Math.log(Math.sqrt(p*p+1)-p),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/Xo,r=function(t){var e=t*n,r=at(v),s=o/(Wo*d)*(r*ot(Xo*e+v)-it(v));return[i+s*u,a+s*f,o*r/at(Xo*e+v)]}}return r.duration=1e3*n,r},co.behavior.zoom=function(){function t(t){t.on(z,f).on($o+".zoom",d).on("dblclick.zoom",p).on(O,h)}function e(t){return[(t[0]-A.x)/A.k,(t[1]-A.y)/A.k]}function r(t){return[t[0]*A.k+A.x,t[1]*A.k+A.y]}function i(t){A.k=Math.max(E[0],Math.min(E[1],t))}function a(t,e){e=r(e),A.x+=t[0]-e[0],A.y+=t[1]-e[1]}function o(e,r,n,o){e.__chart__={x:A.x,y:A.y,k:A.k},i(Math.pow(2,o)),a(v=r,n),e=co.select(e),S>0&&(e=e.transition().duration(S)),e.call(t.event)}function s(){_&&_.domain(x.range().map(function(t){return(t-A.x)/A.k}).map(x.invert)),k&&k.domain(w.range().map(function(t){return(t-A.y)/A.k}).map(w.invert))}function l(t){C++||t({type:"zoomstart"})}function c(t){s(),t({type:"zoom",scale:A.k,translate:[A.x,A.y]})}function u(t){--C||(t({type:"zoomend"}),v=null)}function f(){function t(){s=1,a(co.mouse(i),h),c(o)}function r(){f.on(P,null).on(R,null),d(s),u(o)}var i=this,o=I.of(i,arguments),s=0,f=co.select(n(i)).on(P,t).on(R,r),h=e(co.mouse(i)),d=$(i);Hl.call(i),l(o)}function h(){function t(){var t=co.touches(p);return d=A.k,t.forEach(function(t){t.identifier in v&&(v[t.identifier]=e(t))}),t}function r(){var e=co.event.target;co.select(e).on(x,n).on(_,s),w.push(e);for(var r=co.event.changedTouches,i=0,a=r.length;a>i;++i)v[r[i].identifier]=null;var l=t(),c=Date.now();if(1===l.length){if(500>c-b){var u=l[0];o(p,u,v[u.identifier],Math.floor(Math.log(A.k)/Math.LN2)+1),T()}b=c}else if(l.length>1){var u=l[0],f=l[1],h=u[0]-f[0],d=u[1]-f[1];m=h*h+d*d}}function n(){var t,e,r,n,o=co.touches(p);Hl.call(p);for(var s=0,l=o.length;l>s;++s,n=null)if(r=o[s],n=v[r.identifier]){if(e)break;t=r,e=n}if(n){var u=(u=r[0]-t[0])*u+(u=r[1]-t[1])*u,f=m&&Math.sqrt(u/m);t=[(t[0]+r[0])/2,(t[1]+r[1])/2],e=[(e[0]+n[0])/2,(e[1]+n[1])/2],i(f*d)}b=null,a(t,e),c(g)}function s(){if(co.event.touches.length){for(var e=co.event.changedTouches,r=0,n=e.length;n>r;++r)delete v[e[r].identifier];for(var i in v)return void t()}co.selectAll(w).on(y,null),k.on(z,f).on(O,h),M(),u(g)}var d,p=this,g=I.of(p,arguments),v={},m=0,y=".zoom-"+co.event.changedTouches[0].identifier,x="touchmove"+y,_="touchend"+y,w=[],k=co.select(p),M=$(p);r(),l(g),k.on(z,null).on(O,r)}function d(){var t=I.of(this,arguments);y?clearTimeout(y):(Hl.call(this),g=e(v=m||co.mouse(this)),l(t)),y=setTimeout(function(){y=null,u(t)},50),T(),i(Math.pow(2,.002*Ko())*A.k),a(v,g),c(t)}function p(){var t=co.mouse(this),r=Math.log(A.k)/Math.LN2;o(this,t,e(t),co.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}var g,v,m,y,b,x,_,w,k,A={x:0,y:0,k:1},M=[960,500],E=Qo,S=250,C=0,z="mousedown.zoom",P="mousemove.zoom",R="mouseup.zoom",O="touchstart.zoom",I=L(t,"zoomstart","zoom","zoomend");return $o||($o="onwheel"in ho?(Ko=function(){return-co.event.deltaY*(co.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ho?(Ko=function(){return co.event.wheelDelta},"mousewheel"):(Ko=function(){return-co.event.detail},"MozMousePixelScroll")),t.event=function(t){t.each(function(){var t=I.of(this,arguments),e=A;Vl?co.select(this).transition().each("start.zoom",function(){A=this.__chart__||{x:0,y:0,k:1},l(t)}).tween("zoom:zoom",function(){var r=M[0],n=M[1],i=v?v[0]:r/2,a=v?v[1]:n/2,o=co.interpolateZoom([(i-A.x)/A.k,(a-A.y)/A.k,r/A.k],[(i-e.x)/e.k,(a-e.y)/e.k,r/e.k]);return function(e){var n=o(e),s=r/n[2];this.__chart__=A={x:i-n[0]*s,y:a-n[1]*s,k:s},c(t)}}).each("interrupt.zoom",function(){u(t)}).each("end.zoom",function(){u(t)}):(this.__chart__=A,l(t),c(t),u(t))})},t.translate=function(e){return arguments.length?(A={x:+e[0],y:+e[1],k:A.k},s(),t):[A.x,A.y]},t.scale=function(e){return arguments.length?(A={x:A.x,y:A.y,k:null},i(+e),s(),t):A.k},t.scaleExtent=function(e){return arguments.length?(E=null==e?Qo:[+e[0],+e[1]],t):E},t.center=function(e){return arguments.length?(m=e&&[+e[0],+e[1]],t):m},t.size=function(e){return arguments.length?(M=e&&[+e[0],+e[1]],t):M},t.duration=function(e){return arguments.length?(S=+e,t):S},t.x=function(e){return arguments.length?(_=e,x=e.copy(),A={x:0,y:0,k:1},t):_},t.y=function(e){return arguments.length?(k=e,w=e.copy(),A={x:0,y:0,k:1},t):k},co.rebind(t,I,"on")};var Ko,$o,Qo=[0,1/0];co.color=lt,lt.prototype.toString=function(){return this.rgb()+""},co.hsl=ct;var Jo=ct.prototype=new lt;Jo.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new ct(this.h,this.s,this.l/t)},Jo.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new ct(this.h,this.s,t*this.l)},Jo.rgb=function(){return ut(this.h,this.s,this.l)},co.hcl=ft;var ts=ft.prototype=new lt;ts.brighter=function(t){return new ft(this.h,this.c,Math.min(100,this.l+es*(arguments.length?t:1)))},ts.darker=function(t){return new ft(this.h,this.c,Math.max(0,this.l-es*(arguments.length?t:1)))},ts.rgb=function(){return ht(this.h,this.c,this.l).rgb()},co.lab=dt;var es=18,rs=.95047,ns=1,is=1.08883,as=dt.prototype=new lt;as.brighter=function(t){return new dt(Math.min(100,this.l+es*(arguments.length?t:1)),this.a,this.b)},as.darker=function(t){return new dt(Math.max(0,this.l-es*(arguments.length?t:1)),this.a,this.b)},as.rgb=function(){return pt(this.l,this.a,this.b)},co.rgb=bt;var os=bt.prototype=new lt;os.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&i>e&&(e=i),r&&i>r&&(r=i),n&&i>n&&(n=i),new bt(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new bt(i,i,i)},os.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new bt(t*this.r,t*this.g,t*this.b)},os.hsl=function(){return At(this.r,this.g,this.b)},os.toString=function(){return"#"+wt(this.r)+wt(this.g)+wt(this.b)};var ss=co.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});ss.forEach(function(t,e){ss.set(t,xt(e))}),co.functor=Lt,co.xhr=St(x),co.dsv=function(t,e){function r(t,r,a){arguments.length<3&&(a=r,r=null);var o=Ct(t,e,null==r?n:i(r),a);return o.row=function(t){return arguments.length?o.response(null==(r=t)?n:i(t)):r},o}function n(t){return r.parse(t.responseText)}function i(t){return function(e){return r.parse(e.responseText,t)}}function a(e){return e.map(o).join(t)}function o(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);return r.parse=function(t,e){var n;return r.parseRows(t,function(t,r){if(n)return n(t,r-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");n=e?function(t,r){return e(i(t),r)}:i})},r.parseRows=function(t,e){function r(){if(u>=c)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++u;){var n=t.charCodeAt(u++),s=1;if(10===n)i=!0;else if(13===n)i=!0,10===t.charCodeAt(u)&&(++u,++s);else if(n!==l)continue;return t.slice(e,u-s)}return t.slice(e)}for(var n,i,a={},o={},s=[],c=t.length,u=0,f=0;(n=r())!==o;){for(var h=[];n!==a&&n!==o;)h.push(n),n=r();e&&null==(h=e(h,f++))||s.push(h)}return s},r.format=function(e){if(Array.isArray(e[0]))return r.formatRows(e);var n=new b,i=[];return e.forEach(function(t){for(var e in t)n.has(e)||i.push(n.add(e))}),[i.map(o).join(t)].concat(e.map(function(e){return i.map(function(t){return o(e[t])}).join(t)})).join("\n")},r.formatRows=function(t){return t.map(a).join("\n")},r},co.csv=co.dsv(",","text/csv"),co.tsv=co.dsv(" ","text/tab-separated-values");var ls,cs,us,fs,hs=this[w(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};co.timer=function(){Rt.apply(this,arguments)},co.timer.flush=function(){It(),Nt()},co.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var ds=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Ft);co.formatPrefix=function(t,e){var r=0;return(t=+t)&&(0>t&&(t*=-1),e&&(t=co.round(t,jt(t,e))),r=1+Math.floor(1e-12+Math.log(t)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),ds[8+r/3]};var ps=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,gs=co.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=co.round(t,jt(t,e))).toFixed(Math.max(0,Math.min(20,jt(t*(1+1e-15),e))))}}),vs=co.time={},ms=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ys.setUTCDate.apply(this._,arguments)},setDay:function(){ys.setUTCDay.apply(this._,arguments)},setFullYear:function(){ys.setUTCFullYear.apply(this._,arguments)},setHours:function(){ys.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ys.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ys.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ys.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ys.setUTCSeconds.apply(this._,arguments)},setTime:function(){ys.setTime.apply(this._,arguments)}};var ys=Date.prototype;vs.year=Vt(function(t){return t=vs.day(t),t.setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),vs.years=vs.year.range,vs.years.utc=vs.year.utc.range,vs.day=Vt(function(t){var e=new ms(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),vs.days=vs.day.range,vs.days.utc=vs.day.utc.range,vs.dayOfYear=function(t){var e=vs.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=vs[t]=Vt(function(t){return(t=vs.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});vs[t+"s"]=r.range,vs[t+"s"].utc=r.utc.range,vs[t+"OfYear"]=function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)}}),vs.week=vs.sunday,vs.weeks=vs.sunday.range,vs.weeks.utc=vs.sunday.utc.range,vs.weekOfYear=vs.sundayOfYear;var bs={"-":"",_:" ",0:"0"},xs=/^\s*\d+/,_s=/^%/;co.locale=function(t){return{numberFormat:Dt(t),timeFormat:Ht(t)}};var ws=co.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});co.format=ws.numberFormat,co.geo={},fe.prototype={s:0,t:0,add:function(t){he(t,this.t,ks),he(ks.s,this.s,this),this.s?this.t+=ks.t:this.s=ks.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ks=new fe;co.geo.stream=function(t,e){t&&As.hasOwnProperty(t.type)?As[t.type](t,e):de(t,e)};var As={Feature:function(t,e){de(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++nt?4*Uo+t:t,Ls.lineStart=Ls.lineEnd=Ls.point=k}};co.geo.bounds=function(){function t(t,e){b.push(x=[u=t,h=t]),f>e&&(f=e),e>d&&(d=e)}function e(e,r){var n=me([e*Go,r*Go]);if(m){var i=be(m,n),a=[i[1],-i[0],0],o=be(a,i);we(o),o=ke(o);var l=e-p,c=l>0?1:-1,g=o[0]*Yo*c,v=wo(l)>180;if(v^(g>c*p&&c*e>g)){var y=o[1]*Yo;y>d&&(d=y)}else if(g=(g+360)%360-180,v^(g>c*p&&c*e>g)){var y=-o[1]*Yo;f>y&&(f=y)}else f>r&&(f=r),r>d&&(d=r);v?p>e?s(u,e)>s(u,h)&&(h=e):s(e,h)>s(u,h)&&(u=e):h>=u?(u>e&&(u=e),e>h&&(h=e)):e>p?s(u,e)>s(u,h)&&(h=e):s(e,h)>s(u,h)&&(u=e)}else t(e,r);m=n,p=e}function r(){_.point=e}function n(){x[0]=u,x[1]=h,_.point=t,m=null}function i(t,r){if(m){var n=t-p;y+=wo(n)>180?n+(n>0?360:-360):n}else g=t,v=r;Ls.point(t,r),e(t,r)}function a(){Ls.lineStart()}function o(){i(g,v),Ls.lineEnd(),wo(y)>Do&&(u=-(h=180)),x[0]=u,x[1]=h,m=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function c(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:tEs?(u=-(h=180),f=-(d=90)):y>Do?d=90:-Do>y&&(f=-90),x[0]=u,x[1]=h}};return function(t){d=h=-(u=f=1/0),b=[],co.geo.stream(t,_);var e=b.length;if(e){b.sort(l);for(var r,n=1,i=b[0],a=[i];e>n;++n)r=b[n],c(r[0],i)||c(r[1],i)?(s(i[0],r[1])>s(i[0],i[1])&&(i[1]=r[1]),s(r[0],i[1])>s(i[0],i[1])&&(i[0]=r[0])):a.push(i=r);for(var o,r,p=-(1/0),e=a.length-1,n=0,i=a[e];e>=n;i=r,++n)r=a[n],(o=s(i[1],r[0]))>p&&(p=o,u=r[0],h=i[1])}return b=x=null,u===1/0||f===1/0?[[NaN,NaN],[NaN,NaN]]:[[u,f],[h,d]]}}(),co.geo.centroid=function(t){Ss=Cs=zs=Ps=Rs=Os=Is=Ns=js=Fs=Ds=0,co.geo.stream(t,Bs);var e=js,r=Fs,n=Ds,i=e*e+r*r+n*n;return Bo>i&&(e=Os,r=Is,n=Ns,Do>Cs&&(e=zs,r=Ps,n=Rs),i=e*e+r*r+n*n,Bo>i)?[NaN,NaN]:[Math.atan2(r,e)*Yo,nt(n/Math.sqrt(i))*Yo]};var Ss,Cs,zs,Ps,Rs,Os,Is,Ns,js,Fs,Ds,Bs={sphere:k,point:Me,lineStart:Ee,lineEnd:Le,polygonStart:function(){Bs.lineStart=Se},polygonEnd:function(){Bs.lineStart=Ee}},Us=Ie(ze,De,Ue,[-Uo,-Uo/2]),Vs=1e9;co.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),i=a(t),i.valid=!0,i},extent:function(s){return arguments.length?(a=Ge(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(co.geo.conicEqualArea=function(){return Ye(Xe)}).raw=Xe,co.geo.albers=function(){return co.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},co.geo.albersUsa=function(){ -function t(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}var e,r,n,i,a=co.geo.albers(),o=co.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=co.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};return t.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&.234>i&&n>=-.425&&-.214>n?o:i>=.166&&.234>i&&n>=-.214&&-.115>n?s:a).invert(t)},t.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},t.precision=function(e){return arguments.length?(a.precision(e),o.precision(e),s.precision(e),t):a.precision()},t.scale=function(e){return arguments.length?(a.scale(e),o.scale(.35*e),s.scale(e),t.translate(a.translate())):a.scale()},t.translate=function(e){if(!arguments.length)return a.translate();var c=a.scale(),u=+e[0],f=+e[1];return r=a.translate(e).clipExtent([[u-.455*c,f-.238*c],[u+.455*c,f+.238*c]]).stream(l).point,n=o.translate([u-.307*c,f+.201*c]).clipExtent([[u-.425*c+Do,f+.12*c+Do],[u-.214*c-Do,f+.234*c-Do]]).stream(l).point,i=s.translate([u-.205*c,f+.212*c]).clipExtent([[u-.214*c+Do,f+.166*c+Do],[u-.115*c-Do,f+.234*c-Do]]).stream(l).point,t},t.scale(1070)};var qs,Hs,Gs,Ys,Xs,Ws,Zs={point:k,lineStart:k,lineEnd:k,polygonStart:function(){Hs=0,Zs.lineStart=We},polygonEnd:function(){Zs.lineStart=Zs.lineEnd=Zs.point=k,qs+=wo(Hs/2)}},Ks={point:Ze,lineStart:k,lineEnd:k,polygonStart:k,polygonEnd:k},$s={point:Qe,lineStart:Je,lineEnd:tr,polygonStart:function(){$s.lineStart=er},polygonEnd:function(){$s.point=Qe,$s.lineStart=Je,$s.lineEnd=tr}};co.geo.path=function(){function t(t){return t&&("function"==typeof s&&a.pointRadius(+s.apply(this,arguments)),o&&o.valid||(o=i(a)),co.geo.stream(t,o)),a.result()}function e(){return o=null,t}var r,n,i,a,o,s=4.5;return t.area=function(t){return qs=0,co.geo.stream(t,i(Zs)),qs},t.centroid=function(t){return zs=Ps=Rs=Os=Is=Ns=js=Fs=Ds=0,co.geo.stream(t,i($s)),Ds?[js/Ds,Fs/Ds]:Ns?[Os/Ns,Is/Ns]:Rs?[zs/Rs,Ps/Rs]:[NaN,NaN]},t.bounds=function(t){return Xs=Ws=-(Gs=Ys=1/0),co.geo.stream(t,i(Ks)),[[Gs,Ys],[Xs,Ws]]},t.projection=function(t){return arguments.length?(i=(r=t)?t.stream||ir(t):x,e()):r},t.context=function(t){return arguments.length?(a=null==(n=t)?new Ke:new rr(t),"function"!=typeof s&&a.pointRadius(s),e()):n},t.pointRadius=function(e){return arguments.length?(s="function"==typeof e?e:(a.pointRadius(+e),+e),t):s},t.projection(co.geo.albersUsa()).context(null)},co.geo.transform=function(t){return{stream:function(e){var r=new ar(e);for(var n in t)r[n]=t[n];return r}}},ar.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},co.geo.projection=sr,co.geo.projectionMutator=lr,(co.geo.equirectangular=function(){return sr(ur)}).raw=ur.invert=ur,co.geo.rotation=function(t){function e(e){return e=t(e[0]*Go,e[1]*Go),e[0]*=Yo,e[1]*=Yo,e}return t=hr(t[0]%360*Go,t[1]*Go,t.length>2?t[2]*Go:0),e.invert=function(e){return e=t.invert(e[0]*Go,e[1]*Go),e[0]*=Yo,e[1]*=Yo,e},e},fr.invert=ur,co.geo.circle=function(){function t(){var t="function"==typeof n?n.apply(this,arguments):n,e=hr(-t[0]*Go,-t[1]*Go,0).invert,i=[];return r(null,null,1,{point:function(t,r){i.push(t=e(t,r)),t[0]*=Yo,t[1]*=Yo}}),{type:"Polygon",coordinates:[i]}}var e,r,n=[0,0],i=6;return t.origin=function(e){return arguments.length?(n=e,t):n},t.angle=function(n){return arguments.length?(r=vr((e=+n)*Go,i*Go),t):e},t.precision=function(n){return arguments.length?(r=vr(e*Go,(i=+n)*Go),t):i},t.angle(90)},co.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Go,i=t[1]*Go,a=e[1]*Go,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),c=Math.cos(i),u=Math.sin(a),f=Math.cos(a);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-l*f*s)*r),l*u+c*f*s)},co.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return co.range(Math.ceil(a/v)*v,i,v).map(h).concat(co.range(Math.ceil(c/m)*m,l,m).map(d)).concat(co.range(Math.ceil(n/p)*p,r,p).filter(function(t){return wo(t%v)>Do}).map(u)).concat(co.range(Math.ceil(s/g)*g,o,g).filter(function(t){return wo(t%m)>Do}).map(f))}var r,n,i,a,o,s,l,c,u,f,h,d,p=10,g=p,v=90,m=360,y=2.5;return t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})},t.outline=function(){return{type:"Polygon",coordinates:[h(a).concat(d(l).slice(1),h(i).reverse().slice(1),d(c).reverse().slice(1))]}},t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()},t.majorExtent=function(e){return arguments.length?(a=+e[0][0],i=+e[1][0],c=+e[0][1],l=+e[1][1],a>i&&(e=a,a=i,i=e),c>l&&(e=c,c=l,l=e),t.precision(y)):[[a,c],[i,l]]},t.minorExtent=function(e){return arguments.length?(n=+e[0][0],r=+e[1][0],s=+e[0][1],o=+e[1][1],n>r&&(e=n,n=r,r=e),s>o&&(e=s,s=o,o=e),t.precision(y)):[[n,s],[r,o]]},t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()},t.majorStep=function(e){return arguments.length?(v=+e[0],m=+e[1],t):[v,m]},t.minorStep=function(e){return arguments.length?(p=+e[0],g=+e[1],t):[p,g]},t.precision=function(e){return arguments.length?(y=+e,u=yr(s,o,90),f=br(n,r,y),h=yr(c,l,90),d=br(a,i,y),t):y},t.majorExtent([[-180,-90+Do],[180,90-Do]]).minorExtent([[-180,-80-Do],[180,80+Do]])},co.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}var e,r,n=xr,i=_r;return t.distance=function(){return co.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},t.source=function(r){return arguments.length?(n=r,e="function"==typeof r?null:r,t):n},t.target=function(e){return arguments.length?(i=e,r="function"==typeof e?null:e,t):i},t.precision=function(){return arguments.length?t:0},t},co.geo.interpolate=function(t,e){return wr(t[0]*Go,t[1]*Go,e[0]*Go,e[1]*Go)},co.geo.length=function(t){return Qs=0,co.geo.stream(t,Js),Qs};var Qs,Js={sphere:k,point:k,lineStart:kr,lineEnd:k,polygonStart:k,polygonEnd:k},tl=Ar(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(co.geo.azimuthalEqualArea=function(){return sr(tl)}).raw=tl;var el=Ar(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},x);(co.geo.azimuthalEquidistant=function(){return sr(el)}).raw=el,(co.geo.conicConformal=function(){return Ye(Mr)}).raw=Mr,(co.geo.conicEquidistant=function(){return Ye(Tr)}).raw=Tr;var rl=Ar(function(t){return 1/t},Math.atan);(co.geo.gnomonic=function(){return sr(rl)}).raw=rl,Er.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Ho]},(co.geo.mercator=function(){return Lr(Er)}).raw=Er;var nl=Ar(function(){return 1},Math.asin);(co.geo.orthographic=function(){return sr(nl)}).raw=nl;var il=Ar(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(co.geo.stereographic=function(){return sr(il)}).raw=il,Sr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ho]},(co.geo.transverseMercator=function(){var t=Lr(Sr),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):(t=r(),[t[0],t[1],t[2]-90])},r([0,0,90])}).raw=Sr,co.geom={},co.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Lt(r),a=Lt(n),o=t.length,s=[],l=[];for(e=0;o>e;e++)s.push([+i.call(this,t[e],e),+a.call(this,t[e],e),e]);for(s.sort(Rr),e=0;o>e;e++)l.push([s[e][0],-s[e][1]]);var c=Pr(s),u=Pr(l),f=u[0]===c[0],h=u[u.length-1]===c[c.length-1],d=[];for(e=c.length-1;e>=0;--e)d.push(t[s[c[e]][2]]);for(e=+f;e=n&&c.x<=a&&c.y>=i&&c.y<=o?[[n,o],[a,o],[a,i],[n,i]]:[];u.point=t[s]}),e}function r(t){return t.map(function(t,e){return{x:Math.round(a(t,e)/Do)*Do,y:Math.round(o(t,e)/Do)*Do,i:e}})}var n=Cr,i=zr,a=n,o=i,s=dl;return t?e(t):(e.links=function(t){return cn(r(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},e.triangles=function(t){var e=[];return cn(r(t)).cells.forEach(function(r,n){for(var i,a,o=r.site,s=r.edges.sort(Yr),l=-1,c=s.length,u=s[c-1].edge,f=u.l===o?u.r:u.l;++l=c,h=n>=u,d=h<<1|f;t.leaf=!1,t=t.nodes[d]||(t.nodes[d]=pn()),f?i=c:s=c,h?o=u:l=u,a(t,e,r,n,i,o,s,l)}var u,f,h,d,p,g,v,m,y,b=Lt(s),x=Lt(l);if(null!=e)g=e,v=r,m=n,y=i;else if(m=y=-(g=v=1/0),f=[],h=[],p=t.length,o)for(d=0;p>d;++d)u=t[d],u.xm&&(m=u.x),u.y>y&&(y=u.y),f.push(u.x),h.push(u.y);else for(d=0;p>d;++d){var _=+b(u=t[d],d),w=+x(u,d);g>_&&(g=_),v>w&&(v=w),_>m&&(m=_),w>y&&(y=w),f.push(_),h.push(w)}var k=m-g,A=y-v;k>A?y=v+k:m=g+A;var M=pn();if(M.add=function(t){a(M,t,+b(t,++d),+x(t,d),g,v,m,y)},M.visit=function(t){gn(t,M,g,v,m,y)},M.find=function(t){return vn(M,t[0],t[1],g,v,m,y)},d=-1,null==e){for(;++d=0?t.slice(0,e):t,n=e>=0?t.slice(e+1):"in";return r=ml.get(r)||vl,n=yl.get(n)||x,kn(n(r.apply(null,uo.call(arguments,1))))},co.interpolateHcl=Nn,co.interpolateHsl=jn,co.interpolateLab=Fn,co.interpolateRound=Dn,co.transform=function(t){var e=ho.createElementNS(co.ns.prefix.svg,"g");return(co.transform=function(t){if(null!=t){e.setAttribute("transform",t);var r=e.transform.baseVal.consolidate()}return new Bn(r?r.matrix:bl)})(t)},Bn.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var bl={a:1,b:0,c:0,d:1,e:0,f:0};co.interpolateTransform=Zn,co.layout={},co.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++rs*s/m){if(g>l){var c=e.charge/l;t.px-=a*c,t.py-=o*c}return!0}if(e.point&&l&&g>l){var c=e.pointCharge/l;t.px-=a*c,t.py-=o*c}}return!e.charge}}function e(t){t.px=co.event.x,t.py=co.event.y,l.resume()}var r,n,i,a,o,s,l={},c=co.dispatch("start","tick","end"),u=[1,1],f=.9,h=xl,d=_l,p=-30,g=wl,v=.1,m=.64,y=[],b=[];return l.tick=function(){if((i*=.99)<.005)return r=null,c.end({type:"end",alpha:i=0}),!0;var e,n,l,h,d,g,m,x,_,w=y.length,k=b.length;for(n=0;k>n;++n)l=b[n],h=l.source,d=l.target,x=d.x-h.x,_=d.y-h.y,(g=x*x+_*_)&&(g=i*o[n]*((g=Math.sqrt(g))-a[n])/g,x*=g,_*=g,d.x-=x*(m=h.weight+d.weight?h.weight/(h.weight+d.weight):.5),d.y-=_*m,h.x+=x*(m=1-m),h.y+=_*m);if((m=i*v)&&(x=u[0]/2,_=u[1]/2,n=-1,m))for(;++n0?i=t:(r.c=null,r.t=NaN,r=null,c.end({type:"end",alpha:i=0})):t>0&&(c.start({type:"start",alpha:i=t}),r=Rt(l.tick)),l):i},l.start=function(){function t(t,n){if(!r){for(r=new Array(i),l=0;i>l;++l)r[l]=[];for(l=0;c>l;++l){var a=b[l];r[a.source.index].push(a.target),r[a.target.index].push(a.source)}}for(var o,s=r[e],l=-1,u=s.length;++le;++e)(n=y[e]).index=e,n.weight=0;for(e=0;c>e;++e)n=b[e],"number"==typeof n.source&&(n.source=y[n.source]),"number"==typeof n.target&&(n.target=y[n.target]),++n.source.weight,++n.target.weight;for(e=0;i>e;++e)n=y[e],isNaN(n.x)&&(n.x=t("x",f)),isNaN(n.y)&&(n.y=t("y",g)),isNaN(n.px)&&(n.px=n.x),isNaN(n.py)&&(n.py=n.y);if(a=[],"function"==typeof h)for(e=0;c>e;++e)a[e]=+h.call(this,b[e],e);else for(e=0;c>e;++e)a[e]=h;if(o=[],"function"==typeof d)for(e=0;c>e;++e)o[e]=+d.call(this,b[e],e);else for(e=0;c>e;++e)o[e]=d;if(s=[],"function"==typeof p)for(e=0;i>e;++e)s[e]=+p.call(this,y[e],e);else for(e=0;i>e;++e)s[e]=p;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return n||(n=co.behavior.drag().origin(x).on("dragstart.force",ei).on("drag.force",e).on("dragend.force",ri)),arguments.length?void this.on("mouseover.force",ni).on("mouseout.force",ii).call(n):n},co.rebind(l,c,"on")};var xl=20,_l=1,wl=1/0;co.layout.hierarchy=function(){function t(i){var a,o=[i],s=[];for(i.depth=0;null!=(a=o.pop());)if(s.push(a),(c=r.call(t,a,a.depth))&&(l=c.length)){for(var l,c,u;--l>=0;)o.push(u=c[l]),u.parent=a,u.depth=a.depth+1;n&&(a.value=0),a.children=c}else n&&(a.value=+n.call(t,a,a.depth)||0),delete a.children;return li(i,function(t){var r,i;e&&(r=t.children)&&r.sort(e),n&&(i=t.parent)&&(i.value+=t.value)}),s}var e=fi,r=ci,n=ui;return t.sort=function(r){return arguments.length?(e=r,t):e},t.children=function(e){return arguments.length?(r=e,t):r},t.value=function(e){return arguments.length?(n=e,t):n},t.revalue=function(e){return n&&(si(e,function(t){t.children&&(t.value=0)}),li(e,function(e){var r;e.children||(e.value=+n.call(t,e,e.depth)||0),(r=e.parent)&&(r.value+=e.value)})),e},t},co.layout.partition=function(){function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,c=-1;for(n=e.value?n/e.value:0;++cf?-1:1),p=co.sum(c),g=p?(f-l*d)/p:0,v=co.range(l),m=[];return null!=r&&v.sort(r===kl?function(t,e){return c[e]-c[t]}:function(t,e){return r(o[t],o[e])}),v.forEach(function(t){m[t]={data:o[t],value:s=c[t],startAngle:u,endAngle:u+=s*g+d,padAngle:h}}),m}var e=Number,r=kl,n=0,i=Vo,a=0;return t.value=function(r){return arguments.length?(e=r,t):e},t.sort=function(e){return arguments.length?(r=e,t):r},t.startAngle=function(e){return arguments.length?(n=e,t):n},t.endAngle=function(e){return arguments.length?(i=e,t):i},t.padAngle=function(e){return arguments.length?(a=e,t):a},t};var kl={};co.layout.stack=function(){function t(s,l){if(!(h=s.length))return s;var c=s.map(function(r,n){return e.call(t,r,n)}),u=c.map(function(e){return e.map(function(e,r){return[a.call(t,e,r),o.call(t,e,r)]})}),f=r.call(t,u,l);c=co.permute(c,f),u=co.permute(u,f);var h,d,p,g,v=n.call(t,u,l),m=c[0].length;for(p=0;m>p;++p)for(i.call(t,c[0][p],g=v[p],u[0][p][1]),d=1;h>d;++d)i.call(t,c[d][p],g+=u[d-1][p][1],u[d][p][1]);return s}var e=x,r=vi,n=mi,i=gi,a=di,o=pi;return t.values=function(r){return arguments.length?(e=r,t):e},t.order=function(e){return arguments.length?(r="function"==typeof e?e:Al.get(e)||vi,t):r},t.offset=function(e){return arguments.length?(n="function"==typeof e?e:Ml.get(e)||mi,t):n},t.x=function(e){return arguments.length?(a=e,t):a},t.y=function(e){return arguments.length?(o=e,t):o},t.out=function(e){return arguments.length?(i=e,t):i},t};var Al=co.map({"inside-out":function(t){var e,r,n=t.length,i=t.map(yi),a=t.map(bi),o=co.range(n).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,c=[],u=[];for(e=0;n>e;++e)r=o[e],l>s?(s+=a[r],c.push(r)):(l+=a[r],u.push(r));return u.reverse().concat(c)},reverse:function(t){return co.range(t.length).reverse()},"default":vi}),Ml=co.map({silhouette:function(t){var e,r,n,i=t.length,a=t[0].length,o=[],s=0,l=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];n>s&&(s=n),o.push(n)}for(r=0;a>r;++r)l[r]=(s-o[r])/2;return l},wiggle:function(t){var e,r,n,i,a,o,s,l,c,u=t.length,f=t[0],h=f.length,d=[];for(d[0]=l=c=0,r=1;h>r;++r){for(e=0,i=0;u>e;++e)i+=t[e][r][1];for(e=0,a=0,s=f[r][0]-f[r-1][0];u>e;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*s);e>n;++n)o+=(t[n][r][1]-t[n][r-1][1])/s;a+=o*t[e][r][1]}d[r]=l-=i?a/i*s:0,c>l&&(c=l)}for(r=0;h>r;++r)d[r]-=c;return d},expand:function(t){var e,r,n,i=t.length,a=t[0].length,o=1/i,s=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];if(n)for(e=0;i>e;e++)t[e][r][1]/=n;else for(e=0;i>e;e++)t[e][r][1]=o}for(r=0;a>r;++r)s[r]=0;return s},zero:mi});co.layout.histogram=function(){function t(t,a){for(var o,s,l=[],c=t.map(r,this),u=n.call(this,c,a),f=i.call(this,u,c,a),a=-1,h=c.length,d=f.length-1,p=e?1:1/h;++a0)for(a=-1;++a=u[0]&&s<=u[1]&&(o=l[co.bisect(f,s,1,d)-1],o.y+=p,o.push(t[a]));return l}var e=!0,r=Number,n=ki,i=_i;return t.value=function(e){return arguments.length?(r=e,t):r},t.range=function(e){return arguments.length?(n=Lt(e),t):n},t.bins=function(e){return arguments.length?(i="number"==typeof e?function(t){return wi(t,e)}:Lt(e),t):i},t.frequency=function(r){return arguments.length?(e=!!r,t):e},t},co.layout.pack=function(){function t(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],c=i[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,li(s,function(t){t.r=+u(t.value)}),li(s,Li),n){var f=n*(e?1:Math.max(2*s.r/l,2*s.r/c))/2;li(s,function(t){t.r+=f}),li(s,Li),li(s,function(t){t.r-=f})}return zi(s,l/2,c/2,e?1:1/Math.max(2*s.r/l,2*s.r/c)),o}var e,r=co.layout.hierarchy().sort(Ai),n=0,i=[1,1];return t.size=function(e){return arguments.length?(i=e,t):i},t.radius=function(r){return arguments.length?(e=null==r||"function"==typeof r?r:+r,t):e},t.padding=function(e){return arguments.length?(n=+e,t):n},oi(t,r)},co.layout.tree=function(){function t(t,i){var u=o.call(this,t,i),f=u[0],h=e(f);if(li(h,r),h.parent.m=-h.z,si(h,n),c)si(f,a);else{var d=f,p=f,g=f;si(f,function(t){t.xp.x&&(p=t),t.depth>g.depth&&(g=t)});var v=s(d,p)/2-d.x,m=l[0]/(p.x+s(p,d)/2+v),y=l[1]/(g.depth||1);si(f,function(t){t.x=(t.x+v)*m,t.y=t.depth*y})}return u}function e(t){for(var e,r={A:null,children:[t]},n=[r];null!=(e=n.pop());)for(var i,a=e.children,o=0,s=a.length;s>o;++o)n.push((a[o]=i={_:a[o],parent:e,children:(i=a[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return r.children[0]}function r(t){var e=t.children,r=t.parent.children,n=t.i?r[t.i-1]:null;if(e.length){ji(t);var a=(e[0].z+e[e.length-1].z)/2;n?(t.z=n.z+s(t._,n._),t.m=t.z-a):t.z=a}else n&&(t.z=n.z+s(t._,n._));t.parent.A=i(t,n,t.parent.A||r[0])}function n(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function i(t,e,r){if(e){for(var n,i=t,a=t,o=e,l=i.parent.children[0],c=i.m,u=a.m,f=o.m,h=l.m;o=Ii(o),i=Oi(i),o&&i;)l=Oi(l),a=Ii(a),a.a=t,n=o.z+f-i.z-c+s(o._,i._),n>0&&(Ni(Fi(o,t,r),t,n),c+=n,u+=n),f+=o.m,c+=i.m,h+=l.m,u+=a.m;o&&!Ii(a)&&(a.t=o,a.m+=f-u),i&&!Oi(l)&&(l.t=i,l.m+=c-h,r=t)}return r}function a(t){t.x*=l[0],t.y=t.depth*l[1]}var o=co.layout.hierarchy().sort(null).value(null),s=Ri,l=[1,1],c=null;return t.separation=function(e){return arguments.length?(s=e,t):s},t.size=function(e){return arguments.length?(c=null==(l=e)?a:null,t):c?null:l},t.nodeSize=function(e){return arguments.length?(c=null==(l=e)?null:a,t):c?l:null},oi(t,o)},co.layout.cluster=function(){function t(t,a){var o,s=e.call(this,t,a),l=s[0],c=0;li(l,function(t){var e=t.children;e&&e.length?(t.x=Bi(e),t.y=Di(e)):(t.x=o?c+=r(t,o):0,t.y=0,o=t)});var u=Ui(l),f=Vi(l),h=u.x-r(u,f)/2,d=f.x+r(f,u)/2;return li(l,i?function(t){t.x=(t.x-l.x)*n[0],t.y=(l.y-t.y)*n[1]}:function(t){t.x=(t.x-h)/(d-h)*n[0],t.y=(1-(l.y?t.y/l.y:1))*n[1]}),s}var e=co.layout.hierarchy().sort(null).value(null),r=Ri,n=[1,1],i=!1;return t.separation=function(e){return arguments.length?(r=e,t):r},t.size=function(e){return arguments.length?(i=null==(n=e),t):i?null:n},t.nodeSize=function(e){return arguments.length?(i=null!=(n=e),t):i?n:null},oi(t,e)},co.layout.treemap=function(){function t(t,e){for(var r,n,i=-1,a=t.length;++ie?0:e),r.area=isNaN(n)||0>=n?0:n}function e(r){var a=r.children;if(a&&a.length){var o,s,l,c=f(r),u=[],h=a.slice(),p=1/0,g="slice"===d?c.dx:"dice"===d?c.dy:"slice-dice"===d?1&r.depth?c.dy:c.dx:Math.min(c.dx,c.dy);for(t(h,c.dx*c.dy/r.value),u.area=0;(l=h.length)>0;)u.push(o=h[l-1]),u.area+=o.area,"squarify"!==d||(s=n(u,g))<=p?(h.pop(),p=s):(u.area-=u.pop().area,i(u,g,c,!1),g=Math.min(c.dx,c.dy),u.length=u.area=0,p=1/0);u.length&&(i(u,g,c,!0),u.length=u.area=0),a.forEach(e)}}function r(e){var n=e.children;if(n&&n.length){var a,o=f(e),s=n.slice(),l=[];for(t(s,o.dx*o.dy/e.value),l.area=0;a=s.pop();)l.push(a),l.area+=a.area,null!=a.z&&(i(l,a.z?o.dx:o.dy,o,!s.length),l.length=l.area=0);n.forEach(r)}}function n(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++or&&(a=r),r>i&&(i=r));return n*=n,e*=e,n?Math.max(e*i*p/n,n/(e*a*p)):1/0}function i(t,e,r,n){var i,a=-1,o=t.length,s=r.x,c=r.y,u=e?l(t.area/e):0;if(e==r.dx){for((n||u>r.dy)&&(u=r.dy);++ar.dx)&&(u=r.dx);++ar&&(e=1),1>r&&(t=0),function(){var r,n,i;do r=2*Math.random()-1,n=2*Math.random()-1,i=r*r+n*n;while(!i||i>1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=co.random.normal.apply(co,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=co.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;t>r;r++)e+=Math.random();return e}}},co.scale={};var Tl={floor:x,ceil:x};co.scale.linear=function(){return $i([0,1],[0,1],_n,!1)};var El={s:1,g:1,p:1,r:1,e:1};co.scale.log=function(){return aa(co.scale.linear().domain([0,1]),10,!0,[1,10])};var Ll=co.format(".0e"),Sl={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};co.scale.pow=function(){return oa(co.scale.linear(),1,[0,1])},co.scale.sqrt=function(){return co.scale.pow().exponent(.5)},co.scale.ordinal=function(){return la([],{t:"range",a:[[]]})},co.scale.category10=function(){return co.scale.ordinal().range(Cl)},co.scale.category20=function(){return co.scale.ordinal().range(zl)},co.scale.category20b=function(){return co.scale.ordinal().range(Pl)},co.scale.category20c=function(){return co.scale.ordinal().range(Rl)};var Cl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(_t),zl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(_t),Pl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(_t),Rl=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(_t);co.scale.quantile=function(){return ca([],[])},co.scale.quantize=function(){return ua(0,1,[0,1])},co.scale.threshold=function(){return fa([.5],[0,1])},co.scale.identity=function(){return ha([0,1])},co.svg={},co.svg.arc=function(){function t(){var t=Math.max(0,+r.apply(this,arguments)),c=Math.max(0,+n.apply(this,arguments)),u=o.apply(this,arguments)-Ho,f=s.apply(this,arguments)-Ho,h=Math.abs(f-u),d=u>f?0:1;if(t>c&&(p=c,c=t,t=p),h>=qo)return e(c,d)+(t?e(t,1-d):"")+"Z";var p,g,v,m,y,b,x,_,w,k,A,M,T=0,E=0,L=[];if((m=(+l.apply(this,arguments)||0)/2)&&(v=a===Ol?Math.sqrt(t*t+c*c):+a.apply(this,arguments),d||(E*=-1),c&&(E=nt(v/c*Math.sin(m))),t&&(T=nt(v/t*Math.sin(m)))),c){y=c*Math.cos(u+E),b=c*Math.sin(u+E),x=c*Math.cos(f-E),_=c*Math.sin(f-E);var S=Math.abs(f-u-2*E)<=Uo?0:1;if(E&&ba(y,b,x,_)===d^S){var C=(u+f)/2;y=c*Math.cos(C),b=c*Math.sin(C),x=_=null}}else y=b=0;if(t){w=t*Math.cos(f-T),k=t*Math.sin(f-T),A=t*Math.cos(u+T),M=t*Math.sin(u+T);var z=Math.abs(u-f+2*T)<=Uo?0:1;if(T&&ba(w,k,A,M)===1-d^z){ -var P=(u+f)/2;w=t*Math.cos(P),k=t*Math.sin(P),A=M=null}}else w=k=0;if(h>Do&&(p=Math.min(Math.abs(c-t)/2,+i.apply(this,arguments)))>.001){g=c>t^d?0:1;var R=p,O=p;if(Uo>h){var I=null==A?[w,k]:null==x?[y,b]:Ir([y,b],[A,M],[x,_],[w,k]),N=y-I[0],j=b-I[1],F=x-I[0],D=_-I[1],B=1/Math.sin(Math.acos((N*F+j*D)/(Math.sqrt(N*N+j*j)*Math.sqrt(F*F+D*D)))/2),U=Math.sqrt(I[0]*I[0]+I[1]*I[1]);O=Math.min(p,(t-U)/(B-1)),R=Math.min(p,(c-U)/(B+1))}if(null!=x){var V=xa(null==A?[w,k]:[A,M],[y,b],c,R,d),q=xa([x,_],[w,k],c,R,d);p===R?L.push("M",V[0],"A",R,",",R," 0 0,",g," ",V[1],"A",c,",",c," 0 ",1-d^ba(V[1][0],V[1][1],q[1][0],q[1][1]),",",d," ",q[1],"A",R,",",R," 0 0,",g," ",q[0]):L.push("M",V[0],"A",R,",",R," 0 1,",g," ",q[0])}else L.push("M",y,",",b);if(null!=A){var H=xa([y,b],[A,M],t,-O,d),G=xa([w,k],null==x?[y,b]:[x,_],t,-O,d);p===O?L.push("L",G[0],"A",O,",",O," 0 0,",g," ",G[1],"A",t,",",t," 0 ",d^ba(G[1][0],G[1][1],H[1][0],H[1][1]),",",1-d," ",H[1],"A",O,",",O," 0 0,",g," ",H[0]):L.push("L",G[0],"A",O,",",O," 0 0,",g," ",H[0])}else L.push("L",w,",",k)}else L.push("M",y,",",b),null!=x&&L.push("A",c,",",c," 0 ",S,",",d," ",x,",",_),L.push("L",w,",",k),null!=A&&L.push("A",t,",",t," 0 ",z,",",1-d," ",A,",",M);return L.push("Z"),L.join("")}function e(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}var r=pa,n=ga,i=da,a=Ol,o=va,s=ma,l=ya;return t.innerRadius=function(e){return arguments.length?(r=Lt(e),t):r},t.outerRadius=function(e){return arguments.length?(n=Lt(e),t):n},t.cornerRadius=function(e){return arguments.length?(i=Lt(e),t):i},t.padRadius=function(e){return arguments.length?(a=e==Ol?Ol:Lt(e),t):a},t.startAngle=function(e){return arguments.length?(o=Lt(e),t):o},t.endAngle=function(e){return arguments.length?(s=Lt(e),t):s},t.padAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.centroid=function(){var t=(+r.apply(this,arguments)+ +n.apply(this,arguments))/2,e=(+o.apply(this,arguments)+ +s.apply(this,arguments))/2-Ho;return[Math.cos(e)*t,Math.sin(e)*t]},t};var Ol="auto";co.svg.line=function(){return _a(x)};var Il=co.map({linear:wa,"linear-closed":ka,step:Aa,"step-before":Ma,"step-after":Ta,basis:Pa,"basis-open":Ra,"basis-closed":Oa,bundle:Ia,cardinal:Sa,"cardinal-open":Ea,"cardinal-closed":La,monotone:Ua});Il.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Nl=[0,2/3,1/3,0],jl=[0,1/3,2/3,0],Fl=[0,1/6,2/3,1/6];co.svg.line.radial=function(){var t=_a(Va);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Ma.reverse=Ta,Ta.reverse=Ma,co.svg.area=function(){return qa(x)},co.svg.area.radial=function(){var t=qa(Va);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},co.svg.chord=function(){function t(t,s){var l=e(this,a,t,s),c=e(this,o,t,s);return"M"+l.p0+n(l.r,l.p1,l.a1-l.a0)+(r(l,c)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,c.r,c.p0)+n(c.r,c.p1,c.a1-c.a0)+i(c.r,c.p1,l.r,l.p0))+"Z"}function e(t,e,r,n){var i=e.call(t,r,n),a=s.call(t,i,n),o=l.call(t,i,n)-Ho,u=c.call(t,i,n)-Ho;return{r:a,a0:o,a1:u,p0:[a*Math.cos(o),a*Math.sin(o)],p1:[a*Math.cos(u),a*Math.sin(u)]}}function r(t,e){return t.a0==e.a0&&t.a1==e.a1}function n(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Uo)+",1 "+e}function i(t,e,r,n){return"Q 0,0 "+n}var a=xr,o=_r,s=Ha,l=va,c=ma;return t.radius=function(e){return arguments.length?(s=Lt(e),t):s},t.source=function(e){return arguments.length?(a=Lt(e),t):a},t.target=function(e){return arguments.length?(o=Lt(e),t):o},t.startAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.endAngle=function(e){return arguments.length?(c=Lt(e),t):c},t},co.svg.diagonal=function(){function t(t,i){var a=e.call(this,t,i),o=r.call(this,t,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return l=l.map(n),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,r=_r,n=Ga;return t.source=function(r){return arguments.length?(e=Lt(r),t):e},t.target=function(e){return arguments.length?(r=Lt(e),t):r},t.projection=function(e){return arguments.length?(n=e,t):n},t},co.svg.diagonal.radial=function(){var t=co.svg.diagonal(),e=Ga,r=t.projection;return t.projection=function(t){return arguments.length?r(Ya(e=t)):e},t},co.svg.symbol=function(){function t(t,n){return(Dl.get(e.call(this,t,n))||Za)(r.call(this,t,n))}var e=Wa,r=Xa;return t.type=function(r){return arguments.length?(e=Lt(r),t):e},t.size=function(e){return arguments.length?(r=Lt(e),t):r},t};var Dl=co.map({circle:Za,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Ul)),r=e*Ul;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});co.svg.symbolTypes=Dl.keys();var Bl=Math.sqrt(3),Ul=Math.tan(30*Go);zo.transition=function(t){for(var e,r,n=Vl||++Yl,i=to(t),a=[],o=ql||{time:Date.now(),ease:Ln,delay:0,duration:250},s=-1,l=this.length;++sa;a++){i.push(e=[]);for(var r=this[a],s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return $a(i,this.namespace,this.id)},Gl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):G(this,null==e?function(e){e[n][r].tween.remove(t)}:function(i){i[n][r].tween.set(t,e)})},Gl.attr=function(t,e){function r(){this.removeAttribute(s)}function n(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?r:(t+="",function(){var e,r=this.getAttribute(s);return r!==t&&(e=o(r,t),function(t){this.setAttribute(s,e(t))})})}function a(t){return null==t?n:(t+="",function(){var e,r=this.getAttributeNS(s.space,s.local);return r!==t&&(e=o(r,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var o="transform"==t?Zn:_n,s=co.ns.qualify(t);return Qa(this,"attr."+t,e,s.local?a:i)},Gl.attrTween=function(t,e){function r(t,r){var n=e.call(this,t,r,this.getAttribute(i));return n&&function(t){this.setAttribute(i,n(t))}}function n(t,r){var n=e.call(this,t,r,this.getAttributeNS(i.space,i.local));return n&&function(t){this.setAttributeNS(i.space,i.local,n(t))}}var i=co.ns.qualify(t);return this.tween("attr."+t,i.local?n:r)},Gl.style=function(t,e,r){function i(){this.style.removeProperty(t)}function a(e){return null==e?i:(e+="",function(){var i,a=n(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(i=_n(a,e),function(e){this.style.setProperty(t,i(e),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(r in t)this.style(r,t[r],e);return this}r=""}return Qa(this,"style."+t,e,a)},Gl.styleTween=function(t,e,r){function i(i,a){var o=e.call(this,i,a,n(this).getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),r)}}return arguments.length<3&&(r=""),this.tween("style."+t,i)},Gl.text=function(t){return Qa(this,"text",t,Ja)},Gl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},Gl.ease=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].ease:("function"!=typeof t&&(t=co.ease.apply(co,arguments)),G(this,function(n){n[r][e].ease=t}))},Gl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:G(this,"function"==typeof t?function(n,i,a){n[r][e].delay=+t.call(n,n.__data__,i,a)}:(t=+t,function(n){n[r][e].delay=t}))},Gl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:G(this,"function"==typeof t?function(n,i,a){n[r][e].duration=Math.max(1,t.call(n,n.__data__,i,a))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},Gl.each=function(t,e){var r=this.id,n=this.namespace;if(arguments.length<2){var i=ql,a=Vl;try{Vl=r,G(this,function(e,i,a){ql=e[n][r],t.call(e,e.__data__,i,a)})}finally{ql=i,Vl=a}}else G(this,function(i){var a=i[n][r];(a.event||(a.event=co.dispatch("start","end","interrupt"))).on(t,e)});return this},Gl.transition=function(){for(var t,e,r,n,i=this.id,a=++Yl,o=this.namespace,s=[],l=0,c=this.length;c>l;l++){s.push(t=[]);for(var e=this[l],u=0,f=e.length;f>u;u++)(r=e[u])&&(n=r[o][i],eo(r,u,o,a,{time:n.time,ease:n.ease,delay:n.delay+n.duration,duration:n.duration})),t.push(r)}return $a(s,o,a)},co.svg.axis=function(){function t(t){t.each(function(){var t,c=co.select(this),u=this.__chart__||r,f=this.__chart__=r.copy(),h=null==l?f.ticks?f.ticks.apply(f,s):f.domain():l,d=null==e?f.tickFormat?f.tickFormat.apply(f,s):x:e,p=c.selectAll(".tick").data(h,f),g=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Do),v=co.transition(p.exit()).style("opacity",Do).remove(),m=co.transition(p.order()).style("opacity",1),y=Math.max(i,0)+o,b=Yi(f),_=c.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),co.transition(_));g.append("line"),g.append("text");var k,A,M,T,E=g.select("line"),L=m.select("line"),S=p.select("text").text(d),C=g.select("text"),z=m.select("text"),P="top"===n||"left"===n?-1:1;if("bottom"===n||"top"===n?(t=ro,k="x",M="y",A="x2",T="y2",S.attr("dy",0>P?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+P*a+"V0H"+b[1]+"V"+P*a)):(t=no,k="y",M="x",A="y2",T="x2",S.attr("dy",".32em").style("text-anchor",0>P?"end":"start"),w.attr("d","M"+P*a+","+b[0]+"H0V"+b[1]+"H"+P*a)),E.attr(T,P*i),C.attr(M,P*y),L.attr(A,0).attr(T,P*i),z.attr(k,0).attr(M,P*y),f.rangeBand){var R=f,O=R.rangeBand()/2;u=f=function(t){return R(t)+O}}else u.rangeBand?u=f:v.call(t,f,u);g.call(t,u,f),m.call(t,f,f)})}var e,r=co.scale.linear(),n=Xl,i=6,a=6,o=3,s=[10],l=null;return t.scale=function(e){return arguments.length?(r=e,t):r},t.orient=function(e){return arguments.length?(n=e in Wl?e+"":Xl,t):n},t.ticks=function(){return arguments.length?(s=fo(arguments),t):s},t.tickValues=function(e){return arguments.length?(l=e,t):l},t.tickFormat=function(r){return arguments.length?(e=r,t):e},t.tickSize=function(e){var r=arguments.length;return r?(i=+e,a=+arguments[r-1],t):i},t.innerTickSize=function(e){return arguments.length?(i=+e,t):i},t.outerTickSize=function(e){return arguments.length?(a=+e,t):a},t.tickPadding=function(e){return arguments.length?(o=+e,t):o},t.tickSubdivide=function(){return arguments.length&&t},t};var Xl="bottom",Wl={top:1,right:1,bottom:1,left:1};co.svg.brush=function(){function t(n){n.each(function(){var n=co.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",a).on("touchstart.brush",a),o=n.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),n.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=n.selectAll(".resize").data(g,x);s.exit().remove(),s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Zl[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),s.style("display",t.empty()?"none":null);var l,f=co.transition(n),h=co.transition(o);c&&(l=Yi(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(f)),u&&(l=Yi(u),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(f)),e(f)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+f[+/e$/.test(t)]+","+h[+/^s/.test(t)]+")"})}function r(t){t.select(".extent").attr("x",f[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",f[1]-f[0])}function i(t){t.select(".extent").attr("y",h[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function a(){function a(){32==co.event.keyCode&&(S||(b=null,z[0]-=f[1],z[1]-=h[1],S=2),T())}function g(){32==co.event.keyCode&&2==S&&(z[0]+=f[1],z[1]+=h[1],S=0,T())}function v(){var t=co.mouse(_),n=!1;x&&(t[0]+=x[0],t[1]+=x[1]),S||(co.event.altKey?(b||(b=[(f[0]+f[1])/2,(h[0]+h[1])/2]),z[0]=f[+(t[0]u?(i=n,n=u):i=u),g[0]!=n||g[1]!=i?(r?s=null:o=null,g[0]=n,g[1]=i,!0):void 0}function y(){v(),A.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null),co.select("body").style("cursor",null),P.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),C(),k({type:"brushend"})}var b,x,_=this,w=co.select(co.event.target),k=l.of(_,arguments),A=co.select(_),M=w.datum(),E=!/^(n|s)$/.test(M)&&c,L=!/^(e|w)$/.test(M)&&u,S=w.classed("extent"),C=$(_),z=co.mouse(_),P=co.select(n(_)).on("keydown.brush",a).on("keyup.brush",g);if(co.event.changedTouches?P.on("touchmove.brush",v).on("touchend.brush",y):P.on("mousemove.brush",v).on("mouseup.brush",y),A.interrupt().selectAll("*").interrupt(),S)z[0]=f[0]-z[0],z[1]=h[0]-z[1];else if(M){var R=+/w$/.test(M),O=+/^n/.test(M);x=[f[1-R]-z[0],h[1-O]-z[1]],z[0]=f[R],z[1]=h[O]}else co.event.altKey&&(b=z.slice());A.style("pointer-events","none").selectAll(".resize").style("display",null),co.select("body").style("cursor",w.style("cursor")),k({type:"brushstart"}),v()}var o,s,l=L(t,"brushstart","brush","brushend"),c=null,u=null,f=[0,0],h=[0,0],d=!0,p=!0,g=Kl[0];return t.event=function(t){t.each(function(){var t=l.of(this,arguments),e={x:f,y:h,i:o,j:s},r=this.__chart__||e;this.__chart__=e,Vl?co.select(this).transition().each("start.brush",function(){o=r.i,s=r.j,f=r.x,h=r.y,t({type:"brushstart"})}).tween("brush:brush",function(){var r=wn(f,e.x),n=wn(h,e.y);return o=s=null,function(i){f=e.x=r(i),h=e.y=n(i),t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i,s=e.j,t({type:"brush",mode:"resize"}),t({type:"brushend"})}):(t({type:"brushstart"}),t({type:"brush",mode:"resize"}),t({type:"brushend"}))})},t.x=function(e){return arguments.length?(c=e,g=Kl[!c<<1|!u],t):c},t.y=function(e){return arguments.length?(u=e,g=Kl[!c<<1|!u],t):u},t.clamp=function(e){return arguments.length?(c&&u?(d=!!e[0],p=!!e[1]):c?d=!!e:u&&(p=!!e),t):c&&u?[d,p]:c?d:u?p:null},t.extent=function(e){var r,n,i,a,l;return arguments.length?(c&&(r=e[0],n=e[1],u&&(r=r[0],n=n[0]),o=[r,n],c.invert&&(r=c(r),n=c(n)),r>n&&(l=r,r=n,n=l),r==f[0]&&n==f[1]||(f=[r,n])),u&&(i=e[0],a=e[1],c&&(i=i[1],a=a[1]),s=[i,a],u.invert&&(i=u(i),a=u(a)),i>a&&(l=i,i=a,a=l),i==h[0]&&a==h[1]||(h=[i,a])),t):(c&&(o?(r=o[0],n=o[1]):(r=f[0],n=f[1],c.invert&&(r=c.invert(r),n=c.invert(n)),r>n&&(l=r,r=n,n=l))),u&&(s?(i=s[0],a=s[1]):(i=h[0],a=h[1],u.invert&&(i=u.invert(i),a=u.invert(a)),i>a&&(l=i,i=a,a=l))),c&&u?[[r,i],[n,a]]:c?[r,n]:u&&[i,a])},t.clear=function(){return t.empty()||(f=[0,0],h=[0,0],o=s=null),t},t.empty=function(){return!!c&&f[0]==f[1]||!!u&&h[0]==h[1]},co.rebind(t,l,"on")};var Zl={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Kl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],$l=vs.format=ws.timeFormat,Ql=$l.utc,Jl=Ql("%Y-%m-%dT%H:%M:%S.%LZ");$l.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?io:Jl,io.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},io.toString=Jl.toString,vs.second=Vt(function(t){return new ms(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),vs.seconds=vs.second.range,vs.seconds.utc=vs.second.utc.range,vs.minute=Vt(function(t){return new ms(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),vs.minutes=vs.minute.range,vs.minutes.utc=vs.minute.utc.range,vs.hour=Vt(function(t){var e=t.getTimezoneOffset()/60;return new ms(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),vs.hours=vs.hour.range,vs.hours.utc=vs.hour.utc.range,vs.month=Vt(function(t){return t=vs.day(t),t.setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),vs.months=vs.month.range,vs.months.utc=vs.month.utc.range;var tc=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],ec=[[vs.second,1],[vs.second,5],[vs.second,15],[vs.second,30],[vs.minute,1],[vs.minute,5],[vs.minute,15],[vs.minute,30],[vs.hour,1],[vs.hour,3],[vs.hour,6],[vs.hour,12],[vs.day,1],[vs.day,2],[vs.week,1],[vs.month,1],[vs.month,3],[vs.year,1]],rc=$l.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",ze]]),nc={range:function(t,e,r){return co.range(Math.ceil(t/r)*r,+e,r).map(oo)},floor:x,ceil:x};ec.year=vs.year,vs.scale=function(){return ao(co.scale.linear(),ec,rc)};var ic=ec.map(function(t){return[t[0].utc,t[1]]}),ac=Ql.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",ze]]);ic.year=vs.year.utc,vs.scale.utc=function(){return ao(co.scale.linear(),ic,ac)},co.text=St(function(t){return t.responseText}),co.json=function(t,e){return Ct(t,"application/json",so,e)},co.html=function(t,e){return Ct(t,"text/html",lo,e)},co.xml=St(function(t){return t.responseXML}),"function"==typeof t&&t.amd?(this.d3=co,t(co)):"object"==typeof r&&r.exports?r.exports=co:this.d3=co}()},{}],114:[function(t,e,r){"use strict";function n(t,e){this.point=t,this.index=e}function i(t,e){for(var r=t.point,n=e.point,i=r.length,a=0;i>a;++a){var o=n[a]-r[a];if(o)return o}return 0}function a(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;t>a;++a){var o=n[a-1],s=n[a];i[a-1]=[o[1],s[1]]}return r&&i.push([-1,i[0][1]],[i[t-1][1],-1]),i}function o(t,e){var r=t.length;if(0===r)return[];var o=t[0].length;if(1>o)return[];if(1===o)return a(r,t,e);for(var c=new Array(r),u=1,f=0;r>f;++f){for(var h=t[f],d=new Array(o+1),p=0,g=0;o>g;++g){var v=h[g];d[g]=v,p+=v*v}d[o]=p,c[f]=new n(d,f),u=Math.max(p,u)}l(c,i),r=c.length;for(var m=new Array(r+o+1),y=new Array(r+o+1),b=(o+1)*(o+1)*u,x=new Array(o+1),f=0;o>=f;++f)x[f]=0;x[o]=b,m[0]=x.slice(),y[0]=-1;for(var f=0;o>=f;++f){var d=x.slice();d[f]=1,m[f+1]=d,y[f+1]=-1}for(var f=0;r>f;++f){var _=c[f];m[f+o+1]=_.point,y[f+o+1]=_.index}var w=s(m,!1);if(w=e?w.filter(function(t){for(var e=0,r=0;o>=r;++r){var n=y[t[r]];if(0>n&&++e>=2)return!1;t[r]=n}return!0}):w.filter(function(t){for(var e=0;o>=e;++e){var r=y[t[e]];if(0>r)return!1;t[e]=r}return!0}),1&o)for(var f=0;f=i)return[];var a,o=new Array(i);if(r===t.length-1)for(a=0;i>a;++a)o[a]=e;else for(a=0;i>a;++a)o[a]=n(t,e,r+1);return o}function i(t,e){var r,n;for(r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e){switch("undefined"==typeof e&&(e=0),typeof t){case"number":if(t>0)return i(0|t,e);break;case"object":if("number"==typeof t.length)return n(t,e,0)}return[]}e.exports=a},{}],116:[function(e,r,n){(function(n,i){(function(){"use strict";function a(t){return"function"==typeof t||"object"==typeof t&&null!==t}function o(t){return"function"==typeof t}function s(t){Y=t}function l(t){K=t}function c(){return function(){n.nextTick(p)}}function u(){return function(){G(p)}}function f(){var t=0,e=new J(p),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){r.data=t=++t%2}}function h(){var t=new MessageChannel;return t.port1.onmessage=p,function(){t.port2.postMessage(0)}}function d(){return function(){setTimeout(p,1)}}function p(){for(var t=0;Z>t;t+=2){var e=rt[t],r=rt[t+1];e(r),rt[t]=void 0,rt[t+1]=void 0}Z=0}function g(){try{var t=e,r=t("vertx");return G=r.runOnLoop||r.runOnContext,u()}catch(n){return d()}}function v(t,e){var r=this,n=r._state;if(n===ot&&!t||n===st&&!e)return this;var i=new this.constructor(y),a=r._result;if(n){var o=arguments[n-1];K(function(){O(n,i,o,a)})}else C(r,i,t,e);return i}function m(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var r=new e(y);return T(r,t),r}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function x(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return lt.error=e,lt}}function w(t,e,r,n){try{t.call(e,r,n)}catch(i){return i}}function k(t,e,r){K(function(t){var n=!1,i=w(r,e,function(r){n||(n=!0,e!==r?T(t,r):L(t,r))},function(e){n||(n=!0,S(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&i&&(n=!0,S(t,i))},t)}function A(t,e){e._state===ot?L(t,e._result):e._state===st?S(t,e._result):C(e,void 0,function(e){T(t,e)},function(e){S(t,e)})}function M(t,e,r){e.constructor===t.constructor&&r===nt&&constructor.resolve===it?A(t,e):r===lt?S(t,lt.error):void 0===r?L(t,e):o(r)?k(t,e,r):L(t,e)}function T(t,e){t===e?S(t,b()):a(e)?M(t,e,_(e)):L(t,e)}function E(t){t._onerror&&t._onerror(t._result),z(t)}function L(t,e){t._state===at&&(t._result=e,t._state=ot,0!==t._subscribers.length&&K(z,t))}function S(t,e){t._state===at&&(t._state=st,t._result=e,K(E,t))}function C(t,e,r,n){var i=t._subscribers,a=i.length;t._onerror=null,i[a]=e,i[a+ot]=r,i[a+st]=n,0===a&&t._state&&K(z,t)}function z(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n,i,a=t._result,o=0;oo;o++)C(n.resolve(t[o]),void 0,e,r);return i}function F(t){var e=this,r=new e(y);return S(r,t),r}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function B(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function U(t){this._id=dt++,this._state=void 0,this._result=void 0,this._subscribers=[],y!==t&&("function"!=typeof t&&D(),this instanceof U?I(this,t):B())}function V(t,e){this._instanceConstructor=t,this.promise=new t(y),Array.isArray(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?L(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&L(this.promise,this._result))):S(this.promise,this._validationError())}function q(){var t;if("undefined"!=typeof i)t=i;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var r=t.Promise;r&&"[object Promise]"===Object.prototype.toString.call(r.resolve())&&!r.cast||(t.Promise=pt)}var H;H=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var G,Y,X,W=H,Z=0,K=function(t,e){rt[Z]=t,rt[Z+1]=e,Z+=2,2===Z&&(Y?Y(p):X())},$="undefined"!=typeof window?window:void 0,Q=$||{},J=Q.MutationObserver||Q.WebKitMutationObserver,tt="undefined"!=typeof n&&"[object process]"==={}.toString.call(n),et="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,rt=new Array(1e3);X=tt?c():J?f():et?h():void 0===$&&"function"==typeof e?g():d();var nt=v,it=m,at=void 0,ot=1,st=2,lt=new P,ct=new P,ut=N,ft=j,ht=F,dt=0,pt=U;U.all=ut,U.race=ft,U.resolve=it,U.reject=ht,U._setScheduler=s,U._setAsap=l,U._asap=K,U.prototype={constructor:U,then:nt,"catch":function(t){return this.then(null,t)}};var gt=V;V.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},V.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===at&&t>r;r++)this._eachEntry(e[r],r)},V.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===it){var i=_(t);if(i===nt&&t._state!==at)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(r===pt){var a=new r(y);M(a,t,i),this._willSettleAt(a,e)}else this._willSettleAt(new r(function(e){e(t)}),e)}else this._willSettleAt(n(t),e)},V.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===at&&(this._remaining--,t===st?S(n,r):this._result[e]=r),0===this._remaining&&L(n,this._result)},V.prototype._willSettleAt=function(t,e){var r=this;C(t,void 0,function(t){r._settledAt(ot,e,t)},function(t){r._settledAt(st,e,t)})};var vt=q,mt={Promise:pt,polyfill:vt};"function"==typeof t&&t.amd?t(function(){return mt}):"undefined"!=typeof r&&r.exports?r.exports=mt:"undefined"!=typeof this&&(this.ES6Promise=mt),vt()}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:56}],117:[function(t,e,r){"use strict";function n(t){for(var e,r=t.length,n=0;r>n;n++)if(e=t.charCodeAt(n),(9>e||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(8192>e||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(t=+t,0===t&&n(r))return!1}else if("number"!==e)return!1;return 1>t-t}},{}],118:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}function i(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(0>a)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function a(t,e){for(var r=l.malloc(t.length,e),n=t.length,i=0;n>i;++i)r[i]=t[i];return r}function o(t,e){for(var r=1,n=e.length-1;n>=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}function s(t,e,r,i){if(r=r||t.ARRAY_BUFFER,i=i||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(i!==t.DYNAMIC_DRAW&&i!==t.STATIC_DRAW&&i!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=t.createBuffer(),o=new n(t,r,a,0,i);return o.update(e),o}var l=t("typedarray-pool"),c=t("ndarray-ops"),u=t("ndarray"),f=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"],h=n.prototype;h.bind=function(){this.gl.bindBuffer(this.type,this.handle)},h.unbind=function(){this.gl.bindBuffer(this.type,null)},h.dispose=function(){this.gl.deleteBuffer(this.handle)},h.update=function(t,e){if("number"!=typeof e&&(e=-1),this.bind(),"object"==typeof t&&"undefined"!=typeof t.shape){var r=t.dtype;if(f.indexOf(r)<0&&(r="float32"),this.type===this.gl.ELEMENT_ARRAY_BUFFER){var n=gl.getExtension("OES_element_index_uint");r=n&&"uint16"!==r?"uint32":"uint16"}if(r===t.dtype&&o(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=i(this.gl,this.type,this.length,this.usage,t.data,e):this.length=i(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=l.malloc(t.size,r),h=u(s,t.shape);c.assign(h,t),0>e?this.length=i(this.gl,this.type,this.length,this.usage,s,e):this.length=i(this.gl,this.type,this.length,this.usage,s.subarray(0,t.size),e),l.free(s)}}else if(Array.isArray(t)){var d;d=this.type===this.gl.ELEMENT_ARRAY_BUFFER?a(t,"uint16"):a(t,"float32"),0>e?this.length=i(this.gl,this.type,this.length,this.usage,d,e):this.length=i(this.gl,this.type,this.length,this.usage,d.subarray(0,t.length),e),l.free(d)}else if("object"==typeof t&&"number"==typeof t.length)this.length=i(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");t=0|t,0>=t&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=s},{ndarray:253,"ndarray-ops":252,"typedarray-pool":278}],119:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.shader=e,this.buffer=r,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.color=[0,0,0,1]}function i(t,e){var r=a(t.gl,l.vertex,l.fragment),i=o(t.gl),s=new n(t,r,i);return s.update(e),t.addObject(s),s}var a=t("gl-shader"),o=t("gl-buffer"),s=t("typedarray-pool"),l=t("./lib/shaders");e.exports=i;var c=[[1,0,0,1,0,0],[1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,1,0,0],[1,0,0,1,0,0],[1,0,-1,0,0,1],[1,0,-1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,1],[1,0,-1,0,0,1],[-1,0,-1,0,0,1],[-1,0,-1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,1],[-1,0,-1,0,0,1],[0,1,1,0,0,0],[0,1,-1,0,0,0],[0,-1,-1,0,0,0],[0,-1,-1,0,0,0],[0,1,1,0,0,0],[0,-1,1,0,0,0],[0,1,0,-1,1,0],[0,1,0,-1,-1,0],[0,1,0,1,-1,0],[0,1,0,1,1,0],[0,1,0,-1,1,0],[0,1,0,1,-1,0],[0,-1,0,-1,1,0],[0,-1,0,-1,-1,0],[0,-1,0,1,-1,0],[0,-1,0,1,1,0],[0,-1,0,-1,1,0],[0,-1,0,1,-1,0]],u=n.prototype;u.draw=function(){var t=[1,0,0,0,1,0,0,0,1],e=[1,1];return function(){var r=this.plot,n=this.shader,i=this.buffer,a=this.bounds,o=this.numPoints;if(o){var s=r.gl,l=r.dataBox,u=r.viewBox,f=r.pixelRatio,h=a[2]-a[0],d=a[3]-a[1],p=l[2]-l[0],g=l[3]-l[1];t[0]=2*h/p,t[4]=2*d/g,t[6]=2*(a[0]-l[0])/p-1,t[7]=2*(a[1]-l[1])/g-1;var v=u[2]-u[0],m=u[3]-u[1];e[0]=2*f/v,e[1]=2*f/m,i.bind(),n.bind(),n.uniforms.viewTransform=t, -n.uniforms.pixelScale=e,n.uniforms.color=this.color,n.attributes.position.pointer(s.FLOAT,!1,16,0),n.attributes.pixelOffset.pointer(s.FLOAT,!1,16,8),s.drawArrays(s.TRIANGLES,0,o*c.length)}}}(),u.drawPick=function(t){return t},u.pick=function(t,e){return null},u.update=function(t){t=t||{};var e,r,n,i=t.positions||[],a=t.errors||[],o=1;"lineWidth"in t&&(o=+t.lineWidth);var l=5;"capSize"in t&&(l=+t.capSize),this.color=(t.color||[0,0,0,1]).slice();var u=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=this.numPoints=i.length>>1;for(e=0;f>e;++e)r=i[2*e],n=i[2*e+1],u[0]=Math.min(r,u[0]),u[1]=Math.min(n,u[1]),u[2]=Math.max(r,u[2]),u[3]=Math.max(n,u[3]);u[2]===u[0]&&(u[2]+=1),u[3]===u[1]&&(u[3]+=1);var h=1/(u[2]-u[0]),d=1/(u[3]-u[1]),p=u[0],g=u[1],v=s.mallocFloat32(f*c.length*4),m=0;for(e=0;f>e;++e){r=i[2*e],n=i[2*e+1];for(var y=a[4*e],b=a[4*e+1],x=a[4*e+2],_=a[4*e+3],w=0;wA?A*=y:A>0&&(A*=b),0>M?M*=x:M>0&&(M*=_),v[m++]=h*(r-p+A),v[m++]=d*(n-g+M),v[m++]=o*k[2]+(l+o)*k[4],v[m++]=o*k[3]+(l+o)*k[5]}}this.buffer.update(v),s.free(v)},u.dispose=function(){this.plot.removeObject(this),this.shader.dispose(),this.buffer.dispose()}},{"./lib/shaders":120,"gl-buffer":118,"gl-shader":197,"typedarray-pool":278}],120:[function(t,e,r){e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n",fragment:"precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"}},{}],121:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}function i(t,e){for(var r=0;3>r;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}function a(t,e,r,n){for(var i=h[n],a=0;a=1},f.isTransparent=function(){return this.opacity<1},f.drawTransparent=f.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||u,i=r.projection=t.projection||u;r.model=t.model||u,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],c=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var f=0;3>f;++f)e.lineWidth(this.lineWidth[f]),r.capSize=this.capSize[f]*c,e.drawArrays(e.LINES,this.lineOffset[f],this.lineCount[f]);this.vao.unbind()};var h=function(){for(var t=new Array(3),e=0;3>e;++e){for(var r=[],n=1;2>=n;++n)for(var i=-1;1>=i;i+=2){var a=(n+e)%3,o=[0,0,0];o[a]=i,r.push(o)}t[e]=r}return t}();f.update=function(t){t=t||{},"lineWidth"in t&&(this.lineWidth=t.lineWidth,Array.isArray(this.lineWidth)||(this.lineWidth=[this.lineWidth,this.lineWidth,this.lineWidth])),"capSize"in t&&(this.capSize=t.capSize,Array.isArray(this.capSize)||(this.capSize=[this.capSize,this.capSize,this.capSize])),"opacity"in t&&(this.opacity=t.opacity);var e=t.color||[[0,0,0],[0,0,0],[0,0,0]],r=t.position,n=t.error;if(Array.isArray(e[0])||(e=[e,e,e]),r&&n){var o=[],s=r.length,l=0;this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.lineCount=[0,0,0];for(var c=0;3>c;++c){this.lineOffset[c]=l;t:for(var u=0;s>u;++u){for(var f=r[u],h=0;3>h;++h)if(isNaN(f[h])||!isFinite(f[h]))continue t;var d=n[u],p=e[c];if(Array.isArray(p[0])&&(p=e[u]),3===p.length&&(p=[p[0],p[1],p[2],1]),!isNaN(d[0][c])&&!isNaN(d[1][c])){if(d[0][c]<0){var g=f.slice();g[c]+=d[0][c],o.push(f[0],f[1],f[2],p[0],p[1],p[2],p[3],0,0,0,g[0],g[1],g[2],p[0],p[1],p[2],p[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,p,c)}if(d[1][c]>0){var g=f.slice();g[c]+=d[1][c],o.push(f[0],f[1],f[2],p[0],p[1],p[2],p[3],0,0,0,g[0],g[1],g[2],p[0],p[1],p[2],p[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,p,c)}}}this.lineCount[c]=l-this.lineOffset[c]}this.buffer.update(o)}},f.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":122,"gl-buffer":118,"gl-vao":226}],122:[function(t,e,r){"use strict";var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}",a="precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}";e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"},{name:"offset",type:"vec3"},{name:"color",type:"vec4"}])}},{"gl-shader":197}],123:[function(t,e,r){"use strict";function n(t){var e=t.getParameter(t.FRAMEBUFFER_BINDING),r=t.getParameter(t.RENDERBUFFER_BINDING),n=t.getParameter(t.TEXTURE_BINDING_2D);return[e,r,n]}function i(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function a(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);y=new Array(r+1);for(var n=0;r>=n;++n){for(var i=new Array(r),a=0;n>a;++a)i[a]=t.COLOR_ATTACHMENT0+a;for(var a=n;r>a;++a)i[a]=t.NONE;y[n]=i}}function o(t){switch(t){case p:throw new Error("gl-fbo: Framebuffer unsupported");case g:throw new Error("gl-fbo: Framebuffer incomplete attachment");case v:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case m:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function s(t,e,r,n,i,a){if(!n)return null;var o=d(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function l(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function c(t){var e=n(t.gl),r=t.gl,a=t.handle=r.createFramebuffer(),c=t._shape[0],u=t._shape[1],f=t.color.length,h=t._ext,d=t._useStencil,p=t._useDepth,g=t._colorType;r.bindFramebuffer(r.FRAMEBUFFER,a);for(var v=0;f>v;++v)t.color[v]=s(r,c,u,g,r.RGBA,r.COLOR_ATTACHMENT0+v);0===f?(t._color_rb=l(r,c,u,r.RGBA4,r.COLOR_ATTACHMENT0),h&&h.drawBuffersWEBGL(y[0])):f>1&&h.drawBuffersWEBGL(y[f]);var m=r.getExtension("WEBGL_depth_texture");m?d?t.depth=s(r,c,u,m.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):p&&(t.depth=s(r,c,u,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):p&&d?t._depth_rb=l(r,c,u,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):p?t._depth_rb=l(r,c,u,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):d&&(t._depth_rb=l(r,c,u,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var b=r.checkFramebufferStatus(r.FRAMEBUFFER);if(b!==r.FRAMEBUFFER_COMPLETE){t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null);for(var v=0;vl;++l)this.color[l]=null;this._color_rb=null,this.depth=null,this._depth_rb=null,this._colorType=n,this._useDepth=a,this._useStencil=o;var u=this,f=[0|e,0|r];Object.defineProperties(f,{0:{get:function(){return u._shape[0]},set:function(t){return u.width=t}},1:{get:function(){return u._shape[1]},set:function(t){return u.height=t}}}),this._shapeVector=f,c(this)}function f(t,e,r){if(t._destroyed)throw new Error("gl-fbo: Can't resize destroyed FBO");if(t._shape[0]!==e||t._shape[1]!==r){var a=t.gl,s=a.getParameter(a.MAX_RENDERBUFFER_SIZE);if(0>e||e>s||0>r||r>s)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var l=n(a),c=0;ce||e>o||0>r||r>o)throw new Error("gl-fbo: Parameters are too large for FBO");n=n||{};var s=1;if("color"in n){if(s=Math.max(0|n.color,0),0>s)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(s>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(s>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+s+" draw buffers")}}var l=t.UNSIGNED_BYTE,c=t.getExtension("OES_texture_float");if(n.float&&s>0){if(!c)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&s>0&&c&&(l=t.FLOAT);var f=!0;"depth"in n&&(f=!!n.depth);var h=!1;return"stencil"in n&&(h=!!n.stencil),new u(t,e,r,l,s,f,h,i)}var d=t("gl-texture2d");e.exports=h;var p,g,v,m,y=null,b=u.prototype;Object.defineProperties(b,{shape:{get:function(){return this._destroyed?[0,0]:this._shapeVector},set:function(t){if(Array.isArray(t)||(t=[0|t,0|t]),2!==t.length)throw new Error("gl-fbo: Shape vector must be length 2");var e=0|t[0],r=0|t[1];return f(this,e,r),[e,r]},enumerable:!1},width:{get:function(){return this._destroyed?0:this._shape[0]},set:function(t){return t=0|t,f(this,t,this._shape[1]),t},enumerable:!1},height:{get:function(){return this._destroyed?0:this._shape[1]},set:function(t){return t=0|t,f(this,this._shape[0],t),t},enumerable:!1}}),b.bind=function(){if(!this._destroyed){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.handle),t.viewport(0,0,this._shape[0],this._shape[1])}},b.dispose=function(){if(!this._destroyed){this._destroyed=!0;var t=this.gl;t.deleteFramebuffer(this.handle),this.handle=null,this.depth&&(this.depth.dispose(),this.depth=null),this._depth_rb&&(t.deleteRenderbuffer(this._depth_rb),this._depth_rb=null);for(var e=0;e2&&!this.usingDashes){var C=this.mitreShader;C.bind();var z=C.uniforms;z.matrix=t,z.color=s,z.screenShape=e,z.radius=l*p,C.attributes.p.pointer(f.FLOAT,!1,48,0),f.drawArrays(f.POINTS,0,u/3|0)}}}}(),h.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0],r=[0,0,0,0];return function(n){var i=this.plot,a=this.pickShader,o=this.lineBuffer,s=this.pickBuffer,l=this.width,c=this.numPoints,u=this.bounds,f=this.vertCount,h=i.gl,d=i.viewBox,p=i.dataBox,g=i.pickPixelRatio,v=u[2]-u[0],m=u[3]-u[1],y=p[2]-p[0],b=p[3]-p[1],x=d[2]-d[0],_=d[3]-d[1];if(this.pickOffset=n,!f)return n+c;t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(u[0]-p[0])/y-1,t[7]=2*(u[1]-p[1])/b-1,e[0]=x,e[1]=_,r[0]=255&n,r[1]=n>>>8&255,r[2]=n>>>16&255,r[3]=n>>>24,a.bind();var w=a.uniforms;w.matrix=t,w.width=l*g,w.pickOffset=r,w.screenShape=e;var k=a.attributes;return o.bind(),k.a.pointer(h.FLOAT,!1,16,0),k.d.pointer(h.FLOAT,!1,16,8),s.bind(),k.pick0.pointer(h.UNSIGNED_BYTE,!1,8,0),k.pick1.pointer(h.UNSIGNED_BYTE,!1,8,4),h.drawArrays(h.TRIANGLES,0,f),n+c}}(),h.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.data;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},h.update=function(t){t=t||{};var e=this.plot.gl;!!t.connectGaps;this.color=(t.color||[0,0,1,1]).slice(),this.width=+(t.width||1),this.fill=(t.fill||[!1,!1,!1,!1]).slice(),this.fillColor=i(t.fillColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);for(var r=t.dashes||[1],n=0,a=0;a1,this.dashPattern=l(e,c(o,[n,1,4],[1,0,0])),this.dashPattern.minFilter=e.NEAREST,this.dashPattern.magFilter=e.NEAREST,this.dashLength=n,u.free(o);var d=t.positions;this.data=d;var p=this.bounds;p[0]=p[1]=1/0,p[2]=p[3]=-(1/0);var g=this.numPoints=d.length>>>1;if(0!==g){for(var a=0;g>a;++a){var v=d[2*a],m=d[2*a+1];isNaN(v)||isNaN(m)||(p[0]=Math.min(p[0],v),p[1]=Math.min(p[1],m),p[2]=Math.max(p[2],v),p[3]=Math.max(p[3],m))}p[0]===p[2]&&(p[2]+=1),p[3]===p[1]&&(p[3]+=1);for(var y=u.mallocFloat32(24*(g-1)),b=u.mallocUint32(12*(g-1)),x=y.length,_=b.length,s=g,w=0;s>1;){var k=--s,v=d[2*s],m=d[2*s+1],A=k-1,M=d[2*A],T=d[2*A+1];if(!(isNaN(v)||isNaN(m)||isNaN(M)||isNaN(T))){w+=1,v=(v-p[0])/(p[2]-p[0]),m=(m-p[1])/(p[3]-p[1]),M=(M-p[0])/(p[2]-p[0]),T=(T-p[1])/(p[3]-p[1]);var E=M-v,L=T-m,S=k|1<<24,C=k-1,z=k,P=k-1|1<<24;y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C}}this.vertCount=6*w,this.lineBuffer.update(y.subarray(x)),this.pickBuffer.update(b.subarray(_)),u.free(y),u.free(b)}},h.dispose=function(){this.plot.removeObject(this),this.lineBuffer.dispose(),this.pickBuffer.dispose(),this.lineShader.dispose(),this.mitreShader.dispose(),this.fillShader.dispose(),this.pickShader.dispose(),this.dashPattern.dispose()}},{"./lib/shaders":124,"gl-buffer":118,"gl-shader":197,"gl-texture2d":222,ndarray:253,"typedarray-pool":278}],126:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}",s=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return n(t,i,a,null,s)},r.createPickShader=function(t){return n(t,i,o,null,s)}},{"gl-shader":197}],127:[function(t,e,r){"use strict";function n(t,e){for(var r=0,n=0;3>n;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function i(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;3>r;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function a(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function o(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}function s(t){var e=t.gl||t.scene&&t.scene.gl,r=g(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=v(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=l(e),a=c(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),s=d(new Array(1024),[256,1,4]),f=0;1024>f;++f)s.data[f]=255;var h=u(e,s);h.wrap=e.REPEAT;var p=new o(e,r,n,i,a,h);return p.update(t),p}e.exports=s;var l=t("gl-buffer"),c=t("gl-vao"),u=t("gl-texture2d"),f=t("glsl-read-float"),h=t("binary-search-bounds"),d=t("ndarray"),p=t("./lib/shaders"),g=p.createShader,v=p.createPickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],y=o.prototype;y.isTransparent=function(){return this.opacity<1},y.isOpaque=function(){return this.opacity>=1},y.pickSlots=1,y.setPickBase=function(t){this.pickId=t},y.drawTransparent=y.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,clipBounds:i(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,pickId:this.pickId,clipBounds:i(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.update=function(t){var e,r;this.dirty=!0;var i=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var a=t.position||t.positions;if(a){var o=t.color||t.colors||[0,0,0,1],s=t.lineWidth||1,l=[],c=[],u=[],f=0,p=0,g=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],v=!1;t:for(e=1;er;++r){if(isNaN(m[r])||isNaN(y[r])||!isFinite(m[r])||!isFinite(y[r])){if(!i&&l.length>0){for(var b=0;24>b;++b)l.push(l[l.length-12]);p+=2,v=!0}continue t}g[0][r]=Math.min(g[0][r],m[r],y[r]),g[1][r]=Math.max(g[1][r],m[r],y[r])} -var x,_;Array.isArray(o[0])?(x=o[e-1],_=o[e]):x=_=o,3===x.length&&(x=[x[0],x[1],x[2],1]),3===_.length&&(_=[_[0],_[1],_[2],1]);var w;w=Array.isArray(s)?s[e-1]:s;var k=f;if(f+=n(m,y),v){for(r=0;2>r;++r)l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3]);p+=2,v=!1}l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3],m[0],m[1],m[2],y[0],y[1],y[2],k,-w,x[0],x[1],x[2],x[3],y[0],y[1],y[2],m[0],m[1],m[2],f,-w,_[0],_[1],_[2],_[3],y[0],y[1],y[2],m[0],m[1],m[2],f,w,_[0],_[1],_[2],_[3]),p+=4}if(this.buffer.update(l),c.push(f),u.push(a[a.length-1].slice()),this.bounds=g,this.vertexCount=p,this.points=u,this.arcLength=c,"dashes"in t){var A=t.dashes,M=A.slice();for(M.unshift(0),e=1;ee;++e){for(r=0;4>r;++r)T.set(e,0,r,0);1&h.le(M,M[M.length-1]*e/255)?T.set(e,0,0,0):T.set(e,0,0,255)}this.texture.setPixels(T)}}},y.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},y.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=f(t.value[0],t.value[1],t.value[2],0),r=h.le(this.arcLength,e);if(0>r)return null;if(r===this.arcLength.length-1)return new a(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],o=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),s=1-o,l=[0,0,0],c=0;3>c;++c)l[c]=s*n[c]+o*i[c];var u=Math.min(.5>o?r:r+1,this.points.length-1);return new a(e,l,u,this.points[u])}},{"./lib/shaders":126,"binary-search-bounds":128,"gl-buffer":118,"gl-texture2d":222,"gl-vao":226,"glsl-read-float":129,ndarray:253}],128:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],129:[function(t,e,r){function n(t,e,r,n){return i[0]=n,i[1]=r,i[2]=e,i[3]=t,a[0]}e.exports=n;var i=new Uint8Array(4),a=new Float32Array(i.buffer)},{}],130:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],f=u*o-s*c,h=-u*a+s*l,d=c*a-o*l,p=r*f+n*h+i*d;return p?(p=1/p,t[0]=f*p,t[1]=(-u*n+i*c)*p,t[2]=(s*n-i*o)*p,t[3]=h*p,t[4]=(u*r-i*l)*p,t[5]=(-s*r+i*a)*p,t[6]=d*p,t[7]=(-c*r+n*l)*p,t[8]=(o*r-n*a)*p,t):null}e.exports=n},{}],131:[function(t,e,r){function n(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}e.exports=n},{}],132:[function(t,e,r){function n(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],133:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],c=t[8],u=t[9],f=t[10],h=t[11],d=t[12],p=t[13],g=t[14],v=t[15],m=e*o-r*a,y=e*s-n*a,b=e*l-i*a,x=r*s-n*o,_=r*l-i*o,w=n*l-i*s,k=c*p-u*d,A=c*g-f*d,M=c*v-h*d,T=u*g-f*p,E=u*v-h*p,L=f*v-h*g;return m*L-y*E+b*T+x*M-_*A+w*k}e.exports=n},{}],134:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,c=r*o,u=n*o,f=n*s,h=i*o,d=i*s,p=i*l,g=a*o,v=a*s,m=a*l;return t[0]=1-f-p,t[1]=u+m,t[2]=h-v,t[3]=0,t[4]=u-m,t[5]=1-c-p,t[6]=d+g,t[7]=0,t[8]=h+v,t[9]=d-g,t[10]=1-c-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],135:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,c=a+a,u=n*s,f=n*l,h=n*c,d=i*l,p=i*c,g=a*c,v=o*s,m=o*l,y=o*c;return t[0]=1-(d+g),t[1]=f+y,t[2]=h-m,t[3]=0,t[4]=f-y,t[5]=1-(u+g),t[6]=p+v,t[7]=0,t[8]=h+m,t[9]=p-v,t[10]=1-(u+d),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}e.exports=n},{}],136:[function(t,e,r){function n(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],137:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],f=e[9],h=e[10],d=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*c-a*o,_=n*l-i*s,w=n*c-a*s,k=i*c-a*l,A=u*g-f*p,M=u*v-h*p,T=u*m-d*p,E=f*v-h*g,L=f*m-d*g,S=h*m-d*v,C=y*S-b*L+x*E+_*T-w*M+k*A;return C?(C=1/C,t[0]=(s*S-l*L+c*E)*C,t[1]=(i*L-n*S-a*E)*C,t[2]=(g*k-v*w+m*_)*C,t[3]=(h*w-f*k-d*_)*C,t[4]=(l*T-o*S-c*M)*C,t[5]=(r*S-i*T+a*M)*C,t[6]=(v*x-p*k-m*b)*C,t[7]=(u*k-h*x+d*b)*C,t[8]=(o*L-s*T+c*A)*C,t[9]=(n*T-r*L-a*A)*C,t[10]=(p*w-g*x+m*y)*C,t[11]=(f*x-u*w-d*y)*C,t[12]=(s*M-o*E-l*A)*C,t[13]=(r*E-n*M+i*A)*C,t[14]=(g*b-p*_-v*y)*C,t[15]=(u*_-f*b+h*y)*C,t):null}e.exports=n},{}],138:[function(t,e,r){function n(t,e,r,n){var a,o,s,l,c,u,f,h,d,p,g=e[0],v=e[1],m=e[2],y=n[0],b=n[1],x=n[2],_=r[0],w=r[1],k=r[2];return Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6&&Math.abs(m-k)<1e-6?i(t):(f=g-_,h=v-w,d=m-k,p=1/Math.sqrt(f*f+h*h+d*d),f*=p,h*=p,d*=p,a=b*d-x*h,o=x*f-y*d,s=y*h-b*f,p=Math.sqrt(a*a+o*o+s*s),p?(p=1/p,a*=p,o*=p,s*=p):(a=0,o=0,s=0),l=h*s-d*o,c=d*a-f*s,u=f*o-h*a,p=Math.sqrt(l*l+c*c+u*u),p?(p=1/p,l*=p,c*=p,u*=p):(l=0,c=0,u=0),t[0]=a,t[1]=l,t[2]=f,t[3]=0,t[4]=o,t[5]=c,t[6]=h,t[7]=0,t[8]=s,t[9]=u,t[10]=d,t[11]=0,t[12]=-(a*g+o*v+s*m),t[13]=-(l*g+c*v+u*m),t[14]=-(f*g+h*v+d*m),t[15]=1,t)}var i=t("./identity");e.exports=n},{"./identity":136}],139:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],f=e[8],h=e[9],d=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*f+w*g,t[1]=b*i+x*l+_*h+w*v,t[2]=b*a+x*c+_*d+w*m,t[3]=b*o+x*u+_*p+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*f+w*g,t[5]=b*i+x*l+_*h+w*v,t[6]=b*a+x*c+_*d+w*m,t[7]=b*o+x*u+_*p+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*f+w*g,t[9]=b*i+x*l+_*h+w*v,t[10]=b*a+x*c+_*d+w*m,t[11]=b*o+x*u+_*p+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*f+w*g,t[13]=b*i+x*l+_*h+w*v,t[14]=b*a+x*c+_*d+w*m,t[15]=b*o+x*u+_*p+w*y,t}e.exports=n},{}],140:[function(t,e,r){function n(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t}e.exports=n},{}],141:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,c,u,f,h,d,p,g,v,m,y,b,x,_,w,k,A,M,T,E,L=n[0],S=n[1],C=n[2],z=Math.sqrt(L*L+S*S+C*C);return Math.abs(z)<1e-6?null:(z=1/z,L*=z,S*=z,C*=z,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],c=e[2],u=e[3],f=e[4],h=e[5],d=e[6],p=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=S*L*o+C*i,_=C*L*o-S*i,w=L*S*o-C*i,k=S*S*o+a,A=C*S*o+L*i,M=L*C*o+S*i,T=S*C*o-L*i,E=C*C*o+a,t[0]=s*b+f*x+g*_,t[1]=l*b+h*x+v*_,t[2]=c*b+d*x+m*_,t[3]=u*b+p*x+y*_,t[4]=s*w+f*k+g*A,t[5]=l*w+h*k+v*A,t[6]=c*w+d*k+m*A,t[7]=u*w+p*k+y*A,t[8]=s*M+f*T+g*E,t[9]=l*M+h*T+v*E,t[10]=c*M+d*T+m*E,t[11]=u*M+p*T+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}e.exports=n},{}],142:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],c=e[8],u=e[9],f=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+c*n,t[5]=o*i+u*n,t[6]=s*i+f*n,t[7]=l*i+h*n,t[8]=c*i-a*n,t[9]=u*i-o*n,t[10]=f*i-s*n,t[11]=h*i-l*n,t}e.exports=n},{}],143:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[8],u=e[9],f=e[10],h=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-c*n,t[1]=o*i-u*n,t[2]=s*i-f*n,t[3]=l*i-h*n,t[8]=a*n+c*i,t[9]=o*n+u*i,t[10]=s*n+f*i,t[11]=l*n+h*i,t}e.exports=n},{}],144:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[4],u=e[5],f=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+c*n,t[1]=o*i+u*n,t[2]=s*i+f*n,t[3]=l*i+h*n,t[4]=c*i-a*n,t[5]=u*i-o*n,t[6]=f*i-s*n,t[7]=h*i-l*n,t}e.exports=n},{}],145:[function(t,e,r){function n(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}e.exports=n},{}],146:[function(t,e,r){function n(t,e,r){var n,i,a,o,s,l,c,u,f,h,d,p,g=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],f=e[8],h=e[9],d=e[10],p=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=c,t[7]=u,t[8]=f,t[9]=h,t[10]=d,t[11]=p,t[12]=n*g+s*v+f*m+e[12],t[13]=i*g+l*v+h*m+e[13],t[14]=a*g+c*v+d*m+e[14],t[15]=o*g+u*v+p*m+e[15]),t}e.exports=n},{}],147:[function(t,e,r){function n(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}e.exports=n},{}],148:[function(t,e,r){"use strict";function n(t,e){for(var r=[0,0,0,0],n=0;4>n;++n)for(var i=0;4>i;++i)r[i]+=t[4*n+i]*e[n];return r}function i(t,e,r,i,a){for(var o=n(i,n(r,n(e,[t[0],t[1],t[2],1]))),s=0;3>s;++s)o[s]/=o[3];return[.5*a[0]*(1+o[0]),.5*a[1]*(1-o[1])]}function a(t,e){if(2===t.length){for(var r=0,n=0,i=0;2>i;++i)r+=Math.pow(e[i]-t[0][i],2),n+=Math.pow(e[i]-t[1][i],2);return r=Math.sqrt(r),n=Math.sqrt(n),1e-6>r+n?[1,0]:[n/(r+n),r/(n+r)]}if(3===t.length){var a=[0,0];return c(t[0],t[1],t[2],e,a),l(t,a)}return[]}function o(t,e){for(var r=[0,0,0],n=0;no;++o)r[o]+=a*i[o];return r}function s(t,e,r,n,s,l){if(1===t.length)return[0,t[0].slice()];for(var c=new Array(t.length),u=0;up;++p)d+=Math.pow(c[u][p]-e[p],2);h>d&&(h=d,f=u)}for(var g=a(c,e),v=0,u=0;3>u;++u){if(g[u]<-.001||g[u]>1.0001)return null;v+=g[u]}return Math.abs(v-1)>.001?null:[f,o(t,g),g]}var l=t("barycentric"),c=t("polytope-closest-point/lib/closest_point_2d.js");e.exports=s},{barycentric:151,"polytope-closest-point/lib/closest_point_2d.js":153}],149:[function(t,e,r){var n="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}",i="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}",a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",c="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}",u="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}",f="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}",h="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}",d="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n";r.meshShader={vertex:n,fragment:i,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:a,fragment:o,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:s,fragment:l,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:c,fragment:u,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:f,fragment:u,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:h,fragment:d,attributes:[{name:"position",type:"vec3"}]}},{}],150:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,c,u,f,h,d,p,g,v,m,y,b,x,_,w,k,A,M,T){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=u,this.triangleNormals=h,this.triangleUVs=f,this.triangleIds=c,this.triangleVAO=d,this.triangleCount=0,this.lineWidth=1,this.edgePositions=p,this.edgeColors=v,this.edgeUVs=m,this.edgeIds=g,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=b,this.pointColors=_,this.pointUVs=w,this.pointSizes=k,this.pointIds=x,this.pointVAO=A,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=M,this.contourVAO=T,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=I,this._view=I,this._projection=I,this._resolution=[1,1]}function i(t){for(var e=A({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;256>n;++n){for(var i=e[n],a=0;3>a;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return k(r,[256,256,4],[4,0,1])}function a(t,e,r){for(var n=new Array(e),i=0;e>i;++i)n[i]=0;for(var a=t.length,i=0;a>i;++i)for(var o=t[i],s=0;sn;++n)r[n]=t[n][2];return r}function s(t){var e=v(t,S);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.normal.location=4,e}function l(t){var e=v(t,C);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e}function c(t){var e=v(t,z);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function u(t){var e=v(t,P);return e.attributes.position.location=0,e.attributes.id.location=1,e}function f(t){var e=v(t,R);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function h(t){var e=v(t,O);return e.attributes.position.location=0,e}function d(t){var e=t.gl,r=s(e),i=l(e),a=c(e),o=u(e),d=f(e),p=h(e),g=b(e,k(new Uint8Array([255,255,255,255]),[1,1,4]));g.generateMipmap(),g.minFilter=e.LINEAR_MIPMAP_LINEAR,g.magFilter=e.LINEAR;var v=m(e),x=m(e),_=m(e),w=m(e),A=m(e),M=y(e,[{buffer:v,type:e.FLOAT,size:3},{buffer:A,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:x,type:e.FLOAT,size:4},{buffer:_,type:e.FLOAT,size:2},{buffer:w,type:e.FLOAT,size:3}]),T=m(e),E=m(e),L=m(e),S=m(e),C=y(e,[{buffer:T,type:e.FLOAT,size:3},{buffer:S,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:E,type:e.FLOAT,size:4},{buffer:L,type:e.FLOAT,size:2}]),z=m(e),P=m(e),R=m(e),O=m(e),I=m(e),N=y(e,[{buffer:z,type:e.FLOAT,size:3},{buffer:I,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:P,type:e.FLOAT,size:4},{buffer:R,type:e.FLOAT,size:2},{buffer:O,type:e.FLOAT,size:1}]),j=m(e),F=y(e,[{buffer:j,type:e.FLOAT,size:3}]),D=new n(e,g,r,i,a,o,d,p,v,A,x,_,w,M,T,S,E,L,C,z,I,P,R,O,N,j,F);return D.update(t),D}var p=1e-6,g=1e-6,v=t("gl-shader"),m=t("gl-buffer"),y=t("gl-vao"),b=t("gl-texture2d"),x=t("normals"),_=t("gl-mat4/multiply"),w=t("gl-mat4/invert"),k=t("ndarray"),A=t("colormap"),M=t("simplicial-complex-contour"),T=t("typedarray-pool"),E=t("./lib/shaders"),L=t("./lib/closest-point"),S=E.meshShader,C=E.wireShader,z=E.pointShader,P=E.pickShader,R=E.pointPickShader,O=E.contourShader,I=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],N=n.prototype;N.isOpaque=function(){return this.opacity>=1},N.isTransparent=function(){return this.opacity<1},N.pickSlots=1,N.setPickBase=function(t){this.pickId=t},N.highlight=function(t){if(!t||!this.contourEnable)return void(this.contourCount=0);for(var e=M(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=T.mallocFloat32(6*a),s=0,l=0;a>l;++l)for(var c=r[l],u=0;2>u;++u){var f=c[0];2===c.length&&(f=c[u]);for(var h=n[f][0],d=n[f][1],p=i[f],g=1-p,v=this.positions[h],m=this.positions[d],y=0;3>y;++y)o[s++]=p*v[y]+g*m[y]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),T.free(o)},N.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),t.texture?(this.texture.dispose(),this.texture=b(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(i(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions;if(n&&r){var s=[],l=[],c=[],u=[],f=[],h=[],d=[],v=[],m=[],y=[],_=[],w=[],k=[],A=[];this.cells=r,this.positions=n;var M=t.vertexNormals,T=t.cellNormals,E=void 0===t.vertexNormalsEpsilon?p:t.vertexNormalsEpsilon,L=void 0===t.faceNormalsEpsilon?g:t.faceNormalsEpsilon;t.useFacetNormals&&!T&&(T=x.faceNormals(r,n,L)),T||M||(M=x.vertexNormals(r,n,E));var S=t.vertexColors,C=t.cellColors,z=t.meshColor||[1,1,1,1],P=t.vertexUVs,R=t.vertexIntensity,O=t.cellUVs,I=t.cellIntensity,N=1/0,j=-(1/0);if(!P&&!O)if(R)for(var F=0;Fq;++q)!isNaN(V[q])&&isFinite(V[q])&&(this.bounds[0][q]=Math.min(this.bounds[0][q],V[q]),this.bounds[1][q]=Math.max(this.bounds[1][q],V[q]));var H=0,G=0,Y=0;t:for(var F=0;Fq;++q)if(isNaN(V[q])||!isFinite(V[q]))continue t;y.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?_.push(Z[0],Z[1],Z[2],1):_.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-N)/(j-N),0]:O?O[F]:I?[(I[F]-N)/(j-N),0]:[(V[2]-N)/(j-N),0],w.push(K[0],K[1]),B?k.push(B[W]):k.push(U),A.push(F),Y+=1;break;case 2:for(var q=0;2>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;2>q;++q){var W=X[q],V=n[W];h.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?d.push(Z[0],Z[1],Z[2],1):d.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-N)/(j-N),0]:O?O[F]:I?[(I[F]-N)/(j-N),0]:[(V[2]-N)/(j-N),0],v.push(K[0],K[1]),m.push(F)}G+=1;break;case 3:for(var q=0;3>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;3>q;++q){var W=X[q],V=n[W];s.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?l.push(Z[0],Z[1],Z[2],1):l.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-N)/(j-N),0]:O?O[F]:I?[(I[F]-N)/(j-N),0]:[(V[2]-N)/(j-N),0],u.push(K[0],K[1]);var Q;Q=M?M[W]:T[F],c.push(Q[0],Q[1],Q[2]),f.push(F)}H+=1}}this.pointCount=Y,this.edgeCount=G,this.triangleCount=H,this.pointPositions.update(y),this.pointColors.update(_),this.pointUVs.update(w),this.pointSizes.update(k),this.pointIds.update(new Uint32Array(A)),this.edgePositions.update(h),this.edgeColors.update(d),this.edgeUVs.update(v),this.edgeIds.update(new Uint32Array(m)),this.trianglePositions.update(s),this.triangleColors.update(l),this.triangleUVs.update(u),this.triangleNormals.update(c),this.triangleIds.update(new Uint32Array(f))}},N.drawTransparent=N.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||I,n=t.view||I,i=t.projection||I,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,contourColor:this.contourColor,texture:0};this.texture.bind(0);var l=new Array(16);_(l,s.view,s.model),_(l,s.projection,l),w(l,l);for(var o=0;3>o;++o)s.eyePosition[o]=l[12+o]/l[15];for(var c=l[15],o=0;3>o;++o)c+=this.lightPosition[o]*l[4*o+3];for(var o=0;3>o;++o){for(var u=l[12+o],f=0;3>f;++f)u+=l[4*f+o]*this.lightPosition[f];s.lightPosition[o]=u/c}if(this.triangleCount>0){var h=this.triShader;h.bind(),h.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}if(this.edgeCount>0&&this.lineWidth>0){var h=this.lineShader;h.bind(),h.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()}if(this.pointCount>0){var h=this.pointShader;h.bind(),h.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}if(this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0){var h=this.contourShader;h.bind(),h.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind()}},N.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||I,n=t.view||I,i=t.projection||I,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255},l=this.pickShader;if(l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0){var l=this.pointPickShader;l.bind(),l.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}},N.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;ao;++o){for(var s=new Array(r+1),l=0;r>=l;++l)s[l]=t[l][o];i[o]=s}i[r]=new Array(r+1);for(var o=0;r>=o;++o)i[r][o]=1;for(var c=new Array(r+1),o=0;r>o;++o)c[o]=e[o];c[r]=1;var u=a(i,c),f=n(u[r+1]);0===f&&(f=1);for(var h=new Array(r+1),o=0;r>=o;++o)h[o]=n(u[o])/f;return h}e.exports=i;var a=t("robust-linear-solve")},{"robust-linear-solve":256}],152:[function(t,e,r){var n=1e-6,i=1e-6;r.vertexNormals=function(t,e,r){for(var i=e.length,a=new Array(i),o=void 0===r?n:r,s=0;i>s;++s)a[s]=[0,0,0];for(var s=0;sx;++x)v[x]=d[x]-p[x],m+=v[x]*v[x],y[x]=g[x]-p[x],b+=y[x]*y[x];if(m*b>o)for(var _=a[u],w=1/Math.sqrt(m*b),x=0;3>x;++x){var k=(x+1)%3,A=(x+2)%3;_[x]+=w*(y[k]*v[A]-y[A]*v[k])}}for(var s=0;i>s;++s){for(var _=a[s],M=0,x=0;3>x;++x)M+=_[x]*_[x];if(M>o)for(var w=1/Math.sqrt(M),x=0;3>x;++x)_[x]*=w;else for(var x=0;3>x;++x)_[x]=0}return a},r.faceNormals=function(t,e,r){for(var n=t.length,a=new Array(n),o=void 0===r?i:r,s=0;n>s;++s){for(var l=t[s],c=new Array(3),u=0;3>u;++u)c[u]=e[l[u]];for(var f=new Array(3),h=new Array(3),u=0;3>u;++u)f[u]=c[1][u]-c[0][u],h[u]=c[2][u]-c[0][u];for(var d=new Array(3),p=0,u=0;3>u;++u){var g=(u+1)%3,v=(u+2)%3;d[u]=f[g]*h[v]-f[v]*h[g],p+=d[u]*d[u]}p=p>o?1/Math.sqrt(p):0;for(var u=0;3>u;++u)d[u]*=p;a[s]=d}return a}},{}],153:[function(t,e,r){"use strict";function n(t,e,r,n,s){i.length=x+_)if(0>x)0>_&&0>h?(_=0,-h>=c?(x=1,y=c+2*h+p):(x=-h/c,y=h*x+p)):(x=0,d>=0?(_=0,y=p):-d>=f?(_=1,y=f+2*d+p):(_=-d/f,y=d*_+p));else if(0>_)_=0,h>=0?(x=0,y=p):-h>=c?(x=1,y=c+2*h+p):(x=-h/c,y=h*x+p);else{var w=1/b;x*=w,_*=w,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p}else{var k,A,M,T;0>x?(k=u+h,A=f+d,A>k?(M=A-k,T=c-2*u+f,M>=T?(x=1,_=0,y=c+2*h+p):(x=M/T,_=1-x,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p)):(x=0,0>=A?(_=1,y=f+2*d+p):d>=0?(_=0,y=p):(_=-d/f,y=d*_+p))):0>_?(k=u+d,A=c+h,A>k?(M=A-k,T=c-2*u+f,M>=T?(_=1,x=0,y=f+2*d+p):(_=M/T,x=1-_,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p)):(_=0,0>=A?(x=1,y=c+2*h+p):h>=0?(x=0,y=p):(x=-h/c,y=h*x+p))):(M=f+d-u-h,0>=M?(x=0,_=1,y=f+2*d+p):(T=c-2*u+f,M>=T?(x=1,_=0,y=c+2*h+p):(x=M/T,_=1-x,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p)))}for(var E=1-x-_,l=0;ly?0:y}var i=new Float64Array(4),a=new Float64Array(4),o=new Float64Array(4);e.exports=n},{}],154:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r=0|Math.max(r,t[n].length);return r-1}function i(t,e){for(var r=t.length,n=f.mallocUint8(r),i=0;r>i;++i)n[i]=t[i]o;++o)for(var s=t[o],e=s.length,l=0;e>l;++l)for(var c=0;l>c;++c){var d=s[c],p=s[l];i[a++]=0|Math.min(d,p),i[a++]=0|Math.max(d,p)}var g=a/2|0;h(u(i,[g,2]));for(var v=2,o=2;a>o;o+=2)i[o-2]===i[o]&&i[o-1]===i[o+1]||(i[v++]=i[o],i[v++]=i[o+1]);return u(i,[v/2|0,2])}function o(t,e,r,n){for(var i=t.data,a=t.shape[0],o=f.mallocDouble(a),s=0,l=0;a>l;++l){var c=i[2*l],h=i[2*l+1];if(r[c]!==r[h]){var d=e[c],p=e[h];i[2*s]=c,i[2*s+1]=h,o[s++]=(p-n)/(p-d)}}return t.shape[0]=s,u(o,[s])}function s(t,e){var r=f.mallocInt32(2*e),n=t.shape[0],i=t.data;r[0]=0;for(var a=0,o=0;n>o;++o){var s=i[2*o];if(s!==a){for(r[2*a+1]=o;++ai;++i)n[i]=[r[2*i],r[2*i+1]];return n}function c(t,e,r,c){r=r||0,"undefined"==typeof c&&(c=n(t));var u=t.length;if(0===u||1>c)return{cells:[],vertexIds:[],vertexWeights:[]};var h=i(e,+r),p=a(t,c),g=o(p,e,h,+r),v=s(p,0|e.length),m=d(c)(t,p.data,v,h),y=l(p),b=[].slice.call(g.data,0,g.shape[0]);return f.free(h),f.free(p.data),f.free(g.data),f.free(v),{cells:m,vertexIds:y,vertexWeights:b}}e.exports=c;var u=t("ndarray"),f=t("typedarray-pool"),h=t("ndarray-sort"),d=t("./lib/codegen")},{"./lib/codegen":155,ndarray:253,"ndarray-sort":158,"typedarray-pool":278}],155:[function(t,e,r){"use strict";function n(t){function e(t){if(!(t.length<=0)){c.push("R.push(");for(var e=0;e0&&c.push(","),c.push("[");for(var n=0;n0&&c.push(","),c.push("B(C,E,c[",i[0],"],c[",i[1],"])")}c.push("]")}c.push(");")}}var r=0,n=new Array(t+1);n[0]=[[]];for(var i=1;t>=i;++i)for(var s=n[i]=o(i),l=0;l>1,v=E[2*m+1];","if(v===b){return m}","if(b1;--i){t+1>i&&c.push("else "),c.push("if(l===",i,"){");for(var u=[],l=0;i>l;++l)u.push("(S[c["+l+"]]<<"+l+")");c.push("var M=",u.join("+"),";if(M===0||M===",(1<i;++i)n[i]=0,i===e&&(n[i]+=.5),i===r&&(n[i]+=.5);return n}function i(t,e){if(0===e||e===(1<=a;++a)if(e&1<=s;++s)~e&1<n;++n)r[n]=i(t,n);return r}e.exports=a;var o=t("convex-hull")},{"convex-hull":102}],157:[function(t,e,r){"use strict";function n(t){switch(t){case"uint8":return[l.mallocUint8,l.freeUint8];case"uint16":return[l.mallocUint16,l.freeUint16];case"uint32":return[l.mallocUint32,l.freeUint32];case"int8":return[l.mallocInt8,l.freeInt8];case"int16":return[l.mallocInt16,l.freeInt16];case"int32":return[l.mallocInt32,l.freeInt32];case"float32":return[l.mallocFloat,l.freeFloat];case"float64":return[l.mallocDouble,l.freeDouble];default:return null}}function i(t){for(var e=[],r=0;t>r;++r)e.push("s"+r);for(var r=0;t>r;++r)e.push("n"+r);for(var r=1;t>r;++r)e.push("d"+r);for(var r=1;t>r;++r)e.push("e"+r);for(var r=1;t>r;++r)e.push("f"+r);return e}function a(t,e){function r(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function a(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}var o=["'use strict'"],s=["ndarrayInsertionSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(i(t.length)),c=n(e),u=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var f=[],h=1;h1){o.push("dptr=0;sptr=ptr");for(var h=t.length-1;h>=0;--h){var d=t[h];0!==d&&o.push(["for(i",d,"=0;i",d,"left){","dptr=0","sptr=cptr-s0");for(var h=1;hb){break __l}"].join(""));for(var h=t.length-1;h>=1;--h)o.push("sptr+=e"+h,"dptr+=f"+h,"}");o.push("dptr=cptr;sptr=cptr-s0");for(var h=t.length-1;h>=0;--h){var d=t[h];0!==d&&o.push(["for(i",d,"=0;i",d,"=0;--h){var d=t[h];0!==d&&o.push(["for(i",d,"=0;i",d,"left)&&("+r("cptr-s0")+">scratch)){",a("cptr",r("cptr-s0")),"cptr-=s0","}",a("cptr","scratch"));if(o.push("}"),t.length>1&&c&&o.push("free(scratch)"),o.push("} return "+s),c){var p=new Function("malloc","free",o.join("\n"));return p(c[0],c[1])}var p=new Function(o.join("\n"));return p()}function o(t,e,r){function a(t){return["(offset+",t,"*s0)"].join("")}function o(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function s(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}function l(e,r,n){if(1===e.length)_.push("ptr0="+a(e[0]));else for(var i=0;i=0;--i){var o=t[i];0!==o&&_.push(["for(i",o,"=0;i",o,"1)for(var i=0;i1?_.push("ptr_shift+=d"+o):_.push("ptr0+=d"+o),_.push("}"))}}function u(e,r,n,i){if(1===r.length)_.push("ptr0="+a(r[0]));else{for(var o=0;o1)for(var o=0;o=1;--o)n&&_.push("pivot_ptr+=f"+o),r.length>1?_.push("ptr_shift+=e"+o):_.push("ptr0+=e"+o),_.push("}")}function f(){t.length>1&&A&&_.push("free(pivot1)","free(pivot2)")}function h(e,r){var n="el"+e,i="el"+r;if(t.length>1){var s="__l"+ ++M;u(s,[n,i],!1,["comp=",o("ptr0"),"-",o("ptr1"),"\n","if(comp>0){tmp0=",n,";",n,"=",i,";",i,"=tmp0;break ",s,"}\n","if(comp<0){break ",s,"}"].join(""))}else _.push(["if(",o(a(n)),">",o(a(i)),"){tmp0=",n,";",n,"=",i,";",i,"=tmp0}"].join(""))}function d(e,r){t.length>1?l([e,r],!1,s("ptr0",o("ptr1"))):_.push(s(a(e),o(a(r))))}function p(e,r,n){if(t.length>1){var i="__l"+ ++M;u(i,[r],!0,[e,"=",o("ptr0"),"-pivot",n,"[pivot_ptr]\n","if(",e,"!==0){break ",i,"}"].join(""))}else _.push([e,"=",o(a(r)),"-pivot",n].join(""))}function g(e,r){t.length>1?l([e,r],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join("")):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join(""))}function v(e,r,n){t.length>1?(l([e,r,n],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join("")),_.push("++"+r,"--"+n)):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","ptr2=",a(n),"\n","++",r,"\n","--",n,"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join(""))}function m(t,e){g(t,e),_.push("--"+e)}function y(e,r,n){t.length>1?l([e,r],!0,[s("ptr0",o("ptr1")),"\n",s("ptr1",["pivot",n,"[pivot_ptr]"].join(""))].join("")):_.push(s(a(e),o(a(r))),s(a(r),"pivot"+n))}function b(e,r){_.push(["if((",r,"-",e,")<=",c,"){\n","insertionSort(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}else{\n",w,"(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}"].join(""))}function x(e,r,n){t.length>1?(_.push(["__l",++M,":while(true){"].join("")),l([e],!0,["if(",o("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",M,"}"].join("")),_.push(n,"}")):_.push(["while(",o(a(e)),"===pivot",r,"){",n,"}"].join(""))}var _=["'use strict'"],w=["ndarrayQuickSort",t.join("d"),e].join(""),k=["left","right","data","offset"].concat(i(t.length)),A=n(e),M=0;_.push(["function ",w,"(",k.join(","),"){"].join(""));var T=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var E=[],L=1;LL;++L)T.push("b_ptr"+L);T.push("ptr3","ptr4","ptr5","ptr6","ptr7","pivot_ptr","ptr_shift","elementSize="+E.join("*")),A?T.push("pivot1=malloc(elementSize)","pivot2=malloc(elementSize)"):T.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")}else T.push("pivot1","pivot2");if(_.push("var "+T.join(",")),h(1,2),h(4,5),h(1,3),h(2,3),h(1,4),h(3,4),h(2,5),h(2,3),h(4,5),t.length>1?l(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",o("ptr1"),"\n","pivot2[pivot_ptr]=",o("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",o("ptr0"),"\n","y=",o("ptr2"),"\n","z=",o("ptr4"),"\n",s("ptr5","x"),"\n",s("ptr6","y"),"\n",s("ptr7","z")].join("")):_.push(["pivot1=",o(a("el2")),"\n","pivot2=",o(a("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",o(a("el1")),"\n","y=",o(a("el3")),"\n","z=",o(a("el5")),"\n",s(a("index1"),"x"),"\n",s(a("index3"),"y"),"\n",s(a("index5"),"z")].join("")),d("index2","left"),d("index4","right"),_.push("if(pivots_are_equal){"),_.push("for(k=less;k<=great;++k){"),p("comp","k",1),_.push("if(comp===0){continue}"),_.push("if(comp<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),_.push("while(true){"),p("comp","great",1),_.push("if(comp>0){"),_.push("great--"),_.push("}else if(comp<0){"),v("k","less","great"),_.push("break"),_.push("}else{"),m("k","great"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}else{"),_.push("for(k=less;k<=great;++k){"),p("comp_pivot1","k",1),_.push("if(comp_pivot1<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),p("comp_pivot2","k",2),_.push("if(comp_pivot2>0){"),_.push("while(true){"),p("comp","great",2),_.push("if(comp>0){"),_.push("if(--greatindex5){"),x("less",1,"++less"),x("great",2,"--great"),_.push("for(k=less;k<=great;++k){"),p("comp_pivot1","k",1),_.push("if(comp_pivot1===0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),p("comp_pivot2","k",2),_.push("if(comp_pivot2===0){"),_.push("while(true){"),p("comp","great",2),_.push("if(comp===0){"),_.push("if(--great1&&A){var S=new Function("insertionSort","malloc","free",_.join("\n"));return S(r,A[0],A[1])}var S=new Function("insertionSort",_.join("\n"));return S(r)}function s(t,e){var r=["'use strict'"],n=["ndarraySortWrapper",t.join("d"),e].join(""),s=["array"];r.push(["function ",n,"(",s.join(","),"){"].join(""));for(var l=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"],u=0;u0?l.push(["d",v,"=s",v,"-d",p,"*n",p].join("")):l.push(["d",v,"=s",v].join("")),p=v);var d=t.length-1-u;0!==d&&(g>0?l.push(["e",d,"=s",d,"-e",g,"*n",g,",f",d,"=",f[d],"-f",g,"*n",g].join("")):l.push(["e",d,"=s",d,",f",d,"=",f[d]].join("")),g=d)}r.push("var "+l.join(","));var m=["0","n0-1","data","offset"].concat(i(t.length));r.push(["if(n0<=",c,"){","insertionSort(",m.join(","),")}else{","quickSort(",m.join(","),")}"].join("")),r.push("}return "+n);var y=new Function("insertionSort","quickSort",r.join("\n")),b=a(t,e),x=o(t,e,b);return y(b,x)}var l=t("typedarray-pool"),c=32;e.exports=s},{"typedarray-pool":278}],158:[function(t,e,r){"use strict";function n(t){var e=t.order,r=t.dtype,n=[e,r],o=n.join(":"),s=a[o];return s||(a[o]=s=i(e,r)),s(t),t}var i=t("./lib/compile_sort.js"),a={};e.exports=n},{"./lib/compile_sort.js":157}],159:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[0,0,0,1,1,0,1,1]),i=o(e,s.boxVert,s.lineFrag);return new n(t,r,i)}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawBox=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o){var s=this.plot,l=this.shader,c=s.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,l.uniforms.lo=t,l.uniforms.hi=e,l.uniforms.color=o,c.drawArrays(c.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],160:[function(t,e,r){"use strict";function n(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function i(t,e){return t-e}function a(t){var e=t.gl,r=o(e),i=s(e,c.gridVert,c.gridFrag),a=s(e,c.tickVert,c.gridFrag),l=new n(t,r,i,a);return l}e.exports=a;var o=t("gl-buffer"),s=t("gl-shader"),l=t("binary-search-bounds"),c=t("./shaders"),u=n.prototype;u.draw=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){for(var n=this.plot,i=this.vbo,a=this.shader,o=this.ticks,s=n.gl,l=n._tickBounds,c=n.dataBox,u=n.viewBox,f=n.gridLineWidth,h=n.gridLineColor,d=n.gridLineEnable,p=n.pixelRatio,g=0;2>g;++g){var v=l[g],m=l[g+2],y=m-v,b=.5*(c[g+2]+c[g]),x=c[g+2]-c[g];e[g]=2*y/x,t[g]=2*(v-b)/x}a.bind(),i.bind(),a.attributes.dataCoord.pointer(),a.uniforms.dataShift=t,a.uniforms.dataScale=e;for(var _=0,g=0;2>g;++g){r[0]=r[1]=0,r[g]=1,a.uniforms.dataAxis=r,a.uniforms.lineWidth=f[g]/(u[g+2]-u[g])*p,a.uniforms.color=h[g];var w=6*o[g].length;d[g]&&w&&s.drawArrays(s.TRIANGLES,_,w),_+=w}}}(),u.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],o=[0,0];return function(){for(var s=this.plot,c=this.vbo,u=this.tickShader,f=this.ticks,h=s.gl,d=s._tickBounds,p=s.dataBox,g=s.viewBox,v=s.pixelRatio,m=s.screenBox,y=m[2]-m[0],b=m[3]-m[1],x=g[2]-g[0],_=g[3]-g[1],w=0;2>w;++w){var k=d[w],A=d[w+2],M=A-k,T=.5*(p[w+2]+p[w]),E=p[w+2]-p[w];e[w]=2*M/E,t[w]=2*(k-T)/E}e[0]*=x/y,t[0]*=x/y,e[1]*=_/b,t[1]*=_/b,u.bind(),c.bind(),u.attributes.dataCoord.pointer();var L=u.uniforms;L.dataShift=t,L.dataScale=e;var S=s.tickMarkLength,C=s.tickMarkWidth,z=s.tickMarkColor,P=0,R=6*f[0].length,O=Math.min(l.ge(f[0],(p[0]-d[0])/(d[2]-d[0]),i),f[0].length),I=Math.min(l.gt(f[0],(p[2]-d[0])/(d[2]-d[0]),i),f[0].length),N=P+6*O,j=6*Math.max(0,I-O),F=Math.min(l.ge(f[1],(p[1]-d[1])/(d[3]-d[1]),i),f[1].length),D=Math.min(l.gt(f[1],(p[3]-d[1])/(d[3]-d[1]),i),f[1].length),B=R+6*F,U=6*Math.max(0,D-F);a[0]=2*(g[0]-S[1])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[1]*v/y,o[1]=C[1]*v/b,U&&(L.color=z[1],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[1]-S[0])/b-1,o[0]=C[0]*v/y,o[1]=S[0]*v/b,j&&(L.color=z[0],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,N,j)),a[0]=2*(g[2]+S[3])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[3]*v/y,o[1]=C[3]*v/b,U&&(L.color=z[3],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[3]+S[2])/b-1,o[0]=C[2]*v/y,o[1]=S[2]*v/b,j&&(L.color=z[2],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,N,j))}}(),u.update=function(){var t=[1,1,-1,-1,1,-1],e=[1,-1,1,1,-1,-1];return function(r){for(var n=r.ticks,i=r.bounds,a=new Float32Array(18*(n[0].length+n[1].length)),o=(this.plot.zeroLineEnable,0),s=[[],[]],l=0;2>l;++l)for(var c=s[l],u=n[l],f=i[l],h=i[l+2],d=0;dg;++g)a[o++]=p,a[o++]=t[g],a[o++]=e[g]}this.ticks=s,this.vbo.update(a)}}(),u.dispose=function(){this.vbo.dispose(),this.shader.dispose(),this.tickShader.dispose()}},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197}],161:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[-1,-1,-1,1,1,-1,1,1]),i=o(e,s.lineVert,s.lineFrag),l=new n(t,r,i);return l}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawLine=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o,s){var l=this.plot,c=this.shader,u=l.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,c.uniforms.start=t,c.uniforms.end=e,c.uniforms.width=o*l.pixelRatio,c.uniforms.color=s,u.drawArrays(u.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],162:[function(t,e,r){"use strict";var n="precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n";e.exports={lineVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n",lineFrag:n,textVert:"#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n",textFrag:n,gridVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n",gridFrag:n,boxVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n",tickVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"}},{}],163:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r,this.tickOffset=[[],[]],this.tickX=[[],[]],this.labelOffset=[0,0],this.labelCount=[0,0]}function i(t){var e=t.gl,r=a(e),i=o(e,c.textVert,c.textFrag),s=new n(t,r,i);return s}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("text-cache"),l=t("binary-search-bounds"),c=t("./shaders"),u=n.prototype;u.drawTicks=function(){var t=[0,0],e=[0,0],r=[0,0];return function(n){var i=this.plot,a=this.shader,o=this.tickX[n],s=this.tickOffset[n],c=i.gl,u=i.viewBox,f=i.dataBox,h=i.screenBox,d=i.pixelRatio,p=i.tickEnable,g=i.tickPad,v=i.tickColor,m=i.tickAngle,y=(i.tickMarkLength,i.labelEnable),b=i.labelPad,x=i.labelColor,_=i.labelAngle,w=this.labelOffset[n],k=this.labelCount[n],A=l.lt(o,f[n]),M=l.le(o,f[n+2]);t[0]=t[1]=0,t[n]=1,e[n]=(u[2+n]+u[n])/(h[2+n]-h[n])-1;var T=2/h[2+(1^n)]-h[1^n];e[1^n]=T*u[1^n]-1,p[n]&&(e[1^n]-=T*d*g[n],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n],a.uniforms.angle=m[n],c.drawArrays(c.TRIANGLES,s[A],s[M]-s[A]))),y[n]&&k&&(e[1^n]-=T*d*b[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=_[n],c.drawArrays(c.TRIANGLES,w,k)),e[1^n]=T*u[2+(1^n)]-1,p[n+2]&&(e[1^n]+=T*d*g[n+2],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n+2],a.uniforms.angle=m[n+2],c.drawArrays(c.TRIANGLES,s[A],s[M]-s[A]))),y[n+2]&&k&&(e[1^n]+=T*d*b[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=_[n+2],c.drawArrays(c.TRIANGLES,w,k))}}(),u.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,o=r.titleCenter,c=r.pixelRatio;if(this.titleCount){for(var u=0;2>u;++u)e[u]=2*(o[u]*c-a[u])/(a[2+u]-a[u])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),u.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var c=0;2>c;++c){var u=a[c],f=a[c+2],h=f-u,d=.5*(o[c+2]+o[c]),p=o[c+2]-o[c],g=l[c],v=l[c+2],m=v-g,y=s[c],b=s[c+2],x=b-y;e[c]=2*h/p*m/x,t[c]=2*(u-d)/p*m/x}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),u.update=function(t){for(var e=[],r=t.ticks,n=t.bounds,i=0;2>i;++i){for(var a=[Math.floor(e.length/3)],o=[-(1/0)],l=r[i],c=0;ci;++i){this.labelOffset[i]=Math.floor(e.length/3);for(var g=s(t.labelFont[i],t.labels[i]).data,p=t.labelSize[i],c=0;cp;++p)if(f[p]&&n[p]<=0&&n[p+2]>=0){var g=e[p]-n[p]*(e[p+2]-e[p])/(n[p+2]-n[p]);0===p?o.drawLine(g,e[1],g,e[3],d[p],h[p]):o.drawLine(e[0],g,e[2],g,d[p],h[p])}}for(var p=0;pp;++p)s.drawTicks(p);this.titleEnable&&s.drawTitle();for(var b=this.overlays,p=0;pc;++c){var u=s[c].slice(0);0!==u.length&&(u.sort(a),l[c]=Math.min(l[c],u[0].x),l[c+2]=Math.max(l[c+2],u[u.length-1].x))}this.grid.update({bounds:l,ticks:s}),this.text.update({bounds:l,ticks:s,labels:t.labels||["x","y"],labelSize:t.labelSize||[12,12],labelFont:t.labelFont||["sans-serif","sans-serif"],title:t.title||"",titleSize:t.titleSize||18,titleFont:t.titleFont||"sans-serif"}),this.setDirty()},h.dispose=function(){this.box.dispose(),this.grid.dispose(),this.text.dispose(),this.line.dispose();for(var t=this.objects.length-1;t>=0;--t)this.objects[t].dispose();this.objects.length=0;for(var t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},h.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},h.removeObject=function(t){for(var e=this.objects,r=0;rh;++h)o=o&&l[h]===s[h],l[h]=s[h];var d=t.clientWidth===u&&t.clientHeight===f;return u=t.clientWidth,f=t.clientHeight,o?!d:(c=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){return n.setMode(t),n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return c},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var d=0,p=0;return o(t,function(e,r,a,o){var s=1/t.clientHeight,l=s*(r-d),u=s*(a-p),f=h.flipX?1:-1,g=h.flipY?1:-1,v=Math.PI*h.rotateSpeed,m=i();if(1&e)o.shift?n.rotate(m,0,0,-l*v):n.rotate(m,f*v*l,-g*v*u,0);else if(2&e)n.pan(m,-h.translateSpeed*l*c,h.translateSpeed*u*c,0);else if(4&e){var y=h.zoomSpeed*u/window.innerHeight*(m-n.lastT())*50;n.pan(m,0,0,c*(Math.exp(y)-1))}d=r,p=a}),s(t,function(t,e,r){var a=h.flipX?1:-1,o=h.flipY?1:-1,s=i();if(Math.abs(t)>Math.abs(e))n.rotate(s,0,0,-t*a*Math.PI*h.rotateSpeed/window.innerWidth);else{var l=h.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,c*(Math.exp(l)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],168:[function(t,e,r){!function(){"use strict";function t(e){e.permitHostObjects___&&e.permitHostObjects___(t)}function r(t){return!(t.substr(0,d.length)==d&&"___"===t.substr(t.length-3))}function n(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[p];if(e&&e.key===t)return e;if(h(t)){e={key:t};try{return f(t,p,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(r){return}}}function i(t){return t.prototype=null,Object.freeze(t)}function a(){y||"undefined"==typeof console||(y=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}if("undefined"==typeof ses||!ses.ok||ses.ok()){"undefined"!=typeof ses&&(ses.weakMapPermitHostObjects=t);var o=!1;if("function"==typeof WeakMap){var s=WeakMap;if("undefined"!=typeof navigator&&/Firefox/.test(navigator.userAgent));else{var l=new s,c=Object.freeze({});if(l.set(c,1),1===l.get(c))return void(e.exports=WeakMap);o=!0}}var u=(Object.prototype.hasOwnProperty,Object.getOwnPropertyNames),f=Object.defineProperty,h=Object.isExtensible,d="weakmap:",p=d+"ident:"+Math.random()+"___";if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof ArrayBuffer&&"function"==typeof Uint8Array){var g=new ArrayBuffer(25),v=new Uint8Array(g);crypto.getRandomValues(v),p=d+"rand:"+Array.prototype.map.call(v,function(t){return(t%36).toString(36)}).join("")+"___"}if(f(Object,"getOwnPropertyNames",{value:function(t){return u(t).filter(r)}}),"getPropertyNames"in Object){var m=Object.getPropertyNames;f(Object,"getPropertyNames",{value:function(t){return m(t).filter(r)}})}!function(){var t=Object.freeze;f(Object,"freeze",{value:function(e){return n(e),t(e)}});var e=Object.seal;f(Object,"seal",{value:function(t){return n(t),e(t)}});var r=Object.preventExtensions;f(Object,"preventExtensions",{value:function(t){return n(t),r(t)}})}();var y=!1,b=0,x=function(){function t(t,e){var r,i=n(t);return i?c in i?i[c]:e:(r=s.indexOf(t),r>=0?l[r]:e)}function e(t){var e=n(t);return e?c in e:s.indexOf(t)>=0}function r(t,e){var r,i=n(t);return i?i[c]=e:(r=s.indexOf(t),r>=0?l[r]=e:(r=s.length,l[r]=e,s[r]=t)),this}function o(t){var e,r,i=n(t);return i?c in i&&delete i[c]:(e=s.indexOf(t),0>e?!1:(r=s.length-1,s[e]=void 0,l[e]=l[r],s[e]=s[r],s.length=r,l.length=r,!0))}this instanceof x||a();var s=[],l=[],c=b++;return Object.create(x.prototype,{get___:{value:i(t)},has___:{value:i(e)},set___:{value:i(r)},delete___:{value:i(o)}})};x.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},"delete":{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof s?!function(){function r(){function e(t,e){return u?c.has(t)?c.get(t):u.get___(t,e):c.get(t,e)}function r(t){return c.has(t)||(u?u.has___(t):!1)}function n(t){var e=!!c.delete(t);return u?u.delete___(t)||e:e}this instanceof x||a();var l,c=new s,u=void 0,f=!1;return l=o?function(t,e){return c.set(t,e),c.has(t)||(u||(u=new x),u.set(t,e)),this}:function(t,e){if(f)try{c.set(t,e)}catch(r){u||(u=new x),u.set___(t,e)}else c.set(t,e);return this},Object.create(x.prototype,{get___:{value:i(e)},has___:{value:i(r)},set___:{value:i(l)},delete___:{value:i(n)},permitHostObjects___:{value:i(function(e){if(e!==t)throw new Error("bogus call to permitHostObjects___");f=!0})}})}o&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=x.prototype,e.exports=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=x)}}()},{}],169:[function(t,e,r){"use strict";function n(t){var e=s.get(t);if(!e||!t.isBuffer(e._triangleBuffer.buffer)){var r=a(t,new Float32Array([-1,-1,-1,4,4,-1]));e=o(t,[{buffer:r,type:t.FLOAT,size:2}]),e._triangleBuffer=r,s.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}var i="undefined"==typeof WeakMap?t("weak-map"):WeakMap,a=t("gl-buffer"),o=t("gl-vao"),s=new i;e.exports=n},{"gl-buffer":118,"gl-vao":226,"weak-map":168}],170:[function(t,e,r){"use strict";function n(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function i(t){this.gl=t,this.pixelRatio=1,this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.autoTicks=!0,this.tickSpacing=[1,1,1],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[10,10,10],this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]},this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont="sans-serif",this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[10,10,10],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[0,0,0],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!1,!1,!1],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._firstInit=!0,this._text=null,this._lines=null,this._background=u(t)}function a(){this.primalOffset=[0,0,0],this.primalMinor=[0,0,0],this.mirrorOffset=[0,0,0],this.mirrorMinor=[0,0,0]}function o(t,e,r,n,i){for(var a=t.primalOffset,o=t.primalMinor,s=t.mirrorOffset,l=t.mirrorMinor,c=n[e],u=0;3>u;++u)if(e!==u){var f=a,h=s,d=o,p=l;c&1<0?(d[u]=-1,p[u]=0):(d[u]=0,p[u]=1)}}function s(t,e){var r=new i(t);return r.update(e),r}e.exports=s;var l=t("./lib/text.js"),c=t("./lib/lines.js"),u=t("./lib/background.js"),f=t("./lib/cube.js"),h=t("./lib/ticks.js"),d=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),p=i.prototype;p.update=function(t){function e(e,r,n){if(n in t){var i,a=t[n],o=this[n];(e?Array.isArray(a)&&Array.isArray(a[0]):Array.isArray(a))?this[n]=i=[r(a[0]),r(a[1]),r(a[2])]:this[n]=i=[r(a),r(a),r(a)];for(var s=0;3>s;++s)if(i[s]!==o[s])return!0}return!1}t=t||{};var r,n=e.bind(this,!1,Number),i=e.bind(this,!1,Boolean),a=e.bind(this,!1,String),o=e.bind(this,!0,function(t){if(Array.isArray(t)){if(3===t.length)return[+t[0],+t[1],+t[2],1];if(4===t.length)return[+t[0],+t[1],+t[2],+t[3]]}return[0,0,0,1]}),s=!1,u=!1;if("bounds"in t)for(var f=t.bounds,d=0;2>d;++d)for(var p=0;3>p;++p)f[d][p]!==this.bounds[d][p]&&(u=!0),this.bounds[d][p]=f[d][p];if("ticks"in t){r=t.ticks,s=!0,this.autoTicks=!1;for(var d=0;3>d;++d)this.tickSpacing[d]=0}else n("tickSpacing")&&(this.autoTicks=!0,u=!0);if(this._firstInit&&("ticks"in t||"tickSpacing"in t||(this.autoTicks=!0),u=!0,s=!0,this._firstInit=!1),u&&this.autoTicks&&(r=h.create(this.bounds,this.tickSpacing),s=!0),s){for(var d=0;3>d;++d)r[d].sort(function(t,e){return t.x-e.x});h.equal(r,this.ticks)?s=!1:this.ticks=r}i("tickEnable"),a("tickFont")&&(s=!0),n("tickSize"),n("tickAngle"),n("tickPad"),o("tickColor");var g=a("labels");a("labelFont")&&(g=!0),i("labelEnable"),n("labelSize"),n("labelPad"),o("labelColor"),i("lineEnable"),i("lineMirror"),n("lineWidth"),o("lineColor"),i("lineTickEnable"),i("lineTickMirror"),n("lineTickLength"),n("lineTickWidth"),o("lineTickColor"),i("gridEnable"),n("gridWidth"),o("gridColor"),i("zeroEnable"),o("zeroLineColor"),n("zeroLineWidth"),i("backgroundEnable"),o("backgroundColor"),this._text?this._text&&(g||s)&&this._text.update(this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont):this._text=l(this.gl,this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont),this._lines&&s&&(this._lines.dispose(),this._lines=null),this._lines||(this._lines=c(this.gl,this.bounds,this.ticks))};var g=[new a,new a,new a],v=[0,0,0],m={model:d,view:d,projection:d};p.isOpaque=function(){return!0},p.isTransparent=function(){return!1},p.drawTransparent=function(t){};var y=[0,0,0],b=[0,0,0],x=[0,0,0];p.draw=function(t){t=t||m;for(var e=this.gl,r=t.model||d,i=t.view||d,a=t.projection||d,s=this.bounds,l=f(r,i,a,s),c=l.cubeEdges,u=l.axis,h=i[12],p=i[13],_=i[14],w=i[15],k=this.pixelRatio*(a[3]*h+a[7]*p+a[11]*_+a[15]*w)/e.drawingBufferHeight,A=0;3>A;++A)this.lastCubeProps.cubeEdges[A]=c[A],this.lastCubeProps.axis[A]=u[A];for(var M=g,A=0;3>A;++A)o(g[A],A,this.bounds,c,u);for(var e=this.gl,T=v,A=0;3>A;++A)this.backgroundEnable[A]?T[A]=u[A]:T[A]=0;this._background.draw(r,i,a,s,T,this.backgroundColor),this._lines.bind(r,i,a,this);for(var A=0;3>A;++A){var E=[0,0,0];u[A]>0?E[A]=s[1][A]:E[A]=s[0][A];for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.gridEnable[S]&&this._lines.drawGrid(S,C,this.bounds,E,this.gridColor[S],this.gridWidth[S]*this.pixelRatio)}for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.zeroEnable[C]&&s[0][C]<=0&&s[1][C]>=0&&this._lines.drawZero(S,C,this.bounds,E,this.zeroLineColor[C],this.zeroLineWidth[C]*this.pixelRatio)}}for(var A=0;3>A;++A){this.lineEnable[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].primalOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio),this.lineMirror[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].mirrorOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio);for(var z=n(y,M[A].primalMinor),P=n(b,M[A].mirrorMinor),R=this.lineTickLength,L=0;3>L;++L){var O=k/r[5*L];z[L]*=R[L]*O,P[L]*=R[L]*O}this.lineTickEnable[A]&&this._lines.drawAxisTicks(A,M[A].primalOffset,z,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio),this.lineTickMirror[A]&&this._lines.drawAxisTicks(A,M[A].mirrorOffset,P,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio)}this._text.bind(r,i,a,this.pixelRatio);for(var A=0;3>A;++A){for(var I=M[A].primalMinor,N=n(x,M[A].primalOffset),L=0;3>L;++L)this.lineTickEnable[A]&&(N[L]+=k*I[L]*Math.max(this.lineTickLength[L],0)/r[5*L]);if(this.tickEnable[A]){for(var L=0;3>L;++L)N[L]+=k*I[L]*this.tickPad[L]/r[5*L];this._text.drawTicks(A,this.tickSize[A],this.tickAngle[A],N,this.tickColor[A])}if(this.labelEnable[A]){for(var L=0;3>L;++L)N[L]+=k*I[L]*this.labelPad[L]/r[5*L];N[A]+=.5*(s[0][A]+s[1][A]),this._text.drawLabel(A,this.labelSize[A],this.labelAngle[A],N,this.labelColor[A])}}},p.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":171,"./lib/cube.js":172,"./lib/lines.js":173,"./lib/text.js":175,"./lib/ticks.js":176}],171:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}function i(t){for(var e=[],r=[],i=0,l=0;3>l;++l)for(var c=(l+1)%3,u=(l+2)%3,f=[0,0,0],h=[0,0,0],d=-1;1>=d;d+=2){r.push(i,i+2,i+1,i+1,i+2,i+3),f[l]=d,h[l]=d;for(var p=-1;1>=p;p+=2){f[c]=p;for(var g=-1;1>=g;g+=2)f[u]=g,e.push(f[0],f[1],f[2],h[0],h[1],h[2]),i+=1}var v=c;c=u,u=v}var m=a(t,new Float32Array(e)),y=a(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),b=o(t,[{buffer:m,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:m,type:t.FLOAT,size:3,offset:12,stride:24}],y),x=s(t);return x.attributes.position.location=0,x.attributes.normal.location=1,new n(t,m,b,x)}e.exports=i;var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders").bg,l=n.prototype;l.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;3>s;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),l.disable(l.POLYGON_OFFSET_FILL)}},l.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":174,"gl-buffer":118,"gl-vao":226}],172:[function(t,e,r){"use strict";function n(t,e,r){for(var n=0;4>n;++n){t[n]=r[12+n];for(var i=0;3>i;++i)t[n]+=e[i]*r[4*i+n]}}function i(t){for(var e=0;eg;++g){d[2]=a[g][2];for(var b=0;2>b;++b){d[1]=a[b][1];for(var x=0;2>x;++x)d[0]=a[x][0],n(f[l],d,u),l+=1}}for(var _=-1,g=0;8>g;++g){for(var w=f[g][3],k=0;3>k;++k)h[g][k]=f[g][k]/w;0>w&&(0>_?_=g:h[g][2]_){_=0;for(var A=0;3>A;++A){for(var M=(A+2)%3,T=(A+1)%3,E=-1,L=-1,S=0;2>S;++S){var C=S<E||0>L)L>E&&(_|=1<S;++S){var C=S<E&&(_|=1<g;++g)g!==_&&g!==O&&(0>I?I=g:h[I][1]>h[g][1]&&(I=g));for(var N=-1,g=0;3>g;++g){var j=I^1<N&&(N=j);var T=h[j];T[0]g;++g){var j=I^1<F&&(F=j);var T=h[j];T[0]>h[F][0]&&(F=j)}}var D=v;D[0]=D[1]=D[2]=0,D[o.log2(N^I)]=I&N,D[o.log2(I^F)]=I&F;var B=7^F;B===_||B===O?(B=7^N,D[o.log2(F^B)]=B&F):D[o.log2(N^B)]=B&N;for(var U=m,V=_,A=0;3>A;++A)V&1<t;++t)f[t]=[1,1,1,1],h[t]=[1,1,1]}();var g=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]],v=[1,1,1],m=[0,0,0],y={cubeEdges:v,axis:m}},{"bit-twiddle":50,"gl-mat4/invert":137,"gl-mat4/multiply":139,"robust-orientation":259,"split-polygon":178}],173:[function(t,e,r){"use strict";function n(t){return t[0]=t[1]=t[2]=0,t}function i(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function a(t,e,r,n,i,a,o,s){this.gl=t,this.vertBuffer=e,this.vao=r,this.shader=n,this.tickCount=i,this.tickOffset=a,this.gridCount=o,this.gridOffset=s}function o(t,e,r){var n=[],i=[0,0,0],o=[0,0,0],u=[0,0,0],f=[0,0,0];n.push(0,0,1,0,1,1,0,0,-1,0,0,-1,0,1,1,0,1,-1);for(var h=0;3>h;++h){for(var d=n.length/3|0,p=0;ph;++h)for(var p=u[h],g=2;g>=0;--g){var v=c[p[g]];s.push(l*v[0],-l*v[1],t)}}for(var s=(this.gl,[]),l=[0,0,0],c=[0,0,0],u=[0,0,0],d=[0,0,0],p=0;3>p;++p){u[p]=s.length/h|0,o(.5*(t[0][p]+t[1][p]),e[p],r),d[p]=(s.length/h|0)-u[p],l[p]=s.length/h|0;for(var g=0;g=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,c=o%a;0>o?(l=0|-Math.ceil(l),c=0|-c):(l=0|Math.floor(l),c=0|c);var u=""+l;if(0>o&&(u="-"+u),i){for(var f=""+c;f.lengthi;++i){for(var a=[],o=(.5*(t[0][i]+t[1][i]),0);o*e[i]<=t[1][i];++o)a.push({x:o*e[i],text:n(e[i],o)});for(var o=-1;o*e[i]>=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r}function a(t,e){for(var r=0;3>r;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;na?a=0:a>1&&(a=1);for(var o=1-a,s=t.length,l=new Array(s),c=0;s>c;++c)l[c]=a*t[c]+o*r[c];return l}function a(t,e){for(var r=[],a=[],o=n(t[t.length-1],e),s=t[t.length-1],l=t[0],c=0;co&&u>0||o>0&&0>u){var f=i(s,u,l,o);r.push(f),a.push(f.slice())}0>u?a.push(l.slice()):u>0?r.push(l.slice()):(r.push(l.slice()),a.push(l.slice())),o=u}return{positive:r,negative:a}}function o(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&c>0||a>0&&0>c)&&r.push(i(o,c,s,a)),c>=0&&r.push(s.slice()),a=c}return r}function s(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&c>0||a>0&&0>c)&&r.push(i(o,c,s,a)),0>=c&&r.push(s.slice()),a=c}return r}var l=t("robust-dot-product"),c=t("robust-sum");e.exports=a,e.exports.positive=o,e.exports.negative=s},{"robust-dot-product":179,"robust-sum":262}],179:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t[0],e[0]),n=1;na;++a){for(var o=p,s=g,l=0;3>l;++l)s[l]=o[l]=r[l];s[3]=o[3]=1,s[a]+=1,f(s,s,e),s[3]<0&&(t[a]=1/0),o[a]-=1,f(o,o,e),o[3]<0&&(t[a]=1/0);var c=(o[0]/o[3]-s[0]/s[3])*n,u=(o[1]/o[3]-s[1]/s[3])*i;t[a]=.25*Math.sqrt(c*c+u*u)}return t}function a(t,e,r,n,a){var f=e.model||h,p=e.view||h,g=e.projection||h,y=t.bounds,a=a||l(f,p,g,y),b=a.axis;a.edges;c(d,p,f),c(d,g,d);for(var x=v,_=0;3>_;++_)x[_].lo=1/0,x[_].hi=-(1/0),x[_].pixelsPerDataUnit=1/0;var w=o(u(d,d));u(d,d);for(var k=0;3>k;++k){var A=(k+1)%3,M=(k+2)%3,T=m;t:for(var _=0;2>_;++_){var E=[];if(b[k]<0!=!!_){T[k]=y[_][k];for(var L=0;2>L;++L){T[A]=y[L^_][A];for(var S=0;2>S;++S)T[M]=y[S^L^_][M],E.push(T.slice())}for(var L=0;LS;++S)x[S].lo=Math.min(x[S].lo,M[S]),x[S].hi=Math.max(x[S].hi,M[S]),S!==k&&(x[S].pixelsPerDataUnit=Math.min(x[S].pixelsPerDataUnit,Math.abs(C[S])))}}}return x}e.exports=a;var o=t("extract-frustum-planes"),s=t("split-polygon"),l=t("./lib/cube.js"),c=t("gl-mat4/multiply"),u=t("gl-mat4/transpose"),f=t("gl-vec4/transformMat4"),h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),d=new Float32Array(16),p=[0,0,0,1],g=[0,0,0,1],v=[new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0)],m=[0,0,0]},{"./lib/cube.js":172,"extract-frustum-planes":177,"gl-mat4/multiply":139,"gl-mat4/transpose":147,"gl-vec4/transformMat4":227,"split-polygon":178}],181:[function(t,e,r){"use strict";var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n vec3 vertexPosition = mix(coordinates[0],\n mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n vec2 delta = weight * clipOffset * screenShape;\n vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n gl_Position = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n fragColor = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}"; -e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"},{name:"color",type:"vec3"},{name:"weight",type:"float"}])}},{"gl-shader":197}],182:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n,this.pixelRatio=1,this.bounds=[[-1e3,-1e3,-1e3],[1e3,1e3,1e3]],this.position=[0,0,0],this.lineWidth=[2,2,2],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.enabled=[!0,!0,!0],this.drawSides=[!0,!0,!0],this.axes=null}function i(t,e){function r(t,e,r,n,a,o){var s=[t,e,r,0,0,0,1];s[n+3]=1,s[n]=a,i.push.apply(i,s),s[6]=-1,i.push.apply(i,s),s[n]=o,i.push.apply(i,s),i.push.apply(i,s),s[6]=1,i.push.apply(i,s),s[n]=a,i.push.apply(i,s)}var i=[];r(0,0,0,0,0,1),r(0,0,0,1,0,1),r(0,0,0,2,0,1),r(1,0,0,1,-1,1),r(1,0,0,2,-1,1),r(0,1,0,0,-1,1),r(0,1,0,2,-1,1),r(0,0,1,0,-1,1),r(0,0,1,1,-1,1);var l=a(t,i),c=o(t,[{type:t.FLOAT,buffer:l,size:3,offset:0,stride:28},{type:t.FLOAT,buffer:l,size:3,offset:12,stride:28},{type:t.FLOAT,buffer:l,size:1,offset:24,stride:28}]),u=s(t);u.attributes.position.location=0,u.attributes.color.location=1,u.attributes.weight.location=2;var f=new n(t,l,c,u);return f.update(e),f}var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders/index");e.exports=i;var l=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],c=n.prototype,u=[0,0,0],f=[0,0,0],h=[0,0];c.isTransparent=function(){return!1},c.drawTransparent=function(t){},c.draw=function(t){var e=this.gl,r=this.vao,n=this.shader;r.bind(),n.bind();var i,a=t.model||l,o=t.view||l,s=t.projection||l;this.axes&&(i=this.axes.lastCubeProps.axis);for(var c=u,d=f,p=0;3>p;++p)i&&i[p]<0?(c[p]=this.bounds[0][p],d[p]=this.bounds[1][p]):(c[p]=this.bounds[1][p],d[p]=this.bounds[0][p]);h[0]=e.drawingBufferWidth,h[1]=e.drawingBufferHeight,n.uniforms.model=a,n.uniforms.view=o,n.uniforms.projection=s,n.uniforms.coordinates=[this.position,c,d],n.uniforms.colors=this.colors,n.uniforms.screenShape=h;for(var p=0;3>p;++p)n.uniforms.lineWidth=this.lineWidth[p]*this.pixelRatio,this.enabled[p]&&(r.draw(e.TRIANGLES,6,6*p),this.drawSides[p]&&r.draw(e.TRIANGLES,12,18+12*p));r.unbind()},c.update=function(t){t&&("bounds"in t&&(this.bounds=t.bounds),"position"in t&&(this.position=t.position),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"colors"in t&&(this.colors=t.colors),"enabled"in t&&(this.enabled=t.enabled),"drawSides"in t&&(this.drawSides=t.drawSides))},c.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders/index":181,"gl-buffer":118,"gl-vao":226}],183:[function(t,e,r){"use strict";function n(){this.mouse=[-1,-1],this.screen=null,this.distance=1/0,this.index=null,this.dataCoordinate=null,this.dataPosition=null,this.object=null,this.data=null}function i(t,e){var r=null;try{r=t.getContext("webgl",e),r||(r=t.getContext("experimental-webgl",e))}catch(n){return null}return r}function a(t){var e=Math.round(Math.log(Math.abs(t))/Math.log(10));if(0>e){var r=Math.round(Math.pow(10,-e));return Math.ceil(t*r)/r}if(e>0){var r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function o(t){return"boolean"==typeof t?t:!0}function s(t){function e(){if(!_&&H.autoResize){var t=w.parentNode,e=1,r=1;t&&t!==document.body?(e=t.clientWidth,r=t.clientHeight):(e=window.innerWidth,r=window.innerHeight);var n=0|Math.ceil(e*H.pixelRatio),i=0|Math.ceil(r*H.pixelRatio);if(n!==w.width||i!==w.height){w.width=n,w.height=i;var a=w.style;a.position=a.position||"absolute",a.left="0px",a.top="0px",a.width=e+"px",a.height=r+"px",F=!0}}}function r(){for(var t=O.length,e=j.length,r=0;e>r;++r)N[r]=0;t:for(var r=0;t>r;++r){var n=O[r],i=n.pickSlots;if(i){for(var a=0;e>a;++a)if(N[a]+i<255){I[r]=a,n.setPickBase(N[a]+1),N[a]+=i;continue t}var o=h(A,q);I[r]=e,j.push(o),N.push(i),n.setPickBase(1),e+=1}else I[r]=-1}for(;e>0&&0===N[e-1];)N.pop(),j.pop().dispose()}function s(){return H.contextLost?!0:void(A.isContextLost()&&(H.contextLost=!0,H.mouseListener.enabled=!1,H.selection.object=null,H.oncontextloss&&H.oncontextloss()))}function y(){if(!s()){A.colorMask(!0,!0,!0,!0),A.depthMask(!0),A.disable(A.BLEND),A.enable(A.DEPTH_TEST);for(var t=O.length,e=j.length,r=0;e>r;++r){var n=j[r];n.shape=G,n.begin();for(var i=0;t>i;++i)if(I[i]===r){var a=O[i];a.drawPick&&(a.pixelRatio=1,a.drawPick(V))}n.end()}}}function b(){if(!s()){e();var t=H.camera.tick();V.view=H.camera.matrix,F=F||t,D=D||t,z.pixelRatio=H.pixelRatio,R.pixelRatio=H.pixelRatio;var r=O.length,n=W[0],i=W[1];n[0]=n[1]=n[2]=1/0,i[0]=i[1]=i[2]=-(1/0);for(var o=0;r>o;++o){var l=O[o];l.pixelRatio=H.pixelRatio,l.axes=H.axes,F=F||!!l.dirty,D=D||!!l.dirty;var c=l.bounds;if(c)for(var f=c[0],h=c[1],d=0;3>d;++d)n[d]=Math.min(n[d],f[d]),i[d]=Math.max(i[d],h[d])}var g=H.bounds;if(H.autoBounds)for(var d=0;3>d;++d){if(i[d]d;++d)b=b||Z[0][d]!==g[0][d]||Z[1][d]!==g[1][d],Z[0][d]=g[0][d],Z[1][d]=g[1][d];if(b){for(var x=[0,0,0],o=0;3>o;++o)x[o]=a((g[1][o]-g[0][o])/10);z.autoTicks?z.update({bounds:g,tickSpacing:x}):z.update({bounds:g})}D=D||b,F=F||b;var _=A.drawingBufferWidth,w=A.drawingBufferHeight;q[0]=_,q[1]=w,G[0]=0|Math.max(_/H.pixelRatio,1),G[1]=0|Math.max(w/H.pixelRatio,1),v(B,H.fovy,_/w,H.zNear,H.zFar);for(var o=0;16>o;++o)U[o]=0;U[15]=1;for(var k=0,o=0;3>o;++o)k=Math.max(k,g[1][o]-g[0][o]);for(var o=0;3>o;++o)H.autoScale?U[5*o]=H.aspect[o]/(g[1][o]-g[0][o]):U[5*o]=1/k,H.autoCenter&&(U[12+o]=.5*-U[5*o]*(g[0][o]+g[1][o]));for(var o=0;r>o;++o){var l=O[o];l.axesBounds=g,H.clipToBounds&&(l.clipBounds=g)}if(T.object&&(H.snapToData?R.position=T.dataCoordinate:R.position=T.dataPosition,R.bounds=g),D&&(D=!1,y()),F){H.axesPixels=u(H.axes,V,_,w),H.onrender&&H.onrender(),A.bindFramebuffer(A.FRAMEBUFFER,null),A.viewport(0,0,_,w);var M=H.clearColor;A.clearColor(M[0],M[1],M[2],M[3]),A.clear(A.COLOR_BUFFER_BIT|A.DEPTH_BUFFER_BIT),A.depthMask(!0),A.colorMask(!0,!0,!0,!0),A.enable(A.DEPTH_TEST),A.depthFunc(A.LEQUAL),A.disable(A.BLEND),A.disable(A.CULL_FACE);var S=!1;z.enable&&(S=S||z.isTransparent(),z.draw(V)),R.axes=z,T.object&&R.draw(V),A.disable(A.CULL_FACE);for(var o=0;r>o;++o){var l=O[o];l.axes=z,l.pixelRatio=H.pixelRatio,l.isOpaque&&l.isOpaque()&&l.draw(V),l.isTransparent&&l.isTransparent()&&(S=!0)}if(S){E.shape=q,E.bind(),A.clear(A.DEPTH_BUFFER_BIT),A.colorMask(!1,!1,!1,!1),A.depthMask(!0),A.depthFunc(A.LESS),z.enable&&z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=O[o];l.isOpaque&&l.isOpaque()&&l.draw(V)}A.enable(A.BLEND),A.blendEquation(A.FUNC_ADD),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.colorMask(!0,!0,!0,!0),A.depthMask(!1),A.clearColor(0,0,0,0),A.clear(A.COLOR_BUFFER_BIT),z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=O[o];l.isTransparent&&l.isTransparent()&&l.drawTransparent(V)}A.bindFramebuffer(A.FRAMEBUFFER,null),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.disable(A.DEPTH_TEST),L.bind(),E.color[0].bind(0),L.uniforms.accumBuffer=0,p(A),A.disable(A.BLEND)}F=!1;for(var o=0;r>o;++o)O[o].dirty=!1}}}function x(){_||H.contextLost||(requestAnimationFrame(x),b())}t=t||{};var _=!1,w=(t.pixelRatio||parseFloat(window.devicePixelRatio),t.canvas);if(!w)if(w=document.createElement("canvas"),t.container){var k=t.container;k.appendChild(w)}else document.body.appendChild(w);var A=t.gl;if(A||(A=i(w,t.glOptions||{premultipliedAlpha:!0,antialias:!0})),!A)throw new Error("webgl not supported");var M=t.bounds||[[-10,-10,-10],[10,10,10]],T=new n,E=d(A,[A.drawingBufferWidth,A.drawingBufferHeight],{preferFloat:!0}),L=m(A),S=t.camera||{eye:[2,0,0],center:[0,0,0],up:[0,1,0],zoomMin:.1,zoomMax:100,mode:"turntable"},C=t.axes||{},z=c(A,C);z.enable=!C.disable;var P=t.spikes||{},R=f(A,P),O=[],I=[],N=[],j=[],F=!0,D=!0,B=new Array(16),U=new Array(16),V={view:null,projection:B,model:U},D=!0,q=[A.drawingBufferWidth,A.drawingBufferHeight],H={gl:A,contextLost:!1,pixelRatio:t.pixelRatio||parseFloat(window.devicePixelRatio),canvas:w,selection:T,camera:l(w,S),axes:z,axesPixels:null,spikes:R,bounds:M,objects:O,shape:q,aspect:t.aspectRatio||[1,1,1],pickRadius:t.pickRadius||10,zNear:t.zNear||.01,zFar:t.zFar||1e3,fovy:t.fovy||Math.PI/4,clearColor:t.clearColor||[0,0,0,0],autoResize:o(t.autoResize),autoBounds:o(t.autoBounds),autoScale:!!t.autoScale,autoCenter:o(t.autoCenter),clipToBounds:o(t.clipToBounds),snapToData:!!t.snapToData,onselect:t.onselect||null,onrender:t.onrender||null,onclick:t.onclick||null,cameraParams:V,oncontextloss:null,mouseListener:null},G=[A.drawingBufferWidth/H.pixelRatio|0,A.drawingBufferHeight/H.pixelRatio|0];H.autoResize&&e(),window.addEventListener("resize",e),H.update=function(t){_||(t=t||{},F=!0,D=!0)},H.add=function(t){_||(t.axes=z,O.push(t),I.push(-1),F=!0,D=!0,r())},H.remove=function(t){if(!_){var e=O.indexOf(t);0>e||(O.splice(e,1),I.pop(),F=!0,D=!0,r())}},H.dispose=function(){if(!_&&(_=!0,window.removeEventListener("resize",e),w.removeEventListener("webglcontextlost",s),H.mouseListener.enabled=!1,!H.contextLost)){z.dispose(),R.dispose();for(var t=0;ts;++s){var l=j[s].query(e,G[1]-r-1,H.pickRadius);if(l){if(l.distance>T.distance)continue;for(var c=0;i>c;++c){var u=O[c];if(I[c]===s){var f=u.pick(l);f&&(T.buttons=t,T.screen=l.coord,T.distance=l.distance,T.object=u,T.index=f.distance,T.dataPosition=f.position,T.dataCoordinate=f.dataCoordinate,T.data=f,o=!0)}}}}}a&&a!==T.object&&(a.highlight&&a.highlight(null),F=!0),T.object&&(T.object.highlight&&T.object.highlight(T.data),F=!0),o=o||T.object!==a,o&&H.onselect&&H.onselect(T),1&t&&!(1&X)&&H.onclick&&H.onclick(T),X=t}}),w.addEventListener("webglcontextlost",s);var W=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],Z=[W[0].slice(),W[1].slice()];return x(),H.redraw=function(){_||(F=!0,b())},H}e.exports=s;var l=t("3d-view-controls"),c=t("gl-axes3d"),u=t("gl-axes3d/properties"),f=t("gl-spikes3d"),h=t("gl-select-static"),d=t("gl-fbo"),p=t("a-big-triangle"),g=t("mouse-change"),v=t("gl-mat4/perspective"),m=t("./lib/shader")},{"./lib/shader":166,"3d-view-controls":167,"a-big-triangle":169,"gl-axes3d":170,"gl-axes3d/properties":180,"gl-fbo":123,"gl-mat4/perspective":140,"gl-select-static":196,"gl-spikes3d":182,"mouse-change":241}],184:[function(t,e,r){"use strict";e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",fragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n",pickVertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",pickFragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n"}},{}],185:[function(t,e,r){"use strict";function n(t){if(t in h)return h[t];var e=u(t,{polygons:!0,font:"sans-serif",textAlign:"left",textBaseline:"alphabetic"}),r=[],n=[];e.forEach(function(t){t.forEach(function(t){for(var e=0;eo;++o)i[o]=Math.min(i[o],r[a+o]),i[2+o]=Math.max(i[2+o],r[a+o]);return h[t]={coords:r,normals:n,bounds:i}}function i(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.offsetBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.numVertices=0,this.pickOffset=0,this.points=null}function a(t,e){var r=t.gl,n=o(r,f.vertex,f.fragment),a=o(r,f.pickVertex,f.pickFragment),l=s(r),c=s(r),u=s(r),h=s(r),d=new i(t,n,a,l,c,u,h);return d.update(e),t.addObject(d),d}e.exports=a;var o=t("gl-shader"),s=t("gl-buffer"),l=t("text-cache"),c=t("typedarray-pool"),u=t("vectorize-text"),f=t("./lib/shaders"),h={},d=i.prototype;!function(){function t(){var t=this.plot,n=this.bounds,i=t.viewBox,a=t.dataBox,o=t.pixelRatio,s=n[2]-n[0],l=n[3]-n[1],c=a[2]-a[0],u=a[3]-a[1];e[0]=2*s/c,e[4]=2*l/u,e[6]=2*(n[0]-a[0])/c-1,e[7]=2*(n[1]-a[1])/u-1;var f=i[2]-i[0],h=i[3]-i[1];r[0]=2*o/f,r[1]=2*o/h}var e=[1,0,0,0,1,0,0,0,1],r=[1,1];d.draw=function(){var n=this.plot,i=this.shader,a=this.numVertices;if(a){var o=n.gl;t.call(this),i.bind(),i.uniforms.pixelScale=r,i.uniforms.viewTransform=e,this.positionBuffer.bind(),i.attributes.position.pointer(),this.offsetBuffer.bind(),i.attributes.offset.pointer(),this.colorBuffer.bind(),i.attributes.color.pointer(o.UNSIGNED_BYTE,!0),o.drawArrays(o.TRIANGLES,0,a)}};var n=[0,0,0,0];d.drawPick=function(i){var a=this.plot,o=this.pickShader,s=this.numVertices,l=a.gl;if(this.pickOffset=i,!s)return i;for(var c=0;4>c;++c)n[c]=i>>8*c&255;return t.call(this),o.bind(),o.uniforms.pixelScale=r,o.uniforms.viewTransform=e,o.uniforms.pickOffset=n,this.positionBuffer.bind(),o.attributes.position.pointer(),this.offsetBuffer.bind(),o.attributes.offset.pointer(),this.idBuffer.bind(),o.attributes.id.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,s),i+this.numPoints}}(),d.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},d.update=function(t){t=t||{};var e=t.positions||[],r=t.colors||[],i=t.glyphs||[],a=t.sizes||[],o=t.borderWidths||[],s=t.borderColors||[];this.points=e;for(var u=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=0,h=0;h>1;for(var d=0;2>d;++d)u[d]=Math.min(u[d],e[2*h+d]),u[2+d]=Math.max(u[2+d],e[2*h+d])}u[0]===u[2]&&(u[2]+=1),u[3]===u[1]&&(u[3]+=1);for(var p=1/(u[2]-u[0]),g=1/(u[3]-u[1]),v=u[0],m=u[1],y=c.mallocFloat32(2*f),b=c.mallocFloat32(2*f),x=c.mallocUint8(4*f),_=c.mallocUint32(f),w=0,h=0;h=a?i(0,a-1,t,e,r,n):f(0,a-1,t,e,r,n)}function i(t,e,r,n,i,a){for(var o=t+1;e>=o;++o){for(var s=r[o],l=n[2*o],c=n[2*o+1],u=i[o],f=a[o],h=o;h>t;){var d=r[h-1],p=n[2*(h-1)];if((d-s||l-p)>=0)break;r[h]=d,n[2*h]=p,n[2*h+1]=n[2*h-1],i[h]=i[h-1],a[h]=a[h-1],h-=1}r[h]=s,n[2*h]=l,n[2*h+1]=c,i[h]=u,a[h]=f}}function a(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],c=i[t],u=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=c,a[e]=u}function o(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function s(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],c=i[2*t+1],u=a[t],f=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=c,a[r]=u,o[r]=f}function l(t,e,r,n,i,a,o,s,l,c,u){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],c[t]=c[e],u[t]=u[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,c[e]=a,u[e]=o}function c(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function u(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}function f(t,e,r,n,d,p){var g=(e-t+1)/6|0,v=t+g,m=e-g,y=t+e>>1,b=y-g,x=y+g,_=v,w=b,k=y,A=x,M=m,T=t+1,E=e-1,L=0;c(_,w,r,n,d,p)&&(L=_,_=w,w=L),c(A,M,r,n,d,p)&&(L=A,A=M,M=L),c(_,k,r,n,d,p)&&(L=_,_=k,k=L),c(w,k,r,n,d,p)&&(L=w,w=k,k=L),c(_,A,r,n,d,p)&&(L=_,_=A,A=L),c(k,A,r,n,d,p)&&(L=k,k=A,A=L),c(w,M,r,n,d,p)&&(L=w,w=M,M=L),c(w,k,r,n,d,p)&&(L=w,w=k,k=L),c(A,M,r,n,d,p)&&(L=A,A=M,M=L);var S=r[w],C=n[2*w],z=n[2*w+1],P=d[w],R=p[w],O=r[A],I=n[2*A],N=n[2*A+1],j=d[A],F=p[A],D=_,B=k,U=M,V=v,q=y,H=m,G=r[D],Y=r[B],X=r[U];r[V]=G,r[q]=Y,r[H]=X;for(var W=0;2>W;++W){var Z=n[2*D+W],K=n[2*B+W],$=n[2*U+W];n[2*V+W]=Z,n[2*q+W]=K,n[2*H+W]=$}var Q=d[D],J=d[B],tt=d[U];d[V]=Q,d[q]=J,d[H]=tt;var et=p[D],rt=p[B],nt=p[U];p[V]=et,p[q]=rt,p[H]=nt,o(b,t,r,n,d,p),o(x,e,r,n,d,p);for(var it=T;E>=it;++it)if(u(it,S,C,z,P,r,n,d))it!==T&&a(it,T,r,n,d,p),++T;else if(!u(it,O,I,N,j,r,n,d))for(;;){if(u(E,O,I,N,j,r,n,d)){u(E,S,C,z,P,r,n,d)?(s(it,T,E,r,n,d,p),++T,--E):(a(it,E,r,n,d,p),--E);break}if(--E=T-2-t?i(t,T-2,r,n,d,p):f(t,T-2,r,n,d,p),h>=e-(E+2)?i(E+2,e,r,n,d,p):f(E+2,e,r,n,d,p),h>=E-T?i(T,E,r,n,d,p):f(T,E,r,n,d,p)}e.exports=n;var h=32},{}],189:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s){for(var l=r,c=r;n>c;++c){var u=t[2*c],f=t[2*c+1],h=e[c];u>=i&&o>=u&&f>=a&&s>=f&&(c===l?l+=1:(t[2*c]=t[2*l],t[2*c+1]=t[2*l+1],e[c]=e[l],t[2*l]=u,t[2*l+1]=f,e[l]=h,l+=1))}return l}function i(t,e,r){this.pixelSize=t,this.offset=e,this.count=r}function a(t,e,r,a){function l(i,a,o,s,c,u){var f=.5*o,h=s+1,d=c-s;r[_]=d,x[_++]=u;for(var p=0;2>p;++p)for(var g=0;2>g;++g){var v=i+p*f,m=a+g*f,y=n(t,e,h,c,v,m,v+f,m+f);if(y!==h){if(y-h>=Math.max(.9*d,32)){var b=c+s>>>1;l(v,m,f,h,b,u+1),h=b}l(v,m,f,h,y,u+1),h=y}}}var c=t.length>>>1;if(1>c)return[];for(var u=1/0,f=1/0,h=-(1/0),d=-(1/0),p=0;c>p;++p){var g=t[2*p],v=t[2*p+1];u=Math.min(u,g),h=Math.max(h,g),f=Math.min(f,v),d=Math.max(d,v),e[p]=p}u===h&&(h+=1+Math.abs(h)),f===d&&(d+=1+Math.abs(h));var m=1/(h-u),y=1/(d-f),b=Math.max(h-u,d-f);a=a||[0,0,0,0],a[0]=u,a[1]=f,a[2]=h,a[3]=d;var x=o.mallocInt32(c),_=0;l(u,f,b,0,c,0),s(x,t,e,r,c);for(var w=[],k=0,A=c,_=c-1;_>=0;--_){t[2*_]=(t[2*_]-u)*m,t[2*_+1]=(t[2*_+1]-f)*y;var M=x[_];M!==k&&(w.push(new i(b*Math.pow(.5,M),_+1,A-(_+1))),A=_+1,k=M)}return w.push(new i(b*Math.pow(.5,M+1),0,A)),o.free(x),w}var o=t("typedarray-pool"),s=t("./lib/sort");e.exports=a},{"./lib/sort":188,"typedarray-pool":278}],190:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.weightBuffer=n,this.shader=i,this.pickShader=a,this.scales=[],this.size=12,this.borderSize=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.pickOffset=0,this.points=null,this.xCoords=null}function i(t,e){var r=t.gl,i=o(r),s=o(r),l=o(r),c=a(r,u.pointVertex,u.pointFragment),f=a(r,u.pickVertex,u.pickFragment),h=new n(t,i,s,l,c,f);return h.update(e),t.addObject(h),h}var a=t("gl-shader"),o=t("gl-buffer"),s=t("binary-search-bounds"),l=t("snap-points-2d"),c=t("typedarray-pool"),u=t("./lib/shader");e.exports=i;var f=n.prototype;f.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.xCoords&&c.free(this.xCoords),this.plot.removeObject(this)},f.update=function(t){function e(e,r){return e in t?t[e]:r}t=t||{},this.size=e("size",12),this.color=e("color",[1,0,0,1]).slice(),this.borderSize=e("borderSize",1),this.borderColor=e("borderColor",[0,0,0,1]).slice(),this.xCoords&&c.free(this.xCoords);var r=t.positions,n=c.mallocFloat32(r.length),i=c.mallocInt32(r.length>>>1);n.set(r);var a=c.mallocFloat32(r.length);this.points=r,this.scales=l(n,i,a,this.bounds),this.offsetBuffer.update(n),this.pickBuffer.update(i),this.weightBuffer.update(a);for(var o=c.mallocFloat32(r.length>>>1),s=0,u=0;s>>1,this.pickOffset=0},f.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.scales,o=this.offsetBuffer,l=this.pickBuffer,c=this.bounds,u=this.size,f=this.borderSize,h=n.gl,d=n.pickPixelRatio,p=n.viewBox,g=n.dataBox;if(0===this.pointCount)return r;var v=c[2]-c[0],m=c[3]-c[1],y=g[2]-g[0],b=g[3]-g[1],x=(p[2]-p[0])*d/n.pixelRatio,_=(p[3]-p[1])*d/n.pixelRatio,w=Math.min(y/x,b/_);t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(c[0]-g[0])/y-1,t[7]=2*(c[1]-g[1])/b-1,this.pickOffset=r,e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,i.bind(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointSize=d*(u+f),i.uniforms.pickOffset=e,0===this.borderSize?i.uniforms.centerFraction=2:i.uniforms.centerFraction=u/(u+f+1.25),o.bind(),i.attributes.position.pointer(),l.bind(),i.attributes.pickId.pointer(h.UNSIGNED_BYTE);for(var k=this.xCoords,A=(g[0]-c[0]-w*u*d)/v,M=(g[2]-c[0]+w*u*d)/v,T=a.length-1;T>=0;--T){var E=a[T];if(!(E.pixelSize1)){var L=E.offset,S=E.count+L,C=s.ge(k,A,L,S-1),z=s.lt(k,M,C,S-1)+1;z>C&&h.drawArrays(h.POINTS,C,z-C)}}return r+this.pointCount}}(),f.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.scales,i=this.offsetBuffer,a=this.bounds,o=this.size,l=this.borderSize,c=e.gl,u=e.pixelRatio,f=e.viewBox,h=e.dataBox;if(0!==this.pointCount){var d=a[2]-a[0],p=a[3]-a[1],g=h[2]-h[0],v=h[3]-h[1],m=f[2]-f[0],y=f[3]-f[1],b=Math.min(g/m,v/y);t[0]=2*d/g,t[4]=2*p/v,t[6]=2*(a[0]-h[0])/g-1,t[7]=2*(a[1]-h[1])/v-1,r.bind(),r.uniforms.matrix=t,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointSize=u*(o+l),r.uniforms.useWeight=1,0===this.borderSize?r.uniforms.centerFraction=2:r.uniforms.centerFraction=o/(o+l+1.25),i.bind(),r.attributes.position.pointer(),this.weightBuffer.bind(),r.attributes.weight.pointer();for(var x=this.xCoords,_=(h[0]-a[0]-b*o*u)/d,w=(h[2]-a[0]+b*o*u)/d,k=!0,A=n.length-1;A>=0;--A){var M=n[A];if(!(M.pixelSize1)){var T=M.offset,E=M.count+T,L=s.ge(x,_,T,E-1),S=s.lt(x,w,L,E-1)+1;S>L&&c.drawArrays(c.POINTS,L,S-L),k&&(k=!1,r.uniforms.useWeight=0)}}}}}(),f.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":186,"binary-search-bounds":187,"gl-buffer":118,"gl-shader":197,"snap-points-2d":189,"typedarray-pool":278}],191:[function(t,e,r){"use strict";function n(t,e){var r=a[e];if(r||(r=a[e]={}),t in r)return r[t];for(var n=i(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),o=i(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),s=[[1/0,1/0],[-(1/0),-(1/0)]],l=0;lu;++u)s[0][u]=Math.min(s[0][u],c[u]),s[1][u]=Math.max(s[1][u],c[u]);return r[t]=[o,n,s]}var i=t("vectorize-text");e.exports=n;var a={}},{"vectorize-text":280}],192:[function(t,e,r){function n(t,e){var r=i(t,e),n=r.attributes;return n.position.location=0,n.color.location=1,n.glyph.location=2,n.id.location=3,r}var i=t("gl-shader"),a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n \n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n \n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * view * model * vec4(position, 1);\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n",c="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}",u=[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"glyph",type:"vec2"},{name:"id",type:"vec4"}],f={vertex:a,fragment:l,attributes:u},h={vertex:o,fragment:l,attributes:u},d={vertex:s,fragment:l,attributes:u},p={vertex:a,fragment:c,attributes:u},g={vertex:o,fragment:c,attributes:u},v={vertex:s,fragment:c,attributes:u};r.createPerspective=function(t){return n(t,f)},r.createOrtho=function(t){return n(t,h)},r.createProject=function(t){return n(t,d)},r.createPickPerspective=function(t){return n(t,p)},r.createPickOrtho=function(t){return n(t,g)},r.createPickProject=function(t){return n(t,v)}},{"gl-shader":197}],193:[function(t,e,r){"use strict";function n(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];return t[0]=e[0]*r+e[4]*n+e[8]*i+e[12]*a,t[1]=e[1]*r+e[5]*n+e[9]*i+e[13]*a,t[2]=e[2]*r+e[6]*n+e[10]*i+e[14]*a,t[3]=e[3]*r+e[7]*n+e[11]*i+e[15]*a, -t}function i(t,e,r,i){return n(i,i,r),n(i,i,e),n(i,i,t)}function a(t,e){this.index=t,this.dataCoordinate=this.position=e}function o(t,e,r,n,i,o,s,l,c,u,f,h){this.gl=t,this.pixelRatio=1,this.shader=e,this.orthoShader=r,this.projectShader=n,this.pointBuffer=i,this.colorBuffer=o,this.glyphBuffer=s,this.idBuffer=l,this.vao=c,this.vertexCount=0,this.lineVertexCount=0,this.opacity=1,this.lineWidth=0,this.projectScale=[2/3,2/3,2/3],this.projectOpacity=[1,1,1],this.pickId=0,this.pickPerspectiveShader=u,this.pickOrthoShader=f,this.pickProjectShader=h,this.points=[],this._selectResult=new a(0,[0,0,0]),this.useOrtho=!0,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.axesProject=[!0,!0,!0],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.highlightId=[1,1,1,1],this.highlightScale=2,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.dirty=!0}function s(t){return t[0]=t[1]=t[2]=0,t}function l(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function c(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function u(t){for(var e=S,r=0;2>r;++r)for(var n=0;3>n;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}function f(t,e,r,n,a){var o,f=e.axesProject,h=e.gl,d=t.uniforms,p=r.model||x,g=r.view||x,v=r.projection||x,y=e.axesBounds,b=u(e.clipBounds);o=e.axes?e.axes.lastCubeProps.axis:[1,1,1],w[0]=2/h.drawingBufferWidth,w[1]=2/h.drawingBufferHeight,t.bind(),d.view=g,d.projection=v,d.screenSize=w,d.highlightId=e.highlightId,d.highlightScale=e.highlightScale,d.clipBounds=b,d.pickGroup=e.pickId/255,d.pixelRatio=e.pixelRatio;for(var _=0;3>_;++_)if(f[_]&&e.projectOpacity[_]<1===n){d.scale=e.projectScale[_],d.opacity=e.projectOpacity[_];for(var S=E,C=0;16>C;++C)S[C]=0;for(var C=0;4>C;++C)S[5*C]=1;S[5*_]=0,o[_]<0?S[12+_]=y[0][_]:S[12+_]=y[1][_],m(S,p,S),d.model=S;var z=(_+1)%3,P=(_+2)%3,R=s(k),O=s(A);R[z]=1,O[P]=1;var I=i(v,g,p,l(M,R)),N=i(v,g,p,l(T,O));if(Math.abs(I[1])>Math.abs(N[1])){var j=I;I=N,N=j,j=R,R=O,O=j;var F=z;z=P,P=F}I[0]<0&&(R[z]=-1),N[1]>0&&(O[P]=-1);for(var D=0,B=0,C=0;4>C;++C)D+=Math.pow(p[4*z+C],2),B+=Math.pow(p[4*P+C],2);R[z]/=Math.sqrt(D),O[P]/=Math.sqrt(B),d.axes[0]=R,d.axes[1]=O,d.fragClipBounds[0]=c(L,b[0],_,-1e8),d.fragClipBounds[1]=c(L,b[1],_,1e8),e.vao.draw(h.TRIANGLES,e.vertexCount),e.lineWidth>0&&(h.lineWidth(e.lineWidth),e.vao.draw(h.LINES,e.lineVertexCount,e.vertexCount))}}function h(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||x,s.view=n.view||x,s.projection=n.projection||x,w[0]=2/o.drawingBufferWidth,w[1]=2/o.drawingBufferHeight,s.screenSize=w,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=P,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}f(e,r,n,i,a),r.vao.unbind()}function d(t){var e=t.gl,r=y.createPerspective(e),n=y.createOrtho(e),i=y.createProject(e),a=y.createPickPerspective(e),s=y.createPickOrtho(e),l=y.createPickProject(e),c=p(e),u=p(e),f=p(e),h=p(e),d=g(e,[{buffer:c,size:3,type:e.FLOAT},{buffer:u,size:4,type:e.FLOAT},{buffer:f,size:2,type:e.FLOAT},{buffer:h,size:4,type:e.UNSIGNED_BYTE,normalized:!0}]),v=new o(e,r,n,i,c,u,f,h,d,a,s,l);return v.update(t),v}var p=t("gl-buffer"),g=t("gl-vao"),v=t("typedarray-pool"),m=t("gl-mat4/multiply"),y=t("./lib/shaders"),b=t("./lib/glyphs"),x=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];e.exports=d;var _=o.prototype;_.pickSlots=1,_.setPickBase=function(t){this.pickId=t},_.isTransparent=function(){if(this.opacity<1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]<1)return!0;return!1},_.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var w=[0,0],k=[0,0,0],A=[0,0,0],M=[0,0,0,1],T=[0,0,0,1],E=x.slice(),L=[0,0,0],S=[[0,0,0],[0,0,0]],C=[-1e8,-1e8,-1e8],z=[1e8,1e8,1e8],P=[C,z];_.draw=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!1,!1)},_.drawTransparent=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!0,!1)},_.drawPick=function(t){var e=this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader;h(e,this.pickProjectShader,this,t,!1,!0)},_.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||0>e)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;3>i;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},_.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},_.update=function(t){if(t=t||{},"perspective"in t&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{var r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-(1/0),-(1/0),-(1/0)],l=t.glyph,c=t.color,u=t.size,f=t.angle,h=t.lineColor,d=0,p=0,g=0,m=n.length;t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_)if(isNaN(x[_])||!isFinite(x[_]))continue t;var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];p+=3*k.cells.length,g+=2*A.edges.length}var T=p+g,E=v.mallocFloat(3*T),L=v.mallocFloat(4*T),S=v.mallocFloat(2*T),C=v.mallocUint32(T),z=[0,a[1]],P=0,R=p,O=[0,0,0,1],I=[0,0,0,1],N=Array.isArray(c)&&Array.isArray(c[0]),j=Array.isArray(h)&&Array.isArray(h[0]);t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_){if(isNaN(x[_])||!isFinite(x[_])){d+=1;continue t}s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_])}var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];if(Array.isArray(c)){var F;if(F=N?c[y]:c,3===F.length){for(var _=0;3>_;++_)O[_]=F[_];O[3]=1}else if(4===F.length)for(var _=0;4>_;++_)O[_]=F[_]}else O[0]=O[1]=O[2]=0,O[3]=1;if(Array.isArray(h)){var F;if(F=j?h[y]:h,3===F.length){for(var _=0;3>_;++_)I[_]=F[_];I[_]=1}else if(4===F.length)for(var _=0;4>_;++_)I[_]=F[_]}else I[0]=I[1]=I[2]=0,I[3]=1;var D=.5;Array.isArray(u)?D=+u[y]:u?D=+u:this.useOrtho&&(D=12);var B=0;Array.isArray(f)?B=+f[y]:f&&(B=+f);for(var U=Math.cos(B),V=Math.sin(B),x=n[y],_=0;3>_;++_)s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_]);a[0]<0?z[0]=a[0]*(1+M[1][0]):a[0]>0&&(z[0]=-a[0]*(1+M[0][0]));for(var q=k.cells,H=k.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*P+X]=x[X];for(var X=0;4>X;++X)L[4*P+X]=O[X];C[P]=d;var W=H[G[Y]];S[2*P]=D*(U*W[0]-V*W[1]+z[0]),S[2*P+1]=D*(V*W[0]+U*W[1]+z[1]),P+=1}for(var q=A.edges,H=A.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*R+X]=x[X];for(var X=0;4>X;++X)L[4*R+X]=I[X];C[R]=d;var W=H[G[Y]];S[2*R]=D*(U*W[0]-V*W[1]+z[0]),S[2*R+1]=D*(V*W[0]+U*W[1]+z[1]),R+=1}d+=1}this.vertexCount=p,this.lineVertexCount=g,this.pointBuffer.update(E),this.colorBuffer.update(L),this.glyphBuffer.update(S),this.idBuffer.update(new Uint32Array(C)),v.free(E),v.free(L),v.free(S),v.free(C),this.bounds=[o,s],this.points=n,this.pointCount=n.length}},_.dispose=function(){this.shader.dispose(),this.orthoShader.dispose(),this.pickPerspectiveShader.dispose(),this.pickOrthoShader.dispose(),this.vao.dispose(),this.pointBuffer.dispose(),this.colorBuffer.dispose(),this.glyphBuffer.dispose(),this.idBuffer.dispose()}},{"./lib/glyphs":191,"./lib/shaders":192,"gl-buffer":118,"gl-mat4/multiply":139,"gl-vao":226,"typedarray-pool":278}],194:[function(t,e,r){"use strict";r.boxVertex="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n",r.boxFragment="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n"},{}],195:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.boxBuffer=e,this.boxShader=r,this.enabled=!0,this.selectBox=[1/0,1/0,-(1/0),-(1/0)],this.borderColor=[0,0,0,1],this.innerFill=!1,this.innerColor=[0,0,0,.25],this.outerFill=!0,this.outerColor=[0,0,0,.5],this.borderWidth=10}function i(t,e){var r=t.gl,i=o(r,[0,0,0,1,1,0,1,1]),l=a(r,s.boxVertex,s.boxFragment),c=new n(t,i,l);return c.update(e),t.addOverlay(c),c}var a=t("gl-shader"),o=t("gl-buffer"),s=t("./lib/shaders");e.exports=i;var l=n.prototype;l.draw=function(){if(this.enabled){var t=this.plot,e=this.selectBox,r=this.borderWidth,n=(this.innerFill,this.innerColor),i=(this.outerFill,this.outerColor),a=this.borderColor,o=t.box,s=t.screenBox,l=t.dataBox,c=t.viewBox,u=t.pixelRatio,f=(e[0]-l[0])*(c[2]-c[0])/(l[2]-l[0])+c[0],h=(e[1]-l[1])*(c[3]-c[1])/(l[3]-l[1])+c[1],d=(e[2]-l[0])*(c[2]-c[0])/(l[2]-l[0])+c[0],p=(e[3]-l[1])*(c[3]-c[1])/(l[3]-l[1])+c[1];if(f=Math.max(f,c[0]),h=Math.max(h,c[1]),d=Math.min(d,c[2]),p=Math.min(p,c[3]),!(f>d||h>p)){o.bind();var g=s[2]-s[0],v=s[3]-s[1];if(this.outerFill&&(o.drawBox(0,0,g,h,i),o.drawBox(0,h,f,p,i),o.drawBox(0,p,g,v,i),o.drawBox(d,h,g,p,i)),this.innerFill&&o.drawBox(f,h,d,p,n),r>0){var m=r*u;o.drawBox(f-m,h-m,d+m,h+m,a),o.drawBox(f-m,p-m,d+m,p+m,a),o.drawBox(f-m,h-m,f+m,p+m,a),o.drawBox(d-m,h-m,d+m,p+m,a)}}}},l.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},l.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":194,"gl-buffer":118,"gl-shader":197}],196:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.coord=[t,e],this.id=r,this.value=n,this.distance=i}function i(t,e,r){this.gl=t,this.fbo=e,this.buffer=r,this._readTimeout=null;var n=this;this._readCallback=function(){n.gl&&(e.bind(),t.readPixels(0,0,e.shape[0],e.shape[1],t.RGBA,t.UNSIGNED_BYTE,n.buffer),n._readTimeout=null)}}function a(t,e){var r=o(t,e),n=s.mallocUint8(e[0]*e[1]*4);return new i(t,r,n)}e.exports=a;var o=t("gl-fbo"),s=t("typedarray-pool"),l=t("ndarray"),c=t("bit-twiddle").nextPow2,u=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(255>_inline_34_arg0_||255>_inline_34_arg1_||255>_inline_34_arg2_||255>_inline_34_arg3_){var _inline_34_l=_inline_34_arg4_-_inline_34_arg6_[0],_inline_34_a=_inline_34_arg5_-_inline_34_arg6_[1],_inline_34_f=_inline_34_l*_inline_34_l+_inline_34_a*_inline_34_a;_inline_34_fthis.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(c(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),f.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},f.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},f.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),c=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=c)return null;var f=[o-a,c-s],h=l(this.buffer,[f[0],f[1],4],[4,4*i[0],1],4*(a+i[0]*s)),d=u(h.hi(f[0],f[1],1),r,r),p=d[0],g=d[1];if(0>p||Math.pow(this.radius,2)=0){for(var A=0|k.type.charAt(k.type.length-1),M=new Array(A),T=0;A>T;++T)M[T]=_.length,x.push(k.name+"["+T+"]"),"number"==typeof k.location?_.push(k.location+T):Array.isArray(k.location)&&k.location.length===A&&"number"==typeof k.location[T]?_.push(0|k.location[T]):_.push(-1);b.push({name:k.name,type:k.type,locations:M})}else b.push({name:k.name,type:k.type,locations:[_.length]}),x.push(k.name),"number"==typeof k.location?_.push(0|k.location):_.push(-1)}for(var E=0,w=0;w<_.length;++w)if(_[w]<0){for(;_.indexOf(E)>=0;)E+=1;_[w]=E}var L=new Array(r.length);a(),d._relink=a,d.types={uniforms:l(r),attributes:l(n)},d.attributes=s(p,d,b,_),Object.defineProperty(d,"uniforms",o(p,d,r,L))},e.exports=a},{"./lib/GLError":198,"./lib/create-attributes":199,"./lib/create-uniforms":200,"./lib/reflect":201,"./lib/runtime-reflect":202,"./lib/shader-cache":203}],198:[function(t,e,r){function n(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}n.prototype=new Error,n.prototype.name="GLError",n.prototype.constructor=n,e.exports=n},{}],199:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}function i(t,e,r,i,a,o,s){for(var l=["gl","v"],c=[],u=0;a>u;++u)l.push("x"+u),c.push("x"+u);l.push("if(x0.length===void 0){return gl.vertexAttrib"+a+"f(v,"+c.join()+")}else{return gl.vertexAttrib"+a+"fv(v,x0)}");var f=Function.apply(null,l),h=new n(t,e,r,i,a,f);Object.defineProperty(o,s,{set:function(e){return t.disableVertexAttribArray(i[r]),f(t,i[r],e),e},get:function(){return h},enumerable:!0})}function a(t,e,r,n,a,o,s){for(var l=new Array(a),c=new Array(a),u=0;a>u;++u)i(t,e,r[u],n,a,l,u),c[u]=l[u];Object.defineProperty(l,"location",{set:function(t){if(Array.isArray(t))for(var e=0;a>e;++e)c[e].location=t[e];else for(var e=0;a>e;++e)c[e].location=t+e;return t},get:function(){for(var t=new Array(a),e=0;a>e;++e)t[e]=n[r[e]];return t},enumerable:!0}),l.pointer=function(e,i,o,s){e=e||t.FLOAT,i=!!i,o=o||a*a,s=s||0;for(var l=0;a>l;++l){var c=n[r[l]];t.vertexAttribPointer(c,a,e,i,o,s+l*a),t.enableVertexAttribArray(c)}};var f=new Array(a),h=t["vertexAttrib"+a+"fv"];Object.defineProperty(o,s,{set:function(e){for(var i=0;a>i;++i){var o=n[r[i]];if(t.disableVertexAttribArray(o),Array.isArray(e[0]))h.call(t,o,e[i]);else{for(var s=0;a>s;++s)f[s]=e[a*i+s];h.call(t,o,f)}}return e},get:function(){return l},enumerable:!0})}function o(t,e,r,n){for(var o={},l=0,c=r.length;c>l;++l){var u=r[l],f=u.name,h=u.type,d=u.locations;switch(h){case"bool":case"int":case"float":i(t,e,d[0],n,1,o,f);break;default:if(h.indexOf("vec")>=0){var p=h.charCodeAt(h.length-1)-48;if(2>p||p>4)throw new s("","Invalid data type for attribute "+f+": "+h);i(t,e,d[0],n,p,o,f)}else{if(!(h.indexOf("mat")>=0))throw new s("","Unknown data type for attribute "+f+": "+h);var p=h.charCodeAt(h.length-1)-48;if(2>p||p>4)throw new s("","Invalid data type for attribute "+f+": "+h);a(t,e,d,n,p,o,f)}}}return o}e.exports=o;var s=t("./GLError"),l=n.prototype;l.pointer=function(t,e,r,n){var i=this,a=i._gl,o=i._locations[i._index];a.vertexAttribPointer(o,i._dimension,t||a.FLOAT,!!e,r||0,n||0),a.enableVertexAttribArray(o)},l.set=function(t,e,r,n){return this._constFunc(this._locations[this._index],t,e,r,n)},Object.defineProperty(l,"location",{get:function(){return this._locations[this._index]},set:function(t){return t!==this._locations[this._index]&&(this._locations[this._index]=0|t,this._wrapper.program=null),0|t}})},{"./GLError":198}],200:[function(t,e,r){"use strict";function n(t){var e=new Function("y","return function(){return y}");return e(t)}function i(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e,r,a){function l(r){var n=new Function("gl","wrapper","locations","return function(){return gl.getUniform(wrapper.program,locations["+r+"])}");return n(t,e,a)}function c(t,e,r){switch(r){case"bool":case"int":case"sampler2D":case"samplerCube":return"gl.uniform1i(locations["+e+"],obj"+t+")";case"float":return"gl.uniform1f(locations["+e+"],obj"+t+")";default:var n=r.indexOf("vec");if(!(n>=0&&1>=n&&r.length===4+n)){if(0===r.indexOf("mat")&&4===r.length){var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new s("","Unknown uniform data type for "+name+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new s("","Unrecognized data type for vector "+name+": "+r)}}}function u(t,e){if("object"!=typeof e)return[[t,e]];var r=[];for(var n in e){var i=e[n],a=t;a+=parseInt(n)+""===n?"["+n+"]":"."+n,"object"==typeof i?r.push.apply(r,u(a,i)):r.push([a,i])}return r}function f(e){for(var n=["return function updateProperty(obj){"],i=u("",e),o=0;o=0&&1>=e&&t.length===4+e){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid data type");return"b"===t.charAt(0)?i(r,!1):i(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+t);return i(r*r,0)}throw new s("","Unknown uniform data type for "+name+": "+t)}}function d(t,e,i){if("object"==typeof i){var o=p(i);Object.defineProperty(t,e,{get:n(o),set:f(i),enumerable:!0,configurable:!1})}else a[i]?Object.defineProperty(t,e,{get:l(i),set:f(i),enumerable:!0,configurable:!1}):t[e]=h(r[i].type)}function p(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var c=1;ca;++a){var o=t.getActiveUniform(e,a);if(o){var s=n(t,o.type);if(o.size>1)for(var l=0;la;++a){var o=t.getActiveAttrib(e,a);o&&i.push({name:o.name,type:n(t,o.type)})}return i}r.uniforms=i,r.attributes=a;var o={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube"},s=null},{}],203:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.id=t,this.src=e,this.type=r,this.shader=n,this.count=a,this.programs=[],this.cache=o}function i(t){this.gl=t,this.shaders=[{},{}],this.programs={}}function a(t,e,r){var n=t.createShader(e);if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){var i=t.getShaderInfoLog(n);try{var a=f(i,r,e)}catch(o){throw console.warn("Failed to format compiler error: "+o),new u(i,"Error compiling shader:\n"+i)}throw new u(i,a.short,a.long)}return n}function o(t,e,r,n,i){var a=t.createProgram();t.attachShader(a,e),t.attachShader(a,r);for(var o=0;on;++n){var a=t.programs[r[n]];a&&(delete t.programs[n],e.deleteProgram(a))}e.deleteShader(this.shader),delete t.shaders[this.type===e.FRAGMENT_SHADER|0][this.src]}};var g=i.prototype;g.getShaderReference=function(t,e){var r=this.gl,i=this.shaders[t===r.FRAGMENT_SHADER|0],o=i[e];if(o&&r.isShader(o.shader))o.count+=1;else{var s=a(r,t,e);o=i[e]=new n(p++,e,t,s,[],1,this)}return o},g.getProgram=function(t,e,r,n){var i=[t.id,e.id,r.join(":"),n.join(":")].join("@"),a=this.programs[i];return a&&this.gl.isProgram(a)||(this.programs[i]=a=o(this.gl,t.shader,e.shader,r,n),t.programs.push(i),e.programs.push(i)),a}},{"./GLError":198,"gl-format-compiler-error":204,"weakmap-shim":214}],204:[function(t,e,r){function n(t,e,r){"use strict";var n=o(e)||"of unknown name (see npm glsl-shader-name)",l="unknown type";void 0!==r&&(l=r===a.FRAGMENT_SHADER?"fragment":"vertex");for(var c=i("Error compiling %s shader %s:\n",l,n),u=i("%s%s",c,t),f=t.split("\n"),h={},d=0;ds;s++)if(g=i(t[s]),"string"===g)v[v.length]=t[s];else if("array"===g){if(c=t[s],c[2])for(n=e[d],l=0;l=0),c[8]){case"b":n=n.toString(2);break;case"c":n=String.fromCharCode(n);break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,c[6]?parseInt(c[6]):0);break;case"e":n=c[7]?n.toExponential(c[7]):n.toExponential();break;case"f":n=c[7]?parseFloat(n).toFixed(c[7]):parseFloat(n);break;case"g":n=c[7]?parseFloat(n).toPrecision(c[7]):parseFloat(n);break;case"o":n=n.toString(8);break;case"s":n=(n=String(n))&&c[7]?n.substring(0,c[7]):n;break;case"u":n>>>=0;break;case"x":n=n.toString(16);break;case"X":n=n.toString(16).toUpperCase()}o.json.test(c[8])?v[v.length]=n:(!o.number.test(c[8])||m&&!c[3]?y="":(y=m?"+":"-",n=n.toString().replace(o.sign,"")),f=c[4]?"0"===c[4]?"0":c[4].charAt(1):" ",h=c[6]-(y+n).length,u=c[6]&&h>0?a(f,h):"",v[v.length]=c[5]?y+n+u:"0"===f?y+u+n:u+y+n)}return v.join("")},r.cache={},r.parse=function(t){for(var e=t,r=[],n=[],i=0;e;){if(null!==(r=o.text.exec(e)))n[n.length]=r[0];else if(null!==(r=o.modulo.exec(e)))n[n.length]="%";else{if(null===(r=o.placeholder.exec(e)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){i|=1;var a=[],s=r[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a[a.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))a[a.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");a[a.length]=l[1]}r[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n[n.length]=r}e=e.substring(r[0].length)}return n};var s=function(t,e,n){return n=(e||[]).slice(0),n.splice(0,0,t),r.apply(null,n)};"undefined"!=typeof n?(n.sprintf=r,n.vsprintf=s):(e.sprintf=r,e.vsprintf=s,"function"==typeof t&&t.amd&&t(function(){return{sprintf:r,vsprintf:s}}))}("undefined"==typeof window?this:window)},{}],212:[function(t,e,r){function n(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:i(e,t)}}var i=t("./hidden-store.js");e.exports=n},{"./hidden-store.js":213}],213:[function(t,e,r){function n(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}e.exports=n},{}],214:[function(t,e,r){function n(){var t=i();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){t(e).value=r},has:function(e){return"value"in t(e)},"delete":function(e){return delete t(e).value}}}var i=t("./create-store.js");e.exports=n},{"./create-store.js":212}],215:[function(t,e,r){"use strict";function n(t){this.plot=t,this.enable=[!0,!0,!1,!1],this.width=[1,1,1,1],this.color=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.center=[1/0,1/0]}function i(t,e){var r=new n(t);return r.update(e),t.addOverlay(r),r}e.exports=i;var a=n.prototype;a.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},a.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),c=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,c,s[0],c,e[0],r[0]),t[1]&&a.drawLine(l,c,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,c,s[2],c,e[2],r[2]),t[3]&&a.drawLine(l,c,l,s[3],e[3],r[3])}},a.dispose=function(){this.plot.removeOverlay(this)}},{}],216:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n",s="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n";r.createShader=function(t){var e=n(t,i,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,i,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,o,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},r.createPickContourShader=function(t){var e=n(t,o,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e}},{"gl-shader":197}],217:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],218:[function(t,e,r){"use strict";function n(t){if(t in l)return l[t];for(var e=[],r=0;t>r;++r)e.push("out",r,"s=0.5*(inp",r,"l-inp",r,"r);");for(var n=["array"],i=["junk"],r=0;t>r;++r){n.push("array"),i.push("out"+r+"s");var a=o(t);a[r]=-1,n.push({array:0,offset:a.slice()}),a[r]=1,n.push({array:0,offset:a.slice()}),i.push("inp"+r+"l","inp"+r+"r")}return l[t]=s({args:n,pre:u,post:u,body:{body:e.join(""),args:i.map(function(t){return{name:t,lvalue:0===t.indexOf("out"),rvalue:0===t.indexOf("inp"),count:"junk"!==t|0}}),thisVars:[],localVars:[]},funcName:"fdTemplate"+t})}function i(t){function e(e){for(var r=a-e.length,n=[],i=[],s=[],l=0;a>l;++l)e.indexOf(l+1)>=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),n.push("1"),i.push("s["+l+"]-2"));var c=".lo("+n.join()+").hi("+i.join()+")";if(0===n.length&&(c=""),r>0){o.push("if(1");for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push("&&s[",l,"]>2");o.push("){grad",r,"(src.pick(",s.join(),")",c);for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push(",dst.pick(",s.join(),",",l,")",c);o.push(");")}for(var l=0;l1){dst.set(",s.join(),",",u,",0.5*(src.get(",h.join(),")-src.get(",d.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):o.push("if(s[",u,"]>1){diff(",f,",src.pick(",h.join(),")",c,",src.pick(",d.join(),")",c,");}else{zero(",f,");};");break;case"mirror":0===r?o.push("dst.set(",s.join(),",",u,",0);"):o.push("zero(",f,");");break;case"wrap":var p=s.slice(),g=s.slice();e[l]<0?(p[u]="s["+u+"]-2",g[u]="0"):(p[u]="s["+u+"]-1",g[u]="1"),0===r?o.push("if(s[",u,"]>2){dst.set(",s.join(),",",u,",0.5*(src.get(",p.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):o.push("if(s[",u,"]>2){diff(",f,",src.pick(",p.join(),")",c,",src.pick(",g.join(),")",c,");}else{zero(",f,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}r>0&&o.push("};")}var r=t.join(),i=c[r];if(i)return i;for(var a=t.length,o=["function gradient(dst,src){var s=src.shape.slice();"],s=0;1<s;++s){for(var u=[],d=0;a>d;++d)s&1<=s;++s)v.push("grad"+s),m.push(n(s));v.push(o.join(""));var y=Function.apply(void 0,v),i=y.apply(void 0,m);return l[r]=i,i}function a(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r="string"==typeof r?o(e.dimension,r):o(e.dimension,"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;nr;++r)for(o=o||e.surfaceProject[r],n=0;3>n;++n)s=s||e.contourProject[r][n];for(r=0;3>r;++r){var l=D.projections[r];for(n=0;16>n;++n)l[n]=0;for(n=0;4>n;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],k(l,t.model,l);var c=D.clipBounds[r];for(i=0;2>i;++i)for(n=0;3>n;++n)c[i][n]=t.clipBounds[i][n];c[0][r]=-1e8,c[1][r]=1e8}return D.showSurface=o,D.showContour=s,D}function s(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=B;n.model=t.model||R,n.view=t.view||R,n.projection=t.projection||R,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=A(n.inverseModel,n.model);for(var i=0;2>i;++i)for(var a=n.clipBounds[i],s=0;3>s;++s)a[s]=Math.min(Math.max(this.clipBounds[i][s],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=V;var l=U;for(k(l,n.view,n.model),k(l,n.projection,l),A(l,l),i=0;3>i;++i)n.eyePosition[i]=l[12+i]/l[15];var c=l[15];for(i=0;3>i;++i)c+=this.lightPosition[i]*l[4*i+3];for(i=0;3>i;++i){var u=l[12+i];for(s=0;3>s;++s)u+=l[4*s+i]*this.lightPosition[s];n.lightPosition[i]=u/c}var f=o(n,this);if(f.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;3>i;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=f.projections[i],this._shader.uniforms.clipBounds=f.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(f.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var d=this._contourVAO;for(d.bind(),i=0;3>i;++i)for(h.uniforms.permutation=I[i],r.lineWidth(this.contourWidth[i]),s=0;si;++i)for(h.uniforms.model=f.projections[i],h.uniforms.clipBounds=f.clipBounds[i],s=0;3>s;++s)if(this.contourProject[i][s]){h.uniforms.permutation=I[s],r.lineWidth(this.contourWidth[s]);for(var p=0;pi;++i)if(0!==this._dynamicCounts[i])for(h.uniforms.model=n.model,h.uniforms.clipBounds=n.clipBounds,h.uniforms.permutation=I[i],r.lineWidth(this.dynamicWidth[i]),h.uniforms.contourColor=this.dynamicColor[i],h.uniforms.contourTint=this.dynamicTint[i],h.uniforms.height=this.dynamicLevel[i],d.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]),s=0;3>s;++s)this.contourProject[s][i]&&(h.uniforms.model=f.projections[s],h.uniforms.clipBounds=f.clipBounds[s],d.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]));d.unbind()}}function l(t,e){var r=e.shape.slice(),n=t.shape.slice();b.assign(t.lo(1,1).hi(r[0],r[1]),e),b.assign(t.lo(1).hi(r[0],1),e.hi(r[0],1)),b.assign(t.lo(1,n[1]-1).hi(r[0],1),e.lo(0,r[1]-1).hi(r[0],1)),b.assign(t.lo(0,1).hi(1,r[1]),e.hi(1)),b.assign(t.lo(n[0]-1,1).hi(1,r[1]),e.lo(r[0]-1)),t.set(0,0,e.get(0,0)),t.set(0,n[1]-1,e.get(0,r[1]-1)),t.set(n[0]-1,0,e.get(r[0]-1,0)),t.set(n[0]-1,n[1]-1,e.get(r[0]-1,r[1]-1))}function c(t,e){return Array.isArray(t)?[e(t[0]),e(t[1]),e(t[2])]:[e(t),e(t),e(t)]}function u(t){return Array.isArray(t)?3===t.length?[t[0],t[1],t[2],1]:[t[0],t[1],t[2],t[3]]:[0,0,0,1]}function f(t){if(Array.isArray(t)){if(Array.isArray(t))return[u(t[0]),u(t[1]),u(t[2])];var e=u(t);return[e.slice(),e.slice(),e.slice()]}}function h(t){var e=t.gl,r=L(e),n=C(e),i=S(e),o=z(e),s=p(e),l=g(e,[{buffer:s,size:4,stride:P,offset:0},{buffer:s,size:3,stride:P,offset:16},{buffer:s,size:3,stride:P,offset:28}]),c=p(e),u=g(e,[{buffer:c,size:4,stride:20,offset:0},{buffer:c,size:1,stride:20,offset:16}]),f=p(e),h=g(e,[{buffer:f,size:2,type:e.FLOAT}]),d=v(e,1,N,e.RGBA,e.UNSIGNED_BYTE);d.minFilter=e.LINEAR,d.magFilter=e.LINEAR;var m=new a(e,[0,0],[[0,0,0],[0,0,0]],r,n,s,l,d,i,o,c,u,f,h),y={levels:[[],[],[]]};for(var b in t)y[b]=t[b];return y.colormap=y.colormap||"jet",m.update(y),m}e.exports=h;var d=t("bit-twiddle"),p=t("gl-buffer"),g=t("gl-vao"),v=t("gl-texture2d"),m=t("typedarray-pool"),y=t("colormap"),b=t("ndarray-ops"),x=t("ndarray-pack"),_=t("ndarray"),w=t("surface-nets"),k=t("gl-mat4/multiply"),A=t("gl-mat4/invert"),M=t("binary-search-bounds"),T=t("ndarray-gradient"),E=t("./lib/shaders"),L=E.createShader,S=E.createContourShader,C=E.createPickShader,z=E.createPickContourShader,P=40,R=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],O=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],I=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];!function(){for(var t=0;3>t;++t){var e=I[t],r=(t+1)%3,n=(t+2)%3;e[r+0]=1,e[n+3]=1,e[t+6]=1}}();var N=265,j=a.prototype;j.isTransparent=function(){return this.opacity<1},j.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},j.pickSlots=1,j.setPickBase=function(t){this.pickId=t};var F=[0,0,0],D={showSurface:!1,showContour:!1,projections:[R.slice(),R.slice(),R.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]},B={model:R,view:R,projection:R,inverseModel:R.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1},U=R.slice(),V=[1,0,0,0,1,0,0,0,1];j.draw=function(t){return s.call(this,t,!1)},j.drawTransparent=function(t){return s.call(this,t,!0)};var q={model:R,view:R,projection:R,inverseModel:R,clipBounds:[[0,0,0],[0,0,0]],height:0,shape:[0,0],pickId:0,lowerBound:[0,0,0],upperBound:[0,0,0],zOffset:0,permutation:[1,0,0,0,1,0,0,0,1],lightPosition:[0,0,0],eyePosition:[0,0,0]};j.drawPick=function(t){t=t||{};var e=this.gl;e.disable(e.CULL_FACE);var r=q;r.model=t.model||R,r.view=t.view||R,r.projection=t.projection||R,r.shape=this._field[2].shape,r.pickId=this.pickId/255,r.lowerBound=this.bounds[0],r.upperBound=this.bounds[1],r.permutation=V;for(var n=0;2>n;++n)for(var i=r.clipBounds[n],a=0;3>a;++a)i[a]=Math.min(Math.max(this.clipBounds[n][a],-1e8),1e8);var s=o(r,this);if(s.showSurface){for(this._pickShader.bind(),this._pickShader.uniforms=r,this._vao.bind(),this._vao.draw(e.TRIANGLES,this._vertexCount),n=0;3>n;++n)this.surfaceProject[n]&&(this._pickShader.uniforms.model=s.projections[n],this._pickShader.uniforms.clipBounds=s.clipBounds[n],this._vao.draw(e.TRIANGLES,this._vertexCount));this._vao.unbind()}if(s.showContour){var l=this._contourPickShader;l.bind(),l.uniforms=r;var c=this._contourVAO;for(c.bind(),a=0;3>a;++a)for(e.lineWidth(this.contourWidth[a]),l.uniforms.permutation=I[a],n=0;nn;++n)for(l.uniforms.model=s.projections[n],l.uniforms.clipBounds=s.clipBounds[n],a=0;3>a;++a)if(this.contourProject[n][a]){l.uniforms.permutation=I[a],e.lineWidth(this.contourWidth[a]);for(var u=0;u>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var c=r.position;c[0]=c[1]=c[2]=0;for(var u=0;2>u;++u)for(var f=u?a:1-a,h=0;2>h;++h)for(var d=h?l:1-l,p=i+u,g=s+h,v=f*d,m=0;3>m;++m)c[m]+=this._field[m].get(p,g)*v;for(var y=this._pickResult.level,b=0;3>b;++b)if(y[b]=M.le(this.contourLevels[b],c[b]),y[b]<0)this.contourLevels[b].length>0&&(y[b]=0);else if(y[b]Math.abs(_-c[b])&&(y[b]+=1)}for(r.index[0]=.5>a?i:i+1,r.index[1]=.5>l?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],m=0;3>m;++m)r.dataCoordinate[m]=this._field[m].get(r.index[0],r.index[1]);return r},j.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=c(t.contourWidth,Number)),"showContour"in t&&(this.showContour=c(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=c(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=f(t.contourColor)),"contourProject"in t&&(this.contourProject=c(t.contourProject,function(t){return c(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=f(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=c(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=c(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(m.freeFloat(this._field[2].data),this._field[2].data=m.mallocFloat(d.nextPow2(n))),this._field[2]=_(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),l(this._field[2],e),this.shape=e.shape.slice();for(var a=this.shape,o=0;2>o;++o)this._field[2].size>this._field[o].data.length&&(m.freeFloat(this._field[o].data),this._field[o].data=m.mallocFloat(this._field[2].size)),this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2]);if(t.coords){var s=t.coords;if(!Array.isArray(s)||3!==s.length)throw new Error("gl-surface: invalid coordinates for x/y");for(o=0;2>o;++o){var u=s[o];for(y=0;2>y;++y)if(u.shape[y]!==a[y])throw new Error("gl-surface: coords have incorrect shape");l(this._field[o],u)}}else if(t.ticks){var h=t.ticks;if(!Array.isArray(h)||2!==h.length)throw new Error("gl-surface: invalid ticks");for(o=0;2>o;++o){var p=h[o];if((Array.isArray(p)||p.length)&&(p=_(p)),p.shape[0]!==a[o])throw new Error("gl-surface: invalid tick length");var g=_(p.data,a);g.stride[o]=p.stride[0],g.stride[1^o]=0,l(this._field[o],g)}}else{for(o=0;2>o;++o){var v=[0,0];v[o]=1,this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2],v,0)}this._field[0].set(0,0,0);for(var y=0;yo;++o)T(x.pick(o),b[o],"mirror");var k=_(m.mallocFloat(3*b[2].size),[a[0]+2,a[1]+2,3]);for(o=0;oI?(I=Math.max(Math.abs(z),Math.abs(P),Math.abs(R)),1e-8>I?(R=1,P=z=0,I=1):I=1/I):I=1/Math.sqrt(I),k.set(o,y,0,z*I),k.set(o,y,1,P*I),k.set(o,y,2,R*I)}m.free(x.data);var N=[1/0,1/0,1/0],j=[-(1/0),-(1/0),-(1/0)],F=1/0,D=-(1/0),B=(a[0]-1)*(a[1]-1)*6,U=m.mallocFloat(d.nextPow2(10*B)),V=0,q=0;for(o=0;oH;++H)for(var G=0;2>G;++G)for(var Y=0;3>Y;++Y){var X=this._field[Y].get(1+o+H,1+y+G);if(isNaN(X)||!isFinite(X))continue t}for(Y=0;6>Y;++Y){var W=o+O[Y][0],Z=y+O[Y][1],K=this._field[0].get(W+1,Z+1),$=this._field[1].get(W+1,Z+1);X=this._field[2].get(W+1,Z+1);var Q=X;z=k.get(W+1,Z+1,0),P=k.get(W+1,Z+1,1),R=k.get(W+1,Z+1,2),t.intensity&&(Q=t.intensity.get(W,Z)),U[V++]=W,U[V++]=Z,U[V++]=K,U[V++]=$,U[V++]=X,U[V++]=0,U[V++]=Q,U[V++]=z,U[V++]=P,U[V++]=R,N[0]=Math.min(N[0],K),N[1]=Math.min(N[1],$),N[2]=Math.min(N[2],X),F=Math.min(F,Q),j[0]=Math.max(j[0],K),j[1]=Math.max(j[1],$),j[2]=Math.max(j[2],X),D=Math.max(D,Q),q+=1}}for(t.intensityBounds&&(F=+t.intensityBounds[0],D=+t.intensityBounds[1]),o=6;V>o;o+=10)U[o]=(U[o]-F)/(D-F);this._vertexCount=q,this._coordinateBuffer.update(U.subarray(0,V)),m.freeFloat(U),m.free(k.data),this.bounds=[N,j],this.intensity=t.intensity||this._field[2],this.intensityBounds[0]===F&&this.intensityBounds[1]===D||(r=!0),this.intensityBounds=[F,D]}if("levels"in t){var J=t.levels;for(J=Array.isArray(J[0])?J.slice():[[],[],J],o=0;3>o;++o)J[o]=J[o].slice(),J.sort(function(t,e){return t-e});t:for(o=0;3>o;++o){if(J[o].length!==this.contourLevels[o].length){r=!0;break}for(y=0;yet;++et){J=this.contourLevels[et];var rt=[],nt=[],it=[0,0,0];for(o=0;oY;++Y){var st=at.positions[ot[Y]],lt=st[0],ct=0|Math.floor(lt),ut=lt-ct,ft=st[1],ht=0|Math.floor(ft),dt=ft-ht,pt=!1; -e:for(var gt=0;3>gt;++gt){it[gt]=0;var vt=(et+gt+1)%3;for(H=0;2>H;++H){var mt=H?ut:1-ut;for(W=0|Math.min(Math.max(ct+H,0),a[0]),G=0;2>G;++G){var yt=G?dt:1-dt;if(Z=0|Math.min(Math.max(ht+G,0),a[1]),X=2>gt?this._field[vt].get(W,Z):(this.intensity.get(W,Z)-this.intensityBounds[0])/(this.intensityBounds[1]-this.intensityBounds[0]),!isFinite(X)||isNaN(X)){pt=!0;break e}var bt=mt*yt;it[gt]+=bt*X}}}if(pt){if(Y>0){for(var xt=0;5>xt;++xt)tt.pop();q-=1}continue t}tt.push(it[0],it[1],st[0],st[1],it[2]),q+=1}}nt.push(q)}this._contourOffsets[et]=rt,this._contourCounts[et]=nt}var _t=m.mallocFloat(tt.length);for(o=0;ot;++t)m.freeFloat(this._field[t].data)},j.highlight=function(t){if(!t)return this._dynamicCounts=[0,0,0],this.dyanamicLevel=[NaN,NaN,NaN],void(this.highlightLevel=[-1,-1,-1]);for(var e=0;3>e;++e)this.enableHighlight[e]?this.highlightLevel[e]=t.level[e]:this.highlightLevel[e]=-1;var r;if(r=this.snapToData?t.dataCoordinate:t.position,this.enableDynamic[0]&&r[0]!==this.dynamicLevel[0]||this.enableDynamic[1]&&r[1]!==this.dynamicLevel[1]||this.enableDynamic[2]&&r[2]!==this.dynamicLevel[2]){for(var n=0,i=this.shape,a=m.mallocFloat(12*i[0]*i[1]),o=0;3>o;++o)if(this.enableDynamic[o]){this.dynamicLevel[o]=r[o];var s=(o+1)%3,l=(o+2)%3,c=this._field[o],u=this._field[s],f=this._field[l],h=(this.intensity,w(c,r[o])),d=h.cells,p=h.positions;for(this._dynamicOffsets[o]=n,e=0;ev;++v){var y=p[g[v]],b=+y[0],x=0|b,_=0|Math.min(x+1,i[0]),k=b-x,A=1-k,M=+y[1],T=0|M,E=0|Math.min(T+1,i[1]),L=M-T,S=1-L,C=A*S,z=A*L,P=k*S,R=k*L,O=C*u.get(x,T)+z*u.get(x,E)+P*u.get(_,T)+R*u.get(_,E),I=C*f.get(x,T)+z*f.get(x,E)+P*f.get(_,T)+R*f.get(_,E);if(isNaN(O)||isNaN(I)){v&&(n-=1);break}a[2*n+0]=O,a[2*n+1]=I,n+=1}this._dynamicCounts[o]=n-this._dynamicOffsets[o]}else this.dynamicLevel[o]=NaN,this._dynamicCounts[o]=0;this._dynamicBuffer.update(a.subarray(0,2*n)),m.freeFloat(a)}}},{"./lib/shaders":216,"binary-search-bounds":217,"bit-twiddle":50,colormap:100,"gl-buffer":118,"gl-mat4/invert":137,"gl-mat4/multiply":139,"gl-texture2d":222,"gl-vao":226,ndarray:253,"ndarray-gradient":218,"ndarray-ops":252,"ndarray-pack":219,"surface-nets":272,"typedarray-pool":278}],222:[function(t,e,r){"use strict";function n(t){v=[t.LINEAR,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_NEAREST],m=[t.NEAREST,t.LINEAR,t.NEAREST_MIPMAP_NEAREST,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_LINEAR],y=[t.REPEAT,t.CLAMP_TO_EDGE,t.MIRRORED_REPEAT]}function i(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(0>e||e>i||0>r||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function a(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}function o(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function s(t,e,r,n,i,a,s,l){var c=l.dtype,u=l.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var f=0,h=0,v=o(u,l.stride.slice());"float32"===c?f=t.FLOAT:"float64"===c?(f=t.FLOAT,v=!1,c="float32"):"uint8"===c?f=t.UNSIGNED_BYTE:(f=t.UNSIGNED_BYTE,v=!1,c="uint8");var m=1;if(2===u.length)h=t.LUMINANCE,u=[u[0],u[1],1],l=d(l.data,u,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])h=t.ALPHA;else if(2===u[2])h=t.LUMINANCE_ALPHA;else if(3===u[2])h=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}m=u[2]}if(h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i),h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=l.size,x=s.indexOf(n)<0;if(x&&s.push(n),f===a&&v)0===l.offset&&l.data.length===y?x?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,l.data):x?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,l.data.subarray(l.offset,l.offset+y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,l.data.subarray(l.offset,l.offset+y));else{var _;_=a===t.FLOAT?g.mallocFloat32(y):g.mallocUint8(y);var w=d(_,u,[u[2],u[2]*u[0],1]);f===t.FLOAT&&a===t.UNSIGNED_BYTE?b(w,l):p.assign(w,l),x?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,_.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,_.subarray(0,y)),a===t.FLOAT?g.freeFloat32(_):g.freeUint8(_)}}function l(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function c(t,e,r,n,i){var o=t.getParameter(t.MAX_TEXTURE_SIZE);if(0>e||e>o||0>r||r>o)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var s=l(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new a(t,s,e,r,n,i)}function u(t,e,r,n){var i=l(t);return t.texImage2D(t.TEXTURE_2D,0,r,r,n,e),new a(t,i,0|e.width,0|e.height,r,n)}function f(t,e){var r=e.dtype,n=e.shape.slice(),i=t.getParameter(t.MAX_TEXTURE_SIZE);if(n[0]<0||n[0]>i||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var s=o(n,e.stride.slice()),c=0;"float32"===r?c=t.FLOAT:"float64"===r?(c=t.FLOAT,s=!1,r="float32"):"uint8"===r?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,s=!1,r="uint8");var u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=d(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}c!==t.FLOAT||t.getExtension("OES_texture_float")||(c=t.UNSIGNED_BYTE,s=!1);var f,h,v=e.size;if(s)f=0===e.offset&&e.data.length===v?e.data:e.data.subarray(e.offset,e.offset+v);else{var m=[n[2],n[2]*n[0],1];h=g.malloc(v,r);var y=d(h,n,m,0);"float32"!==r&&"float64"!==r||c!==t.UNSIGNED_BYTE?p.assign(y,e):b(y,e),f=h.subarray(0,v)}var x=l(t);return t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,c,f),s||g.free(h),new a(t,x,n[0],n[1],u,c)}function h(t){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(v||n(t),"number"==typeof arguments[1])return c(t,arguments[1],arguments[2],arguments[3]||t.RGBA,arguments[4]||t.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return c(t,0|arguments[1][0],0|arguments[1][1],arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if("object"==typeof arguments[1]){var e=arguments[1];if(e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e instanceof ImageData)return u(t,e,arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return f(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}var d=t("ndarray"),p=t("ndarray-ops"),g=t("typedarray-pool");e.exports=h;var v=null,m=null,y=null,b=function(t,e){p.muls(t,e,255)},x=a.prototype;Object.defineProperties(x,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;2>e;++e)if(y.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return i(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return t=0|t,i(this,t,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t=0|t,i(this,this._shape[0],t),t}}}),x.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},x.dispose=function(){this.gl.deleteTexture(this.handle)},x.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},x.setPixels=function(t,e,r,n){var i=this.gl;if(this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0,t instanceof HTMLCanvasElement||t instanceof ImageData||t instanceof HTMLImageElement||t instanceof HTMLVideoElement){var a=this._mipLevels.indexOf(n)<0;a?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,t),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,t)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||0>e||0>r)throw new Error("gl-texture2d: Texture dimensions are out of bounds");s(i,e,r,n,this.format,this.type,this._mipLevels,t)}}},{ndarray:253,"ndarray-ops":252,"typedarray-pool":278}],223:[function(t,e,r){"use strict";function n(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;ii;++i)t.disableVertexAttribArray(i)}else{t.bindBuffer(t.ARRAY_BUFFER,null);for(var i=0;n>i;++i)t.disableVertexAttribArray(i)}}e.exports=n},{}],224:[function(t,e,r){"use strict";function n(t){this.gl=t,this._elements=null,this._attributes=null,this._elementsType=t.UNSIGNED_SHORT}function i(t){return new n(t)}var a=t("./do-bind.js");n.prototype.bind=function(){a(this.gl,this._elements,this._attributes)},n.prototype.update=function(t,e,r){this._elements=e,this._attributes=t,this._elementsType=r||this.gl.UNSIGNED_SHORT},n.prototype.dispose=function(){},n.prototype.unbind=function(){},n.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._elements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=i},{"./do-bind.js":223}],225:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.location=t,this.dimension=e,this.a=r,this.b=n,this.c=i,this.d=a}function i(t,e,r){this.gl=t,this._ext=e,this.handle=r,this._attribs=[],this._useElements=!1,this._elementsType=t.UNSIGNED_SHORT}function a(t,e){return new i(t,e,e.createVertexArrayOES())}var o=t("./do-bind.js");n.prototype.bind=function(t){switch(this.dimension){case 1:t.vertexAttrib1f(this.location,this.a);break;case 2:t.vertexAttrib2f(this.location,this.a,this.b);break;case 3:t.vertexAttrib3f(this.location,this.a,this.b,this.c);break;case 4:t.vertexAttrib4f(this.location,this.a,this.b,this.c,this.d)}},i.prototype.bind=function(){this._ext.bindVertexArrayOES(this.handle);for(var t=0;tF;){switch(e=F,B){case f:F=L();break;case h:F=E();break;case d:F=T();break;case p:F=S();break;case g:F=P();break;case w:F=z();break;case v:F=R();break;case u:F=O();break;case x:F=M();break;case c:F=A()}if(e!==F)switch(W[e]){case"\n":H=0,++q;break;default:++H}}return D+=F,W=W.slice(F),V}function n(t){return U.length&&e(U.join("")),B=_,e("(eof)"),V}function A(){return U=U.length?[]:U,"/"===N&&"*"===I?(G=D+F-1,B=f,N=I,F+1):"/"===N&&"/"===I?(G=D+F-1,B=h,N=I,F+1):"#"===I?(B=d,G=D+F,F):/\s/.test(I)?(B=x,G=D+F,F):(Y=/\d/.test(I),X=/[^\w_]/.test(I),G=D+F,B=Y?g:X?p:u,F)}function M(){return/[^\s]/g.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function T(){return"\n"===I&&"\\"!==N?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function E(){return T()}function L(){return"/"===I&&"*"===N?(U.push(I),e(U.join("")),B=c,F+1):(U.push(I),N=I,F+1)}function S(){if("."===N&&/\d/.test(I))return B=v,F;if("/"===N&&"*"===I)return B=f,F;if("/"===N&&"/"===I)return B=h,F;if("."===I&&U.length){for(;C(U););return B=v,F}if(";"===I||")"===I||"("===I){if(U.length)for(;C(U););return e(I),B=c,F+1}var t=2===U.length&&"="!==I;if(/[\w_\d\s]/.test(I)||t){for(;C(U););return B=c,F}return U.push(I),N=I,F+1}function C(t){for(var r,n,i=0;;){if(r=a.indexOf(t.slice(0,t.length+i).join("")),n=a[r],-1===r){if(i--+t.length>0)continue;n=t.slice(0,1).join("")}return e(n),G+=n.length,U=U.slice(n.length),U.length}}function z(){return/[^a-fA-F0-9]/.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function P(){return"."===I?(U.push(I),B=v,N=I,F+1):/[eE]/.test(I)?(U.push(I),B=v,N=I,F+1):"x"===I&&1===U.length&&"0"===U[0]?(B=w,U.push(I),N=I,F+1):/[^\d]/.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function R(){return"f"===I&&(U.push(I),N=I,F+=1),/[eE]/.test(I)?(U.push(I),N=I,F+1):"-"===I&&/[eE]/.test(N)?(U.push(I),N=I,F+1):/[^\d]/.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function O(){if(/[^\d\w_]/.test(I)){var t=U.join("");return B=K.indexOf(t)>-1?b:Z.indexOf(t)>-1?y:m,e(U.join("")),B=c,F}return U.push(I),N=I,F+1}var I,N,j,F=0,D=0,B=c,U=[],V=[],q=1,H=0,G=0,Y=!1,X=!1,W="";t=t||{};var Z=o,K=i;return"300 es"===t.version&&(Z=l,K=s),function(t){return V=[],null!==t?r(t):n()}}e.exports=n;var i=t("./lib/literals"),a=t("./lib/operators"),o=t("./lib/builtins"),s=t("./lib/literals-300es"),l=t("./lib/builtins-300es"),c=999,u=9999,f=0,h=1,d=2,p=3,g=4,v=5,m=6,y=7,b=8,x=9,_=10,w=11,k=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":230,"./lib/builtins-300es":229,"./lib/literals":232,"./lib/literals-300es":231,"./lib/operators":233}],229:[function(t,e,r){var n=t("./builtins");n=n.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)}),e.exports=n.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"])},{"./builtins":230}],230:[function(t,e,r){e.exports=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]},{}],231:[function(t,e,r){var n=t("./literals");e.exports=n.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"])},{"./literals":232}],232:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],233:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],234:[function(t,e,r){function n(t,e){var r=i(e),n=[];return n=n.concat(r(t)),n=n.concat(r(null))}var i=t("./index");e.exports=n},{"./index":228}],235:[function(t,e,r){"use strict";function n(t,e,r){this.vertices=t,this.adjacent=e,this.boundary=r,this.lastVisited=-1}function i(t,e,r){this.vertices=t,this.cell=e,this.index=r}function a(t,e){return u(t.vertices,e.vertices)}function o(t){for(var e=["function orient(){var tuple=this.tuple;return test("],r=0;t>=r;++r)r>0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=c[t+1];return i||(i=c),n(i)}function s(t,e,r){this.dimension=t,this.vertices=e,this.simplices=r,this.interior=r.filter(function(t){return!t.boundary}),this.tuple=new Array(t+1);for(var n=0;t>=n;++n)this.tuple[n]=this.vertices[n];var i=f[t];i||(i=f[t]=o(t)),this.orient=i}function l(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(i>=r)throw new Error("Must input at least d+1 points");var a=t.slice(0,i+1),o=c.apply(void 0,a);if(0===o)throw new Error("Input not in general position");for(var l=new Array(i+1),u=0;i>=u;++u)l[u]=u;0>o&&(l[0]=1,l[1]=0);for(var f=new n(l,new Array(i+1),!1),h=f.adjacent,d=new Array(i+2),u=0;i>=u;++u){for(var p=l.slice(),g=0;i>=g;++g)g===u&&(p[g]=-1);var v=p[0];p[0]=p[1],p[1]=v;var m=new n(p,new Array(i+1),!0);h[u]=m,d[u]=m}d[i+1]=f;for(var u=0;i>=u;++u)for(var p=h[u].vertices,y=h[u].adjacent,g=0;i>=g;++g){var b=p[g];if(0>b)y[g]=f;else for(var x=0;i>=x;++x)h[x].vertices.indexOf(b)<0&&(y[g]=h[x])}for(var _=new s(i,a,d),w=!!e,u=i+1;r>u;++u)_.insert(t[u],w);return _.boundary()}e.exports=l;var c=t("robust-orientation"),u=t("simplicial-complex").compareCells;n.prototype.flip=function(){var t=this.vertices[0];this.vertices[0]=this.vertices[1],this.vertices[1]=t;var e=this.adjacent[0];this.adjacent[0]=this.adjacent[1],this.adjacent[1]=e};var f=[],h=s.prototype;h.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){t=o.pop();for(var s=(t.vertices,t.adjacent),l=0;r>=l;++l){var c=s[l];if(c.boundary&&!(c.lastVisited<=-n)){for(var u=c.vertices,f=0;r>=f;++f){var h=u[f];0>h?i[f]=e:i[f]=a[h]}var d=this.orient();if(d>0)return c;c.lastVisited=-n,0===d&&o.push(c)}}}return null},h.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,c=s.adjacent,u=0;n>=u;++u)a[u]=i[l[u]];s.lastVisited=r;for(var u=0;n>=u;++u){var f=c[u];if(!(f.lastVisited>=r)){var h=a[u];a[u]=t;var d=this.orient();if(a[u]=h,0>d){s=f;continue t}f.boundary?f.lastVisited=-r:f.lastVisited=r}}return}return s},h.addPeaks=function(t,e){var r=this.vertices.length-1,o=this.dimension,s=this.vertices,l=this.tuple,c=this.interior,u=this.simplices,f=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,c.push(e);for(var h=[];f.length>0;){var e=f.pop(),d=e.vertices,p=e.adjacent,g=d.indexOf(r);if(!(0>g))for(var v=0;o>=v;++v)if(v!==g){var m=p[v];if(m.boundary&&!(m.lastVisited>=r)){var y=m.vertices;if(m.lastVisited!==-r){for(var b=0,x=0;o>=x;++x)y[x]<0?(b=x,l[x]=t):l[x]=s[y[x]];var _=this.orient();if(_>0){y[b]=r,m.boundary=!1,c.push(m),f.push(m),m.lastVisited=r;continue}m.lastVisited=-r}var w=m.adjacent,k=d.slice(),A=p.slice(),M=new n(k,A,!0);u.push(M);var T=w.indexOf(e);if(!(0>T)){w[T]=M,A[g]=m,k[v]=-1,A[v]=e,p[v]=M,M.flip();for(var x=0;o>=x;++x){var E=k[x];if(!(0>E||E===r)){for(var L=new Array(o-1),S=0,C=0;o>=C;++C){var z=k[C];0>z||C===x||(L[S++]=z)}h.push(new i(L,M,x))}}}}}}h.sort(a);for(var v=0;v+1O||0>I||(P.cell.adjacent[P.index]=R.cell,R.cell.adjacent[R.index]=P.cell)}},h.insert=function(t,e){var r=this.vertices;r.push(t);var n=this.walk(t,e);if(n){for(var i=this.dimension,a=this.tuple,o=0;i>=o;++o){var s=n.vertices[o];0>s?a[o]=t:a[o]=r[s]}var l=this.orient(a);0>l||(0!==l||(n=this.handleBoundaryDegeneracy(n,t)))&&this.addPeaks(t,n)}},h.boundary=function(){for(var t=this.dimension,e=[],r=this.simplices,n=r.length,i=0;n>i;++i){var a=r[i];if(a.boundary){for(var o=new Array(t),s=a.vertices,l=0,c=0,u=0;t>=u;++u)s[u]>=0?o[l++]=s[u]:c=1&u;if(c===(1&t)){var f=o[0];o[0]=o[1],o[1]=f}e.push(o)}}return e}},{"robust-orientation":259,"simplicial-complex":238}],236:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],237:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{dup:97}],238:[function(t,e,r){"use strict";"use restrict";function n(t){for(var e=0,r=Math.max,n=0,i=t.length;i>n;++n)e=r(e,t[n].length);return e-1}function i(t){for(var e=-1,r=Math.max,n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)e=r(e,a[o]);return e+1}function a(t){for(var e=new Array(t.length),r=0,n=t.length;n>r;++r)e[r]=t[r].slice(0);return e}function o(t,e){var r=t.length,n=t.length-e.length,i=Math.min;if(n)return n;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:var a=t[0]+t[1]-e[0]-e[1];return a?a:i(t[0],t[1])-i(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=i(t[0],t[1]),c=i(e[0],e[1]),a=i(l,t[2])-i(c,e[2]);return a?a:i(l+t[2],o)-i(c+e[2],s);default:var u=t.slice(0);u.sort();var f=e.slice(0);f.sort();for(var h=0;r>h;++h)if(n=u[h]-f[h])return n;return 0}}function s(t,e){return o(t[0],e[0])}function l(t,e){if(e){for(var r=t.length,n=new Array(r),i=0;r>i;++i)n[i]=[t[i],e[i]];n.sort(s);for(var i=0;r>i;++i)t[i]=n[i][0],e[i]=n[i][1];return t}return t.sort(o),t}function c(t){if(0===t.length)return[];for(var e=1,r=t.length,n=1;r>n;++n){var i=t[n];if(o(i,t[n-1])){if(n===e){e++;continue}t[e++]=i}}return t.length=e,t}function u(t,e){for(var r=0,n=t.length-1,i=-1;n>=r;){var a=r+n>>1,s=o(t[a],e);0>=s?(0===s&&(i=a),r=a+1):s>0&&(n=a-1)}return i}function f(t,e){for(var r=new Array(t.length),n=0,i=r.length;i>n;++n)r[n]=[];for(var a=[],n=0,s=e.length;s>n;++n)for(var l=e[n],c=l.length,f=1,h=1<f;++f){a.length=b.popCount(f);for(var d=0,p=0;c>p;++p)f&1<g))for(;;)if(r[g++].push(n),g>=t.length||0!==o(t[g],a))break}return r}function h(t,e){if(!e)return f(c(p(t,0)),t,0);for(var r=new Array(e),n=0;e>n;++n)r[n]=[];for(var n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)r[a[o]].push(n);return r}function d(t){for(var e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0|i.length,o=1,s=1<o;++o){for(var c=[],u=0;a>u;++u)o>>>u&1&&c.push(i[u]);e.push(c)}return l(e)}function p(t,e){if(0>e)return[];for(var r=[],n=(1<r;++r)for(var i=t[r],a=0,o=i.length;o>a;++a){for(var s=new Array(i.length-1),c=0,u=0;o>c;++c)c!==a&&(s[u++]=i[c]);e.push(s)}return l(e)}function v(t,e){for(var r=new x(e),n=0;nr;++r)e[r]=r;return e}e.exports=n},{}],240:[function(t,e,r){e.exports=function(t){return!(null==t||!(t._isBuffer||t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)))}},{}],241:[function(t,e,r){"use strict";function n(t,e){function r(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==g.alt,g.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==g.shift,g.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==g.control,g.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==g.meta,g.meta=!!t.metaKey),e}function n(t,n){var a=i.x(n),o=i.y(n);"buttons"in n&&(t=0|n.buttons),(t!==h||a!==d||o!==p||r(n))&&(h=0|t,d=a||0,p=o||0,e(h,d,p,g))}function a(t){n(0,t)}function o(){(h||d||p||g.shift||g.alt||g.meta||g.control)&&(d=p=0,h=0,g.shift=g.alt=g.control=g.meta=!1,e(0,0,0,g))}function s(t){r(t)&&e(h,d,p,g)}function l(t){0===i.buttons(t)?n(0,t):n(h,t)}function c(t){n(h|i.buttons(t),t)}function u(t){n(h&~i.buttons(t),t)}function f(){v||(v=!0,t.addEventListener("mousemove",l),t.addEventListener("mousedown",c),t.addEventListener("mouseup",u),t.addEventListener("mouseleave",a),t.addEventListener("mouseenter",a),t.addEventListener("mouseout",a),t.addEventListener("mouseover",a),t.addEventListener("blur",o),t.addEventListener("keyup",s),t.addEventListener("keydown",s),t.addEventListener("keypress",s),t!==window&&(window.addEventListener("blur",o),window.addEventListener("keyup",s),window.addEventListener("keydown",s),window.addEventListener("keypress",s)))}e||(e=t,t=window);var h=0,d=0,p=0,g={shift:!1,alt:!1,control:!1,meta:!1},v=!1;f();var m={element:t};return Object.defineProperties(m,{enabled:{get:function(){return v},set:function(t){t&&f()},enumerable:!0},buttons:{get:function(){return h},enumerable:!0},x:{get:function(){return d},enumerable:!0},y:{get:function(){return p},enumerable:!0},mods:{get:function(){return g},enumerable:!0}}),m}e.exports=n;var i=t("mouse-event")},{"mouse-event":242}],242:[function(t,e,r){"use strict";function n(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){var e=t.which;if(2===e)return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1<=0&&r=0&&r+1=0&&n=0&&n+1=0&&s=0&&s+1=0&&i=0&&i+1=0&&l=0&&l+1=0&&h=0&&h+1e;++e)r=+arguments[e+1],i[e]=Math.floor(r),a[e]=r-i[e],o[e]=0<=i[e]&&i[e]e;++e){for(c=1,u=t.offset,l=0;n>l;++l)if(e&1<r;++r){t[r]=o[(n+1)*n+r];for(var i=0;n>i;++i)t[r]+=o[(n+1)*i+r]*e[i]}for(var a=o[(n+1)*(n+1)-1],i=0;n>i;++i)a+=o[(n+1)*i+n]*e[i];for(var s=1/a,r=0;n>r;++r)t[r]*=s;return t}),t}var i=t("ndarray-warp"),a=t("gl-matrix-invert");e.exports=n},{"gl-matrix-invert":247,"ndarray-warp":250}],252:[function(t,e,r){"use strict";function n(t){if(!t)return s;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in l){var e=l[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var c={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in c){var e=c[t];r[t]=a({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=a({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var u={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in u){var e=u[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var f=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=o({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=o({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=a({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=a({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=a({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=o({args:["array","array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":109}],253:[function(t,e,r){function n(t,e){return t[0]-e[0]}function i(){var t,e=this.stride,r=new Array(e.length);for(t=0;te&&(r="View_Nil"+t);var n="generic"===t;if(-1===e){var a="function "+r+"(a){this.data=a;};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+r+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+r+"(a){return new "+r+"(a);}",o=new Function(a);return o()}if(0===e){var a="function "+r+"(a,d) {this.data = a;this.offset = d};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+r+"_copy() {return new "+r+"(this.data,this.offset)};proto.pick=function "+r+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+r+"_get(){return "+(n?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+r+"_set(v){return "+(n?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+r+"(a,b,c,d){return new "+r+"(a,d)}",o=new Function("TrivialArray",a);return o(f[t][0])}var a=["'use strict'"],s=l(e),c=s.map(function(t){return"i"+t}),u="this.offset+"+s.map(function(t){return"this.stride["+t+"]*i"+t}).join("+"),h=s.map(function(t){return"b"+t}).join(","),d=s.map(function(t){return"c"+t}).join(",");a.push("function "+r+"(a,"+h+","+d+",d){this.data=a","this.shape=["+h+"]","this.stride=["+d+"]","this.offset=d|0}","var proto="+r+".prototype","proto.dtype='"+t+"'","proto.dimension="+e),a.push("Object.defineProperty(proto,'size',{get:function "+r+"_size(){return "+s.map(function(t){return"this.shape["+t+"]"}).join("*"),"}})"),1===e?a.push("proto.order=[0]"):(a.push("Object.defineProperty(proto,'order',{get:"),4>e?(a.push("function "+r+"_order(){"),2===e?a.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+c.join(",")+",v){"),n?a.push("return this.data.set("+u+",v)}"):a.push("return this.data["+u+"]=v}"),a.push("proto.get=function "+r+"_get("+c.join(",")+"){"),n?a.push("return this.data.get("+u+")}"):a.push("return this.data["+u+"]}"),a.push("proto.index=function "+r+"_index(",c.join(),"){return "+u+"}"),a.push("proto.hi=function "+r+"_hi("+c.join(",")+"){return new "+r+"(this.data,"+s.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+s.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var p=s.map(function(t){return"a"+t+"=this.shape["+t+"]"}),g=s.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+c.join(",")+"){var b=this.offset,d=0,"+p.join(",")+","+g.join(","));for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){d=i"+v+"|0;b+=c"+v+"*d;a"+v+"-=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+c.join(",")+"){var "+s.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+s.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'){d=i"+v+"|0;if(d<0){c+=b"+v+"*(a"+v+"-1);a"+v+"=ceil(-a"+v+"/d)}else{a"+v+"=ceil(a"+v+"/d)}b"+v+"*=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"b"+t}).join(",")+",c)}");for(var m=new Array(e),y=new Array(e),v=0;e>v;++v)m[v]="a[i"+v+"]",y[v]="b[i"+v+"]";a.push("proto.transpose=function "+r+"_transpose("+c+"){"+c.map(function(t,e){return t+"=("+t+"===undefined?"+e+":"+t+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+r+"(this.data,"+m.join(",")+","+y.join(",")+",this.offset)}"),a.push("proto.pick=function "+r+"_pick("+c+"){var a=[],b=[],c=this.offset");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){c=(c+this.stride["+v+"]*i"+v+")|0}else{a.push(this.shape["+v+"]);b.push(this.stride["+v+"])}");a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+s.map(function(t){return"shape["+t+"]"}).join(",")+","+s.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}");var o=new Function("CTOR_LIST","ORDER",a.join("\n"));return o(f[t],i)}function o(t){if(c(t))return"buffer";if(u)switch(Object.prototype.toString.call(t)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(t)?"array":"generic"}function s(t,e,r,n){if(void 0===t){var i=f.array[0];return i([])}"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var s=e.length;if(void 0===r){r=new Array(s);for(var l=s-1,c=1;l>=0;--l)r[l]=c,c*=e[l]}if(void 0===n){n=0;for(var l=0;s>l;++l)r[l]<0&&(n-=(e[l]-1)*r[l])}for(var u=o(t),h=f[u];h.length<=s+1;)h.push(a(u,h.length-1));var i=h[s+1];return i(t,e,r,n)}var l=t("iota-array"),c=t("is-buffer"),u="undefined"!=typeof Float64Array,f={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=s},{"iota-array":239,"is-buffer":240}],254:[function(t,e,r){"use strict";function n(t,e){if("string"!=typeof t)throw new TypeError("repeat-string expects a string.");if(1===e)return t;if(2===e)return t+t;var r=t.length*e;for(i===t&&"undefined"!=typeof i||(i=t,a="");r>a.length&&e>0&&(1&e&&(a+=t),e>>=1);)t+=t;return a.substr(0,r)}var i,a="";e.exports=n},{}],255:[function(t,e,r){(function(t){e.exports=t.performance&&t.performance.now?function(){return performance.now()}:Date.now||function(){return+new Date}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],256:[function(t,e,r){"use strict";function n(t){for(var e="robustLinearSolve"+t+"d",r=["function ",e,"(A,b){return ["],n=0;t>n;++n){r.push("det([");for(var i=0;t>i;++i){i>0&&r.push(","),r.push("[");for(var a=0;t>a;++a)a>0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(6>t?s[t]:s)}function i(){return[0]}function a(t,e){return[[e[0]],[t[0][0]]]}function o(){for(;c.lengthi;++i)t.push("s"+i),r.push("case ",i,":return s",i,"(A,b);");r.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve"),t.push("CACHE","g",r.join(""));var a=Function.apply(void 0,t);e.exports=a.apply(void 0,c.concat([c,n]));for(var i=0;l>i;++i)e.exports[i]=c[i]}var s=t("robust-determinant"),l=6,c=[i,a];o()},{"robust-determinant":258}],257:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=t[t.length-1],n=e,i=e-2;i>=0;--i){var a=r,o=t[i];r=a+o;var s=r-a,l=o-s;l&&(t[--n]=r,r=l)}for(var c=0,i=n;e>i;++i){var a=t[i],o=r;r=a+o;var s=r-a,l=o-s;l&&(t[c++]=l)}return t[c++]=r,t.length=c,t}e.exports=n},{}],258:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m[",r,"][",n,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("");for(var e=[],r=0;rn;++n)t.push("det"+n),r.push("case ",n,":return det",n,"(m);");r.push("}var det=CACHE[m.length];if(!det)det=CACHE[m.length]=gen(m.length);return det(m);}return robustDeterminant"),t.push("CACHE","gen",r.join(""));var i=Function.apply(void 0,t);e.exports=i.apply(void 0,g.concat([g,l]));for(var n=0;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-1,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;rc;++c)0===(1&c)?e.push.apply(e,s(n(a,c))):r.push.apply(r,s(n(a,c))),l.push("m"+c);var u=o(e),g=o(r),v="orientation"+t+"Exact",m=["function ",v,"(",l.join(),"){var p=",u,",n=",g,",d=sub(p,n);return d[d.length-1];};return ",v].join(""),y=new Function("sum","prod","scale","sub",m);return y(h,f,d,p)}function c(t){var e=_[t.length];return e||(e=_[t.length]=l(t.length)),e.apply(void 0,t)}function u(){for(;_.length<=g;)_.push(l(_.length));for(var t=[],r=["slow"],n=0;g>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;g>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var f=t("two-product"),h=t("robust-sum"),d=t("robust-scale"),p=t("robust-subtract"),g=5,v=1.1102230246251565e-16,m=(3+16*v)*v,y=(7+56*v)*v,b=l(3),x=l(4),_=[function(){return 0},function(){return 0},function(t,e){return e[0]-t[0]},function(t,e,r){var n,i=(t[1]-r[1])*(e[0]-r[0]),a=(t[0]-r[0])*(e[1]-r[1]),o=i-a;if(i>0){if(0>=a)return o;n=i+a}else{if(!(0>i))return o;if(a>=0)return o;n=-(i+a)}var s=m*n;return o>=s||-s>=o?o:b(t,e,r)},function(t,e,r,n){ -var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],c=r[1]-n[1],u=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],d=a*c,p=o*l,g=o*s,v=i*c,m=i*l,b=a*s,_=u*(d-p)+f*(g-v)+h*(m-b),w=(Math.abs(d)+Math.abs(p))*Math.abs(u)+(Math.abs(g)+Math.abs(v))*Math.abs(f)+(Math.abs(m)+Math.abs(b))*Math.abs(h),k=y*w;return _>k||-_>k?_:x(t,e,r,n)}];u()},{"robust-scale":260,"robust-subtract":261,"robust-sum":262,"two-product":276}],260:[function(t,e,r){"use strict";function n(t,e){var r=t.length;if(1===r){var n=i(t[0],e);return n[0]?n:[n[1]]}var o=new Array(2*r),s=[.1,.1],l=[.1,.1],c=0;i(t[0],e,s),s[0]&&(o[c++]=s[0]);for(var u=1;r>u;++u){i(t[u],e,l);var f=s[1];a(f,l[0],s),s[0]&&(o[c++]=s[0]);var h=l[1],d=s[1],p=h+d,g=p-h,v=d-g;s[1]=p,v&&(o[c++]=v)}return s[1]&&(o[c++]=s[1]),0===c&&(o[c++]=0),o.length=c,o}var i=t("two-product"),a=t("two-sum");e.exports=n},{"two-product":276,"two-sum":277}],261:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],-e[0]);var a,o,s=r+i,l=new Array(s),c=0,u=0,f=0,h=Math.abs,d=t[u],p=h(d),g=-e[f],v=h(g);v>p?(o=d,u+=1,r>u&&(d=t[u],p=h(d))):(o=g,f+=1,i>f&&(g=-e[f],v=h(g))),r>u&&v>p||f>=i?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>u&&i>f;)v>p?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>u;)a=d,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,u+=1,r>u&&(d=t[u]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=-e[f]);return M&&(l[c++]=M),T&&(l[c++]=T),c||(l[c++]=0),l.length=c,l}e.exports=i},{}],262:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],e[0]);var a,o,s=r+i,l=new Array(s),c=0,u=0,f=0,h=Math.abs,d=t[u],p=h(d),g=e[f],v=h(g);v>p?(o=d,u+=1,r>u&&(d=t[u],p=h(d))):(o=g,f+=1,i>f&&(g=e[f],v=h(g))),r>u&&v>p||f>=i?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>u&&i>f;)v>p?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>u;)a=d,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,u+=1,r>u&&(d=t[u]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=e[f]);return M&&(l[c++]=M),T&&(l[c++]=T),c||(l[c++]=0),l.length=c,l}e.exports=i},{}],263:[function(t,e,r){"use strict";function n(t){return t.split("").map(function(t){return t in i?i[t]:""}).join("")}e.exports=n;var i={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"}},{}],264:[function(t,e,r){"use strict";function n(t){return"a"+t}function i(t){return"d"+t}function a(t,e){return"c"+t+"_"+e}function o(t){return"s"+t}function s(t,e){return"t"+t+"_"+e}function l(t){return"o"+t}function c(t){return"x"+t}function u(t){return"p"+t}function f(t,e){return"d"+t+"_"+e}function h(t){return"i"+t}function d(t,e){return"u"+t+"_"+e}function p(t){return"b"+t}function g(t){return"y"+t}function v(t){return"e"+t}function m(t){return"v"+t}function y(t,e,r){for(var n=0,i=0;t>i;++i)e&1<e;++e)F.push(u(e),"+=",d(e,x[t]),";");F.push("}")}function z(t){for(var e=t-1;e>=0;--e)S(e,0);for(var r=[],e=0;I>e;++e)L[e]?r.push(i(e)+".get("+u(e)+")"):r.push(i(e)+"["+u(e)+"]");for(var e=0;b>e;++e)r.push(c(e));F.push(k,"[",T,"++]=phase(",r.join(),");");for(var e=0;t>e;++e)C(e);for(var n=0;I>n;++n)F.push(u(n),"+=",d(n,x[t]),";")}function P(t){for(var e=0;I>e;++e)L[e]?F.push(a(e,0),"=",i(e),".get(",u(e),");"):F.push(a(e,0),"=",i(e),"[",u(e),"];");for(var r=[],e=0;I>e;++e)r.push(a(e,0));for(var e=0;b>e;++e)r.push(c(e));F.push(p(0),"=",k,"[",T,"]=phase(",r.join(),");");for(var n=1;1<n;++n)F.push(p(n),"=",k,"[",T,"+",v(n),"];");for(var o=[],n=1;1<n;++n)o.push("("+p(0)+"!=="+p(n)+")");F.push("if(",o.join("||"),"){");for(var s=[],e=0;N>e;++e)s.push(h(e));for(var e=0;I>e;++e){s.push(a(e,0));for(var n=1;1<n;++n)L[e]?F.push(a(e,n),"=",i(e),".get(",u(e),"+",f(e,n),");"):F.push(a(e,n),"=",i(e),"[",u(e),"+",f(e,n),"];"),s.push(a(e,n))}for(var e=0;1<e;++e)s.push(p(e));for(var e=0;b>e;++e)s.push(c(e));F.push("vertex(",s.join(),");",m(0),"=",w,"[",T,"]=",A,"++;");for(var l=(1<n;++n)if(0===(t&~(1<0;_=_-1&g)x.push(w+"["+T+"+"+v(_)+"]");x.push(m(0));for(var _=0;I>_;++_)1&n?x.push(a(_,l),a(_,g)):x.push(a(_,g),a(_,l));1&n?x.push(d,y):x.push(y,d);for(var _=0;b>_;++_)x.push(c(_));F.push("if(",d,"!==",y,"){","face(",x.join(),")}")}F.push("}",T,"+=1;")}function R(){for(var t=1;1<t;++t)F.push(E,"=",v(t),";",v(t),"=",g(t),";",g(t),"=",E,";")}function O(t,e){if(0>t)return void P(e);z(t),F.push("if(",o(x[t]),">0){",h(x[t]),"=1;"),O(t-1,e|1<r;++r)F.push(u(r),"+=",d(r,x[t]),";");t===N-1&&(F.push(T,"=0;"),R()),S(t,2),O(t-1,e),t===N-1&&(F.push("if(",h(x[N-1]),"&1){",T,"=0;}"),R()),C(t),F.push("}")}var I=L.length,N=x.length;if(2>N)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var j="extractContour"+x.join("_"),F=[],D=[],B=[],U=0;I>U;++U)B.push(n(U));for(var U=0;b>U;++U)B.push(c(U));for(var U=0;N>U;++U)D.push(o(U)+"="+n(0)+".shape["+U+"]|0");for(var U=0;I>U;++U){D.push(i(U)+"="+n(U)+".data",l(U)+"="+n(U)+".offset|0");for(var V=0;N>V;++V)D.push(s(U,V)+"="+n(U)+".stride["+V+"]|0")}for(var U=0;I>U;++U){D.push(u(U)+"="+l(U)),D.push(a(U,0));for(var V=1;1<V;++V){for(var q=[],H=0;N>H;++H)V&1<U;++U)for(var V=0;N>V;++V){var G=[s(U,x[V])];V>0&&G.push(s(U,x[V-1])+"*"+o(x[V-1])),D.push(d(U,x[V])+"=("+G.join("-")+")|0")}for(var U=0;N>U;++U)D.push(h(U)+"=0");D.push(A+"=0");for(var Y=["2"],U=N-2;U>=0;--U)Y.push(o(x[U]));D.push(M+"=("+Y.join("*")+")|0",k+"=mallocUint32("+M+")",w+"=mallocUint32("+M+")",T+"=0"),D.push(p(0)+"=0");for(var V=1;1<V;++V){for(var X=[],W=[],H=0;N>H;++H)V&1<n&&e("Must have at least one array argument");var i=t.scalarArguments||0;0>i&&e("Scalar arg count must be > 0"),"function"!=typeof t.vertex&&e("Must specify vertex creation function"),"function"!=typeof t.cell&&e("Must specify cell creation function"),"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;n>s;++s)a.indexOf(s)>=0?o[s]=!0:o[s]=!1;return b(t.vertex,t.cell,t.phase,i,r,o)}var _=t("typedarray-pool");e.exports=x;var w="V",k="P",A="N",M="Q",T="X",E="T"},{"typedarray-pool":278}],265:[function(t,e,r){function n(t){if(0>t)return Number("0/0");for(var e=s[0],r=s.length-1;r>0;--r)e+=s[r]/(t+r);var n=t+o+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}var i=7,a=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],o=607/128,s=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];e.exports=function l(t){if(.5>t)return Math.PI/(Math.sin(Math.PI*t)*l(1-t));if(t>100)return Math.exp(n(t));t-=1;for(var e=a[0],r=1;i+2>r;r++)e+=a[r]/(t+r);var o=t+i+.5;return Math.sqrt(2*Math.PI)*Math.pow(o,t+.5)*Math.exp(-o)*e},e.exports.log=n},{}],266:[function(t,e,r){"use strict";function n(t){var e=t.length;if(i>e){for(var r=1,n=0;e>n;++n)for(var o=0;n>o;++o)if(t[n]n;++n)s[n]=0;for(var r=1,n=0;e>n;++n)if(!s[n]){var l=1;s[n]=1;for(var o=t[n];o!==n;o=t[o]){if(s[o])return a.freeUint8(s),0;l+=1,s[o]=1}1&l||(r=-r)}return a.freeUint8(s),r}e.exports=n;var i=32,a=t("typedarray-pool")},{"typedarray-pool":278}],267:[function(t,e,r){"use strict";function n(t){var e=t.length;switch(e){case 0:case 1:return 0;case 2:return t[1]}var r,n,i,s=a.mallocUint32(e),l=a.mallocUint32(e),c=0;for(o(t,l),i=0;e>i;++i)s[i]=t[i];for(i=e-1;i>0;--i)n=l[i],r=s[i],s[i]=s[n],s[n]=r,l[i]=l[r],l[r]=n,c=(c+r)*i;return a.freeUint32(l),a.freeUint32(s),c}function i(t,e,r){switch(t){case 0:return r?r:[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}r=r||new Array(t);var n,i,a,o=1;for(r[0]=0,a=1;t>a;++a)r[a]=a,o=o*a|0;for(a=t-1;a>0;--a)n=e/o|0,e=e-n*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}var a=t("typedarray-pool"),o=t("invert-permutation");r.rank=n,r.unrank=i},{"invert-permutation":268,"typedarray-pool":278}],268:[function(t,e,r){"use strict";function n(t,e){e=e||new Array(t.length);for(var r=0;rt)return[];if(0===t)return[[0]];for(var e=0|Math.round(o(t+1)),r=[],n=0;e>n;++n){for(var s=i.unrank(t,n),l=[0],c=0,u=0;u= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":109}],271:[function(t,e,r){"use strict";function n(t,e){var r=[];return e=+e||0,i(t.hi(t.shape[0]-1),r,e),r}e.exports=n;var i=t("./lib/zc-core")},{"./lib/zc-core":270}],272:[function(t,e,r){"use strict";function n(t,e){var r=t.length,n=["'use strict';"],i="surfaceNets"+t.join("_")+"d"+e;n.push("var contour=genContour({","order:[",t.join(),"],","scalarArguments: 3,","phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],l=[],c=0;r>c;++c)a.push("d"+c),l.push("d"+c);for(var c=0;1<c;++c)a.push("v"+c),l.push("v"+c);for(var c=0;1<c;++c)a.push("p"+c),l.push("p"+c);a.push("a","b","c"),l.push("a","c"),n.push("vertex:function vertexFunc(",a.join(),"){");for(var u=[],c=0;1<c;++c)u.push("(p"+c+"<<"+c+")");n.push("var m=(",u.join("+"),")|0;if(m===0||m===",(1<<(1<=1<<(1<>>7){");for(var c=0;1<<(1<c;++c){if(1<<(1<128&&c%128===0){f.length>0&&h.push("}}");var d="vExtra"+f.length;n.push("case ",c>>>7,":",d,"(m&0x7f,",l.join(),");break;"),h=["function ",d,"(m,",l.join(),"){switch(m){"],f.push(h)}h.push("case ",127&c,":");for(var p=new Array(r),g=new Array(r),v=new Array(r),m=new Array(r),y=0,b=0;r>b;++b)p[b]=[],g[b]=[],v[b]=0,m[b]=0;for(var b=0;1<b;++b)for(var x=0;r>x;++x){var _=b^1<b)&&!(c&1<<_)!=!(c&1<w?(p[x].push("-v"+b+"-v"+_),v[x]+=2):(p[x].push("v"+b+"+v"+_),v[x]-=2),y+=1;for(var k=0;r>k;++k)k!==x&&(_&1<x;++x)if(0===p[x].length)A.push("d"+x+"-0.5");else{var M="";v[x]<0?M=v[x]+"*c":v[x]>0&&(M="+"+v[x]+"*c");var T=.5*(p[x].length/y),E=.5+.5*(m[x]/y);A.push("d"+x+"-"+E+"-"+T+"*("+p[x].join("+")+M+")/("+g[x].join("+")+")")}h.push("a.push([",A.join(),"]);","break;")}n.push("}},"),f.length>0&&h.push("}}");for(var L=[],c=0;1<c;++c)L.push("v"+c);L.push("c0","c1","p0","p1","a","b","c"),n.push("cell:function cellFunc(",L.join(),"){");var S=s(r-1);n.push("if(p0){b.push(",S.map(function(t){return"["+t.map(function(t){return"v"+t})+"]"}).join(),")}else{b.push(",S.map(function(t){var e=t.slice();return e.reverse(),"["+e.map(function(t){return"v"+t})+"]"}).join(),")}}});function ",i,"(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ",i,";");for(var c=0;co;++o)i[o]=[r[o]],a[o]=[o];return{positions:i,cells:a}}function a(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return i(t,e);var r=t.order.join()+"-"+t.dtype,a=c[r],e=+e||0;return a||(a=c[r]=n(t.order,t.dtype)),a(t,e)}e.exports=a;var o=t("ndarray-extract-contour"),s=t("triangulate-hypercube"),l=t("zero-crossings"),c={}},{"ndarray-extract-contour":264,"triangulate-hypercube":269,"zero-crossings":271}],273:[function(t,e,r){(function(r){"use strict";function n(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;ol;++l){var c=r[s[l]];n[i++]=c[0],n[i++]=c[1]+1.4,a=Math.max(c[0],a)}return{data:n,shape:a}}function i(t,e){var r=s[t];r||(r=s[t]={" ":{data:new Float32Array(0),shape:.2}});var o=r[e];if(!o)if(e.length<=1||!/\d/.test(e))o=r[e]=n(a(e,{triangles:!0,font:t,textAlign:"left",textBaseline:"alphabetic"}));else{for(var l=e.split(/(\d|\s)/),c=new Array(l.length),u=0,f=0,h=0;h0&&(f+=.02);for(var d=new Float32Array(u),p=0,g=-.5*f,h=0;h.5?l/(2-a-o):l/(a+o),a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,l:s}}function o(t,e,r){function n(t,e,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?t+6*(e-t)*r:.5>r?e:2/3>r?t+(e-t)*(2/3-r)*6:t}var i,a,o;if(t=T(t,360),e=T(e,100),r=T(r,100),0===e)i=a=o=r;else{var s=.5>r?r*(1+e):r+e-r*e,l=2*r-s;i=n(l,s,t+1/3),a=n(l,s,t),o=n(l,s,t-1/3)}return{r:255*i,g:255*a,b:255*o}}function s(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=a,l=a-o;if(i=0===a?0:l/a,a==o)n=0;else{switch(a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,v:s}}function l(t,e,r){t=6*T(t,360),e=T(e,100),r=T(r,100);var n=B.floor(t),i=t-n,a=r*(1-e),o=r*(1-i*e),s=r*(1-(1-i)*e),l=n%6,c=[r,o,a,a,s,r][l],u=[s,r,r,o,a,a][l],f=[a,a,s,r,r,o][l];return{r:255*c,g:255*u,b:255*f}}function c(t,e,r,n){var i=[z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function u(t,e,r,n){var i=[z(R(n)),z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return i.join("")}function f(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s-=r/100,n.s=E(n.s),e(n)}function h(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s+=r/100,n.s=E(n.s),e(n)}function d(t){return e(t).desaturate(100)}function p(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l+=r/100,n.l=E(n.l),e(n)}function g(t,r){r=0===r?0:r||10;var n=e(t).toRgb();return n.r=q(0,V(255,n.r-U(255*-(r/100)))),n.g=q(0,V(255,n.g-U(255*-(r/100)))),n.b=q(0,V(255,n.b-U(255*-(r/100)))),e(n)}function v(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l-=r/100,n.l=E(n.l),e(n)}function m(t,r){var n=e(t).toHsl(),i=(U(n.h)+r)%360;return n.h=0>i?360+i:i,e(n)}function y(t){var r=e(t).toHsl();return r.h=(r.h+180)%360,e(r)}function b(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+120)%360,s:r.s,l:r.l}),e({h:(n+240)%360,s:r.s,l:r.l})]}function x(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+90)%360,s:r.s,l:r.l}),e({h:(n+180)%360,s:r.s,l:r.l}),e({h:(n+270)%360,s:r.s,l:r.l})]}function _(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+72)%360,s:r.s,l:r.l}),e({h:(n+216)%360,s:r.s,l:r.l})]}function w(t,r,n){r=r||6,n=n||30;var i=e(t).toHsl(),a=360/n,o=[e(t)];for(i.h=(i.h-(a*r>>1)+720)%360;--r;)i.h=(i.h+a)%360,o.push(e(i));return o}function k(t,r){r=r||6;for(var n=e(t).toHsv(),i=n.h,a=n.s,o=n.v,s=[],l=1/r;r--;)s.push(e({h:i,s:a,v:o})),o=(o+l)%1;return s}function A(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}function M(t){return t=parseFloat(t),(isNaN(t)||0>t||t>1)&&(t=1),t}function T(t,e){S(t)&&(t="100%");var r=C(t);return t=V(e,q(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),B.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function E(t){return V(1,q(0,t))}function L(t){return parseInt(t,16)}function S(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)}function C(t){return"string"==typeof t&&-1!=t.indexOf("%")}function z(t){return 1==t.length?"0"+t:""+t}function P(t){return 1>=t&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function O(t){return L(t)/255}function I(t){t=t.replace(j,"").replace(F,"").toLowerCase();var e=!1;if(G[t])t=G[t],e=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};var r;return(r=X.rgb.exec(t))?{r:r[1],g:r[2],b:r[3]}:(r=X.rgba.exec(t))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=X.hsl.exec(t))?{h:r[1],s:r[2],l:r[3]}:(r=X.hsla.exec(t))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=X.hsv.exec(t))?{h:r[1],s:r[2],v:r[3]}:(r=X.hsva.exec(t))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=X.hex8.exec(t))?{a:O(r[1]),r:L(r[2]),g:L(r[3]),b:L(r[4]),format:e?"name":"hex8"}:(r=X.hex6.exec(t))?{r:L(r[1]),g:L(r[2]),b:L(r[3]),format:e?"name":"hex"}:(r=X.hex3.exec(t))?{r:L(r[1]+""+r[1]),g:L(r[2]+""+r[2]),b:L(r[3]+""+r[3]),format:e?"name":"hex"}:!1}function N(t){var e,r;return t=t||{level:"AA",size:"small"},e=(t.level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA"),"small"!==r&&"large"!==r&&(r="small"),{level:e,size:r}}var j=/^\s+/,F=/\s+$/,D=0,B=Math,U=B.round,V=B.min,q=B.max,H=B.random;e.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n,i,a,o=this.toRgb();return t=o.r/255,e=o.g/255,r=o.b/255,n=.03928>=t?t/12.92:Math.pow((t+.055)/1.055,2.4),i=.03928>=e?e/12.92:Math.pow((e+.055)/1.055,2.4),a=.03928>=r?r/12.92:Math.pow((r+.055)/1.055,2.4),.2126*n+.7152*i+.0722*a},setAlpha:function(t){return this._a=M(t),this._roundA=U(100*this._a)/100,this},toHsv:function(){var t=s(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=s(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return c(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(){return u(this._r,this._g,this._b,this._a)},toHex8String:function(){return"#"+this.toHex8()},toRgb:function(){return{r:U(this._r),g:U(this._g),b:U(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+U(this._r)+", "+U(this._g)+", "+U(this._b)+")":"rgba("+U(this._r)+", "+U(this._g)+", "+U(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:U(100*T(this._r,255))+"%",g:U(100*T(this._g,255))+"%",b:U(100*T(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%)":"rgba("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":this._a<1?!1:Y[c(this._r,this._g,this._b,!0)]||!1},toFilter:function(t){var r="#"+u(this._r,this._g,this._b,this._a),n=r,i=this._gradientType?"GradientType = 1, ":"";if(t){var a=e(t);n=a.toHex8String()}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+r+",endColorstr="+n+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0,i=!e&&n&&("hex"===t||"hex6"===t||"hex3"===t||"name"===t);return i?"name"===t&&0===this._a?this.toName():this.toRgbString():("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString())},clone:function(){return e(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(p,arguments)},brighten:function(){return this._applyModification(g,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(f,arguments)},saturate:function(){return this._applyModification(h,arguments)},greyscale:function(){return this._applyModification(d,arguments)},spin:function(){return this._applyModification(m,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(w,arguments)},complement:function(){return this._applyCombination(y,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(b,arguments)},tetrad:function(){return this._applyCombination(x,arguments)}},e.fromRatio=function(t,r){if("object"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&("a"===i?n[i]=t[i]:n[i]=P(t[i]));t=n}return e(t,r)},e.equals=function(t,r){return t&&r?e(t).toRgbString()==e(r).toRgbString():!1},e.random=function(){return e.fromRatio({r:H(),g:H(),b:H()})},e.mix=function(t,r,n){n=0===n?0:n||50;var i,a=e(t).toRgb(),o=e(r).toRgb(),s=n/100,l=2*s-1,c=o.a-a.a;i=l*c==-1?l:(l+c)/(1+l*c),i=(i+1)/2;var u=1-i,f={r:o.r*i+a.r*u,g:o.g*i+a.g*u,b:o.b*i+a.b*u,a:o.a*s+a.a*(1-s)};return e(f)},e.readability=function(t,r){var n=e(t),i=e(r);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},e.isReadable=function(t,r,n){var i,a,o=e.readability(t,r);switch(a=!1,i=N(n),i.level+i.size){case"AAsmall":case"AAAlarge":a=o>=4.5;break;case"AAlarge":a=o>=3;break;case"AAAsmall":a=o>=7}return a},e.mostReadable=function(t,r,n){var i,a,o,s,l=null,c=0;n=n||{},a=n.includeFallbackColors,o=n.level,s=n.size;for(var u=0;uc&&(c=i,l=e(r[u]));return e.isReadable(t,l,{level:o,size:s})||!a?l:(n.includeFallbackColors=!1,e.mostReadable(t,["#fff","#000"],n))};var G=e.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Y=e.hexNames=A(G),X=function(){var t="[-\\+]?\\d+%?",e="[-\\+]?\\d*\\.\\d+%?",r="(?:"+e+")|(?:"+t+")",n="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?",i="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?";return{rgb:new RegExp("rgb"+n),rgba:new RegExp("rgba"+i),hsl:new RegExp("hsl"+n),hsla:new RegExp("hsla"+i),hsv:new RegExp("hsv"+n),hsva:new RegExp("hsva"+i),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();"undefined"!=typeof r&&r.exports?r.exports=e:"function"==typeof t&&t.amd?t(function(){return e}):window.tinycolor=e}()},{}],275:[function(e,r,n){!function(e,i){"object"==typeof n&&"undefined"!=typeof r?i(n):"function"==typeof t&&t.amd?t(["exports"],i):i(e.topojson={})}(this,function(t){"use strict";function e(){}function r(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0),t[0]=(r+=t[0])*i+o,t[1]=(n+=t[1])*a+s}}function n(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0);var l=(t[0]-o)/i|0,c=(t[1]-s)/a|0;t[0]=l-r,t[1]=c-n,r=l,n=c}}function i(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r}function a(t,e){for(var r=0,n=t.length;n>r;){var i=r+n>>>1;t[i]t?~t:t],a=0,o=n.length;o>a;++a)e.push(r=n[a].slice()),u(r,a);0>t&&i(e,o)}function a(t){return t=t.slice(),u(t,0),t}function o(t){for(var e=[],r=0,i=t.length;i>r;++r)n(t[r],e);return e.length<2&&e.push(e[0].slice()),e}function s(t){for(var e=o(t);e.length<4;)e.push(e[0].slice());return e}function l(t){return t.map(s)}function c(t){var e=t.type;return"GeometryCollection"===e?{type:e,geometries:t.geometries.map(c)}:e in h?{type:e,coordinates:h[e](t)}:null}var u=r(t.transform),f=t.arcs,h={Point:function(t){return a(t.coordinates)},MultiPoint:function(t){return t.coordinates.map(a)},LineString:function(t){return o(t.arcs)},MultiLineString:function(t){return t.arcs.map(o)},Polygon:function(t){return l(t.arcs)},MultiPolygon:function(t){return t.arcs.map(l)}};return c(e)}function c(t,e){function r(e){var r,n=t.arcs[0>e?~e:e],i=n[0];return t.transform?(r=[0,0],n.forEach(function(t){r[0]+=t[0],r[1]+=t[1]})):r=n[n.length-1],0>e?[r,i]:[i,r]}function n(t,e){for(var r in t){var n=t[r];delete e[n.start],delete n.start,delete n.end,n.forEach(function(t){i[0>t?~t:t]=1}),s.push(n)}}var i={},a={},o={},s=[],l=-1;return e.forEach(function(r,n){ -var i,a=t.arcs[0>r?~r:r];a.length<3&&!a[1][0]&&!a[1][1]&&(i=e[++l],e[l]=r,e[n]=i)}),e.forEach(function(t){var e,n,i=r(t),s=i[0],l=i[1];if(e=o[s])if(delete o[e.end],e.push(t),e.end=l,n=a[l]){delete a[n.start];var c=n===e?e:e.concat(n);a[c.start=e.start]=o[c.end=n.end]=c}else a[e.start]=o[e.end]=e;else if(e=a[l])if(delete a[e.start],e.unshift(t),e.start=s,n=o[s]){delete o[n.end];var u=n===e?e:n.concat(e);a[u.start=n.start]=o[u.end=e.end]=u}else a[e.start]=o[e.end]=e;else e=[t],a[e.start=s]=o[e.end=l]=e}),n(o,a),n(a,o),e.forEach(function(t){i[0>t?~t:t]||s.push([t])}),s}function u(t){return l(t,f.apply(this,arguments))}function f(t,e,r){function n(t){var e=0>t?~t:t;(u[e]||(u[e]=[])).push({i:t,g:l})}function i(t){t.forEach(n)}function a(t){t.forEach(i)}function o(t){"GeometryCollection"===t.type?t.geometries.forEach(o):t.type in f&&(l=t,f[t.type](t.arcs))}var s=[];if(arguments.length>1){var l,u=[],f={LineString:i,MultiLineString:a,Polygon:a,MultiPolygon:function(t){t.forEach(a)}};o(e),u.forEach(arguments.length<3?function(t){s.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&s.push(t[0].i)})}else for(var h=0,d=t.arcs.length;d>h;++h)s.push(h);return{type:"MultiLineString",arcs:c(t,s)}}function h(t){var e=t[0],r=t[1],n=t[2];return Math.abs((e[0]-n[0])*(r[1]-e[1])-(e[0]-r[0])*(n[1]-e[1]))}function d(t){for(var e,r=-1,n=t.length,i=t[n-1],a=0;++re?~e:e]||(i[e]=[])).push(t)})}),a.push(t)}function n(e){return d(l(t,{type:"Polygon",arcs:[e]}).coordinates[0])>0}var i={},a=[],o=[];return e.forEach(function(t){"Polygon"===t.type?r(t.arcs):"MultiPolygon"===t.type&&t.arcs.forEach(r)}),a.forEach(function(t){if(!t._){var e=[],r=[t];for(t._=1,o.push(e);t=r.pop();)e.push(t),t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].forEach(function(t){t._||(t._=1,r.push(t))})})})}}),a.forEach(function(t){delete t._}),{type:"MultiPolygon",arcs:o.map(function(e){var r,a=[];if(e.forEach(function(t){t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].length<2&&a.push(t)})})}),a=c(t,a),(r=a.length)>1)for(var o,s=n(e[0][0]),l=0;r>l;++l)if(s===n(a[l])){o=a[0],a[0]=a[l],a[l]=o;break}return a})}}function v(t){function e(t,e){t.forEach(function(t){0>t&&(t=~t);var r=i[t];r?r.push(e):i[t]=[e]})}function r(t,r){t.forEach(function(t){e(t,r)})}function n(t,e){"GeometryCollection"===t.type?t.geometries.forEach(function(t){n(t,e)}):t.type in s&&s[t.type](t.arcs,e)}var i={},o=t.map(function(){return[]}),s={LineString:e,MultiLineString:r,Polygon:r,MultiPolygon:function(t,e){t.forEach(function(t){r(t,e)})}};t.forEach(n);for(var l in i)for(var c=i[l],u=c.length,f=0;u>f;++f)for(var h=f+1;u>h;++h){var d,p=c[f],g=c[h];(d=o[p])[l=a(d,g)]!==g&&d.splice(l,0,g),(d=o[g])[l=a(d,p)]!==p&&d.splice(l,0,p)}return o}function m(t,e){return t[1][2]-e[1][2]}function y(){function t(t,e){for(;e>0;){var r=(e+1>>1)-1,i=n[r];if(m(t,i)>=0)break;n[i._=e]=i,n[t._=e=r]=t}}function e(t,e){for(;;){var r=e+1<<1,a=r-1,o=e,s=n[o];if(i>a&&m(n[a],s)<0&&(s=n[o=a]),i>r&&m(n[r],s)<0&&(s=n[o=r]),o===e)break;n[s._=e]=s,n[t._=e=o]=t}}var r={},n=[],i=0;return r.push=function(e){return t(n[e._=i]=e,i++),i},r.pop=function(){if(!(0>=i)){var t,r=n[0];return--i>0&&(t=n[i],e(n[t._=0]=t,0)),r}},r.remove=function(r){var a,o=r._;if(n[o]===r)return o!==--i&&(a=n[i],(m(a,r)<0?t:e)(n[a._=o]=a,o)),o},r}function b(t,e){function i(t){s.remove(t),t[1][2]=e(t),s.push(t)}var a=r(t.transform),o=n(t.transform),s=y();return e||(e=h),t.arcs.forEach(function(t){var r,n,l,c,u=[],f=0;for(n=0,l=t.length;l>n;++n)c=t[n],a(t[n]=[c[0],c[1],1/0],n);for(n=1,l=t.length-1;l>n;++n)r=t.slice(n-1,n+2),r[1][2]=e(r),u.push(r),s.push(r);for(n=0,l=u.length;l>n;++n)r=u[n],r.previous=u[n-1],r.next=u[n+1];for(;r=s.pop();){var h=r.previous,d=r.next;r[1][2]0?r.pop():new ArrayBuffer(t)}function s(t){return new Uint8Array(o(t),0,t)}function l(t){return new Uint16Array(o(2*t),0,t)}function c(t){return new Uint32Array(o(4*t),0,t)}function u(t){return new Int8Array(o(t),0,t)}function f(t){return new Int16Array(o(2*t),0,t)}function h(t){return new Int32Array(o(4*t),0,t)}function d(t){return new Float32Array(o(4*t),0,t)}function p(t){return new Float64Array(o(8*t),0,t)}function g(t){return x?new Uint8ClampedArray(o(t),0,t):s(t)}function v(t){return new DataView(o(t),0,t)}function m(t){t=y.nextPow2(t);var e=y.log2(t),r=k[e];return r.length>0?r.pop():new n(t)}var y=t("bit-twiddle"),b=t("dup");e.__TYPEDARRAY_POOL||(e.__TYPEDARRAY_POOL={UINT8:b([32,0]),UINT16:b([32,0]),UINT32:b([32,0]),INT8:b([32,0]),INT16:b([32,0]),INT32:b([32,0]),FLOAT:b([32,0]),DOUBLE:b([32,0]),DATA:b([32,0]),UINT8C:b([32,0]),BUFFER:b([32,0])});var x="undefined"!=typeof Uint8ClampedArray,_=e.__TYPEDARRAY_POOL;_.UINT8C||(_.UINT8C=b([32,0])),_.BUFFER||(_.BUFFER=b([32,0]));var w=_.DATA,k=_.BUFFER;r.free=function(t){if(n.isBuffer(t))k[y.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|y.log2(e);w[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=a,r.freeArrayBuffer=i,r.freeBuffer=function(t){k[y.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return o(t);switch(e){case"uint8":return s(t);case"uint16":return l(t);case"uint32":return c(t);case"int8":return u(t);case"int16":return f(t);case"int32":return h(t);case"float":case"float32":return d(t);case"double":case"float64":return p(t);case"uint8_clamped":return g(t);case"buffer":return m(t);case"data":case"dataview":return v(t);default:return null}return null},r.mallocArrayBuffer=o,r.mallocUint8=s,r.mallocUint16=l,r.mallocUint32=c,r.mallocInt8=u,r.mallocInt16=f,r.mallocInt32=h,r.mallocFloat32=r.mallocFloat=d,r.mallocFloat64=r.mallocDouble=p,r.mallocUint8Clamped=g,r.mallocDataView=v,r.mallocBuffer=m,r.clearCache=function(){for(var t=0;32>t;++t)_.UINT8[t].length=0,_.UINT16[t].length=0,_.UINT32[t].length=0,_.INT8[t].length=0,_.INT16[t].length=0,_.INT32[t].length=0,_.FLOAT[t].length=0,_.DOUBLE[t].length=0,_.UINT8C[t].length=0,w[t].length=0,k[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":50,buffer:51,dup:115}],279:[function(t,e,r){"use strict";function n(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;n>o;++o)if(a=i,i=t[o],e(i,a)){if(o===r){r++;continue}t[r++]=i}return t.length=r,t}function i(t){for(var e=1,r=t.length,n=t[0],i=t[0],a=1;r>a;++a,i=n)if(i=n,n=t[a],n!==i){if(a===e){e++;continue}t[e++]=n}return t.length=e,t}function a(t,e,r){return 0===t.length?t:e?(r||t.sort(e),n(t,e)):(r||t.sort(),i(t))}e.exports=a},{}],280:[function(t,e,r){"use strict";function n(t,e){return"object"==typeof e&&null!==e||(e={}),i(t,e.canvas||a,e.context||o,e)}e.exports=n;var i=t("./lib/vtext"),a=null,o=null;"undefined"!=typeof document&&(a=document.createElement("canvas"),a.width=8192,a.height=1024,o=a.getContext("2d"))},{"./lib/vtext":281}],281:[function(t,e,r){"use strict";function n(t,e,r){for(var n=e.textAlign||"start",i=e.textBaseline||"alphabetic",a=[1<<30,1<<30],o=[0,0],s=t.length,l=0;s>l;++l)for(var c=t[l],u=0;2>u;++u)a[u]=0|Math.min(a[u],c[u]),o[u]=0|Math.max(o[u],c[u]);var f=0;switch(n){case"center":f=-.5*(a[0]+o[0]);break;case"right":case"end":f=-o[0];break;case"left":case"start":f=-a[0];break;default:throw new Error("vectorize-text: Unrecognized textAlign: '"+n+"'")}var h=0;switch(i){case"hanging":case"top":h=-a[1];break;case"middle":h=-.5*(a[1]+o[1]);break;case"alphabetic":case"ideographic":h=-3*r;break;case"bottom":h=-o[1];break;default:throw new Error("vectorize-text: Unrecoginized textBaseline: '"+i+"'")}var d=1/r;return"lineHeight"in e?d*=+e.lineHeight:"width"in e?d=e.width/(o[0]-a[0]):"height"in e&&(d=e.height/(o[1]-a[1])),t.map(function(t){return[d*(t[0]+f),d*(t[1]+h)]})}function i(t,e,r,n){var i=0|Math.ceil(e.measureText(r).width+2*n);if(i>8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height=l&&o.push(s)}for(;o.length>0;){var c=o.pop();n[c]=!1;for(var u=r[c],s=0;sn;++n){var a=t[n];e=Math.max(e,a[0],a[1])}e=(0|e)+1}e=0|e;for(var o=new Array(e),n=0;e>n;++n)o[n]=[];for(var n=0;r>n;++n){var a=t[n];o[a[0]].push(a[1]),o[a[1]].push(a[0])}for(var s=0;e>s;++s)i(o[s],function(t,e){return t-e});return o}e.exports=n;var i=t("uniq")},{uniq:279}],284:[function(t,e,r){"use strict";function n(t,e){function r(t,e){var r=c[e][t[e]];r.splice(r.indexOf(t),1)}function n(t,n,a){for(var o,s,l,u=0;2>u;++u)if(c[u][n].length>0){o=c[u][n][0],l=u;break}s=o[1^l];for(var f=0;2>f;++f)for(var h=c[f][n],d=0;d0&&(o=p,s=g,l=f)}return a?s:(o&&r(o,l),s)}function a(t,a){var o=c[a][t][0],s=[t];r(o,a);for(var l=o[1^a];;){for(;l!==t;)s.push(l),l=n(s[s.length-2],l,!1);if(c[0][t].length+c[1][t].length===0)break;var u=s[s.length-1],f=t,h=s[1],d=n(u,f,!0);if(i(e[u],e[f],e[h],e[d])<0)break;s.push(t),l=n(u,f)}return s}function o(t,e){return e[1]===e[e.length-1]}for(var s=0|e.length,l=t.length,c=[new Array(s),new Array(s)],u=0;s>u;++u)c[0][u]=[],c[1][u]=[];for(var u=0;l>u;++u){var f=t[u];c[0][f[0]].push(f),c[1][f[1]].push(f)}for(var h=[],u=0;s>u;++u)c[0][u].length+c[1][u].length===0&&h.push([u]);for(var u=0;s>u;++u)for(var d=0;2>d;++d){for(var p=[];c[d][u].length>0;){var g=(c[0][u].length,a(u,d));o(p,g)?p.push.apply(p,g):(p.length>0&&h.push(p),p=g)}p.length>0&&h.push(p)}return h}e.exports=n;var i=t("compare-angle")},{"compare-angle":285}],285:[function(t,e,r){"use strict";function n(t,e,r){var n=s(t[0],-e[0]),i=s(t[1],-e[1]),a=s(r[0],-e[0]),o=s(r[1],-e[1]),u=c(l(n,a),l(i,o));return u[u.length-1]>=0}function i(t,e,r,i){var s=a(e,r,i);if(0===s){var l=o(a(t,e,r)),c=o(a(t,e,i));if(l===c){if(0===l){var u=n(t,e,r),f=n(t,e,i);return u===f?0:u?1:-1}return 0}return 0===c?l>0?-1:n(t,e,i)?-1:1:0===l?c>0?1:n(t,e,r)?1:-1:o(c-l)}var h=a(t,e,r);if(h>0)return s>0&&a(t,e,i)>0?1:-1;if(0>h)return s>0||a(t,e,i)>0?1:-1;var d=a(t,e,i);return d>0?1:n(t,e,r)?1:-1}e.exports=i;var a=t("robust-orientation"),o=t("signum"),s=t("two-sum"),l=t("robust-product"),c=t("robust-sum")},{"robust-orientation":259,"robust-product":286,"robust-sum":262,signum:287,"two-sum":277}],286:[function(t,e,r){"use strict";function n(t,e){if(1===t.length)return a(e,t[0]);if(1===e.length)return a(t,e[0]);if(0===t.length||0===e.length)return[0];var r=[0];if(t.lengtht?-1:t>0?1:0}},{}],288:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],289:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}function i(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function a(t,e){var r=p(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function o(t,e){var r=t.intervals([]);r.push(e),a(t,r)}function s(t,e){var r=t.intervals([]),n=r.indexOf(e);return 0>n?y:(r.splice(n,1),a(t,r),b)}function l(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function u(t,e){for(var r=0;r>1],a=[],o=[],s=[],r=0;r3*(e+1)?o(this,t):this.left.insert(t):this.left=p([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?o(this,t):this.right.insert(t):this.right=p([t]);else{var r=m.ge(this.leftPoints,t,h),n=m.ge(this.rightPoints,t,d);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1))return s(this,t);var n=this.left.remove(t);return n===x?(this.left=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(t[0]>this.mid){if(!this.right)return y;var a=this.left?this.left.count:0;if(4*a>3*(e-1))return s(this,t);var n=this.right.remove(t);return n===x?(this.right=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(1===this.count)return this.leftPoints[0]===t?x:y;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var o=this,l=this.left;l.right;)o=l,l=l.right;if(o===this)l.right=this.right;else{var c=this.left,n=this.right;o.count-=l.count,o.right=l.left,l.left=c,l.right=n}i(this,l),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?i(this,this.left):i(this,this.right);return b}for(var c=m.ge(this.leftPoints,t,h);cthis.mid){if(this.right){var r=this.right.queryPoint(t,e);if(r)return r}return c(this.rightPoints,t,e)}return u(this.leftPoints,e)},_.queryInterval=function(t,e,r){if(tthis.mid&&this.right){var n=this.right.queryInterval(t,e,r);if(n)return n}return ethis.mid?c(this.rightPoints,t,r):u(this.leftPoints,r)};var w=g.prototype;w.insert=function(t){this.root?this.root.insert(t):this.root=new n(t[0],null,null,[t],[t])},w.remove=function(t){if(this.root){var e=this.root.remove(t);return e===x&&(this.root=null),e!==y}return!1},w.queryPoint=function(t,e){return this.root?this.root.queryPoint(t,e):void 0},w.queryInterval=function(t,e,r){return e>=t&&this.root?this.root.queryInterval(t,e,r):void 0},Object.defineProperty(w,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(w,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":288}],290:[function(t,e,r){"use strict";function n(t,e){var r,n;if(e[0][0]e[1][0])){var i=Math.min(t[0][1],t[1][1]),o=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),l=Math.max(e[0][1],e[1][1]);return s>o?o-s:i>l?i-l:o-l}r=e[1],n=e[0]}var c,u;t[0][1]e[1][0]))return n(e,t);r=e[1],i=e[0]}var o,s;if(t[0][0]t[1][0]))return-n(t,e);o=t[1],s=t[0]}var l=a(r,i,s),c=a(r,i,o);if(0>l){if(0>=c)return l}else if(l>0){if(c>=0)return l}else if(c)return c;if(l=a(s,o,i),c=a(s,o,r),0>l){if(0>=c)return l}else if(l>0){if(c>=0)return l}else if(c)return c;return i[0]-s[0]}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":259}],291:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function i(t){return new n(t._color,t.key,t.value,t.left,t.right,t._count)}function a(t,e){return new n(t,e.key,e.value,e.left,e.right,e._count)}function o(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function s(t,e){this._compare=t,this.root=e}function l(t,e){if(e.left){var r=l(t,e.left);if(r)return r}var r=t(e.key,e.value);return r?r:e.right?l(t,e.right):void 0}function c(t,e,r,n){var i=e(t,n.key);if(0>=i){if(n.left){var a=c(t,e,r,n.left);if(a)return a}var a=r(n.key,n.value);if(a)return a}return n.right?c(t,e,r,n.right):void 0}function u(t,e,r,n,i){var a,o=r(t,i.key),s=r(e,i.key);if(0>=o){if(i.left&&(a=u(t,e,r,n,i.left)))return a;if(s>0&&(a=n(i.key,i.value)))return a}return s>0&&i.right?u(t,e,r,n,i.right):void 0}function f(t,e){this.tree=t,this._stack=e}function h(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function d(t){for(var e,r,n,s,l=t.length-1;l>=0;--l){if(e=t[l],0===l)return void(e._color=m);if(r=t[l-1],r.left===e){if(n=r.right,n.right&&n.right._color===v){if(n=r.right=i(n),s=n.right=i(n.right),r.right=n.left,n.left=r,n.right=s,n._color=r._color,e._color=m,r._color=m,s._color=m,o(r),o(n),l>1){var c=t[l-2];c.left===r?c.left=n:c.right=n}return void(t[l-1]=n)}if(n.left&&n.left._color===v){if(n=r.right=i(n),s=n.left=i(n.left),r.right=s.left,n.left=s.right,s.left=r,s.right=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var c=t[l-2];c.left===r?c.left=s:c.right=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.right=a(v,n));r.right=a(v,n);continue}if(n=i(n),r.right=n.left,n.left=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var c=t[l-2];c.left===r?c.left=n:c.right=n}t[l-1]=n,t[l]=r,l+11){var c=t[l-2];c.right===r?c.right=n:c.left=n}return void(t[l-1]=n)}if(n.right&&n.right._color===v){if(n=r.left=i(n),s=n.right=i(n.right),r.left=s.right,n.right=s.left,s.right=r,s.left=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var c=t[l-2];c.right===r?c.right=s:c.left=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.left=a(v,n));r.left=a(v,n);continue}if(n=i(n),r.left=n.right,n.right=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var c=t[l-2];c.right===r?c.right=n:c.left=n}t[l-1]=n,t[l]=r,l+1t?-1:t>e?1:0}function g(t){return new s(t||p,null)}e.exports=g;var v=0,m=1,y=s.prototype;Object.defineProperty(y,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(y,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(y,"length",{get:function(){return this.root?this.root._count:0}}),y.insert=function(t,e){for(var r=this._compare,i=this.root,l=[],c=[];i;){var u=r(t,i.key);l.push(i),c.push(u),i=0>=u?i.left:i.right}l.push(new n(v,t,e,null,null,1));for(var f=l.length-2;f>=0;--f){var i=l[f];c[f]<=0?l[f]=new n(i._color,i.key,i.value,l[f+1],i.right,i._count+1):l[f]=new n(i._color,i.key,i.value,i.left,l[f+1],i._count+1)}for(var f=l.length-1;f>1;--f){var h=l[f-1],i=l[f];if(h._color===m||i._color===m)break;var d=l[f-2];if(d.left===h)if(h.left===i){var p=d.right;if(!p||p._color!==v){if(d._color=v,d.left=h.right,h._color=m,h.right=d,l[f-2]=h,l[f-1]=i,o(d),o(h),f>=3){var g=l[f-3];g.left===d?g.left=h:g.right=h}break}h._color=m,d.right=a(m,p),d._color=v,f-=1}else{var p=d.right;if(!p||p._color!==v){if(h.right=i.left,d._color=v,d.left=i.right,i._color=m,i.left=h,i.right=d,l[f-2]=i,l[f-1]=h,o(d),o(h),o(i),f>=3){var g=l[f-3];g.left===d?g.left=i:g.right=i}break}h._color=m,d.right=a(m,p),d._color=v,f-=1}else if(h.right===i){var p=d.left;if(!p||p._color!==v){if(d._color=v,d.right=h.left,h._color=m,h.left=d,l[f-2]=h,l[f-1]=i,o(d),o(h),f>=3){var g=l[f-3];g.right===d?g.right=h:g.left=h}break}h._color=m,d.left=a(m,p),d._color=v,f-=1}else{var p=d.left;if(!p||p._color!==v){if(h.left=i.right,d._color=v,d.right=i.left,i._color=m,i.right=h,i.left=d,l[f-2]=i,l[f-1]=h,o(d),o(h),o(i),f>=3){var g=l[f-3];g.right===d?g.right=i:g.left=i}break}h._color=m,d.left=a(m,p),d._color=v,f-=1}}return l[0]._color=m,new s(r,l[0])},y.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return l(t,this.root);case 2:return c(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return u(e,r,this._compare,t,this.root)}},Object.defineProperty(y,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new f(this,t)}}),Object.defineProperty(y,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new f(this,t)}}),y.at=function(t){if(0>t)return new f(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new f(this,[])},y.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>=a&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>a&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new f(this,n);r=0>=i?r.left:r.right}return new f(this,[])},y.remove=function(t){var e=this.find(t);return e?e.remove():this},y.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=0>=n?r.left:r.right}};var b=f.prototype;Object.defineProperty(b,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(b,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),b.clone=function(){return new f(this.tree,this._stack.slice())},b.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new n(r._color,r.key,r.value,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i){var r=t[i];r.left===t[i+1]?e[i]=new n(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count)}if(r=e[e.length-1],r.left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var o=e[a-1];e.push(new n(r._color,o.key,o.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(var i=e.length-2;i>=a;--i)r=e[i],e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count);e[a-1].left=e[a]}if(r=e[e.length-1],r._color===v){var l=e[e.length-2];l.left===r?l.left=null:l.right===r&&(l.right=null),e.pop();for(var i=0;i0?this._stack[this._stack.length-1].key:void 0},enumerable:!0}),Object.defineProperty(b,"value",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1].value:void 0},enumerable:!0}),Object.defineProperty(b,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),b.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),b.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),i=e[e.length-1];r[r.length-1]=new n(i._color,i.key,t,i.left,i.right,i._count);for(var a=e.length-2;a>=0;--a)i=e[a],i.left===e[a+1]?r[a]=new n(i._color,i.key,i.value,r[a+1],i.right,i._count):r[a]=new n(i._color,i.key,i.value,i.left,r[a+1],i._count);return new s(this.tree._compare,r[0])},b.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],292:[function(t,e,r){"use strict";function n(t,e,r){this.slabs=t,this.coordinates=e,this.horizontal=r}function i(t,e){return t.y-e}function a(t,e){for(var r=null;t;){var n,i,o=t.key;o[0][0]s)t=t.left;else if(s>0)if(e[0]!==o[1][0])r=t,t=t.right;else{var l=a(t.right,e);if(l)return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l=a(t.right,e);if(l)return l;t=t.left}}return r}function o(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function s(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}function l(t){for(var e=t.length,r=2*e,i=new Array(r),a=0;e>a;++a){var l=t[a],c=l[0][0]a;){for(var v=i[a].x,m=[];r>a;){var y=i[a];if(y.x!==v)break;a+=1,y.segment[0][0]===y.x&&y.segment[1][0]===y.x?y.create&&(y.segment[0][1]e)return-1;var r=(this.slabs[e],a(this.slabs[e],t)),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var o=null;if(r&&(o=r.key),e>0){var s=a(this.slabs[e-1],t);s&&(o?h(s.key,o)>0&&(o=s.key,n=s.value):(n=s.value,o=s.key))}var l=this.horizontal[e];if(l.length>0){var u=c.ge(l,t[1],i);if(u=l.length)return n;d=l[u]}}if(d.start)if(o){var p=f(o[0],o[1],[t[0],d.y]);o[0][0]>o[1][0]&&(p=-p),p>0&&(n=d.index)}else n=d.index;else d.y!==t[1]&&(n=d.index)}}}return n}},{"./lib/order-segments":290,"binary-search-bounds":288,"functional-red-black-tree":291,"robust-orientation":259}],293:[function(t,e,r){function n(){return!0}function i(t){return function(e,r){var i=t[e];return i?!!i.queryPoint(r,n):!1}}function a(t){for(var e={},r=0;rn)return 1;var i=t[n];if(!i){if(!(n>0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=f(r,o[0],o[1]);if(o[0][0]s)i=i.left;else{if(!(s>0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(0>s))return 0;a=1,i=i.right}}return a}}function s(t){return 1}function l(t){return function(e){return t(e[0],e[1])?0:1}}function c(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}function u(t){for(var e=t.length,r=[],n=[],i=0;e>i;++i)for(var u=t[i],f=u.length,d=f-1,p=0;f>p;d=p++){var g=u[d],v=u[p];g[0]===v[0]?n.push([g,v]):r.push([g,v]); -}if(0===r.length)return 0===n.length?s:l(a(n));var m=h(r),y=o(m.slabs,m.coordinates);return 0===n.length?y:c(a(n),y)}e.exports=u;var f=t("robust-orientation")[3],h=t("slab-decomposition"),d=t("interval-tree-1d"),p=t("binary-search-bounds")},{"binary-search-bounds":288,"interval-tree-1d":289,"robust-orientation":259,"slab-decomposition":292}],294:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function i(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=[];return e}function a(t,e){function r(t){for(var r=t.length,n=[0],i=0;r>i;++i){var a=e[t[i]],o=e[t[(i+1)%r]],s=c(-a[0],a[1]),l=c(-a[0],o[1]),f=c(o[0],a[1]),h=c(o[0],o[1]);n=u(n,u(u(s,l),u(f,h)))}return n[n.length-1]>0}function a(t){for(var e=t.length,r=0;e>r;++r)if(!O[t[r]])return!1;return!0}var d=h(t,e);t=d[0],e=d[1];for(var p=e.length,g=(t.length,o(t,e.length)),v=0;p>v;++v)if(g[v].length%2===1)throw new Error("planar-graph-to-polyline: graph must be manifold");var m=s(t,e);m=m.filter(r);for(var y=m.length,b=new Array(y),x=new Array(y),v=0;y>v;++v){b[v]=v;var _=new Array(y),w=m[v].map(function(t){return e[t]}),k=l([w]),A=0;t:for(var M=0;y>M;++M)if(_[M]=0,v!==M){for(var T=m[M],E=T.length,L=0;E>L;++L){var S=k(e[T[L]]);if(0!==S){0>S&&(_[M]=1,A+=1);continue t}}_[M]=1,A+=1}x[v]=[A,v,_]}x.sort(function(t,e){return e[0]-t[0]});for(var v=0;y>v;++v)for(var _=x[v],C=_[1],z=_[2],M=0;y>M;++M)z[M]&&(b[M]=C);for(var P=i(y),v=0;y>v;++v)P[v].push(b[v]),P[b[v]].push(v);for(var R={},O=n(p,!1),v=0;y>v;++v)for(var T=m[v],E=T.length,M=0;E>M;++M){var I=T[M],N=T[(M+1)%E],j=Math.min(I,N)+":"+Math.max(I,N);if(j in R){var F=R[j];P[F].push(v),P[v].push(F),O[I]=O[N]=!0}else R[j]=v}for(var D=[],B=n(y,-1),v=0;y>v;++v)b[v]!==v||a(m[v])?B[v]=-1:(D.push(v),B[v]=0);for(var d=[];D.length>0;){var U=D.pop(),V=P[U];f(V,function(t,e){return t-e});var q,H=V.length,G=B[U];if(0===G){var T=m[U];q=[T]}for(var v=0;H>v;++v){var Y=V[v];if(!(B[Y]>=0)&&(B[Y]=1^G,D.push(Y),0===G)){var T=m[Y];a(T)||(T.reverse(),q.push(T))}}0===G&&d.push(q)}return d}e.exports=a;var o=t("edges-to-adjacency-list"),s=t("planar-dual"),l=t("point-in-big-polygon"),c=t("two-product"),u=t("robust-sum"),f=t("uniq"),h=t("./lib/trim-leaves")},{"./lib/trim-leaves":282,"edges-to-adjacency-list":283,"planar-dual":284,"point-in-big-polygon":293,"robust-sum":262,"two-product":276,uniq:279}],295:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],296:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n,n.prototype.length=function(){return this.roots.length},n.prototype.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},n.prototype.find=function(t){for(var e=this.roots;e[t]!==t;){var r=e[t];e[t]=e[r],t=r}return t},n.prototype.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],297:[function(t,e,r){arguments[4][238][0].apply(r,arguments)},{"bit-twiddle":295,dup:238,"union-find":296}],298:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.abs(a(t,e,r)),i=Math.sqrt(Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2));return n/i}function i(t,e,r){function i(t){if(x[t])return 1/0;var r=m[t],i=y[t];return 0>r||0>i?1/0:n(e[t],e[r],e[i])}function a(t,e){var r=M[t],n=M[e];M[t]=n,M[e]=r,T[r]=e,T[n]=t}function s(t){return b[M[t]]}function l(t){return 1&t?t-1>>1:(t>>1)-1}function c(t){for(var e=s(t);;){var r=e,n=2*t+1,i=2*(t+1),o=t;if(L>n){var l=s(n);r>l&&(o=n,r=l)}if(L>i){var c=s(i);r>c&&(o=i)}if(o===t)return t;a(t,o),t=o}}function u(t){for(var e=s(t);t>0;){var r=l(t);if(r>=0){var n=s(r);if(n>e){a(t,r),t=r;continue}}return t}}function f(){if(L>0){var t=M[0];return a(0,L-1),L-=1,c(0),t}return-1}function h(t,e){var r=M[t];return b[r]===e?t:(b[r]=-(1/0),u(t),f(),b[r]=e,L+=1,u(L-1))}function d(t){if(!x[t]){x[t]=!0;var e=m[t],r=y[t];m[r]>=0&&(m[r]=e),y[e]>=0&&(y[e]=r),T[e]>=0&&h(T[e],i(e)),T[r]>=0&&h(T[r],i(r))}}function p(t,e){if(t[e]<0)return e;var r=e,n=e;do{var i=t[n];if(!x[n]||0>i||i===n)break;if(n=i,i=t[n],!x[n]||0>i||i===n)break;n=i,r=t[r]}while(r!==n);for(var a=e;a!==n;a=t[a])t[a]=n;return n}for(var g=e.length,v=t.length,m=new Array(g),y=new Array(g),b=new Array(g),x=new Array(g),_=0;g>_;++_)m[_]=y[_]=-1,b[_]=1/0,x[_]=!1;for(var _=0;v>_;++_){var w=t[_];if(2!==w.length)throw new Error("Input must be a graph");var k=w[1],A=w[0];-1!==y[A]?y[A]=-2:y[A]=k,-1!==m[k]?m[k]=-2:m[k]=A}for(var M=[],T=new Array(g),_=0;g>_;++_){var E=b[_]=i(_);1/0>E?(T[_]=M.length,M.push(_)):T[_]=-1}for(var L=M.length,_=L>>1;_>=0;--_)c(_);for(;;){var S=f();if(0>S||b[S]>r)break;d(S)}for(var C=[],_=0;g>_;++_)x[_]||(T[_]=C.length,C.push(e[_].slice()));var z=(C.length,[]);return t.forEach(function(t){var e=p(m,t[0]),r=p(y,t[1]);if(e>=0&&r>=0&&e!==r){var n=T[e],i=T[r];n!==i&&z.push([n,i])}}),o.unique(o.normalize(z)),{positions:C,edges:z}}e.exports=i;var a=t("robust-orientation"),o=t("simplicial-complex")},{"robust-orientation":259,"simplicial-complex":297}],299:[function(t,e,r){"use strict";e.exports=["",{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0},{path:"M2,2V-2H-2V2Z",backoff:0}]},{}],300:[function(t,e,r){"use strict";var n=t("./arrow_paths"),i=t("../../plots/font_attributes"),a=t("../../plots/cartesian/constants"),o=t("../../lib/extend").extendFlat;e.exports={_isLinkedToArray:!0,text:{valType:"string"},textangle:{valType:"angle",dflt:0},font:o({},i,{}),opacity:{valType:"number",min:0,max:1,dflt:1},align:{valType:"enumerated",values:["left","center","right"],dflt:"center"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)"},borderpad:{valType:"number",min:0,dflt:1},borderwidth:{valType:"number",min:0,dflt:1},showarrow:{valType:"boolean",dflt:!0},arrowcolor:{valType:"color"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1},arrowsize:{valType:"number",min:.3,dflt:1},arrowwidth:{valType:"number",min:.1},ax:{valType:"number",dflt:-10},ay:{valType:"number",dflt:-30},xref:{valType:"enumerated",values:["paper",a.idRegex.x.toString()]},x:{valType:"number"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto"},yref:{valType:"enumerated",values:["paper",a.idRegex.y.toString()]},y:{valType:"number"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"},_deprecated:{ref:{valType:"string"}}}},{"../../lib/extend":377,"../../plots/cartesian/constants":410,"../../plots/font_attributes":423,"./arrow_paths":299}],301:[function(t,e,r){"use strict";function n(t,e){function r(e,r){return c.coerce(t,n,v.layoutAttributes,e,r)}var n={};r("opacity"),r("align"),r("bgcolor");var i=r("bordercolor"),a=f.opacity(i);r("borderpad");var o=r("borderwidth"),s=r("showarrow");s&&(r("arrowcolor",a?n.bordercolor:f.defaultLine),r("arrowhead"),r("arrowsize"),r("arrowwidth",2*(a&&o||1)),r("ax"),r("ay"),c.noneOrAll(t,n,["ax","ay"])),r("text",s?" ":"new text"),r("textangle"),c.coerceFont(r,"font",e.font);for(var l=["x","y"],h=0;2>h;h++){var d=l[h],p={_fullLayout:e},g=u.coerceRef(t,n,p,d),m=.5;if("paper"!==g){var y=u.getFromId(p,g);if(m=y.range[0]+m*(y.range[1]-y.range[0]),-1!==["date","category"].indexOf(y.type)&&"string"==typeof t[d]){var b;"date"===y.type?(b=c.dateTime2ms(t[d]),b!==!1&&(t[d]=b)):(y._categories||[]).length&&(b=y._categories.indexOf(t[d]),-1!==b&&(t[d]=b))}}r(d,m),s||r(d+"anchor")}return c.noneOrAll(t,n,["x","y"]),n}function i(t){var e=t._fullLayout;e.annotations.forEach(function(e){var r=u.getFromId(t,e.xref),n=u.getFromId(t,e.yref);if(r||n){var i=(e._xsize||0)/2,a=e._xshift||0,o=(e._ysize||0)/2,s=e._yshift||0,l=i-a,c=i+a,f=o-s,h=o+s;if(e.showarrow){var d=3*e.arrowsize*e.arrowwidth;l=Math.max(l,d),c=Math.max(c,d),f=Math.max(f,d),h=Math.max(h,d)}r&&r.autorange&&u.expand(r,[r.l2c(e.x)],{ppadplus:c,ppadminus:l}),n&&n.autorange&&u.expand(n,[n.l2c(e.y)],{ppadplus:h,ppadminus:f})}})}function a(t,e,r,n,i,a,o,s){var l=r-t,c=i-t,u=o-i,f=n-e,h=a-e,d=s-a,p=l*d-u*f;if(0===p)return null;var g=(c*d-u*h)/p,v=(c*f-l*h)/p;return 0>v||v>1||0>g||g>1?null:{x:t+l*g,y:e+f*g}}var o=t("d3"),s=t("fast-isnumeric"),l=t("../../plotly"),c=t("../../lib"),u=t("../../plots/cartesian/axes"),f=t("../color"),h=t("../drawing"),d=t("../../lib/svg_text_utils"),p=t("../../lib/setcursor"),g=t("../dragelement"),v=e.exports={};v.ARROWPATHS=t("./arrow_paths"),v.layoutAttributes=t("./attributes"),v.supplyLayoutDefaults=function(t,e){for(var r=t.annotations||[],i=e.annotations=[],a=0;at?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}tt.selectAll("tspan.line").attr({y:0,x:0});var n=W.select(".annotation-math-group"),i=!n.empty(),s=h.bBox((i?n:tt).node()),d=s.width,m=s.height,y=Math.round(d+2*$),b=Math.round(m+2*$);U._w=d,U._h=m;var x=!1;if(["x","y"].forEach(function(e){var n,i=u.getFromId(t,U[e+"ref"]||e),a=(G+("x"===e?0:90))*Math.PI/180,o=y*Math.abs(Math.cos(a))+b*Math.abs(Math.sin(a)),s=U[e+"anchor"];if(i){if(!i.autorange&&(U[e]-i.range[0])*(U[e]-i.range[1])>0)return void(x=!0);H[e]=i._offset+i.l2p(U[e]),n=.5}else n=U[e],"y"===e&&(n=1-n),H[e]="x"===e?S.l+S.w*n:S.t+S.h*n;var l=0;l=U.showarrow?U["a"+e]:o*r(n,s),H[e]+=l,U["_"+e+"type"]=i&&i.type,U["_"+e+"size"]=o,U["_"+e+"shift"]=l}),x)return void W.remove();var w,k;U.showarrow&&(w=c.constrain(H.x-U.ax,1,_.width-1),k=c.constrain(H.y-U.ay,1,_.height-1)),H.x=c.constrain(H.x,1,_.width-1),H.y=c.constrain(H.y,1,_.height-1);var A=$-s.top,M=$-s.left;i?n.select("svg").attr({x:$-1,y:$}):(tt.attr({x:M,y:A}),tt.selectAll("tspan.line").attr({y:A,x:M})),Q.call(h.setRect,Z/2,Z/2,y-Z,b-Z);var T=Math.round(H.x-y/2),E=Math.round(H.y-b/2);W.call(c.setTranslate,T,E);var L="annotations["+e+"]",C=function(r,n){o.select(t).selectAll('.annotation-arrow-g[data-index="'+e+'"]').remove();var i=H.x+r,s=H.y+n,u=c.rotationXYMatrix(G,i,s),h=c.apply2DTransform(u),d=c.apply2DTransform2(u),p=Q.attr("width")/2,m=Q.attr("height")/2,y=[[i-p,s-m,i-p,s+m],[i-p,s+m,i+p,s+m],[i+p,s+m,i+p,s-m],[i+p,s-m,i-p,s-m]].map(d);if(!y.reduce(function(t,e){return t^!!a(w,k,w+1e6,k+1e6,e[0],e[1],e[2],e[3])},!1)){y.forEach(function(t){var e=a(i,s,w,k,t[0],t[1],t[2],t[3]);e&&(i=e.x,s=e.y)});var b=U.arrowwidth,x=U.arrowcolor,_=Y.append("g").style({opacity:f.opacity(x)}).classed("annotation-arrow-g",!0).attr("data-index",String(e)),A=_.append("path").attr("d","M"+i+","+s+"L"+w+","+k).style("stroke-width",b+"px").call(f.stroke,f.rgb(x));v.arrowhead(A,U.arrowhead,"end",U.arrowsize);var M=_.append("path").classed("annotation",!0).classed("anndrag",!0).attr({"data-index":String(e),d:"M3,3H-3V-3H3ZM0,0L"+(i-w)+","+(s-k),transform:"translate("+w+","+k+")"}).style("stroke-width",b+6+"px").call(f.stroke,"rgba(0,0,0,0)").call(f.fill,"rgba(0,0,0,0)");if(t._context.editable){var T,E,C;g.init({element:M.node(),prepFn:function(){var t=c.getTranslate(W);E=t.x,C=t.y,T={},V&&V.autorange&&(T[V._name+".autorange"]=!0),q&&q.autorange&&(T[q._name+".autorange"]=!0)},moveFn:function(t,e){_.attr("transform","translate("+t+","+e+")");var r=h(E,C),n=r[0]+t,i=r[1]+e;W.call(c.setTranslate,n,i),T[L+".x"]=V?U.x+t/V._m:(w+t-S.l)/S.w,T[L+".y"]=q?U.y+e/q._m:1-(k+e-S.t)/S.h,X.attr({transform:"rotate("+G+","+n+","+i+")"})},doneFn:function(e){if(e){l.relayout(t,T);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}};U.showarrow&&C(0,0);var z=c.rotationXYMatrix(G,H.x,H.y),P=c.apply2DTransform(z);if(t._context.editable){var R,O,I;g.init({element:W.node(),prepFn:function(){var t=c.getTranslate(W);R=t.x,O=t.y,I={}},moveFn:function(t,e){W.call(c.setTranslate,R+t,O+e);var r="pointer";if(U.showarrow)I[L+".ax"]=U.ax+t,I[L+".ay"]=U.ay+e,C(t,e);else{if(V)I[L+".x"]=U.x+t/V._m;else{var n=U._xsize/S.w,i=U.x+U._xshift/S.w-n/2;I[L+".x"]=g.align(i+t/S.w,n,0,1,U.xanchor)}if(q)I[L+".y"]=U.y+e/q._m;else{var a=U._ysize/S.h,o=U.y-U._yshift/S.h-a/2;I[L+".y"]=g.align(o-e/S.h,a,0,1,U.yanchor)}V&&q||(r=g.getCursor(V?.5:I[L+".x"],q?.5:I[L+".y"],U.xanchor,U.yanchor))}var s=P(R,O),l=s[0]+t,u=s[1]+e;W.call(c.setTranslate,R+t,O+e),X.attr({transform:"rotate("+G+","+l+","+u+")"}),p(W,r)},doneFn:function(e){if(p(W),e){l.relayout(t,I);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}var b,x=t.layout,_=t._fullLayout;if(!s(e)||-1===e){if(!e&&Array.isArray(i))return x.annotations=i,v.supplyLayoutDefaults(x,_),void v.drawAll(t);if("remove"===i)return delete x.annotations,_.annotations=[],void v.drawAll(t);if(r&&"add"!==i){for(b=0;b<_.annotations.length;b++)v.draw(t,b,r,i);return}e=_.annotations.length,_.annotations.push({})}if(!r&&i){if("remove"===i){for(_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove(),_.annotations.splice(e,1),x.annotations.splice(e,1),b=e;b<_.annotations.length;b++)_._infolayer.selectAll('.annotation[data-index="'+(b+1)+'"]').attr("data-index",String(b)),v.draw(t,b);return}if("add"===i||c.isPlainObject(i)){_.annotations.splice(e,0,{});var w=c.isPlainObject(i)?c.extendFlat({},i):{text:"New text"};for(x.annotations?x.annotations.splice(e,0,w):x.annotations=[w],b=_.annotations.length-1;b>e;b--)_._infolayer.selectAll('.annotation[data-index="'+(b-1)+'"]').attr("data-index",String(b)),v.draw(t,b)}}_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove();var k=x.annotations[e],A=_.annotations[e];if(k){var M={xref:k.xref,yref:k.yref},T={};"string"==typeof r&&r?T[r]=i:c.isPlainObject(r)&&(T=r);var E=Object.keys(T);for(b=0;bb;b++){var z=C[b];if(void 0===T[z]&&void 0!==k[z]){var P=u.getFromId(t,u.coerceRef(M,{},t,z)),R=u.getFromId(t,u.coerceRef(k,{},t,z)),O=k[z],I=A["_"+z+"type"];if(void 0!==T[z+"ref"]){var N="auto"===k[z+"anchor"],j="x"===z?S.w:S.h,F=(A["_"+z+"size"]||0)/(2*j);if(P&&R)O=(O-P.range[0])/(P.range[1]-P.range[0]),O=R.range[0]+O*(R.range[1]-R.range[0]);else if(P){if(O=(O-P.range[0])/(P.range[1]-P.range[0]),O=P.domain[0]+O*(P.domain[1]-P.domain[0]),N){var D=O+F,B=O-F;2/3>O+B?O=B:O+D>4/3&&(O=D)}}else R&&(N&&(1/3>O?O+=F:O>2/3&&(O-=F)),O=(O-R.domain[0])/(R.domain[1]-R.domain[0]),O=R.range[0]+O*(R.range[1]-R.range[0]))}R&&R===P&&I&&("log"===I&&"log"!==R.type?O=Math.pow(10,O):"log"!==I&&"log"===R.type&&(O=O>0?Math.log(O)/Math.LN10:void 0)),k[z]=O}}var U=n(k,_);_.annotations[e]=U;var V=u.getFromId(t,U.xref),q=u.getFromId(t,U.yref),H={x:0,y:0},G=+U.textangle||0,Y=_._infolayer.append("g").classed("annotation",!0).attr("data-index",String(e)).style("opacity",U.opacity).on("click",function(){t._dragging=!1,t.emit("plotly_clickannotation",{index:e,annotation:k,fullAnnotation:U})}),X=Y.append("g").classed("annotation-text-g",!0).attr("data-index",String(e)),W=X.append("g"),Z=U.borderwidth,K=U.borderpad,$=Z+K,Q=W.append("rect").attr("class","bg").style("stroke-width",Z+"px").call(f.stroke,U.bordercolor).call(f.fill,U.bgcolor),J=U.font,tt=W.append("text").classed("annotation",!0).attr("data-unformatted",U.text).text(U.text);t._context.editable?tt.call(d.makeEditable,W).call(m).on("edit",function(r){U.text=r,this.attr({"data-unformatted":U.text}),this.call(m);var n={};n["annotations["+e+"].text"]=U.text,V&&V.autorange&&(n[V._name+".autorange"]=!0),q&&q.autorange&&(n[q._name+".autorange"]=!0),l.relayout(t,n)}):tt.call(m),X.attr({transform:"rotate("+G+","+H.x+","+H.y+")"}).call(h.setPosition,H.x,H.y)}},v.arrowhead=function(t,e,r,n){s(n)||(n=1);var i=t.node(),a=v.ARROWPATHS[e||0];if(a){"string"==typeof r&&r||(r="end");var l,c,u,d,p=(h.getPx(t,"stroke-width")||1)*n,g=t.style("stroke")||f.defaultLine,m=t.style("stroke-opacity")||1,y=r.indexOf("start")>=0,b=r.indexOf("end")>=0,x=a.backoff*p;if("line"===i.nodeName){if(l={x:+t.attr("x1"),y:+t.attr("y1")},c={x:+t.attr("x2"),y:+t.attr("y2")},u=Math.atan2(l.y-c.y,l.x-c.x),d=u+Math.PI,x){var _=x*Math.cos(u),w=x*Math.sin(u);y&&(l.x-=_,l.y-=w,t.attr({x1:l.x,y1:l.y})),b&&(c.x+=_,c.y+=w,t.attr({x2:c.x,y2:c.y}))}}else if("path"===i.nodeName){var k=i.getTotalLength(),A="";if(y){var M=i.getPointAtLength(0),T=i.getPointAtLength(.1);u=Math.atan2(M.y-T.y,M.x-T.x),l=i.getPointAtLength(Math.min(x,k)),x&&(A="0px,"+x+"px,")}if(b){var E=i.getPointAtLength(k),L=i.getPointAtLength(k-.1);if(d=Math.atan2(E.y-L.y,E.x-L.x),c=i.getPointAtLength(Math.max(0,k-x)),x){var S=A?2*x:x;A+=k-S+"px,"+k+"px"}}else A&&(A+=k+"px");A&&t.style("stroke-dasharray",A)}var C=function(r,n){e>5&&(n=0),o.select(i.parentElement).append("path").attr({"class":t.attr("class"),d:a.path,transform:"translate("+r.x+","+r.y+")rotate("+180*n/Math.PI+")scale("+p+")"}).style({fill:g,opacity:m,"stroke-width":0})};y&&C(l,u),b&&C(c,d)}},v.calcAutorange=function(t){var e=t._fullLayout,r=e.annotations;if(r.length&&t._fullData.length){var n={};r.forEach(function(t){n[t.xref]=!0,n[t.yref]=!0});var a=u.list(t).filter(function(t){return t.autorange&&n[t._id]});if(a.length)return c.syncOrAsync([v.drawAll,i],t)}}},{"../../lib":382,"../../lib/setcursor":391,"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/cartesian/axes":405,"../color":303,"../dragelement":324,"../drawing":326,"./arrow_paths":299,"./attributes":300,d3:113,"fast-isnumeric":117}],302:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.lightFraction=1e3/11},{}],303:[function(t,e,r){"use strict";function n(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}var i=t("tinycolor2"),a=t("fast-isnumeric"),o=e.exports={},s=t("./attributes");o.defaults=s.defaults,o.defaultLine=s.defaultLine,o.lightLine=s.lightLine,o.background=s.background,o.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},o.rgb=function(t){return o.tinyRGB(i(t))},o.opacity=function(t){return t?i(t).getAlpha():0},o.addOpacity=function(t,e){var r=i(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},o.combine=function(t,e){var r=i(t).toRgb();if(1===r.a)return i(t).toRgbString();var n=i(e||o.background).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},s={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return i(s).toRgbString()},o.stroke=function(t,e){var r=i(e);t.style({stroke:o.tinyRGB(r),"stroke-opacity":r.getAlpha()})},o.fill=function(t,e){var r=i(e);t.style({fill:o.tinyRGB(r),"fill-opacity":r.getAlpha()})},o.clean=function(t){if(t&&"object"==typeof t){var e,r,i,a,s=Object.keys(t);for(e=0;el&&(a[1]-=(ot-l)/2)):r.node()&&!r.classed("js-placeholder")&&(ot=h.bBox(e.node()).height),ot){if(ot+=5,"top"===x.titleside)Q.domain[1]-=ot/M.h,a[1]*=-1;else{Q.domain[0]+=ot/M.h;var u=Math.max(1,r.selectAll("tspan.line").size());a[1]+=(1-u)*l}e.attr("transform","translate("+a+")"),Q.setScale()}}it.selectAll(".cbfills,.cblines,.cbaxis").attr("transform","translate(0,"+Math.round(M.h*(1-Q.domain[1]))+")");var f=it.select(".cbfills").selectAll("rect.cbfill").data(S);f.enter().append("rect").classed("cbfill",!0).style("stroke","none"),f.exit().remove(),f.each(function(t,e){var r=[0===e?E[0]:(S[e]+S[e-1])/2,e===S.length-1?E[1]:(S[e]+S[e+1])/2].map(Q.c2p).map(Math.round);e!==S.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=z(t).replace("e-",""),o=i(a).toHexString();n.select(this).attr({x:Y,width:Math.max(D,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var d=it.select(".cblines").selectAll("path.cbline").data(x.line.color&&x.line.width?L:[]);return d.enter().append("path").classed("cbline",!0),d.exit().remove(),d.each(function(t){n.select(this).attr("d","M"+Y+","+(Math.round(Q.c2p(t))+x.line.width/2%1)+"h"+D).call(h.lineGroupStyle,x.line.width,C(t),x.line.dash)}),Q._axislayer.selectAll("g."+Q._id+"tick,path").remove(),Q._pos=Y+D+(x.outlinewidth||0)/2-("outside"===x.ticks?1:0),Q.side="right",c.syncOrAsync([function(){return s.doTicks(t,Q,!0)},function(){if(-1===["top","bottom"].indexOf(x.titleside)){var e=Q.titlefont.size,r=Q._offset+Q._length/2,i=M.l+(Q.position||0)*M.w+("right"===Q.side?10+e*(Q.showticklabels?1:.5):-10-e*(Q.showticklabels?.5:0));w("h"+Q._id+"title",{avoid:{selection:n.select(t).selectAll("g."+Q._id+"tick"),side:x.titleside,offsetLeft:M.l,offsetTop:M.t,maxShift:A.width},attributes:{x:i,y:r,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])}function w(e,r){var n,i=b();n=o.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var a={propContainer:Q,propName:n,traceIndex:i.index,dfltName:"colorscale",containerGroup:it.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;it.selectAll("."+s+",."+s+"-math-group").remove(),p.draw(t,e,u(a,r||{}))}function k(){var r=D+x.outlinewidth/2+h.bBox(Q._axislayer.node()).width;if(N=at.select("text"),N.node()&&!N.classed("js-placeholder")){var n,i=at.select(".h"+Q._id+"title-math-group").node();n=i&&-1!==["top","bottom"].indexOf(x.titleside)?h.bBox(i).width:h.bBox(at.node()).right-Y-M.l,r=Math.max(r,n)}var a=2*x.xpad+r+x.borderwidth+x.outlinewidth/2,s=Z-K;it.select(".cbbg").attr({x:Y-x.xpad-(x.borderwidth+x.outlinewidth)/2,y:K-H,width:Math.max(a,2),height:Math.max(s+2*H,2)}).call(d.fill,x.bgcolor).call(d.stroke,x.bordercolor).style({"stroke-width":x.borderwidth}),it.selectAll(".cboutline").attr({x:Y,y:K+x.ypad+("top"===x.titleside?ot:0),width:Math.max(D,2),height:Math.max(s-2*x.ypad-ot,2)}).call(d.stroke,x.outlinecolor).style({fill:"None","stroke-width":x.outlinewidth});var l=({center:.5,right:1}[x.xanchor]||0)*a;it.attr("transform","translate("+(M.l-l)+","+M.t+")"),o.autoMargin(t,e,{x:x.x,y:x.y,l:a*({right:1,center:.5}[x.xanchor]||0),r:a*({left:1,center:.5}[x.xanchor]||0),t:s*({bottom:1,middle:.5}[x.yanchor]||0),b:s*({top:1,middle:.5}[x.yanchor]||0)})}var A=t._fullLayout,M=A._size;if("function"!=typeof x.fillcolor&&"function"!=typeof x.line.color)return void A._infolayer.selectAll("g."+e).remove();var T,E=n.extent(("function"==typeof x.fillcolor?x.fillcolor:x.line.color).domain()),L=[],S=[],C="function"==typeof x.line.color?x.line.color:function(){return x.line.color},z="function"==typeof x.fillcolor?x.fillcolor:function(){return x.fillcolor},P=x.levels.end+x.levels.size/100,R=x.levels.size,O=1.001*E[0]-.001*E[1],I=1.001*E[1]-.001*E[0];for(T=x.levels.start;0>(T-P)*R;T+=R)T>O&&I>T&&L.push(T);if("function"==typeof x.fillcolor)if(x.filllevels)for(P=x.filllevels.end+x.filllevels.size/100,R=x.filllevels.size,T=x.filllevels.start;0>(T-P)*R;T+=R)T>E[0]&&T1){var nt=Math.pow(10,Math.floor(Math.log(rt)/Math.LN10));tt*=nt*c.roundUp(rt/nt,[2,5,10]),(Math.abs(x.levels.start)/x.levels.size+1e-6)%1<2e-6&&(Q.tick0=0)}Q.dtick=tt}Q.domain=[W+G,W+V-G],Q.setScale();var it=A._infolayer.selectAll("g."+e).data([0]);it.enter().append("g").classed(e,!0).each(function(){var t=n.select(this);t.append("rect").classed("cbbg",!0),t.append("g").classed("cbfills",!0),t.append("g").classed("cblines",!0),t.append("g").classed("cbaxis",!0).classed("crisp",!0),t.append("g").classed("cbtitleunshift",!0).append("g").classed("cbtitle",!0),t.append("rect").classed("cboutline",!0),t.select(".cbtitle").datum(0)}),it.attr("transform","translate("+Math.round(M.l)+","+Math.round(M.t)+")");var at=it.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(M.l)+",-"+Math.round(M.t)+")");Q._axislayer=it.select(".cbaxis");var ot=0;if(-1!==["top","bottom"].indexOf(x.titleside)){var st,lt=M.l+(x.x+q)*M.w,ct=Q.titlefont.size;st="top"===x.titleside?(1-(W+V-G))*M.h+M.t+3+.75*ct:(1-(W+G))*M.h+M.t-3-.25*ct,w(Q._id+"title",{attributes:{x:lt,y:st,"text-anchor":"start"}})}var ut=c.syncOrAsync([o.previousPromises,_,o.previousPromises,k],t);if(ut&&ut.then&&(t._promises||[]).push(ut),t._context.editable){var ft,ht,dt;l.init({element:it.node(),prepFn:function(){ft=it.attr("transform"),f(it)},moveFn:function(t,e){it.attr("transform",ft+" translate("+t+","+e+")"),ht=l.align(X+t/M.w,B,0,1,x.xanchor),dt=l.align(W-e/M.h,V,0,1,x.yanchor);var r=l.getCursor(ht,dt,x.xanchor,x.yanchor);f(it,r)},doneFn:function(e){f(it),e&&void 0!==ht&&void 0!==dt&&a.restyle(t,{"colorbar.x":ht,"colorbar.y":dt},b().index)}})}return ut}function b(){var r,n,i=e.substr(2);for(r=0;ru*f?i.RdBu:u>=0?i.Reds:i.Blues,l.colorscale=h,s.reversescale&&(h=a(h)),s.colorscale=h)}},{"../../lib":382,"./flip_scale":314,"./scales":321}],311:[function(t,e,r){"use strict";var n=t("./attributes"),i=t("../../lib/extend").extendDeep;e.exports=function(t){return{color:{valType:"color",arrayOk:!0},colorscale:i({},n.colorscale,{}),cauto:i({},n.zauto,{}),cmax:i({},n.zmax,{}),cmin:i({},n.zmin,{}),autocolorscale:i({},n.autocolorscale,{}),reversescale:i({},n.reversescale,{})}}},{"../../lib/extend":377,"./attributes":309}],312:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":321}],313:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./is_valid_scale"),l=t("./flip_scale");e.exports=function(t,e,r,c,u){var f=u.prefix,h=u.cLetter,d=f.slice(0,f.length-1),p=f?i.nestedProperty(t,d).get()||{}:t,g=f?i.nestedProperty(e,d).get()||{}:e,v=p[h+"min"],m=p[h+"max"],y=p.colorscale,b=n(v)&&n(m)&&m>v;c(f+h+"auto",!b),c(f+h+"min"),c(f+h+"max");var x;void 0!==y&&(x=!s(y)),c(f+"autocolorscale",x);var _=c(f+"colorscale"),w=c(f+"reversescale");if(w&&(g.colorscale=l(_)),"marker.line."!==f){var k;f&&(k=a(p));var A=c(f+"showscale",k);A&&o(p,g,r)}}},{"../../lib":382,"../colorbar/defaults":305,"../colorbar/has_colorbar":307,"./flip_scale":314,"./is_valid_scale":318,"fast-isnumeric":117}],314:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n}},{}],315:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./default_scale"),a=t("./is_valid_scale_array");e.exports=function(t,e){function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return e||(e=i),t?("string"==typeof t&&(r(),"string"==typeof t&&r()),a(t)?t:e):e}},{"./default_scale":312,"./is_valid_scale_array":319,"./scales":321}],316:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("./is_valid_scale");e.exports=function(t,e){var r=e?i.nestedProperty(t,e).get()||{}:t,o=r.color,s=!1;if(Array.isArray(o))for(var l=0;lh;h++)l=t[h],u[h]=e+l[0]*(r-e),f[h]=i(l[1]).toRgb();var d=n.scale.linear().domain(u).interpolate(n.interpolateObject).range(f);return function(t){if(a(t)){var n=o.constrain(t,e,r),l=d(n);return i(l).toRgbString()}return i(t).isValid()?t:s.defaultLine}}},{"../../lib":382,"../color":303,d3:113,"fast-isnumeric":117,tinycolor2:274}],321:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]]}},{}],322:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=(t-r)/(n-r),o=a+e/(n-r),s=(a+o)/2;return"left"===i||"bottom"===i?a:"center"===i||"middle"===i?s:"right"===i||"top"===i?o:2/3-s>a?a:o>4/3-s?o:s}},{}],323:[function(t,e,r){"use strict";var n=t("../../lib"),i=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,a){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===a?0:"middle"===a?1:"top"===a?2:n.constrain(Math.floor(3*e),0,2),i[e][t]}},{"../../lib":382}],324:[function(t,e,r){"use strict";function n(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function i(t){t._dragging=!1,t._replotPending&&a.plot(t)}var a=t("../../plotly"),o=t("../../lib"),s=t("../../plots/cartesian/constants"),l=e.exports={};l.align=t("./align"),l.getCursor=t("./cursor");var c=t("./unhover");l.unhover=c.wrapped,l.unhoverRaw=c.raw,l.init=function(t){function e(e){return p._dragged=!1,p._dragging=!0,c=e.clientX,u=e.clientY,d=e.target,f=(new Date).getTime(),f-p._mouseDownTimev&&(g=Math.max(g-1,1)),t.doneFn&&t.doneFn(p._dragged,g),!p._dragged){var r=document.createEvent("MouseEvents");r.initEvent("click",!0,!0),d.dispatchEvent(r)}return i(p),p._dragged=!1,o.pauseEvent(e)}var c,u,f,h,d,p=o.getPlotDiv(t.element)||{},g=1,v=s.DBLCLICKDELAY;p._mouseDownTime||(p._mouseDownTime=0),t.element.onmousedown=e,t.element.style.pointerEvents="all"}},{"../../lib":382,"../../plotly":402,"../../plots/cartesian/constants":410,"./align":322,"./cursor":323,"./unhover":325}],325:[function(t,e,r){"use strict";var n=t("../../lib/events"),i=e.exports={};i.wrapped=function(t,e,r){"string"==typeof t&&(t=document.getElementById(t)),t._hoverTimer&&(clearTimeout(t._hoverTimer),t._hoverTimer=void 0),i.raw(t,e,r)},i.raw=function(t,e){var r=t._fullLayout;e||(e={}),e.target&&n.triggerHandler(t,"plotly_beforehover",e)===!1||(r._hoverlayer.selectAll("g").remove(),e.target&&t._hoverdata&&t.emit("plotly_unhover",{points:t._hoverdata}),t._hoverdata=void 0)}},{"../../lib/events":376}],326:[function(t,e,r){"use strict";function n(t,e,r,n){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],c=Math.pow(a*a+o*o,x/2),u=Math.pow(s*s+l*l,x/2),f=(u*u*a-c*c*s)*n,h=(u*u*o-c*c*l)*n,d=3*u*(c+u),p=3*c*(c+u);return[[i.round(e[0]+(d&&f/d),2),i.round(e[1]+(d&&h/d),2)],[i.round(e[0]-(p&&f/p),2),i.round(e[1]-(p&&h/p),2)]]}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../plots/plots"),s=t("../color"),l=t("../colorscale"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),h=t("../../traces/scatter/subtypes"),d=t("../../traces/scatter/make_bubble_size_func"),p=e.exports={};p.font=function(t,e,r,n){e&&e.family&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(s.fill,n)},p.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},p.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},p.setRect=function(t,e,r,n,i){t.call(p.setPosition,e,r).call(p.setSize,n,i)},p.translatePoints=function(t,e,r){t.each(function(t){var n=t.xp||e.c2p(t.x),o=t.yp||r.c2p(t.y),s=i.select(this);a(n)&&a(o)?"text"===this.nodeName?s.attr("x",n).attr("y",o):s.attr("transform","translate("+n+","+o+")"):s.remove()})},p.getPx=function(t,e){return Number(t.style(e).replace(/px$/,""))},p.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:1>e?1:Math.round(e):r||0},p.lineGroupStyle=function(t,e,r,n){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,l=n||a.dash||"";i.select(this).call(s.stroke,r||a.color).call(p.dashLine,l,o)})},p.dashLine=function(t,e,r){var n=Math.max(r,3);"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},p.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=i.select(this);try{r.call(s.fill,e[0].trace.fillcolor)}catch(n){c.error(n,t),r.remove()}})};var g=t("./symbol_defs");p.symbolNames=[],p.symbolFuncs=[],p.symbolNeedLines={},p.symbolNoDot={},p.symbolList=[],Object.keys(g).forEach(function(t){var e=g[t];p.symbolList=p.symbolList.concat([e.n,t,e.n+100,t+"-open"]),p.symbolNames[e.n]=t,p.symbolFuncs[e.n]=e.f,e.needLine&&(p.symbolNeedLines[e.n]=!0),e.noDot?p.symbolNoDot[e.n]=!0:p.symbolList=p.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"])});var v=p.symbolNames.length,m="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";p.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),t=p.symbolNames.indexOf(t),t>=0&&(t+=e)}return t%100>=v||t>=400?0:Math.floor(Math.max(t,0))},p.pointStyle=function(t,e){if(t.size()){var r=e.marker,n=r.line;if(o.traceIs(e,"symbols")){var a=d(e);t.attr("d",function(t){var n;n="various"===t.ms||"various"===r.size?3:h.isBubble(e)?a(t.ms):(r.size||6)/2,t.mrc=n;var i=p.symbolNumber(t.mx||r.symbol)||0,o=i%100;return t.om=i%200>=100,p.symbolFuncs[o](n)+(i>=200?m:"")}).style("opacity",function(t){return(t.mo+1||r.opacity+1)-1})}var l=(e._input||{}).marker||{},c=p.tryColorscale(r,l,""),u=p.tryColorscale(r,l,"line.");t.each(function(t){var e,a,o;t.so?(o=n.outlierwidth,a=n.outliercolor,e=r.outliercolor):(o=(t.mlw+1||n.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,a="mlc"in t?t.mlcc=u(t.mlc):Array.isArray(n.color)?s.defaultLine:n.color,e="mc"in t?t.mcc=c(t.mc):Array.isArray(r.color)?s.defaultLine:r.color||"rgba(0,0,0,0)");var l=i.select(this);t.om?l.call(s.stroke,e).style({"stroke-width":(o||1)+"px",fill:"none"}):(l.style("stroke-width",o+"px").call(s.fill,e),o&&l.call(s.stroke,a))})}},p.tryColorscale=function(t,e,r){var n=c.nestedProperty(t,r+"color").get(),i=c.nestedProperty(t,r+"colorscale").get(),o=c.nestedProperty(t,r+"cauto").get(),s=c.nestedProperty(t,r+"cmin"),u=c.nestedProperty(t,r+"cmax"),f=s.get(),h=u.get();return i&&Array.isArray(n)?(!o&&a(f)&&a(h)||(f=1/0,h=-(1/0),n.forEach(function(t){a(t)&&(f>t&&(f=+t),t>h&&(h=+t))}),f>h&&(f=0,h=1),s.set(f),u.set(h),c.nestedProperty(e,r+"cmin").set(f),c.nestedProperty(e,r+"cmax").set(h)),l.makeScaleFunction(i,f,h)):c.identity};var y={start:1,end:-1,middle:0,bottom:1,top:-1},b=1.3;p.textPointStyle=function(t,e){t.each(function(t){var r=i.select(this),n=t.tx||e.text;if(!n||Array.isArray(n))return void r.remove();var o=t.tp||e.textposition,s=-1!==o.indexOf("top")?"top":-1!==o.indexOf("bottom")?"bottom":"middle",l=-1!==o.indexOf("left")?"end":-1!==o.indexOf("right")?"start":"middle",c=t.ts||e.textfont.size,f=t.mrc?t.mrc/.8+1:0;c=a(c)&&c>0?c:0,r.call(p.font,t.tf||e.textfont.family,c,t.tc||e.textfont.color).attr("text-anchor",l).text(n).call(u.convertToTspans);var h=i.select(this.parentNode),d=r.selectAll("tspan.line"),g=((d[0].length||1)-1)*b+1,v=y[l]*f,m=.75*c+y[s]*f+(y[s]-1)*g*c/2;h.attr("transform","translate("+v+","+m+")"),g>1&&d.attr({x:r.attr("x"),y:r.attr("y")})})};var x=.5;p.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,i="M"+t[0],a=[];for(r=1;rr;r++)o.push(n(t[r-1],t[r],t[r+1],e));for(o.push(n(t[a-1],t[a],t[0],e)),r=1;a>=r;r++)i+="C"+o[r-1][1]+" "+o[r][0]+" "+t[r];return i+="C"+o[a][1]+" "+o[0][0]+" "+t[0]+"Z"};var _={hv:function(t,e){return"H"+i.round(e[0],2)+"V"+i.round(e[1],2)},vh:function(t,e){return"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},hvh:function(t,e){return"H"+i.round((t[0]+e[0])/2,2)+"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},vhv:function(t,e){return"V"+i.round((t[1]+e[1])/2,2)+"H"+i.round(e[0],2)+"V"+i.round(e[1],2)}},w=function(t,e){return"L"+i.round(e[0],2)+","+i.round(e[1],2)};p.steps=function(t){var e=_[t]||w;return function(t){for(var r="M"+i.round(t[0][0],2)+","+i.round(t[0][1],2),n=1;n=A&&(i.selectAll("[data-bb]").attr("data-bb",null),k=[]),t.setAttribute("data-bb",k.length),k.push(l),c.extendFlat({},l)},p.setClipUrl=function(t,e){if(!e)return void t.attr("clip-path",null);var r="#"+e,n=i.select("base");n.size()&&n.attr("href")&&(r=window.location.href+r),t.attr("clip-path","url("+r+")")}},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../../lib/svg_text_utils":395,"../../plots/plots":454,"../../traces/scatter/make_bubble_size_func":569,"../../traces/scatter/subtypes":575,"../color":303,"../colorscale":317,"./symbol_defs":327,d3:113,"fast-isnumeric":117}],327:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+","+r+"H"+e+"L0,-"+i+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+",-"+r+"H"+e+"L0,"+i+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M"+r+",-"+e+"V"+e+"L-"+i+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+r+",-"+e+"V"+e+"L"+i+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(t*-.309,2),o=n.round(.809*t,2);return"M"+e+","+a+"L"+r+","+o+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(e*-.309,2),c=n.round(.118*e,2),u=n.round(.809*e,2),f=n.round(.382*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+c+"L"+o+","+u+"L0,"+f+"L-"+o+","+u+"L-"+a+","+c+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0}}},{d3:113}],328:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"]},symmetric:{valType:"boolean"},array:{valType:"data_array"},arrayminus:{valType:"data_array"},value:{valType:"number",min:0,dflt:10},valueminus:{valType:"number",min:0,dflt:10},traceref:{valType:"integer",min:0,dflt:0},tracerefminus:{valType:"integer",min:0,dflt:0},copy_ystyle:{valType:"boolean"},copy_zstyle:{valType:"boolean"},color:{valType:"color"},thickness:{valType:"number",min:0,dflt:2},width:{valType:"number",min:0},_deprecated:{opacity:{valType:"number"}}}},{}],329:[function(t,e,r){"use strict";function n(t,e,r,n){var a=e["error_"+n]||{},l=a.visible&&-1!==["linear","log"].indexOf(r.type),c=[];if(l){for(var u=s(a),f=0;fs;s++)o[s]={x:r[s],y:i[s]};return o[0].trace=t,n.calc({calcdata:[o],_fullLayout:e}),o},n.plot=t("./plot"),n.style=t("./style"),n.hoverInfo=function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys)),(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}},{"./attributes":328,"./calc":329,"./defaults":331,"./plot":333,"./style":334}],333:[function(t,e,r){"use strict";function n(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../lib"),s=t("../../traces/scatter/subtypes");e.exports=function(t,e){var r=e.x(),l=e.y();t.each(function(t){var e=t[0].trace,c=e.error_x||{},u=e.error_y||{},f=s.hasMarkers(e)&&e.marker.maxdisplayed>0;if(u.visible||c.visible){var h=i.select(this).selectAll("g.errorbar").data(o.identity);h.enter().append("g").classed("errorbar",!0),h.each(function(t){var e=i.select(this),o=n(t,r,l);if(!f||t.vis){var s;if(u.visible&&a(o.x)&&a(o.yh)&&a(o.ys)){var h=u.width;s="M"+(o.x-h)+","+o.yh+"h"+2*h+"m-"+h+",0V"+o.ys,o.noYS||(s+="m-"+h+",0h"+2*h),e.append("path").classed("yerror",!0).attr("d",s)}if(c.visible&&a(o.y)&&a(o.xh)&&a(o.xs)){var d=(c.copy_ystyle?u:c).width;s="M"+o.xh+","+(o.y-d)+"v"+2*d+"m0,-"+d+"H"+o.xs,o.noXS||(s+="m0,-"+d+"v"+2*d),e.append("path").classed("xerror",!0).attr("d",s)}}})}})}},{"../../lib":382,"../../traces/scatter/subtypes":575,d3:113,"fast-isnumeric":117}],334:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(i.stroke,r.color),a.copy_ystyle&&(a=r),o.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(i.stroke,a.color)})}},{"../color":303,d3:113}],335:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants");e.exports={_isLinkedToArray:!0,source:{valType:"string"},layer:{valType:"enumerated",values:["below","above"],dflt:"above"},sizex:{valType:"number",dflt:0},sizey:{valType:"number",dflt:0},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain"},opacity:{valType:"number",min:0,max:1,dflt:1},x:{valType:"number",dflt:0},y:{valType:"number",dflt:0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper"}}},{"../../plots/cartesian/constants":410}],336:[function(t,e,r){"use strict";function n(t,e,r){function n(r,n){return a.coerce(t,e,o,r,n)}e=e||{},n("source"),n("layer"),n("x"),n("y"),n("xanchor"),n("yanchor"),n("sizex"),n("sizey"),n("sizing"),n("opacity");for(var s=0;2>s;s++){var l={_fullLayout:r},c=["x","y"][s];i.coerceRef(t,e,l,c,"paper")}return e}var i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./attributes");e.exports=function(t,e){if(t.images&&Array.isArray(t.images))for(var r=t.images,i=e.images=[],a=0;a=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],340:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat;e.exports={bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.defaultLine},borderwidth:{valType:"number",min:0,dflt:0},font:a({},n,{}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"]},tracegroupgap:{valType:"number",min:0,dflt:10},x:{valType:"number",min:-2,max:3,dflt:1.02},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"}}},{"../../lib/extend":377,"../../plots/font_attributes":423,"../color/attributes":302}],341:[function(t,e,r){"use strict";e.exports={scrollBarWidth:4,scrollBarHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],342:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/plots"),a=t("./attributes"),o=t("./helpers");e.exports=function(t,e,r){function s(t,e){return n.coerce(h,d,a,t,e)}for(var l,c,u,f,h=t.legend||{},d=e.legend={},p=0,g="normal",v=0;v1);if(y!==!1){if(s("bgcolor",e.paper_bgcolor),s("bordercolor"),s("borderwidth"),n.coerceFont(s,"font",e.font),s("orientation"),"h"===d.orientation){var b=t.xaxis;b&&b.rangeslider&&b.rangeslider.visible?(l=0,u="left",c=1.1,f="bottom"):(l=0,u="left",c=-.1,f="top")}s("traceorder",g),o.isGrouped(e.legend)&&s("tracegroupgap"),s("x",l),s("xanchor",u),s("y",c),s("yanchor",f),n.noneOrAll(h,d,["x","y"])}}},{"../../lib":382,"../../plots/plots":454,"./attributes":340,"./helpers":345}],343:[function(t,e,r){"use strict";function n(t,e){function r(r){u.util.convertToTspans(r,function(){r.selectAll("tspan.line").attr({x:r.attr("x")}),t.call(a,e)})}var n=t.data()[0][0],i=e._fullLayout,o=n.trace,s=h.traceIs(o,"pie"),l=o.index,c=s?n.label:o.name,f=t.selectAll("text.legendtext").data([0]);f.enter().append("text").classed("legendtext",!0),f.attr({x:40,y:0,"data-unformatted":c}).style("text-anchor","start").classed("user-select-none",!0).call(p.font,i.legend.font).text(c),e._context.editable&&!s?f.call(u.util.makeEditable).call(r).on("edit",function(t){this.attr({"data-unformatted":t}),this.text(t).call(r),this.text()||(t=" "),u.restyle(e,"name",t,l)}):f.call(r)}function i(t,e){var r=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(g.fill,"rgba(0,0,0,0)"),n.on("click",function(){if(!e._dragged){var n,i,a=t.data()[0][0],o=e._fullData,s=a.trace,l=s.legendgroup,c=[];if(h.traceIs(s,"pie")){var f=a.label,d=r.indexOf(f);-1===d?r.push(f):r.splice(d,1),u.relayout(e,"hiddenlabels",r)}else{if(""===l)c=[s.index];else for(var p=0;ptspan"),d=h[0].length||1;r=l*d,n=u.node()&&p.bBox(u.node()).width;var g=l*(.3+(1-d)/2);u.attr("y",g),h.attr("y",g)}r=Math.max(r,16)+3,a.attr({x:0,y:-r/2,height:r}),i.height=r,i.width=n}function o(t,e,r){var n=t._fullLayout,i=n.legend,a=i.borderwidth,o=b.isGrouped(i);if(b.isVertical(i))o&&e.each(function(t,e){f.setTranslate(this,0,e*i.tracegroupgap)}),i.width=0,i.height=0,r.each(function(t){var e=t[0],r=e.height,n=e.width;f.setTranslate(this,a,5+a+i.height+r/2),i.height+=r,i.width=Math.max(i.width,n)}),i.width+=45+2*a,i.height+=10+2*a,o&&(i.height+=(i._lgroupsLength-1)*i.tracegroupgap),r.selectAll(".legendtoggle").attr("width",(t._context.editable?0:i.width)+40),i.width=Math.ceil(i.width),i.height=Math.ceil(i.height);else if(o){i.width=0,i.height=0;for(var s=[i.width],l=e.data(),u=0,h=l.length;h>u;u++){var d=l[u].map(function(t){return t[0].width}),p=40+Math.max.apply(null,d);i.width+=i.tracegroupgap+p,s.push(i.width)}e.each(function(t,e){f.setTranslate(this,s[e],0)}),e.each(function(){var t=c.select(this),e=t.selectAll("g.traces"),r=0;e.each(function(t){var e=t[0],n=e.height;f.setTranslate(this,0,5+a+r+n/2),r+=n}),i.height=Math.max(i.height,r)}),i.height+=10+2*a,i.width+=2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}else i.width=0,i.height=0,r.each(function(t){var e=t[0],r=40+e.width,n=i.tracegroupgap||5;f.setTranslate(this,a+i.width,5+a+e.height/2),i.width+=n+r,i.height=Math.max(i.height,e.height)}),i.width+=2*a,i.height+=10+2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}function s(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center");var i="top";x.isBottomAnchor(r)?i="bottom":x.isMiddleAnchor(r)&&(i="middle"),h.autoMargin(t,"legend",{x:r.x,y:r.y,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:r.height*({top:1,middle:.5}[i]||0),t:r.height*({bottom:1,middle:.5}[i]||0)})}function l(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center"),h.autoMargin(t,"legend",{x:r.x,y:.5,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:0,t:0})}var c=t("d3"),u=t("../../plotly"),f=t("../../lib"),h=t("../../plots/plots"),d=t("../dragelement"),p=t("../drawing"),g=t("../color"),v=t("./constants"),m=t("./get_legend_data"),y=t("./style"),b=t("./helpers"),x=t("./anchor_utils");e.exports=function(t){function e(t,e){T.attr("data-scroll",e).call(f.setTranslate,0,e),E.call(p.setRect,F,t,v.scrollBarWidth,v.scrollBarHeight),A.select("rect").attr({y:b.borderwidth-e})}var r=t._fullLayout,a="legend"+r._uid;if(r._infolayer&&t.calcdata){var b=r.legend,_=r.showlegend&&m(t.calcdata,b),w=r.hiddenlabels||[];if(!r.showlegend||!_.length)return r._infolayer.selectAll(".legend").remove(),r._topdefs.select("#"+a).remove(),void h.autoMargin(t,"legend");var k=r._infolayer.selectAll("g.legend").data([0]);k.enter().append("g").attr({"class":"legend","pointer-events":"all"});var A=r._topdefs.selectAll("#"+a).data([0]);A.enter().append("clipPath").attr("id",a).append("rect");var M=k.selectAll("rect.bg").data([0]);M.enter().append("rect").attr({"class":"bg","shape-rendering":"crispEdges"}).call(g.stroke,b.bordercolor).call(g.fill,b.bgcolor).style("stroke-width",b.borderwidth+"px");var T=k.selectAll("g.scrollbox").data([0]);T.enter().append("g").attr("class","scrollbox");var E=k.selectAll("rect.scrollbar").data([0]);E.enter().append("rect").attr({"class":"scrollbar",rx:20,ry:2,width:0,height:0}).call(g.fill,"#808BA4");var L=T.selectAll("g.groups").data(_);L.enter().append("g").attr("class","groups"),L.exit().remove();var S=L.selectAll("g.traces").data(f.identity);S.enter().append("g").attr("class","traces"),S.exit().remove(),S.call(y).style("opacity",function(t){var e=t[0].trace;return h.traceIs(e,"pie")?-1!==w.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){c.select(this).call(n,t).call(i,t)});var C=0!==k.enter().size();C&&(o(t,L,S),s(t));var z=0,P=r.width,R=0,O=r.height;o(t,L,S),b.height>O?l(t):s(t);var I=r._size,N=I.l+I.w*b.x,j=I.t+I.h*(1-b.y);x.isRightAnchor(b)?N-=b.width:x.isCenterAnchor(b)&&(N-=b.width/2),x.isBottomAnchor(b)?j-=b.height:x.isMiddleAnchor(b)&&(j-=b.height/2);var F=b.width,D=I.w;F>D?(N=I.l,F=D):(N+F>P&&(N=P-F),z>N&&(N=z),F=Math.min(P-N,b.width));var B=b.height,U=I.h;B>U?(j=I.t,B=U):(j+B>O&&(j=O-B),R>j&&(j=R),B=Math.min(O-j,b.height)),f.setTranslate(k,N,j);var V,q,H=B-v.scrollBarHeight-2*v.scrollBarMargin,G=b.height-B;if(b.height<=B||t._context.staticPlot)M.attr({width:F-b.borderwidth,height:B-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2}),f.setTranslate(T,0,0),A.select("rect").attr({width:F-2*b.borderwidth,height:B-2*b.borderwidth,x:b.borderwidth,y:b.borderwidth}),T.call(p.setClipUrl,a);else{V=v.scrollBarMargin,q=T.attr("data-scroll")||0,M.attr({width:F-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin,height:B-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2}),A.select("rect").attr({width:F-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin,height:B-2*b.borderwidth,x:b.borderwidth,y:b.borderwidth-q}),T.call(p.setClipUrl,a),C&&e(V,q),k.on("wheel",null),k.on("wheel",function(){q=f.constrain(T.attr("data-scroll")-c.event.deltaY/H*G,-G,0),V=v.scrollBarMargin-q/G*H,e(V,q),c.event.preventDefault()}),E.on(".drag",null),T.on(".drag",null);var Y=c.behavior.drag().on("drag",function(){V=f.constrain(c.event.y-v.scrollBarHeight/2,v.scrollBarMargin,v.scrollBarMargin+H),q=-(V-v.scrollBarMargin)/H*G,e(V,q)});E.call(Y),T.call(Y)}if(t._context.editable){var X,W,Z,K;k.classed("cursor-move",!0),d.init({element:k.node(),prepFn:function(){var t=f.getTranslate(k);Z=t.x,K=t.y},moveFn:function(t,e){var r=Z+t,n=K+e;f.setTranslate(k,r,n),X=d.align(r,0,I.l,I.l+I.w,b.xanchor),W=d.align(n,0,I.t+I.h,I.t,b.yanchor)},doneFn:function(e){e&&void 0!==X&&void 0!==W&&u.relayout(t,{"legend.x":X,"legend.y":W})}})}}}},{"../../lib":382,"../../plotly":402,"../../plots/plots":454,"../color":303,"../dragelement":324,"../drawing":326,"./anchor_utils":339,"./constants":341,"./get_legend_data":344,"./helpers":345,"./style":347,d3:113}],344:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("./helpers");e.exports=function(t,e){function r(t,r){if(""!==t&&i.isGrouped(e))-1===l.indexOf(t)?(l.push(t),c=!0,s[t]=[[r]]):s[t].push([r]);else{var n="~~i"+f;l.push(n),s[n]=[[r]],f++}}var a,o,s={},l=[],c=!1,u={},f=0;for(a=0;aa;a++)m=s[l[a]],y[a]=i.isReversed(e)?m.reverse():m;else{for(y=[new Array(b)],a=0;b>a;a++)m=s[l[a]][0],y[0][i.isReversed(e)?b-a-1:a]=m;b=1}return e._lgroupsLength=b,y}},{"../../plots/plots":454,"./helpers":345}],345:[function(t,e,r){"use strict";var n=t("../../plots/plots");r.legendGetsTrace=function(t){return t.visible&&n.traceIs(t,"showLegend")},r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{"../../plots/plots":454}],346:[function(t,e,r){"use strict";var n=e.exports={};n.layoutAttributes=t("./attributes"),n.supplyLayoutDefaults=t("./defaults"),n.draw=t("./draw"),n.style=t("./style")},{"./attributes":340,"./defaults":342,"./draw":343,"./style":347}],347:[function(t,e,r){"use strict";function n(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,n=d.hasLines(e),i=l.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);i.enter().append("path").classed("js-fill",!0),i.exit().remove(),i.attr("d","M5,0h30v6h-30z").call(f.fillGroupStyle);var a=l.select(this).select(".legendlines").selectAll("path").data(n?[t]:[]);a.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),a.exit().remove(),a.call(f.lineGroupStyle)}function i(t){function e(t,e,r){var n=c.nestedProperty(o,t).get(),i=Array.isArray(n)&&e?e(n):n;if(r){if(ir[1])return r[1]}return i}function r(t){return t[0]}var n,i,a=t[0],o=a.trace,s=d.hasMarkers(o),u=d.hasText(o),h=d.hasLines(o);if(s||u||h){var p={},g={};s&&(p.mc=e("marker.color",r),p.mo=e("marker.opacity",c.mean,[.2,1]),p.ms=e("marker.size",c.mean,[2,16]),p.mlc=e("marker.line.color",r),p.mlw=e("marker.line.width",c.mean,[0,5]),g.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),h&&(g.line={width:e("line.width",r,[0,10])}),u&&(p.tx="Aa",p.tp=e("textposition",r),p.ts=10,p.tc=e("textfont.color",r),p.tf=e("textfont.family",r)),n=[c.minExtend(a,p)],i=c.minExtend(o,g)}var v=l.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(s?n:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(f.pointStyle,i),s&&(n[0].mrc=3);var y=v.selectAll("g.pointtext").data(u?n:[]);y.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),y.exit().remove(),y.selectAll("text").call(f.textPointStyle,i)}function a(t){var e=t[0].trace,r=e.marker||{},n=r.line||{},i=l.select(this).select("g.legendpoints").selectAll("path.legendbar").data(u.traceIs(e,"bar")?[t]:[]);i.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),i.exit().remove(),i.each(function(t){var e=(t.mlw+1||n.width+1)-1,i=l.select(this);i.style("stroke-width",e+"px").call(h.fill,t.mc||r.color),e&&i.call(h.stroke,t.mlc||n.color)})}function o(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendbox").data(u.traceIs(e,"box")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(t){var r=(t.lw+1||e.line.width+1)-1,n=l.select(this);n.style("stroke-width",r+"px").call(h.fill,t.fc||e.fillcolor),r&&n.call(h.stroke,t.lc||e.line.color)})}function s(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendpie").data(u.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(p,t[0],e)}var l=t("d3"),c=t("../../lib"),u=t("../../plots/plots"),f=t("../drawing"),h=t("../color"),d=t("../../traces/scatter/subtypes"),p=t("../../traces/pie/style_one");e.exports=function(t){t.each(function(t){var e=l.select(this),r=e.selectAll("g.legendfill").data([t]);r.enter().append("g").classed("legendfill",!0);var n=e.selectAll("g.legendlines").data([t]);n.enter().append("g").classed("legendlines",!0);var i=e.selectAll("g.legendsymbols").data([t]);i.enter().append("g").classed("legendsymbols",!0),i.style("opacity",t[0].trace.opacity),i.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(a).each(o).each(s).each(n).each(i)}},{"../../lib":382,"../../plots/plots":454,"../../traces/pie/style_one":554,"../../traces/scatter/subtypes":575,"../color":303,"../drawing":326,d3:113}],348:[function(t,e,r){"use strict";function n(t,e){var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o={};if("zoom"===n){for(var s,l,u="in"===i?.5:2,h=(1+u)/2,d=(1-u)/2,p=c.Axes.list(t,null,!0),v=0;vy;y++){var b=s[y];h=m[b]={};for(var x=0;x1)return n(["resetViews","toggleHover"]),o(v,r);u&&(n(["zoom3d","pan3d","orbitRotation","tableRotation"]),n(["resetCameraDefault3d","resetCameraLastSave3d"]),n(["hoverClosest3d"])),h&&(n(["zoomInGeo","zoomOutGeo","resetGeo"]),n(["hoverClosestGeo"]));var m=i(s),y=[];return((c||p)&&!m||g)&&(y=["zoom2d","pan2d"]),(c||g)&&a(l)&&(y.push("select2d"),y.push("lasso2d")),y.length&&n(y),!c&&!p||m||g||n(["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]),c&&d?n(["toggleHover"]):p?n(["hoverClosestGl2d"]):c?n(["hoverClosestCartesian","hoverCompareCartesian"]):d&&n(["hoverClosestPie"]),o(v,r)}function i(t){for(var e=l.Axes.list({_fullLayout:t},null,!0),r=!0,n=0;n0);if(h){var d=i(e,r,s);l("x",d[0]),l("y",d[1]),a.noneOrAll(t,e,["x","y"]),l("xanchor"),l("yanchor"),a.coerceFont(l,"font",r.font),l("bgcolor"),l("bordercolor"),l("borderwidth")}}},{"../../lib":382,"./attributes":351,"./button_attributes":352,"./constants":353}],355:[function(t,e,r){"use strict";function n(t){for(var e=m.list(t,"x",!0),r=[],n=0;ne){var r=e;e=t,t=r}s.setAttributes(w,{"data-min":t,"data-max":e}),s.setAttributes(R,{x:t,width:e-t}),s.setAttributes(M,{width:t}),s.setAttributes(T,{x:e,width:p-e}),s.setAttributes(E,{transform:"translate("+(t-v-1)+")"}),s.setAttributes(C,{transform:"translate("+e+")"})}var f=t._fullLayout,h=f._infolayer.selectAll("g.range-slider"),d=f.xaxis.rangeslider,p=f._size.w,g=(f.height-f.margin.b-f.margin.t)*d.thickness,v=2,m=Math.floor(d.borderwidth/2),y=f.margin.l,b=f.height-g-f.margin.b,x=0,_=p,w=document.createElementNS(o,"g");s.setAttributes(w,{"class":"range-slider","data-min":x,"data-max":_,"pointer-events":"all",transform:"translate("+y+","+b+")"});var k=document.createElementNS(o,"rect"),A=d.borderwidth%2===0?d.borderwidth:d.borderwidth-1;s.setAttributes(k,{fill:d.bgcolor,stroke:d.bordercolor,"stroke-width":d.borderwidth,height:g+A,width:p+A,transform:"translate(-"+m+", -"+m+")","shape-rendering":"crispEdges"});var M=document.createElementNS(o,"rect");s.setAttributes(M,{x:0,width:x,height:g,fill:"rgba(0,0,0,0.4)"});var T=document.createElementNS(o,"rect");s.setAttributes(T,{x:_,width:p-_,height:g,fill:"rgba(0,0,0,0.4)"});var E=document.createElementNS(o,"g"),L=document.createElementNS(o,"rect"),S=document.createElementNS(o,"rect");s.setAttributes(E,{transform:"translate("+(x-v-1)+")"}),s.setAttributes(L,{width:10,height:g,x:-6,fill:"transparent",cursor:"col-resize"}),s.setAttributes(S,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(E,[S,L]);var C=document.createElementNS(o,"g"),z=document.createElementNS(o,"rect"),P=document.createElementNS(o,"rect");s.setAttributes(C,{transform:"translate("+_+")"}),s.setAttributes(z,{width:10,height:g,x:-2,fill:"transparent",cursor:"col-resize"}),s.setAttributes(P,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(C,[P,z]);var R=document.createElementNS(o,"rect");s.setAttributes(R,{x:x,width:_-x,height:g,cursor:"ew-resize",fill:"transparent"}),w.addEventListener("mousedown",function(t){function r(t){var r,n,f=+t.clientX-a;switch(i){case R:w.style.cursor="ew-resize",r=+s+f,n=+l+f,u(r,n),c(e(r),e(n));break;case L:w.style.cursor="col-resize",r=+s+f,n=+l,u(r,n),c(e(r),e(n));break;case z:w.style.cursor="col-resize",r=+s,n=+l+f,u(r,n),c(e(r),e(n));break;default:w.style.cursor="ew-resize",r=o,n=o+f,u(r,n),c(e(r),e(n))}}function n(){window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n),w.style.cursor="auto"}var i=t.target,a=t.clientX,o=a-w.getBoundingClientRect().left,s=w.getAttribute("data-min"),l=w.getAttribute("data-max");window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)}),d.range||(d.range=i.getAutoRange(f.xaxis));var O=l(t,p,g);s.appendChildren(w,[k,O,M,T,R,E,C]),r(f.xaxis.range[0],f.xaxis.range[1]),h.data([0]).enter().append(function(){return d.setRange=r,w})}},{"../../constants/xmlns_namespaces":370,"../../lib":382,"../../plotly":402,"../../plots/cartesian/axes":405,"./helpers":361,"./range_plot":363}],360:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(t,e){return n.coerce(s,l,i,t,e)}if(t[r].rangeslider){var s="object"==typeof t[r].rangeslider?t[r].rangeslider:{},l=e[r].rangeslider={};if(o("bgcolor"),o("bordercolor"),o("borderwidth"),o("thickness"),o("visible"),o("range"),l.range&&!e[r].autorange){var c=l.range,u=e[r].range;c[0]=Math.min(c[0],u[0]),c[1]=Math.max(c[1],u[1])}else e[r]._needsExpand=!0;l.visible&&a.forEach(function(t){var r=e[t]||{};r.fixedrange=!0,e[t]=r})}}},{"../../lib":382,"./attributes":358}],361:[function(t,e,r){"use strict";r.setAttributes=function(t,e){for(var r in e)t.setAttribute(r,e[r])},r.appendChildren=function(t,e){for(var r=0;rl;l++){var c=s[l],u={_fullLayout:e},f=x.coerceRef(t,n,u,c);if("path"!==o){var h=.25,d=.75;if("paper"!==f){var p=x.getFromId(u,f),g=a(p);h=g(p.range[0]+h*(p.range[1]-p.range[0])),d=g(p.range[0]+d*(p.range[1]-p.range[0]))}r(c+"0",h),r(c+"1",d)}}return"path"===o?r("path"):b.noneOrAll(t,n,["x0","x1","y0","y1"]),n}function i(t){return"category"===t.type?t.c2l:t.d2l}function a(t){return"category"===t.type?t.l2c:t.l2d}function o(t,e){t.layout.shapes=e,k.supplyLayoutDefaults(t.layout,t._fullLayout),k.drawAll(t)}function s(t){delete t.layout.shapes,t._fullLayout.shapes=[],k.drawAll(t)}function l(t,e,r){for(var n=0;ne;i--)h(t,i).selectAll('[data-index="'+(i-1)+'"]').attr("data-index",i),k.draw(t,i)}function f(t,e,r,o){function s(e){var r=e.append("path").attr(z).style("opacity",S.opacity).call(_.stroke,P).call(_.fill,S.fillcolor).call(w.dashLine,S.line.dash,S.line.width);C&&r.call(w.setClipUrl,"clip"+t._fullLayout._uid+C)}var l,c;h(t,e).selectAll('[data-index="'+e+'"]').remove();var u=t.layout.shapes[e];if(u){var f={xref:u.xref,yref:u.yref},p={};"string"==typeof r&&r?p[r]=o:b.isPlainObject(r)&&(p=r);var v=Object.keys(p);for(l=0;ll;l++){var k=y[l];if(void 0===p[k]&&void 0!==u[k]){var A,M=k.charAt(0),T=x.getFromId(t,x.coerceRef(f,{},t,M)),E=x.getFromId(t,x.coerceRef(u,{},t,M)),L=u[k];void 0!==p[M+"ref"]&&(T?(A=i(T)(L),L=(A-T.range[0])/(T.range[1]-T.range[0])):L=(L-E.domain[0])/(E.domain[1]-E.domain[0]),E?(A=E.range[0]+L*(E.range[1]-E.range[0]),L=a(E)(A)):L=T.domain[0]+L*(T.domain[1]-T.domain[0])),u[k]=L}}var S=n(u,t._fullLayout);t._fullLayout.shapes[e]=S;var C,z={"data-index":e,"fill-rule":"evenodd",d:g(t,S)},P=S.line.width?S.line.color:"rgba(0,0,0,0)";if("below"!==S.layer)C=(S.xref+S.yref).replace(/paper/g,""),s(t._fullLayout._shapeUpperLayer);else if("paper"===S.xref&&"paper"===S.yref)C="",s(t._fullLayout._shapeLowerLayer);else{var R,O=t._fullLayout._plots||{},I=Object.keys(O);for(l=0,c=I.length;c>l;l++)R=O[I[l]],C=I[l],d(t,S,R)&&s(R.shapelayer)}}}function h(t,e){var r=t._fullLayout.shapes[e],n=t._fullLayout._shapeUpperLayer;return r?"below"===r.layer&&(n="paper"===r.xref&&"paper"===r.yref?t._fullLayout._shapeLowerLayer:t._fullLayout._shapeSubplotLayer):b.log("getShapeLayer: undefined shape: index",e),n}function d(t,e,r){var n=y.Axes.getFromId(t,r.id,"x")._id,i=y.Axes.getFromId(t,r.id,"y")._id,a="below"===e.layer,o=n===e.xref||i===e.yref,s=!!r.shapelayer;return a&&o&&s}function p(t){return function(e){return t(e.replace("_"," "))}}function g(t,e){var r,n,a,o,s=e.type,l=x.getFromId(t,e.xref),c=x.getFromId(t,e.yref),u=t._fullLayout._size;if(l?(r=i(l),n=function(t){return l._offset+l.l2p(r(t,!0))}):n=function(t){return u.l+u.w*t},c?(a=i(c),o=function(t){return c._offset+c.l2p(a(t,!0))}):o=function(t){return u.t+u.h*(1-t)},"path"===s)return l&&"date"===l.type&&(n=p(n)),c&&"date"===c.type&&(o=p(o)),k.convertPath(e.path,n,o);var f=n(e.x0),h=n(e.x1),d=o(e.y0),g=o(e.y1);if("line"===s)return"M"+f+","+d+"L"+h+","+g;if("rect"===s)return"M"+f+","+d+"H"+h+"V"+g+"H"+f+"Z";var v=(f+h)/2,m=(d+g)/2,y=Math.abs(v-f),b=Math.abs(m-d),_="A"+y+","+b,w=v+y+","+m,A=v+","+(m-b);return"M"+w+_+" 0 1,1 "+A+_+" 0 0,1 "+w+"Z"}function v(t,e,r,n,i){var a="category"===t.type?Number:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var o,s,l,c,u,f=1/0,h=-(1/0),d=n.match(A);for("date"===t.type&&(a=p(a)),o=0;ou&&(f=u),u>h&&(h=u)));return h>=f?[f,h]:void 0}}var m=t("fast-isnumeric"),y=t("../../plotly"),b=t("../../lib"),x=t("../../plots/cartesian/axes"),_=t("../color"),w=t("../drawing"),k=e.exports={};k.layoutAttributes=t("./attributes"),k.supplyLayoutDefaults=function(t,e){for(var r=t.shapes||[],i=e.shapes=[],a=0;as&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),b.log("Ignoring extra params in segment "+t)),i+l})},k.calcAutorange=function(t){var e,r,n,i,a,o=t._fullLayout,s=o.shapes;if(s.length&&t._fullData.length)for(e=0;eh?r=h:(u.left-=b.offsetLeft,u.right-=b.offsetLeft,u.top-=b.offsetTop,u.bottom-=b.offsetTop,b.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(u,t,c)&&(r=Math.max(r,o*(t[b.side]-u[a])+c))}),r=Math.min(h,r)),r>0||0>h){var d={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[b.side];e.attr("transform","translate("+d+")")}}}function p(){E=0,L=!0,S=z,k._infolayer.select("."+e).attr({"data-unformatted":S}).text(S).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)})}var g=r.propContainer,v=r.propName,m=r.traceIndex,y=r.dfltName,b=r.avoid||{},x=r.attributes,_=r.transform,w=r.containerGroup,k=t._fullLayout,A=g.titlefont.family,M=g.titlefont.size,T=g.titlefont.color,E=1,L=!1,S=g.title.trim();""===S&&(E=0),S.match(/Click to enter .+ title/)&&(E=.2,L=!0),w||(w=k._infolayer.selectAll(".g-"+e).data([0]),w.enter().append("g").classed("g-"+e,!0));var C=w.selectAll("text").data([0]);C.enter().append("text"),C.text(S).attr("class",e),C.attr({"data-unformatted":S}).call(f);var z="Click to enter "+y+" title";t._context.editable?(S||p(),C.call(u.makeEditable).on("edit",function(e){void 0!==m?a.restyle(t,v,e,m):a.relayout(t,v,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(f)}).on("input",function(t){this.text(t||" ").attr(x).selectAll("tspan.line").attr(x)})):S&&!S.match(/Click to enter .+ title/)||C.remove(),C.classed("js-placeholder",L)}},{"../../lib":382,"../../lib/svg_text_utils":395,"../../plotly":402,"../../plots/plots":454,"../color":303,"../drawing":326,d3:113,"fast-isnumeric":117}],367:[function(t,e,r){"use strict";e.exports={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}},{}],368:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],369:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],370:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],371:[function(t,e,r){"use strict";var n=t("./plotly");r.version="1.13.0",r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.setPlotConfig=t("./plot_api/set_plot_config"),r.register=n.register,r.toImage=t("./plot_api/to_image"),r.downloadImage=t("./snapshot/download"),r.Icons=t("../build/ploticon"),r.Plots=n.Plots,r.Fx=n.Fx,r.Snapshot=n.Snapshot,r.PlotSchema=n.PlotSchema,r.Queue=n.Queue,r.d3=t("d3")},{"../build/ploticon":2,"./plot_api/set_plot_config":400,"./plot_api/to_image":401,"./plotly":402,"./snapshot/download":469,d3:113}],372:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],373:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){Array.isArray(t)&&(e[r]=t[n])}},{}],374:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("./nested_property"),o=t("../components/colorscale/get_scale"),s=(Object.keys(t("../components/colorscale/scales")),/^([2-9]|[1-9][0-9]+)$/);r.valObjects={data_array:{coerceFunction:function(t,e,r){Array.isArray(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)}},"boolean":{coerceFunction:function(t,e,r){t===!0||t===!1?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,i){!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if(n.strict===!0&&"string"!=typeof t)return void e.set(r);var i=String(t);void 0===t||n.noBlank===!0&&!i?e.set(r):e.set(i)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?(Math.abs(t)>180&&(t-=360*Math.round(t/360)),e.set(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r){var n=r.length;return"string"==typeof t&&t.substr(0,n)===r&&s.test(t.substr(n))?void e.set(t):void e.set(r)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"!=typeof t)return void e.set(r);if(-1!==n.extras.indexOf(t))return void e.set(t);for(var i=t.split("+"),a=0;a2)return!1;var l=o[0].split("-");if(l.length>3||3!==l.length&&o[1])return!1;if(4===l[0].length)r=Number(l[0]);else{if(2!==l[0].length)return!1;var c=(new Date).getFullYear();r=((Number(l[0])-c+70)%100+200)%100+c-70}return s(r)?1===l.length?new Date(r,0,1).getTime():(n=Number(l[1])-1,l[1].length>2||!(n>=0&&11>=n)?!1:2===l.length?new Date(r,n,1).getTime():(i=Number(l[2]),l[2].length>2||!(i>=1&&31>=i)?!1:(i=new Date(r,n,i).getTime(),o[1]?(l=o[1].split(":"),l.length>3?!1:(a=Number(l[0]),l[0].length>2||!(a>=0&&23>=a)?!1:(i+=36e5*a,1===l.length?i:(n=Number(l[1]),l[1].length>2||!(n>=0&&59>=n)?!1:(i+=6e4*n,2===l.length?i:(t=Number(l[2]),t>=0&&60>t?i+1e3*t:!1)))))):i))):!1},r.isDateTime=function(t){return r.dateTime2ms(t)!==!1},r.ms2DateTime=function(t,e){if("undefined"==typeof o)return void l.error("d3 is not defined.");e||(e=0);var r=new Date(t),i=o.time.format("%Y-%m-%d")(r);return 7776e6>e?(i+=" "+n(r.getHours(),2),432e6>e&&(i+=":"+n(r.getMinutes(),2),108e5>e&&(i+=":"+n(r.getSeconds(),2),3e5>e&&(i+="."+n(r.getMilliseconds(),3)))),i.replace(/([:\s]00)*\.?[0]*$/,"")):i};var c={H:["%H:%M:%S~%L","%H:%M:%S","%H:%M"],I:["%I:%M:%S~%L%p","%I:%M:%S%p","%I:%M%p"],D:["%H","%I%p","%Hh"]},u={Y:["%Y~%m~%d","%Y%m%d","%y%m%d","%m~%d~%Y","%d~%m~%Y"],Yb:["%b~%d~%Y","%d~%b~%Y","%Y~%d~%b","%Y~%b~%d"],y:["%m~%d~%y","%d~%m~%y","%y~%m~%d"],yb:["%b~%d~%y","%d~%b~%y","%y~%d~%b","%y~%b~%d"]},f=o.time.format.utc,h={Y:{H:["%Y~%m~%dT%H:%M:%S","%Y~%m~%dT%H:%M:%S~%L"].map(f),I:[],D:["%Y%m%d%H%M%S","%Y~%m","%m~%Y"].map(f)},Yb:{H:[],I:[],D:["%Y~%b","%b~%Y"].map(f)},y:{H:[],I:[],D:[]},yb:{H:[],I:[],D:[]}};["Y","Yb","y","yb"].forEach(function(t){u[t].forEach(function(e){h[t].D.push(f(e)),["H","I","D"].forEach(function(r){c[r].forEach(function(n){var i=h[t][r];i.push(f(e+"~"+n)),i.push(f(n+"~"+e))})})})});var d=/[a-z]*/g,p=function(t){return t.substr(0,3)},g=/(mon|tue|wed|thu|fri|sat|sun|the|of|st|nd|rd|th)/g,v=/[\s,\/\-\.\(\)]+/g,m=/~?([ap])~?m(~|$)/,y=function(t,e){return e+"m "},b=/\d\d\d\d/,x=/(^|~)[a-z]{3}/,_=/[ap]m/,w=/:/,k=/q([1-4])/,A=["31~mar","30~jun","30~sep","31~dec"],M=function(t,e){return A[e-1]},T=/ ?([+\-]\d\d:?\d\d|Z)$/;r.parseDate=function(t){if(t.getTime)return t;if("string"!=typeof t)return!1;t=t.toLowerCase().replace(d,p).replace(g,"").replace(v,"~").replace(m,y).replace(k,M).trim().replace(T,"");var e,r,n=null,o=i(t),s=a(t);e=h[o][s],r=e.length;for(var l=0;r>l&&!(n=e[l].parse(t));l++);if(!(n instanceof Date))return!1;var c=n.getTimezoneOffset();return n.setTime(n.getTime()+60*c*1e3),n}},{"../lib":382,d3:113,"fast-isnumeric":117}],376:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i={init:function(t){if(t._ev instanceof n)return t;var e=new n;return t._ev=e,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t.emit=function(r,n){"undefined"!=typeof jQuery&&jQuery(t).trigger(r,n),e.emit(r,n)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;lp;p++){o=t[p];for(s in o)l=h[s],c=o[s],e&&c&&(i(c)||(u=a(c)))?(u?(u=!1,f=l&&a(l)?l:[]):f=l&&i(l)?l:{},h[s]=n([f,c],e,r)):("undefined"!=typeof c||r)&&(h[s]=c)}return h}var i=t("./is_plain_object.js"),a=Array.isArray;r.extendFlat=function(){return n(arguments,!1,!1)},r.extendDeep=function(){return n(arguments,!0,!1)},r.extendDeepAll=function(){return n(arguments,!0,!0)}},{"./is_plain_object.js":383}],378:[function(t,e,r){"use strict";e.exports=function(t){for(var e=[],r=0;ry;y++)f=s(p,y),d=l(e,y),m[y]=n(f,d);else m=n(p,e);return m}var s=t("tinycolor2"),l=t("fast-isnumeric"),c=t("../components/colorscale/make_scale_function"),u=t("../components/color/attributes").defaultLine,f=t("./str2rgbarray"),h=1;e.exports=o},{"../components/color/attributes":302,"../components/colorscale/make_scale_function":320,"./str2rgbarray":394,"fast-isnumeric":117,tinycolor2:274}],381:[function(t,e,r){"use strict";function n(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(e>r)break;t=t.slice(0,e)+l(t.slice(e+5,r))+t.slice(r+6); -}return t}function i(t){return t.replace(/\/g,"\n")}function a(t){return t.replace(/\<.*\>/g,"")}function o(t){for(var e=0;(e=t.indexOf("&",e))>=0;){var r=t.indexOf(";",e);if(e>r)e+=1;else{var n=c[t.slice(e+1,r)];t=n?t.slice(0,e)+n+t.slice(r+1):t.slice(0,e)+t.slice(r+1)}}return t}function s(t){return""+o(a(n(i(t))))}var l=t("superscript-text"),c={mu:"\u03bc",amp:"&",lt:"<",gt:">"};e.exports=s},{"superscript-text":263}],382:[function(t,e,r){"use strict";var n=t("d3"),i=e.exports={};i.nestedProperty=t("./nested_property"),i.isPlainObject=t("./is_plain_object");var a=t("./coerce");i.valObjects=a.valObjects,i.coerce=a.coerce,i.coerce2=a.coerce2,i.coerceFont=a.coerceFont;var o=t("./dates");i.dateTime2ms=o.dateTime2ms,i.isDateTime=o.isDateTime,i.ms2DateTime=o.ms2DateTime,i.parseDate=o.parseDate;var s=t("./search");i.findBin=s.findBin,i.sorterAsc=s.sorterAsc,i.sorterDes=s.sorterDes,i.distinctVals=s.distinctVals,i.roundUp=s.roundUp;var l=t("./stats");i.aggNums=l.aggNums,i.len=l.len,i.mean=l.mean,i.variance=l.variance,i.stdev=l.stdev,i.interp=l.interp;var c=t("./matrix");i.init2dArray=c.init2dArray,i.transposeRagged=c.transposeRagged,i.dot=c.dot,i.translationMatrix=c.translationMatrix,i.rotationMatrix=c.rotationMatrix,i.rotationXYMatrix=c.rotationXYMatrix,i.apply2DTransform=c.apply2DTransform,i.apply2DTransform2=c.apply2DTransform2;var u=t("./extend");i.extendFlat=u.extendFlat,i.extendDeep=u.extendDeep,i.extendDeepAll=u.extendDeepAll;var f=t("./loggers");i.log=f.log,i.warn=f.warn,i.error=f.error,i.notifier=t("./notifier"),i.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},i.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},i.identity=function(t){return t},i.randstr=function h(t,e,r){if(r||(r=16),void 0===e&&(e=24),0>=e)return"0";var n,i,a,o=Math.log(Math.pow(2,e))/Math.log(r),s="";for(n=2;o===1/0;n*=2)o=Math.log(Math.pow(2,e/n))/Math.log(r)*n;var l=o-Math.floor(o);for(n=0;n-1||c!==1/0&&c>=Math.pow(2,e)?h(t,e,r):s},i.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={};return r.optionList=[],r._newoption=function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)},r["_"+e]=t,r},i.smooth=function(t,e){if(e=Math.round(e)||0,2>e)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,c=new Array(l),u=new Array(o);for(r=0;l>r;r++)c[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;o>r;r++){for(a=0,n=0;l>n;n++)i=r+n+1-e,-o>i?i-=s*Math.round(i/s):i>=s&&(i-=s*Math.floor(i/s)),0>i?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*c[n];u[r]=a}return u},i.syncOrAsync=function(t,e,r){function n(){return i.syncOrAsync(t,e,r)}for(var a,o;t.length;)if(o=t.splice(0,1)[0],a=o(e),a&&a.then)return a.then(n).then(void 0,i.promiseError);return r&&r(e)},i.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},i.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;ni;i++)e[i][r]=t[i]},i.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,o,s=3,l=Object.keys(t);for(n=0;n1?n+a[1]:"";if(i&&(a.length>1||o.length>4))for(;r.test(o);)o=o.replace(r,"$1"+i+"$2");return o+s}},{"./coerce":374,"./dates":375,"./extend":377,"./is_plain_object":383,"./loggers":384,"./matrix":385,"./nested_property":386,"./notifier":387,"./search":390,"./stats":393,d3:113}],383:[function(t,e,r){"use strict";e.exports=function(t){return"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],384:[function(t,e,r){"use strict";var n=t("../plot_api/plot_config"),i=e.exports={};i.log=function(){if(n.logging>1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;en;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,i=t.length;for(e=0;i>e;e++)n=Math.max(n,t[e].length);var a=new Array(n);for(e=0;n>e;e++)for(a[e]=new Array(i),r=0;i>r;r++)a[e][r]=t[r][e];return a},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,i,a=t.length;if(t[0].length)for(n=new Array(a),i=0;a>i;i++)n[i]=r.dot(t[i],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),i=0;ii;i++)n+=t[i]*e[i];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],386:[function(t,e,r){"use strict";function n(t,e){return function(){var r,i,a,o,s,l=t;for(o=0;o=0;e--){if(n=t[e],o=!1,Array.isArray(n))for(r=n.length-1;r>=0;r--)c(n[r])?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)c(n[a[r]])&&!i(n[a[r]],a[r])?delete n[a[r]]:o=!0;if(o)return}}function c(t){return void 0===t||null===t?!0:"object"!=typeof t?!1:Array.isArray(t)?!t.length:!Object.keys(t).length}function u(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}var f=t("fast-isnumeric");e.exports=function(t,e){if(f(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,l=e.split(".");sr||r>a||o>n||n>s?!1:!e||!c(t)}function r(t,e){var r=t[0],l=t[1];if(i>r||r>a||o>l||l>s)return!1;var c,u,f,h,d,p=n.length,g=n[0][0],v=n[0][1],m=0;for(c=1;p>c;c++)if(u=g,f=v,g=n[c][0],v=n[c][1],h=Math.min(u,g),!(h>r||r>Math.max(u,g)||l>Math.max(f,v)))if(l=l&&r!==h&&m++}return m%2===1}var n=t.slice(),i=n[0][0],a=i,o=n[0][1],s=o;n.push(n[0]);for(var l=1;la;a++)if(o=[t[a][0]-l[0],t[a][1]-l[1]],s=n(o,c),0>s||s>u||Math.abs(n(o,h))>i)return!0;return!1};i.filter=function(t,e){function r(r){t.push(r);var s=n.length,l=i;n.splice(o+1);for(var c=l+1;c1){var s=t.pop();r(s)}return{addPt:r,raw:t,filtered:n}}},{"./matrix":385}],389:[function(t,e,r){"use strict";function n(t,e){for(var r,n=[],a=0;a=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;rt}function i(t,e){return e>=t}function a(t,e){return t>e}function o(t,e){return t>=e}var s=t("fast-isnumeric"),l=t("../lib");r.findBin=function(t,e,r){if(s(e.start))return r?Math.ceil((t-e.start)/e.size)-1:Math.floor((t-e.start)/e.size);var c,u,f=0,h=e.length,d=0;for(u=e[e.length-1]>=e[0]?r?n:i:r?o:a;h>f&&d++<100;)c=Math.floor((f+h)/2),u(e[c],t)?f=c+1:h=c;return d>90&&l.log("Long binary search..."),f-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;n>s;s++)e[s+1]>e[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,c=r?Math.ceil:Math.floor;a>i&&o++<100;)n=c((i+a)/2),e[n]<=t?i=n+s:a=n-l;return e[i]}},{"../lib":382,"fast-isnumeric":117}],391:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],392:[function(t,e,r){"use strict";var n=t("../components/color"),i=function(){};e.exports=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=i);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=n.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1}},{"../components/color":303}],393:[function(t,e,r){"use strict";var n=t("fast-isnumeric");r.aggNums=function(t,e,i,a){var o,s;if(a||(a=i.length),n(e)||(e=!1),Array.isArray(i[0])){for(s=new Array(a),o=0;a>o;o++)s[o]=r.aggNums(t,e,i[o]);i=s}for(o=0;a>o;o++)n(e)?n(i[o])&&(e=t(+e,+i[o])):e=i[o];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.variance=function(t,e,i){return e||(e=r.len(t)),n(i)||(i=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-i,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if(e=e*t.length-.5,0>e)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"fast-isnumeric":117}],394:[function(t,e,r){"use strict";function n(t){return t=i(t),a.str2RgbaArray(t.toRgbString())}var i=t("tinycolor2"),a=t("arraytools");e.exports=n},{arraytools:49,tinycolor2:274}],395:[function(t,e,r){"use strict";function n(t,e){return t.node().getBoundingClientRect()[e]}function i(t){return t.replace(/(<|<|<)/g,"\\lt ").replace(/(>|>|>)/g,"\\gt ")}function a(t,e,r){var n="math-output-"+l.Lib.randstr([],64),a=c.select("body").append("div").attr({id:n}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text(i(t));MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var e=c.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())u.log("There was an error in the tex syntax.",t),r();else{var n=a.select("svg").node().getBoundingClientRect();r(a.select(".MathJax_SVG"),e,n)}a.remove()})}function o(t){for(var e=l.util.html_entity_decode(t),r=e.split(/(<[^<>]*>)/).map(function(t){var e=t.match(/<(\/?)([^ >]*)\s*(.*)>/i),r=e&&e[2].toLowerCase(),n=d[r];if(void 0!==n){var i=e[1],a=e[3],o=a.match(/^style\s*=\s*"([^"]+)"\s*/i);if("a"===r){if(i)return"";if("href"!==a.substr(0,4).toLowerCase())return"";var s=document.createElement("a");return s.href=a.substr(4).replace(/["'=]/g,""),-1===p.indexOf(s.protocol)?"":'"}if("br"===r)return"
";if(i)return"sup"===r?'':"sub"===r?'':"";var c=""}return l.util.xml_entity_encode(t).replace(/");i>0;i=r.indexOf("
",i+1))n.push(i);var a=0;n.forEach(function(t){for(var e=t+a,n=r.slice(0,e),i="",o=n.length-1;o>=0;o--){var s=n[o].match(/<(\/?).*>/i);if(s&&"
"!==n[o]){s[1]||(i=n[o]);break}}i&&(r.splice(e+1,0,i),r.splice(e,0,""),a+=2)});var o=r.join(""),s=o.split(/
/gi);return s.length>1&&(r=s.map(function(t,e){return''+t+""})),r.join("")}function s(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),c=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-c.top+"px",left:a()-c.left+"px","z-index":1e3}),this}}var l=t("../plotly"),c=t("d3"),u=t("../lib"),f=t("../constants/xmlns_namespaces"),h=e.exports={};c.selection.prototype.appendSVG=function(t){for(var e=['',t,""].join(""),r=(new DOMParser).parseFromString(e,"application/xml"),n=r.documentElement.firstChild;n;)this.node().appendChild(this.node().ownerDocument.importNode(n,!0)),n=n.nextSibling;return r.querySelector("parsererror")?(u.log(r.querySelector("parsererror div").textContent),null):c.select(this.node().lastChild)},h.html_entity_decode=function(t){var e=c.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"<"===t?"<":"&rt;"===t?">":e.html(t).text()});return e.remove(),r},h.xml_entity_encode=function(t){return t.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")},h.convertToTspans=function(t,e){function r(){d.empty()||(p=u.attr("class")+"-math",d.select("svg."+p).remove()),t.text("").style({visibility:"visible","white-space":"pre"}),h=t.appendSVG(s),h||t.text(i),t.select("a").size()&&t.style("pointer-events","all"),e&&e.call(u)}var i=t.text(),s=o(i),u=t,f=!u.attr("data-notex")&&s.match(/([^$]*)([$]+[^$]*[$]+)([^$]*)/),h=i,d=c.select(u.node().parentNode);if(!d.empty()){var p=u.attr("class")?u.attr("class").split(" ")[0]:"text";p+="-math",d.selectAll("svg."+p).remove(),d.selectAll("g."+p+"-group").remove(),t.style({visibility:null});for(var g=t.node();g&&g.removeAttribute;g=g.parentNode)g.removeAttribute("data-bb");if(f){var v=l.Lib.getPlotDiv(u.node());(v&&v._promises||[]).push(new Promise(function(t){u.style({visibility:"hidden"});var i={fontSize:parseInt(u.style("font-size"),10)};a(f[2],i,function(i,a,o){d.selectAll("svg."+p).remove(),d.selectAll("g."+p+"-group").remove();var s=i&&i.select("svg");if(!s||!s.node())return r(),void t();var l=d.append("g").classed(p+"-group",!0).attr({"pointer-events":"none"});l.node().appendChild(s.node()),a&&a.node()&&s.node().insertBefore(a.node().cloneNode(!0),s.node().firstChild),s.attr({"class":p,height:o.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var c=u.style("fill")||"black";s.select("g").attr({fill:c,stroke:c});var f=n(s,"width"),h=n(s,"height"),g=+u.attr("x")-f*{start:0,middle:.5,end:1}[u.attr("text-anchor")||"start"],v=parseInt(u.style("font-size"),10)||n(u,"height"),m=-v/4;"y"===p[0]?(l.attr({transform:"rotate("+[-90,+u.attr("x"),+u.attr("y")]+") translate("+[-f/2,m-h/2]+")"}),s.attr({x:+u.attr("x"),y:+u.attr("y")})):"l"===p[0]?s.attr({x:u.attr("x"),y:m-h/2}):"a"===p[0]?s.attr({x:0,y:m}):s.attr({x:g,y:+u.attr("y")+m-h/2}),e&&e.call(u,l),t(l)})}))}else r();return t}};var d={sup:'font-size:70%" dy="-0.6em',sub:'font-size:70%" dy="0.3em',b:"font-weight:bold",i:"font-style:italic",a:"",span:"",br:"",em:"font-style:italic;font-weight:bold"},p=["http:","https:","mailto:"],g=new RegExp("]*)?/?>","g");h.plainText=function(t){return(t||"").replace(g," ")},h.makeEditable=function(t,e,r){function n(){a(),o.style({opacity:0});var t,e=h.attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&c.select(o.node().parentNode).select(t).style({opacity:0})}function i(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}function a(){var t=c.select(l.Lib.getPlotDiv(o.node())),e=t.select(".svg-container"),n=e.append("div");n.classed("plugin-editable editable",!0).style({position:"absolute","font-family":o.style("font-family")||"Arial","font-size":o.style("font-size")||12,color:r.fill||o.style("fill")||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-parseFloat(o.style("font-size"))/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||o.attr("data-unformatted")).call(s(o,e,r)).on("blur",function(){o.text(this.textContent).style({opacity:1});var t,e=c.select(this).attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&c.select(o.node().parentNode).select(t).style({opacity:0});var r=this.textContent;c.select(this).transition().duration(0).remove(),c.select(document).on("mouseup",null),u.edit.call(o,r)}).on("focus",function(){var t=this;c.select(document).on("mouseup",function(){return c.event.target===t?!1:void(document.activeElement===n.node()&&n.node().blur())})}).on("keyup",function(){27===c.event.which?(o.style({opacity:1}),c.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),u.cancel.call(o,this.textContent)):(u.input.call(o,this.textContent),c.select(this).call(s(o,e,r)))}).on("keydown",function(){13===c.event.which&&this.blur()}).call(i)}r||(r={});var o=this,u=c.dispatch("edit","input","cancel"),f=c.select(this.node()).style({"pointer-events":"all"}),h=e||f;return e&&f.style({"pointer-events":"none"}),r.immediate?n():h.on("click",n),c.rebind(this,u,"on")}},{"../constants/xmlns_namespaces":370,"../lib":382,"../plotly":402,d3:113}],396:[function(t,e,r){"use strict";var n=e.exports={},i=t("../plots/geo/constants").locationmodeToLayer,a=t("topojson").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../plots/geo/constants":424,topojson:275}],397:[function(t,e,r){"use strict";function n(t){var e;if("string"==typeof t){if(e=document.getElementById(t),null===e)throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t}function i(t,e){t._fullLayout._paperdiv.style("background","white"),P.defaultConfig.setBackground(t,e)}function a(t,e){t._context||(t._context=R.extendFlat({},P.defaultConfig));var r=t._context;e&&(Object.keys(e).forEach(function(t){t in r&&("setBackground"===t&&"opaque"===e[t]?r[t]=i:r[t]=e[t])}),e.plot3dPixelRatio&&!r.plotGlPixelRatio&&(r.plotGlPixelRatio=r.plot3dPixelRatio)),r.staticPlot&&(r.editable=!1,r.autosizable=!1,r.scrollZoom=!1,r.doubleClick=!1,r.showTips=!1,r.showLink=!1,r.displayModeBar=!1)}function o(t,e,r){var n=S.select(t).selectAll(".plot-container").data([0]);n.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=n.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e),r&&(t.layout=r),P.micropolar.manager.fillLayout(t),"initial"===t._fullLayout.autosize&&t._context.autosizable&&(w(t,{}),t._fullLayout.autosize=r.autosize=!0),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=P.micropolar.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var a=t.framework.svg(),o=1,s=t._fullLayout.title;""!==s&&s||(o=0);var l="Click to enter title",c=function(){this.call(P.util.convertToTspans)},u=a.select(".title-group text").call(c);if(t._context.editable){u.attr({"data-unformatted":s}),s&&s!==l||(o=.2,u.attr({"data-unformatted":l}).text(l).style({opacity:o}).on("mouseover.opacity",function(){S.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){S.select(this).transition().duration(1e3).style("opacity",0)}));var f=function(){this.call(P.util.makeEditable).on("edit",function(e){t.framework({layout:{title:e}}),this.attr({"data-unformatted":e}).text(e).call(c),this.call(f)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(c)})};u.call(f)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),N.addLinks(t),Promise.resolve()}function s(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1);var n=P.Axes.list({_fullLayout:t});for(e=0;ee;e++){var o=t.annotations[e];o.ref&&("paper"===o.ref?(o.xref="paper",o.yref="paper"):"data"===o.ref&&(o.xref="x",o.yref="y"),delete o.ref),l(o,"xref"),l(o,"yref")}void 0===t.shapes||Array.isArray(t.shapes)||(R.warn("Shapes must be an array."),delete t.shapes);var s=(t.shapes||[]).length;for(e=0;s>e;e++){var c=t.shapes[e];l(c,"xref"),l(c,"yref")}var u=t.legend;u&&(u.x>3?(u.x=1.02,u.xanchor="left"):u.x<-2&&(u.x=-.02,u.xanchor="right"),u.y>3?(u.y=1.02,u.yanchor="bottom"):u.y<-2&&(u.y=-.02,u.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var h=N.getSubplotIds(t,"gl3d");for(e=0;er;++r)b[r]=v[e]+m*y[2+4*r];d.camera={eye:{x:b[0],y:b[1],z:b[2]},center:{x:v[0],y:v[1],z:v[2]},up:{x:y[1],y:y[5],z:y[9]}},delete d.cameraposition}}return F.clean(t),t}function l(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=P.Axes.cleanId(r,n))}function c(t,e){for(var r=[],n=(t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid})),i=0;ia&&(s=R.randstr(n),-1!==r.indexOf(s));a++);o.uid=R.randstr(n),n.push(o.uid)}if(r.push(o.uid),"histogramy"===o.type&&"xbins"in o&&!("ybins"in o)&&(o.ybins=o.xbins,delete o.xbins),o.error_y&&"opacity"in o.error_y){var l=F.defaults,c=o.error_y.color||(N.traceIs(o,"bar")?F.defaultLine:l[i%l.length]);o.error_y.color=F.addOpacity(F.rgb(c),F.opacity(c)*o.error_y.opacity),delete o.error_y.opacity}if("bardir"in o&&("h"!==o.bardir||!N.traceIs(o,"bar")&&"histogram"!==o.type.substr(0,9)||(o.orientation="h",x(o)),delete o.bardir),"histogramy"===o.type&&x(o),"histogramx"!==o.type&&"histogramy"!==o.type||(o.type="histogram"),"scl"in o&&(o.colorscale=o.scl,delete o.scl),"reversescl"in o&&(o.reversescale=o.reversescl,delete o.reversescl),o.xaxis&&(o.xaxis=P.Axes.cleanId(o.xaxis,"x")),o.yaxis&&(o.yaxis=P.Axes.cleanId(o.yaxis,"y")),N.traceIs(o,"gl3d")&&o.scene&&(o.scene=N.subplotsRegistry.gl3d.cleanId(o.scene)),N.traceIs(o,"pie")||(Array.isArray(o.textposition)?o.textposition=o.textposition.map(u):o.textposition&&(o.textposition=u(o.textposition))),N.traceIs(o,"2dMap")&&("YIGnBu"===o.colorscale&&(o.colorscale="YlGnBu"),"YIOrRd"===o.colorscale&&(o.colorscale="YlOrRd")),N.traceIs(o,"markerColorscale")&&o.marker){var h=o.marker;"YIGnBu"===h.colorscale&&(h.colorscale="YlGnBu"),"YIOrRd"===h.colorscale&&(h.colorscale="YlOrRd")}if("surface"===o.type&&R.isPlainObject(o.contours)){var d=["x","y","z"];for(a=0;an?a.push(i+n):a.push(n);return a}function p(t,e,r){var n,i;for(n=0;n=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||0>i&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function g(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),p(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&p(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function v(t,e,r){var n,i;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n=0&&l0){var s=_(t._boundingBoxMargins),l=s.left+s.right,c=s.bottom+s.top,u=a._container.node().getBoundingClientRect(),f=1-2*o.frameMargins;i=Math.round(f*(u.width-l)),n=Math.round(f*(u.height-c))}else r=window.getComputedStyle(t),n=parseFloat(r.height)||a.height,i=parseFloat(r.width)||a.width;return Math.abs(a.width-i)>1||Math.abs(a.height-n)>1?(a.height=t.layout.height=n,a.width=t.layout.width=i):"initial"!==a.autosize&&(delete e.autosize,a.autosize=t.layout.autosize=!0),N.sanitizeMargins(a),e}function k(t){var e=S.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),"initial"===r.autosize&&(w(t,{}),r.autosize=!0,t.layout.autosize=!0),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([0]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._geocontainer=r._paperdiv.selectAll(".geo-container").data([0]),r._geocontainer.enter().append("div").classed("geo-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var n=[];S.selectAll("defs").each(function(){this.id&&n.push(this.id.split("-")[1])}),r._uid=R.randstr(n)}r._paperdiv.selectAll(".main-svg").attr(W.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=i.append("g").classed("imagelayer",!0),r._shapeLowerLayer=i.append("g").classed("shapelayer",!0);var a=P.Axes.getSubplots(t);a.join("")!==Object.keys(t._fullLayout._plots||{}).join("")&&A(t,a),r._has("cartesian")&&M(t,a),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0);var o=r._paper.selectAll(".layer-subplot");r._imageSubplotLayer=o.selectAll(".imagelayer"),r._shapeSubplotLayer=o.selectAll(".shapelayer");var s=r._paper.append("g").classed("layer-above",!0);r._imageUpperLayer=s.append("g").classed("imagelayer",!0),r._shapeUpperLayer=s.append("g").classed("shapelayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0),r._geoimages=r._paper.append("g").classed("geoimages",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework");var l=R.syncOrAsync([T,function(){return P.Axes.doTicks(t,"redraw")},j.init],t);return l&&l.then&&t._promises.push(l),l}function A(t,e){function r(e,r){return function(){return P.Axes.getFromId(t,e,r)}}for(var n,i,a=t._fullLayout._plots={},o=0;o0,_=P.Axes.getSubplots(t).join(""),w=Object.keys(t._fullLayout._plots||{}).join(""),A=w===_;x?t.framework===k&&!b&&A||(t.framework=k,k(t)):A?b&&k(t):(t.framework=k,k(t)),b&&P.Axes.saveRangeInitial(t);var M=t._fullLayout,E=!t.calcdata||t.calcdata.length!==(t.data||[]).length;E&&h(t);for(var L=0;LY.range[0]?[1,2]:[2,1]);else{var W=Y.range[0],Z=Y.range[1];"log"===O?(0>=W&&0>=Z&&i(q+".autorange",!0),0>=W?W=Z/1e6:0>=Z&&(Z=W/1e6),i(q+".range[0]",Math.log(W)/Math.LN10),i(q+".range[1]",Math.log(Z)/Math.LN10)):(i(q+".range[0]",Math.pow(10,W)),i(q+".range[1]",Math.pow(10,Z)))}else i(q+".autorange",!0)}if("reverse"===D)H.range?H.range.reverse():(i(q+".autorange",!0),H.range=[1,0]),G.autorange?_=!0:x=!0;else if("annotations"===z.parts[0]||"shapes"===z.parts[0]){var K=z.parts[1],$=z.parts[0],Q=p[$]||[],J=P[R.titleCase($)],tt=Q[K]||{};2===z.parts.length&&("add"===v[C]||R.isPlainObject(v[C])?E[C]="remove":"remove"===v[C]?-1===K?(E[$]=Q,delete E[C]):E[C]=tt:R.log("???",v)),!a(tt,"x")&&!a(tt,"y")||R.containsAny(C,["color","opacity","align","dash"])||(_=!0),J.draw(t,K,z.parts.slice(2).join("."),v[C]),delete v[C]}else if("images"===z.parts[0]){var rt=R.objectFromPath(C,O);R.extendDeepAll(t.layout,rt),U.supplyLayoutDefaults(t.layout,t._fullLayout),U.draw(t)}else if("mapbox"===z.parts[0]&&"layers"===z.parts[1]){R.extendDeepAll(t.layout,R.objectFromPath(C,O));var nt=(t._fullLayout.mapbox||{}).layers||[],it=z.parts[2]+1-nt.length;for(d=0;it>d;d++)nt.push({});x=!0}else 0===z.parts[0].indexOf("scene")?x=!0:0===z.parts[0].indexOf("geo")?x=!0:0===z.parts[0].indexOf("ternary")?x=!0:!g._has("gl2d")||-1===C.indexOf("axis")&&"plot_bgcolor"!==z.parts[0]?"hiddenlabels"===C?_=!0:-1!==z.parts[0].indexOf("legend")?m=!0:-1!==C.indexOf("title")?y=!0:-1!==z.parts[0].indexOf("bgcolor")?b=!0:z.parts.length>1&&R.containsAny(z.parts[1],["tick","exponent","grid","zeroline"])?y=!0:-1!==C.indexOf(".linewidth")&&-1!==C.indexOf("axis")?y=b=!0:z.parts.length>1&&-1!==z.parts[1].indexOf("line")?b=!0:z.parts.length>1&&"mirror"===z.parts[1]?y=b=!0:"margin.pad"===C?y=b=!0:"margin"===z.parts[0]||"autorange"===z.parts[1]||"rangemode"===z.parts[1]||"type"===z.parts[1]||"domain"===z.parts[1]||C.match(/^(bar|box|font)/)?_=!0:-1!==["hovermode","dragmode"].indexOf(C)?k=!0:-1===["hovermode","dragmode","height","width","autosize"].indexOf(C)&&(x=!0):x=!0,z.set(O)}I&&I.add(t,et,[t,E],et,[t,M]),v.autosize&&(v=w(t,v)),(v.height||v.width||v.autosize)&&(_=!0);var at=Object.keys(v),ot=[N.previousPromises];if(x||_)ot.push(function(){return t.layout=void 0,_&&(t.calcdata=void 0),P.plot(t,"",p)});else if(at.length&&(N.supplyDefaults(t),g=t._fullLayout,m&&ot.push(function(){return V.draw(t),N.previousPromises(t)}),b&&ot.push(T),y&&ot.push(function(){return P.Axes.doTicks(t,"redraw"),L(t),N.previousPromises(t)}),k)){var st;for(X(t),st=N.getSubplotIds(g,"gl3d"),d=0;d1)};c(r.width)&&c(r.height)||s(new Error("Height and width should be pixel values."));var u=n.clone(e,{format:"png",height:r.height,width:r.width}),f=u.td;f.style.position="absolute",f.style.left="-5000px",document.body.appendChild(f);var h=n.getRedrawFunc(f);a.plot(f,u.data,u.layout,u.config).then(h).then(l).then(function(e){t(e)}).catch(function(t){s(t)})});return s}var i=t("fast-isnumeric"),a=t("../plotly"),o=t("../lib");e.exports=n},{"../lib":382,"../plotly":402,"../snapshot":471,"fast-isnumeric":117}],402:[function(t,e,r){"use strict";t("es6-promise").polyfill(),r.Lib=t("./lib"),r.util=t("./lib/svg_text_utils"),r.Queue=t("./lib/queue"),t("../build/plotcss"),r.MathJaxConfig=t("./fonts/mathjax_config"),r.defaultConfig=t("./plot_api/plot_config");var n=r.Plots=t("./plots/plots");r.Axes=t("./plots/cartesian/axes"),r.Fx=t("./plots/cartesian/graph_interact"),r.micropolar=t("./plots/polar/micropolar"),r.Color=t("./components/color"),r.Drawing=t("./components/drawing"),r.Colorscale=t("./components/colorscale"),r.Colorbar=t("./components/colorbar"),r.ErrorBars=t("./components/errorbars"),r.Annotations=t("./components/annotations"),r.Shapes=t("./components/shapes"),r.Legend=t("./components/legend"),r.Images=t("./components/images"),r.ModeBar=t("./components/modebar"),r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;ec&&u>e&&(void 0===i[r]?a[f]=T.tickText(t,e):a[f]=s(t,e,String(i[r])),f++);return f=864e5?t._tickround="d":r>=36e5?t._tickround="H":r>=6e4?t._tickround="M":r>=1e3?t._tickround="S":t._tickround=3-Math.round(Math.log(r/2)/Math.LN10);else{b(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01),e="log"===t.type?Math.pow(10,Math.max(t.range[0],t.range[1])):Math.max(Math.abs(t.range[0]),Math.abs(t.range[1]));var n=Math.floor(Math.log(e)/Math.LN10+.01);Math.abs(n)>3&&("SI"===t.exponentformat||"B"===t.exponentformat?t._tickexponent=3*Math.round((n-1)/3):t._tickexponent=n)}else"M"===r.charAt(0)?t._tickround=2===r.length?"m":"y":t._tickround=null}function o(t,e){var r=t.match(U),n=new Date(e);if(r){var i=Math.min(+r[1]||6,6),a=String(e/1e3%1+2.0000005).substr(2,i).replace(/0+$/,"")||"0";return y.time.format(t.replace(U,a))(n)}return y.time.format(t)(n)}function s(t,e,r){var n=t.tickfont||t._gd._fullLayout.font;return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}function l(t,e,r,n){var i,a=e.x,s=t._tickround,l=new Date(a),c="";r&&t.hoverformat?i=o(t.hoverformat,a):t.tickformat?i=o(t.tickformat,a):(n&&(b(s)?s+=2:s={y:"m",m:"d",d:"H",H:"M",M:"S",S:2}[s]),"y"===s?i=I(l):"m"===s?i=N(l):(a!==t._tmin||r||(c="
"+I(l)),"d"===s?i=j(l):"H"===s?i=F(l):(a!==t._tmin||r||(c="
"+j(l)+", "+I(l)),i=D(l),"M"!==s&&(i+=B(l),"S"!==s&&(i+=h(m(a/1e3,1),t,"none",r).substr(1)))))),e.text=i+c}function c(t,e,r,n,i){var a=t.dtick,o=e.x;if(!n||"string"==typeof a&&"L"===a.charAt(0)||(a="L3"),t.tickformat||"string"==typeof a&&"L"===a.charAt(0))e.text=h(Math.pow(10,o),t,i,n);else if(b(a)||"D"===a.charAt(0)&&m(o+.01,1)<.1)if(-1!==["e","E","power"].indexOf(t.exponentformat)){var s=Math.round(o);0===s?e.text=1:1===s?e.text="10":s>1?e.text="10"+s+"":e.text="10\u2212"+-s+"",e.fontSize*=1.25}else e.text=h(Math.pow(10,o),t,"","fakehover"),"D1"===a&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6);else{if("D"!==a.charAt(0))throw"unrecognized dtick "+String(a);e.text=String(Math.round(Math.pow(10,m(o,1)))),e.fontSize*=.75}if("D1"===t.dtick){var l=String(e.text).charAt(0);"0"!==l&&"1"!==l||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(0>o?.5:.25)))}}function u(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r=""),e.text=String(r)}function f(t,e,r,n,i){"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide"),e.text=h(e.x,t,i,n)}function h(t,e,r,n){var i=0>t,o=e._tickround,s=r||e.exponentformat||"B",l=e._tickexponent,c=e.tickformat;if(n){var u={exponentformat:e.exponentformat,dtick:"none"===e.showexponent?e.dtick:b(t)?Math.abs(t)||1:1,range:"none"===e.showexponent?e.range:[0,t||1]};a(u),o=(Number(u._tickround)||0)+4,l=u._tickexponent,e.hoverformat&&(c=e.hoverformat)}if(c)return y.format(c)(t).replace(/-/g,"\u2212");var f=Math.pow(10,-o)/2;if("none"===s&&(l=0),t=Math.abs(t),f>t)t="0",i=!1;else{if(t+=f,l&&(t*=Math.pow(10,-l),o+=l),0===o)t=String(Math.floor(t));else if(0>o){t=String(Math.round(t)),t=t.substr(0,t.length+o);for(var h=o;0>h;h++)t+="0"}else{t=String(t);var d=t.indexOf(".")+1;d&&(t=t.substr(0,d+o).replace(/\.?0+$/,""))}t=_.numSeparate(t,e._gd._fullLayout.separators)}if(l&&"hide"!==s){var p;p=0>l?"\u2212"+-l:"power"!==s?"+"+l:String(l),"e"===s||("SI"===s||"B"===s)&&(l>12||-15>l)?t+="e"+p:"E"===s?t+="E"+p:"power"===s?t+="×10"+p+"":"B"===s&&9===l?t+="B":"SI"!==s&&"B"!==s||(t+=V[l/3+5])}return i?"\u2212"+t:t}function d(t,e){var r,n,i=[];for(r=0;r1)for(n=1;n2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},T.getAutoRange=function(t){var e,r=[],n=t._min[0].val,i=t._max[0].val;for(e=1;e0&&u>0&&f/u>h&&(l=o,c=s,h=f/u);return n===i?r=d?[n+1,"normal"!==t.rangemode?0:n-1]:["normal"!==t.rangemode?0:n-1,n+1]:h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode&&l.val>=0?l={val:0,pad:0}:"nonnegative"===t.rangemode&&(l.val-h*l.pad<0&&(l={val:0,pad:0}),c.val<0&&(c={val:1,pad:0})),h=(c.val-l.val)/(t._length-l.pad-c.pad)),r=[l.val-h*l.pad,c.val+h*c.pad],r[0]===r[1]&&(r=[r[0]-1,r[0]+1]),d&&r.reverse()),r},T.doAutoRange=function(t){t._length||t.setScale();var e=t._min&&t._max&&t._min.length&&t._max.length;if(t.autorange&&e){t.range=T.getAutoRange(t);var r=t._gd.layout[t._name];r||(t._gd.layout[t._name]=r={}),r!==t&&(r.range=t.range.slice(),r.autorange=t.autorange)}},T.saveRangeInitial=function(t,e){for(var r=T.list(t,"",!0),n=!1,i=0;ip&&(p=g/10),c=t.c2l(p),u=t.c2l(g),y&&(c=Math.min(0,c),u=Math.max(0,u)),n(c)){for(d=!0,o=0;o=h?d=!1:s.val>=c&&s.pad<=h&&(t._min.splice(o,1),o--);d&&t._min.push({val:c,pad:y&&0===c?0:h})}if(n(u)){for(d=!0,o=0;o=u&&s.pad>=f?d=!1:s.val<=u&&s.pad<=f&&(t._max.splice(o,1),o--);d&&t._max.push({val:u,pad:y&&0===u?0:f})}}}if((t.autorange||t._needsExpand)&&e){t._min||(t._min=[]),t._max||(t._max=[]),r||(r={}),t._m||t.setScale();var a,o,s,l,c,u,f,h,d,p,g,v=e.length,m=r.padded?.05*t._length:0,y=r.tozero&&("linear"===t.type||"-"===t.type),x=n((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),_=n((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),w=n(r.vpadplus||r.vpad),k=n(r.vpadminus||r.vpad);for(a=0;6>a;a++)i(a);for(a=v-1;a>5;a--)i(a)}},T.autoBin=function(t,e,r,n){function i(t){return(1+100*(t-d)/f.dtick)%100<2}var a=_.aggNums(Math.min,null,t),o=_.aggNums(Math.max,null,t);if("category"===e.type)return{start:a-.5,end:o+.5,size:1};var s;if(r)s=(o-a)/r;else{var l=_.distinctVals(t),c=Math.pow(10,Math.floor(Math.log(l.minDiff)/Math.LN10)),u=c*_.roundUp(l.minDiff/c,[.9,1.9,4.9,9.9],!0);s=Math.max(u,2*_.stdev(t)/Math.pow(t.length,n?.25:.4))}var f={type:"log"===e.type?"linear":e.type,range:[a,o]};T.autoTicks(f,s);var h,d=T.tickIncrement(T.tickFirst(f),f.dtick,"reverse");if("number"==typeof f.dtick){for(var p=0,g=0,v=0,m=0,y=0;yg&&(p>.3*x||i(a)||i(o))){var w=f.dtick/2;d+=a>d+w?w:-w}var k=1+Math.floor((o-d)/f.dtick);h=d+k*f.dtick}else for(h=d;o>=h;)h=T.tickIncrement(h,f.dtick);return{start:d,end:h,size:f.dtick}},T.calcTicks=function(t){if("array"===t.tickmode)return n(t);if("auto"===t.tickmode||!t.dtick){var e,r=t.nticks;r||("category"===t.type?(e=t.tickfont?1.2*(t.tickfont.size||12):15,r=t._length/e):(e="y"===t._id.charAt(0)?40:80,r=_.constrain(t._length/e,4,9)+1)),T.autoTicks(t,Math.abs(t.range[1]-t.range[0])/r),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t._forceTick0)}t.tick0||(t.tick0="date"===t.type?new Date(2e3,0,1).getTime():0),a(t),t._tmin=T.tickFirst(t);var i=t.range[1]=s:s>=l)&&(o.push(l),!(o.length>1e3));l=T.tickIncrement(l,t.dtick,i));t._tmax=o[o.length-1];for(var c=new Array(o.length),u=0;u157788e5?(e/=315576e5,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="M"+12*i(e,r,S)):e>12096e5?(e/=26298e5,t.dtick="M"+i(e,1,C)):e>432e5?(t.dtick=i(e,864e5,P),t.tick0=new Date(2e3,0,2).getTime()):e>18e5?t.dtick=i(e,36e5,C):e>3e4?t.dtick=i(e,6e4,z):e>500?t.dtick=i(e,1e3,z):(r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));else if("log"===t.type)if(t.tick0=0,e>.7)t.dtick=Math.ceil(e);else if(Math.abs(t.range[1]-t.range[0])<1){var n=1.5*Math.abs((t.range[1]-t.range[0])/e);e=Math.abs(Math.pow(10,t.range[1])-Math.pow(10,t.range[0]))/n,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="L"+i(e,r,S)}else t.dtick=e>.3?"D2":"D1";else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):(t.tick0=0,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));if(0===t.dtick&&(t.dtick=1),!b(t.dtick)&&"string"!=typeof t.dtick){var a=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(a)}},T.tickIncrement=function(t,e,r){var n=r?-1:1;if(b(e))return t+n*e;var i=e.charAt(0),a=n*Number(e.substr(1));if("M"===i){var o=new Date(t);return o.setMonth(o.getMonth()+a)}if("L"===i)return Math.log(Math.pow(10,t)+a)/Math.LN10;if("D"===i){var s="D2"===e?O:R,l=t+.01*n,c=_.roundUp(m(l,1),s,r);return Math.floor(l)+Math.log(y.round(Math.pow(10,c),1))/Math.LN10}throw"unrecognized dtick "+String(e)},T.tickFirst=function(t){var e=t.range[1]n:n>c;)c=T.tickIncrement(c,i,e);return c}if("L"===u)return Math.log(r((Math.pow(10,n)-a)/f)*f+a)/Math.LN10;if("D"===u){var h="D2"===i?O:R,d=_.roundUp(m(n,1),h,e);return Math.floor(n)+Math.log(y.round(Math.pow(10,d),1))/Math.LN10}throw"unrecognized dtick "+String(i)};var I=y.time.format("%Y"),N=y.time.format("%b %Y"),j=y.time.format("%b %-d"),F=y.time.format("%b %-d %Hh"),D=y.time.format("%H:%M"),B=y.time.format(":%S"),U=/%(\d?)f/g;T.tickText=function(t,e,r){function n(n){var i;return void 0===n?!0:r?"none"===n:(i={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==i)}var i,a,o=s(t,e),h="array"===t.tickmode,d=r||h;if(h&&Array.isArray(t.ticktext)){var p=Math.abs(t.range[1]-t.range[0])/1e4;for(a=0;a1&&er&&(A=90),i(u,A)}c._lastangle=A}return o(e),e+" done"}function l(){c._boundingBox=r.node().getBoundingClientRect()}var u=r.selectAll("g."+C).data(L,S);if(!c.showticklabels||!b(n))return u.remove(),void o(e);var f,h,p,m,x;"x"===v?(x="bottom"===B?1:-1,f=function(t){return t.dx+I*x},m=n+(O+R)*x,h=function(t){return t.dy+m+t.fontSize*("bottom"===B?1:-.5)},p=function(t){return b(t)&&0!==t&&180!==t?0>t*x?"end":"start":"middle"}):(x="right"===B?1:-1,h=function(t){return t.dy+t.fontSize/2-I*x},f=function(t){return t.dx+n+(O+R+(90===Math.abs(c.tickangle)?t.fontSize/2:0))*x},p=function(t){return b(t)&&90===Math.abs(t)?"middle":"right"===B?"start":"end"});var k=0,A=0,T=[];u.enter().append("g").classed(C,1).append("text").attr("text-anchor","middle").each(function(e){var r=y.select(this),n=t._promises.length;r.call(M.setPosition,f(e),h(e)).call(M.font,e.font,e.fontSize,e.fontColor).text(e.text).call(w.convertToTspans),n=t._promises[n],n?T.push(t._promises.pop().then(function(){i(r,c.tickangle)})):i(r,c.tickangle)}),u.exit().remove(),u.each(function(t){k=Math.max(k,t.fontSize)}),i(u,c._lastangle||c.tickangle);var E=_.syncOrAsync([a,s,l]);return E&&E.then&&t._promises.push(E),E}function o(e){if(!r){var n,i,a,o,s=E.getFromId(t,e),l=y.select(t).selectAll("g."+e+"tick"),c={selection:l,side:s.side},f=e.charAt(0),h=t._fullLayout._size,d=1.5,p=s.titlefont.size;if(l.size()){var g=y.select(l.node().parentNode).attr("transform").match(/translate\(([-\.\d]+),([-\.\d]+)\)/);g&&(c.offsetLeft=+g[1],c.offsetTop=+g[2])}"x"===f?(i="free"===s.anchor?{_offset:h.t+(1-(s.position||0))*h.h,_length:0}:E.getFromId(t,s.anchor),a=s._offset+s._length/2,o=i._offset+("top"===s.side?-10-p*(d+(s.showticklabels?1:0)):i._length+10+p*(d+(s.showticklabels?1.5:.5))),s.rangeslider&&s.rangeslider.visible&&s._boundingBox&&(o+=(u.height-u.margin.b-u.margin.t)*s.rangeslider.thickness+s._boundingBox.height),c.side||(c.side="bottom")):(i="free"===s.anchor?{_offset:h.l+(s.position||0)*h.w,_length:0}:E.getFromId(t,s.anchor),o=s._offset+s._length/2,a=i._offset+("right"===s.side?i._length+10+p*(d+(s.showticklabels?1:.5)):-10-p*(d+(s.showticklabels?.5:0))),n={rotate:"-90",offset:0},c.side||(c.side="left")),k.draw(t,e+"title",{propContainer:s,propName:s._name+".title",dfltName:f.toUpperCase()+" axis",avoid:c,transform:n,attributes:{x:a,y:o,"text-anchor":"middle"}})}}function s(t,e){return t.visible!==!0||t.xaxis+t.yaxis!==e?!1:x.Plots.traceIs(t,"bar")&&t.orientation==={x:"h",y:"v"}[v]?!0:t.fill&&t.fill.charAt(t.fill.length-1)===v}function l(e,r,i){var a=e.gridlayer,o=e.zerolinelayer,l=e["hidegrid"+v]?[]:V,u=c._gridpath||"M0,0"+("x"===v?"v":"h")+r._length,f=a.selectAll("path."+z).data(c.showgrid===!1?[]:l,S);if(f.enter().append("path").classed(z,1).classed("crisp",1).attr("d",u).each(function(t){c.zeroline&&("linear"===c.type||"-"===c.type)&&Math.abs(t.x)g;g++){var y=c.mirrors[o._id+h[g]];"ticks"!==y&&"labels"!==y||(f[g]=!0)}return void 0!==n[2]&&(f[2]=!0),f.forEach(function(t,e){var r=n[e],i=U[e];t&&b(r)&&(d+=p(r+R*i,i*c.ticklen))}),i(r,d),l(e,o,t),a(r,n[3])}}).filter(function(t){return t&&t.then});return H.length?Promise.all(H):0},T.swap=function(t,e){for(var r=d(t,e),n=0;n2*n; -}function u(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}var f=t("fast-isnumeric"),h=t("tinycolor2").mix,d=t("../../lib"),p=t("../plots"),g=t("../../components/color/attributes").lightFraction,v=t("./layout_attributes"),m=t("./tick_value_defaults"),y=t("./tick_mark_defaults"),b=t("./tick_label_defaults"),x=t("./category_order_defaults"),_=t("./set_convert"),w=t("./ordered_categories"),k=t("./clean_datum"),A=t("./axis_ids");e.exports=function(t,e,r,i){function a(r,n){return d.coerce2(t,e,v,r,n)}var o=i.letter,s=i.font||{},l="Click to enter "+(i.title||o.toUpperCase()+" axis")+" title";i.name&&(e._name=i.name,e._id=A.name2id(i.name));var c=r("type");"-"===c&&(n(e,i.data),"-"===e.type?e.type="linear":c=t.type=e.type),_(e);var u=r("color"),p=u===t.color?u:s.color;r("title",l),d.coerceFont(r,"titlefont",{family:s.family,size:Math.round(1.2*s.size),color:p});var k=2===(t.range||[]).length&&f(t.range[0])&&f(t.range[1]),M=r("autorange",!k);M&&r("rangemode");var T=r("range",[-1,"x"===o?6:4]);T[0]===T[1]&&(e.range=[T[0]-1,T[0]+1]),d.noneOrAll(t.range,e.range,[0,1]),r("fixedrange"),m(t,e,r,c),b(t,e,r,c,i),y(t,e,r,i),x(t,e,r);var E=a("linecolor",u),L=a("linewidth"),S=r("showline",!!E||!!L);S||(delete e.linecolor,delete e.linewidth),(S||e.ticks)&&r("mirror");var C=a("gridcolor",h(u,i.bgColor,g).toRgbString()),z=a("gridwidth"),P=r("showgrid",i.showGrid||!!C||!!z);P||(delete e.gridcolor,delete e.gridwidth);var R=a("zerolinecolor",u),O=a("zerolinewidth"),I=r("zeroline",i.showGrid||!!R||!!O);return I||(delete e.zerolinecolor,delete e.zerolinewidth),e._initialCategories="category"===c?w(o,e.categoryorder,e.categoryarray,i.data):[],e}},{"../../components/color/attributes":302,"../../lib":382,"../plots":454,"./axis_ids":407,"./category_order_defaults":408,"./clean_datum":409,"./layout_attributes":414,"./ordered_categories":416,"./set_convert":419,"./tick_label_defaults":420,"./tick_mark_defaults":421,"./tick_value_defaults":422,"fast-isnumeric":117,tinycolor2:274}],407:[function(t,e,r){"use strict";function n(t,e,r){function n(t,r){for(var n=Object.keys(t),i=/^[xyz]axis[0-9]*/,a=[],o=0;o0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}},{}],409:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t){try{if("object"==typeof t&&null!==t&&t.getTime)return i.ms2DateTime(t);if("string"!=typeof t&&!n(t))return"";t=t.toString().replace(/['"%,$# ]/g,"")}catch(e){i.error(e,t)}return t}},{"../../lib":382,"fast-isnumeric":117}],410:[function(t,e,r){"use strict";e.exports={idRegex:{x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},attrRegex:{x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},BADNUM:void 0,xAxisMatch:/^xaxis[0-9]*$/,yAxisMatch:/^yaxis[0-9]*$/,AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,DBLCLICKDELAY:300,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,MAXDIST:20,YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,BENDPX:1.5,REDRAWDELAY:50}},{}],411:[function(t,e,r){"use strict";function n(t,e){var r,n=t.range[e],i=Math.abs(n-t.range[1-e]);return"date"===t.type?c.ms2DateTime(n,i):"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,o.format("."+r+"g")(Math.pow(10,n))):(r=Math.floor(Math.log(Math.abs(n))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,o.format("."+String(r)+"g")(n))}function i(t,e){return t?"nsew"===t?"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}function a(t){o.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var o=t("d3"),s=t("tinycolor2"),l=t("../../plotly"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../components/color"),h=t("../../components/drawing"),d=t("../../lib/setcursor"),p=t("../../components/dragelement"),g=t("./axes"),v=t("./select"),m=t("./constants"),y=!0;e.exports=function(t,e,r,o,b,x,_,w){function k(t,e){for(var r=0;r.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+ht+", "+dt+")").attr("d",ot+"Z"),ut=ft.append("path").attr("class","zoombox-corners").style({fill:f.background,stroke:f.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+ht+", "+dt+")").attr("d","M0,0Z"),T();for(var a=0;ai?(lt="",it.r=it.l,it.t=it.b,ut.attr("d","M0,0Z")):(it.t=0,it.b=V,lt="x",ut.attr("d","M"+(it.l-.5)+","+(nt-H-.5)+"h-3v"+(2*H+1)+"h3ZM"+(it.r+.5)+","+(nt-H-.5)+"h3v"+(2*H+1)+"h-3Z")):!Z||i.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),ut.transition().style("opacity",1).duration(200),st=!0)}function L(t,e,r){var n,i,a;for(n=0;nzoom back out","long"),y=!1)))}function C(e,r){var i=1===(_+w).length;if(e)I();else if(2!==r||i){if(1===r&&i){var a=_?B[0]:D[0],o="s"===_||"w"===w?0:1,s=a._name+".range["+o+"]",c=n(a,o),f="left",h="middle";if(a.fixedrange)return;_?(h="n"===_?"top":"bottom","right"===a.side&&(f="right")):"e"===w&&(f="right"),J.call(u.makeEditable,null,{immediate:!0,background:j.paper_bgcolor,text:String(c),fill:a.tickfont?a.tickfont.color:"#444",horizontalAlign:f,verticalAlign:h}).on("edit",function(e){var r="category"===a.type?a.c2l(e):a.d2l(e);void 0!==r&&l.relayout(t,s,r)})}}else O()}function z(e){function r(t,e,r){if(!t.fixedrange){A(t.range);var n=t.range,i=n[0]+(n[1]-n[0])*e;t.range=[i+(n[0]-i)*r,i+(n[1]-i)*r]}}if(t._context.scrollZoom||j._enablescrollzoom){var n=t.querySelector(".plotly");if(!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(gt);var i=-e.deltaY;if(isFinite(i)||(i=e.wheelDelta/10),!isFinite(i))return void c.log("Did not find wheel motion attributes: ",e);var a,o=Math.exp(-Math.min(Math.max(i,-20),20)/100),s=mt.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(e.clientX-s.left)/s.width,u=pt[0]+pt[2]*l,f=(s.bottom-e.clientY)/s.height,h=pt[1]+pt[3]*(1-f);if(w){for(a=0;a=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function i(t,e,r){for(var i=1-e,a=0,o=0;o0;n--)r.push(e);return r}function i(t,e){for(var r=[],n=0;nT;T++){var E=a[T],L=d[E];if(L)A[T]=w.getFromId(t,L.xaxis._id),M[T]=w.getFromId(t,L.yaxis._id);else{var S=o[E]._subplot;A[T]=S.xaxis,M[T]=S.yaxis}}var C=e.hovermode||o.hovermode;if(-1===["x","y","closest"].indexOf(C)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return _.unhoverRaw(t,e);var z,P,R,O,I,N,j,F,D,B,U,V,q=[],H=[];if(Array.isArray(e))for(C="array",R=0;RG||G>X.width||0>Y||Y>X.height)return _.unhoverRaw(t,e)}else G="xpx"in e?e.xpx:A[0]._length/2,Y="ypx"in e?e.ypx:M[0]._length/2;if(z="xval"in e?n(a,e.xval):i(A,G),P="yval"in e?n(a,e.yval):i(M,Y),!g(z[0])||!g(P[0]))return v.warn("Plotly.Fx.hover failed",e,t),_.unhoverRaw(t,e)}var W=1/0;for(O=0;O1||-1!==N.hoverinfo.indexOf("name")?N.name:void 0,index:!1,distance:Math.min(W,k.MAXDIST),color:b.defaultLine,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},V=q.length,"array"===F){var Z=e[O];"pointNumber"in Z?(U.index=Z.pointNumber,F="closest"):(F="","xval"in Z&&(D=Z.xval,F="x"),"yval"in Z&&(B=Z.yval,F=F?"closest":"y"))}else D=z[j],B=P[j];if(N._module&&N._module.hoverPoints){var K=N._module.hoverPoints(U,D,B,F);if(K)for(var $,Q=0;QV&&(q.splice(0,V),W=q[0].distance)}if(0===q.length)return _.unhoverRaw(t,e);var J="y"===C&&H.length>1;q.sort(function(t,e){return t.distance-e.distance});var tt=b.combine(o.plot_bgcolor||b.background,o.paper_bgcolor),et={hovermode:C,rotateLabels:J,bgColor:tt,container:o._hoverlayer,outerContainer:o._paperdiv},rt=c(q,et);u(q,J?"xa":"ya"),f(rt,J);var nt=t._hoverdata,it=[];for(R=0;R128?"#000":b.background;if(t.name&&void 0===t.zLabelVal){var u=document.createElement("p");u.innerHTML=t.name,r=u.textContent||"",r.length>15&&(r=r.substr(0,12)+"...")}void 0!==t.extraText&&(n+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(n+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(n+="y: "+t.yLabel+"
"),n+=(n?"z: ":"")+t.zLabel):M&&t[i+"Label"]===g?n=t[("x"===i?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(n=t.yLabel):n=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(n+=(n?"
":"")+t.text),""===n&&(""===r&&e.remove(),n=r);var f=e.select("text.nums").style("fill",c).call(x.setPosition,0,0).text(n).attr("data-notex",1).call(y.convertToTspans);f.selectAll("tspan.line").call(x.setPosition,0,0);var h=e.select("text.name"),v=0;r&&r!==n?(h.style("fill",l).text(r).call(x.setPosition,0,0).attr("data-notex",1).call(y.convertToTspans),h.selectAll("tspan.line").call(x.setPosition,0,0),v=h.node().getBoundingClientRect().width+2*P):(h.remove(),e.select("rect").remove()),e.select("path").style({fill:l,stroke:c});var m,k,E=f.node().getBoundingClientRect(),L=t.xa._offset+(t.x0+t.x1)/2,S=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),R=Math.abs(t.y1-t.y0),O=E.width+z+P+v;t.ty0=_-E.top,t.bx=E.width+2*P,t.by=E.height+2*P,t.anchor="start",t.txwidth=E.width,t.tx2width=v,t.offset=0,a?(t.pos=L,m=A>=S+R/2+O,k=S-R/2-O>=0,"top"!==t.idealAlign&&m||!k?m?(S+=R/2,t.anchor="start"):t.anchor="middle":(S-=R/2,t.anchor="end")):(t.pos=S,m=w>=L+C/2+O,k=L-C/2-O>=0,"left"!==t.idealAlign&&m||!k?m?(L+=C/2,t.anchor="start"):t.anchor="middle":(L-=C/2,t.anchor="end")),f.attr("text-anchor",t.anchor),v&&h.attr("text-anchor",t.anchor),e.attr("transform","translate("+L+","+S+")"+(a?"rotate("+T+")":""))}),S}function u(t,e){function r(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(.01>a)){if(-.01>i){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var c=0;for(o=0;oe.pmax&&c++;for(o=t.length-1;o>=0&&!(0>=c);o--)l=t[o],l.pos>e.pmax-1&&(l.del=!0,c--);for(o=0;o=c);o++)if(l=t[o],l.pos=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(0>=c);o--)l=t[o],l.pos+l.dp+l.size>e.pmax&&(l.del=!0,c--)}}}for(var n,i,a,o,s,l,c,u=0,f=t.map(function(t,r){var n=t[e];return[{i:r,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===n._id.charAt(0)?L:1)/2,pmin:n._offset,pmax:n._offset+n._length}]}).sort(function(t,e){return t[0].posref-e[0].posref});!n&&u<=t.length;){for(u++,n=!0,o=0;o.01&&p.pmin===g.pmin&&p.pmax===g.pmax){for(s=d.length-1;s>=0;s--)d[s].dp+=i;for(h.push.apply(h,d),f.splice(o+1,1),c=0,s=h.length-1;s>=0;s--)c+=h[s].dp;for(a=c/h.length,s=h.length-1;s>=0;s--)h[s].dp-=a;n=!1}else o++}f.forEach(r)}for(o=f.length-1;o>=0;o--){var v=f[o];for(s=v.length-1;s>=0;s--){var m=v[s],y=t[m.i];y.offset=m.dp,y.del=m.del}}}function f(t,e){t.each(function(t){var r=d.select(this);if(t.del)return void r.remove();var n="end"===t.anchor?-1:1,i=r.select("text.nums"),a={start:1,end:-1,middle:0}[t.anchor],o=a*(z+P),s=o+a*(t.txwidth+P),l=0,c=t.offset;"middle"===t.anchor&&(o-=t.tx2width/2,s-=t.tx2width/2),e&&(c*=-C,l=t.offset*S),r.select("path").attr("d","middle"===t.anchor?"M-"+t.bx/2+",-"+t.by/2+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(n*z+l)+","+(z+c)+"v"+(t.by/2-z)+"h"+n*t.bx+"v-"+t.by+"H"+(n*z+l)+"V"+(c-z)+"Z"),i.call(x.setPosition,o+l,c+t.ty0-t.by/2+P).selectAll("tspan.line").attr({x:i.attr("x"),y:i.attr("y")}),t.tx2width&&(r.select("text.name, text.name tspan.line").call(x.setPosition,s+a*P+l,c+t.ty0-t.by/2+P),r.select("rect").call(x.setRect,s+(a-1)*t.tx2width/2+l,c-t.by/2-1,t.tx2width,t.by+2))})}function h(t,e,r){if(!e.target)return!1;if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}var d=t("d3"),p=t("tinycolor2"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../lib/events"),y=t("../../lib/svg_text_utils"),b=t("../../components/color"),x=t("../../components/drawing"),_=t("../../components/dragelement"),w=t("./axes"),k=t("./constants"),A=t("./dragbox"),M=e.exports={};M.unhover=_.unhover,M.layoutAttributes={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom"},hovermode:{valType:"enumerated",values:["x","y","closest",!1]}},M.supplyLayoutDefaults=function(t,e,r){function n(r,n){return v.coerce(t,e,M.layoutAttributes,r,n)}n("dragmode");var i;if(e._has("cartesian")){var a=e._isHoriz=M.isHoriz(r);i=a?"y":"x"}else i="closest";n("hovermode",i)},M.isHoriz=function(t){for(var e=!0,r=0;rt._lastHoverTime+k.HOVERMINTIME?(o(t,e,r),void(t._lastHoverTime=Date.now())):void(t._hoverTimer=setTimeout(function(){o(t,e,r),t._lastHoverTime=Date.now(),t._hoverTimer=void 0},k.HOVERMINTIME))},M.getDistanceFunction=function(t,e,r,n){return"closest"===t?n||a(e,r):"x"===t?e:r},M.getClosest=function(t,e,r){if(r.index!==!1)r.index>=0&&r.indext*e||0===t?k.MAXDIST*(.6-.3/Math.max(3,Math.abs(t-e))):1/0}},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../lib":382,"../../lib/events":376,"../../lib/svg_text_utils":395,"./axes":405,"./constants":410,"./dragbox":411,d3:113,"fast-isnumeric":117,tinycolor2:274}],413:[function(t,e,r){"use strict";var n=t("../plots"),i=t("./constants");r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=i.idRegex,r.attrRegex=i.attrRegex,r.attributes=t("./attributes"),r.plot=function(t){function e(t,e){for(var r=[],n=0;nf[1]-.01&&(e.domain=[0,1]),i.noneOrAll(t.domain,e.domain,[0,1])}return e}},{"../../lib":382,"fast-isnumeric":117}],418:[function(t,e,r){"use strict";function n(t){return t._id}var i=t("../../lib/polygon"),a=t("../../components/color"),o=t("./axes"),s=t("./constants"),l=i.filter,c=i.tester,u=s.MINSELECT;e.exports=function(t,e,r,i,f){function h(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function d(t,e){return t-e}var p,g=i.gd._fullLayout._zoomlayer,v=i.element.getBoundingClientRect(),m=i.plotinfo.x()._offset,y=i.plotinfo.y()._offset,b=e-v.left,x=r-v.top,_=b,w=x,k="M"+b+","+x,A=i.xaxes[0]._length,M=i.yaxes[0]._length,T=i.xaxes.map(n),E=i.yaxes.map(n),L=i.xaxes.concat(i.yaxes);"lasso"===f&&(p=l([[b,x]],s.BENDPX));var S=g.selectAll("path.select-outline").data([1,2]);S.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t}).attr("transform","translate("+m+", "+y+")").attr("d",k+"Z");var C,z,P,R,O,I=g.append("path").attr("class","zoombox-corners").style({fill:a.background,stroke:a.defaultLine,"stroke-width":1}).attr("transform","translate("+m+", "+y+")").attr("d","M0,0Z"),N=[],j=i.gd,F=[];for(C=0;C0)return Math.log(e)/Math.LN10;if(0>=e&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*u*Math.abs(n-i))}return o.BADNUM}function r(t){return Math.pow(10,t)}function c(t){return i(t)?Number(t):o.BADNUM}var u=10;if(t.c2l="log"===t.type?e:c,t.l2c="log"===t.type?r:c,t.l2d=function(e){return t.c2d(t.l2c(e))},t.p2d=function(e){return t.l2d(t.p2l(e))},t.setScale=function(){var e,r=t._gd._fullLayout._size;if(t._categories||(t._categories=[]),t.overlaying){var n=l.getFromId(t._gd,t.overlaying);t.domain=n.domain}for(t.range&&2===t.range.length&&t.range[0]!==t.range[1]||(t.range=[-1,1]),e=0;2>e;e++)i(t.range[e])||(t.range[e]=i(t.range[1-e])?t.range[1-e]*(e?10:.1):e?1:-1),t.range[e]<-(Number.MAX_VALUE/2)?t.range[e]=-(Number.MAX_VALUE/2):t.range[e]>Number.MAX_VALUE/2&&(t.range[e]=Number.MAX_VALUE/2);if("y"===t._id.charAt(0)?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[0]-t.range[1]),t._b=-t._m*t.range[1]):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[1]-t.range[0]),t._b=-t._m*t.range[0]),!isFinite(t._m)||!isFinite(t._b))throw a.notifier("Something went wrong with axis scaling","long"),t._gd._replotting=!1,new Error("axis scaling")},t.l2p=function(e){return i(e)?n.round(t._b+t._m*e,2):o.BADNUM},t.p2l=function(e){return(e-t._b)/t._m},t.c2p=function(e,r){return t.l2p(t.c2l(e,r))},t.p2c=function(e){return t.l2c(t.p2l(e))},-1!==["linear","log","-"].indexOf(t.type))t.c2d=c,t.d2c=function(t){return t=s(t),i(t)?Number(t):o.BADNUM},t.d2l=function(e,r){return"log"===t.type?t.c2l(t.d2c(e),r):t.d2c(e)};else if("date"===t.type){if(t.c2d=function(t){return i(t)?a.ms2DateTime(t):o.BADNUM},t.d2c=function(t){return i(t)?Number(t):a.dateTime2ms(t)},t.d2l=t.d2c,t.range&&t.range.length>1)try{var f=t.range.map(a.dateTime2ms);!i(t.range[0])&&i(f[0])&&(t.range[0]=f[0]),!i(t.range[1])&&i(f[1])&&(t.range[1]=f[1])}catch(h){a.error(h,t.range)}}else"category"===t.type&&(t.c2d=function(e){return t._categories[Math.round(e)]},t.d2c=function(e){null!==e&&void 0!==e&&-1===t._categories.indexOf(e)&&t._categories.push(e);var r=t._categories.indexOf(e);return-1===r?o.BADNUM:r},t.d2l=t.d2c);t.makeCalcdata=function(e,r){var n,i,a;if(r in e)for(n=e[r],i=new Array(n.length),a=0;an?"0":"1.0"}var r=this.framework,n=r.select("g.choroplethlayer"),i=r.select("g.scattergeolayer"),a=this.projection,o=this.path,s=this.clipAngle;r.selectAll("path.basepath").attr("d",o),r.selectAll("path.graticulepath").attr("d",o),n.selectAll("path.choroplethlocation").attr("d",o),n.selectAll("path.basepath").attr("d",o),i.selectAll("path.js-line").attr("d",o),null!==s?(i.selectAll("path.point").style("opacity",e).attr("transform",t),i.selectAll("text").style("opacity",e).attr("transform",t)):(i.selectAll("path.point").attr("transform",t),i.selectAll("text").attr("transform",t))}},{"../../components/color":303,"../../components/drawing":326,"../../constants/xmlns_namespaces":370,"../../lib/filter_visible":378,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"./constants":424,"./projections":432,"./set_scale":433,"./zoom":434,"./zoom_reset":435,d3:113,topojson:275}],426:[function(t,e,r){"use strict";var n=t("./geo"),i=t("../../plots/plots");r.name="geo",r.attr="geo",r.idRoot="geo",r.idRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"geo");void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var o=0;o=n}function a(t,e){for(var r=e[0],n=e[1],i=!1,a=0,o=t.length,s=o-1;o>a;s=a++){var l=t[a],c=l[0],u=l[1],f=t[s],h=f[0],d=f[1];u>n^d>n&&(h-c)*(n-u)/(d-u)+c>r&&(i=!i)}return i}function o(t){return t?t/Math.sin(t):1}function s(t){return t>1?P:-1>t?-P:Math.asin(t)}function l(t){return t>1?0:-1>t?z:Math.acos(t)}function c(t,e){var r=(2+P)*Math.sin(e);e/=2;for(var n=0,i=1/0;10>n&&Math.abs(i)>S;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(z*(4+z))*t*(1+Math.cos(e)),2*Math.sqrt(z/(4+z))*Math.sin(e)]}function u(t,e){function r(r,n){var i=j(r/e,n);return i[0]*=t,i}return arguments.length<2&&(e=t),1===e?j:e===1/0?h:(r.invert=function(r,n){var i=j.invert(r/t,n);return i[0]*=e,i},r)}function f(){var t=2,e=N(u),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}function h(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function d(t,e){return[3*t/(2*z)*Math.sqrt(z*z/3-e*e),e]}function p(t,e){return[t,1.25*Math.log(Math.tan(z/4+.4*e))]}function g(t){return function(e){var r,n=t*Math.sin(e),i=30;do e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e));while(Math.abs(r)>S&&--i>0);return e/2}}function v(t,e,r){function n(r,n){return[t*r*Math.cos(n=i(n)),e*Math.sin(n)]}var i=g(r);return n.invert=function(n,i){var a=s(i/e);return[n/(t*Math.cos(a)),s((2*a+Math.sin(2*a))/r)]},n}function m(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(-.013791+n*(.003971*r-.001529*n))),e*(1.007226+r*(.015085+n*(-.044475+.028874*r-.005916*n)))]}function y(t,e){var r,n=Math.min(18,36*Math.abs(e)/z),i=Math.floor(n),a=n-i,o=(r=D[i])[0],s=r[1],l=(r=D[++i])[0],c=r[1],u=(r=D[Math.min(19,++i)])[0],f=r[1];return[t*(l+a*(u-o)/2+a*a*(u-2*l+o)/2),(e>0?P:-P)*(c+a*(f-s)/2+a*a*(f-2*c+s)/2)]}function b(t,e){return[t*Math.cos(e),e]}function x(t,e){var r=Math.cos(e),n=o(l(r*Math.cos(t/=2)));return[2*r*Math.sin(t)*n,Math.sin(e)*n]}function _(t,e){var r=x(t,e);return[(r[0]+t/P)/2,(r[1]+e)/2]}t.geo.project=function(t,e){var n=e.stream;if(!n)throw new Error("not yet supported");return(t&&w.hasOwnProperty(t.type)?w[t.type]:r)(t,n)};var w={Feature:e,FeatureCollection:function(t,r){return{type:"FeatureCollection",features:t.features.map(function(t){return e(t,r)})}}},k=[],A=[],M={point:function(t,e){k.push([t,e])},result:function(){var t=k.length?k.length<2?{type:"Point",coordinates:k[0]}:{type:"MultiPoint",coordinates:k}:null;return k=[],t}},T={lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){k.length&&(A.push(k),k=[])},result:function(){var t=A.length?A.length<2?{type:"LineString",coordinates:A[0]}:{type:"MultiLineString",coordinates:A}:null;return A=[],t}},E={polygonStart:n,lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){var t=k.length;if(t){do k.push(k[0].slice());while(++t<4);A.push(k),k=[]}},polygonEnd:n,result:function(){if(!A.length)return null;var t=[],e=[];return A.forEach(function(r){i(r)?t.push([r]):e.push(r)}),e.forEach(function(e){var r=e[0];t.some(function(t){return a(t[0],r)?(t.push(e),!0):void 0})||t.push([e])}),A=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},L={Point:M,MultiPoint:M,LineString:T,MultiLineString:T,Polygon:E,MultiPolygon:E,Sphere:E},S=1e-6,C=S*S,z=Math.PI,P=z/2,R=(Math.sqrt(z),z/180),O=180/z,I=t.geo.projection,N=t.geo.projectionMutator;t.geo.interrupt=function(e){function r(t,r){for(var n=0>r?-1:1,i=l[+(0>r)],a=0,o=i.length-1;o>a&&t>i[a][2][0];++a);var s=e(t-i[a][1][0],r);return s[0]+=e(i[a][1][0],n*r>n*i[a][0][1]?i[a][0][1]:r)[0],s}function n(){s=l.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})})}function i(){for(var e=1e-6,r=[],n=0,i=l[0].length;i>n;++n){var o=l[0][n],s=180*o[0][0]/z,c=180*o[0][1]/z,u=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[s+e,c+e],[s+e,u-e],[f-e,u-e],[f-e,h+e]],30))}for(var n=l[1].length-1;n>=0;--n){var o=l[1][n],s=180*o[0][0]/z,c=180*o[0][1]/z,u=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[f-e,h-e],[f-e,u+e],[s+e,u+e],[s+e,c-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}function a(t,e){for(var r,n,i,a=-1,o=t.length,s=t[0],l=[];++ac;++c)l.push([s[0]+c*n,s[1]+c*i]);s=r}return l.push(r),l}function o(t,e){return Math.abs(t[0]-e[0])n)],a=l[+(0>n)],c=0,u=i.length;u>c;++c){var f=i[c];if(f[0][0]<=t&&tS&&--i>0);return[t/(.8707+(a=n*n)*(-.131979+a*(-.013791+a*a*a*(.003971-.001529*a)))),n]},(t.geo.naturalEarth=function(){return I(m)}).raw=m;var D=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];D.forEach(function(t){t[1]*=1.0144}),y.invert=function(t,e){var r=e/P,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],c=l-o,u=l-2*s+o,f=2*(Math.abs(r)-s)/c,h=u/c,d=f*(1-h*f*(1-2*h*f));if(d>=0||1===a){n=(e>=0?5:-5)*(d+i);var p,g=50;do i=Math.min(18,Math.abs(n)/5),a=Math.floor(i),d=i-a,o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],n-=(p=(e>=0?P:-P)*(s+d*(l-o)/2+d*d*(l-2*s+o)/2)-e)*O;while(Math.abs(p)>C&&--g>0);break}}while(--a>=0);var v=D[a][0],m=D[a+1][0],y=D[Math.min(19,a+2)][0];return[t/(m+d*(y-v)/2+d*d*(y-2*m+v)/2),n*R]},(t.geo.robinson=function(){return I(y)}).raw=y,b.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return I(b)}).raw=b,x.invert=function(t,e){if(!(t*t+4*e*e>z*z+S)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),c=Math.cos(r/2),u=Math.sin(n),f=Math.cos(n),h=Math.sin(2*n),d=u*u,p=f*f,g=s*s,v=1-p*c*c,m=v?l(f*c)*Math.sqrt(a=1/v):a=0,y=2*m*f*s-t,b=m*u-e,x=a*(p*g+m*f*c*d),_=a*(.5*o*h-2*m*u*s),w=.25*a*(h*s-m*u*p*o),k=a*(d*c+m*g*f),A=_*w-k*x;if(!A)break;var M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return I(x)}).raw=x,_.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),c=Math.sin(2*n),u=s*s,f=o*o,h=Math.sin(r),d=Math.cos(r/2),p=Math.sin(r/2),g=p*p,v=1-f*d*d,m=v?l(o*d)*Math.sqrt(a=1/v):a=0,y=.5*(2*m*o*p+r/P)-t,b=.5*(m*s+n)-e,x=.5*a*(f*g+m*o*d*u)+.5/P,_=a*(h*c/4-m*s*p),w=.125*a*(c*p-m*s*f*h),k=.5*a*(u*d+m*g*o)+.5,A=_*w-k*x,M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return I(_)}).raw=_}e.exports=n},{}],433:[function(t,e,r){"use strict";function n(t,e){var r=t.projection,n=t.lonaxis,o=t.lataxis,l=t.domain,c=t.framewidth||0,u=e.w*(l.x[1]-l.x[0]),f=e.h*(l.y[1]-l.y[0]),h=n.range[0]+s,d=n.range[1]-s,p=o.range[0]+s,g=o.range[1]-s,v=n._fullRange[0]+s,m=n._fullRange[1]-s,y=o._fullRange[0]+s,b=o._fullRange[1]-s;r._translate0=[e.l+u/2,e.t+f/2];var x=d-h,_=g-p,w=[h+x/2,p+_/2],k=r._rotate;r._center=[w[0]+k[0],w[1]+k[1]];var A=function(e){function n(t){return Math.min(_*u/(t[1][0]-t[0][0]),_*f/(t[1][1]-t[0][1]))}var o,s,l,x,_=e.scale(),w=r._translate0,k=i(h,p,d,g),A=i(v,y,m,b);l=a(e,k),o=n(l),x=a(e,A),r._fullScale=n(x),e.scale(o),l=a(e,k),s=[w[0]-l[0][0]+c,w[1]-l[0][1]+c],r._translate=s,e.translate(s),l=a(e,k),t._isAlbersUsa||e.clipExtent(l),o=r.scale*o,r._scale=o,t._width=Math.round(l[1][0])+c,t._height=Math.round(l[1][1])+c,t._marginX=(u-Math.round(l[1][0]))/2,t._marginY=(f-Math.round(l[1][1]))/2};return A}function i(t,e,r,n){var i=(r-t)/4;return{type:"Polygon",coordinates:[[[t,e],[t,n],[t+i,n],[t+2*i,n],[t+3*i,n],[r,n],[r,e],[r-i,e],[r-2*i,e],[r-3*i,e],[t,e]]]}}function a(t,e){return o.geo.path().projection(t).bounds(e)}var o=t("d3"),s=t("./constants").clipPad;e.exports=n},{"./constants":424,d3:113}],434:[function(t,e,r){"use strict";function n(t,e){var r;return(r=e._isScoped?a:e._clipAngle?s:o)(t,e.projection)}function i(t,e){var r=e._fullScale;return _.behavior.zoom().translate(t.translate()).scale(t.scale()).scaleExtent([.5*r,100*r])}function a(t,e){function r(){_.select(this).style(A)}function n(){o.scale(_.event.scale).translate(_.event.translate),t.render()}function a(){_.select(this).style(M)}var o=t.projection,s=i(o,e);return s.on("zoomstart",r).on("zoom",n).on("zoomend",a),s}function o(t,e){function r(t){return v.invert(t)}function n(t){var e=v(r(t));return Math.abs(e[0]-t[0])>y||Math.abs(e[1]-t[1])>y}function a(){_.select(this).style(A),l=_.mouse(this),c=v.rotate(),u=v.translate(),f=c,h=r(l)}function o(){return d=_.mouse(this),n(l)?(m.scale(v.scale()),void m.translate(v.translate())):(v.scale(_.event.scale),v.translate([u[0],_.event.translate[1]]),h?r(d)&&(g=r(d),p=[f[0]+(g[0]-h[0]),c[1],c[2]],v.rotate(p),f=p):(l=d,h=r(l)),void t.render())}function s(){_.select(this).style(M)}var l,c,u,f,h,d,p,g,v=t.projection,m=i(v,e),y=2;return m.on("zoomstart",a).on("zoom",o).on("zoomend",s),m}function s(t,e){function r(t){m++||t({type:"zoomstart"})}function n(t){t({type:"zoom"})}function a(t){--m||t({type:"zoomend"})}var o,s=t.projection,d={r:s.rotate(),k:s.scale()},p=i(s,e),g=x(p,"zoomstart","zoom","zoomend"),m=0,y=p.on;return p.on("zoomstart",function(){_.select(this).style(A);var t=_.mouse(this),e=s.rotate(),i=e,a=s.translate(),m=c(e);o=l(s,t),y.call(p,"zoom",function(){var r=_.mouse(this);if(s.scale(d.k=_.event.scale),o){if(l(s,r)){s.rotate(e).translate(a);var c=l(s,r),p=f(o,c),y=v(u(m,p)),b=d.r=h(y,o,i);isFinite(b[0])&&isFinite(b[1])&&isFinite(b[2])||(b=i),s.rotate(b),i=b}}else t=r,o=l(s,t);n(g.of(this,arguments))}),r(g.of(this,arguments))}).on("zoomend",function(){_.select(this).style(M),y.call(p,"zoom",null),a(g.of(this,arguments))}).on("zoom.redraw",function(){t.render()}),_.rebind(p,g,"on")}function l(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&m(r)}function c(t){var e=.5*t[0]*w,r=.5*t[1]*w,n=.5*t[2]*w,i=Math.sin(e),a=Math.cos(e),o=Math.sin(r),s=Math.cos(r),l=Math.sin(n),c=Math.cos(n);return[a*s*c+i*o*l,i*s*c-a*o*l,a*o*c+i*s*l,a*s*l-i*o*c]}function u(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],l=e[2],c=e[3];return[r*o-n*s-i*l-a*c,r*s+n*o+i*c-a*l,r*l-n*c+i*o+a*s,r*c+n*l-i*s+a*o]}function f(t,e){if(t&&e){var r=b(t,e),n=Math.sqrt(y(r,r)),i=.5*Math.acos(Math.max(-1,Math.min(1,y(t,e)))),a=Math.sin(i)/n;return n&&[Math.cos(i),r[2]*a,-r[1]*a,r[0]*a]}}function h(t,e,r){var n=g(e,2,t[0]);n=g(n,1,t[1]),n=g(n,0,t[2]-r[2]);var i,a,o=e[0],s=e[1],l=e[2],c=n[0],u=n[1],f=n[2],h=Math.atan2(s,o)*k,p=Math.sqrt(o*o+s*s);Math.abs(u)>p?(a=(u>0?90:-90)-h,i=0):(a=Math.asin(u/p)*k-h,i=Math.sqrt(p*p-u*u));var v=180-a-2*h,m=(Math.atan2(f,c)-Math.atan2(l,i))*k,y=(Math.atan2(f,c)-Math.atan2(l,-i))*k,b=d(r[0],r[1],a,m),x=d(r[0],r[1],v,y);return x>=b?[a,m,r[2]]:[v,y,r[2]]}function d(t,e,r,n){var i=p(r-t),a=p(n-e);return Math.sqrt(i*i+a*a)}function p(t){return(t%360+540)%360-180}function g(t,e,r){var n=r*w,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function v(t){return[Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),1-2*(t[1]*t[1]+t[2]*t[2]))*k,Math.asin(Math.max(-1,Math.min(1,2*(t[0]*t[2]-t[3]*t[1]))))*k,Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),1-2*(t[2]*t[2]+t[3]*t[3]))*k]}function m(t){var e=t[0]*w,r=t[1]*w,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function y(t,e){for(var r=0,n=0,i=t.length;i>n;++n)r+=t[n]*e[n];return r}function b(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function x(t){for(var e=0,r=arguments.length,n=[];++ed;++d){for(e=c[d],r=t[this.scene[e]._name],n=/Click to enter .+ title/.test(r.title)?"":r.title,p=0;2>=p;p+=2)this.labelEnable[d+p]=!1,this.labels[d+p]=o(n),this.labelColor[d+p]=s(r.titlefont.color),this.labelFont[d+p]=r.titlefont.family,this.labelSize[d+p]=r.titlefont.size,this.labelPad[d+p]=this.getLabelPad(e,r),this.tickEnable[d+p]=!1,this.tickColor[d+p]=s((r.tickfont||{}).color),this.tickAngle[d+p]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[d+p]=this.getTickPad(r),this.tickMarkLength[d+p]=0,this.tickMarkWidth[d+p]=r.tickwidth||0,this.tickMarkColor[d+p]=s(r.tickcolor),this.borderLineEnable[d+p]=!1,this.borderLineColor[d+p]=s(r.linecolor),this.borderLineWidth[d+p]=r.linewidth||0;u=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!u,l=this.hasAxisInAltrPos(e,r)&&!u,i=r.mirror||!1,f=u?-1!==String(i).indexOf("all"):!!i,h=u?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[d]=!0:l&&(this.labelEnable[d+2]=!0),a?this.tickEnable[d]=r.showticklabels:l&&(this.tickEnable[d+2]=r.showticklabels),(a||f)&&(this.borderLineEnable[d]=r.showline),(l||f)&&(this.borderLineEnable[d+2]=r.showline),(a||h)&&(this.tickMarkLength[d]=this.getTickMarkLength(r)),(l||h)&&(this.tickMarkLength[d+2]=this.getTickMarkLength(r)),this.gridLineEnable[d]=r.showgrid,this.gridLineColor[d]=s(r.gridcolor),this.gridLineWidth[d]=r.gridwidth,this.zeroLineEnable[d]=r.zeroline,this.zeroLineColor[d]=s(r.zerolinecolor),this.zeroLineWidth[d]=r.zerolinewidth}},l.hasSharedAxis=function(t){var e=this.scene,r=a.Plots.getSubplotIds(e.fullLayout,"gl2d"),n=a.Axes.findSubplotsWithAxis(r,t);return 0!==n.indexOf(e.id)},l.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},l.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},l.getLabelPad=function(t,e){var r=1.5,n=e.titlefont.size,i=e.showticklabels;return"xaxis"===t?"top"===e.side?-10+n*(r+(i?1:0)):-10+n*(r+(i?.5:0)):"yaxis"===t?"right"===e.side?10+n*(r+(i?1:.5)):10+n*(r+(i?.5:0)):void 0},l.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},l.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e},e.exports=i},{"../../lib/html2unicode":381,"../../lib/str2rgbarray":394,"../../plotly":402}],438:[function(t,e,r){"use strict";var n=t("./scene2d"),i=t("../plots"),a=t("../../constants/xmlns_namespaces");r.name="gl2d",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex={x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},r.attrRegex={x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},r.attributes=t("../cartesian/attributes"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"gl2d"),o=0;or;++r){var n=t[r],i=e[r];if(n.length!==i.length)return!0;for(var a=0;ao;++o,--s)for(var l=0;r>l;++l)for(var c=0;4>c;++c){var u=i[4*(r*o+l)+c];i[4*(r*o+l)+c]=i[4*(r*s+l)+c],i[4*(r*s+l)+c]=u}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),d=h.createImageData(r,n);d.data.set(i),h.putImageData(d,0,0);var p;switch(t){case"jpeg":p=f.toDataURL("image/jpeg");break;case"webp":p=f.toDataURL("image/webp");break;default:p=f.toDataURL("image/png")}return this.staticPlot&&this.container.removeChild(a),p},m.computeTickMarks=function(){this.xaxis._length=this.glplot.viewBox[2]-this.glplot.viewBox[0],this.yaxis._length=this.glplot.viewBox[3]-this.glplot.viewBox[1];for(var t=[s.calcTicks(this.xaxis),s.calcTicks(this.yaxis)],e=0;2>e;++e)for(var r=0;rk;++k)w[k]=Math.min(w[k],a.bounds[k]),w[k+2]=Math.max(w[k+2],a.bounds[k+2])}var A;for(n=0;2>n;++n)w[n]>w[n+2]&&(w[n]=-1,w[n+2]=1),A=this[v[n]],A._length=y.viewBox[n+2]-y.viewBox[n],s.doAutoRange(A);y.ticks=this.computeTickMarks();var M=this.xaxis.range,T=this.yaxis.range;y.dataBox=[M[0],T[0],M[1],T[1]],y.merge(r),o.update(y),this.glplot.draw()},m.draw=function(){if(!this.stopped){requestAnimationFrame(this.redraw);var t=this.glplot,e=this.camera,r=e.mouseListener,n=this.fullLayout;this.cameraChanged();var i=r.x*t.pixelRatio,a=this.canvas.height-t.pixelRatio*r.y;if(e.boxEnabled&&"zoom"===n.dragmode)this.selectBox.enabled=!0,this.selectBox.selectBox=[Math.min(e.boxStart[0],e.boxEnd[0]),Math.min(e.boxStart[1],e.boxEnd[1]),Math.max(e.boxStart[0],e.boxEnd[0]),Math.max(e.boxStart[1],e.boxEnd[1])],t.setDirty();else{this.selectBox.enabled=!1;var o=n._size,s=this.xaxis.domain,c=this.yaxis.domain,u=t.pick(i/t.pixelRatio+o.l+s[0]*o.w,a/t.pixelRatio-(o.t+(1-c[1])*o.h));if(u&&n.hovermode){var f=u.object._trace.handlePick(u);if(f&&(!this.lastPickResult||this.lastPickResult.trace!==f.trace||this.lastPickResult.dataCoord[0]!==f.dataCoord[0]||this.lastPickResult.dataCoord[1]!==f.dataCoord[1])){var h=this.lastPickResult=f;this.spikes.update({center:u.dataCoord}),h.screenCoord=[((t.viewBox[2]-t.viewBox[0])*(u.dataCoord[0]-t.dataBox[0])/(t.dataBox[2]-t.dataBox[0])+t.viewBox[0])/t.pixelRatio,(this.canvas.height-(t.viewBox[3]-t.viewBox[1])*(u.dataCoord[1]-t.dataBox[1])/(t.dataBox[3]-t.dataBox[1])-t.viewBox[1])/t.pixelRatio];var d=h.hoverinfo;if("all"!==d){var p=d.split("+");-1===p.indexOf("x")&&(h.traceCoord[0]=void 0),-1===p.indexOf("y")&&(h.traceCoord[1]=void 0),-1===p.indexOf("z")&&(h.traceCoord[2]=void 0),-1===p.indexOf("text")&&(h.textLabel=void 0),-1===p.indexOf("name")&&(h.name=void 0)}l.loneHover({x:h.screenCoord[0],y:h.screenCoord[1],xLabel:this.hoverFormatter("xaxis",h.traceCoord[0]),yLabel:this.hoverFormatter("yaxis",h.traceCoord[1]),zLabel:h.traceCoord[2],text:h.textLabel,name:h.name,color:h.color},{container:this.svgContainer}),this.lastPickResult={dataCoord:u.dataCoord}}}else!u&&this.lastPickResult&&(this.spikes.update({}),this.lastPickResult=null,l.loneUnhover(this.svgContainer))}t.draw()}},m.hoverFormatter=function(t,e){if(void 0!==e){var r=this[t];return s.tickText(r,r.c2l(e),"hover").text}}},{"../../lib/html2unicode":381,"../../lib/show_no_webgl_msg":392,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"./camera":436,"./convert":437,"gl-plot2d":165,"gl-select-box":195,"gl-spikes2d":215}],440:[function(t,e,r){"use strict";function n(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]),"zoomMin"in e&&(r[0]=e.zoomMin),"zoomMax"in e&&(r[1]=e.zoomMax);var n=a({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],c=0,u=t.clientWidth,f=t.clientHeight,h={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=i(),r=this.delay,a=e-2*r;n.idle(e-r),n.recalcMatrix(a),n.flush(e-(100+2*r));for(var o=!0,s=n.computedMatrix,h=0;16>h;++h)o=o&&l[h]===s[h],l[h]=s[h];var d=t.clientWidth===u&&t.clientHeight===f;return u=t.clientWidth,f=t.clientHeight,o?!d:(c=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),a=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var o=i();n._active.lookAt(o,r,a,e),n._active.lookAt(o+500,r,a,[0,0,1]),n._active.flush(o)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return c},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var d=0,p=0;return o(t,function(e,r,a,o){var s="rotate"===h.keyBindingMode,l="pan"===h.keyBindingMode,u="zoom"===h.keyBindingMode,f=!!o.control,g=!!o.alt,v=!!o.shift,m=!!(1&e),y=!!(2&e),b=!!(4&e),x=1/t.clientHeight,_=x*(r-d),w=x*(a-p),k=h.flipX?1:-1,A=h.flipY?1:-1,M=i(),T=Math.PI*h.rotateSpeed;if((s&&m&&!f&&!g&&!v||m&&!f&&!g&&v)&&n.rotate(M,k*T*_,-A*T*w,0),(l&&m&&!f&&!g&&!v||y||m&&f&&!g&&!v)&&n.pan(M,-h.translateSpeed*_*c,h.translateSpeed*w*c,0),u&&m&&!f&&!g&&!v||b||m&&!f&&g&&!v){var E=-h.zoomSpeed*w/window.innerHeight*(M-n.lastT())*100;n.pan(M,0,0,c*(Math.exp(E)-1))}return d=r,p=a,!0}),s(t,function(t,e){var r=h.flipX?1:-1,a=h.flipY?1:-1,o=i();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*h.rotateSpeed/window.innerWidth);else{var s=-h.zoomSpeed*a*e/window.innerHeight*(o-n.lastT())/100;n.pan(o,0,0,c*(Math.exp(s)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],441:[function(t,e,r){"use strict";function n(t,e){for(var r=0;3>r;++r){var n=s[r];e[n]._gd=t}}var i=t("./scene"),a=t("../plots"),o=t("../../constants/xmlns_namespaces"),s=["xaxis","yaxis","zaxis"];r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,o=a.getSubplotIds(e,"gl3d");e._paperdiv.style({width:e.width+"px",height:e.height+"px"}),t._context.setBackground(t,e.paper_bgcolor);for(var s=0;sr;++r){var n=t[c[r]];e.labels[r]=o(n.title),"titlefont"in n&&(n.titlefont.color&&(e.labelColor[r]=s(n.titlefont.color)),n.titlefont.family&&(e.labelFont[r]=n.titlefont.family),n.titlefont.size&&(e.labelSize[r]=n.titlefont.size)),"showline"in n&&(e.lineEnable[r]=n.showline),"linecolor"in n&&(e.lineColor[r]=s(n.linecolor)),"linewidth"in n&&(e.lineWidth[r]=n.linewidth),"showgrid"in n&&(e.gridEnable[r]=n.showgrid),"gridcolor"in n&&(e.gridColor[r]=s(n.gridcolor)),"gridwidth"in n&&(e.gridWidth[r]=n.gridwidth), -"log"===n.type?e.zeroEnable[r]=!1:"zeroline"in n&&(e.zeroEnable[r]=n.zeroline),"zerolinecolor"in n&&(e.zeroLineColor[r]=s(n.zerolinecolor)),"zerolinewidth"in n&&(e.zeroLineWidth[r]=n.zerolinewidth),"ticks"in n&&n.ticks?e.lineTickEnable[r]=!0:e.lineTickEnable[r]=!1,"ticklen"in n&&(e.lineTickLength[r]=e._defaultLineTickLength[r]=n.ticklen),"tickcolor"in n&&(e.lineTickColor[r]=s(n.tickcolor)),"tickwidth"in n&&(e.lineTickWidth[r]=n.tickwidth),"tickangle"in n&&(e.tickAngle[r]="auto"===n.tickangle?0:Math.PI*-n.tickangle/180),"showticklabels"in n&&(e.tickEnable[r]=n.showticklabels),"tickfont"in n&&(n.tickfont.color&&(e.tickColor[r]=s(n.tickfont.color)),n.tickfont.family&&(e.tickFont[r]=n.tickfont.family),n.tickfont.size&&(e.tickSize[r]=n.tickfont.size)),"mirror"in n?-1!==["ticks","all","allticks"].indexOf(n.mirror)?(e.lineTickMirror[r]=!0,e.lineMirror[r]=!0):n.mirror===!0?(e.lineTickMirror[r]=!1,e.lineMirror[r]=!0):(e.lineTickMirror[r]=!1,e.lineMirror[r]=!1):e.lineMirror[r]=!1,"showbackground"in n&&n.showbackground!==!1?(e.backgroundEnable[r]=!0,e.backgroundColor[r]=s(n.backgroundcolor)):e.backgroundEnable[r]=!1}},e.exports=i},{"../../../lib/html2unicode":381,"../../../lib/str2rgbarray":394,arraytools:49}],446:[function(t,e,r){"use strict";function n(t,e,r,n){for(var a=r("bgcolor"),l=i.combine(a,n.paper_bgcolor),c=Object.keys(o.camera),u=0;ue;++e){var r=t[o[e]];this.enabled[e]=r.showspikes,this.colors[e]=a(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness}},e.exports=i},{"../../../lib/str2rgbarray":394}],449:[function(t,e,r){"use strict";function n(t){for(var e=new Array(3),r=0;3>r;++r){for(var n=t[r],i=new Array(n.length),a=0;au;++u){var f=i[s[u]];if(f._length=(r[u].hi-r[u].lo)*r[u].pixelsPerDataUnit/t.dataScale[u],Math.abs(f._length)===1/0)c[u]=[];else{f.range[0]=r[u].lo/t.dataScale[u],f.range[1]=r[u].hi/t.dataScale[u],f._m=1/(t.dataScale[u]*r[u].pixelsPerDataUnit),f.range[0]===f.range[1]&&(f.range[0]-=1,f.range[1]+=1);var h=f.tickmode;if("auto"===f.tickmode){f.tickmode="linear";var d=f.nticks||a.Lib.constrain(f._length/40,4,9);a.Axes.autoTicks(f,Math.abs(f.range[1]-f.range[0])/d)}for(var p=a.Axes.calcTicks(f),g=0;gu;++u){l[u]=.5*(t.glplot.bounds[0][u]+t.glplot.bounds[1][u]);for(var g=0;2>g;++g)e.bounds[g][u]=t.glplot.bounds[g][u]}t.contourLevels=n(c)}e.exports=i;var a=t("../../../plotly"),o=t("../../../lib/html2unicode"),s=["xaxis","yaxis","zaxis"],l=[0,0,0]},{"../../../lib/html2unicode":381,"../../../plotly":402}],450:[function(t,e,r){"use strict";function n(t,e){var r,n,i=[0,0,0,0];for(r=0;4>r;++r)for(n=0;4>n;++n)i[n]+=t[4*r+n]*e[r];return i}function i(t,e){var r=n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])));return r}e.exports=i},{}],451:[function(t,e,r){"use strict";function n(t){function e(e,r){if("string"==typeof r)return r;var n=t.fullSceneLayout[e];return g.tickText(n,n.c2l(r),"hover").text}var r,n=t.svgContainer,i=t.container.getBoundingClientRect(),a=i.width,o=i.height;n.setAttributeNS(null,"viewBox","0 0 "+a+" "+o),n.setAttributeNS(null,"width",a),n.setAttributeNS(null,"height",o),A(t),t.glplot.axes.update(t.axesOptions);for(var s=Object.keys(t.traces),l=null,c=t.glplot.selection,u=0;ua;++a)l=u[T[a]],_(l);t?Array.isArray(t)||(t=[t]):t=[];var h=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]];for(a=0;ao;++o)h[0][o]>h[1][o]?d[o]=1:h[1][o]===h[0][o]?d[o]=1:d[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=d,a=0;aa;++a){if(l=u[T[a]],c=l.type,c in x?(x[c].acc*=d[a],x[c].count+=1):x[c]={acc:d[a],count:1},l.autorange){for(y[0][a]=1/0,y[1][a]=-(1/0),o=0;oy[1][a])y[0][a]=-1,y[1][a]=1;else{var k=y[1][a]-y[0][a];y[0][a]-=k/32,y[1][a]+=k/32}}else{var A=u[T[a]].range;y[0][a]=A[0],y[1][a]=A[1]}y[0][a]===y[1][a]&&(y[0][a]-=1,y[1][a]+=1),b[a]=y[1][a]-y[0][a],this.glplot.bounds[0][a]=y[0][a]*d[a],this.glplot.bounds[1][a]=y[1][a]*d[a]}var M=[1,1,1];for(a=0;3>a;++a){l=u[T[a]],c=l.type;var E=x[c];M[a]=Math.pow(E.acc,1/E.count)/d[a]}var L,S=4;if("auto"===u.aspectmode)L=Math.max.apply(null,M)/Math.min.apply(null,M)<=S?M:[1,1,1];else if("cube"===u.aspectmode)L=[1,1,1];else if("data"===u.aspectmode)L=M;else{if("manual"!==u.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var C=u.aspectratio;L=[C.x,C.y,C.z]}u.aspectratio.x=f.aspectratio.x=L[0],u.aspectratio.y=f.aspectratio.y=L[1],u.aspectratio.z=f.aspectratio.z=L[2],this.glplot.aspect=L;var z=u.domain||null,P=e._size||null;if(z&&P){var R=this.container.style;R.position="absolute",R.left=P.l+z.x[0]*P.w+"px",R.top=P.t+(1-z.y[1])*P.h+"px",R.width=P.w*(z.x[1]-z.x[0])+"px",R.height=P.h*(z.y[1]-z.y[0])+"px"}this.glplot.redraw()}},M.destroy=function(){this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null},M.setCameraToDefault=function(){this.setCamera({eye:{x:1.25,y:1.25,z:1.25},center:{x:0,y:0,z:0},up:{x:0,y:0,z:1}})},M.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),c(this.glplot.camera)},M.setCamera=function(t){var e={};e[this.id]=t,this.glplot.camera.lookAt.apply(this,l(t)),this.graphDiv.emit("plotly_relayout",e)},M.saveCamera=function(t){function e(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}var r=this.getCamera(),n=d.nestedProperty(t,this.id+".camera"),i=n.get(),a=!1;if(void 0===i)a=!0;else for(var o=0;3>o;o++)for(var s=0;3>s;s++)if(!e(r,i,o,s)){a=!0;break}return a&&n.set(r),a},M.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},M.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(u),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;o>a;++a,--o)for(var s=0;r>s;++s)for(var l=0;4>l;++l){var c=i[4*(r*a+s)+l];i[4*(r*a+s)+l]=i[4*(r*o+s)+l],i[4*(r*o+s)+l]=c}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),d=h.createImageData(r,n);d.data.set(i),h.putImageData(d,0,0);var p;switch(t){case"jpeg":p=f.toDataURL("image/jpeg");break;case"webp":p=f.toDataURL("image/webp");break;default:p=f.toDataURL("image/png")}return this.staticMode&&this.container.removeChild(u),p},e.exports=a},{"../../lib":382,"../../lib/show_no_webgl_msg":392,"../../lib/str2rgbarray":394,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../../plots/plots":454,"./camera":440,"./layout/convert":445,"./layout/spikes":448,"./layout/tick_marks":449,"./project":450,"./set_convert":452,"gl-plot3d":183}],452:[function(t,e,r){"use strict";var n=t("../cartesian/axes"),i=function(){};e.exports=function(t){n.setConvert(t),t.setScale=i}},{"../cartesian/axes":405}],453:[function(t,e,r){"use strict";var n=t("../plotly"),i=t("./font_attributes"),a=t("../components/color/attributes"),o=n.Lib.extendFlat;e.exports={font:{family:o({},i.family,{dflt:'"Open Sans", verdana, arial, sans-serif'}),size:o({},i.size,{dflt:12}),color:o({},i.color,{dflt:a.defaultLine})},title:{valType:"string",dflt:"Click to enter Plot title"},titlefont:o({},i,{}),autosize:{valType:"enumerated",values:[!0,!1,"initial"]},width:{valType:"number",min:10,dflt:700},height:{valType:"number",min:10,dflt:450},margin:{l:{valType:"number",min:0,dflt:80},r:{valType:"number",min:0,dflt:80},t:{valType:"number",min:0,dflt:100},b:{valType:"number",min:0,dflt:80},pad:{valType:"number",min:0,dflt:0},autoexpand:{valType:"boolean",dflt:!0}},paper_bgcolor:{valType:"color",dflt:a.background},plot_bgcolor:{valType:"color",dflt:a.background},separators:{valType:"string",dflt:".,"},hidesources:{valType:"boolean",dflt:!1},smith:{valType:"enumerated",values:[!1],dflt:!1},showlegend:{valType:"boolean"},_composedModules:{"*":"Fx"},_nestedModules:{xaxis:"Axes",yaxis:"Axes",scene:"gl3d",geo:"geo",legend:"Legend",annotations:"Annotations",shapes:"Shapes",images:"Images",ternary:"ternary",mapbox:"mapbox"}}},{"../components/color/attributes":302,"../plotly":402,"./font_attributes":423}],454:[function(t,e,r){"use strict";function n(t){return"object"==typeof t&&(t=t.type),t}function i(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#","class":"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){f.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}function a(t,e){for(var r,n=Object.keys(e),i=0;i=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var s=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),c=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&i(t,s),l.text(s.text()&&c.text()?" - ":"")},f.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=o.select(t).append("div").attr("id","hiddenform").style("display","none"),n=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"}),i=n.append("input").attr({type:"text",name:"data"});return i.node().value=f.graphJson(t,!1,"keepdata"),n.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1},f.supplyDefaults=function(t){var e,r,n=t._fullLayout||{},i=t._fullLayout={},o=t.layout||{},s=t._fullData||[],u=t._fullData=[],h=t.data||[],d=i._modules=[],p=i._basePlotModules=[];for(f.supplyLayoutGlobalDefaults(o,i),i._dataLength=h.length,e=0;ea&&(e=(r-1)/(i.l+i.r),i.l=Math.floor(e*i.l),i.r=Math.floor(e*i.r)),0>o&&(e=(n-1)/(i.t+i.b),i.t=Math.floor(e*i.t),i.b=Math.floor(e*i.b))}},f.autoMargin=function(t,e,r){var n=t._fullLayout;if(n._pushmargin||(n._pushmargin={}),n.margin.autoexpand!==!1){if(r){var i=void 0===r.pad?12:r.pad;r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];t._replotting||f.doAutoMargin(t)}},f.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),a=Math.max(e.margin.r||0,0),o=Math.max(e.margin.t||0,0),c=Math.max(e.margin.b||0,0),u=e._pushmargin;return e.margin.autoexpand!==!1&&(u.base={l:{val:0,size:i},r:{val:1,size:a},t:{val:1,size:o},b:{val:0,size:c}},Object.keys(u).forEach(function(t){var r=u[t].l||{},n=u[t].b||{},l=r.val,f=r.size,h=n.val,d=n.size;Object.keys(u).forEach(function(t){if(s(f)&&u[t].r){var r=u[t].r.val,n=u[t].r.size;if(r>l){var p=(f*r+(n-e.width)*l)/(r-l),g=(n*(1-l)+(f-e.width)*(1-r))/(r-l);p>=0&&g>=0&&p+g>i+a&&(i=p,a=g)}}if(s(d)&&u[t].t){var v=u[t].t.val,m=u[t].t.size;if(v>h){var y=(d*v+(m-e.height)*h)/(v-h),b=(m*(1-h)+(d-e.height)*(1-v))/(v-h);y>=0&&b>=0&&y+b>c+o&&(c=y,o=b)}}})})),r.l=Math.round(i),r.r=Math.round(a),r.t=Math.round(o),r.b=Math.round(c),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,t._replotting||"{}"===n||n===JSON.stringify(e._size)?void 0:l.plot(t)},f.graphJson=function(t,e,r,n,i){function a(t){if("function"==typeof t)return null;if(c.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0&&!c.isPlainObject(t.stream))continue}else if("keepall"!==r&&(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0))continue;i[e]=a(t[e])}return i}return Array.isArray(t)?t.map(a):t&&t.getTime?c.ms2DateTime(t):t}(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&f.supplyDefaults(t);var o=i?t._fullData:t.data,s=i?t._fullLayout:t.layout,l={data:(o||[]).map(function(t){var r=a(t);return e&&delete r.fit,r})};return e||(l.layout=a(s)),t.framework&&t.framework.isPolar&&(l=t.framework.getConfig()),"object"===n?l:JSON.stringify(l)}},{"../components/color":303,"../lib":382,"../plotly":402,"./attributes":403,"./font_attributes":423,"./layout_attributes":453,d3:113,"fast-isnumeric":117}],455:[function(t,e,r){"use strict";var n=t("../../traces/scatter/attributes"),i=n.marker;e.exports={r:n.r,t:n.t,marker:{color:i.color,size:i.size,symbol:i.symbol,opacity:i.opacity}}},{"../../traces/scatter/attributes":556}],456:[function(t,e,r){"use strict";function n(t,e){var r={showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}};return a({},e,r)}var i=t("../cartesian/layout_attributes"),a=t("../../lib/extend").extendFlat,o=a({},i.domain,{});e.exports={radialaxis:n("radial",{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:n("angular",{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}}},{"../../lib/extend":377,"../cartesian/layout_attributes":414}],457:[function(t,e,r){var n=t("../../plotly"),i=t("d3"),a=e.exports={version:"0.2.2",manager:t("./micropolar_manager")},o=n.Lib.extendDeepAll;a.Axis=function(){function t(t){r=t||r;var c=l.data,f=l.layout;return("string"==typeof r||r.nodeName)&&(r=i.select(r)),r.datum(c).each(function(t,r){function l(t,e){return s(t)%360+f.orientation}var c=t.slice();u={data:a.util.cloneJson(c),layout:a.util.cloneJson(f)};var h=0;c.forEach(function(t,e){t.color||(t.color=f.defaultColorRange[h],h=(h+1)%f.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:i.rgb(t.color).darker().toString()),u.data[e].color=t.color,u.data[e].strokeColor=t.strokeColor,u.data[e].strokeDash=t.strokeDash,u.data[e].strokeSize=t.strokeSize});var d=c.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||r===!0}),p=!1,g=d.map(function(t,e){return p=p||"undefined"!=typeof t.groupId,t});if(p){var v=i.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),m=[],y=v.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],m.push(r),r=a.util.sumArrays(t.r,r)}),t.values});d=i.merge(y)}d.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var b=Math.min(f.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2;b=Math.max(10,b);var x,_=[f.margin.left+b,f.margin.top+b];if(p){var w=i.max(a.util.sumArrays(a.util.arrayLast(d).r[0],a.util.arrayLast(m)));x=[0,w]}else x=i.extent(a.util.flattenArray(d.map(function(t,e){return t.r})));f.radialAxis.domain!=a.DATAEXTENT&&(x[0]=0),n=i.scale.linear().domain(f.radialAxis.domain!=a.DATAEXTENT&&f.radialAxis.domain?f.radialAxis.domain:x).range([0,b]),u.layout.radialAxis.domain=n.domain();var k,A=a.util.flattenArray(d.map(function(t,e){return t.t})),M="string"==typeof A[0];M&&(A=a.util.deduplicate(A),k=A.slice(),A=i.range(A.length),d=d.map(function(t,e){var r=t;return t.t=[A],p&&(r.yStack=t.yStack),r}));var T=d.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===d.length,E=null===f.needsEndSpacing?M||!T:f.needsEndSpacing,L=f.angularAxis.domain&&f.angularAxis.domain!=a.DATAEXTENT&&!M&&f.angularAxis.domain[0]>=0,S=L?f.angularAxis.domain:i.extent(A),C=Math.abs(A[1]-A[0]);T&&!M&&(C=0);var z=S.slice();E&&M&&(z[1]+=C);var P=f.angularAxis.ticksCount||4;P>8&&(P=P/(P/8)+P%8),f.angularAxis.ticksStep&&(P=(z[1]-z[0])/P);var R=f.angularAxis.ticksStep||(z[1]-z[0])/(P*(f.minorTicks+1));k&&(R=Math.max(Math.round(R),1)),z[2]||(z[2]=R);var O=i.range.apply(this,z);if(O=O.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=i.scale.linear().domain(z.slice(0,2)).range("clockwise"===f.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=s.domain(),u.layout.angularAxis.endPadding=E?C:0,e=i.select(this).select("svg.chart-root"),"undefined"==typeof e||e.empty()){var I="' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '",N=(new DOMParser).parseFromString(I,"application/xml"),j=this.appendChild(this.ownerDocument.importNode(N.documentElement,!0)); -e=i.select(j)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var F,D=e.select(".chart-group"),B={fill:"none",stroke:f.tickColor},U={"font-size":f.font.size,"font-family":f.font.family,fill:f.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+f.font.outlineColor}).join(",")};if(f.showLegend){F=e.select(".legend-group").attr({transform:"translate("+[b,f.margin.top]+")"}).style({display:"block"});var V=d.map(function(t,e){var r=a.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});a.Legend().config({data:d.map(function(t,e){return t.name||"Element"+e}),legendConfig:o({},a.Legend.defaultConfig().legendConfig,{container:F,elements:V,reverseOrder:f.legend.reverseOrder})})();var q=F.node().getBBox();b=Math.min(f.width-q.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2,b=Math.max(10,b),_=[f.margin.left+b,f.margin.top+b],n.range([0,b]),u.layout.radialAxis.domain=n.domain(),F.attr("transform","translate("+[_[0]+b,_[1]-b]+")")}else F=e.select(".legend-group").style({display:"none"});e.attr({width:f.width,height:f.height}).style({opacity:f.opacity}),D.attr("transform","translate("+_+")").style({cursor:"crosshair"});var H=[(f.width-(f.margin.left+f.margin.right+2*b+(q?q.width:0)))/2,(f.height-(f.margin.top+f.margin.bottom+2*b))/2];if(H[0]=Math.max(0,H[0]),H[1]=Math.max(0,H[1]),e.select(".outer-group").attr("transform","translate("+H+")"),f.title){var G=e.select("g.title-group text").style(U).text(f.title),Y=G.node().getBBox();G.attr({x:_[0]-Y.width/2,y:_[1]-b-20})}var X=e.select(".radial.axis-group");if(f.radialAxis.gridLinesVisible){var W=X.selectAll("circle.grid-circle").data(n.ticks(5));W.enter().append("circle").attr({"class":"grid-circle"}).style(B),W.attr("r",n),W.exit().remove()}X.select("circle.outside-circle").attr({r:b}).style(B);var Z=e.select("circle.background-circle").attr({r:b}).style({fill:f.backgroundColor,stroke:f.stroke});if(f.radialAxis.visible){var K=i.svg.axis().scale(n).ticks(5).tickSize(5);X.call(K).attr({transform:"rotate("+f.radialAxis.orientation+")"}),X.selectAll(".domain").style(B),X.selectAll("g>text").text(function(t,e){return this.textContent+f.radialAxis.ticksSuffix}).style(U).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===f.radialAxis.tickOrientation?"rotate("+-f.radialAxis.orientation+") translate("+[0,U["font-size"]]+")":"translate("+[0,U["font-size"]]+")"}}),X.selectAll("g>line").style({stroke:"black"})}var $=e.select(".angular.axis-group").selectAll("g.angular-tick").data(O),Q=$.enter().append("g").classed("angular-tick",!0);$.attr({transform:function(t,e){return"rotate("+l(t,e)+")"}}).style({display:f.angularAxis.visible?"block":"none"}),$.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(f.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(f.minorTicks+1)==0)}).style(B),Q.selectAll(".minor").style({stroke:f.minorTickColor}),$.select("line.grid-line").attr({x1:f.tickLength?b-f.tickLength:0,x2:b}).style({display:f.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(U);var J=$.select("text.axis-text").attr({x:b+f.labelOffset,dy:".35em",transform:function(t,e){var r=l(t,e),n=b+f.labelOffset,i=f.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?270>r&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(180>=r&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:f.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(f.minorTicks+1)!=0?"":k?k[t]+f.angularAxis.ticksSuffix:t+f.angularAxis.ticksSuffix}).style(U);f.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(f.minorTicks+1)!=0?"":f.angularAxis.rewriteTicks(this.textContent,e)});var tt=i.max(D.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));F.attr({transform:"translate("+[b+tt,f.margin.top]+")"});var et=e.select("g.geometry-group").selectAll("g").size()>0,rt=e.select("g.geometry-group").selectAll("g.geometry").data(d);if(rt.enter().append("g").attr({"class":function(t,e){return"geometry geometry"+e}}),rt.exit().remove(),d[0]||et){var nt=[];d.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=s,r.container=rt.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=f.orientation,r.direction=f.direction,r.index=e,nt.push({data:t,geometryConfig:r})});var it=i.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(nt),at=[];it.forEach(function(t,e){"unstacked"===t.key?at=at.concat(t.values.map(function(t,e){return[t]})):at.push(t.values)}),at.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return o(a[r].defaultConfig(),t)});a[r]().config(n)()})}var ot,st,lt=e.select(".guides-group"),ct=e.select(".tooltips-group"),ut=a.tooltipPanel().config({container:ct,fontSize:8})(),ft=a.tooltipPanel().config({container:ct,fontSize:8})(),ht=a.tooltipPanel().config({container:ct,hasTick:!0})();if(!M){var dt=lt.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});D.on("mousemove.angular-guide",function(t,e){var r=a.util.getMousePos(Z).angle;dt.attr({x2:-b,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-f.orientation)%360;ot=s.invert(n);var i=a.util.convertToCartesian(b+12,r+180);ut.text(a.util.round(ot)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){lt.select("line").style({opacity:0})})}var pt=lt.select("circle").style({stroke:"grey",fill:"none"});D.on("mousemove.radial-guide",function(t,e){var r=a.util.getMousePos(Z).radius;pt.attr({r:r}).style({opacity:.5}),st=n.invert(a.util.getMousePos(Z).radius);var i=a.util.convertToCartesian(r,f.radialAxis.orientation);ft.text(a.util.round(st)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){pt.style({opacity:0}),ht.hide(),ut.hide(),ft.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(t,r){var n=i.select(this),o=n.style("fill"),s="black",l=n.style("opacity")||1;if(n.attr({"data-opacity":l}),"none"!=o){n.attr({"data-fill":o}),s=i.hsl(o).darker().toString(),n.style({fill:s,opacity:1});var c={t:a.util.round(t[0]),r:a.util.round(t[1])};M&&(c.t=k[t[0]]);var u="t: "+c.t+", r: "+c.r,f=this.getBoundingClientRect(),h=e.node().getBoundingClientRect(),d=[f.left+f.width/2-H[0]-h.left,f.top+f.height/2-H[1]-h.top];ht.config({color:s}).text(u),ht.move(d)}else o=n.style("stroke"),n.attr({"data-stroke":o}),s=i.hsl(o).darker().toString(),n.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){return 0!=i.event.which?!1:void(i.select(this).attr("data-fill")&&ht.show())}).on("mouseout.tooltip",function(t,e){ht.hide();var r=i.select(this),n=r.attr("data-fill");n?r.style({fill:n,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})}),h}var e,r,n,s,l={data:[],layout:{}},c={},u={},f=i.dispatch("hover"),h={};return h.render=function(e){return t(e),this},h.config=function(t){if(!arguments.length)return l;var e=a.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),o(l.data[e],a.Axis.defaultConfig().data[0]),o(l.data[e],t)}),o(l.layout,a.Axis.defaultConfig().layout),o(l.layout,e.layout),this},h.getLiveConfig=function(){return u},h.getinputConfig=function(){return c},h.radialScale=function(t){return n},h.angularScale=function(t){return s},h.svg=function(){return e},i.rebind(h,f,"on"),h},a.Axis.defaultConfig=function(t,e){var r={data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:i.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}};return r},a.util={},a.DATAEXTENT="dataExtent",a.AREA="AreaChart",a.LINE="LinePlot",a.DOT="DotPlot",a.BAR="BarChart",a.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},a.util._extend=function(t,e){for(var r in t)e[r]=t[r]},a.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},a.util.dataFromEquation2=function(t,e){var r=e||6,n=i.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180,i=t(n);return[e,i]});return n},a.util.dataFromEquation=function(t,e,r){var n=e||6,a=[],o=[];i.range(0,360+n,n).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},a.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return i.range(e).map(function(t,e){return r[e]||r[0]})},a.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=a.util.ensureArray(t[e],r)}),t},a.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},a.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},a.util.sumArrays=function(t,e){return i.zip(t,e).map(function(t,e){return i.sum(t)})},a.util.arrayLast=function(t){return t[t.length-1]},a.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},a.util.flattenArray=function(t){for(var e=[];!a.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},a.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},a.util.convertToCartesian=function(t,e){var r=e*Math.PI/180,n=t*Math.cos(r),i=t*Math.sin(r);return[n,i]},a.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},a.util.getMousePos=function(t){var e=i.mouse(t.node()),r=e[0],n=e[1],a={};return a.x=r,a.y=n,a.pos=e,a.angle=180*(Math.atan2(n,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+n*n),a},a.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;a>i;i++)e=t[i],e in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},a.util.duplicates=function(t){return Object.keys(a.util.duplicatesCount(t))},a.util.translator=function(t,e,r,n){if(n){var i=r.slice();r=e,e=i}var a=e.reduce(function(t,e){return"undefined"!=typeof t?t[e]:void 0},t);"undefined"!=typeof a&&(e.reduce(function(t,r,n){return"undefined"!=typeof t?(n===e.length-1&&delete t[r],t[r]):void 0},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=a),t[e]},t))},a.PolyChart=function(){function t(){var t=r[0].geometryConfig,e=t.container;"string"==typeof e&&(e=i.select(e)),e.datum(r).each(function(e,r){function n(e,r){var n=t.radialScale(e[1]),i=(t.angularScale(e[0])+t.orientation)*Math.PI/180;return{r:n,t:i}}function a(t){var e=t.r*Math.cos(t.t),r=t.r*Math.sin(t.t);return{x:e,y:r}}var o=!!e[0].data.yStack,l=e.map(function(t,e){return o?i.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):i.zip(t.data.t[0],t.data.r[0])}),c=t.angularScale,u=t.radialScale.domain()[0],f={};f.bar=function(r,n,a){var o=e[a].data,s=t.radialScale(r[1])-t.radialScale(0),l=t.radialScale(r[2]||0),u=o.barWidth;i.select(this).attr({"class":"mark bar",d:"M"+[[s+l,-u/2],[s+l,u/2],[l,u/2],[l,-u/2]].join("L")+"Z",transform:function(e,r){return"rotate("+(t.orientation+c(e[0]))+")"}})},f.dot=function(t,r,o){var s=t[2]?[t[0],t[1]+t[2]]:t,l=i.svg.symbol().size(e[o].data.dotSize).type(e[o].data.dotType)(t,r);i.select(this).attr({"class":"mark dot",d:l,transform:function(t,e){var r=a(n(s));return"translate("+[r.x,r.y]+")"}})};var h=i.svg.line.radial().interpolate(e[0].data.lineInterpolation).radius(function(e){return t.radialScale(e[1])}).angle(function(e){return t.angularScale(e[0])*Math.PI/180});f.line=function(r,n,a){var o=r[2]?l[a].map(function(t,e){return[t[0],t[1]+t[2]]}):l[a];if(i.select(this).each(f.dot).style({opacity:function(t,r){return+e[a].data.dotVisible},fill:v.stroke(r,n,a)}).attr({"class":"mark dot"}),!(n>0)){var s=i.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({"class":"line",d:h(o),transform:function(e,r){return"rotate("+(t.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return v.fill(r,n,a)},"fill-opacity":0,stroke:function(t,e){return v.stroke(r,n,a)},"stroke-width":function(t,e){return v["stroke-width"](r,n,a)},"stroke-dasharray":function(t,e){return v["stroke-dasharray"](r,n,a)},opacity:function(t,e){return v.opacity(r,n,a)},display:function(t,e){return v.display(r,n,a)}})}};var d=t.angularScale.range(),p=Math.abs(d[1]-d[0])/l[0].length*Math.PI/180,g=i.svg.arc().startAngle(function(t){return-p/2}).endAngle(function(t){return p/2}).innerRadius(function(e){return t.radialScale(u+(e[2]||0))}).outerRadius(function(e){return t.radialScale(u+(e[2]||0))+t.radialScale(e[1])});f.arc=function(e,r,n){i.select(this).attr({"class":"mark arc",d:g,transform:function(e,r){return"rotate("+(t.orientation+c(e[0])+90)+")"}})};var v={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,n){return s[e[n].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return"undefined"==typeof e[n].data.visible||e[n].data.visible?"block":"none"}},m=i.select(this).selectAll("g.layer").data(l);m.enter().append("g").attr({"class":"layer"});var y=m.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({"class":"mark"}),y.style(v).each(f[t.geometryType]),y.exit().remove(),m.exit().remove()})}var e,r=[a.PolyChart.defaultConfig()],n=i.dispatch("hover"),s={solid:"none",dash:[5,2],dot:[2,5]};return t.config=function(t){return arguments.length?(t.forEach(function(t,e){r[e]||(r[e]={}),o(r[e],a.PolyChart.defaultConfig()),o(r[e],t)}),this):r},t.getColorScale=function(){return e},i.rebind(t,n,"on"),t},a.PolyChart.defaultConfig=function(){var t={data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:i.scale.category20()}};return t},a.BarChart=function(){return a.PolyChart()},a.BarChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"bar"}};return t},a.AreaChart=function(){return a.PolyChart()},a.AreaChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"arc"}};return t},a.DotPlot=function(){return a.PolyChart()},a.DotPlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"dot",dotType:"circle"}};return t},a.LinePlot=function(){return a.PolyChart()},a.LinePlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"line"}};return t},a.Legend=function(){function t(){var r=e.legendConfig,n=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=o({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=i.merge(n);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||"undefined"==typeof r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var s=r.container;("string"==typeof s||s.nodeName)&&(s=i.select(s));var l=a.map(function(t,e){return t.color}),c=r.fontSize,u=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,f=u?r.height:c*a.length,h=s.classed("legend-group",!0),d=h.selectAll("svg").data([0]),p=d.enter().append("svg").attr({width:300,height:f+c,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});p.append("g").classed("legend-axis",!0),p.append("g").classed("legend-marks",!0);var g=i.range(a.length),v=i.scale[u?"linear":"ordinal"]().domain(g).range(l),m=i.scale[u?"linear":"ordinal"]().domain(g)[u?"range":"rangePoints"]([0,f]),y=function(t,e){var r=3*e;return"line"===t?"M"+[[-e/2,-e/12],[e/2,-e/12],[e/2,e/12],[-e/2,e/12]]+"Z":-1!=i.svg.symbolTypes.indexOf(t)?i.svg.symbol().type(t).size(r)():i.svg.symbol().type("square").size(r)()};if(u){var b=d.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);b.enter().append("stop"),b.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),d.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var x=d.select(".legend-marks").selectAll("path.legend-mark").data(a);x.enter().append("path").classed("legend-mark",!0),x.attr({transform:function(t,e){return"translate("+[c/2,m(e)+c/2]+")"},d:function(t,e){var r=t.symbol;return y(r,c)},fill:function(t,e){return v(e)}}),x.exit().remove()}var _=i.svg.axis().scale(m).orient("right"),w=d.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:c,c/2]+")"}).call(_);return w.selectAll(".domain").style({fill:"none",stroke:"none"}),w.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),w.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),t}var e=a.Legend.defaultConfig(),r=i.dispatch("hover");return t.config=function(t){return arguments.length?(o(e,t),this):e},i.rebind(t,r,"on"),t},a.Legend.defaultConfig=function(t,e){var r={data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}};return r},a.tooltipPanel=function(){var t,e,r,n={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+a.tooltipPanel.uid++,l=10,c=function(){t=n.container.selectAll("g."+s).data([0]);var i=t.enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=i.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=i.append("text").attr({dx:n.padding+l,dy:.3*+n.fontSize}),c};return c.text=function(a){var o=i.hsl(n.color).l,s=o>=.5?"#aaa":"white",u=o>=.5?"black":"white",f=a||"";e.style({fill:u,"font-size":n.fontSize+"px"}).text(f);var h=n.padding,d=e.node().getBBox(),p={fill:n.color,stroke:s,"stroke-width":"2px"},g=d.width+2*h+l,v=d.height+2*h;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[n.hasTick?0:l,0],[l,v/4],[l,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[l,-v/2+2*h]+")"}),t.style({display:"block"}),c},c.move=function(e){return t?(t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),c):void 0},c.hide=function(){return t?(t.style({display:"none"}),c):void 0},c.show=function(){return t?(t.style({display:"block"}),c):void 0},c.config=function(t){return o(n,t),c},c},a.tooltipPanel.uid=1,a.adapter={},a.adapter.plotly=function(){var t={};return t.convert=function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=o({},t),i=[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]];return i.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",n.dotVisible===!0?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var n=a.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var i=n.indexOf(t.geometry);-1!=i&&(r.data[e].groupId=i)})}if(t.layout){var s=o({},t.layout),l=[[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]];if(l.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&"undefined"!=typeof s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&"undefined"!=typeof s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&"undefined"!=typeof s.margin.t){var c=["t","r","b","l","pad"],u=["top","right","bottom","left","pad"],f={};i.entries(s.margin).forEach(function(t,e){f[u[c.indexOf(t.key)]]=t.value}),s.margin=f}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r},t}},{"../../plotly":402,"./micropolar_manager":458,d3:113}],458:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("d3"),a=t("./undo_manager"),o=e.exports={},s=n.Lib.extendDeepAll;o.framework=function(t){function e(e,a){return a&&(f=a),i.select(i.select(f).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),r=r?s(r,e):e,c||(c=n.micropolar.Axis()),u=n.micropolar.adapter.plotly().convert(r),c.config(u).render(f),t.data=r.data,t.layout=r.layout,o.fillLayout(t),r}var r,l,c,u,f,h=new a;return e.isPolar=!0,e.svg=function(){return c.svg()},e.getConfig=function(){return r},e.getLiveConfig=function(){return n.micropolar.adapter.plotly().convert(c.getLiveConfig(),!0)},e.getLiveScales=function(){return{t:c.angularScale(),r:c.radialScale()}},e.setUndoPoint=function(){var t=this,e=n.micropolar.util.cloneJson(r);!function(e,r){h.add({undo:function(){r&&t(r)},redo:function(){t(e)}})}(e,l),l=n.micropolar.util.cloneJson(e)},e.undo=function(){h.undo()},e.redo=function(){h.redo()},e},o.fillLayout=function(t){var e=i.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:n.Color.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../plotly":402,"./undo_manager":459,d3:113}],459:[function(t,e,r){"use strict";e.exports=function(){function t(t,e){return t?(i=!0,t[e](),i=!1,this):this}var e,r=[],n=-1,i=!1;return{add:function(t){return i?this:(r.splice(n+1,r.length-n),r.push(t),n=r.length-1,this)},setCallback:function(t){e=t},undo:function(){var i=r[n];return i?(t(i,"undo"),n-=1,e&&e(i.undo),this):this},redo:function(){var i=r[n+1];return i?(t(i,"redo"),n+=1,e&&e(i.redo),this):this},clear:function(){r=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return ng;g++){var v=d[g];s=t[v]?t[v]:t[v]={},e[v]=l={},o("domain."+h,[g/p,(g+1)/p]),o("domain."+{x:"y",y:"x"}[h]),a.id=v,f(s,l,o,a)}}},{"../lib":382,"./plots":454}],461:[function(t,e,r){"use strict";var n=t("./ternary"),i=t("../../plots/plots");r.name="ternary",r.attr="subplot",r.idRoot="ternary",r.idRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"ternary"),o=0;o=o&&(d.min=0,p.min=0,g.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}var i=t("../../../components/color"),a=t("../../subplot_defaults"),o=t("./layout_attributes"),s=t("./axis_defaults"),l=["aaxis","baxis","caxis"];e.exports=function(t,e,r){a(t,e,r,{type:"ternary",attributes:o,handleDefaults:n,font:e.font,paper_bgcolor:e.paper_bgcolor})}},{"../../../components/color":303,"../../subplot_defaults":460,"./axis_defaults":464,"./layout_attributes":466}],466:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("./axis_attributes");e.exports={domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},bgcolor:{valType:"color",dflt:n.background},sum:{valType:"number",dflt:1,min:0},aaxis:i,baxis:i,caxis:i}},{"../../../components/color/attributes":302,"./axis_attributes":463}],467:[function(t,e,r){"use strict";function n(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework()}function i(t){a.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var a=t("d3"),o=t("tinycolor2"),s=t("../../plotly"),l=t("../../lib"),c=t("../../components/color"),u=t("../../components/drawing"),f=t("../cartesian/set_convert"),h=t("../../lib/extend").extendFlat,d=t("../cartesian/axes"),p=t("../../lib/filter_visible"),g=t("../../components/dragelement"),v=t("../../components/titles"),m=t("../cartesian/select"),y=t("../cartesian/constants"),b=t("../cartesian/graph_interact");e.exports=n;var x=n.prototype;x.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={}},x.plot=function(t,e){var r,n=this,i=e[n.id],a=e._size;l.getPlotDiv(n.plotContainer.node())!==n.graphDiv&&(n.init(n.graphDiv._fullLayout),n.makeFramework()),n.adjustLayout(i,a);var o=n.traceHash,s={};for(r=0;r_*y?(a=y,i=a*_):(i=m,a=i/_),o=g*i/m,s=v*a/y,r=e.l+e.w*d-i/2,n=e.t+e.h*(1-p)-a/2,l.x0=r,l.y0=n,l.w=i,l.h=a,l.sum=b,l.xaxis={type:"linear",range:[x+2*k-b,b-x-2*w],domain:[d-o/2,d+o/2],_id:"x",_gd:l.graphDiv},f(l.xaxis),l.xaxis.setScale(),l.yaxis={type:"linear",range:[x,b-w-k],domain:[p-s/2,p+s/2],_id:"y",_gd:l.graphDiv},f(l.yaxis),l.yaxis.setScale();var A=l.yaxis.domain[0],M=l.aaxis=h({},t.aaxis,{range:[x,b-w-k],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[A,A+s*_],_axislayer:l.layers.aaxis,_gridlayer:l.layers.agrid,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2});f(M);var T=l.baxis=h({},t.baxis,{range:[b-x-k,w],side:"bottom",_counterangle:30,domain:l.xaxis.domain,_axislayer:l.layers.baxis,_gridlayer:l.layers.bgrid,_counteraxis:l.aaxis,_pos:0,_gd:l.graphDiv,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a});f(T),M._counteraxis=T;var E=l.caxis=h({},t.caxis,{range:[b-x-w,k],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[A,A+s*_],_axislayer:l.layers.caxis,_gridlayer:l.layers.cgrid,_counteraxis:l.baxis,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2});f(E);var L="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDef.select("path").attr("d",L),l.layers.plotbg.select("path").attr("d",L);var S="translate("+r+","+n+")";l.plotContainer.selectAll(".scatterlayer,.maplayer,.zoom").attr("transform",S);var C="translate("+r+","+(n+a)+")";l.layers.baxis.attr("transform",C),l.layers.bgrid.attr("transform",C);var z="translate("+(r+i/2)+","+n+")rotate(30)";l.layers.aaxis.attr("transform",z),l.layers.agrid.attr("transform",z);var P="translate("+(r+i/2)+","+n+")rotate(-30)";l.layers.caxis.attr("transform",P),l.layers.cgrid.attr("transform",P),l.drawAxes(!0),l.plotContainer.selectAll(".crisp").classed("crisp",!1);var R=l.layers.axlines;R.select(".aline").attr("d",M.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(c.stroke,M.linecolor||"#000").style("stroke-width",(M.linewidth||0)+"px"),R.select(".bline").attr("d",T.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(c.stroke,T.linecolor||"#000").style("stroke-width",(T.linewidth||0)+"px"),R.select(".cline").attr("d",E.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(c.stroke,E.linecolor||"#000").style("stroke-width",(E.linewidth||0)+"px")},x.drawAxes=function(t){var e=this,r=e.graphDiv,n=e.id.substr(7)+"title",i=e.aaxis,a=e.baxis,o=e.caxis;if(d.doTicks(r,i,!0),d.doTicks(r,a,!0),d.doTicks(r,o,!0),t){var s=Math.max(i.showticklabels?i.tickfont.size/2:0,(o.showticklabels?.75*o.tickfont.size:0)+("outside"===o.ticks?.87*o.ticklen:0));v.draw(r,"a"+n,{propContainer:i,propName:e.id+".aaxis.title",dfltName:"Component A",attributes:{x:e.x0+e.w/2,y:e.y0-i.titlefont.size/3-s,"text-anchor":"middle"}});var l=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;v.draw(r,"b"+n,{propContainer:a,propName:e.id+".baxis.title",dfltName:"Component B",attributes:{x:e.x0-l,y:e.y0+e.h+.83*a.titlefont.size+l,"text-anchor":"middle"}}),v.draw(r,"c"+n,{propContainer:o,propName:e.id+".caxis.title",dfltName:"Component C",attributes:{x:e.x0+e.w+l,y:e.y0+e.h+.83*o.titlefont.size+l,"text-anchor":"middle"}})}};var w=y.MINZOOM/2+.87,k="m-0.87,.5h"+w+"v3h-"+(w+5.2)+"l"+(w/2+2.6)+",-"+(.87*w+4.5)+"l2.6,1.5l-"+w/2+","+.87*w+"Z",A="m0.87,.5h-"+w+"v3h"+(w+5.2)+"l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-2.6,1.5l"+w/2+","+.87*w+"Z",M="m0,1l"+w/2+","+.87*w+"l2.6,-1.5l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-"+(w/2+2.6)+","+(.87*w+4.5)+"l2.6,1.5l"+w/2+",-"+.87*w+"Z",T="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",E=!0;x.initInteractions=function(){function t(t,e,r){var n=j.getBoundingClientRect();x=e-n.left,w=r-n.top,L={a:N.aaxis.range[0],b:N.baxis.range[1],c:N.caxis.range[1]},C=L,S=N.aaxis.range[1]-L.a,z=o(N.graphDiv._fullLayout[N.id].bgcolor).getLuminance(),P="M0,"+N.h+"L"+N.w/2+", 0L"+N.w+","+N.h+"Z",R=!1,O=D.append("path").attr("class","zoombox").style({fill:z>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",P),I=D.append("path").attr("class","zoombox-corners").style({fill:c.background,stroke:c.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),p()}function e(t,e){return 1-e/N.h}function r(t,e){return 1-(t+(N.h-e)/Math.sqrt(3))/N.w}function n(t,e){return(t-(N.h-e)/Math.sqrt(3))/N.w}function a(t,i){var a=x+t,o=w+i,s=Math.max(0,Math.min(1,e(x,w),e(a,o))),l=Math.max(0,Math.min(1,r(x,w),r(a,o))),c=Math.max(0,Math.min(1,n(x,w),n(a,o))),u=(s/2+c)*N.w,f=(1-s/2-l)*N.w,h=(u+f)/2,d=f-u,p=(1-s)*N.h,g=p-d/_;d.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),I.transition().style("opacity",1).duration(200),R=!0)}function u(t,e){if(C===L)return 2===e&&v(),i(F);i(F);var r={};r[N.id+".aaxis.min"]=C.a,r[N.id+".baxis.min"]=C.b,r[N.id+".caxis.min"]=C.c,s.relayout(F,r),E&&F.data&&F._context.showTips&&(l.notifier("Double-click to
zoom back out","long"),E=!1)}function f(){L={a:N.aaxis.range[0],b:N.baxis.range[1],c:N.caxis.range[1]},C=L}function h(t,e){var r=t/N.xaxis._m,n=e/N.yaxis._m;C={a:L.a-n,b:L.b+(r+n)/2,c:L.c-(r-n)/2};var i=[C.a,C.b,C.c].sort(),a={a:i.indexOf(C.a),b:i.indexOf(C.b),c:i.indexOf(C.c)};i[0]<0&&(i[1]+i[0]/2<0?(i[2]+=i[0]+i[1],i[0]=i[1]=0):(i[2]+=i[0]/2,i[1]+=i[0]/2,i[0]=0),C={a:i[a.a],b:i[a.b],c:i[a.c]},e=(L.a-C.a)*N.yaxis._m,t=(L.c-C.c-L.b+C.b)*N.xaxis._m);var o="translate("+(N.x0+t)+","+(N.y0+e)+")";N.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",o),N.aaxis.range=[C.a,N.sum-C.b-C.c],N.baxis.range=[N.sum-C.a-C.c,C.b],N.caxis.range=[N.sum-C.a-C.b,C.c],N.drawAxes(!1),N.plotContainer.selectAll(".crisp").classed("crisp",!1)}function d(t,e){if(t){var r={};r[N.id+".aaxis.min"]=C.a,r[N.id+".baxis.min"]=C.b,r[N.id+".caxis.min"]=C.c,s.relayout(F,r)}else 2===e&&v()}function p(){N.plotContainer.selectAll(".select-outline").remove()}function v(){var t={};t[N.id+".aaxis.min"]=0,t[N.id+".baxis.min"]=0,t[N.id+".caxis.min"]=0,F.emit("plotly_doubleclick",null),s.relayout(F,t)}var x,w,L,S,C,z,P,R,O,I,N=this,j=N.layers.plotbg.select("path").node(),F=N.graphDiv,D=N.layers.zoom,B={element:j,gd:F,plotinfo:{plot:D},doubleclick:v,subplot:N.id,prepFn:function(e,r,n){B.xaxes=[N.xaxis],B.yaxes=[N.yaxis];var i=F._fullLayout.dragmode;e.shiftKey&&(i="pan"===i?"zoom":"pan"),"lasso"===i?B.minDrag=1:B.minDrag=void 0,"zoom"===i?(B.moveFn=a,B.doneFn=u,t(e,r,n)):"pan"===i?(B.moveFn=h,B.doneFn=d,f(),p()):"select"!==i&&"lasso"!==i||m(e,r,n,B,i)}};g.init(B),j.onmousemove=function(t){b.hover(F,t,N.id),F._fullLayout._lasthover=j,F._fullLayout._hoversubplot=N.id},j.onmouseout=function(t){F._dragging||g.unhover(F,t)},j.onclick=function(t){b.click(F,t)}}},{"../../components/color":303,"../../components/dragelement":324,"../../components/drawing":326,"../../components/titles":366,"../../lib":382,"../../lib/extend":377,"../../lib/filter_visible":378,"../../plotly":402,"../cartesian/axes":405,"../cartesian/constants":410,"../cartesian/graph_interact":412,"../cartesian/select":418,"../cartesian/set_convert":419,d3:113,tinycolor2:274}],468:[function(t,e,r){"use strict";function n(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}function i(t){var e=["xaxis","yaxis","zaxis"];return e.indexOf(t.slice(0,5))>-1}var a=t("../plotly"),o=a.Lib.extendFlat,s=a.Lib.extendDeep;e.exports=function(t,e){t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var r,l=t.data,c=t.layout,u=s([],l),f=s({},c,n(e.tileClass));if(e.width&&(f.width=e.width),e.height&&(f.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){f.annotations=[];var h=Object.keys(f);for(r=0;rl;l++)n(r[l])&&d.push({p:r[l],s:s[l],b:0});return a(e,"marker")&&o(e,e.marker.color,"marker","c"),a(e,"marker.line")&&o(e,e.marker.line.color,"marker.line","c"),d}},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":316,"../../plots/cartesian/axes":405,"fast-isnumeric":117}],478:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../scatter/xy_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,l,r,i)}var f=a(t,e,u);return f?(u("orientation",e.x&&!e.y?"h":"v"),u("text"),o(t,e,u,r,c),s(t,e,i.defaultLine,{axis:"y"}),void s(t,e,i.defaultLine,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/color":303,"../../components/errorbars/defaults":331,"../../lib":382,"../bar/style_defaults":486,"../scatter/xy_defaults":577,"./attributes":476}],479:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../components/errorbars"),a=t("../../components/color");e.exports=function(t,e,r,o){var s,l=t.cd,c=l[0].trace,u=l[0].t,f=t.xa,h=t.ya,d="closest"===o?u.barwidth/2:u.dbar*(1-f._gd._fullLayout.bargap)/2;s="closest"!==o?function(t){return t.p}:"h"===c.orientation?function(t){return t.y}:function(t){return t.x};var p,g;"h"===c.orientation?(p=function(t){return n.inbox(t.b-e,t.x-e)+(t.x-e)/(t.x-t.b)},g=function(t){var e=s(t)-r;return n.inbox(e-d,e+d)}):(g=function(t){return n.inbox(t.b-r,t.y-r)+(t.y-r)/(t.y-t.b)},p=function(t){var r=s(t)-e;return n.inbox(r-d,r+d)});var v=n.getDistanceFunction(o,p,g);if(n.getClosest(l,v,t),t.index!==!1){var m=l[t.index],y=m.mcc||c.marker.color,b=m.mlcc||c.marker.line.color,x=m.mlw||c.marker.line.width;return a.opacity(y)?t.color=y:a.opacity(b)&&x&&(t.color=b),"h"===c.orientation?(t.x0=t.x1=f.c2p(m.x,!0),t.xLabelVal=m.s,t.y0=h.c2p(s(m)-d,!0),t.y1=h.c2p(s(m)+d,!0),t.yLabelVal=m.p):(t.y0=t.y1=h.c2p(m.y,!0),t.yLabelVal=m.s,t.x0=f.c2p(s(m)-d,!0),t.x1=f.c2p(s(m)+d,!0),t.xLabelVal=m.p),m.tx&&(t.text=m.tx),i.hoverInfo(m,c,t),[t]}}},{"../../components/color":303,"../../components/errorbars":332,"../../plots/cartesian/graph_interact":412}],480:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","oriented","markerColorscale","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":413,"../scatter/colorbar":559,"./arrays_to_calcdata":475,"./attributes":476,"./calc":477,"./defaults":478,"./hover":479,"./layout_attributes":481,"./layout_defaults":482,"./plot":483,"./set_positions":484,"./style":485}],481:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:""},bargap:{valType:"number",min:0,max:1},bargroupgap:{valType:"number",min:0,max:1,dflt:0}}},{}],482:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function s(r,n){return a.coerce(t,e,o,r,n)}for(var l=!1,c=!1,u=!1,f={},h=0;h=2?a(t):t>e?Math.ceil(t):Math.floor(t)}var h,d,p,g;if("h"===s.orientation?(p=u.c2p(r.poffset+e.p,!0),g=u.c2p(r.poffset+e.p+r.barwidth,!0),h=c.c2p(e.b,!0),d=c.c2p(e.s+e.b,!0)):(h=c.c2p(r.poffset+e.p,!0),d=c.c2p(r.poffset+e.p+r.barwidth,!0),g=u.c2p(e.s+e.b,!0),p=u.c2p(e.b,!0)),!(i(h)&&i(d)&&i(p)&&i(g)&&h!==d&&p!==g))return void n.select(this).remove();var v=(e.mlw+1||s.marker.line.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,m=n.round(v/2%1,2);if(!t._context.staticPlot){var y=o.opacity(e.mc||s.marker.color),b=1>y||v>.01?a:l;h=b(h,d),d=b(d,h),p=b(p,g),g=b(g,p)}n.select(this).attr("d","M"+h+","+p+"V"+g+"H"+d+"V"+p+"Z")})}),h.call(s.plot,e)}},{"../../components/color":303,"../../components/errorbars":332,"../../lib":382,"./arrays_to_calcdata":475,d3:113,"fast-isnumeric":117}],484:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axes"),o=t("../../lib");e.exports=function(t,e){var r,s,l=t._fullLayout,c=e.x(),u=e.y();["v","h"].forEach(function(f){function h(e){function r(t){t[p]=t.p+h}var n=[];e.forEach(function(e){t.calcdata[e].forEach(function(t){n.push(t.p)})});var i=o.distinctVals(n),s=i.vals,c=i.minDiff,u=!1,f=[];"group"===l.barmode&&e.forEach(function(e){u||(t.calcdata[e].forEach(function(t){u||f.forEach(function(e){Math.abs(t.p-e)_&&(S=!0,M=_),_>A+R&&(S=!0,A=_))}a.expand(m,[M,A],{tozero:!0,padded:S})}else{var O=function(t){return t[g]=t.s,t.s};for(r=0;r1||0===s.bargap&&0===s.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),e.selectAll("g.points").each(function(t){var e=t[0].trace,r=e.marker,o=r.line,s=(e._input||{}).marker||{},l=a.tryColorscale(r,s,""),c=a.tryColorscale(r,s,"line.");n.select(this).selectAll("path").each(function(t){var e,a,s=(t.mlw+1||o.width+1)-1,u=n.select(this);e="mc"in t?t.mcc=l(t.mc):Array.isArray(r.color)?i.defaultLine:r.color,u.style("stroke-width",s+"px").call(i.fill,e),s&&(a="mlc"in t?t.mlcc=c(t.mlc):Array.isArray(o.color)?i.defaultLine:o.color,u.call(i.stroke,a))})}),e.call(o.style)}},{"../../components/color":303,"../../components/drawing":326,"../../components/errorbars":332,d3:113}],486:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width")}},{"../../components/color":303,"../../components/colorscale/defaults":313,"../../components/colorscale/has_colorscale":316}],487:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/color/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=o.line;e.exports={y:{valType:"data_array"},x:{valType:"data_array"},x0:{valType:"any"},y0:{valType:"any"},whiskerwidth:{valType:"number",min:0,max:1,dflt:.5},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1},jitter:{valType:"number",min:0,max:1},pointpos:{valType:"number",min:-2,max:2},orientation:{valType:"enumerated",values:["v","h"]},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)"},symbol:a({},o.symbol,{arrayOk:!1}),opacity:a({},o.opacity,{arrayOk:!1,dflt:1}),size:a({},o.size,{arrayOk:!1}),color:a({},o.color,{arrayOk:!1}),line:{color:a({},s.color,{arrayOk:!1,dflt:i.defaultLine}),width:a({},s.width,{arrayOk:!1,dflt:0}),outliercolor:{valType:"color"},outlierwidth:{valType:"number",min:0,dflt:1}}},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2}},fillcolor:n.fillcolor}},{"../../components/color/attributes":302,"../../lib/extend":377,"../scatter/attributes":556}],488:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes");e.exports=function(t,e){function r(t,e,r,a,o){var s;return r in e?p=a.makeCalcdata(e,r):(s=r+"0"in e?e[r+"0"]:"name"in e&&("category"===a.type||n(e.name)&&-1!==["linear","log"].indexOf(a.type)||i.isDateTime(e.name)&&"date"===a.type)?e.name:t.numboxes,s=a.d2c(s),p=o.map(function(){return s})),p}function o(t,e,r,a,o){var s,l,c,u,f=a.length,h=e.length,d=[],p=[];for(s=0;f>s;++s)l=a[s],t[s]={pos:l},p[s]=l-o,d[s]=[];for(p.push(a[f-1]+o),s=0;h>s;++s)u=e[s],n(u)&&(c=i.findBin(r[s],p),c>=0&&h>c&&d[c].push(u));return d}function s(t,e){var r,n,a,o;for(o=0;o1,m=r.dPos*(1-h.boxgap)*(1-h.boxgroupgap)/(v?t.numboxes:1),y=v?2*r.dPos*(-.5+(r.boxnum+.5)/t.numboxes)*(1-h.boxgap):0,b=m*g.whiskerwidth;return g.visible!==!0||r.emptybox?void a.select(this).remove():("h"===g.orientation?(l=p,f=d):(l=d,f=p),r.bPos=y,r.bdPos=m,n(),a.select(this).selectAll("path.box").data(o.identity).enter().append("path").attr("class","box").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=l.c2p(t.pos+y-b,!0),s=l.c2p(t.pos+y+b,!0),c=f.c2p(t.q1,!0),u=f.c2p(t.q3,!0),h=o.constrain(f.c2p(t.med,!0),Math.min(c,u)+1,Math.max(c,u)-1),d=f.c2p(g.boxpoints===!1?t.min:t.lf,!0),p=f.c2p(g.boxpoints===!1?t.max:t.uf,!0);"h"===g.orientation?a.select(this).attr("d","M"+h+","+r+"V"+n+"M"+c+","+r+"V"+n+"H"+u+"V"+r+"ZM"+c+","+e+"H"+d+"M"+u+","+e+"H"+p+(0===g.whiskerwidth?"":"M"+d+","+i+"V"+s+"M"+p+","+i+"V"+s)):a.select(this).attr("d","M"+r+","+h+"H"+n+"M"+r+","+c+"H"+n+"V"+u+"H"+r+"ZM"+e+","+c+"V"+d+"M"+e+","+u+"V"+p+(0===g.whiskerwidth?"":"M"+i+","+d+"H"+s+"M"+i+","+p+"H"+s))}),g.boxpoints&&a.select(this).selectAll("g.points").data(function(t){return t.forEach(function(t){t.t=r,t.trace=g}),t}).enter().append("g").attr("class","points").selectAll("path").data(function(t){var e,r,n,a,s,l,f,h="all"===g.boxpoints?t.val:t.val.filter(function(e){return et.uf}),d=(t.q3-t.q1)*u,p=[],v=0;if(g.jitter){for(e=0;et.lo&&(n.so=!0),n})}).enter().append("path").call(s.translatePoints,d,p),void(g.boxmean&&a.select(this).selectAll("path.mean").data(o.identity).enter().append("path").attr("class","mean").style("fill","none").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=f.c2p(t.mean,!0),o=f.c2p(t.mean-t.sd,!0),s=f.c2p(t.mean+t.sd,!0);"h"===g.orientation?a.select(this).attr("d","M"+i+","+r+"V"+n+("sd"!==g.boxmean?"":"m0,0L"+o+","+e+"L"+i+","+r+"L"+s+","+e+"Z")):a.select(this).attr("d","M"+r+","+i+"H"+n+("sd"!==g.boxmean?"":"m0,0L"+e+","+o+"L"+r+","+i+"L"+e+","+s+"Z"))})))})}},{"../../components/drawing":326,"../../lib":382,d3:113}],495:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib");e.exports=function(t,e){var r,o,s,l,c=t._fullLayout,u=e.x(),f=e.y(),h=["v","h"];for(o=0;ol&&(e.z=u.slice(0,l)),s("locationmode"),s("text"),s("marker.line.color"),s("marker.line.width"),i(t,e,o,s,{prefix:"",cLetter:"z"}),void s("hoverinfo",1===o._dataLength?"location+z+text":void 0)):void(e.visible=!1)}},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":497}],500:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./plot").plot,n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":426,"../heatmap/colorbar":514,"./attributes":497,"./calc":498,"./defaults":499,"./plot":501}],501:[function(t,e,r){"use strict";function n(t,e){function r(e){var r=t.mockAxis;return o.tickText(r,r.c2l(e),"hover").text}var n=e.hoverinfo;if("none"===n)return function(t){delete t.nameLabel,delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("name"),s=-1!==i.indexOf("location"),l=-1!==i.indexOf("z"),c=-1!==i.indexOf("text"),u=!a&&s;return function(t){var n=[];u?t.nameLabel=t.id:(a&&(t.nameLabel=e.name),s&&n.push(t.id)),l&&n.push(r(t.z)),c&&n.push(t.tx),t.textLabel=n.join("
")}}function i(t){return function(e,r){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:r,location:e.id,z:e.z}]}}}var a=t("d3"),o=t("../../plots/cartesian/axes"),s=t("../../plots/cartesian/graph_interact"),l=t("../../components/color"),c=t("../../components/drawing"),u=t("../../components/colorscale/get_scale"),f=t("../../components/colorscale/make_scale_function"),h=t("../../lib/topojson_utils").getTopojsonFeatures,d=t("../../lib/geo_location_utils").locationToFeature,p=t("../../lib/array_to_calc_item"),g=t("../../plots/geo/constants"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){for(var r,n=[],i=t.locations,a=i.length,o=h(t,e),s=(t.marker||{}).line||{},l=0;a>l;l++)r=d(t.locationmode,i[l],o),void 0!==r&&(r.z=t.z[l],void 0!==t.text&&(r.tx=t.text[l]),p(s.color,r,"mlc",l),p(s.width,r,"mlw",l),n.push(r));return n.length>0&&(n[0].trace=t),n},m.plot=function(t,e,r){var o,l=t.framework,c=l.select("g.choroplethlayer"),u=l.select("g.baselayer"),f=l.select("g.baselayeroverchoropleth"),h=g.baseLayersOverChoropleth,d=c.selectAll("g.trace.choropleth").data(e,function(t){return t.uid});d.enter().append("g").attr("class","trace choropleth"),d.exit().remove(),d.each(function(e){function r(e,r){if(t.showHover){var n=t.projection(e.properties.ct);c(e),s.loneHover({x:n[0],y:n[1],name:e.nameLabel,text:e.textLabel},{container:t.hoverContainer.node()}),f=u(e,r),t.graphDiv.emit("plotly_hover",f)}}function o(e,r){t.graphDiv.emit("plotly_click",u(e,r))}var l=m.calcGeoJSON(e,t.topojson),c=n(t,e),u=i(e),f=null,h=a.select(this).selectAll("path.choroplethlocation").data(l);h.enter().append("path").classed("choroplethlocation",!0).on("mouseover",r).on("click",o).on("mouseout",function(){s.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",f)}).on("mousedown",function(){s.loneUnhover(t.hoverContainer)}).on("mouseup",r),h.exit().remove()}),f.selectAll("*").remove();for(var p=0;pr;r++)e=f[r],d[r]=e[0]*(t.zmax-t.zmin)+t.zmin,p[r]=e[1];var g=n.extent([t.zmin,t.zmax,a.start,a.start+l*(c-1)]),v=g[t.zminr;r++)e=f[r],d[r]=(e[0]*(c+u-1)-u/2)*l+o,p[r]=e[1];var y=n.scale.linear().interpolate(n.interpolateRgb).domain(d).range(p);return y}},{"../../components/colorscale/get_scale":315,d3:113}],509:[function(t,e,r){"use strict";function n(t,e,r){var n=r[0].trace,a=r[0].x,s=r[0].y,c=n.contours,u=n.uid,f=e.x(),h=e.y(),v=t._fullLayout,b="contour"+u,x=i(c,e,r[0]);if(n.visible!==!0)return v._paper.selectAll("."+b+",.hm"+u).remove(),void v._infolayer.selectAll(".cb"+u).remove();"heatmap"===c.coloring?(n.zauto&&n.autocontour===!1&&(n._input.zmin=n.zmin=c.start-c.size/2,n._input.zmax=n.zmax=n.zmin+x.length*c.size),k(t,e,[r])):v._paper.selectAll(".hm"+u).remove(),o(x),l(x);var _=f.c2p(a[0],!0),w=f.c2p(a[a.length-1],!0),A=h.c2p(s[0],!0),M=h.c2p(s[s.length-1],!0),T=[[_,M],[w,M],[w,A],[_,A]],E=d(e,r,b);p(E,T,c),g(E,x,T,c),m(E,x,c),y(E,e,r[0],T)}function i(t,e,r){for(var n=t.size||1,i=[],a=t.start;at?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);if(5===r||10===r){var n=(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4;return t>n?5===r?713:1114:5===r?104:208}return 15===r?0:r}function o(t){var e,r,n,i,o,s,l,c,u,f=t[0].z,h=f.length,d=f[0].length,p=2===h||2===d;for(r=0;h-1>r;r++)for(i=[],0===r&&(i=i.concat(A)),r===h-2&&(i=i.concat(M)),e=0;d-1>e;e++)for(n=i.slice(),0===e&&(n=n.concat(T)),e===d-2&&(n=n.concat(E)),o=e+","+r,s=[[f[r][e],f[r][e+1]],[f[r+1][e],f[r+1][e+1]]],u=0;ui;i++){if(s>20?(s=S[s][(l[0]||l[1])<0?0:1],t.crossings[o]=C[s]):delete t.crossings[o],l=L[s],!l){_.log("Found bad marching index:",s,e,t.level);break}if(d.push(h(t,e,l)),e[0]+=l[0],e[1]+=l[1],u(d[d.length-1],d[d.length-2])&&d.pop(),o=e.join(","),o===a&&l.join(",")===p||r&&(l[0]&&(e[0]<0||e[0]>v-2)||l[1]&&(e[1]<0||e[1]>g-2)))break;s=t.crossings[o]}1e4===i&&_.log("Infinite loop in contour?");var m,y,b,x,w,k,A,M=u(d[0],d[d.length-1]),T=0,E=.2*t.smoothing,z=[],P=0;for(i=1;i=P;i--)if(m=z[i],R>m){for(b=0,y=i-1;y>=P&&m+z[y]b&&m+z[b]e;)e++,r=Object.keys(i.crossings)[0].split(",").map(Number),s(i,r);1e4===e&&_.log("Infinite loop in contour?")}}function c(t,e,r){var n=0,i=0;return t>20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==A.indexOf(t)?i=1:-1!==T.indexOf(t)?n=1:-1!==M.indexOf(t)?i=-1:n=-1,[n,i]}function u(t,e){return Math.abs(t[0]-e[0])<.01&&Math.abs(t[1]-e[1])<.01}function f(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}function h(t,e,r){var n=e[0]+Math.max(r[0],0),i=e[1]+Math.max(r[1],0),a=t.z[i][n],o=t.xaxis,s=t.yaxis;if(r[1]){var l=(t.level-a)/(t.z[i][n+1]-a);return[o.c2p((1-l)*t.x[n]+l*t.x[n+1],!0),s.c2p(t.y[i],!0)]}var c=(t.level-a)/(t.z[i+1][n]-a);return[o.c2p(t.x[n],!0),s.c2p((1-c)*t.y[i]+c*t.y[i+1],!0)]}function d(t,e,r){var n=t.plot.select(".maplayer").selectAll("g.contour."+r).data(e);return n.enter().append("g").classed("contour",!0).classed(r,!0),n.exit().remove(),n}function p(t,e,r){var n=t.selectAll("g.contourbg").data([0]);n.enter().append("g").classed("contourbg",!0);var i=n.selectAll("path").data("fill"===r.coloring?[0]:[]);i.enter().append("path"),i.exit().remove(),i.attr("d","M"+e.join("L")+"Z").style("stroke","none")}function g(t,e,r,n){var i=t.selectAll("g.contourfill").data([0]);i.enter().append("g").classed("contourfill",!0);var a=i.selectAll("path").data("fill"===n.coloring?e:[]);a.enter().append("path"),a.exit().remove(),a.each(function(t){var e=v(t,r);e?x.select(this).attr("d",e).style("stroke","none"):x.select(this).remove()})}function v(t,e){function r(t){return Math.abs(t[1]-e[0][1])<.01}function n(t){return Math.abs(t[1]-e[2][1])<.01}function i(t){return Math.abs(t[0]-e[0][0])<.01}function a(t){return Math.abs(t[0]-e[2][0])<.01}for(var o,s,l,c,u,f,h=t.edgepaths.length||t.z[0][0]l;l++){if(!o){_.log("Missing end?",d,t);break}for(r(o)&&!a(o)?s=e[1]:i(o)?s=e[0]:n(o)?s=e[3]:a(o)&&(s=e[2]),u=0;u=0&&(s=v,c=u):Math.abs(o[1]-s[1])<.01?Math.abs(o[1]-v[1])<.01&&(v[0]-o[0])*(s[0]-v[0])>=0&&(s=v,c=u):_.log("endpt to newendpt is not vert. or horz.",o,s,v)}if(o=s,c>=0)break;h+="L"+s}if(c===t.edgepaths.length){_.log("unclosed perimeter path");break}d=c,g=-1===p.indexOf(d),g&&(d=p[0],h+="Z")}for(d=0;de;e++)s.push(1);for(e=0;a>e;e++)i.push(s.slice());for(e=0;eo;o++)for(n=i(l,o),u[o]=new Array(n),s=0;n>s;s++)u[o][s]=e(a(l,o,s));return u}function i(t,e,r,n,i,a){var o,s,l,c=[],u=h.traceIs(t,"contour"),f=h.traceIs(t,"histogram"),d=h.traceIs(t,"gl2d");if(Array.isArray(e)&&!f&&"category"!==a.type){e=e.map(a.d2c);var p=e.length;if(!(i>=p))return u?e.slice(0,i):e.slice(0,i+1);if(u||d)c=e.slice(0,i);else if(1===i)c=[e[0]-.5,e[0]+.5];else{for(c=[1.5*e[0]-.5*e[1]],l=1;p>l;l++)c.push(.5*(e[l-1]+e[l]));c.push(1.5*e[p-1]-.5*e[p-2])}if(i>p){var g=c[c.length-1],v=g-c[c.length-2];for(l=p;i>l;l++)g+=v,c.push(g)}}else for(s=n||1,o=void 0===r?0:f||"category"===a.type?r:a.d2c(r),l=u||d?0:-.5;i>l;l++)c.push(o+s*l);return c}function a(t){return.5-.25*Math.min(1,.5*t)}function o(t,e,r){var n,i,o=1;if(Array.isArray(r))for(n=0;nn&&o>y;n++)o=l(t,e,a(o));return o>y&&u.log("interp2d didn't converge quickly",o),t}function s(t){var e,r,n,i,a,o,s,l,c=[],u={},f=[],h=t[0],d=[],p=[0,0,0],g=m(t);for(r=0;rn;n++)void 0===d[n]&&(o=(void 0!==d[n-1]?1:0)+(void 0!==d[n+1]?1:0)+(void 0!==e[n]?1:0)+(void 0!==h[n]?1:0),o?(0===r&&o++,0===n&&o++,r===t.length-1&&o++,n===d.length-1&&o++,4>o&&(u[[r,n]]=[r,n,o]),c.push([r,n,o])):f.push([r,n]));for(;f.length;){for(s={},l=!1,a=f.length-1;a>=0;a--)i=f[a],r=i[0],n=i[1],o=((u[[r-1,n]]||p)[2]+(u[[r+1,n]]||p)[2]+(u[[r,n-1]]||p)[2]+(u[[r,n+1]]||p)[2])/20,o&&(s[i]=[r,n,o],f.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)u[i]=s[i],c.push(s[i])}return c.sort(function(t,e){return e[2]-t[2]})}function l(t,e,r){var n,i,a,o,s,l,c,u,f,h,d,p,g,v=0;for(o=0;os;s++)l=b[s],c=t[i+l[0]],c&&(u=c[a+l[1]],void 0!==u&&(0===h?p=g=u:(p=Math.min(p,u),g=Math.max(g,u)),f++,h+=u));if(0===f)throw"iterateInterp2d order is wrong: no defined neighbors";t[i][a]=h/f,void 0===d?4>f&&(v=1):(t[i][a]=(1+r)*t[i][a]-r*d,g>p&&(v=Math.max(v,Math.abs(t[i][a]-d)/(g-p))))}return v}var c=t("fast-isnumeric"),u=t("../../lib"),f=t("../../plots/cartesian/axes"),h=t("../../plots/plots"),d=t("../histogram2d/calc"),p=t("../../components/colorscale/calc"),g=t("./has_columns"),v=t("./convert_column_xyz"),m=t("./max_row_length");e.exports=function(t,e){function r(t){E=e._input.zsmooth=e.zsmooth=!1,u.notifier("cannot fast-zsmooth: "+t)}var a,l,c,y,b,x,_,w,k=f.getFromId(t,e.xaxis||"x"),A=f.getFromId(t,e.yaxis||"y"),M=h.traceIs(e,"contour"),T=h.traceIs(e,"histogram"),E=M?"best":e.zsmooth;if(k._minDtick=0,A._minDtick=0,T){var L=d(t,e);a=L.x,l=L.x0,c=L.dx,y=L.y,b=L.y0,x=L.dy,_=L.z}else g(e)&&v(e,k,A),a=e.x?k.makeCalcdata(e,"x"):[],y=e.y?A.makeCalcdata(e,"y"):[],l=e.x0||0,c=e.dx||1,b=e.y0||0,x=e.dy||1,_=n(e),(M||e.connectgaps)&&(e._emptypoints=s(_),e._interpz=o(_,e._emptypoints,e._interpz));if("fast"===E)if("log"===k.type||"log"===A.type)r("log axis found");else if(!T){if(a.length){var S=(a[a.length-1]-a[0])/(a.length-1),C=Math.abs(S/100);for(w=0;wC){r("x scale is not linear");break}}if(y.length&&"fast"===E){var z=(y[y.length-1]-y[0])/(y.length-1),P=Math.abs(z/100);for(w=0;wP){r("y scale is not linear");break}}}var R=m(_),O="scaled"===e.xtype?"":e.x,I=i(e,O,l,c,R,k),N="scaled"===e.ytype?"":e.y,j=i(e,N,b,x,_.length,A);f.expand(k,I),f.expand(A,j);var F={x:I,y:j,z:_};if(p(e,_,"","z"),M&&e.contours&&"heatmap"===e.contours.coloring){var D="contour"===e.type?"heatmap":"histogram2d";F.xfill=i(D,O,l,c,R,k),F.yfill=i(D,N,b,x,_.length,A)}return[F]};var y=.01,b=[[-1,0],[1,0],[0,-1],[0,1]]},{"../../components/colorscale/calc":310,"../../lib":382,"../../plots/cartesian/axes":405,"../../plots/plots":454,"../histogram2d/calc":533,"./convert_column_xyz":515,"./has_columns":517,"./max_row_length":520,"fast-isnumeric":117}],514:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,c="cb"+r.uid,u=s(r.colorscale),f=r.zmin,h=r.zmax;if(i(f)||(f=a.aggNums(Math.min,null,r.z)),i(h)||(h=a.aggNums(Math.max,null,r.z)),t._fullLayout._infolayer.selectAll("."+c).remove(),!r.showscale)return void o.autoMargin(t,c);var d=e[0].t.cb=l(t,c);d.fillcolor(n.scale.linear().domain(u.map(function(t){return f+t[0]*(h-f)})).range(u.map(function(t){return t[1]}))).filllevels({start:f,end:h,size:(h-f)/254}).options(r.colorbar)()}},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,d3:113,"fast-isnumeric":117}],515:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a=t.x.slice(),o=t.y.slice(),s=t.z,l=t.text,c=Math.min(a.length,o.length,s.length),u=void 0!==l&&!Array.isArray(l[0]);for(ci;i++)a[i]=e.d2c(a[i]),o[i]=r.d2c(o[i]);var f,h,d,p=n.distinctVals(a),g=p.vals,v=n.distinctVals(o),m=v.vals,y=n.init2dArray(m.length,g.length);for(u&&(d=n.init2dArray(m.length,g.length)),i=0;c>i;i++)f=n.findBin(a[i]+p.minDiff/2,g),h=n.findBin(o[i]+v.minDiff/2,m),y[h][f]=s[i],u&&(d[h][f]=l[i]);t.x=g,t.y=m,t.z=y,u&&(t.text=d)}},{"../../lib":382}],516:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./has_columns"),a=t("./xyz_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function c(r,i){return n.coerce(t,e,s,r,i)}var u=a(t,e,c);return u?(c("text"),c("zsmooth"),c("connectgaps",i(e)&&e.zsmooth!==!1),void o(t,e,l,c,{prefix:"",cLetter:"z"})):void(e.visible=!1)}},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":512,"./has_columns":517,"./xyz_defaults":523}],517:[function(t,e,r){"use strict";e.exports=function(t){return!Array.isArray(t.z[0])}},{}],518:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../lib");e.exports=function(t,e,r,a,o){if(!(t.distancec||c>=m[0].length||0>u||u>m.length)return}else{if(n.inbox(e-g[0],e-g[g.length-1])>n.MAXDIST||n.inbox(r-v[0],r-v[v.length-1])>n.MAXDIST)return;if(o){var w;for(b=[2*g[0]-g[1]],w=1;w0;)_=v.c2p(C[M]),M--;for(x>_&&(w=_,_=x,x=w,N=!0),M=0;void 0===k&&M0;)A=m.c2p(z[M]),M--;if(k>A&&(w=k,k=A,A=w,j=!0),P&&(C=r[0].xfill,z=r[0].yfill),"fast"!==R){var F="best"===R?0:.5;x=Math.max(-F*v._length,x),_=Math.min((1+F)*v._length,_),k=Math.max(-F*m._length,k),A=Math.min((1+F)*m._length,A)}var D=Math.round(_-x),B=Math.round(A-k);if(!(0>=D||0>=B)){var U,V;"fast"===R?(U=I,V=O):(U=D,V=B);var q=document.createElement("canvas");q.width=U,q.height=V;var H,G,Y=q.getContext("2d"),X=i.scale.linear().domain(S.map(function(t){return t[0]})).range(S.map(function(t){var e=a(t[1]).toRgb();return[e.r,e.g,e.b,e.a]})).clamp(!0);"fast"===R?(H=N?function(t){return I-1-t}:o.identity,G=j?function(t){return O-1-t}:o.identity):(H=function(t){return o.constrain(Math.round(v.c2p(C[t])-x),0,D)},G=function(t){return o.constrain(Math.round(m.c2p(z[t])-k),0,B)});var W,Z,K,$,Q,J,tt=G(0),et=[tt,tt],rt=N?0:1,nt=j?0:1,it=0,at=0,ot=0,st=0;if(R){var lt=0,ct=new Uint8Array(D*B*4);if("best"===R){var ut,ft,ht,dt=new Array(C.length),pt=new Array(z.length),gt=new Array(D);for(M=0;MM;M++)gt[M]=n(M,dt);for(Z=0;B>Z;Z++)for(ut=n(Z,pt),ft=T[ut.bin0],ht=T[ut.bin1],M=0;D>M;M++,lt+=4)J=d(ft,ht,gt[M],ut),h(ct,lt,J)}else for(Z=0;O>Z;Z++)for(Q=T[Z],et=G(Z),M=0;D>M;M++)J=f(Q[M],1),lt=4*(et*D+H(M)),h(ct,lt,J);var vt=Y.createImageData(D,B);vt.data.set(ct),Y.putImageData(vt,0,0)}else for(Z=0;O>Z;Z++)if(Q=T[Z],et.reverse(),et[nt]=G(Z+1),et[0]!==et[1]&&void 0!==et[0]&&void 0!==et[1])for(K=H(0),W=[K,K],M=0;I>M;M++)W.reverse(),W[rt]=H(M+1),W[0]!==W[1]&&void 0!==W[0]&&void 0!==W[1]&&($=Q[M],J=f($,(W[1]-W[0])*(et[1]-et[0])),Y.fillStyle="rgba("+J.join(",")+")",Y.fillRect(W[0],et[0],W[1]-W[0],et[1]-et[0]));at=Math.round(at/it),ot=Math.round(ot/it),st=Math.round(st/it);var mt=a("rgb("+at+","+ot+","+st+")");t._hmpixcount=(t._hmpixcount||0)+it,t._hmlumcount=(t._hmlumcount||0)+it*mt.getLuminance();var yt=e.plot.select(".imagelayer").selectAll("g.hm."+b).data([0]);yt.enter().append("g").classed("hm",!0).classed(b,!0),yt.exit().remove();var bt=yt.selectAll("image").data(r);bt.enter().append("svg:image"),bt.exit().remove(),bt.attr({xmlns:c.svg,"xlink:href":q.toDataURL("image/png"),height:B,width:D,x:x,y:k,preserveAspectRatio:"none"})}}var i=t("d3"),a=t("tinycolor2"),o=t("../../lib"),s=t("../../plots/plots"),l=t("../../components/colorscale/get_scale"),c=t("../../constants/xmlns_namespaces"),u=t("./max_row_length");e.exports=function(t,e,r){for(var i=0;i0&&(n=!0);for(var s=0;si;i++)e[i]?(t[i]/=e[i],n+=t[i]):t[i]=null;return n}},{}],526:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){var e=r(t+"bins.start"),n=r(t+"bins.end"),i=r("autobin"+t,!(e&&n));r(i?"nbins"+t:t+"bins.size")}),e}},{}],527:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,i){var a=i[e];return n(a)?(a=Number(a),r[t]+=a,a):0},avg:function(t,e,r,i,a){var o=i[e];return n(o)&&(o=Number(o),r[t]+=o,a[t]++),0},min:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]>a)return r[t]=a,a-r[t]}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]r&&c.length<5e3;)g=a.tickIncrement(r,b.size),c.push((r+g)/2),u.push(S),x&&_.push(r),E&&w.push(1/(g-r)),P&&k.push(0),r=g;var R=u.length;for(r=0;r=0&&R>m&&(A+=C(m,r,u,y,k));P&&(A=l(u,k)),z&&z(u,A,w);var O=Math.min(c.length,u.length),I=[],N=0,j=O-1;for(r=0;O>r;r++)if(u[r]){N=r;break}for(r=O-1;r>N;r--)if(u[r]){j=r;break}for(r=N;j>=r;r++)n(c[r])&&n(u[r])&&I.push({p:c[r],s:u[r],b:0});return I}}},{"../../lib":382,"../../plots/cartesian/axes":405,"./average":525,"./bin_functions":527,"./norm_functions":531,"fast-isnumeric":117}],529:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("./bin_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,l,r,i)}var f=u("x"),h=u("y");u("text");var d=u("orientation",h&&!f?"h":"v"),p=e["v"===d?"x":"y"];if(!p||!p.length)return void(e.visible=!1);var g=e["h"===d?"x":"y"];g&&u("histfunc");var v="h"===d?["y"]:["x"];a(t,e,u,v),o(t,e,u,r,c),s(t,e,i.defaultLine,{axis:"y"}),s(t,e,i.defaultLine,{axis:"x",inherit:"y"})}},{"../../components/color":303,"../../components/errorbars/defaults":331,"../../lib":382,"../bar/style_defaults":486,"./attributes":524,"./bin_defaults":526}],530:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.style=t("../bar/style"),n.colorbar=t("../scatter/colorbar"),n.hoverPoints=t("../bar/hover"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":413,"../bar/hover":479,"../bar/layout_attributes":481,"../bar/layout_defaults":482,"../bar/plot":483,"../bar/set_positions":484,"../bar/style":485,"../scatter/colorbar":559,"./attributes":524,"./calc":528,"./defaults":529}],531:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,i=0;r>i;i++)t[i]*=n},probability:function(t,e){for(var r=t.length,n=0;r>n;n++)t[n]/=e},density:function(t,e,r,n){var i=t.length;n=n||1;for(var a=0;i>a;a++)t[a]*=r[a]*n},"probability density":function(t,e,r,n){var i=t.length;n&&(e/=n);for(var a=0;i>a;a++)t[a]*=r[a]/e}}},{}],532:[function(t,e,r){"use strict";var n=t("../histogram/attributes"),i=t("../heatmap/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports=o({},{x:n.x,y:n.y,z:{valType:"data_array"},marker:{color:{valType:"data_array"}},histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zsmooth:i.zsmooth,_nestedModules:{colorbar:"Colorbar"}},a,{autocolorscale:o({},a.autocolorscale,{dflt:!1})})},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../heatmap/attributes":512,"../histogram/attributes":524}],533:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../histogram/bin_functions"),o=t("../histogram/norm_functions"),s=t("../histogram/average");e.exports=function(t,e){var r,l,c,u,f,h,d=i.getFromId(t,e.xaxis||"x"),p=e.x?d.makeCalcdata(e,"x"):[],g=i.getFromId(t,e.yaxis||"y"),v=e.y?g.makeCalcdata(e,"y"):[],m=Math.min(p.length,v.length);p.length>m&&p.splice(m,p.length-m),v.length>m&&v.splice(m,v.length-m),!e.autobinx&&"xbins"in e||(e.xbins=i.autoBin(p,d,e.nbinsx,"2d"),"histogram2dcontour"===e.type&&(e.xbins.start-=e.xbins.size,e.xbins.end+=e.xbins.size),e._input.xbins=e.xbins),!e.autobiny&&"ybins"in e||(e.ybins=i.autoBin(v,g,e.nbinsy,"2d"),"histogram2dcontour"===e.type&&(e.ybins.start-=e.ybins.size,e.ybins.end+=e.ybins.size),e._input.ybins=e.ybins),f=[];var y,b,x=[],_=[],w="string"==typeof e.xbins.size?[]:e.xbins,k="string"==typeof e.xbins.size?[]:e.ybins,A=0,M=[],T=e.histnorm,E=e.histfunc,L=-1!==T.indexOf("density"),S="max"===E||"min"===E,C=S?null:0,z=a.count,P=o[T],R=!1,O=[],I=[],N="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";N&&"count"!==E&&(R="avg"===E,z=a[E]);var j=e.xbins,F=j.end+(j.start-i.tickIncrement(j.start,j.size))/1e6;for(h=j.start;F>h;h=i.tickIncrement(h,j.size))x.push(C),Array.isArray(w)&&w.push(h),R&&_.push(0);Array.isArray(w)&&w.push(h);var D=x.length;for(r=e.xbins.start,l=(h-r)/D,r+=l/2,j=e.ybins,F=j.end+(j.start-i.tickIncrement(j.start,j.size))/1e6,h=j.start;F>h;h=i.tickIncrement(h,j.size))f.push(x.concat()),Array.isArray(k)&&k.push(h),R&&M.push(_.concat());Array.isArray(k)&&k.push(h);var B=f.length;for(c=e.ybins.start,u=(h-c)/B,c+=u/2,L&&(O=x.map(function(t,e){return Array.isArray(w)?1/(w[e+1]-w[e]):1/l}),I=f.map(function(t,e){return Array.isArray(k)?1/(k[e+1]-k[e]):1/u})),h=0;m>h;h++)y=n.findBin(p[h],w),b=n.findBin(v[h],k),y>=0&&D>y&&b>=0&&B>b&&(A+=z(y,h,f[b],N,M[b]));if(R)for(b=0;B>b;b++)A+=s(f[b],M[b]);if(P)for(b=0;B>b;b++)P(f[b],A,O,I[b]);return{x:p,x0:r,dx:l,y:v,y0:c,dy:u,z:f}}},{"../../lib":382,"../../plots/cartesian/axes":405,"../histogram/average":525,"../histogram/bin_functions":527,"../histogram/norm_functions":531}],534:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./sample_defaults"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r){function s(r,i){return n.coerce(t,e,o,r,i)}i(t,e,s),s("zsmooth"),a(t,e,r,s,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":532,"./sample_defaults":536}],535:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../heatmap/calc"),n.plot=t("../heatmap/plot"),n.colorbar=t("../heatmap/colorbar"),n.style=t("../heatmap/style"),n.hoverPoints=t("../heatmap/hover"),n.moduleType="trace",n.name="histogram2d",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":413,"../heatmap/calc":513,"../heatmap/colorbar":514,"../heatmap/hover":518,"../heatmap/plot":521,"../heatmap/style":522,"./attributes":532,"./defaults":534}],536:[function(t,e,r){"use strict";var n=t("../histogram/bin_defaults");e.exports=function(t,e,r){var i=r("x"),a=r("y");if(!(i&&i.length&&a&&a.length))return void(e.visible=!1);var o=r("z")||r("marker.color");o&&r("histfunc");var s=["x","y"];n(t,e,r,s)}},{"../histogram/bin_defaults":526}],537:[function(t,e,r){"use strict";var n=t("../histogram2d/attributes"),i=t("../contour/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports=o({},{x:n.x,y:n.y,z:n.z,marker:n.marker,histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,autocontour:i.autocontour,ncontours:i.ncontours,contours:i.contours,line:i.line,_nestedModules:{colorbar:"Colorbar"}},a)},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../contour/attributes":502,"../histogram2d/attributes":532}],538:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../histogram2d/sample_defaults"),a=t("../contour/style_defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}i(t,e,l);var c=n.coerce2(t,e,o,"contours.start"),u=n.coerce2(t,e,o,"contours.end"),f=l("autocontour",!(c&&u));l(f?"ncontours":"contours.size"),a(t,e,l,s)}},{"../../lib":382,"../contour/style_defaults":511,"../histogram2d/sample_defaults":536,"./attributes":537}],539:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../contour/calc"),n.plot=t("../contour/plot"),n.style=t("../contour/style"),n.colorbar=t("../contour/colorbar"),n.hoverPoints=t("../contour/hover"),n.moduleType="trace",n.name="histogram2dcontour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","contour","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":413,"../contour/calc":503,"../contour/colorbar":504,"../contour/hover":506,"../contour/plot":509,"../contour/style":510,"./attributes":537,"./defaults":538}],540:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../surface/attributes"),a=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},i:{valType:"data_array"},j:{valType:"data_array"},k:{valType:"data_array"},delaunayaxis:{valType:"enumerated",values:["x","y","z"],dflt:"z"},alphahull:{valType:"number",dflt:-1},intensity:{valType:"data_array"},color:{valType:"color"},vertexcolor:{valType:"data_array"},facecolor:{valType:"data_array"},opacity:a({},i.opacity),flatshading:{valType:"boolean",dflt:!1},contour:{show:a({},i.contours.x.show,{}),color:a({},i.contours.x.color),width:a({},i.contours.x.width)},colorscale:n.colorscale,reversescale:n.reversescale,showscale:n.showscale,lightposition:{x:a({},i.lightposition.x,{dflt:1e5}),y:a({},i.lightposition.y,{dflt:1e5}),z:a({},i.lightposition.z,{dflt:0})},lighting:a({},{vertexnormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-12},facenormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-6}},i.lighting),_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":309,"../../lib/extend":377,"../surface/attributes":601}],541:[function(t,e,r){"use strict";function n(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.color="#fff",this.data=null,this.showContour=!1}function i(t){return t.map(function(t){var e=t[0],r=c(t[1]),n=r.toRgb();return{index:e,rgb:[n.r,n.g,n.b,1]}})}function a(t){return t.map(d)}function o(t,e,r){for(var n=new Array(t.length),i=0;i0)s=f(t.alphahull,l);else{var c=["x","y","z"].indexOf(t.delaunayaxis);s=u(l.map(function(t){return[t[(c+1)%3],t[(c+2)%3]]}))}var p={positions:l,cells:s,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:d(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",p.vertexIntensity=t.intensity,p.colormap=i(t.colorscale)):t.vertexcolor?(this.color=t.vertexcolors[0],p.vertexColors=a(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],p.cellColors=a(t.facecolor)):(this.color=t.color,p.meshColor=d(t.color)),this.mesh.update(p)},p.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=s},{"../../lib/str2rgbarray":394,"alpha-shape":40,"convex-hull":102,"delaunay-triangulate":114,"gl-mesh3d":150,tinycolor2:274}],542:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorbar/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}function l(t){var e=t.map(function(t){var e=s(t);return e&&Array.isArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var c=l(["x","y","z"]),u=l(["i","j","k"]);return c?(u&&u.forEach(function(t){for(var e=0;el||(c=p[r],void 0!==c&&""!==c||(c=r),c=String(c),void 0===y[c]&&(y[c]=!0,u=a(e.marker.colors[r]),u.isValid()?(u=o.addOpacity(u,u.getAlpha()),m[c]||(m[c]=u)):m[c]?u=m[c]:(u=!1,b=!0),f=-1!==_.indexOf(c),f||(x+=l),g.push({v:l,label:c,color:u,i:r,hidden:f}))));if(e.sort&&g.sort(function(t,e){return e.v-t.v}),b)for(r=0;r")}return g};var l},{"../../components/color":303,"./helpers":548,"fast-isnumeric":117,tinycolor2:274}],547:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}var s=n.coerceFont,l=o("values");if(!Array.isArray(l)||!l.length)return void(e.visible=!1);var c=o("labels");Array.isArray(c)||(o("label0"),o("dlabel"));var u=o("marker.line.width");u&&o("marker.line.color");var f=o("marker.colors");Array.isArray(f)||(e.marker.colors=[]),o("scalegroup");var h=o("text"),d=o("textinfo",Array.isArray(h)?"text+percent":"percent");if(o("hoverinfo",1===a._dataLength?"label+text+value+percent":void 0),d&&"none"!==d){var p=o("textposition"),g=Array.isArray(p)||"auto"===p,v=g||"inside"===p,m=g||"outside"===p;if(v||m){var y=s(o,"textfont",a.font);v&&s(o,"insidetextfont",y),m&&s(o,"outsidetextfont",y)}}o("domain.x"),o("domain.y"),o("hole"),o("sort"),o("direction"),o("rotation"),o("pull")}},{"../../lib":382,"./attributes":544}],548:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)}},{"../../lib":382}],549:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":544,"./base_plot":545,"./calc":546,"./defaults":547,"./layout_attributes":550,"./layout_defaults":551,"./plot":552,"./style":553,"./style_one":554}],550:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array"}}},{}],551:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e){function r(r,a){return n.coerce(t,e,i,r,a)}r("hiddenlabels")}},{"../../lib":382,"./layout_attributes":550}],552:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,o=Math.PI*Math.min(e.v/r.vTotal,.5),s=1-r.trace.hole,l=i(e,r),c={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(c.scale>=1)return c;var u=a+1/(2*Math.tan(o)),f=r.r*Math.min(1/(Math.sqrt(u*u+.5)+u),s/(Math.sqrt(a*a+s/2)+a)),h={scale:2*f/t.height,rCenter:Math.cos(f/r.r)-f*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},d=1/a,p=d+1/(2*Math.tan(o)),g=r.r*Math.min(1/(Math.sqrt(p*p+.5)+p),s/(Math.sqrt(d*d+s/2)+d)),v={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},m=v.scale>h.scale?v:h;return c.scale<1&&m.scale>c.scale?m:c}function i(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function a(t,e){var r=e.pxmid[0],n=e.pxmid[1],i=t.width/2,a=t.height/2;return 0>r&&(i*=-1),0>n&&(a*=-1),{scale:1,rCenter:1,rotate:0,x:i+Math.abs(a)*(i>0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}function o(t,e){function r(t,e){return t.pxmid[1]-e.pxmid[1]}function n(t,e){return e.pxmid[1]-t.pxmid[1]}function i(t,r){r||(r={});var n,i,a,s,h,d,g=r.labelExtraY+(o?r.yLabelMax:r.yLabelMin),v=o?t.yLabelMin:t.yLabelMax,m=o?t.yLabelMax:t.yLabelMin,y=t.cyFinal+c(t.px0[1],t.px1[1]),b=g-v;if(b*f>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(i=0;i=e.pull[a.i]||((t.pxmid[1]-a.pxmid[1])*f>0?(s=a.cyFinal+c(a.px0[1],a.px1[1]),b=s-v-t.labelExtraY,b*f>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-y)*f>0&&(n=3*u*Math.abs(i-p.indexOf(t)),h=a.cxFinal+l(a.px0[0],a.px1[0]),d=h+n-(t.cxFinal+t.pxmid[0])-t.labelExtraX,d*u>0&&(t.labelExtraX+=d)))}var a,o,s,l,c,u,f,h,d,p,g,v,m;for(o=0;2>o;o++)for(s=o?r:n,c=o?Math.max:Math.min,f=o?1:-1,a=0;2>a;a++){for(l=a?Math.max:Math.min,u=a?1:-1,h=t[o][a],h.sort(s),d=t[1-o][a],p=d.concat(h),v=[],g=0;gu&&(u=s.pull[a]);o.r=Math.min(r/c(s.tilt,Math.sin(l),s.depth),n/c(s.tilt,Math.cos(l),s.depth))/(2+2*u),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===d.indexOf(s.scalegroup)&&d.push(s.scalegroup)}for(a=0;af.vTotal/2?1:0)}function c(t,e,r){if(!t)return 1;var n=Math.sin(t*Math.PI/180);return Math.max(.01,r*n*Math.abs(e)+2*Math.sqrt(1-n*n*e*e))}var u=t("d3"),f=t("../../plots/cartesian/graph_interact"),h=t("../../components/color"),d=t("../../components/drawing"),p=t("../../lib/svg_text_utils"),g=t("./helpers");e.exports=function(t,e){var r=t._fullLayout;s(e,r._size);var c=r._pielayer.selectAll("g.trace").data(e);c.enter().append("g").attr({"stroke-linejoin":"round","class":"trace"}),c.exit().remove(),c.order(),c.each(function(e){var s=u.select(this),c=e[0],v=c.trace,m=0,y=(v.depth||0)*c.r*Math.sin(m)/2,b=v.tiltaxis||0,x=b*Math.PI/180,_=[y*Math.sin(x),y*Math.cos(x)],w=c.r*Math.cos(m),k=s.selectAll("g.part").data(v.tilt?["top","sides"]:["top"]);k.enter().append("g").attr("class",function(t){return t+" part"}),k.exit().remove(),k.order(),l(e),s.selectAll(".top").each(function(){var s=u.select(this).selectAll("g.slice").data(e);s.enter().append("g").classed("slice",!0),s.exit().remove();var l=[[[],[]],[[],[]]],m=!1;s.each(function(o){function s(e){var n=t._fullLayout,a=t._fullData[v.index],s=a.hoverinfo;if("all"===s&&(s="label+text+value+percent+name"),!t._dragging&&n.hovermode!==!1&&"none"!==s&&s){var l=i(o,c),u=k+o.pxmid[0]*(1-l),h=A+o.pxmid[1]*(1-l),d=r.separators,p=[];-1!==s.indexOf("label")&&p.push(o.label),a.text&&a.text[o.i]&&-1!==s.indexOf("text")&&p.push(a.text[o.i]),-1!==s.indexOf("value")&&p.push(g.formatPieValue(o.v,d)),-1!==s.indexOf("percent")&&p.push(g.formatPiePercent(o.v/c.vTotal,d)),f.loneHover({x0:u-l*c.r,x1:u+l*c.r,y:h,text:p.join("
"),name:-1!==s.indexOf("name")?a.name:void 0,color:o.color,idealAlign:o.pxmid[0]<0?"left":"right"},{container:n._hoverlayer.node(), -outerContainer:n._paper.node()}),f.hover(t,e,"pie"),E=!0}}function h(e){t.emit("plotly_unhover",{points:[e]}),E&&(f.loneUnhover(r._hoverlayer.node()),E=!1)}function y(){t._hoverdata=[o],t._hoverdata.trace=e.trace,f.click(t,{target:!0})}function x(t,e,r,n){return"a"+n*c.r+","+n*w+" "+b+" "+o.largeArc+(r?" 1 ":" 0 ")+n*(e[0]-t[0])+","+n*(e[1]-t[1])}if(o.hidden)return void u.select(this).selectAll("path,g").remove();l[o.pxmid[1]<0?0:1][o.pxmid[0]<0?0:1].push(o);var k=c.cx+_[0],A=c.cy+_[1],M=u.select(this),T=M.selectAll("path.surface").data([o]),E=!1;if(T.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),M.select("path.textline").remove(),M.on("mouseover",s).on("mouseout",h).on("click",y),v.pull){var L=+(Array.isArray(v.pull)?v.pull[o.i]:v.pull)||0;L>0&&(k+=L*o.pxmid[0],A+=L*o.pxmid[1])}o.cxFinal=k,o.cyFinal=A;var S=v.hole;if(o.v===c.vTotal){var C="M"+(k+o.px0[0])+","+(A+o.px0[1])+x(o.px0,o.pxmid,!0,1)+x(o.pxmid,o.px0,!0,1)+"Z";S?T.attr("d","M"+(k+S*o.px0[0])+","+(A+S*o.px0[1])+x(o.px0,o.pxmid,!1,S)+x(o.pxmid,o.px0,!1,S)+"Z"+C):T.attr("d",C)}else{var z=x(o.px0,o.px1,!0,1);if(S){var P=1-S;T.attr("d","M"+(k+S*o.px1[0])+","+(A+S*o.px1[1])+x(o.px1,o.px0,!1,S)+"l"+P*o.px0[0]+","+P*o.px0[1]+z+"Z")}else T.attr("d","M"+k+","+A+"l"+o.px0[0]+","+o.px0[1]+z+"Z")}var R=Array.isArray(v.textposition)?v.textposition[o.i]:v.textposition,O=M.selectAll("g.slicetext").data(o.text&&"none"!==R?[0]:[]);O.enter().append("g").classed("slicetext",!0),O.exit().remove(),O.each(function(){var t=u.select(this).selectAll("text").data([0]);t.enter().append("text").attr("data-notex",1),t.exit().remove(),t.text(o.text).attr({"class":"slicetext",transform:"","data-bb":"","text-anchor":"middle",x:0,y:0}).call(d.font,"outside"===R?v.outsidetextfont:v.insidetextfont).call(p.convertToTspans),t.selectAll("tspan.line").attr({x:0,y:0});var e,r=d.bBox(t.node());"outside"===R?e=a(r,o):(e=n(r,o,c),"auto"===R&&e.scale<1&&(t.call(d.font,v.outsidetextfont),v.outsidetextfont.family===v.insidetextfont.family&&v.outsidetextfont.size===v.insidetextfont.size||(t.attr({"data-bb":""}),r=d.bBox(t.node())),e=a(r,o)));var i=k+o.pxmid[0]*e.rCenter+(e.x||0),s=A+o.pxmid[1]*e.rCenter+(e.y||0);e.outside&&(o.yLabelMin=s-r.height/2,o.yLabelMid=s,o.yLabelMax=s+r.height/2,o.labelExtraX=0,o.labelExtraY=0,m=!0),t.attr("transform","translate("+i+","+s+")"+(e.scale<1?"scale("+e.scale+")":"")+(e.rotate?"rotate("+e.rotate+")":"")+"translate("+-(r.left+r.right)/2+","+-(r.top+r.bottom)/2+")")})}),m&&o(l,v),s.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=u.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var n=t.cxFinal+t.pxmid[0],i=t.cyFinal+t.pxmid[1],a="M"+n+","+i,o=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],l=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);a+=Math.abs(s)>Math.abs(l)?"l"+l*t.pxmid[0]/t.pxmid[1]+","+l+"H"+(n+t.labelExtraX+o):"l"+t.labelExtraX+","+s+"v"+(l-s)+"h"+o}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+o;e.append("path").classed("textline",!0).call(h.stroke,v.outsidetextfont.color).attr({"stroke-width":Math.min(2,v.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){c.selectAll("tspan").each(function(){var t=u.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":303,"../../components/drawing":326,"../../lib/svg_text_utils":395,"../../plots/cartesian/graph_interact":412,"./helpers":548,d3:113}],553:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0],r=e.trace,a=n.select(this);a.style({opacity:r.opacity}),a.selectAll(".top path.surface").each(function(t){n.select(this).call(i,t,r)})})}},{"./style_one":554,d3:113}],554:[function(t,e,r){"use strict";var n=t("../../components/color");e.exports=function(t,e,r){var i=r.marker.line.color;Array.isArray(i)&&(i=i[e.i]||n.defaultLine);var a=r.marker.line.width||0;Array.isArray(a)&&(a=a[e.i]||0),t.style({"stroke-width":a,fill:e.color}).call(n.stroke,i)}},{"../../components/color":303}],555:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){var e=t[0].trace,r=e.marker;if(n.mergeArray(e.text,t,"tx"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf")),r&&r.line){var i=r.line;n.mergeArray(r.opacity,t,"mo"),n.mergeArray(r.symbol,t,"mx"),n.mergeArray(r.color,t,"mc"),n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw")}}},{"../../lib":382}],556:[function(t,e,r){"use strict";var n=t("../../components/colorscale/color_attributes"),i=t("../../components/drawing"),a=(t("./constants"),t("../../lib/extend").extendFlat);e.exports={x:{valType:"data_array"},x0:{valType:"any",dflt:0},dx:{valType:"number",dflt:1},y:{valType:"data_array"},y0:{valType:"any",dflt:0},dy:{valType:"number",dflt:1},text:{valType:"string",dflt:"",arrayOk:!0},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"]},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear"},smoothing:{valType:"number",min:0,max:1.3,dflt:1},dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid"}},connectgaps:{valType:"boolean",dflt:!1},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none"},fillcolor:{valType:"color"},marker:a({},{symbol:{valType:"enumerated",values:i.symbolList,dflt:"circle",arrayOk:!0},opacity:{valType:"number",min:0,max:1,arrayOk:!0},size:{valType:"number",min:0,dflt:6,arrayOk:!0},maxdisplayed:{valType:"number",min:0,dflt:0},sizeref:{valType:"number",dflt:1},sizemin:{valType:"number",min:0,dflt:0},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter"},showscale:{valType:"boolean",dflt:!1},line:a({},{width:{valType:"number",min:0,arrayOk:!0}},n("marker.line"))},n("marker")),textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0},textfont:{family:{valType:"string",noBlank:!0,strict:!0,arrayOk:!0},size:{valType:"number",min:1,arrayOk:!0},color:{valType:"color",arrayOk:!0}},r:{valType:"data_array"},t:{valType:"data_array"},_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":311,"../../components/drawing":326,"../../lib/extend":377,"./constants":560}],557:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./subtypes"),s=t("./marker_colorscale_calc");e.exports=function(t,e){var r,l,c,u=i.getFromId(t,e.xaxis||"x"),f=i.getFromId(t,e.yaxis||"y"),h=u.makeCalcdata(e,"x"),d=f.makeCalcdata(e,"y"),p=Math.min(h.length,d.length);u._minDtick=0,f._minDtick=0,h.length>p&&h.splice(p,h.length-p),d.length>p&&d.splice(p,d.length-p);var g={padded:!0},v={padded:!0};if(o.hasMarkers(e)){if(r=e.marker,l=r.size,Array.isArray(l)){var m={type:"linear"};i.setConvert(m),l=m.makeCalcdata(e.marker,"size"),l.length>p&&l.splice(p,l.length-p)}var y,b=1.6*(e.marker.sizeref||1);y="area"===e.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/b),3)}:function(t){return Math.max((t||0)/b,3)},g.ppad=v.ppad=Array.isArray(l)?l.map(y):y(l)}s(e),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||h[0]===h[p-1]&&d[0]===d[p-1]?e.error_y.visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(o.hasMarkers(e)||o.hasText(e))||(g.padded=!1,g.ppad=0):g.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||h[0]===h[p-1]&&d[0]===d[p-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(v.padded=!1):v.tozero=!0,i.expand(u,h,g),i.expand(f,d,v);var x=new Array(p);for(c=0;p>c;c++)x[c]=n(h[c])&&n(d[c])?{x:h[c],y:d[c]}:{x:!1,y:!1};return void 0!==typeof l&&a.mergeArray(l,x,"ms"),t.firstscatter=!1,x}},{"../../lib":382,"../../plots/cartesian/axes":405,"./marker_colorscale_calc":570,"./subtypes":575,"fast-isnumeric":117}],558:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i,a;for(e=0;e=0;i--)if(a=t[i],"scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}},{}],559:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,c=r.marker,u="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+u).remove(),void 0===c||!c.showscale)return void o.autoMargin(t,u);var f=s(c.colorscale),h=c.color,d=c.cmin,p=c.cmax;i(d)||(d=a.aggNums(Math.min,null,h)),i(p)||(p=a.aggNums(Math.max,null,h));var g=e[0].t.cb=l(t,u);g.fillcolor(n.scale.linear().domain(f.map(function(t){return d+t[0]*(p-d)})).range(f.map(function(t){return t[1]}))).filllevels({start:d,end:p,size:(p-d)/254}).options(c.colorbar)()}},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":315,"../../lib":382,"../../plots/plots":454,d3:113,"fast-isnumeric":117}],560:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20}},{}],561:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./constants"),o=t("./subtypes"),s=t("./xy_defaults"),l=t("./marker_defaults"),c=t("./line_defaults"),u=t("./line_shape_defaults"),f=t("./text_defaults"),h=t("./fillcolor_defaults"),d=t("../../components/errorbars/defaults");e.exports=function(t,e,r,p){function g(r,a){return n.coerce(t,e,i,r,a)}var v=s(t,e,g),m=vi(f))break;l=f,y=g[0]*p[0]+g[1]*p[1],y>v?(v=y,c=f,d=!1):m>y&&(m=y,u=f,d=!0)}if(d?(C[z++]=c,l!==u&&(C[z++]=u)):(u!==s&&(C[z++]=u),l!==c&&(C[z++]=c)),C[z++]=l,o>=t.length||!f)break;C[z++]=f,s=f}}else C[z++]=c}E.push(C.slice(0,z))}return E}},{"../../plots/cartesian/axes":405}],568:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=r("line.shape");"spline"===n&&r("line.smoothing")}},{}],569:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t){var e=t.marker,r=e.sizeref||1,i=e.sizemin||0,a="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=a(t/2);return n(e)&&e>0?Math.max(e,i):0}}},{"fast-isnumeric":117}],570:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t){if(a.hasMarkers(t)){var e=t.marker;n(t,"marker")&&i(t,e.color,"marker","c"),n(t,"marker.line")&&i(t,e.line.color,"marker.line","c")}}},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":316,"./subtypes":575}],571:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l){var c,u=o.isBubble(t),f=(t.line||{}).color;f&&(r=f),l("marker.symbol"),l("marker.opacity",u?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),c=f&&e.marker.color!==f?f:u?n.background:n.defaultLine,l("marker.line.color",c),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",u?1:0),u&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode"))}},{"../../components/color":303,"../../components/colorscale/defaults":313,"../../components/colorscale/has_colorscale":316,"./subtypes":575}],572:[function(t,e,r){"use strict";function n(t,e,r){var n=e.x(),a=e.y(),o=i.extent(n.range.map(n.l2c)),s=i.extent(a.range.map(a.l2c));r.forEach(function(t,e){var n=t[0].trace;if(l.hasMarkers(n)){var i=n.marker.maxdisplayed;if(0!==i){var a=t.filter(function(t){return t.x>=o[0]&&t.x<=o[1]&&t.y>=s[0]&&t.y<=s[1]}),c=Math.ceil(a.length/i),u=0;r.forEach(function(t,r){var n=t[0].trace;l.hasMarkers(n)&&n.marker.maxdisplayed>0&&e>r&&u++});var f=Math.round(u*c/3+Math.floor(u/3)*c/7.1);t.forEach(function(t){delete t.vis}),a.forEach(function(t,e){0===Math.round((e+f)%c)&&(t.vis=!0)})}}})}var i=t("d3"),a=t("../../lib"),o=t("../../components/drawing"),s=t("../../components/errorbars"),l=t("./subtypes"),c=t("./arrays_to_calcdata"),u=t("./line_points");e.exports=function(t,e,r){function f(t){return t.filter(function(t){return t.vis})}n(t,e,r);var h=e.x(),d=e.y(),p=e.plot.select(".scatterlayer").selectAll("g.trace.scatter").data(r);p.enter().append("g").attr("class","trace scatter").style("stroke-miterlimit",2),p.call(s.plot,e);var g,v,m,y,b="";p.each(function(t){var e=t[0].trace,r=e.line,n=i.select(this);if(e.visible===!0&&(v=e.fill.charAt(e.fill.length-1),"x"!==v&&"y"!==v&&(v=""),t[0].node3=n,c(t),l.hasLines(e)||"none"!==e.fill)){var a,s,f,p,x,_="",w="";g="tozero"===e.fill.substr(0,6)||"toself"===e.fill||"to"===e.fill.substr(0,2)&&!b?n.append("path").classed("js-fill",!0):null,y&&(m=y.datum(t)),y=n.append("path").classed("js-fill",!0),-1!==["hv","vh","hvh","vhv"].indexOf(r.shape)?(f=o.steps(r.shape),p=o.steps(r.shape.split("").reverse().join(""))):f=p="spline"===r.shape?function(t){var e=t[t.length-1];return t[0][0]===e[0]&&t[0][1]===e[1]?o.smoothclosed(t.slice(1),r.smoothing):o.smoothopen(t,r.smoothing)}:function(t){return"M"+t.join("L")},x=function(t){return p(t.reverse())};var k=u(t,{xaxis:h,yaxis:d,connectGaps:e.connectgaps,baseTolerance:Math.max(r.width||1,3)/4,linear:"linear"===r.shape});if(k.length){for(var A=k[0][0],M=k[k.length-1],T=M[M.length-1],E=0;E1&&n.append("path").classed("js-line",!0).attr("d",a)}g?A&&T&&(v?("y"===v?A[1]=T[1]=d.c2p(0,!0):"x"===v&&(A[0]=T[0]=h.c2p(0,!0)),g.attr("d",_+"L"+T+"L"+A+"Z")):g.attr("d",_+"Z")):"tonext"===e.fill.substr(0,6)&&_&&b&&("tonext"===e.fill?m.attr("d",_+"Z"+b+"Z"):m.attr("d",_+"L"+b.substr(1)+"Z")),b=w}}}),p.selectAll("path:not([d])").remove(),p.append("g").attr("class","points").each(function(t){var e=t[0].trace,r=i.select(this),n=l.hasMarkers(e),s=l.hasText(e);!n&&!s||e.visible!==!0?r.remove():(n&&r.selectAll("path.point").data(e.marker.maxdisplayed?f:a.identity).enter().append("path").classed("point",!0).call(o.translatePoints,h,d),s&&r.selectAll("g").data(e.marker.maxdisplayed?f:a.identity).enter().append("g").append("text").call(o.translatePoints,h,d))})}},{"../../components/drawing":326,"../../components/errorbars":332,"../../lib":382,"./arrays_to_calcdata":555,"./line_points":567,"./subtypes":575,d3:113}],573:[function(t,e,r){"use strict";var n=t("./subtypes"),i=.2;e.exports=function(t,e){var r,a,o,s,l=t.cd,c=t.xaxis,u=t.yaxis,f=[],h=l[0].trace,d=h.index,p=h.marker;if(n.hasMarkers(h)||n.hasText(h)){var g=Array.isArray(p.opacity)?1:p.opacity;if(e===!1)for(r=0;rs;s++){for(var l=[[0,0,0],[0,0,0]],c=0;3>c;c++)if(r[c])for(var u=0;2>u;u++)l[u][c]=r[c][s][u];o[s]=l}return o}var o=t("../../components/errorbars/compute_error");e.exports=a},{"../../components/errorbars/compute_error":330}],581:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.linePlot=null,this.scatterPlot=null,this.errorBars=null,this.textMarkers=null,this.delaunayMesh=null,this.color=null,this.mode="",this.dataPoints=[],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.textLabels=null,this.data=null}function i(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;ni;i++){var a=t[i];a&&a.copy_zstyle!==!1&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=b(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}function o(t){var e=[0,0];return Array.isArray(t)?[0,-1]:(t.indexOf("bottom")>=0&&(e[1]+=1),t.indexOf("top")>=0&&(e[1]-=1),t.indexOf("left")>=0&&(e[0]-=1),t.indexOf("right")>=0&&(e[0]+=1),e)}function s(t,e){return e(4*t)}function l(t){return k[t]}function c(t,e,r,n,i){var a=null;if(Array.isArray(t)){a=[];for(var o=0;e>o;o++)void 0===t[o]?a[o]=n:a[o]=r(t[o],i)}else a=r(t,y.identity);return a}function u(t,e){var r,n,i,u,f,h,d=[],p=t.fullSceneLayout,g=t.dataScale,v=p.xaxis,m=p.yaxis,w=p.zaxis,k=e.marker,M=e.line,T=e.x||[],E=e.y||[],L=e.z||[],S=T.length;for(n=0;S>n;n++)i=v.d2l(T[n])*g[0],u=m.d2l(E[n])*g[1],f=w.d2l(L[n])*g[2],d[n]=[i,u,f];if(Array.isArray(e.text))h=e.text;else if(void 0!==e.text)for(h=new Array(S),n=0;S>n;n++)h[n]=e.text;if(r={position:d,mode:e.mode,text:h},"line"in e&&(r.lineColor=b(M.color),r.lineWidth=M.width,r.lineDashes=M.dash),"marker"in e){var C=_(e);r.scatterColor=x(k,1,S),r.scatterSize=c(k.size,S,s,20,C),r.scatterMarker=c(k.symbol,S,l,"\u25cf"),r.scatterLineWidth=k.line.width,r.scatterLineColor=x(k.line,1,S),r.scatterAngle=0}"textposition"in e&&(r.textOffset=o(e.textposition),r.textColor=x(e.textfont,1,S),r.textSize=c(e.textfont.size,S,y.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var z=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;3>n;++n){var P=e.projection[z[n]];(r.project[n]=P.show)&&(r.projectOpacity[n]=P.opacity,r.projectScale[n]=P.scale)}r.errorBounds=A(e,g);var R=a([e.error_x,e.error_y,e.error_z]);return r.errorColor=R.color,r.errorLineWidth=R.lineWidth,r.errorCapSize=R.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=b(e.surfacecolor),r}function f(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}function h(t,e){var r=new n(t,e.uid);return r.update(e),r}var d=t("gl-line3d"),p=t("gl-scatter3d"),g=t("gl-error3d"),v=t("gl-mesh3d"),m=t("delaunay-triangulate"),y=t("../../lib"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/make_bubble_size_func"),w=t("../../constants/gl3d_dashes"),k=t("../../constants/gl_markers"),A=t("./calc_errors"),M=n.prototype;M.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels&&void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel="";var e=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},M.update=function(t){var e,r,n,a,o=this.scene.glplot.gl,s=w.solid;this.data=t;var l=u(this.scene,t);"mode"in l&&(this.mode=l.mode),"lineDashes"in l&&l.lineDashes in w&&(s=w[l.lineDashes]),this.color=f(l.scatterColor)||f(l.lineColor),this.dataPoints=l.position,e={gl:o,position:l.position,color:l.lineColor,lineWidth:l.lineWidth||1,dashes:s[0],dashScale:s[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=d(e),this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var c=t.opacity;if(t.marker&&t.marker.opacity&&(c*=t.marker.opacity),r={gl:o,position:l.position,color:l.scatterColor,size:l.scatterSize,glyph:l.scatterMarker,opacity:c,orthographic:!0,lineWidth:l.scatterLineWidth,lineColor:l.scatterLineColor,project:l.project,projectScale:l.projectScale,projectOpacity:l.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=p(r),this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),a={gl:o,position:l.position,glyph:l.text,color:l.textColor,size:l.textSize,angle:l.textAngle,alignment:l.textOffset,font:l.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=l.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(a):(this.textMarkers=p(a),this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:o,position:l.position,color:l.errorColor,error:l.errorBounds,lineWidth:l.errorLineWidth,capSize:l.errorCapSize,opacity:t.opacity},this.errorBars?l.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):l.errorBounds&&(this.errorBars=g(n),this.scene.glplot.add(this.errorBars)),l.delaunayAxis>=0){var h=i(l.position,l.delaunayColor,l.delaunayAxis);h.opacity=t.opacity,this.delaunayMesh?this.delaunayMesh.update(h):(h.gl=o,this.delaunayMesh=v(h),this.scene.glplot.add(this.delaunayMesh))}else this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose(),this.delaunayMesh=null)},M.dispose=function(){this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose()),this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose()),this.errorBars&&(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose()),this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose()),this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose())},e.exports=h},{"../../constants/gl3d_dashes":368,"../../constants/gl_markers":369,"../../lib":382,"../../lib/gl_format_color":380,"../../lib/str2rgbarray":394,"../scatter/make_bubble_size_func":569,"./calc_errors":580,"delaunay-triangulate":114,"gl-error3d":121,"gl-line3d":127,"gl-mesh3d":150,"gl-scatter3d":193}],582:[function(t,e,r){"use strict";function n(t,e,r){var n=0,i=r("x"),a=r("y"),o=r("z");return i&&a&&o&&(n=Math.min(i.length,a.length,o.length),n=0&&h("surfacecolor",p||g);for(var v=["x","y","z"],m=0;3>m;++m){var y="projection."+v[m];h(y+".show")&&(h(y+".opacity"),h(y+".scale"))}c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}},{"../../components/errorbars/defaults":331,"../../lib":382,"../scatter/line_defaults":566,"../scatter/marker_defaults":571,"../scatter/subtypes":575,"../scatter/text_defaults":576,"./attributes":578}],583:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../constants/gl_markers":369,"../../plots/gl3d":441,"../scatter/colorbar":559,"./attributes":578,"./calc":579,"./convert":581,"./defaults":582}],584:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../components/colorscale/color_attributes"),o=t("../../lib/extend").extendFlat,s=n.marker,l=n.line,c=s.line; -e.exports={lon:{valType:"data_array"},lat:{valType:"data_array"},locations:{valType:"data_array"},locationmode:{valType:"enumerated",values:["ISO-3","USA-states","country names"],dflt:"ISO-3"},mode:o({},n.mode,{dflt:"markers"}),text:o({},n.text,{}),line:{color:l.color,width:l.width,dash:l.dash},marker:o({},{symbol:s.symbol,opacity:s.opacity,size:s.size,sizeref:s.sizeref,sizemin:s.sizemin,sizemode:s.sizemode,showscale:s.showscale,line:o({},{width:c.width},a("marker.line"))},a("marker")),textfont:n.textfont,textposition:n.textposition,hoverinfo:o({},i.hoverinfo,{flags:["lon","lat","location","text","name"]}),_nestedModules:{"marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":311,"../../lib/extend":377,"../../plots/attributes":403,"../scatter/attributes":556}],585:[function(t,e,r){"use strict";var n=t("../scatter/marker_colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(e),r}},{"../scatter/marker_colorscale_calc":570}],586:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=0,o=r("locations");return o?(r("locationmode"),a=o.length):(n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length),an;n++)r[n]=[t.lon[n],t.lat[n]];return{type:"LineString",coordinates:r,trace:t}}function a(t,e){function r(e){var r=t.mockAxis;return c.tickText(r,r.c2l(e),"hover").text+"\xb0"}var n=e.hoverinfo;if("none"===n)return function(t){delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("location")&&Array.isArray(e.locations),o=-1!==i.indexOf("lon"),s=-1!==i.indexOf("lat"),l=-1!==i.indexOf("text");return function(t){var n=[];a?n.push(t.location):o&&s?n.push("("+r(t.lon)+", "+r(t.lat)+")"):o?n.push("lon: "+r(t.lon)):s&&n.push("lat: "+r(t.lat)),l&&n.push(t.tx||e.text),t.textLabel=n.join("
")}}function o(t){var e=Array.isArray(t.locations);return function(r,n){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:n,lon:r.lon,lat:r.lat,location:e?r.location:null}]}}}var s=t("d3"),l=t("../../plots/cartesian/graph_interact"),c=t("../../plots/cartesian/axes"),u=t("../../lib/topojson_utils").getTopojsonFeatures,f=t("../../lib/geo_location_utils").locationToFeature,h=t("../../lib/array_to_calc_item"),d=t("../../components/color"),p=t("../../components/drawing"),g=t("../scatter/subtypes"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){var r,i,a,o,s=[],l=Array.isArray(t.locations);l?(o=t.locations,r=o.length,i=u(t,e),a=function(t,e){var r=f(t.locationmode,o[e],i);return void 0!==r?r.properties.ct:void 0}):(r=t.lon.length,a=function(t,e){return[t.lon[e],t.lat[e]]});for(var c=0;r>c;c++){var h=a(t,c);if(h){var d={lon:h[0],lat:h[1],location:l?t.locations[c]:null};n(t,d,c),s.push(d)}}return s.length>0&&(s[0].trace=t),s},m.plot=function(t,e){var r=t.framework.select(".scattergeolayer").selectAll("g.trace.scattergeo").data(e,function(t){return t.uid});r.enter().append("g").attr("class","trace scattergeo"),r.exit().remove(),r.selectAll("*").remove(),r.each(function(t){var e=s.select(this);g.hasLines(t)&&e.selectAll("path.js-line").data([i(t)]).enter().append("path").classed("js-line",!0)}),r.each(function(e){function r(r,n){if(t.showHover){var i=t.projection([r.lon,r.lat]);h(r),l.loneHover({x:i[0],y:i[1],name:v?e.name:void 0,text:r.textLabel,color:r.mc||(e.marker||{}).color},{container:t.hoverContainer.node()}),y=d(r,n),t.graphDiv.emit("plotly_hover",y)}}function n(e,r){t.graphDiv.emit("plotly_click",d(e,r))}var i=s.select(this),c=g.hasMarkers(e),u=g.hasText(e);if(c||u){var f=m.calcGeoJSON(e,t.topojson),h=a(t,e),d=o(e),p=e.hoverinfo,v="all"===p||-1!==p.indexOf("name"),y=null;c&&i.selectAll("path.point").data(f).enter().append("path").classed("point",!0).on("mouseover",r).on("click",n).on("mouseout",function(){l.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",y)}).on("mousedown",function(){l.loneUnhover(t.hoverContainer)}).on("mouseup",r),u&&i.selectAll("g").data(f).enter().append("g").append("text")}}),m.style(t)},m.style=function(t){var e=t.framework.selectAll("g.trace.scattergeo");e.style("opacity",function(t){return t.opacity}),e.each(function(t){s.select(this).selectAll("path.point").call(p.pointStyle,t),s.select(this).selectAll("text").call(p.textPointStyle,t)}),e.selectAll("path.js-line").style("fill","none").each(function(t){var e=t.trace,r=e.line||{};s.select(this).call(d.stroke,r.color).call(p.dashLine,r.dash||"",r.width||0)})}},{"../../components/color":303,"../../components/drawing":326,"../../lib/array_to_calc_item":373,"../../lib/geo_location_utils":379,"../../lib/topojson_utils":396,"../../plots/cartesian/axes":405,"../../plots/cartesian/graph_interact":412,"../scatter/subtypes":575,"./attributes":584,d3:113}],589:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/colorscale/color_attributes"),a=t("../../constants/gl2d_dashes"),o=t("../../constants/gl_markers"),s=t("../../lib/extend").extendFlat,l=t("../../lib/extend").extendDeep,c=n.line,u=n.marker,f=u.line;e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:s({},n.text,{}),mode:{valType:"flaglist",flags:["lines","markers"],extras:["none"]},line:{color:c.color,width:c.width,dash:{valType:"enumerated",values:Object.keys(a),dflt:"solid"}},marker:l({},i("marker"),{symbol:{valType:"enumerated",values:Object.keys(o),dflt:"circle",arrayOk:!0},size:u.size,sizeref:u.sizeref,sizemin:u.sizemin,sizemode:u.sizemode,opacity:u.opacity,showscale:u.showscale,line:l({},i("marker.line"),{width:f.width})}),connectgaps:n.connectgaps,fill:s({},n.fill,{values:["none","tozeroy","tozerox"]}),fillcolor:n.fillcolor,_nestedModules:{error_x:"ErrorBars",error_y:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":311,"../../constants/gl2d_dashes":367,"../../constants/gl_markers":369,"../../lib/extend":377,"../scatter/attributes":556}],590:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.connectgaps=!0,this.idToIndex=[],this.bounds=[0,0,0,0],this.hasLines=!1,this.lineOptions={positions:new Float32Array(0),color:[0,0,0,1],width:1,fill:[!1,!1,!1,!1],fillColor:[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],dashes:[1]},this.line=d(t.glplot,this.lineOptions),this.line._trace=this,this.hasErrorX=!1,this.errorXOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorX=p(t.glplot,this.errorXOptions),this.errorX._trace=this,this.hasErrorY=!1,this.errorYOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorY=p(t.glplot,this.errorYOptions),this.errorY._trace=this,this.hasMarkers=!1,this.scatterOptions={positions:new Float32Array(0),sizes:[],colors:[],glyphs:[],borderWidths:[],borderColors:[],size:12,color:[0,0,0,1],borderSize:1,borderColor:[0,0,0,1]},this.scatter=f(t.glplot,this.scatterOptions),this.scatter._trace=this,this.fancyScatter=h(t.glplot,this.scatterOptions),this.fancyScatter._trace=this}function i(t,e,r){return Array.isArray(e)||(e=[e]),a(t,e,r)}function a(t,e,r){for(var n=new Array(r),i=e[0],a=0;r>a;++a)n[a]=t(a>=e.length?i:e[a]);return n}function o(t,e,r){return l(S(t,r),L(e,r),r)}function s(t,e,r,n){var i=x(t,e,n);return i=Array.isArray(i[0])?i:a(v.identity,[i],n),l(i,L(r,n),n)}function l(t,e,r){for(var n=new Array(4*r),i=0;r>i;++i){for(var a=0;3>a;++a)n[4*i+a]=t[i][a];n[4*i+3]=t[i][3]*e[i]}return n}function c(t,e){if(void 0===Float32Array.slice){for(var r=new Float32Array(e),n=0;e>n;n++)r[n]=t[n];return r}return t.slice(0,e)}function u(t,e){var r=new n(t,e.uid);return r.update(e),r}var f=t("gl-scatter2d"),h=t("gl-scatter2d-fancy"),d=t("gl-line2d"),p=t("gl-error2d"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../plots/cartesian/axes"),y=t("../../components/errorbars"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/subtypes"),w=t("../scatter/make_bubble_size_func"),k=t("../scatter/get_trace_color"),A=t("../../constants/gl_markers"),M=t("../../constants/gl2d_dashes"),T=["xaxis","yaxis"],E=n.prototype;E.handlePick=function(t){var e=t.pointId;return(t.object!==this.line||this.connectgaps)&&(e=this.idToIndex[t.pointId]),{trace:this,dataCoord:t.dataCoord,traceCoord:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:Array.isArray(this.color)?this.color[e]:this.color,name:this.name,hoverinfo:this.hoverinfo}},E.isFancy=function(t){if("linear"!==this.scene.xaxis.type)return!0;if("linear"!==this.scene.yaxis.type)return!0;if(!t.x||!t.y)return!0;if(this.hasMarkers){var e=t.marker||{};if(Array.isArray(e.symbol)||"circle"!==e.symbol||Array.isArray(e.size)||Array.isArray(e.color)||Array.isArray(e.line.width)||Array.isArray(e.line.color)||Array.isArray(e.opacity))return!0}return this.hasLines&&!this.connectgaps?!0:this.hasErrorX?!0:!!this.hasErrorY};var L=i.bind(null,function(t){return+t}),S=i.bind(null,b),C=i.bind(null,function(t){return A[t]||"\u25cf"});E.update=function(t){t.visible!==!0?(this.hasLines=!1,this.hasErrorX=!1,this.hasErrorY=!1,this.hasMarkers=!1):(this.hasLines=_.hasLines(t),this.hasErrorX=t.error_x.visible===!0,this.hasErrorY=t.error_y.visible===!0,this.hasMarkers=_.hasMarkers(t)),this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.connectgaps=!!t.connectgaps,this.isFancy(t)?this.updateFancy(t):this.updateFast(t),this.color=k(t,{})},E.updateFast=function(t){for(var e,r,n=this.xData=this.pickXData=t.x,i=this.yData=this.pickYData=t.y,a=n.length,o=new Array(a),s=new Float32Array(2*a),l=this.bounds,u=0,f=0,h=0;a>h;++h)e=n[h],r=i[h],g(e)&&g(r)&&(o[u++]=h,s[f++]=e,s[f++]=r,l[0]=Math.min(l[0],e),l[1]=Math.min(l[1],r),l[2]=Math.max(l[2],e),l[3]=Math.max(l[3],r));s=c(s,f),this.idToIndex=o,this.updateLines(t,s),this.updateError("X",t),this.updateError("Y",t);var d;if(this.hasMarkers){this.scatterOptions.positions=s;var p=b(t.marker.color),v=b(t.marker.line.color),m=t.opacity*t.marker.opacity;p[3]*=m,this.scatterOptions.color=p,v[3]*=m,this.scatterOptions.borderColor=v,d=t.marker.size,this.scatterOptions.size=d,this.scatterOptions.borderSize=t.marker.line.width,this.scatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions),this.expandAxesFast(l,d)},E.updateFancy=function(t){var e=this.scene,r=e.xaxis,n=e.yaxis,a=this.bounds,o=this.pickXData=r.makeCalcdata(t,"x").slice(),l=this.pickYData=n.makeCalcdata(t,"y").slice();this.xData=o.slice(),this.yData=l.slice();var u,f,h,d,p,g,v,m,b=y.calcFromTrace(t,e.fullLayout),x=o.length,_=new Array(x),k=new Float32Array(2*x),A=new Float32Array(4*x),M=new Float32Array(4*x),T=0,E=0,S=0,z=0,P="log"===r.type?function(t){return r.d2l(t)}:function(t){return t},R="log"===n.type?function(t){return n.d2l(t)}:function(t){return t};for(u=0;x>u;++u)this.xData[u]=h=P(o[u]),this.yData[u]=d=R(l[u]),isNaN(h)||isNaN(d)||(_[T++]=u,k[E++]=h,k[E++]=d,p=A[S++]=h-b[u].xs||0,g=A[S++]=b[u].xh-h||0,A[S++]=0,A[S++]=0,M[z++]=0,M[z++]=0,v=M[z++]=d-b[u].ys||0,m=M[z++]=b[u].yh-d||0,a[0]=Math.min(a[0],h-p),a[1]=Math.min(a[1],d-v),a[2]=Math.max(a[2],h+g),a[3]=Math.max(a[3],d+m));k=c(k,E),this.idToIndex=_,this.updateLines(t,k),this.updateError("X",t,k,A),this.updateError("Y",t,k,M);var O;if(this.hasMarkers){this.scatterOptions.positions=k,this.scatterOptions.sizes=new Array(T),this.scatterOptions.glyphs=new Array(T),this.scatterOptions.borderWidths=new Array(T),this.scatterOptions.colors=new Array(4*T),this.scatterOptions.borderColors=new Array(4*T);var I,N=w(t),j=t.marker,F=j.opacity,D=t.opacity,B=s(j,F,D,x),U=C(j.symbol,x),V=L(j.line.width,x),q=s(j.line,F,D,x);for(O=i(N,j.size,x),u=0;T>u;++u)for(I=_[u],this.scatterOptions.sizes[u]=4*O[I],this.scatterOptions.glyphs[u]=U[I],this.scatterOptions.borderWidths[u]=.5*V[I],f=0;4>f;++f)this.scatterOptions.colors[4*u+f]=B[4*I+f],this.scatterOptions.borderColors[4*u+f]=q[4*I+f];this.fancyScatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions),this.expandAxesFancy(o,l,O)},E.updateLines=function(t,e){var r;if(this.hasLines){var n=e;if(!t.connectgaps){var i=0,a=this.xData,s=this.yData;for(n=new Float32Array(2*a.length),r=0;ro;o++)r=this.scene[T[o]],n=r._min,n||(n=[]),n.push({val:t[o],pad:a}),i=r._max,i||(i=[]),i.push({val:t[o+2],pad:a})},E.expandAxesFancy=function(t,e,r){var n=this.scene,i={padded:!0,ppad:r};m.expand(n.xaxis,t,i),m.expand(n.yaxis,e,i)},E.dispose=function(){this.line.dispose(),this.errorX.dispose(),this.errorY.dispose(),this.scatter.dispose(),this.fancyScatter.dispose()},e.exports=u},{"../../components/errorbars":332,"../../constants/gl2d_dashes":367,"../../constants/gl_markers":369,"../../lib":382,"../../lib/gl_format_color":380,"../../lib/str2rgbarray":394,"../../plots/cartesian/axes":405,"../scatter/get_trace_color":563,"../scatter/make_bubble_size_func":569,"../scatter/subtypes":575,"fast-isnumeric":117,"gl-error2d":119,"gl-line2d":125,"gl-scatter2d":190,"gl-scatter2d-fancy":185}],591:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/xy_defaults"),s=t("../scatter/marker_defaults"),l=t("../scatter/line_defaults"),c=t("../scatter/fillcolor_defaults"),u=t("../../components/errorbars/defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function d(r,i){return n.coerce(t,e,f,r,i)}var p=o(t,e,d);return p?(d("text"),d("mode",pr;r++)y=e.a[r],b=e.b[r],x=e.c[r],n(y)&&n(b)&&n(x)?(y=+y,b=+b,x=+x,_=v/(y+b+x),1!==_&&(y*=_,b*=_,x*=_),k=y,w=x-b,M[r]={x:w,y:k,a:y,b:b,c:x}):M[r]={x:!1,y:!1};var T,E;if(o.hasMarkers(e)&&(T=e.marker,E=T.size,Array.isArray(E))){var L={type:"linear"};i.setConvert(L),E=L.makeCalcdata(e.marker,"size"),E.length>A&&E.splice(A,E.length-A)}return s(e),void 0!==typeof E&&a.mergeArray(E,M,"ms"),M}},{"../../lib":382,"../../plots/cartesian/axes":405,"../scatter/marker_colorscale_calc":570,"../scatter/subtypes":575,"fast-isnumeric":117}],595:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/line_shape_defaults"),c=t("../scatter/text_defaults"),u=t("../scatter/fillcolor_defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function d(r,i){return n.coerce(t,e,f,r,i)}var p,g=d("a"),v=d("b"),m=d("c");if(g?(p=g.length,v?(p=Math.min(p,v.length),m&&(p=Math.min(p,m.length))):p=m?Math.min(p,m.length):0):v&&m&&(p=Math.min(v.length,m.length)),!p)return void(e.visible=!1);g&&p"),s}}},{"../../plots/cartesian/axes":405,"../scatter/hover":564}],597:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scatterternary",n.basePlotModule=t("../../plots/ternary"),n.categories=["ternary","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../plots/ternary":461,"../scatter/colorbar":559,"./attributes":593,"./calc":594,"./defaults":595,"./hover":596,"./plot":598,"./select":599,"./style":600}],598:[function(t,e,r){"use strict";var n=t("../scatter/plot");e.exports=function(t,e){var r=t.plotContainer;r.select(".scatterlayer").selectAll("*").remove();for(var i={x:function(){return t.xaxis},y:function(){return t.yaxis},plot:r},a=new Array(e.length),o=t.graphDiv.calcdata,s=0;se){for(var r=g/e,n=[0|Math.floor(t[0].shape[0]*r+1),0|Math.floor(t[0].shape[1]*r+1)],i=n[0]*n[1],o=0;or;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},v.update=function(t){var e,r=this.scene,n=r.fullSceneLayout,a=this.surface,s=t.opacity,l=i(t.colorscale,s),u=t.z,h=t.x,d=t.y,g=n.xaxis,v=n.yaxis,m=n.zaxis,y=r.dataScale,b=u[0].length,x=u.length,_=[c(new Float32Array(b*x),[b,x]),c(new Float32Array(b*x),[b,x]),c(new Float32Array(b*x),[b,x])],w=_[0],k=_[1],A=r.contourLevels;this.data=t,f(_[2],function(t,e){return m.d2l(u[e][t])*y[2]}),Array.isArray(h[0])?f(w,function(t,e){return g.d2l(h[e][t])*y[0]}):f(w,function(t){return g.d2l(h[t])*y[0]}),Array.isArray(d[0])?f(k,function(t,e){return v.d2l(d[e][t])*y[1]}):f(k,function(t,e){return v.d2l(d[e])*y[1]});var M={colormap:l,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:1};if(M.intensityBounds=[t.cmin,t.cmax],t.surfacecolor){var T=c(new Float32Array(b*x),[b,x]);f(T,function(e,r){return t.surfacecolor[r][e]}),_.push(T)}else M.intensityBounds[0]*=y[2],M.intensityBounds[1]*=y[2];this.dataScale=o(_),t.surfacecolor&&(M.intensity=_.pop()),"opacity"in t&&t.opacity<1&&(M.opacity=.25*t.opacity);var E=[!0,!0,!0],L=["x","y","z"];for(e=0;3>e;++e){var S=t.contours[L[e]];E[e]=S.highlight,M.showContour[e]=S.show||S.highlight,M.showContour[e]&&(M.contourProject[e]=[S.project.x,S.project.y,S.project.z],S.show?(this.showContour[e]=!0,M.levels[e]=A[e],a.highlightColor[e]=M.contourColor[e]=p(S.color),S.usecolormap?a.highlightTint[e]=M.contourTint[e]=0:a.highlightTint[e]=M.contourTint[e]=1,M.contourWidth[e]=S.width):this.showContour[e]=!1,S.highlight&&(M.dynamicColor[e]=p(S.highlightcolor),M.dynamicWidth[e]=S.highlightwidth))}M.coords=_,a.update(M),a.visible=t.visible,a.enableDynamic=E,a.snapToData=!0,"lighting"in t&&(a.ambientLight=t.lighting.ambient,a.diffuseLight=t.lighting.diffuse,a.specularLight=t.lighting.specular,a.roughness=t.lighting.roughness,a.fresnel=t.lighting.fresnel),"lightposition"in t&&(a.lightPosition=[t.lightposition.x,t.lightposition.y,t.lightposition.z]),s&&1>s&&(a.supportsTransparency=!0)},v.dispose=function(){this.scene.glplot.remove(this.surface),this.surface.dispose()},e.exports=s},{"../../lib/str2rgbarray":394,"gl-surface3d":221,ndarray:253,"ndarray-fill":246,"ndarray-homography":251,"ndarray-ops":252,tinycolor2:274}],605:[function(t,e,r){"use strict";function n(t,e,r){e in t&&!(r in t)&&(t[r]=t[e])}var i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}var c,u,f=l("z");if(!f)return void(e.visible=!1);var h=f[0].length,d=f.length;if(l("x"),l("y"),!Array.isArray(e.x))for(e.x=[],c=0;h>c;++c)e.x[c]=c;if(l("text"),!Array.isArray(e.y))for(e.y=[],c=0;d>c;++c)e.y[c]=c;["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lightposition.x","lightposition.y","lightposition.z","hidesurface","opacity"].forEach(function(t){l(t)});var p=l("surfacecolor");l("colorscale");var g=["x","y","z"];for(c=0;3>c;++c){var v="contours."+g[c],m=l(v+".show"),y=l(v+".highlight");if(m||y)for(u=0;3>u;++u)l(v+".project."+g[u]);m&&(l(v+".color"),l(v+".width"),l(v+".usecolormap")),y&&(l(v+".highlightcolor"),l(v+".highlightwidth"))}p||(n(t,"zmin","cmin"),n(t,"zmax","cmax"),n(t,"zauto","cauto")),a(t,e,s,l,{prefix:"",cLetter:"c"})}},{"../../components/colorscale/defaults":313,"../../lib":382,"./attributes":601}],606:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("./colorbar"),n.calc=t("./calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="surface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","noOpacity"],n.meta={},e.exports=n},{"../../plots/gl3d":441,"./attributes":601,"./calc":602,"./colorbar":603,"./convert":604,"./defaults":605}]},{},[12])(12)}); \ No newline at end of file +!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.Plotly=t()}}(function(){var t;return function e(t,r,n){function i(o,s){if(!r[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[o]={exports:{}};t[o][0].call(c.exports,function(e){var r=t[o][1][e];return i(r?r:e)},c,c.exports,e,t,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;or)){var i=this._components;if(r===e.length-1)for(var l=16*r,u=0;16>u;++u)n[u]=i[l++];else{for(var c=e[r+1]-e[r],l=16*r,f=this.prevMatrix,h=!0,u=0;16>u;++u)f[u]=i[l++];for(var d=this.nextMatrix,u=0;16>u;++u)d[u]=i[l++],h=h&&f[u]===d[u];if(1e-6>c||h)for(var u=0;16>u;++u)n[u]=f[u];else o(n,f,d,(t-e[r])/c)}var g=this.computedUp;g[0]=n[1],g[1]=n[5],g[2]=n[6],p(g,g);var v=this.computedInverse;s(v,n);var m=this.computedEye,y=v[15];m[0]=v[12]/y,m[1]=v[13]/y,m[2]=v[14]/y;for(var b=this.computedCenter,x=Math.exp(this.computedRadius[0]),u=0;3>u;++u)b[u]=m[u]-n[2+4*u]*x}},g.idle=function(t){if(!(tn;++n)e.push(e[r++]);this._time.push(t)}},g.flush=function(t){var e=a.gt(this._time,t)-2;0>e||(this._time.slice(0,e),this._components.slice(0,16*e))},g.lastT=function(){return this._time[this._time.length-1]},g.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||d,n=n||this.computedUp,this.setMatrix(t,f(this.computedMatrix,e,r,n));for(var i=0,a=0;3>a;++a)i+=Math.pow(r[a]-e[a],2);i=Math.log(Math.sqrt(i)),this.computedRadius[0]=i},g.rotate=function(t,e,r,n){this.recalcMatrix(t);var i=this.computedInverse;e&&u(i,i,e),r&&l(i,i,r),n&&c(i,i,n),this.setMatrix(t,s(this.computedMatrix,i))};var v=[0,0,0];g.pan=function(t,e,r,n){v[0]=-(e||0),v[1]=-(r||0),v[2]=-(n||0),this.recalcMatrix(t);var i=this.computedInverse;h(i,i,v),this.setMatrix(t,s(i,i))},g.translate=function(t,e,r,n){v[0]=e||0,v[1]=r||0,v[2]=n||0,this.recalcMatrix(t);var i=this.computedMatrix;h(i,i,v),this.setMatrix(t,i)},g.setMatrix=function(t,e){if(!(tr;++r)this._components.push(e[r])}},g.setDistance=function(t,e){this.computedRadius[0]=e},g.setDistanceLimits=function(t,e){var r=this._limits;r[0]=t,r[1]=e},g.getDistanceLimits=function(t){var e=this._limits;return t?(t[0]=e[0],t[1]=e[1],t):e}},{"binary-search-bounds":21,"gl-mat4/invert":240,"gl-mat4/lookAt":241,"gl-mat4/rotateX":245,"gl-mat4/rotateY":246,"gl-mat4/rotateZ":247,"gl-mat4/scale":248,"gl-mat4/translate":249,"gl-vec3/normalize":26,"mat4-interpolate":27}],21:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],22:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t}e.exports=n},{}],23:[function(t,e,r){function n(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}e.exports=n},{}],24:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}e.exports=n},{}],25:[function(t,e,r){function n(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}e.exports=n},{}],26:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a),t}e.exports=n},{}],27:[function(t,e,r){function n(t,e,r,n){if(0===c(e)||0===c(r))return!1;var i=u(e,h.translate,h.scale,h.skew,h.perspective,h.quaternion),a=u(r,p.translate,p.scale,p.skew,p.perspective,p.quaternion);return i&&a?(s(d.translate,h.translate,p.translate,n),s(d.skew,h.skew,p.skew,n),s(d.scale,h.scale,p.scale,n),s(d.perspective,h.perspective,p.perspective,n),f(d.quaternion,h.quaternion,p.quaternion,n),l(t,d.translate,d.scale,d.skew,d.perspective,d.quaternion),!0):!1}function i(){return{translate:a(),scale:a(1),skew:a(),perspective:o(),quaternion:o()}}function a(t){return[t||0,t||0,t||0]}function o(){return[0,0,0,1]}var s=t("gl-vec3/lerp"),l=t("mat4-recompose"),u=t("mat4-decompose"),c=t("gl-mat4/determinant"),f=t("quat-slerp"),h=i(),p=i(),d=i();e.exports=n},{"gl-mat4/determinant":236,"gl-vec3/lerp":25,"mat4-decompose":28,"mat4-recompose":30,"quat-slerp":31}],28:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function i(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}function a(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var o=t("./normalize"),s=t("gl-mat4/create"),l=t("gl-mat4/clone"),u=t("gl-mat4/determinant"),c=t("gl-mat4/invert"),f=t("gl-mat4/transpose"),h={length:t("gl-vec3/length"),normalize:t("gl-vec3/normalize"),dot:t("gl-vec3/dot"),cross:t("gl-vec3/cross")},p=s(),d=s(),g=[0,0,0,0],v=[[0,0,0],[0,0,0],[0,0,0]],m=[0,0,0];e.exports=function(t,e,r,s,y,b){if(e||(e=[0,0,0]),r||(r=[0,0,0]),s||(s=[0,0,0]),y||(y=[0,0,0,1]),b||(b=[0,0,0,1]),!o(p,t))return!1;if(l(d,p),d[3]=0,d[7]=0,d[11]=0,d[15]=1,Math.abs(u(d)<1e-8))return!1;var x=p[3],_=p[7],w=p[11],k=p[12],A=p[13],M=p[14],T=p[15];if(0!==x||0!==_||0!==w){g[0]=x,g[1]=_,g[2]=w,g[3]=T;var E=c(d,d);if(!E)return!1;f(d,d),n(y,g,d)}else y[0]=y[1]=y[2]=0,y[3]=1;if(e[0]=k,e[1]=A,e[2]=M,i(v,p),r[0]=h.length(v[0]),h.normalize(v[0],v[0]),s[0]=h.dot(v[0],v[1]),a(v[1],v[1],v[0],1,-s[0]),r[1]=h.length(v[1]),h.normalize(v[1],v[1]),s[0]/=r[1],s[1]=h.dot(v[0],v[2]),a(v[2],v[2],v[0],1,-s[1]),s[2]=h.dot(v[1],v[2]),a(v[2],v[2],v[1],1,-s[2]),r[2]=h.length(v[2]),h.normalize(v[2],v[2]),s[1]/=r[2],s[2]/=r[2],h.cross(m,v[1],v[2]),h.dot(v[0],m)<0)for(var L=0;3>L;L++)r[L]*=-1,v[L][0]*=-1,v[L][1]*=-1,v[L][2]*=-1;return b[0]=.5*Math.sqrt(Math.max(1+v[0][0]-v[1][1]-v[2][2],0)),b[1]=.5*Math.sqrt(Math.max(1-v[0][0]+v[1][1]-v[2][2],0)),b[2]=.5*Math.sqrt(Math.max(1-v[0][0]-v[1][1]+v[2][2],0)),b[3]=.5*Math.sqrt(Math.max(1+v[0][0]+v[1][1]+v[2][2],0)),v[2][1]>v[1][2]&&(b[0]=-b[0]),v[0][2]>v[2][0]&&(b[1]=-b[1]),v[1][0]>v[0][1]&&(b[2]=-b[2]),!0}},{"./normalize":29,"gl-mat4/clone":234,"gl-mat4/create":235,"gl-mat4/determinant":236,"gl-mat4/invert":240,"gl-mat4/transpose":250,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],29:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;16>i;i++)t[i]=e[i]*n;return!0}},{}],30:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":235,"gl-mat4/fromRotationTranslation":238,"gl-mat4/identity":239,"gl-mat4/multiply":242,"gl-mat4/scale":248,"gl-mat4/translate":249}],31:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":32}],32:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],f=e[2],h=e[3],p=r[0],d=r[1],g=r[2],v=r[3];return a=u*p+c*d+f*g+h*v,0>a&&(a=-a,p=-p,d=-d,g=-g,v=-v),1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n),t[0]=s*u+l*p,t[1]=s*c+l*d,t[2]=s*f+l*g,t[3]=s*h+l*v,t}e.exports=n},{}],33:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(f>0){var f=Math.sqrt(c+1);t[0]=.5*(o-l)/f,t[1]=.5*(s-n)/f,t[2]=.5*(r-a)/f,t[3]=.5*f}else{var h=Math.max(e,a,u),f=Math.sqrt(2*h-c+1);e>=h?(t[0]=.5*f,t[1]=.5*(i+r)/f,t[2]=.5*(s+n)/f,t[3]=.5*(o-l)/f):a>=h?(t[0]=.5*(r+i)/f,t[1]=.5*f,t[2]=.5*(l+o)/f,t[3]=.5*(s-n)/f):(t[0]=.5*(n+s)/f,t[1]=.5*(o+l)/f,t[2]=.5*f,t[3]=.5*(r-i)/f)}return t}e.exports=n},{}],34:[function(t,e,r){"use strict";function n(t,e,r){return Math.min(e,Math.max(t,r))}function i(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;nr;++r)e[r]=0;return e}function o(t,e,r){switch(arguments.length){case 0:return new i([0],[0],0);case 1:if("number"==typeof t){var n=a(t);return new i(n,n,0)}return new i(t,a(t.length),0);case 2:if("number"==typeof e){var n=a(t.length);return new i(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new i(t,e,r)}}e.exports=o;var s=t("cubic-hermite"),l=t("binary-search-bounds"),u=i.prototype;u.flush=function(t){var e=l.gt(this._time,t)-1;0>=e||(this._time.splice(0,e),this._state.splice(0,e*this.dimension),this._velocity.splice(0,e*this.dimension))},u.curve=function(t){var e=this._time,r=e.length,i=l.le(e,t),a=this._scratch[0],o=this._state,u=this._velocity,c=this.dimension,f=this.bounds;if(0>i)for(var h=c-1,p=0;c>p;++p,--h)a[p]=o[h];else if(i>=r-1)for(var h=o.length-1,d=t-e[r-1],p=0;c>p;++p,--h)a[p]=o[h]+d*u[h];else{for(var h=c*(i+1)-1,g=e[i],v=e[i+1],m=v-g||1,y=this._scratch[1],b=this._scratch[2],x=this._scratch[3],_=this._scratch[4],w=!0,p=0;c>p;++p,--h)y[p]=o[h],x[p]=u[h]*m,b[p]=o[h+c],_[p]=u[h+c]*m,w=w&&y[p]===b[p]&&x[p]===_[p]&&0===x[p];if(w)for(var p=0;c>p;++p)a[p]=y[p];else s(y,x,b,_,(t-g)/m,a)}for(var k=f[0],A=f[1],p=0;c>p;++p)a[p]=n(k[p],A[p],a[p]);return a},u.dcurve=function(t){var e=this._time,r=e.length,n=l.le(e,t),i=this._scratch[0],a=this._state,o=this._velocity,u=this.dimension;if(n>=r-1)for(var c=a.length-1,f=(t-e[r-1],0);u>f;++f,--c)i[f]=o[c];else{for(var c=u*(n+1)-1,h=e[n],p=e[n+1],d=p-h||1,g=this._scratch[1],v=this._scratch[2],m=this._scratch[3],y=this._scratch[4],b=!0,f=0;u>f;++f,--c)g[f]=a[c],m[f]=o[c]*d,v[f]=a[c+u],y[f]=o[c+u]*d,b=b&&g[f]===v[f]&&m[f]===y[f]&&0===m[f];if(b)for(var f=0;u>f;++f)i[f]=0;else{s.derivative(g,m,v,y,(t-h)/d,i);for(var f=0;u>f;++f)i[f]/=d}}return i},u.lastT=function(){var t=this._time;return t[t.length-1]},u.stable=function(){for(var t=this._velocity,e=t.length,r=this.dimension-1;r>=0;--r)if(t[--e])return!1;return!0},u.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],u=s[1];this._time.push(e,t);for(var c=0;2>c;++c)for(var f=0;r>f;++f)i.push(i[o++]),a.push(0);this._time.push(t);for(var f=r;f>0;--f)i.push(n(l[f-1],u[f-1],arguments[f])),a.push(0)}},u.push=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=t-e,l=this.bounds,u=l[0],c=l[1],f=s>1e-6?1/s:0;this._time.push(t);for(var h=r;h>0;--h){var p=n(u[h-1],c[h-1],arguments[h]);i.push(p),a.push((p-i[o++])*f)}}},u.set=function(t){var e=this.dimension;if(!(t0;--l)r.push(n(o[l-1],s[l-1],arguments[l])),i.push(0)}},u.move=function(t){var e=this.lastT(),r=this.dimension;if(!(e>=t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],u=s[1],c=t-e,f=c>1e-6?1/c:0;this._time.push(t);for(var h=r;h>0;--h){var p=arguments[h];i.push(n(l[h-1],u[h-1],i[o++]+p)),a.push(p*f)}}},u.idle=function(t){var e=this.lastT();if(!(e>t)){var r=this.dimension,i=this._state,a=this._velocity,o=i.length-r,s=this.bounds,l=s[0],u=s[1],c=t-e;this._time.push(t);for(var f=r-1;f>=0;--f)i.push(n(l[f],u[f],i[o]+c*a[o])),a.push(0),o+=1}}},{"binary-search-bounds":35,"cubic-hermite":36}],35:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],36:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n}function i(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,u=(1+2*i)*l,c=i*l,f=s*(3-2*i),h=s*o;if(t.length){a||(a=new Array(t.length));for(var p=t.length-1;p>=0;--p)a[p]=u*t[p]+c*e[p]+f*r[p]+h*n[p];return a}return u*t+c*e+f*r+h*n}e.exports=i,e.exports.derivative=n},{}],37:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function a(t,e){var r=e[0],n=e[1],a=e[2],o=e[3],s=i(r,n,a,o);s>1e-6?(t[0]=r/s,t[1]=n/s,t[2]=a/s,t[3]=o/s):(t[0]=t[1]=t[2]=0,t[3]=1)}function o(t,e,r){this.radius=l([r]),this.center=l(e),this.rotation=l(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),r=[].slice.call(r,0,4),a(r,r);var i=new o(r,e,Math.log(n));return i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up),i}e.exports=s;var l=t("filtered-vector"),u=t("gl-mat4/lookAt"),c=t("gl-mat4/fromQuat"),f=t("gl-mat4/invert"),h=t("./lib/quatFromFrame"),p=o.prototype;p.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},p.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;a(e,e);var r=this.computedMatrix;c(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;3>l;++l){for(var u=0,f=0;3>f;++f)u+=r[l+4*f]*i[f];r[12+l]=-u}},p.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r},p.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},p.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},p.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=a[1],s=a[5],l=a[9],u=n(o,s,l);o/=u,s/=u,l/=u;var c=a[0],f=a[4],h=a[8],p=c*o+f*s+h*l;c-=o*p,f-=s*p,h-=l*p;var d=n(c,f,h);c/=d,f/=d,h/=d;var g=a[2],v=a[6],m=a[10],y=g*o+v*s+m*l,b=g*c+v*f+m*h;g-=y*o+b*c,v-=y*s+b*f,m-=y*l+b*h;var x=n(g,v,m);g/=x,v/=x,m/=x;var _=c*e+o*r,w=f*e+s*r,k=h*e+l*r;this.center.move(t,_,w,k);var A=Math.exp(this.computedRadius[0]);A=Math.max(1e-4,A+i),this.radius.set(t,Math.log(A))},p.rotate=function(t,e,r,a){this.recalcMatrix(t),e=e||0,r=r||0;var o=this.computedMatrix,s=o[0],l=o[4],u=o[8],c=o[1],f=o[5],h=o[9],p=o[2],d=o[6],g=o[10],v=e*s+r*c,m=e*l+r*f,y=e*u+r*h,b=-(d*y-g*m),x=-(g*v-p*y),_=-(p*m-d*v),w=Math.sqrt(Math.max(0,1-Math.pow(b,2)-Math.pow(x,2)-Math.pow(_,2))),k=i(b,x,_,w);k>1e-6?(b/=k,x/=k,_/=k,w/=k):(b=x=_=0,w=1);var A=this.computedRotation,M=A[0],T=A[1],E=A[2],L=A[3],S=M*w+L*b+T*_-E*x,C=T*w+L*x+E*b-M*_,z=E*w+L*_+M*x-T*b,P=L*w-M*b-T*x-E*_;if(a){b=p,x=d,_=g;var R=Math.sin(a)/n(b,x,_);b*=R,x*=R,_*=R,w=Math.cos(e),S=S*w+P*b+C*_-z*x,C=C*w+P*x+z*b-S*_,z=z*w+P*_+S*x-C*b,P=P*w-S*b-C*x-z*_}var j=i(S,C,z,P);j>1e-6?(S/=j,C/=j,z/=j,P/=j):(S=C=z=0,P=1),this.rotation.set(t,S,C,z,P)},p.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;u(i,e,r,n);var o=this.computedRotation;h(o,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),a(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var s=0,l=0;3>l;++l)s+=Math.pow(r[l]-e[l],2);this.radius.set(t,.5*Math.log(Math.max(s,1e-6))),this.center.set(t,r[0],r[1],r[2])},p.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},p.setMatrix=function(t,e){var r=this.computedRotation;h(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),a(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;f(n,e);var i=n[15];if(Math.abs(i)>1e-6){var o=n[12]/i,s=n[13]/i,l=n[14]/i;this.recalcMatrix(t);var u=Math.exp(this.computedRadius[0]);this.center.set(t,o-n[2]*u,s-n[6]*u,l-n[10]*u),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},p.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},p.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},p.getDistanceLimits=function(t){ +var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},p.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},p.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":33,"filtered-vector":34,"gl-mat4/fromQuat":237,"gl-mat4/invert":240,"gl-mat4/lookAt":241}],38:[function(t,e,r){arguments[4][34][0].apply(r,arguments)},{"binary-search-bounds":39,"cubic-hermite":40,dup:34}],39:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],40:[function(t,e,r){arguments[4][36][0].apply(r,arguments)},{dup:36}],41:[function(t,e,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],42:[function(t,e,r){arguments[4][23][0].apply(r,arguments)},{dup:23}],43:[function(t,e,r){arguments[4][26][0].apply(r,arguments)},{dup:26}],44:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t){return Math.min(1,Math.max(-1,t))}function a(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;3>s;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(var s=0;3>s;++s)i[s]-=o/a*t[s];return h(i,i),i}function o(t,e,r,n,i,a,o,s){this.center=l(r),this.up=l(n),this.right=l(i),this.radius=l([a]),this.angle=l([o,s]),this.angle.bounds=[[-(1/0),-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var u=0;16>u;++u)this.computedMatrix[u]=.5;this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.up||[0,1,0],i=t.right||a(r),s=t.radius||1,l=t.theta||0,u=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),h(r,r),i=[].slice.call(i,0,3),h(i,i),"eye"in t){var c=t.eye,d=[c[0]-e[0],c[1]-e[1],c[2]-e[2]];f(i,d,r),n(i[0],i[1],i[2])<1e-6?i=a(r):h(i,i),s=n(d[0],d[1],d[2]);var g=p(r,d)/s,v=p(i,d)/s;u=Math.acos(g),l=Math.acos(v)}return s=Math.log(s),new o(t.zoomMin,t.zoomMax,e,r,i,s,l,u)}e.exports=s;var l=t("filtered-vector"),u=t("gl-mat4/invert"),c=t("gl-mat4/rotate"),f=t("gl-vec3/cross"),h=t("gl-vec3/normalize"),p=t("gl-vec3/dot"),d=o.prototype;d.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},d.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},d.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,i=0,a=0,o=0;3>o;++o)a+=e[o]*r[o],i+=e[o]*e[o];for(var s=Math.sqrt(i),l=0,o=0;3>o;++o)r[o]-=e[o]*a/i,l+=r[o]*r[o],e[o]/=s;for(var u=Math.sqrt(l),o=0;3>o;++o)r[o]/=u;var c=this.computedToward;f(c,e,r),h(c,c);for(var p=Math.exp(this.computedRadius[0]),d=this.computedAngle[0],g=this.computedAngle[1],v=Math.cos(d),m=Math.sin(d),y=Math.cos(g),b=Math.sin(g),x=this.computedCenter,_=v*y,w=m*y,k=b,A=-v*b,M=-m*b,T=y,E=this.computedEye,L=this.computedMatrix,o=0;3>o;++o){var S=_*r[o]+w*c[o]+k*e[o];L[4*o+1]=A*r[o]+M*c[o]+T*e[o],L[4*o+2]=S,L[4*o+3]=0}var C=L[1],z=L[5],P=L[9],R=L[2],j=L[6],O=L[10],I=z*O-P*j,N=P*R-C*O,F=C*j-z*R,D=n(I,N,F);I/=D,N/=D,F/=D,L[0]=I,L[4]=N,L[8]=F;for(var o=0;3>o;++o)E[o]=x[o]+L[2+4*o]*p;for(var o=0;3>o;++o){for(var l=0,B=0;3>B;++B)l+=L[o+4*B]*E[B];L[12+o]=-l}L[15]=1},d.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r};var g=[0,0,0];d.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;g[0]=i[2],g[1]=i[6],g[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;3>l;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];c(i,i,n,g);for(var l=0;3>l;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},d.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=(Math.exp(this.computedRadius[0]),a[1]),s=a[5],l=a[9],u=n(o,s,l);o/=u,s/=u,l/=u;var c=a[0],f=a[4],h=a[8],p=c*o+f*s+h*l;c-=o*p,f-=s*p,h-=l*p;var d=n(c,f,h);c/=d,f/=d,h/=d;var g=c*e+o*r,v=f*e+s*r,m=h*e+l*r;this.center.move(t,g,v,m);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+i),this.radius.set(t,Math.log(y))},d.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},d.setMatrix=function(t,e,r,a){var o=1;"number"==typeof r&&(o=0|r),(0>o||o>3)&&(o=1);var s=(o+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var l=e[o],c=e[o+4],f=e[o+8];if(a){var h=Math.abs(l),p=Math.abs(c),d=Math.abs(f),g=Math.max(h,p,d);h===g?(l=0>l?-1:1,c=f=0):d===g?(f=0>f?-1:1,l=c=0):(c=0>c?-1:1,l=f=0)}else{var v=n(l,c,f);l/=v,c/=v,f/=v}var m=e[s],y=e[s+4],b=e[s+8],x=m*l+y*c+b*f;m-=l*x,y-=c*x,b-=f*x;var _=n(m,y,b);m/=_,y/=_,b/=_;var w=c*b-f*y,k=f*m-l*b,A=l*y-c*m,M=n(w,k,A);w/=M,k/=M,A/=M,this.center.jump(t,G,H,Y),this.radius.idle(t),this.up.jump(t,l,c,f),this.right.jump(t,m,y,b);var T,E;if(2===o){var L=e[1],S=e[5],C=e[9],z=L*m+S*y+C*b,P=L*w+S*k+C*A;T=0>I?-Math.PI/2:Math.PI/2,E=Math.atan2(P,z)}else{var R=e[2],j=e[6],O=e[10],I=R*l+j*c+O*f,N=R*m+j*y+O*b,F=R*w+j*k+O*A;T=Math.asin(i(I)),E=Math.atan2(F,N)}this.angle.jump(t,E,T),this.recalcMatrix(t);var D=e[2],B=e[6],U=e[10],V=this.computedMatrix;u(V,e);var q=V[15],G=V[12]/q,H=V[13]/q,Y=V[14]/q,X=Math.exp(this.computedRadius[0]);this.center.jump(t,G-D*X,H-B*X,Y-U*X)},d.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},d.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},d.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},d.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},d.lookAt=function(t,e,r,a){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter,a=a||this.computedUp;var o=a[0],s=a[1],l=a[2],u=n(o,s,l);if(!(1e-6>u)){o/=u,s/=u,l/=u;var c=e[0]-r[0],f=e[1]-r[1],h=e[2]-r[2],p=n(c,f,h);if(!(1e-6>p)){c/=p,f/=p,h/=p;var d=this.computedRight,g=d[0],v=d[1],m=d[2],y=o*g+s*v+l*m;g-=y*o,v-=y*s,m-=y*l;var b=n(g,v,m);if(!(.01>b&&(g=s*h-l*f,v=l*c-o*h,m=o*f-s*c,b=n(g,v,m),1e-6>b))){g/=b,v/=b,m/=b,this.up.set(t,o,s,l),this.right.set(t,g,v,m),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(p));var x=s*m-l*v,_=l*g-o*m,w=o*v-s*g,k=n(x,_,w);x/=k,_/=k,w/=k;var A=o*c+s*f+l*h,M=g*c+v*f+m*h,T=x*c+_*f+w*h,E=Math.asin(i(A)),L=Math.atan2(T,M),S=this.angle._state,C=S[S.length-1],z=S[S.length-2];C%=2*Math.PI;var P=Math.abs(C+2*Math.PI-L),R=Math.abs(C-L),j=Math.abs(C-2*Math.PI-L);R>P&&(C+=2*Math.PI),R>j&&(C-=2*Math.PI),this.angle.jump(this.angle.lastT(),C,z),this.angle.set(t,L,E)}}}}},{"filtered-vector":38,"gl-mat4/invert":240,"gl-mat4/rotate":244,"gl-vec3/cross":41,"gl-vec3/dot":42,"gl-vec3/normalize":43}],45:[function(t,e,r){"use strict";function n(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}function i(t){t=t||{};var e=t.eye||[0,0,1],r=t.center||[0,0,0],i=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],u=t.mode||"turntable",c=a(),f=o(),h=s();return c.setDistanceLimits(l[0],l[1]),c.lookAt(0,e,r,i),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,i),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,i),new n({turntable:c,orbit:f,matrix:h},u)}e.exports=i;var a=t("turntable-camera-controller"),o=t("orbit-camera-controller"),s=t("matrix-camera-controller"),l=n.prototype,u=[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]];u.forEach(function(t){for(var e=t[0],r=[],n=0;ne)){var r=this._active,n=this._controllerList[e],i=Math.max(r.lastT(),n.lastT());r.recalcMatrix(i),n.setMatrix(i,r.computedMatrix),this._active=n,this._mode=t,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}}},l.getMode=function(){return this._mode}},{"matrix-camera-controller":20,"orbit-camera-controller":37,"turntable-camera-controller":44}],46:[function(t,e,r){function n(t,e){return a(i(t,e))}e.exports=n;var i=t("alpha-complex"),a=t("simplicial-complex-boundary")},{"alpha-complex":47,"simplicial-complex-boundary":58}],47:[function(t,e,r){"use strict";function n(t,e){return i(e).filter(function(r){for(var n=new Array(r.length),i=0;ii;++i)r+=t[i]*e[i];return r}function i(t){var e=t.length;if(0===e)return[];var r=(t[0].length,o([t.length+1,t.length+1],1)),i=o([t.length+1],1);r[e][e]=0;for(var a=0;e>a;++a){for(var l=0;a>=l;++l)r[l][a]=r[a][l]=2*n(t[a],t[l]);i[a]=n(t[a],t[a])}for(var u=s(r,i),c=0,f=u[e+1],a=0;aa;++a){for(var f=u[a],p=0,l=0;ls;++s)r[s]+=t[a][s]*n[a];return r}var o=t("dup"),s=t("robust-linear-solve");a.barycenetric=i,e.exports=a},{dup:50,"robust-linear-solve":51}],50:[function(t,e,r){"use strict";function n(t,e,r){var i=0|t[r];if(0>=i)return[];var a,o=new Array(i);if(r===t.length-1)for(a=0;i>a;++a)o[a]=e;else for(a=0;i>a;++a)o[a]=n(t,e,r+1);return o}function i(t,e){var r,n;for(r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e){switch("undefined"==typeof e&&(e=0),typeof t){case"number":if(t>0)return i(0|t,e);break;case"object":if("number"==typeof t.length)return n(t,e,0)}return[]}e.exports=a},{}],51:[function(t,e,r){"use strict";function n(t){for(var e="robustLinearSolve"+t+"d",r=["function ",e,"(A,b){return ["],n=0;t>n;++n){r.push("det([");for(var i=0;t>i;++i){i>0&&r.push(","),r.push("[");for(var a=0;t>a;++a)a>0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(6>t?s[t]:s)}function i(){return[0]}function a(t,e){return[[e[0]],[t[0][0]]]}function o(){for(;u.lengthi;++i)t.push("s"+i),r.push("case ",i,":return s",i,"(A,b);");r.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve"),t.push("CACHE","g",r.join(""));var a=Function.apply(void 0,t);e.exports=a.apply(void 0,u.concat([u,n]));for(var i=0;l>i;++i)e.exports[i]=u[i]}var s=t("robust-determinant"),l=6,u=[i,a];o()},{"robust-determinant":57}],52:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=t[t.length-1],n=e,i=e-2;i>=0;--i){var a=r,o=t[i];r=a+o;var s=r-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;e>i;++i){var a=t[i],o=r;r=a+o;var s=r-a,l=o-s;l&&(t[u++]=l)}return t[u++]=r,t.length=u,t}e.exports=n},{}],53:[function(t,e,r){"use strict";function n(t,e,r){var n=t+e,i=n-t,a=n-i,o=e-i,s=t-a;return r?(r[0]=s+o,r[1]=n,r):[s+o,n]}e.exports=n},{}],54:[function(t,e,r){"use strict";function n(t,e){var r=t.length;if(1===r){var n=i(t[0],e);return n[0]?n:[n[1]]}var o=new Array(2*r),s=[.1,.1],l=[.1,.1],u=0;i(t[0],e,s),s[0]&&(o[u++]=s[0]);for(var c=1;r>c;++c){i(t[c],e,l);var f=s[1];a(f,l[0],s),s[0]&&(o[u++]=s[0]);var h=l[1],p=s[1],d=h+p,g=d-h,v=p-g;s[1]=d,v&&(o[u++]=v)}return s[1]&&(o[u++]=s[1]),0===u&&(o[u++]=0),o.length=u,o}var i=t("two-product"),a=t("two-sum");e.exports=n},{"two-product":56,"two-sum":53}],55:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],e[0]);var a,o,s=r+i,l=new Array(s),u=0,c=0,f=0,h=Math.abs,p=t[c],d=h(p),g=e[f],v=h(g);v>d?(o=p,c+=1,r>c&&(p=t[c],d=h(p))):(o=g,f+=1,i>f&&(g=e[f],v=h(g))),r>c&&v>d||f>=i?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>c&&i>f;)v>d?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>c;)a=p,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,c+=1,r>c&&(p=t[c]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=e[f]);return M&&(l[u++]=M),T&&(l[u++]=T),u||(l[u++]=0),l.length=u,l}e.exports=i},{}],56:[function(t,e,r){"use strict";function n(t,e,r){var n=t*e,a=i*t,o=a-t,s=a-o,l=t-s,u=i*e,c=u-e,f=u-c,h=e-f,p=n-s*f,d=p-l*f,g=d-s*h,v=l*h-g;return r?(r[0]=v,r[1]=n,r):[v,n]}e.exports=n;var i=+(Math.pow(2,27)+1)},{}],57:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m[",r,"][",n,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("");for(var e=[],r=0;rn;++n)t.push("det"+n),r.push("case ",n,":return det",n,"(m);");r.push("}var det=CACHE[m.length];if(!det)det=CACHE[m.length]=gen(m.length);return det(m);}return robustDeterminant"),t.push("CACHE","gen",r.join(""));var i=Function.apply(void 0,t);e.exports=i.apply(void 0,g.concat([g,l]));for(var n=0;ne;++e)a+=t[e].length;var o=new Array(a),s=0;for(e=0;i>e;++e){var l=t[e],u=l.length;for(r=0;u>r;++r){var c=o[s++]=new Array(u-1),f=0;for(n=0;u>n;++n)n!==r&&(c[f++]=l[n]);if(1&r){var h=c[1];c[1]=c[0],c[0]=h}}}return o}e.exports=n},{}],60:[function(t,e,r){"use strict";function n(t){for(var e=1,r=1;rn;++n)if(t[r]x;++x)if(i=y[x]-b[x])return i;return 0}}e.exports=i;var a=Math.min},{}],62:[function(t,e,r){"use strict";function n(t,e){return i(t,e)||a(t)-a(e)}var i=t("compare-cell"),a=t("cell-orientation");e.exports=n},{"cell-orientation":60,"compare-cell":61}],63:[function(t,e,r){"use strict";function n(t){t.sort(a);for(var e=t.length,r=0,n=0;e>n;++n){var s=t[n],l=o(s);if(0!==l){if(r>0){var u=t[r-1];if(0===i(s,u)&&o(u)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}var i=t("compare-cell"),a=t("compare-oriented-cell"),o=t("cell-orientation");e.exports=n},{"cell-orientation":60,"compare-cell":61,"compare-oriented-cell":62}],64:[function(t,e,r){"use strict";var n=function(){function t(t){return!Array.isArray(t)&&null!==t&&"object"==typeof t}function e(t,e,r){for(var n=(e-t)/Math.max(r-1,1),i=[],a=0;r>a;a++)i.push(t+a*n);return i}function r(){for(var t=[].slice.call(arguments),e=t.map(function(t){return t.length}),r=Math.min.apply(null,e),n=[],i=0;r>i;i++){n[i]=[];for(var a=0;aa;a++)i.push([t[a],e[a],r[a]]);return i}function i(t){function e(t){for(var n=0;n>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3])),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}function u(t,e){var r,n;if("string"!=typeof t)return t;if(r=[],"#"===t[0]?(t=t.substr(1),3===t.length&&(t+=t),n=parseInt(t,16),r[0]=n>>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3]),n[4]?r[3]=parseFloat(n[4]):r[3]=1),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}var c={},f=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/,h=/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/;return c.isPlainObject=t,c.linspace=e,c.zip3=n,c.sum=i,c.zip=r,c.isEqual=s,c.copy2D=a,c.copy1D=o,c.str2RgbArray=l,c.str2RgbaArray=u,c};e.exports=n()},{}],65:[function(t,e,r){(function(e){"use strict";function n(){try{var t=new Uint8Array(1);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(e){return!1}}function i(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(i()=e?a(t,e):void 0!==r?"string"==typeof n?a(t,e).fill(r,n):a(t,e).fill(r):a(t,e)}function c(t,e){if(l(e),t=a(t,0>e?0:0|g(e)),!o.TYPED_ARRAY_SUPPORT)for(var r=0;e>r;r++)t[r]=0;return t}function f(t,e,r){if("string"==typeof r&&""!==r||(r="utf8"),!o.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|m(e,r);return t=a(t,n),t.write(e,r),t}function h(t,e){var r=0|g(e.length);t=a(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function p(t,e,r,n){if(e.byteLength,0>r||e.byteLength=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function v(t){return+t!=t&&(t=0),o.alloc(+t)}function m(t,e){if(o.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"binary":case"raw":case"raws":return r;case"utf8":case"utf-8":case void 0:return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return X(t).length;default:if(n)return G(t).length;e=(""+e).toLowerCase(),n=!0}}function y(t,e,r){var n=!1;if((void 0===e||0>e)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),0>=r)return"";if(r>>>=0,e>>>=0,e>=r)return"";for(t||(t="utf8");;)switch(t){case"hex":return P(this,e,r);case"utf8":case"utf-8":return L(this,e,r);case"ascii":return C(this,e,r);case"binary":return z(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function b(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function x(t,e,r,n){function i(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}var a=1,o=t.length,s=e.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;a=2,o/=2,s/=2,r/=2}for(var l=-1,u=0;o>r+u;u++)if(i(t,r+u)===i(e,-1===l?0:u-l)){if(-1===l&&(l=u),u-l+1===s)return(r+l)*a}else-1!==l&&(u-=u-l),l=-1;return-1}function _(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var a=e.length;if(a%2!==0)throw new Error("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;n>o;o++){var s=parseInt(e.substr(2*o,2),16);if(isNaN(s))return o;t[r+o]=s}return o}function w(t,e,r,n){return W(G(e,t.length-r),t,r,n)}function k(t,e,r,n){return W(H(e),t,r,n)}function A(t,e,r,n){return k(t,e,r,n)}function M(t,e,r,n){return W(X(e),t,r,n)}function T(t,e,r,n){return W(Y(e,t.length-r),t,r,n)}function E(t,e,r){return 0===e&&r===t.length?K.fromByteArray(t):K.fromByteArray(t.slice(e,r))}function L(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;r>i;){var a=t[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(r>=i+s){var l,u,c,f;switch(s){case 1:128>a&&(o=a);break;case 2:l=t[i+1],128===(192&l)&&(f=(31&a)<<6|63&l,f>127&&(o=f));break;case 3:l=t[i+1],u=t[i+2],128===(192&l)&&128===(192&u)&&(f=(15&a)<<12|(63&l)<<6|63&u,f>2047&&(55296>f||f>57343)&&(o=f));break;case 4:l=t[i+1],u=t[i+2],c=t[i+3],128===(192&l)&&128===(192&u)&&128===(192&c)&&(f=(15&a)<<18|(63&l)<<12|(63&u)<<6|63&c,f>65535&&1114112>f&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return S(n)}function S(t){var e=t.length;if(J>=e)return String.fromCharCode.apply(String,t);for(var r="",n=0;e>n;)r+=String.fromCharCode.apply(String,t.slice(n,n+=J));return r}function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(127&t[i]);return n}function z(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function P(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",a=e;r>a;a++)i+=q(t[a]);return i}function R(t,e,r){for(var n=t.slice(e,r),i="",a=0;at)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,a){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||a>e)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function I(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,a=Math.min(t.length-r,2);a>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function N(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,a=Math.min(t.length-r,4);a>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function F(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("Index out of range")}function D(t,e,r,n,i){return i||F(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),$.write(t,e,r,n,23,4),r+4}function B(t,e,r,n,i){return i||F(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),$.write(t,e,r,n,52,8),r+8}function U(t){if(t=V(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function V(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function q(t){return 16>t?"0"+t.toString(16):t.toString(16)}function G(t,e){e=e||1/0;for(var r,n=t.length,i=null,a=[],o=0;n>o;o++){if(r=t.charCodeAt(o),r>55295&&57344>r){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(56320>r){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,128>r){if((e-=1)<0)break;a.push(r)}else if(2048>r){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(65536>r){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(1114112>r))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(t){for(var e=[],r=0;r>8,i=r%256,a.push(i),a.push(n);return a}function X(t){return K.toByteArray(U(t))}function W(t,e,r,n){for(var i=0;n>i&&!(i+r>=e.length||i>=t.length);i++)e[i+r]=t[i];return i}function Z(t){return t!==t}var K=t("base64-js"),$=t("ieee754"),Q=t("isarray");r.Buffer=o,r.SlowBuffer=v,r.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),r.kMaxLength=i(),o.poolSize=8192,o._augment=function(t){return t.__proto__=o.prototype,t},o.from=function(t,e,r){return s(null,t,e,r)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(t,e,r){return u(null,t,e,r)},o.allocUnsafe=function(t){return c(null,t)},o.allocUnsafeSlow=function(t){return c(null,t)},o.isBuffer=function(t){return!(null==t||!t._isBuffer)},o.compare=function(t,e){if(!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);a>i;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return n>r?-1:r>n?1:0},o.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(t,e){if(!Q(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);var r;if(void 0===e)for(e=0,r=0;re;e+=2)b(this,e,e+1);return this},o.prototype.swap32=function(){var t=this.length;if(t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;t>e;e+=4)b(this,e,e+3),b(this,e+1,e+2);return this},o.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?L(this,0,t):y.apply(this,arguments)},o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:0===o.compare(this,t)},o.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},o.prototype.compare=function(t,e,r,n,i){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),0>e||r>t.length||0>n||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,s=r-e,l=Math.min(a,s),u=this.slice(n,i),c=t.slice(e,r),f=0;l>f;++f)if(u[f]!==c[f]){a=u[f],s=c[f];break}return s>a?-1:a>s?1:0},o.prototype.indexOf=function(t,e,r){if("string"==typeof e?(r=e,e=0):e>2147483647?e=2147483647:-2147483648>e&&(e=-2147483648),e>>=0,0===this.length)return-1;if(e>=this.length)return-1;if(0>e&&(e=Math.max(this.length+e,0)),"string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:x(this,t,e,r);if("number"==typeof t)return o.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,e):x(this,[t],e,r);throw new TypeError("val must be string, number or Buffer")},o.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},o.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e=0|e,isFinite(r)?(r=0|r,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(0>r||0>e)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds"); +n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":return k(this,t,e,r);case"binary":return A(this,t,e,r);case"base64":return M(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var J=4096;o.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t);var n;if(o.TYPED_ARRAY_SUPPORT)n=this.subarray(t,e),n.__proto__=o.prototype;else{var i=e-t;n=new o(i,void 0);for(var a=0;i>a;a++)n[a]=this[a+t]}return n},o.prototype.readUIntLE=function(t,e,r){t=0|t,e=0|e,r||j(t,e,this.length);for(var n=this[t],i=1,a=0;++a0&&(i*=256);)n+=this[t+--e]*i;return n},o.prototype.readUInt8=function(t,e){return e||j(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,e){return e||j(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,e){return e||j(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,e){return e||j(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,e){return e||j(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,e,r){t=0|t,e=0|e,r||j(t,e,this.length);for(var n=this[t],i=1,a=0;++a=i&&(n-=Math.pow(2,8*e)),n},o.prototype.readIntBE=function(t,e,r){t=0|t,e=0|e,r||j(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*e)),a},o.prototype.readInt8=function(t,e){return e||j(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){e||j(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(t,e){e||j(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(t,e){return e||j(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return e||j(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,e){return e||j(t,4,this.length),$.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return e||j(t,4,this.length),$.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return e||j(t,8,this.length),$.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return e||j(t,8,this.length),$.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e=0|e,r=0|r,!n){var i=Math.pow(2,8*r)-1;O(this,t,e,r,i,0)}var a=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+a]=t/o&255;return e+r},o.prototype.writeUInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,255,0),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},o.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},o.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},o.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):N(this,t,e,!0),e+4},o.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},o.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++at&&0===s&&0!==this[e+a-1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},o.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)0>t&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},o.prototype.writeInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,127,-128),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},o.prototype.writeInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},o.prototype.writeInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):N(this,t,e,!0),e+4},o.prototype.writeInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},o.prototype.writeFloatLE=function(t,e,r){return D(this,t,e,!0,r)},o.prototype.writeFloatBE=function(t,e,r){return D(this,t,e,!1,r)},o.prototype.writeDoubleLE=function(t,e,r){return B(this,t,e,!0,r)},o.prototype.writeDoubleBE=function(t,e,r){return B(this,t,e,!1,r)},o.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(0>e)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-er&&n>e)for(i=a-1;i>=0;i--)t[i+e]=this[i+r];else if(1e3>a||!o.TYPED_ARRAY_SUPPORT)for(i=0;a>i;i++)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+a),e);return a},o.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===t.length){var i=t.charCodeAt(0);256>i&&(t=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t=255&t);if(0>e||this.length=r)return this;e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0);var a;if("number"==typeof t)for(a=e;r>a;a++)this[a]=t;else{var s=o.isBuffer(t)?t:G(new o(t,n).toString()),l=s.length;for(a=0;r-e>a;a++)this[a+e]=s[a%l]}return this};var tt=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":66,ieee754:67,isarray:68}],66:[function(t,e,r){"use strict";function n(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;r>e;++e)l[e]=t[e],u[t.charCodeAt(e)]=e;u["-".charCodeAt(0)]=62,u["_".charCodeAt(0)]=63}function i(t){var e,r,n,i,a,o,s=t.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===t[s-2]?2:"="===t[s-1]?1:0,o=new c(3*s/4-a),n=a>0?s-4:s;var l=0;for(e=0,r=0;n>e;e+=4,r+=3)i=u[t.charCodeAt(e)]<<18|u[t.charCodeAt(e+1)]<<12|u[t.charCodeAt(e+2)]<<6|u[t.charCodeAt(e+3)],o[l++]=i>>16&255,o[l++]=i>>8&255,o[l++]=255&i;return 2===a?(i=u[t.charCodeAt(e)]<<2|u[t.charCodeAt(e+1)]>>4,o[l++]=255&i):1===a&&(i=u[t.charCodeAt(e)]<<10|u[t.charCodeAt(e+1)]<<4|u[t.charCodeAt(e+2)]>>2,o[l++]=i>>8&255,o[l++]=255&i),o}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function o(t,e,r){for(var n,i=[],o=e;r>o;o+=3)n=(t[o]<<16)+(t[o+1]<<8)+t[o+2],i.push(a(n));return i.join("")}function s(t){for(var e,r=t.length,n=r%3,i="",a=[],s=16383,u=0,c=r-n;c>u;u+=s)a.push(o(t,u,u+s>c?c:u+s));return 1===n?(e=t[r-1],i+=l[e>>2],i+=l[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=l[e>>10],i+=l[e>>4&63],i+=l[e<<2&63],i+="="),a.push(i),a.join("")}r.toByteArray=i,r.fromByteArray=s;var l=[],u=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],67:[function(t,e,r){r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,c=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+t[e+f],f+=h,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=h,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:(p?-1:1)*(1/0);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),e+=o+f>=1?h/l:h*Math.pow(2,1-f),e*l>=2&&(o++,l/=2),o+f>=c?(s=0,o=c):o+f>=1?(s=(e*l-1)*Math.pow(2,i),o+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}},{}],68:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],69:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!a(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,a,l,u;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(o(r))for(a=Array.prototype.slice.call(arguments,1),u=r.slice(),n=u.length,l=0;n>l;l++)u[l].apply(this,a);return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(r=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],70:[function(t,e,r){function n(){h&&c&&(h=!1,c.length?f=c.concat(f):p=-1,f.length&&i())}function i(){if(!h){var t=s(n);h=!0;for(var e=f.length;e;){for(c=f,f=[];++p1)for(var r=1;rt[r][0]&&(r=n);return r>e?[[e],[r]]:e>r?[[r],[e]]:[[e]]}e.exports=n},{}],73:[function(t,e,r){"use strict";function n(t){var e=i(t),r=e.length;if(2>=r)return[];for(var n=new Array(r),a=e[r-1],o=0;r>o;++o){var s=e[o];n[o]=[a,s],a=s}return n}e.exports=n;var i=t("monotone-convex-hull-2d")},{"monotone-convex-hull-2d":80}],74:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),i=0;ii;++i)e.indexOf(i)<0&&(n[a++]=t[i]);return n}function i(t,e){for(var r=t.length,n=e.length,i=0;r>i;++i)for(var a=t[i],o=0;os)a[o]=e[s];else{s-=n;for(var l=0;n>l;++l)s>=e[l]&&(s+=1);a[o]=s}}return t}function a(t,e){try{return o(t,!0)}catch(r){var a=s(t);if(a.length<=e)return[];var l=n(t,a),u=o(l,!0);return i(u,a)}}e.exports=a;var o=t("incremental-convex-hull"),s=t("affine-hull")},{"affine-hull":75,"incremental-convex-hull":76}],75:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(e+1),n=0;n=i;++i){for(var o=new Array(e),s=0;e>s;++s)o[s]=Math.pow(i+1-n,s);r[i]=o}var l=a.apply(void 0,r);if(l)return!0}return!1}function i(t){var e=t.length;if(0===e)return[];if(1===e)return[0];for(var r=t[0].length,i=[t[0]],a=[0],o=1;e>o;++o)if(i.push(t[o]),n(i,r)){if(a.push(o),a.length===r+1)return a}else i.pop();return a}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":1040}],76:[function(t,e,r){"use strict";function n(t,e,r){this.vertices=t,this.adjacent=e,this.boundary=r,this.lastVisited=-1}function i(t,e,r){this.vertices=t,this.cell=e,this.index=r}function a(t,e){return c(t.vertices,e.vertices)}function o(t){for(var e=["function orient(){var tuple=this.tuple;return test("],r=0;t>=r;++r)r>0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=u[t+1];return i||(i=u),n(i)}function s(t,e,r){this.dimension=t,this.vertices=e,this.simplices=r,this.interior=r.filter(function(t){return!t.boundary}),this.tuple=new Array(t+1);for(var n=0;t>=n;++n)this.tuple[n]=this.vertices[n];var i=f[t];i||(i=f[t]=o(t)),this.orient=i}function l(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(i>=r)throw new Error("Must input at least d+1 points");var a=t.slice(0,i+1),o=u.apply(void 0,a);if(0===o)throw new Error("Input not in general position");for(var l=new Array(i+1),c=0;i>=c;++c)l[c]=c;0>o&&(l[0]=1,l[1]=0);for(var f=new n(l,new Array(i+1),!1),h=f.adjacent,p=new Array(i+2),c=0;i>=c;++c){for(var d=l.slice(),g=0;i>=g;++g)g===c&&(d[g]=-1);var v=d[0];d[0]=d[1],d[1]=v;var m=new n(d,new Array(i+1),!0);h[c]=m,p[c]=m}p[i+1]=f;for(var c=0;i>=c;++c)for(var d=h[c].vertices,y=h[c].adjacent,g=0;i>=g;++g){var b=d[g];if(0>b)y[g]=f;else for(var x=0;i>=x;++x)h[x].vertices.indexOf(b)<0&&(y[g]=h[x])}for(var _=new s(i,a,p),w=!!e,c=i+1;r>c;++c)_.insert(t[c],w);return _.boundary()}e.exports=l;var u=t("robust-orientation"),c=t("simplicial-complex").compareCells;n.prototype.flip=function(){var t=this.vertices[0];this.vertices[0]=this.vertices[1],this.vertices[1]=t;var e=this.adjacent[0];this.adjacent[0]=this.adjacent[1],this.adjacent[1]=e};var f=[],h=s.prototype;h.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){t=o.pop();for(var s=(t.vertices,t.adjacent),l=0;r>=l;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,f=0;r>=f;++f){var h=c[f];0>h?i[f]=e:i[f]=a[h]}var p=this.orient();if(p>0)return u;u.lastVisited=-n,0===p&&o.push(u)}}}return null},h.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;n>=c;++c)a[c]=i[l[c]];s.lastVisited=r;for(var c=0;n>=c;++c){var f=u[c];if(!(f.lastVisited>=r)){var h=a[c];a[c]=t;var p=this.orient();if(a[c]=h,0>p){s=f;continue t}f.boundary?f.lastVisited=-r:f.lastVisited=r}}return}return s},h.addPeaks=function(t,e){var r=this.vertices.length-1,o=this.dimension,s=this.vertices,l=this.tuple,u=this.interior,c=this.simplices,f=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,u.push(e);for(var h=[];f.length>0;){var e=f.pop(),p=e.vertices,d=e.adjacent,g=p.indexOf(r);if(!(0>g))for(var v=0;o>=v;++v)if(v!==g){var m=d[v];if(m.boundary&&!(m.lastVisited>=r)){var y=m.vertices;if(m.lastVisited!==-r){for(var b=0,x=0;o>=x;++x)y[x]<0?(b=x,l[x]=t):l[x]=s[y[x]];var _=this.orient();if(_>0){y[b]=r,m.boundary=!1,u.push(m),f.push(m),m.lastVisited=r;continue}m.lastVisited=-r}var w=m.adjacent,k=p.slice(),A=d.slice(),M=new n(k,A,!0);c.push(M);var T=w.indexOf(e);if(!(0>T)){w[T]=M,A[g]=m,k[v]=-1,A[v]=e,d[v]=M,M.flip();for(var x=0;o>=x;++x){var E=k[x];if(!(0>E||E===r)){for(var L=new Array(o-1),S=0,C=0;o>=C;++C){var z=k[C];0>z||C===x||(L[S++]=z)}h.push(new i(L,M,x))}}}}}}h.sort(a);for(var v=0;v+1j||0>O||(P.cell.adjacent[P.index]=R.cell,R.cell.adjacent[R.index]=P.cell)}},h.insert=function(t,e){var r=this.vertices;r.push(t);var n=this.walk(t,e);if(n){for(var i=this.dimension,a=this.tuple,o=0;i>=o;++o){var s=n.vertices[o];0>s?a[o]=t:a[o]=r[s]}var l=this.orient(a);0>l||(0!==l||(n=this.handleBoundaryDegeneracy(n,t)))&&this.addPeaks(t,n)}},h.boundary=function(){for(var t=this.dimension,e=[],r=this.simplices,n=r.length,i=0;n>i;++i){var a=r[i];if(a.boundary){for(var o=new Array(t),s=a.vertices,l=0,u=0,c=0;t>=c;++c)s[c]>=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var f=o[0];o[0]=o[1],o[1]=f}e.push(o)}}return e}},{"robust-orientation":1040,"simplicial-complex":79}],77:[function(t,e,r){"use strict";"use restrict";function n(t){var e=32;return t&=-t,t&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}var i=32;r.INT_BITS=i,r.INT_MAX=2147483647,r.INT_MIN=-1<0)-(0>t)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(e>t)},r.max=function(t,e){return t^(t^e)&-(e>t)},r.isPow2=function(t){return!(t&t-1||!t)},r.log2=function(t){var e,r;return e=(t>65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var a=new Array(256);!function(t){for(var e=0;256>e;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|a[t>>>16&255]<<8|a[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],78:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n;var i=n.prototype;Object.defineProperty(i,"length",{get:function(){return this.roots.length}}),i.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},i.find=function(t){for(var e=t,r=this.roots;r[t]!==t;)t=r[t];for(;r[e]!==t;){var n=r[e];r[e]=t,e=n}return t},i.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],79:[function(t,e,r){"use strict";"use restrict";function n(t){for(var e=0,r=Math.max,n=0,i=t.length;i>n;++n)e=r(e,t[n].length);return e-1}function i(t){for(var e=-1,r=Math.max,n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)e=r(e,a[o]);return e+1}function a(t){for(var e=new Array(t.length),r=0,n=t.length;n>r;++r)e[r]=t[r].slice(0);return e}function o(t,e){var r=t.length,n=t.length-e.length,i=Math.min;if(n)return n;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:var a=t[0]+t[1]-e[0]-e[1];return a?a:i(t[0],t[1])-i(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=i(t[0],t[1]),u=i(e[0],e[1]),a=i(l,t[2])-i(u,e[2]);return a?a:i(l+t[2],o)-i(u+e[2],s);default:var c=t.slice(0);c.sort();var f=e.slice(0);f.sort();for(var h=0;r>h;++h)if(n=c[h]-f[h])return n;return 0}}function s(t,e){return o(t[0],e[0])}function l(t,e){if(e){for(var r=t.length,n=new Array(r),i=0;r>i;++i)n[i]=[t[i],e[i]];n.sort(s);for(var i=0;r>i;++i)t[i]=n[i][0],e[i]=n[i][1];return t}return t.sort(o),t}function u(t){if(0===t.length)return[];for(var e=1,r=t.length,n=1;r>n;++n){var i=t[n];if(o(i,t[n-1])){if(n===e){e++;continue}t[e++]=i}}return t.length=e,t}function c(t,e){for(var r=0,n=t.length-1,i=-1;n>=r;){var a=r+n>>1,s=o(t[a],e);0>=s?(0===s&&(i=a),r=a+1):s>0&&(n=a-1)}return i}function f(t,e){for(var r=new Array(t.length),n=0,i=r.length;i>n;++n)r[n]=[];for(var a=[],n=0,s=e.length;s>n;++n)for(var l=e[n],u=l.length,f=1,h=1<f;++f){a.length=b.popCount(f);for(var p=0,d=0;u>d;++d)f&1<g))for(;;)if(r[g++].push(n),g>=t.length||0!==o(t[g],a))break}return r}function h(t,e){if(!e)return f(u(d(t,0)),t,0);for(var r=new Array(e),n=0;e>n;++n)r[n]=[];for(var n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)r[a[o]].push(n);return r}function p(t){for(var e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0|i.length,o=1,s=1<o;++o){for(var u=[],c=0;a>c;++c)o>>>c&1&&u.push(i[c]);e.push(u)}return l(e)}function d(t,e){if(0>e)return[];for(var r=[],n=(1<r;++r)for(var i=t[r],a=0,o=i.length;o>a;++a){for(var s=new Array(i.length-1),u=0,c=0;o>u;++u)u!==a&&(s[c++]=i[u]);e.push(s)}return l(e)}function v(t,e){for(var r=new x(e),n=0;ne){for(var r=new Array(e),n=0;e>n;++n)r[n]=n;return 2===e&&t[0][0]===t[1][0]&&t[0][1]===t[1][1]?[0]:r}for(var a=new Array(e),n=0;e>n;++n)a[n]=n;a.sort(function(e,r){var n=t[e][0]-t[r][0];return n?n:t[e][1]-t[r][1]});for(var o=[a[0],a[1]],s=[a[0],a[1]],n=2;e>n;++n){for(var l=a[n],u=t[l],c=o.length;c>1&&i(t[o[c-2]],t[o[c-1]],u)<=0;)c-=1,o.pop();for(o.push(l),c=s.length;c>1&&i(t[s[c-2]],t[s[c-1]],u)>=0;)c-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),f=0,n=0,h=o.length;h>n;++n)r[f++]=o[n];for(var p=s.length-2;p>0;--p)r[f++]=s[p];return r}e.exports=n;var i=t("robust-orientation")[3]},{"robust-orientation":1040}],81:[function(t,e,r){e.exports={AFG:"afghan",ALA:"\\b\\wland",ALB:"albania",DZA:"algeria",ASM:"^(?=.*americ).*samoa",AND:"andorra",AGO:"angola",AIA:"anguill?a",ATA:"antarctica",ATG:"antigua",ARG:"argentin",ARM:"armenia",ABW:"^(?!.*bonaire).*\\baruba",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baustri.*\\bemp",AZE:"azerbaijan",BHS:"bahamas",BHR:"bahrain",BGD:"bangladesh|^(?=.*east).*paki?stan",BRB:"barbados",BLR:"belarus|byelo",BEL:"^(?!.*luxem).*belgium",BLZ:"belize|^(?=.*british).*honduras",BEN:"benin|dahome",BMU:"bermuda",BTN:"bhutan",BOL:"bolivia",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",BIH:"herzegovina|bosnia",BWA:"botswana|bechuana",BVT:"bouvet",BRA:"brazil",IOT:"british.?indian.?ocean",BRN:"brunei",BGR:"bulgaria",BFA:"burkina|\\bfaso|upper.?volta",BDI:"burundi",KHM:"cambodia|kampuchea|khmer",CMR:"cameroon",CAN:"canada",CPV:"verde",CYM:"cayman",CAF:"\\bcentral.african.republic",TCD:"\\bchad",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china",CXR:"christmas",CCK:"\\bcocos|keeling",COL:"colombia",COM:"comoro",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",COG:"^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",COK:"\\bcook",CRI:"costa.?rica",CIV:"ivoire|ivory",HRV:"croatia",CUB:"\\bcuba",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",CYP:"cyprus",CZE:"^(?=.*rep).*czech|czechia|bohemia",CSK:"czechoslovakia",DNK:"denmark",DJI:"djibouti",DMA:"dominica(?!n)",DOM:"dominican.rep",ECU:"ecuador",EGY:"egypt",SLV:"el.?salvador",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",ERI:"eritrea",EST:"estonia",ETH:"ethiopia|abyssinia",FLK:"falkland|malvinas",FRO:"faroe|faeroe",FJI:"fiji",FIN:"finland",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",GUF:"^(?=.*french).*guiana",PYF:"french.?polynesia|tahiti",ATF:"french.?southern",GAB:"gabon",GMB:"gambia",GEO:"^(?!.*south).*georgia",DDR:"german.?democratic.?republic|democratic.?republic.*germany|east.germany",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GHA:"ghana|gold.?coast",GIB:"gibraltar",GRC:"greece|hellenic|hellas",GRL:"greenland",GRD:"grenada",GLP:"guadeloupe",GUM:"\\bguam",GTM:"guatemala",GGY:"guernsey",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",GNB:"bissau|^(?=.*portu).*guinea",GUY:"guyana|british.?guiana",HTI:"haiti",HMD:"heard.*mcdonald",VAT:"holy.?see|vatican|papal.?st",HND:"^(?!.*brit).*honduras",HKG:"hong.?kong",HUN:"^(?!.*austr).*hungary",ISL:"iceland",IND:"india(?!.*ocea)",IDN:"indonesia",IRN:"\\biran|persia",IRQ:"\\biraq|mesopotamia",IRL:"ireland",IMN:"^(?=.*isle).*\\bman",ISR:"israel",ITA:"italy",JAM:"jamaica",JPN:"japan",JEY:"jersey",JOR:"jordan",KAZ:"kazak",KEN:"kenya|british.?east.?africa|east.?africa.?prot",KIR:"kiribati",PRK:"^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk",KOR:"^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea",KWT:"kuwait",KGZ:"kyrgyz|kirghiz",LAO:"\\blaos?\\b",LVA:"latvia",LBN:"lebanon",LSO:"lesotho|basuto",LBR:"liberia",LBY:"libya",LIE:"liechtenstein",LTU:"lithuania",LUX:"^(?!.*belg).*luxem",MAC:"maca(o|u)",MKD:"macedonia|fyrom",MDG:"madagascar|malagasy",MWI:"malawi|nyasa",MYS:"malaysia",MDV:"maldive",MLI:"\\bmali\\b",MLT:"\\bmalta",MHL:"marshall",MTQ:"martinique",MRT:"mauritania",MUS:"mauritius",MYT:"\\bmayotte",MEX:"\\bmexic",FSM:"micronesia",MDA:"moldov|b(a|e)ssarabia",MCO:"monaco",MNG:"mongolia",MNE:"^(?!.*serbia).*montenegro",MSR:"montserrat",MAR:"morocco|\\bmaroc",MOZ:"mozambique",MMR:"myanmar|burma",NAM:"namibia",NRU:"nauru",NPL:"nepal",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",ANT:"^(?=.*\\bant).*(nether|dutch)",NCL:"new.?caledonia",NZL:"new.?zealand",NIC:"nicaragua",NER:"\\bniger(?!ia)",NGA:"nigeria",NIU:"niue",NFK:"norfolk",MNP:"mariana",NOR:"norway",OMN:"\\boman|trucial",PAK:"^(?!.*east).*paki?stan",PLW:"palau",PSE:"palestin|\\bgaza|west.?bank",PAN:"panama",PNG:"papua|new.?guinea",PRY:"paraguay",PER:"peru",PHL:"philippines",PCN:"pitcairn",POL:"poland",PRT:"portugal",PRI:"puerto.?rico",QAT:"qatar",REU:"r(e|\xe9)union",ROU:"r(o|u|ou)mania",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",RWA:"rwanda",BLM:"barth(e|\xe9)lemy",SHN:"helena",KNA:"kitts|\\bnevis",LCA:"\\blucia",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",SPM:"miquelon",VCT:"vincent",WSM:"^(?!.*amer).*samoa",SMR:"san.?marino",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SAU:"\\bsa\\w*.?arabia",SEN:"senegal",SRB:"^(?!.*monte).*serbia",SYC:"seychell",SLE:"sierra", +SGP:"singapore",SXM:"^(?!.*martin)(?!.*saba).*maarten",SVK:"^(?!.*cze).*slovak",SVN:"slovenia",SLB:"solomon",SOM:"somali",ZAF:"\\bs\\w*.?africa",SGS:"south.?georgia|sandwich",SSD:"\\bs\\w*.?sudan",ESP:"spain",LKA:"sri.?lanka|ceylon",SDN:"^(?!.*\\bs(?!u)).*sudan",SUR:"surinam|dutch.?guiana",SJM:"svalbard",SWZ:"swaziland",SWE:"sweden",CHE:"switz|swiss",SYR:"syria",TWN:"taiwan|taipei|formosa",TJK:"tajik",TZA:"tanzania",THA:"thailand|\\bsiam",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TGO:"togo",TKL:"tokelau",TON:"tonga",TTO:"trinidad|tobago",TUN:"tunisia",TUR:"turkey",TKM:"turkmen",TCA:"turks",TUV:"tuvalu",UGA:"uganda",UKR:"ukrain",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",USA:"united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)",UMI:"minor.?outlying.?is",URY:"uruguay",UZB:"uzbek",VUT:"vanuatu|new.?hebrides",VEN:"venezuela",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",WLF:"futuna|wallis",ESH:"western.sahara",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",YUG:"yugoslavia",ZMB:"zambia|northern.?rhodesia",EAZ:"zanzibar",ZWE:"zimbabwe|^(?!.*northern).*rhodesia"}},{}],82:[function(e,r,n){!function(){function e(t){return t&&(t.ownerDocument||t.document||t).documentElement}function n(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}function i(t,e){return e>t?-1:t>e?1:t>=e?0:NaN}function a(t){return null===t?NaN:+t}function o(t){return!isNaN(t)}function s(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}function l(t){return t.length}function u(t){for(var e=1;t*e%1;)e*=10;return e}function c(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function f(){this._=Object.create(null)}function h(t){return(t+="")===ko||t[0]===Ao?Ao+t:t}function p(t){return(t+="")[0]===Ao?t.slice(1):t}function d(t){return h(t)in this._}function g(t){return(t=h(t))in this._&&delete this._[t]}function v(){var t=[];for(var e in this._)t.push(p(e));return t}function m(){var t=0;for(var e in this._)++t;return t}function y(){for(var t in this._)return!1;return!0}function b(){this._=Object.create(null)}function x(t){return t}function _(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function w(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=Mo.length;n>r;++r){var i=Mo[r]+e;if(i in t)return i}}function k(){}function A(){}function M(t){function e(){for(var e,n=r,i=-1,a=n.length;++ir;r++)for(var i,a=t[r],o=0,s=a.length;s>o;o++)(i=a[o])&&e(i,o,r);return t}function Y(t){return Eo(t,jo),t}function X(t){var e,r;return function(n,i,a){var o,s=t[a].update,l=s.length;for(a!=r&&(r=a,e=0),i>=e&&(e=i+1);!(o=s[e])&&++e0&&(t=t.slice(0,s));var u=Oo.get(t);return u&&(t=u,l=K),s?e?i:n:e?k:a}function Z(t,e){return function(r){var n=uo.event;uo.event=r,e[0]=this.__data__;try{t.apply(this,e)}finally{uo.event=n}}}function K(t,e){var r=Z(t,e);return function(t){var e=this,n=t.relatedTarget;n&&(n===e||8&n.compareDocumentPosition(e))||r.call(e,t)}}function $(t){var r=".dragsuppress-"+ ++No,i="click"+r,a=uo.select(n(t)).on("touchmove"+r,T).on("dragstart"+r,T).on("selectstart"+r,T);if(null==Io&&(Io="onselectstart"in t?!1:w(t.style,"userSelect")),Io){var o=e(t).style,s=o[Io];o[Io]="none"}return function(t){if(a.on(r,null),Io&&(o[Io]=s),t){var e=function(){a.on(i,null)};a.on(i,function(){T(),e()},!0),setTimeout(e,0)}}}function Q(t,e){e.changedTouches&&(e=e.changedTouches[0]);var r=t.ownerSVGElement||t;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Fo){var a=n(t);if(a.scrollX||a.scrollY){r=uo.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Fo=!(o.f||o.e),r.remove()}}return Fo?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}function J(){return uo.event.changedTouches[0].identifier}function tt(t){return t>0?1:0>t?-1:0}function et(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function rt(t){return t>1?0:-1>t?Uo:Math.acos(t)}function nt(t){return t>1?Go:-1>t?-Go:Math.asin(t)}function it(t){return((t=Math.exp(t))-1/t)/2}function at(t){return((t=Math.exp(t))+1/t)/2}function ot(t){return((t=Math.exp(2*t))-1)/(t+1)}function st(t){return(t=Math.sin(t/2))*t}function lt(){}function ut(t,e,r){return this instanceof ut?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof ut?new ut(t.h,t.s,t.l):kt(""+t,At,ut):new ut(t,e,r)}function ct(t,e,r){function n(t){return t>360?t-=360:0>t&&(t+=360),60>t?a+(o-a)*t/60:180>t?o:240>t?a+(o-a)*(240-t)/60:a}function i(t){return Math.round(255*n(t))}var a,o;return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:0>e?0:e>1?1:e,r=0>r?0:r>1?1:r,o=.5>=r?r*(1+e):r+e-r*e,a=2*r-o,new bt(i(t+120),i(t),i(t-120))}function ft(t,e,r){return this instanceof ft?(this.h=+t,this.c=+e,void(this.l=+r)):arguments.length<2?t instanceof ft?new ft(t.h,t.c,t.l):t instanceof pt?gt(t.l,t.a,t.b):gt((t=Mt((t=uo.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ft(t,e,r)}function ht(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new pt(r,Math.cos(t*=Ho)*e,Math.sin(t)*e)}function pt(t,e,r){return this instanceof pt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof pt?new pt(t.l,t.a,t.b):t instanceof ft?ht(t.h,t.c,t.l):Mt((t=bt(t)).r,t.g,t.b):new pt(t,e,r)}function dt(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return i=vt(i)*rs,n=vt(n)*ns,a=vt(a)*is,new bt(yt(3.2404542*i-1.5371385*n-.4985314*a),yt(-.969266*i+1.8760108*n+.041556*a),yt(.0556434*i-.2040259*n+1.0572252*a))}function gt(t,e,r){return t>0?new ft(Math.atan2(r,e)*Yo,Math.sqrt(e*e+r*r),t):new ft(NaN,NaN,t)}function vt(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function mt(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function yt(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function bt(t,e,r){return this instanceof bt?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof bt?new bt(t.r,t.g,t.b):kt(""+t,bt,ct):new bt(t,e,r)}function xt(t){return new bt(t>>16,t>>8&255,255&t)}function _t(t){return xt(t)+""}function wt(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function kt(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(Et(i[0]),Et(i[1]),Et(i[2]))}return(a=ss.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o=o>>4|o,s=240&a,s=s>>4|s,l=15&a,l=l<<4|l):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function At(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=.5>l?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(r>e?6:0):e==o?(r-t)/s+2:(t-e)/s+4,n*=60):(n=NaN,i=l>0&&1>l?0:n),new ut(n,i,l)}function Mt(t,e,r){t=Tt(t),e=Tt(e),r=Tt(r);var n=mt((.4124564*t+.3575761*e+.1804375*r)/rs),i=mt((.2126729*t+.7151522*e+.072175*r)/ns),a=mt((.0193339*t+.119192*e+.9503041*r)/is);return pt(116*i-16,500*(n-i),200*(i-a))}function Tt(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Et(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Lt(t){return"function"==typeof t?t:function(){return t}}function St(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),Ct(e,r,t,n)}}function Ct(t,e,r,n){function i(){var t,e=l.status;if(!e&&Pt(l)||e>=200&&300>e||304===e){try{t=r.call(a,l)}catch(n){return void o.error.call(a,n)}o.load.call(a,t)}else o.error.call(a,l)}var a={},o=uo.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,u=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(t){var e=uo.event;uo.event=t;try{o.progress.call(a,l)}finally{uo.event=e}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(e=null==t?null:t+"",a):e},a.responseType=function(t){return arguments.length?(u=t,a):u},a.response=function(t){return r=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(fo(arguments)))}}),a.send=function(r,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),l.open(r,t,!0),null==e||"accept"in s||(s.accept=e+",*/*"),l.setRequestHeader)for(var c in s)l.setRequestHeader(c,s[c]);return null!=e&&l.overrideMimeType&&l.overrideMimeType(e),null!=u&&(l.responseType=u),null!=i&&a.on("error",i).on("load",function(t){i(null,t)}),o.beforesend.call(a,l),l.send(null==n?null:n),a},a.abort=function(){return l.abort(),a},uo.rebind(a,o,"on"),null==n?a:a.get(zt(n))}function zt(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}function Pt(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function Rt(t,e,r){var n=arguments.length;2>n&&(e=0),3>n&&(r=Date.now());var i=r+e,a={c:t,t:i,n:null};return us?us.n=a:ls=a,us=a,cs||(fs=clearTimeout(fs),cs=1,hs(jt)),a}function jt(){var t=Ot(),e=It()-t;e>24?(isFinite(e)&&(clearTimeout(fs),fs=setTimeout(jt,e)),cs=0):(cs=1,hs(jt))}function Ot(){for(var t=Date.now(),e=ls;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function It(){for(var t,e=ls,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}}function Dt(t){var e=t.decimal,r=t.thousands,n=t.grouping,i=t.currency,a=n&&r?function(t,e){for(var i=t.length,a=[],o=0,s=n[0],l=0;i>0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(i-=s,i+s)),!((l+=s+1)>e));)s=n[o=(o+1)%n.length];return a.reverse().join(r)}:x;return function(t){var r=ds.exec(t),n=r[1]||" ",o=r[2]||">",s=r[3]||"-",l=r[4]||"",u=r[5],c=+r[6],f=r[7],h=r[8],p=r[9],d=1,g="",v="",m=!1,y=!0;switch(h&&(h=+h.substring(1)),(u||"0"===n&&"="===o)&&(u=n="0",o="="),p){case"n":f=!0,p="g";break;case"%":d=100,v="%",p="f";break;case"p":d=100,v="%",p="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+p.toLowerCase());case"c":y=!1;case"d":m=!0,h=0;break;case"s":d=-1,p="r"}"$"===l&&(g=i[0],v=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=gs.get(p)||Bt;var b=u&&f;return function(t){var r=v;if(m&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>d){var l=uo.formatPrefix(t,h);t=l.scale(t),r=l.symbol+v}else t*=d;t=p(t,h);var x,_,w=t.lastIndexOf(".");if(0>w){var k=y?t.lastIndexOf("e"):-1;0>k?(x=t,_=""):(x=t.substring(0,k),_=t.substring(k))}else x=t.substring(0,w),_=e+t.substring(w+1);!u&&f&&(x=a(x,1/0));var A=g.length+x.length+_.length+(b?0:i.length),M=c>A?new Array(A=c-A+1).join(n):"";return b&&(x=a(M+x,M.length?c-_.length:1/0)),i+=g,t=x+_,("<"===o?i+t+M:">"===o?M+i+t:"^"===o?M.substring(0,A>>=1)+i+t+M.substring(A):i+(b?t:M+t))+r}}}function Bt(t){return t+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Vt(t,e,r){function n(e){var r=t(e),n=a(r,1);return n-e>e-r?r:n}function i(r){return e(r=t(new ms(r-1)),1),r}function a(t,r){return e(t=new ms(+t),r),t}function o(t,n,a){var o=i(t),s=[];if(a>1)for(;n>o;)r(o)%a||s.push(new Date(+o)),e(o,1);else for(;n>o;)s.push(new Date(+o)),e(o,1);return s}function s(t,e,r){try{ms=Ut;var n=new Ut;return n._=t,o(n,e,r)}finally{ms=Date}}t.floor=t,t.round=n,t.ceil=i,t.offset=a,t.range=o;var l=t.utc=qt(t);return l.floor=l,l.round=qt(n),l.ceil=qt(i),l.offset=qt(a),l.range=s,t}function qt(t){return function(e,r){try{ms=Ut;var n=new Ut;return n._=e,t(n,r)._}finally{ms=Date}}}function Gt(t){function e(t){function e(e){for(var r,i,a,o=[],s=-1,l=0;++ss;){if(n>=u)return-1;if(i=e.charCodeAt(s++),37===i){if(o=e.charAt(s++),a=S[o in bs?e.charAt(s++):o],!a||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}function n(t,e,r){w.lastIndex=0;var n=w.exec(e.slice(r));return n?(t.w=k.get(n[0].toLowerCase()),r+n[0].length):-1}function i(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.w=_.get(n[0].toLowerCase()),r+n[0].length):-1}function a(t,e,r){T.lastIndex=0;var n=T.exec(e.slice(r));return n?(t.m=E.get(n[0].toLowerCase()),r+n[0].length):-1}function o(t,e,r){A.lastIndex=0;var n=A.exec(e.slice(r));return n?(t.m=M.get(n[0].toLowerCase()),r+n[0].length):-1}function s(t,e,n){return r(t,L.c.toString(),e,n)}function l(t,e,n){return r(t,L.x.toString(),e,n)}function u(t,e,n){return r(t,L.X.toString(),e,n)}function c(t,e,r){var n=b.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)}var f=t.dateTime,h=t.date,p=t.time,d=t.periods,g=t.days,v=t.shortDays,m=t.months,y=t.shortMonths;e.utc=function(t){function r(t){try{ms=Ut;var e=new ms;return e._=t,n(e)}finally{ms=Date}}var n=e(t);return r.parse=function(t){try{ms=Ut;var e=n.parse(t);return e&&e._}finally{ms=Date}},r.toString=n.toString,r},e.multi=e.utc.multi=ce;var b=uo.map(),x=Yt(g),_=Xt(g),w=Yt(v),k=Xt(v),A=Yt(m),M=Xt(m),T=Yt(y),E=Xt(y);d.forEach(function(t,e){b.set(t.toLowerCase(),e)});var L={a:function(t){return v[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:e(f),d:function(t,e){return Ht(t.getDate(),e,2)},e:function(t,e){return Ht(t.getDate(),e,2)},H:function(t,e){return Ht(t.getHours(),e,2)},I:function(t,e){return Ht(t.getHours()%12||12,e,2)},j:function(t,e){return Ht(1+vs.dayOfYear(t),e,3)},L:function(t,e){return Ht(t.getMilliseconds(),e,3)},m:function(t,e){return Ht(t.getMonth()+1,e,2)},M:function(t,e){return Ht(t.getMinutes(),e,2)},p:function(t){return d[+(t.getHours()>=12)]},S:function(t,e){return Ht(t.getSeconds(),e,2)},U:function(t,e){return Ht(vs.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ht(vs.mondayOfYear(t),e,2)},x:e(h),X:e(p),y:function(t,e){return Ht(t.getFullYear()%100,e,2)},Y:function(t,e){return Ht(t.getFullYear()%1e4,e,4)},Z:le,"%":function(){return"%"}},S={a:n,A:i,b:a,B:o,c:s,d:re,e:re,H:ie,I:ie,j:ne,L:se,m:ee,M:ae,p:c,S:oe,U:Zt,w:Wt,W:Kt,x:l,X:u,y:Qt,Y:$t,Z:Jt,"%":ue};return e}function Ht(t,e,r){var n=0>t?"-":"",i=(n?-t:t)+"",a=i.length;return n+(r>a?new Array(r-a+1).join(e)+i:i)}function Yt(t){return new RegExp("^(?:"+t.map(uo.requote).join("|")+")","i")}function Xt(t){for(var e=new f,r=-1,n=t.length;++r68?1900:2e3)}function ee(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function re(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function ne(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function ie(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function ae(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function oe(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function se(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function le(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=wo(e)/60|0,i=wo(e)%60;return r+Ht(n,"0",2)+Ht(i,"0",2)}function ue(t,e,r){_s.lastIndex=0;var n=_s.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function ce(t){for(var e=t.length,r=-1;++r=0?1:-1,s=o*r,l=Math.cos(e),u=Math.sin(e),c=a*u,f=i*l+c*Math.cos(s),h=c*o*Math.sin(s);Es.add(Math.atan2(h,f)),n=t,i=l,a=u}var e,r,n,i,a;Ls.point=function(o,s){Ls.point=t,n=(e=o)*Ho,i=Math.cos(s=(r=s)*Ho/2+Uo/4),a=Math.sin(s)},Ls.lineEnd=function(){t(e,r)}}function me(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function ye(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function be(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xe(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function _e(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function we(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function ke(t){return[Math.atan2(t[1],t[0]),nt(t[2])]}function Ae(t,e){return wo(t[0]-e[0])s;++s)i.point((r=t[s])[0],r[1]);return void i.lineEnd()}var l=new je(r,t,null,!0),u=new je(r,null,l,!1);l.o=u,a.push(l),o.push(u),l=new je(n,t,null,!1),u=new je(n,null,l,!0),l.o=u,a.push(l),o.push(u)}}),o.sort(e),Re(a),Re(o),a.length){for(var s=0,l=r,u=o.length;u>s;++s)o[s].e=l=!l;for(var c,f,h=a[0];;){for(var p=h,d=!0;p.v;)if((p=p.n)===h)return;c=p.z,i.lineStart();do{if(p.v=p.o.v=!0,p.e){if(d)for(var s=0,u=c.length;u>s;++s)i.point((f=c[s])[0],f[1]);else n(p.x,p.n.x,1,i);p=p.n}else{if(d){c=p.p.z;for(var s=c.length-1;s>=0;--s)i.point((f=c[s])[0],f[1])}else n(p.x,p.p.x,-1,i);p=p.p}p=p.o,c=p.z,d=!d}while(!p.v);i.lineEnd()}}}function Re(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n0){for(_||(a.polygonStart(),_=!0),a.lineStart();++o1&&2&e&&r.push(r.pop().concat(r.shift())),p.push(r.filter(Ie))}var p,d,g,v=e(a),m=i.invert(n[0],n[1]),y={point:o,lineStart:l,lineEnd:u,polygonStart:function(){y.point=c,y.lineStart=f,y.lineEnd=h,p=[],d=[]},polygonEnd:function(){y.point=o,y.lineStart=l,y.lineEnd=u,p=uo.merge(p);var t=Ve(m,d);p.length?(_||(a.polygonStart(),_=!0),Pe(p,Fe,t,r,a)):t&&(_||(a.polygonStart(),_=!0),a.lineStart(),r(null,null,1,a),a.lineEnd()),_&&(a.polygonEnd(),_=!1),p=d=null},sphere:function(){a.polygonStart(),a.lineStart(),r(null,null,1,a),a.lineEnd(),a.polygonEnd()}},b=Ne(),x=e(b),_=!1;return y}}function Ie(t){return t.length>1}function Ne(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:k,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Fe(t,e){return((t=t.x)[0]<0?t[1]-Go-Do:Go-t[1])-((e=e.x)[0]<0?e[1]-Go-Do:Go-e[1])}function De(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Uo:-Uo,l=wo(a-r);wo(l-Uo)0?Go:-Go),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Uo&&(wo(r-i)Do?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}function Ue(t,e,r,n){var i;if(null==t)i=r*Go,n.point(-Uo,i),n.point(0,i),n.point(Uo,i),n.point(Uo,0),n.point(Uo,-i),n.point(0,-i),n.point(-Uo,-i),n.point(-Uo,0),n.point(-Uo,i);else if(wo(t[0]-e[0])>Do){var a=t[0]s;++s){var u=e[s],c=u.length;if(c)for(var f=u[0],h=f[0],p=f[1]/2+Uo/4,d=Math.sin(p),g=Math.cos(p),v=1;;){v===c&&(v=0),t=u[v];var m=t[0],y=t[1]/2+Uo/4,b=Math.sin(y),x=Math.cos(y),_=m-h,w=_>=0?1:-1,k=w*_,A=k>Uo,M=d*b;if(Es.add(Math.atan2(M*w*Math.sin(k),g*x+M*Math.cos(k))),a+=A?_+w*Vo:_,A^h>=r^m>=r){var T=be(me(f),me(t));we(T);var E=be(i,T);we(E);var L=(A^_>=0?-1:1)*nt(E[2]);(n>L||n===L&&(T[0]||T[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;h=m,d=b,g=x,f=t}}return(-Do>a||Do>a&&-Do>Es)^1&o}function qe(t){function e(t,e){return Math.cos(t)*Math.cos(e)>a}function r(t){var r,a,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(f,h){var p,d=[f,h],g=e(f,h),v=o?g?0:i(f,h):g?i(f+(0>f?Uo:-Uo),h):0;if(!r&&(u=l=g)&&t.lineStart(),g!==l&&(p=n(r,d),(Ae(r,p)||Ae(d,p))&&(d[0]+=Do,d[1]+=Do,g=e(d[0],d[1]))),g!==l)c=0,g?(t.lineStart(),p=n(d,r),t.point(p[0],p[1])):(p=n(r,d),t.point(p[0],p[1]),t.lineEnd()),r=p;else if(s&&r&&o^g){var m;v&a||!(m=n(d,r,!0))||(c=0,o?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||r&&Ae(r,d)||t.point(d[0],d[1]),r=d,l=g,a=v},lineEnd:function(){l&&t.lineEnd(),r=null},clean:function(){return c|(u&&l)<<1}}}function n(t,e,r){var n=me(t),i=me(e),o=[1,0,0],s=be(n,i),l=ye(s,s),u=s[0],c=l-u*u;if(!c)return!r&&t;var f=a*l/c,h=-a*u/c,p=be(o,s),d=_e(o,f),g=_e(s,h);xe(d,g);var v=p,m=ye(d,v),y=ye(v,v),b=m*m-y*(ye(d,d)-1);if(!(0>b)){var x=Math.sqrt(b),_=_e(v,(-m-x)/y);if(xe(_,d),_=ke(_),!r)return _;var w,k=t[0],A=e[0],M=t[1],T=e[1];k>A&&(w=k,k=A,A=w);var E=A-k,L=wo(E-Uo)E;if(!L&&M>T&&(w=M,M=T,T=w),S?L?M+T>0^_[1]<(wo(_[0]-k)Uo^(k<=_[0]&&_[0]<=A)){var C=_e(v,(-m+x)/y);return xe(C,d),[_,ke(C)]}}}function i(e,r){var n=o?t:Uo-t,i=0;return-n>e?i|=1:e>n&&(i|=2),-n>r?i|=4:r>n&&(i|=8),i}var a=Math.cos(t),o=a>0,s=wo(a)>Do,l=vr(t,6*Ho);return Oe(e,r,l,o?[0,-t]:[-Uo,t-Uo])}function Ge(t,e,r,n){return function(i){var a,o=i.a,s=i.b,l=o.x,u=o.y,c=s.x,f=s.y,h=0,p=1,d=c-l,g=f-u;if(a=t-l,d||!(a>0)){if(a/=d,0>d){if(h>a)return;p>a&&(p=a)}else if(d>0){if(a>p)return;a>h&&(h=a)}if(a=r-l,d||!(0>a)){if(a/=d,0>d){if(a>p)return;a>h&&(h=a)}else if(d>0){if(h>a)return;p>a&&(p=a)}if(a=e-u,g||!(a>0)){if(a/=g,0>g){if(h>a)return;p>a&&(p=a)}else if(g>0){if(a>p)return;a>h&&(h=a)}if(a=n-u,g||!(0>a)){if(a/=g,0>g){if(a>p)return;a>h&&(h=a)}else if(g>0){if(h>a)return;p>a&&(p=a)}return h>0&&(i.a={x:l+h*d,y:u+h*g}),1>p&&(i.b={x:l+p*d,y:u+p*g}),i}}}}}}function He(t,e,r,n){function i(n,i){return wo(n[0]-t)0?0:3:wo(n[0]-r)0?2:1:wo(n[1]-e)0?1:0:i>0?3:2}function a(t,e){return o(t.x,e.x)}function o(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,r=v.length,n=t[1],i=0;r>i;++i)for(var a,o=1,s=v[i],l=s.length,u=s[0];l>o;++o)a=s[o],u[1]<=n?a[1]>n&&et(u,a,t)>0&&++e:a[1]<=n&&et(u,a,t)<0&&--e,u=a;return 0!==e}function u(a,s,l,u){var c=0,f=0;if(null==a||(c=i(a,l))!==(f=i(s,l))||o(a,s)<0^l>0){do u.point(0===c||3===c?t:r,c>1?n:e);while((c=(c+l+4)%4)!==f)}else u.point(s[0],s[1])}function c(i,a){return i>=t&&r>=i&&a>=e&&n>=a}function f(t,e){c(t,e)&&s.point(t,e)}function h(){S.point=d,v&&v.push(m=[]),A=!0,k=!1,_=w=NaN}function p(){g&&(d(y,b),x&&k&&E.rejoin(),g.push(E.buffer())),S.point=f,k&&s.lineEnd()}function d(t,e){t=Math.max(-Vs,Math.min(Vs,t)),e=Math.max(-Vs,Math.min(Vs,e));var r=c(t,e);if(v&&m.push([t,e]),A)y=t,b=e,x=r,A=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&k)s.point(t,e);else{var n={a:{x:_,y:w},b:{x:t,y:e}};L(n)?(k||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),M=!1):r&&(s.lineStart(),s.point(t,e),M=!1)}_=t,w=e,k=r}var g,v,m,y,b,x,_,w,k,A,M,T=s,E=Ne(),L=Ge(t,e,r,n),S={point:f,lineStart:h,lineEnd:p,polygonStart:function(){s=E,g=[],v=[],M=!0},polygonEnd:function(){s=T,g=uo.merge(g);var e=l([t,n]),r=M&&e,i=g.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),u(null,null,1,s),s.lineEnd()),i&&Pe(g,a,e,u,s),s.polygonEnd()),g=v=m=null}};return S}}function Ye(t){var e=0,r=Uo/3,n=lr(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Uo/180,r=t[1]*Uo/180):[e/Uo*180,r/Uo*180]},i}function Xe(t,e){function r(t,e){var r=Math.sqrt(a-2*i*Math.sin(e))/i;return[r*Math.sin(t*=i),o-r*Math.cos(t)]}var n=Math.sin(t),i=(n+Math.sin(e))/2,a=1+n*(2*i-n),o=Math.sqrt(a)/i;return r.invert=function(t,e){var r=o-e;return[Math.atan2(t,r)/i,nt((a-(t*t+r*r)*i*i)/(2*i))]},r}function We(){function t(t,e){Gs+=i*t-n*e,n=t,i=e}var e,r,n,i;Zs.point=function(a,o){Zs.point=t,e=n=a,r=i=o},Zs.lineEnd=function(){t(e,r)}}function Ze(t,e){Hs>t&&(Hs=t),t>Xs&&(Xs=t),Ys>e&&(Ys=e),e>Ws&&(Ws=e)}function Ke(){function t(t,e){o.push("M",t,",",e,a)}function e(t,e){o.push("M",t,",",e),s.point=r}function r(t,e){o.push("L",t,",",e)}function n(){s.point=t}function i(){o.push("Z")}var a=$e(4.5),o=[],s={point:t,lineStart:function(){s.point=e},lineEnd:n,polygonStart:function(){ +s.lineEnd=i},polygonEnd:function(){s.lineEnd=n,s.point=t},pointRadius:function(t){return a=$e(t),s},result:function(){if(o.length){var t=o.join("");return o=[],t}}};return s}function $e(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Qe(t,e){zs+=t,Ps+=e,++Rs}function Je(){function t(t,n){var i=t-e,a=n-r,o=Math.sqrt(i*i+a*a);js+=o*(e+t)/2,Os+=o*(r+n)/2,Is+=o,Qe(e=t,r=n)}var e,r;$s.point=function(n,i){$s.point=t,Qe(e=n,r=i)}}function tr(){$s.point=Qe}function er(){function t(t,e){var r=t-n,a=e-i,o=Math.sqrt(r*r+a*a);js+=o*(n+t)/2,Os+=o*(i+e)/2,Is+=o,o=i*t-n*e,Ns+=o*(n+t),Fs+=o*(i+e),Ds+=3*o,Qe(n=t,i=e)}var e,r,n,i;$s.point=function(a,o){$s.point=t,Qe(e=n=a,r=i=o)},$s.lineEnd=function(){t(e,r)}}function rr(t){function e(e,r){t.moveTo(e+o,r),t.arc(e,r,o,0,Vo)}function r(e,r){t.moveTo(e,r),s.point=n}function n(e,r){t.lineTo(e,r)}function i(){s.point=e}function a(){t.closePath()}var o=4.5,s={point:e,lineStart:function(){s.point=r},lineEnd:i,polygonStart:function(){s.lineEnd=a},polygonEnd:function(){s.lineEnd=i,s.point=e},pointRadius:function(t){return o=t,s},result:k};return s}function nr(t){function e(t){return(s?n:r)(t)}function r(e){return or(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})}function n(e){function r(r,n){r=t(r,n),e.point(r[0],r[1])}function n(){b=NaN,A.point=a,e.lineStart()}function a(r,n){var a=me([r,n]),o=t(r,n);i(b,x,y,_,w,k,b=o[0],x=o[1],y=r,_=a[0],w=a[1],k=a[2],s,e),e.point(b,x)}function o(){A.point=r,e.lineEnd()}function l(){n(),A.point=u,A.lineEnd=c}function u(t,e){a(f=t,h=e),p=b,d=x,g=_,v=w,m=k,A.point=a}function c(){i(b,x,y,_,w,k,p,d,f,g,v,m,s,e),A.lineEnd=o,o()}var f,h,p,d,g,v,m,y,b,x,_,w,k,A={point:r,lineStart:n,lineEnd:o,polygonStart:function(){e.polygonStart(),A.lineStart=l},polygonEnd:function(){e.polygonEnd(),A.lineStart=n}};return A}function i(e,r,n,s,l,u,c,f,h,p,d,g,v,m){var y=c-e,b=f-r,x=y*y+b*b;if(x>4*a&&v--){var _=s+p,w=l+d,k=u+g,A=Math.sqrt(_*_+w*w+k*k),M=Math.asin(k/=A),T=wo(wo(k)-1)a||wo((y*C+b*z)/x-.5)>.3||o>s*p+l*d+u*g)&&(i(e,r,n,s,l,u,L,S,T,_/=A,w/=A,k,v,m),m.point(L,S),i(L,S,T,_,w,k,c,f,h,p,d,g,v,m))}}var a=.5,o=Math.cos(30*Ho),s=16;return e.precision=function(t){return arguments.length?(s=(a=t*t)>0&&16,e):Math.sqrt(a)},e}function ir(t){var e=nr(function(e,r){return t([e*Yo,r*Yo])});return function(t){return ur(e(t))}}function ar(t){this.stream=t}function or(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){return t=s(t[0]*Ho,t[1]*Ho),[t[0]*h+l,u-t[1]*h]}function r(t){return t=s.invert((t[0]-l)/h,(u-t[1])/h),t&&[t[0]*Yo,t[1]*Yo]}function n(){s=Ce(o=hr(m,y,b),a);var t=a(g,v);return l=p-t[0]*h,u=d+t[1]*h,i()}function i(){return c&&(c.valid=!1,c=null),e}var a,o,s,l,u,c,f=nr(function(t,e){return t=a(t,e),[t[0]*h+l,u-t[1]*h]}),h=150,p=480,d=250,g=0,v=0,m=0,y=0,b=0,_=Us,w=x,k=null,A=null;return e.stream=function(t){return c&&(c.valid=!1),c=ur(_(o,f(w(t)))),c.valid=!0,c},e.clipAngle=function(t){return arguments.length?(_=null==t?(k=t,Us):qe((k=+t)*Ho),i()):k},e.clipExtent=function(t){return arguments.length?(A=t,w=t?He(t[0][0],t[0][1],t[1][0],t[1][1]):x,i()):A},e.scale=function(t){return arguments.length?(h=+t,n()):h},e.translate=function(t){return arguments.length?(p=+t[0],d=+t[1],n()):[p,d]},e.center=function(t){return arguments.length?(g=t[0]%360*Ho,v=t[1]%360*Ho,n()):[g*Yo,v*Yo]},e.rotate=function(t){return arguments.length?(m=t[0]%360*Ho,y=t[1]%360*Ho,b=t.length>2?t[2]%360*Ho:0,n()):[m*Yo,y*Yo,b*Yo]},uo.rebind(e,f,"precision"),function(){return a=t.apply(this,arguments),e.invert=a.invert&&r,n()}}function ur(t){return or(t,function(e,r){t.point(e*Ho,r*Ho)})}function cr(t,e){return[t,e]}function fr(t,e){return[t>Uo?t-Vo:-Uo>t?t+Vo:t,e]}function hr(t,e,r){return t?e||r?Ce(dr(t),gr(e,r)):dr(t):e||r?gr(e,r):fr}function pr(t){return function(e,r){return e+=t,[e>Uo?e-Vo:-Uo>e?e+Vo:e,r]}}function dr(t){var e=pr(t);return e.invert=pr(-t),e}function gr(t,e){function r(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,u=Math.sin(e),c=u*n+s*i;return[Math.atan2(l*a-c*o,s*n-u*i),nt(c*a+l*o)]}var n=Math.cos(t),i=Math.sin(t),a=Math.cos(e),o=Math.sin(e);return r.invert=function(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,u=Math.sin(e),c=u*a-l*o;return[Math.atan2(l*a+u*o,s*n+c*i),nt(c*n-s*i)]},r}function vr(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=mr(r,i),a=mr(r,a),(o>0?a>i:i>a)&&(i+=o*Vo)):(i=t+o*Vo,a=t-.5*l);for(var u,c=i;o>0?c>a:a>c;c-=l)s.point((u=ke([r,-n*Math.cos(c),-n*Math.sin(c)]))[0],u[1])}}function mr(t,e){var r=me(e);r[0]-=t,we(r);var n=rt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-Do)%(2*Math.PI)}function yr(t,e,r){var n=uo.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[t,e]})}}function br(t,e,r){var n=uo.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[e,t]})}}function xr(t){return t.source}function _r(t){return t.target}function wr(t,e,r,n){var i=Math.cos(e),a=Math.sin(e),o=Math.cos(n),s=Math.sin(n),l=i*Math.cos(t),u=i*Math.sin(t),c=o*Math.cos(r),f=o*Math.sin(r),h=2*Math.asin(Math.sqrt(st(n-e)+i*o*st(r-t))),p=1/Math.sin(h),d=h?function(t){var e=Math.sin(t*=h)*p,r=Math.sin(h-t)*p,n=r*l+e*c,i=r*u+e*f,o=r*a+e*s;return[Math.atan2(i,n)*Yo,Math.atan2(o,Math.sqrt(n*n+i*i))*Yo]}:function(){return[t*Yo,e*Yo]};return d.distance=h,d}function kr(){function t(t,i){var a=Math.sin(i*=Ho),o=Math.cos(i),s=wo((t*=Ho)-e),l=Math.cos(s);Qs+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=n*a-r*o*l)*s),r*a+n*o*l),e=t,r=a,n=o}var e,r,n;Js.point=function(i,a){e=i*Ho,r=Math.sin(a*=Ho),n=Math.cos(a),Js.point=t},Js.lineEnd=function(){Js.point=Js.lineEnd=k}}function Ar(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}function Mr(t,e){function r(t,e){o>0?-Go+Do>e&&(e=-Go+Do):e>Go-Do&&(e=Go-Do);var r=o/Math.pow(i(e),a);return[r*Math.sin(a*t),o-r*Math.cos(a*t)]}var n=Math.cos(t),i=function(t){return Math.tan(Uo/4+t/2)},a=t===e?Math.sin(t):Math.log(n/Math.cos(e))/Math.log(i(e)/i(t)),o=n*Math.pow(i(t),a)/a;return a?(r.invert=function(t,e){var r=o-e,n=tt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(o/n,1/a))-Go]},r):Er}function Tr(t,e){function r(t,e){var r=a-e;return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}var n=Math.cos(t),i=t===e?Math.sin(t):(n-Math.cos(e))/(e-t),a=n/i+t;return wo(i)i;i++){for(;n>1&&et(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function Rr(t,e){return t[0]-e[0]||t[1]-e[1]}function jr(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function Or(t,e,r,n){var i=t[0],a=r[0],o=e[0]-i,s=n[0]-a,l=t[1],u=r[1],c=e[1]-l,f=n[1]-u,h=(s*(l-u)-f*(i-a))/(f*o-s*c);return[i+h*o,l+h*c]}function Ir(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}function Nr(){an(this),this.edge=this.site=this.circle=null}function Fr(t){var e=fl.pop()||new Nr;return e.site=t,e}function Dr(t){Zr(t),ll.remove(t),fl.push(t),an(t)}function Br(t){var e=t.circle,r=e.x,n=e.cy,i={x:r,y:n},a=t.P,o=t.N,s=[t];Dr(t);for(var l=a;l.circle&&wo(r-l.circle.x)c;++c)u=s[c],l=s[c-1],en(u.edge,l.site,u.site,i);l=s[0],u=s[f-1],u.edge=Jr(l.site,u.site,null,i),Wr(l),Wr(u)}function Ur(t){for(var e,r,n,i,a=t.x,o=t.y,s=ll._;s;)if(n=Vr(s,o)-a,n>Do)s=s.L;else{if(i=a-qr(s,o),!(i>Do)){n>-Do?(e=s.P,r=s):i>-Do?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=Fr(t);if(ll.insert(e,l),e||r){if(e===r)return Zr(e),r=Fr(e.site),ll.insert(l,r),l.edge=r.edge=Jr(e.site,l.site),Wr(e),void Wr(r);if(!r)return void(l.edge=Jr(e.site,l.site));Zr(e),Zr(r);var u=e.site,c=u.x,f=u.y,h=t.x-c,p=t.y-f,d=r.site,g=d.x-c,v=d.y-f,m=2*(h*v-p*g),y=h*h+p*p,b=g*g+v*v,x={x:(v*y-p*b)/m+c,y:(h*b-g*y)/m+f};en(r.edge,u,d,x),l.edge=Jr(u,t,null,x),r.edge=Jr(t,d,null,x),Wr(e),Wr(r)}}function Vr(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-(1/0);r=o.site;var s=r.x,l=r.y,u=l-e;if(!u)return s;var c=s-n,f=1/a-1/u,h=c/u;return f?(-h+Math.sqrt(h*h-2*f*(c*c/(-2*u)-l+u/2+i-a/2)))/f+n:(n+s)/2}function qr(t,e){var r=t.N;if(r)return Vr(r,e);var n=t.site;return n.y===e?n.x:1/0}function Gr(t){this.site=t,this.edges=[]}function Hr(t){for(var e,r,n,i,a,o,s,l,u,c,f=t[0][0],h=t[1][0],p=t[0][1],d=t[1][1],g=sl,v=g.length;v--;)if(a=g[v],a&&a.prepare())for(s=a.edges,l=s.length,o=0;l>o;)c=s[o].end(),n=c.x,i=c.y,u=s[++o%l].start(),e=u.x,r=u.y,(wo(n-e)>Do||wo(i-r)>Do)&&(s.splice(o,0,new rn(tn(a.site,c,wo(n-f)Do?{x:f,y:wo(e-f)Do?{x:wo(r-d)Do?{x:h,y:wo(e-h)Do?{x:wo(r-p)=-Bo)){var p=l*l+u*u,d=c*c+f*f,g=(f*p-u*d)/h,v=(l*d-c*p)/h,f=v+s,m=hl.pop()||new Xr;m.arc=t,m.site=i,m.x=g+o,m.y=f+Math.sqrt(g*g+v*v),m.cy=f,t.circle=m;for(var y=null,b=cl._;b;)if(m.yv||v>=s)return;if(h>d){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.yn||n>1)if(h>d){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.yp){if(a){if(a.x>=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xa||f>o||n>h||i>p)){if(d=t.point){var d,g=e-t.x,v=r-t.y,m=g*g+v*v;if(l>m){var y=Math.sqrt(l=m);n=e-y,i=r-y,a=e+y,o=r+y,s=d}}for(var b=t.nodes,x=.5*(c+h),_=.5*(f+p),w=e>=x,k=r>=_,A=k<<1|w,M=A+4;M>A;++A)if(t=b[3&A])switch(3&A){case 0:u(t,c,f,x,_);break;case 1:u(t,x,f,h,_);break;case 2:u(t,c,_,x,p);break;case 3:u(t,x,_,h,p)}}}(t,n,i,a,o),s}function mn(t,e){t=uo.rgb(t),e=uo.rgb(e);var r=t.r,n=t.g,i=t.b,a=e.r-r,o=e.g-n,s=e.b-i;return function(t){return"#"+wt(Math.round(r+a*t))+wt(Math.round(n+o*t))+wt(Math.round(i+s*t))}}function yn(t,e){var r,n={},i={};for(r in t)r in e?n[r]=_n(t[r],e[r]):i[r]=t[r];for(r in e)r in t||(i[r]=e[r]);return function(t){for(r in n)i[r]=n[r](t);return i}}function bn(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function xn(t,e){var r,n,i,a=dl.lastIndex=gl.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=dl.exec(t))&&(n=gl.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:bn(r,n)})),a=gl.lastIndex;return an;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}function _n(t,e){for(var r,n=uo.interpolators.length;--n>=0&&!(r=uo.interpolators[n](t,e)););return r}function wn(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;s>r;++r)n.push(_n(t[r],e[r]));for(;a>r;++r)i[r]=t[r];for(;o>r;++r)i[r]=e[r];return function(t){for(r=0;s>r;++r)i[r]=n[r](t);return i}}function kn(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function An(t){return function(e){return 1-t(1-e)}}function Mn(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Tn(t){return t*t}function En(t){return t*t*t}function Ln(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(.5>t?r:3*(t-e)+r-.75)}function Sn(t){return function(e){return Math.pow(e,t)}}function Cn(t){return 1-Math.cos(t*Go)}function zn(t){return Math.pow(2,10*(t-1))}function Pn(t){return 1-Math.sqrt(1-t*t)}function Rn(t,e){var r;return arguments.length<2&&(e=.45),arguments.length?r=e/Vo*Math.asin(1/t):(t=1,r=e/4),function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*Vo/e)}}function jn(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}}function On(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function In(t,e){t=uo.hcl(t),e=uo.hcl(e);var r=t.h,n=t.c,i=t.l,a=e.h-r,o=e.c-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.c:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ht(r+a*t,n+o*t,i+s*t)+""}}function Nn(t,e){t=uo.hsl(t),e=uo.hsl(e);var r=t.h,n=t.s,i=t.l,a=e.h-r,o=e.s-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.s:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ct(r+a*t,n+o*t,i+s*t)+""}}function Fn(t,e){t=uo.lab(t),e=uo.lab(e);var r=t.l,n=t.a,i=t.b,a=e.l-r,o=e.a-n,s=e.b-i;return function(t){return dt(r+a*t,n+o*t,i+s*t)+""}}function Dn(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function Bn(t){var e=[t.a,t.b],r=[t.c,t.d],n=Vn(e),i=Un(e,r),a=Vn(qn(r,e,-i))||0;e[0]*r[1]180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(Gn(r)+"rotate(",null,")")-2,x:bn(t,e)})):e&&r.push(Gn(r)+"rotate("+e+")")}function Xn(t,e,r,n){t!==e?n.push({i:r.push(Gn(r)+"skewX(",null,")")-2,x:bn(t,e)}):e&&r.push(Gn(r)+"skewX("+e+")")}function Wn(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(Gn(r)+"scale(",null,",",null,")");n.push({i:i-4,x:bn(t[0],e[0])},{i:i-2,x:bn(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(Gn(r)+"scale("+e+")")}function Zn(t,e){var r=[],n=[];return t=uo.transform(t),e=uo.transform(e),Hn(t.translate,e.translate,r,n),Yn(t.rotate,e.rotate,r,n),Xn(t.skew,e.skew,r,n),Wn(t.scale,e.scale,r,n),t=e=null,function(t){for(var e,i=-1,a=n.length;++i=0;)r.push(i[n])}function li(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++or;++r)(e=t[r][1])>i&&(n=r,i=e);return n}function bi(t){return t.reduce(xi,0)}function xi(t,e){return t+e[1]}function _i(t,e){return wi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function wi(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function ki(t){return[uo.min(t),uo.max(t)]}function Ai(t,e){return t.value-e.value}function Mi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ti(t,e){t._pack_next=e,e._pack_prev=t}function Ei(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Li(t){function e(t){c=Math.min(t.x-t.r,c),f=Math.max(t.x+t.r,f),h=Math.min(t.y-t.r,h),p=Math.max(t.y+t.r,p)}if((r=t.children)&&(u=r.length)){var r,n,i,a,o,s,l,u,c=1/0,f=-(1/0),h=1/0,p=-(1/0);if(r.forEach(Si),n=r[0],n.x=-n.r,n.y=0,e(n),u>1&&(i=r[1],i.x=i.r,i.y=0,e(i),u>2))for(a=r[2],Pi(n,i,a),e(a),Mi(n,a),n._pack_prev=a,Mi(a,i),i=n._pack_next,o=3;u>o;o++){Pi(n,i,a=r[o]);var d=0,g=1,v=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(Ei(s,a)){d=1;break}if(1==d)for(l=n._pack_prev;l!==s._pack_prev&&!Ei(l,a);l=l._pack_prev,v++);d?(v>g||g==v&&i.ro;o++)a=r[o],a.x-=m,a.y-=y,b=Math.max(b,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=b,r.forEach(Ci)}}function Si(t){t._pack_next=t._pack_prev=t}function Ci(t){delete t._pack_next,delete t._pack_prev}function zi(t,e,r,n){var i=t.children;if(t.x=e+=n*t.x,t.y=r+=n*t.y,t.r*=n,i)for(var a=-1,o=i.length;++a=0;)e=i[a],e.z+=r,e.m+=r,r+=e.s+(n+=e.c)}function Fi(t,e,r){return t.a.parent===e.parent?t.a:r}function Di(t){return 1+uo.max(t,function(t){return t.y})}function Bi(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Ui(t){var e=t.children;return e&&e.length?Ui(e[0]):t}function Vi(t){var e,r=t.children;return r&&(e=r.length)?Vi(r[e-1]):t}function qi(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Gi(t,e){var r=t.x+e[3],n=t.y+e[0],i=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return 0>i&&(r+=i/2,i=0),0>a&&(n+=a/2,a=0),{x:r,y:n,dx:i,dy:a}}function Hi(t){var e=t[0],r=t[t.length-1];return r>e?[e,r]:[r,e]}function Yi(t){return t.rangeExtent?t.rangeExtent():Hi(t.range())}function Xi(t,e,r,n){var i=r(t[0],t[1]),a=n(e[0],e[1]);return function(t){return a(i(t))}}function Wi(t,e){var r,n=0,i=t.length-1,a=t[n],o=t[i];return a>o&&(r=n,n=i,i=r,r=a,a=o,o=r),t[n]=e.floor(a),t[i]=e.ceil(o),t}function Zi(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:Tl}function Ki(t,e,r,n){var i=[],a=[],o=0,s=Math.min(t.length,e.length)-1;for(t[s]2?Ki:Xi,l=n?$n:Kn;return o=i(t,e,l,r),s=i(e,t,l,_n),a}function a(t){return o(t)}var o,s;return a.invert=function(t){return s(t)},a.domain=function(e){return arguments.length?(t=e.map(Number),i()):t},a.range=function(t){return arguments.length?(e=t,i()):e},a.rangeRound=function(t){return a.range(t).interpolate(Dn)},a.clamp=function(t){return arguments.length?(n=t,i()):n},a.interpolate=function(t){return arguments.length?(r=t,i()):r},a.ticks=function(e){return ea(t,e)},a.tickFormat=function(e,r){return ra(t,e,r)},a.nice=function(e){return Ji(t,e),i()},a.copy=function(){return $i(t,e,r,n)},i()}function Qi(t,e){return uo.rebind(t,e,"range","rangeRound","interpolate","clamp")}function Ji(t,e){return Wi(t,Zi(ta(t,e)[2])),Wi(t,Zi(ta(t,e)[2])),t}function ta(t,e){null==e&&(e=10);var r=Hi(t),n=r[1]-r[0],i=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),a=e/n*i;return.15>=a?i*=10:.35>=a?i*=5:.75>=a&&(i*=2),r[0]=Math.ceil(r[0]/i)*i,r[1]=Math.floor(r[1]/i)*i+.5*i,r[2]=i,r}function ea(t,e){return uo.range.apply(uo,ta(t,e))}function ra(t,e,r){var n=ta(t,e);if(r){var i=ds.exec(r);if(i.shift(),"s"===i[8]){var a=uo.formatPrefix(Math.max(wo(n[0]),wo(n[1])));return i[7]||(i[7]="."+na(a.scale(n[2]))),i[8]="f",r=uo.format(i.join("")),function(t){return r(a.scale(t))+a.symbol}}i[7]||(i[7]="."+ia(i[8],n)),r=i.join("")}else r=",."+na(n[2])+"f";return uo.format(r)}function na(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function ia(t,e){var r=na(e[2]);return t in El?Math.abs(r-na(Math.max(wo(e[0]),wo(e[1]))))+ +("e"!==t):r-2*("%"===t)}function aa(t,e,r,n){function i(t){return(r?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function a(t){return r?Math.pow(e,t):-Math.pow(e,-t)}function o(e){return t(i(e))}return o.invert=function(e){return a(t.invert(e))},o.domain=function(e){return arguments.length?(r=e[0]>=0,t.domain((n=e.map(Number)).map(i)),o):n},o.base=function(r){return arguments.length?(e=+r,t.domain(n.map(i)),o):e},o.nice=function(){var e=Wi(n.map(i),r?Math:Sl);return t.domain(e),n=e.map(a),o},o.ticks=function(){var t=Hi(n),o=[],s=t[0],l=t[1],u=Math.floor(i(s)),c=Math.ceil(i(l)),f=e%1?2:e;if(isFinite(c-u)){if(r){for(;c>u;u++)for(var h=1;f>h;h++)o.push(a(u)*h);o.push(a(u))}else for(o.push(a(u));u++0;h--)o.push(a(u)*h);for(u=0;o[u]l;c--);o=o.slice(u,c)}return o},o.tickFormat=function(t,r){if(!arguments.length)return Ll;arguments.length<2?r=Ll:"function"!=typeof r&&(r=uo.format(r));var n=Math.max(1,e*t/o.ticks().length);return function(t){var o=t/a(Math.round(i(t)));return e-.5>o*e&&(o*=e),n>=o?r(t):""}},o.copy=function(){return aa(t.copy(),e,r,n)},Qi(o,t)}function oa(t,e,r){function n(e){return t(i(e))}var i=sa(e),a=sa(1/e);return n.invert=function(e){return a(t.invert(e))},n.domain=function(e){return arguments.length?(t.domain((r=e.map(Number)).map(i)),n):r},n.ticks=function(t){return ea(r,t)},n.tickFormat=function(t,e){return ra(r,t,e)},n.nice=function(t){return n.domain(Ji(r,t))},n.exponent=function(o){return arguments.length?(i=sa(e=o),a=sa(1/e),t.domain(r.map(i)),n):e},n.copy=function(){return oa(t.copy(),e,r)},Qi(n,t)}function sa(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function la(t,e){function r(r){return a[((i.get(r)||("range"===e.t?i.set(r,t.push(r)):NaN))-1)%a.length]}function n(e,r){return uo.range(t.length).map(function(t){return e+r*t})}var i,a,o;return r.domain=function(n){if(!arguments.length)return t;t=[],i=new f;for(var a,o=-1,s=n.length;++or?[NaN,NaN]:[r>0?s[r-1]:t[0],re?NaN:e/a+t,[e,e+1/a]},n.copy=function(){return ca(t,e,r)},i()}function fa(t,e){function r(r){return r>=r?e[uo.bisect(t,r)]:void 0}return r.domain=function(e){return arguments.length?(t=e,r):t},r.range=function(t){return arguments.length?(e=t,r):e},r.invertExtent=function(r){return r=e.indexOf(r),[t[r-1],t[r]]},r.copy=function(){return fa(t,e)},r}function ha(t){function e(t){return+t}return e.invert=e,e.domain=e.range=function(r){return arguments.length?(t=r.map(e),e):t},e.ticks=function(e){return ea(t,e)},e.tickFormat=function(e,r){return ra(t,e,r)},e.copy=function(){return ha(t)},e}function pa(){return 0}function da(t){return t.innerRadius}function ga(t){return t.outerRadius}function va(t){return t.startAngle}function ma(t){return t.endAngle}function ya(t){return t&&t.padAngle}function ba(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function xa(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,f=t[1]+u,h=e[0]+l,p=e[1]+u,d=(c+h)/2,g=(f+p)/2,v=h-c,m=p-f,y=v*v+m*m,b=r-n,x=c*p-h*f,_=(0>m?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,k=(-x*v-m*_)/y,A=(x*m+v*_)/y,M=(-x*v+m*_)/y,T=w-d,E=k-g,L=A-d,S=M-g;return T*T+E*E>L*L+S*S&&(w=A,k=M),[[w-l,k-u],[w*r/b,k*r/b]]}function _a(t){function e(e){function o(){u.push("M",a(t(c),s))}for(var l,u=[],c=[],f=-1,h=e.length,p=Lt(r),d=Lt(n);++f1?t.join("L"):t+"Z"}function ka(t){return t.join("L")+"Z"}function Aa(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1&&i.push("H",n[0]),i.join("")}function Ma(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;u9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));for(s=-1;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}function Ua(t){return t.length<3?wa(t):t[0]+Ca(t,Ba(t))}function Va(t){for(var e,r,n,i=-1,a=t.length;++i=e?o(t-e):void(u.c=o)}function o(r){var i=d.active,a=d[i];a&&(a.timer.c=null,a.timer.t=NaN,--d.count,delete d[i],a.event&&a.event.interrupt.call(t,t.__data__,a.index));for(var o in d)if(n>+o){var f=d[o];f.timer.c=null,f.timer.t=NaN,--d.count,delete d[o]}u.c=s,Rt(function(){return u.c&&s(r||1)&&(u.c=null,u.t=NaN),1},0,l),d.active=n,g.event&&g.event.start.call(t,t.__data__,e),p=[],g.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&p.push(n)}),h=g.ease,c=g.duration}function s(i){for(var a=i/c,o=h(a),s=p.length;s>0;)p[--s].call(t,o);return a>=1?(g.event&&g.event.end.call(t,t.__data__,e),--d.count?delete d[n]:delete t[r],1):void 0}var l,u,c,h,p,d=t[r]||(t[r]={active:0,count:0}),g=d[n];g||(l=i.time,u=Rt(a,0,l),g=d[n]={tween:new f,time:l,timer:u,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++d.count)}function ro(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function no(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}function io(t){return t.toISOString()}function ao(t,e,r){function n(e){return t(e)}function i(t,r){var n=t[1]-t[0],i=n/r,a=uo.bisect(tu,i);return a==tu.length?[e.year,ta(t.map(function(t){return t/31536e6}),r)[2]]:a?e[i/tu[a-1]1?{floor:function(e){for(;r(e=t.floor(e));)e=oo(e-1);return e},ceil:function(e){for(;r(e=t.ceil(e));)e=oo(+e+1);return e}}:t))},n.ticks=function(t,e){var r=Hi(n.domain()),a=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return a&&(t=a[0],e=a[1]),t.range(r[0],oo(+r[1]+1),1>e?1:e)},n.tickFormat=function(){return r},n.copy=function(){return ao(t.copy(),e,r)},Qi(n,t)}function oo(t){return new Date(t)}function so(t){return JSON.parse(t.responseText)}function lo(t){var e=ho.createRange();return e.selectNode(ho.body),e.createContextualFragment(t.responseText)}var uo={version:"3.5.17"},co=[].slice,fo=function(t){return co.call(t)},ho=this.document;if(ho)try{fo(ho.documentElement.childNodes)[0].nodeType}catch(po){fo=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),ho)try{ho.createElement("DIV").style.setProperty("opacity",0,"")}catch(go){var vo=this.Element.prototype,mo=vo.setAttribute,yo=vo.setAttributeNS,bo=this.CSSStyleDeclaration.prototype,xo=bo.setProperty;vo.setAttribute=function(t,e){mo.call(this,t,e+"")},vo.setAttributeNS=function(t,e,r){yo.call(this,t,e,r+"")},bo.setProperty=function(t,e,r){xo.call(this,t,e+"",r)}}uo.ascending=i,uo.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:NaN},uo.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},uo.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},uo.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}else{for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}return[r,i]},uo.sum=function(t,e){var r,n=0,i=t.length,a=-1;if(1===arguments.length)for(;++a1?l/(c-1):void 0},uo.deviation=function(){var t=uo.variance.apply(this,arguments);return t?Math.sqrt(t):t};var _o=s(i);uo.bisectLeft=_o.left,uo.bisect=uo.bisectRight=_o.right,uo.bisector=function(t){return s(1===t.length?function(e,r){return i(t(e),r)}:t)},uo.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,2>a&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},uo.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},uo.pairs=function(t){for(var e,r=0,n=t.length-1,i=t[0],a=new Array(0>n?0:n);n>r;)a[r]=[e=i,i=t[++r]];return a},uo.transpose=function(t){if(!(i=t.length))return[];for(var e=-1,r=uo.min(t,l),n=new Array(r);++e=0;)for(n=t[i],e=n.length;--e>=0;)r[--o]=n[e];return r};var wo=Math.abs;uo.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r===1/0)throw new Error("infinite range");var n,i=[],a=u(wo(r)),o=-1;if(t*=a,e*=a,r*=a,0>r)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=a.length)return n?n.call(i,o):r?o.sort(r):o;for(var l,u,c,h,p=-1,d=o.length,g=a[s++],v=new f;++p=a.length)return t;var n=[],i=o[r++];return t.forEach(function(t,i){n.push({key:t,values:e(i,r)})}),i?n.sort(function(t,e){return i(t.key,e.key)}):n}var r,n,i={},a=[],o=[];return i.map=function(e,r){return t(r,e,0)},i.entries=function(r){return e(t(uo.map,r,0),0)},i.key=function(t){return a.push(t),i},i.sortKeys=function(t){return o[a.length-1]=t,i},i.sortValues=function(t){return r=t,i},i.rollup=function(t){return n=t,i},i},uo.set=function(t){var e=new b;if(t)for(var r=0,n=t.length;n>r;++r)e.add(t[r]);return e},c(b,{has:d,add:function(t){return this._[h(t+="")]=!0,t},remove:g,values:v,size:m,empty:y,forEach:function(t){for(var e in this._)t.call(this,p(e))}}),uo.behavior={},uo.rebind=function(t,e){for(var r,n=1,i=arguments.length;++n=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},uo.event=null,uo.requote=function(t){return t.replace(To,"\\$&")};var To=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Eo={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]},Lo=function(t,e){return e.querySelector(t)},So=function(t,e){return e.querySelectorAll(t)},Co=function(t,e){var r=t.matches||t[w(t,"matchesSelector")];return(Co=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(Lo=function(t,e){return Sizzle(t,e)[0]||null},So=Sizzle,Co=Sizzle.matchesSelector),uo.selection=function(){return uo.select(ho.documentElement)};var zo=uo.selection.prototype=[];zo.select=function(t){var e,r,n,i,a=[];t=C(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),Ro.hasOwnProperty(r)?{space:Ro[r],local:t}:t}},zo.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node();return t=uo.ns.qualify(t),t.local?r.getAttributeNS(t.space,t.local):r.getAttribute(t)}for(e in t)this.each(P(e,t[e]));return this}return this.each(P(t,e))},zo.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=O(t)).length,i=-1;if(e=r.classList){for(;++ii){if("string"!=typeof t){2>i&&(e="");for(r in t)this.each(F(r,t[r],e));return this}if(2>i){var a=this.node();return n(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(F(t,e,r))},zo.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(D(e,t[e]));return this}return this.each(D(t,e))},zo.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},zo.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},zo.append=function(t){return t=B(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},zo.insert=function(t,e){return t=B(t),e=C(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},zo.remove=function(){return this.each(U)},zo.data=function(t,e){function r(t,r){var n,i,a,o=t.length,c=r.length,h=Math.min(o,c),p=new Array(c),d=new Array(c),g=new Array(o);if(e){var v,m=new f,y=new Array(o);for(n=-1;++nn;++n)d[n]=V(r[n]);for(;o>n;++n)g[n]=t[n]}d.update=p,d.parentNode=p.parentNode=g.parentNode=t.parentNode,s.push(d),l.push(p),u.push(g)}var n,i,a=-1,o=this.length;if(!arguments.length){for(t=new Array(o=(n=this[0]).length);++aa;a++){i.push(e=[]),e.parentNode=(r=this[a]).parentNode;for(var s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return S(i)},zo.order=function(){for(var t=-1,e=this.length;++t=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},zo.sort=function(t){t=G.apply(this,arguments);for(var e=-1,r=this.length;++et;t++)for(var r=this[t],n=0,i=r.length;i>n;n++){var a=r[n];if(a)return a}return null},zo.size=function(){var t=0;return H(this,function(){++t}),t};var jo=[];uo.selection.enter=Y,uo.selection.enter.prototype=jo,jo.append=zo.append,jo.empty=zo.empty,jo.node=zo.node,jo.call=zo.call,jo.size=zo.size,jo.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++sn){if("string"!=typeof t){2>n&&(e=!1);for(r in t)this.each(W(r,t[r],e));return this}if(2>n)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(W(t,e,r))};var Oo=uo.map({mouseenter:"mouseover",mouseleave:"mouseout"});ho&&Oo.forEach(function(t){"on"+t in ho&&Oo.remove(t)});var Io,No=0;uo.mouse=function(t){return Q(t,E())};var Fo=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;uo.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=E().changedTouches),e)for(var n,i=0,a=e.length;a>i;++i)if((n=e[i]).identifier===r)return Q(t,n)},uo.behavior.drag=function(){function t(){this.on("mousedown.drag",a).on("touchstart.drag",o)}function e(t,e,n,a,o){return function(){function s(){var t,r,n=e(h,g);n&&(t=n[0]-b[0],r=n[1]-b[1],d|=t|r,b=n,p({type:"drag",x:n[0]+u[0],y:n[1]+u[1],dx:t,dy:r}))}function l(){e(h,g)&&(m.on(a+v,null).on(o+v,null),y(d),p({type:"dragend"}))}var u,c=this,f=uo.event.target.correspondingElement||uo.event.target,h=c.parentNode,p=r.of(c,arguments),d=0,g=t(),v=".drag"+(null==g?"":"-"+g),m=uo.select(n(f)).on(a+v,s).on(o+v,l),y=$(f),b=e(h,g);i?(u=i.apply(c,arguments),u=[u.x-b[0],u.y-b[1]]):u=[0,0],p({type:"dragstart"})}}var r=L(t,"drag","dragstart","dragend"),i=null,a=e(k,uo.mouse,n,"mousemove","mouseup"),o=e(J,uo.touch,x,"touchmove","touchend");return t.origin=function(e){return arguments.length?(i=e,t):i},uo.rebind(t,r,"on")},uo.touches=function(t,e){return arguments.length<2&&(e=E().touches),e?fo(e).map(function(e){var r=Q(t,e);return r.identifier=e.identifier,r}):[]};var Do=1e-6,Bo=Do*Do,Uo=Math.PI,Vo=2*Uo,qo=Vo-Do,Go=Uo/2,Ho=Uo/180,Yo=180/Uo,Xo=Math.SQRT2,Wo=2,Zo=4;uo.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,f=l-a,h=c*c+f*f;if(Bo>h)n=Math.log(u/o)/Xo,r=function(t){return[i+t*c,a+t*f,o*Math.exp(Xo*t*n)]};else{var p=Math.sqrt(h),d=(u*u-o*o+Zo*h)/(2*o*Wo*p),g=(u*u-o*o-Zo*h)/(2*u*Wo*p),v=Math.log(Math.sqrt(d*d+1)-d),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/Xo,r=function(t){var e=t*n,r=at(v),s=o/(Wo*p)*(r*ot(Xo*e+v)-it(v));return[i+s*c,a+s*f,o*r/at(Xo*e+v)]}}return r.duration=1e3*n,r},uo.behavior.zoom=function(){function t(t){t.on(z,f).on($o+".zoom",p).on("dblclick.zoom",d).on(j,h)}function e(t){return[(t[0]-A.x)/A.k,(t[1]-A.y)/A.k]}function r(t){return[t[0]*A.k+A.x,t[1]*A.k+A.y]}function i(t){A.k=Math.max(E[0],Math.min(E[1],t))}function a(t,e){e=r(e),A.x+=t[0]-e[0],A.y+=t[1]-e[1]}function o(e,r,n,o){e.__chart__={x:A.x,y:A.y,k:A.k},i(Math.pow(2,o)),a(v=r,n),e=uo.select(e),S>0&&(e=e.transition().duration(S)),e.call(t.event)}function s(){_&&_.domain(x.range().map(function(t){return(t-A.x)/A.k}).map(x.invert)),k&&k.domain(w.range().map(function(t){return(t-A.y)/A.k}).map(w.invert))}function l(t){C++||t({type:"zoomstart"})}function u(t){s(),t({type:"zoom",scale:A.k,translate:[A.x,A.y]})}function c(t){--C||(t({type:"zoomend"}),v=null)}function f(){function t(){s=1,a(uo.mouse(i),h),u(o)}function r(){f.on(P,null).on(R,null),p(s),c(o)}var i=this,o=O.of(i,arguments),s=0,f=uo.select(n(i)).on(P,t).on(R,r),h=e(uo.mouse(i)),p=$(i);Gl.call(i),l(o)}function h(){function t(){var t=uo.touches(d);return p=A.k,t.forEach(function(t){t.identifier in v&&(v[t.identifier]=e(t))}),t}function r(){var e=uo.event.target;uo.select(e).on(x,n).on(_,s),w.push(e);for(var r=uo.event.changedTouches,i=0,a=r.length;a>i;++i)v[r[i].identifier]=null;var l=t(),u=Date.now();if(1===l.length){if(500>u-b){var c=l[0];o(d,c,v[c.identifier],Math.floor(Math.log(A.k)/Math.LN2)+1),T()}b=u}else if(l.length>1){var c=l[0],f=l[1],h=c[0]-f[0],p=c[1]-f[1];m=h*h+p*p}}function n(){var t,e,r,n,o=uo.touches(d);Gl.call(d);for(var s=0,l=o.length;l>s;++s,n=null)if(r=o[s],n=v[r.identifier]){if(e)break;t=r,e=n}if(n){var c=(c=r[0]-t[0])*c+(c=r[1]-t[1])*c,f=m&&Math.sqrt(c/m);t=[(t[0]+r[0])/2,(t[1]+r[1])/2],e=[(e[0]+n[0])/2,(e[1]+n[1])/2],i(f*p)}b=null,a(t,e),u(g)}function s(){if(uo.event.touches.length){for(var e=uo.event.changedTouches,r=0,n=e.length;n>r;++r)delete v[e[r].identifier];for(var i in v)return void t()}uo.selectAll(w).on(y,null),k.on(z,f).on(j,h),M(),c(g)}var p,d=this,g=O.of(d,arguments),v={},m=0,y=".zoom-"+uo.event.changedTouches[0].identifier,x="touchmove"+y,_="touchend"+y,w=[],k=uo.select(d),M=$(d);r(),l(g),k.on(z,null).on(j,r)}function p(){var t=O.of(this,arguments);y?clearTimeout(y):(Gl.call(this),g=e(v=m||uo.mouse(this)),l(t)),y=setTimeout(function(){y=null,c(t)},50),T(),i(Math.pow(2,.002*Ko())*A.k),a(v,g),u(t)}function d(){var t=uo.mouse(this),r=Math.log(A.k)/Math.LN2;o(this,t,e(t),uo.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}var g,v,m,y,b,x,_,w,k,A={x:0,y:0,k:1},M=[960,500],E=Qo,S=250,C=0,z="mousedown.zoom",P="mousemove.zoom",R="mouseup.zoom",j="touchstart.zoom",O=L(t,"zoomstart","zoom","zoomend");return $o||($o="onwheel"in ho?(Ko=function(){return-uo.event.deltaY*(uo.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ho?(Ko=function(){return uo.event.wheelDelta},"mousewheel"):(Ko=function(){return-uo.event.detail},"MozMousePixelScroll")),t.event=function(t){t.each(function(){var t=O.of(this,arguments),e=A;Vl?uo.select(this).transition().each("start.zoom",function(){A=this.__chart__||{x:0,y:0,k:1},l(t)}).tween("zoom:zoom",function(){var r=M[0],n=M[1],i=v?v[0]:r/2,a=v?v[1]:n/2,o=uo.interpolateZoom([(i-A.x)/A.k,(a-A.y)/A.k,r/A.k],[(i-e.x)/e.k,(a-e.y)/e.k,r/e.k]);return function(e){var n=o(e),s=r/n[2];this.__chart__=A={x:i-n[0]*s,y:a-n[1]*s,k:s},u(t)}}).each("interrupt.zoom",function(){c(t)}).each("end.zoom",function(){c(t)}):(this.__chart__=A,l(t),u(t),c(t))})},t.translate=function(e){return arguments.length?(A={x:+e[0],y:+e[1],k:A.k},s(),t):[A.x,A.y]},t.scale=function(e){return arguments.length?(A={x:A.x,y:A.y,k:null},i(+e),s(),t):A.k},t.scaleExtent=function(e){return arguments.length?(E=null==e?Qo:[+e[0],+e[1]],t):E},t.center=function(e){return arguments.length?(m=e&&[+e[0],+e[1]],t):m},t.size=function(e){return arguments.length?(M=e&&[+e[0],+e[1]],t):M},t.duration=function(e){return arguments.length?(S=+e,t):S},t.x=function(e){return arguments.length?(_=e,x=e.copy(),A={x:0,y:0,k:1},t):_},t.y=function(e){return arguments.length?(k=e,w=e.copy(),A={x:0,y:0,k:1},t):k},uo.rebind(t,O,"on")};var Ko,$o,Qo=[0,1/0];uo.color=lt,lt.prototype.toString=function(){return this.rgb()+""},uo.hsl=ut;var Jo=ut.prototype=new lt;Jo.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new ut(this.h,this.s,this.l/t)},Jo.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new ut(this.h,this.s,t*this.l)},Jo.rgb=function(){return ct(this.h,this.s,this.l)},uo.hcl=ft;var ts=ft.prototype=new lt;ts.brighter=function(t){return new ft(this.h,this.c,Math.min(100,this.l+es*(arguments.length?t:1)))},ts.darker=function(t){return new ft(this.h,this.c,Math.max(0,this.l-es*(arguments.length?t:1)))},ts.rgb=function(){return ht(this.h,this.c,this.l).rgb()},uo.lab=pt;var es=18,rs=.95047,ns=1,is=1.08883,as=pt.prototype=new lt;as.brighter=function(t){return new pt(Math.min(100,this.l+es*(arguments.length?t:1)),this.a,this.b)},as.darker=function(t){return new pt(Math.max(0,this.l-es*(arguments.length?t:1)),this.a,this.b)},as.rgb=function(){return dt(this.l,this.a,this.b)},uo.rgb=bt;var os=bt.prototype=new lt;os.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&i>e&&(e=i),r&&i>r&&(r=i),n&&i>n&&(n=i),new bt(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new bt(i,i,i)},os.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new bt(t*this.r,t*this.g,t*this.b)},os.hsl=function(){return At(this.r,this.g,this.b)},os.toString=function(){return"#"+wt(this.r)+wt(this.g)+wt(this.b)};var ss=uo.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});ss.forEach(function(t,e){ss.set(t,xt(e))}),uo.functor=Lt,uo.xhr=St(x),uo.dsv=function(t,e){function r(t,r,a){arguments.length<3&&(a=r,r=null);var o=Ct(t,e,null==r?n:i(r),a);return o.row=function(t){return arguments.length?o.response(null==(r=t)?n:i(t)):r},o}function n(t){return r.parse(t.responseText)}function i(t){return function(e){return r.parse(e.responseText,t)}}function a(e){return e.map(o).join(t)}function o(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);return r.parse=function(t,e){var n;return r.parseRows(t,function(t,r){if(n)return n(t,r-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");n=e?function(t,r){return e(i(t),r)}:i})},r.parseRows=function(t,e){function r(){if(c>=u)return o;if(i)return i=!1,a;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++c;){var n=t.charCodeAt(c++),s=1;if(10===n)i=!0;else if(13===n)i=!0,10===t.charCodeAt(c)&&(++c,++s);else if(n!==l)continue;return t.slice(e,c-s)}return t.slice(e)}for(var n,i,a={},o={},s=[],u=t.length,c=0,f=0;(n=r())!==o;){for(var h=[];n!==a&&n!==o;)h.push(n),n=r();e&&null==(h=e(h,f++))||s.push(h)}return s},r.format=function(e){if(Array.isArray(e[0]))return r.formatRows(e);var n=new b,i=[];return e.forEach(function(t){for(var e in t)n.has(e)||i.push(n.add(e))}),[i.map(o).join(t)].concat(e.map(function(e){return i.map(function(t){return o(e[t])}).join(t)})).join("\n")},r.formatRows=function(t){return t.map(a).join("\n")},r},uo.csv=uo.dsv(",","text/csv"),uo.tsv=uo.dsv(" ","text/tab-separated-values");var ls,us,cs,fs,hs=this[w(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};uo.timer=function(){Rt.apply(this,arguments)},uo.timer.flush=function(){Ot(),It()},uo.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var ps=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Ft);uo.formatPrefix=function(t,e){var r=0;return(t=+t)&&(0>t&&(t*=-1),e&&(t=uo.round(t,Nt(t,e))),r=1+Math.floor(1e-12+Math.log(t)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),ps[8+r/3]};var ds=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,gs=uo.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=uo.round(t,Nt(t,e))).toFixed(Math.max(0,Math.min(20,Nt(t*(1+1e-15),e))))}}),vs=uo.time={},ms=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ys.setUTCDate.apply(this._,arguments)},setDay:function(){ys.setUTCDay.apply(this._,arguments)},setFullYear:function(){ys.setUTCFullYear.apply(this._,arguments)},setHours:function(){ys.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ys.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ys.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ys.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ +ys.setUTCSeconds.apply(this._,arguments)},setTime:function(){ys.setTime.apply(this._,arguments)}};var ys=Date.prototype;vs.year=Vt(function(t){return t=vs.day(t),t.setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),vs.years=vs.year.range,vs.years.utc=vs.year.utc.range,vs.day=Vt(function(t){var e=new ms(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),vs.days=vs.day.range,vs.days.utc=vs.day.utc.range,vs.dayOfYear=function(t){var e=vs.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=vs[t]=Vt(function(t){return(t=vs.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});vs[t+"s"]=r.range,vs[t+"s"].utc=r.utc.range,vs[t+"OfYear"]=function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)}}),vs.week=vs.sunday,vs.weeks=vs.sunday.range,vs.weeks.utc=vs.sunday.utc.range,vs.weekOfYear=vs.sundayOfYear;var bs={"-":"",_:" ",0:"0"},xs=/^\s*\d+/,_s=/^%/;uo.locale=function(t){return{numberFormat:Dt(t),timeFormat:Gt(t)}};var ws=uo.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});uo.format=ws.numberFormat,uo.geo={},fe.prototype={s:0,t:0,add:function(t){he(t,this.t,ks),he(ks.s,this.s,this),this.s?this.t+=ks.t:this.s=ks.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ks=new fe;uo.geo.stream=function(t,e){t&&As.hasOwnProperty(t.type)?As[t.type](t,e):pe(t,e)};var As={Feature:function(t,e){pe(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++nt?4*Uo+t:t,Ls.lineStart=Ls.lineEnd=Ls.point=k}};uo.geo.bounds=function(){function t(t,e){b.push(x=[c=t,h=t]),f>e&&(f=e),e>p&&(p=e)}function e(e,r){var n=me([e*Ho,r*Ho]);if(m){var i=be(m,n),a=[i[1],-i[0],0],o=be(a,i);we(o),o=ke(o);var l=e-d,u=l>0?1:-1,g=o[0]*Yo*u,v=wo(l)>180;if(v^(g>u*d&&u*e>g)){var y=o[1]*Yo;y>p&&(p=y)}else if(g=(g+360)%360-180,v^(g>u*d&&u*e>g)){var y=-o[1]*Yo;f>y&&(f=y)}else f>r&&(f=r),r>p&&(p=r);v?d>e?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e):h>=c?(c>e&&(c=e),e>h&&(h=e)):e>d?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e)}else t(e,r);m=n,d=e}function r(){_.point=e}function n(){x[0]=c,x[1]=h,_.point=t,m=null}function i(t,r){if(m){var n=t-d;y+=wo(n)>180?n+(n>0?360:-360):n}else g=t,v=r;Ls.point(t,r),e(t,r)}function a(){Ls.lineStart()}function o(){i(g,v),Ls.lineEnd(),wo(y)>Do&&(c=-(h=180)),x[0]=c,x[1]=h,m=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function u(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:tEs?(c=-(h=180),f=-(p=90)):y>Do?p=90:-Do>y&&(f=-90),x[0]=c,x[1]=h}};return function(t){p=h=-(c=f=1/0),b=[],uo.geo.stream(t,_);var e=b.length;if(e){b.sort(l);for(var r,n=1,i=b[0],a=[i];e>n;++n)r=b[n],u(r[0],i)||u(r[1],i)?(s(i[0],r[1])>s(i[0],i[1])&&(i[1]=r[1]),s(r[0],i[1])>s(i[0],i[1])&&(i[0]=r[0])):a.push(i=r);for(var o,r,d=-(1/0),e=a.length-1,n=0,i=a[e];e>=n;i=r,++n)r=a[n],(o=s(i[1],r[0]))>d&&(d=o,c=r[0],h=i[1])}return b=x=null,c===1/0||f===1/0?[[NaN,NaN],[NaN,NaN]]:[[c,f],[h,p]]}}(),uo.geo.centroid=function(t){Ss=Cs=zs=Ps=Rs=js=Os=Is=Ns=Fs=Ds=0,uo.geo.stream(t,Bs);var e=Ns,r=Fs,n=Ds,i=e*e+r*r+n*n;return Bo>i&&(e=js,r=Os,n=Is,Do>Cs&&(e=zs,r=Ps,n=Rs),i=e*e+r*r+n*n,Bo>i)?[NaN,NaN]:[Math.atan2(r,e)*Yo,nt(n/Math.sqrt(i))*Yo]};var Ss,Cs,zs,Ps,Rs,js,Os,Is,Ns,Fs,Ds,Bs={sphere:k,point:Me,lineStart:Ee,lineEnd:Le,polygonStart:function(){Bs.lineStart=Se},polygonEnd:function(){Bs.lineStart=Ee}},Us=Oe(ze,De,Ue,[-Uo,-Uo/2]),Vs=1e9;uo.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),i=a(t),i.valid=!0,i},extent:function(s){return arguments.length?(a=He(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(uo.geo.conicEqualArea=function(){return Ye(Xe)}).raw=Xe,uo.geo.albers=function(){return uo.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},uo.geo.albersUsa=function(){function t(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}var e,r,n,i,a=uo.geo.albers(),o=uo.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=uo.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};return t.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&.234>i&&n>=-.425&&-.214>n?o:i>=.166&&.234>i&&n>=-.214&&-.115>n?s:a).invert(t)},t.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},t.precision=function(e){return arguments.length?(a.precision(e),o.precision(e),s.precision(e),t):a.precision()},t.scale=function(e){return arguments.length?(a.scale(e),o.scale(.35*e),s.scale(e),t.translate(a.translate())):a.scale()},t.translate=function(e){if(!arguments.length)return a.translate();var u=a.scale(),c=+e[0],f=+e[1];return r=a.translate(e).clipExtent([[c-.455*u,f-.238*u],[c+.455*u,f+.238*u]]).stream(l).point,n=o.translate([c-.307*u,f+.201*u]).clipExtent([[c-.425*u+Do,f+.12*u+Do],[c-.214*u-Do,f+.234*u-Do]]).stream(l).point,i=s.translate([c-.205*u,f+.212*u]).clipExtent([[c-.214*u+Do,f+.166*u+Do],[c-.115*u-Do,f+.234*u-Do]]).stream(l).point,t},t.scale(1070)};var qs,Gs,Hs,Ys,Xs,Ws,Zs={point:k,lineStart:k,lineEnd:k,polygonStart:function(){Gs=0,Zs.lineStart=We},polygonEnd:function(){Zs.lineStart=Zs.lineEnd=Zs.point=k,qs+=wo(Gs/2)}},Ks={point:Ze,lineStart:k,lineEnd:k,polygonStart:k,polygonEnd:k},$s={point:Qe,lineStart:Je,lineEnd:tr,polygonStart:function(){$s.lineStart=er},polygonEnd:function(){$s.point=Qe,$s.lineStart=Je,$s.lineEnd=tr}};uo.geo.path=function(){function t(t){return t&&("function"==typeof s&&a.pointRadius(+s.apply(this,arguments)),o&&o.valid||(o=i(a)),uo.geo.stream(t,o)),a.result()}function e(){return o=null,t}var r,n,i,a,o,s=4.5;return t.area=function(t){return qs=0,uo.geo.stream(t,i(Zs)),qs},t.centroid=function(t){return zs=Ps=Rs=js=Os=Is=Ns=Fs=Ds=0,uo.geo.stream(t,i($s)),Ds?[Ns/Ds,Fs/Ds]:Is?[js/Is,Os/Is]:Rs?[zs/Rs,Ps/Rs]:[NaN,NaN]},t.bounds=function(t){return Xs=Ws=-(Hs=Ys=1/0),uo.geo.stream(t,i(Ks)),[[Hs,Ys],[Xs,Ws]]},t.projection=function(t){return arguments.length?(i=(r=t)?t.stream||ir(t):x,e()):r},t.context=function(t){return arguments.length?(a=null==(n=t)?new Ke:new rr(t),"function"!=typeof s&&a.pointRadius(s),e()):n},t.pointRadius=function(e){return arguments.length?(s="function"==typeof e?e:(a.pointRadius(+e),+e),t):s},t.projection(uo.geo.albersUsa()).context(null)},uo.geo.transform=function(t){return{stream:function(e){var r=new ar(e);for(var n in t)r[n]=t[n];return r}}},ar.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},uo.geo.projection=sr,uo.geo.projectionMutator=lr,(uo.geo.equirectangular=function(){return sr(cr)}).raw=cr.invert=cr,uo.geo.rotation=function(t){function e(e){return e=t(e[0]*Ho,e[1]*Ho),e[0]*=Yo,e[1]*=Yo,e}return t=hr(t[0]%360*Ho,t[1]*Ho,t.length>2?t[2]*Ho:0),e.invert=function(e){return e=t.invert(e[0]*Ho,e[1]*Ho),e[0]*=Yo,e[1]*=Yo,e},e},fr.invert=cr,uo.geo.circle=function(){function t(){var t="function"==typeof n?n.apply(this,arguments):n,e=hr(-t[0]*Ho,-t[1]*Ho,0).invert,i=[];return r(null,null,1,{point:function(t,r){i.push(t=e(t,r)),t[0]*=Yo,t[1]*=Yo}}),{type:"Polygon",coordinates:[i]}}var e,r,n=[0,0],i=6;return t.origin=function(e){return arguments.length?(n=e,t):n},t.angle=function(n){return arguments.length?(r=vr((e=+n)*Ho,i*Ho),t):e},t.precision=function(n){return arguments.length?(r=vr(e*Ho,(i=+n)*Ho),t):i},t.angle(90)},uo.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ho,i=t[1]*Ho,a=e[1]*Ho,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),f=Math.cos(a);return Math.atan2(Math.sqrt((r=f*o)*r+(r=u*c-l*f*s)*r),l*c+u*f*s)},uo.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return uo.range(Math.ceil(a/v)*v,i,v).map(h).concat(uo.range(Math.ceil(u/m)*m,l,m).map(p)).concat(uo.range(Math.ceil(n/d)*d,r,d).filter(function(t){return wo(t%v)>Do}).map(c)).concat(uo.range(Math.ceil(s/g)*g,o,g).filter(function(t){return wo(t%m)>Do}).map(f))}var r,n,i,a,o,s,l,u,c,f,h,p,d=10,g=d,v=90,m=360,y=2.5;return t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})},t.outline=function(){return{type:"Polygon",coordinates:[h(a).concat(p(l).slice(1),h(i).reverse().slice(1),p(u).reverse().slice(1))]}},t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()},t.majorExtent=function(e){return arguments.length?(a=+e[0][0],i=+e[1][0],u=+e[0][1],l=+e[1][1],a>i&&(e=a,a=i,i=e),u>l&&(e=u,u=l,l=e),t.precision(y)):[[a,u],[i,l]]},t.minorExtent=function(e){return arguments.length?(n=+e[0][0],r=+e[1][0],s=+e[0][1],o=+e[1][1],n>r&&(e=n,n=r,r=e),s>o&&(e=s,s=o,o=e),t.precision(y)):[[n,s],[r,o]]},t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()},t.majorStep=function(e){return arguments.length?(v=+e[0],m=+e[1],t):[v,m]},t.minorStep=function(e){return arguments.length?(d=+e[0],g=+e[1],t):[d,g]},t.precision=function(e){return arguments.length?(y=+e,c=yr(s,o,90),f=br(n,r,y),h=yr(u,l,90),p=br(a,i,y),t):y},t.majorExtent([[-180,-90+Do],[180,90-Do]]).minorExtent([[-180,-80-Do],[180,80+Do]])},uo.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}var e,r,n=xr,i=_r;return t.distance=function(){return uo.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},t.source=function(r){return arguments.length?(n=r,e="function"==typeof r?null:r,t):n},t.target=function(e){return arguments.length?(i=e,r="function"==typeof e?null:e,t):i},t.precision=function(){return arguments.length?t:0},t},uo.geo.interpolate=function(t,e){return wr(t[0]*Ho,t[1]*Ho,e[0]*Ho,e[1]*Ho)},uo.geo.length=function(t){return Qs=0,uo.geo.stream(t,Js),Qs};var Qs,Js={sphere:k,point:k,lineStart:kr,lineEnd:k,polygonStart:k,polygonEnd:k},tl=Ar(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(uo.geo.azimuthalEqualArea=function(){return sr(tl)}).raw=tl;var el=Ar(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},x);(uo.geo.azimuthalEquidistant=function(){return sr(el)}).raw=el,(uo.geo.conicConformal=function(){return Ye(Mr)}).raw=Mr,(uo.geo.conicEquidistant=function(){return Ye(Tr)}).raw=Tr;var rl=Ar(function(t){return 1/t},Math.atan);(uo.geo.gnomonic=function(){return sr(rl)}).raw=rl,Er.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Go]},(uo.geo.mercator=function(){return Lr(Er)}).raw=Er;var nl=Ar(function(){return 1},Math.asin);(uo.geo.orthographic=function(){return sr(nl)}).raw=nl;var il=Ar(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(uo.geo.stereographic=function(){return sr(il)}).raw=il,Sr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Go]},(uo.geo.transverseMercator=function(){var t=Lr(Sr),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):(t=r(),[t[0],t[1],t[2]-90])},r([0,0,90])}).raw=Sr,uo.geom={},uo.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Lt(r),a=Lt(n),o=t.length,s=[],l=[];for(e=0;o>e;e++)s.push([+i.call(this,t[e],e),+a.call(this,t[e],e),e]);for(s.sort(Rr),e=0;o>e;e++)l.push([s[e][0],-s[e][1]]);var u=Pr(s),c=Pr(l),f=c[0]===u[0],h=c[c.length-1]===u[u.length-1],p=[];for(e=u.length-1;e>=0;--e)p.push(t[s[u[e]][2]]);for(e=+f;e=n&&u.x<=a&&u.y>=i&&u.y<=o?[[n,o],[a,o],[a,i],[n,i]]:[];c.point=t[s]}),e}function r(t){return t.map(function(t,e){return{x:Math.round(a(t,e)/Do)*Do,y:Math.round(o(t,e)/Do)*Do,i:e}})}var n=Cr,i=zr,a=n,o=i,s=pl;return t?e(t):(e.links=function(t){return un(r(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},e.triangles=function(t){var e=[];return un(r(t)).cells.forEach(function(r,n){for(var i,a,o=r.site,s=r.edges.sort(Yr),l=-1,u=s.length,c=s[u-1].edge,f=c.l===o?c.r:c.l;++l=u,h=n>=c,p=h<<1|f;t.leaf=!1,t=t.nodes[p]||(t.nodes[p]=dn()),f?i=u:s=u,h?o=c:l=c,a(t,e,r,n,i,o,s,l)}var c,f,h,p,d,g,v,m,y,b=Lt(s),x=Lt(l);if(null!=e)g=e,v=r,m=n,y=i;else if(m=y=-(g=v=1/0),f=[],h=[],d=t.length,o)for(p=0;d>p;++p)c=t[p],c.xm&&(m=c.x),c.y>y&&(y=c.y),f.push(c.x),h.push(c.y);else for(p=0;d>p;++p){var _=+b(c=t[p],p),w=+x(c,p);g>_&&(g=_),v>w&&(v=w),_>m&&(m=_),w>y&&(y=w),f.push(_),h.push(w)}var k=m-g,A=y-v;k>A?y=v+k:m=g+A;var M=dn();if(M.add=function(t){a(M,t,+b(t,++p),+x(t,p),g,v,m,y)},M.visit=function(t){gn(t,M,g,v,m,y)},M.find=function(t){return vn(M,t[0],t[1],g,v,m,y)},p=-1,null==e){for(;++p=0?t.slice(0,e):t,n=e>=0?t.slice(e+1):"in";return r=ml.get(r)||vl,n=yl.get(n)||x,kn(n(r.apply(null,co.call(arguments,1))))},uo.interpolateHcl=In,uo.interpolateHsl=Nn,uo.interpolateLab=Fn,uo.interpolateRound=Dn,uo.transform=function(t){var e=ho.createElementNS(uo.ns.prefix.svg,"g");return(uo.transform=function(t){if(null!=t){e.setAttribute("transform",t);var r=e.transform.baseVal.consolidate()}return new Bn(r?r.matrix:bl)})(t)},Bn.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var bl={a:1,b:0,c:0,d:1,e:0,f:0};uo.interpolateTransform=Zn,uo.layout={},uo.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++rs*s/m){if(g>l){var u=e.charge/l;t.px-=a*u,t.py-=o*u}return!0}if(e.point&&l&&g>l){var u=e.pointCharge/l;t.px-=a*u,t.py-=o*u}}return!e.charge}}function e(t){t.px=uo.event.x,t.py=uo.event.y,l.resume()}var r,n,i,a,o,s,l={},u=uo.dispatch("start","tick","end"),c=[1,1],f=.9,h=xl,p=_l,d=-30,g=wl,v=.1,m=.64,y=[],b=[];return l.tick=function(){if((i*=.99)<.005)return r=null,u.end({type:"end",alpha:i=0}),!0;var e,n,l,h,p,g,m,x,_,w=y.length,k=b.length;for(n=0;k>n;++n)l=b[n],h=l.source,p=l.target,x=p.x-h.x,_=p.y-h.y,(g=x*x+_*_)&&(g=i*o[n]*((g=Math.sqrt(g))-a[n])/g,x*=g,_*=g,p.x-=x*(m=h.weight+p.weight?h.weight/(h.weight+p.weight):.5),p.y-=_*m,h.x+=x*(m=1-m),h.y+=_*m);if((m=i*v)&&(x=c[0]/2,_=c[1]/2,n=-1,m))for(;++n0?i=t:(r.c=null,r.t=NaN,r=null,u.end({type:"end",alpha:i=0})):t>0&&(u.start({type:"start",alpha:i=t}),r=Rt(l.tick)),l):i},l.start=function(){function t(t,n){if(!r){for(r=new Array(i),l=0;i>l;++l)r[l]=[];for(l=0;u>l;++l){var a=b[l];r[a.source.index].push(a.target),r[a.target.index].push(a.source)}}for(var o,s=r[e],l=-1,c=s.length;++le;++e)(n=y[e]).index=e,n.weight=0;for(e=0;u>e;++e)n=b[e],"number"==typeof n.source&&(n.source=y[n.source]),"number"==typeof n.target&&(n.target=y[n.target]),++n.source.weight,++n.target.weight;for(e=0;i>e;++e)n=y[e],isNaN(n.x)&&(n.x=t("x",f)),isNaN(n.y)&&(n.y=t("y",g)),isNaN(n.px)&&(n.px=n.x),isNaN(n.py)&&(n.py=n.y);if(a=[],"function"==typeof h)for(e=0;u>e;++e)a[e]=+h.call(this,b[e],e);else for(e=0;u>e;++e)a[e]=h;if(o=[],"function"==typeof p)for(e=0;u>e;++e)o[e]=+p.call(this,b[e],e);else for(e=0;u>e;++e)o[e]=p;if(s=[],"function"==typeof d)for(e=0;i>e;++e)s[e]=+d.call(this,y[e],e);else for(e=0;i>e;++e)s[e]=d;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return n||(n=uo.behavior.drag().origin(x).on("dragstart.force",ei).on("drag.force",e).on("dragend.force",ri)),arguments.length?void this.on("mouseover.force",ni).on("mouseout.force",ii).call(n):n},uo.rebind(l,u,"on")};var xl=20,_l=1,wl=1/0;uo.layout.hierarchy=function(){function t(i){var a,o=[i],s=[];for(i.depth=0;null!=(a=o.pop());)if(s.push(a),(u=r.call(t,a,a.depth))&&(l=u.length)){for(var l,u,c;--l>=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;n&&(a.value=0),a.children=u}else n&&(a.value=+n.call(t,a,a.depth)||0),delete a.children;return li(i,function(t){var r,i;e&&(r=t.children)&&r.sort(e),n&&(i=t.parent)&&(i.value+=t.value)}),s}var e=fi,r=ui,n=ci;return t.sort=function(r){return arguments.length?(e=r,t):e},t.children=function(e){return arguments.length?(r=e,t):r},t.value=function(e){return arguments.length?(n=e,t):n},t.revalue=function(e){return n&&(si(e,function(t){t.children&&(t.value=0)}),li(e,function(e){var r;e.children||(e.value=+n.call(t,e,e.depth)||0),(r=e.parent)&&(r.value+=e.value)})),e},t},uo.layout.partition=function(){function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++uf?-1:1),d=uo.sum(u),g=d?(f-l*p)/d:0,v=uo.range(l),m=[];return null!=r&&v.sort(r===kl?function(t,e){return u[e]-u[t]}:function(t,e){return r(o[t],o[e])}),v.forEach(function(t){m[t]={data:o[t],value:s=u[t],startAngle:c,endAngle:c+=s*g+p,padAngle:h}}),m}var e=Number,r=kl,n=0,i=Vo,a=0;return t.value=function(r){return arguments.length?(e=r,t):e},t.sort=function(e){return arguments.length?(r=e,t):r},t.startAngle=function(e){return arguments.length?(n=e,t):n},t.endAngle=function(e){return arguments.length?(i=e,t):i},t.padAngle=function(e){return arguments.length?(a=e,t):a},t};var kl={};uo.layout.stack=function(){function t(s,l){if(!(h=s.length))return s;var u=s.map(function(r,n){return e.call(t,r,n)}),c=u.map(function(e){return e.map(function(e,r){return[a.call(t,e,r),o.call(t,e,r)]})}),f=r.call(t,c,l);u=uo.permute(u,f),c=uo.permute(c,f);var h,p,d,g,v=n.call(t,c,l),m=u[0].length;for(d=0;m>d;++d)for(i.call(t,u[0][d],g=v[d],c[0][d][1]),p=1;h>p;++p)i.call(t,u[p][d],g+=c[p-1][d][1],c[p][d][1]);return s}var e=x,r=vi,n=mi,i=gi,a=pi,o=di;return t.values=function(r){return arguments.length?(e=r,t):e},t.order=function(e){return arguments.length?(r="function"==typeof e?e:Al.get(e)||vi,t):r},t.offset=function(e){return arguments.length?(n="function"==typeof e?e:Ml.get(e)||mi,t):n},t.x=function(e){return arguments.length?(a=e,t):a},t.y=function(e){return arguments.length?(o=e,t):o},t.out=function(e){return arguments.length?(i=e,t):i},t};var Al=uo.map({"inside-out":function(t){var e,r,n=t.length,i=t.map(yi),a=t.map(bi),o=uo.range(n).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,u=[],c=[];for(e=0;n>e;++e)r=o[e],l>s?(s+=a[r],u.push(r)):(l+=a[r],c.push(r));return c.reverse().concat(u)},reverse:function(t){return uo.range(t.length).reverse()},"default":vi}),Ml=uo.map({silhouette:function(t){var e,r,n,i=t.length,a=t[0].length,o=[],s=0,l=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];n>s&&(s=n),o.push(n)}for(r=0;a>r;++r)l[r]=(s-o[r])/2;return l},wiggle:function(t){var e,r,n,i,a,o,s,l,u,c=t.length,f=t[0],h=f.length,p=[];for(p[0]=l=u=0,r=1;h>r;++r){for(e=0,i=0;c>e;++e)i+=t[e][r][1];for(e=0,a=0,s=f[r][0]-f[r-1][0];c>e;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*s);e>n;++n)o+=(t[n][r][1]-t[n][r-1][1])/s;a+=o*t[e][r][1]}p[r]=l-=i?a/i*s:0,u>l&&(u=l)}for(r=0;h>r;++r)p[r]-=u;return p},expand:function(t){var e,r,n,i=t.length,a=t[0].length,o=1/i,s=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];if(n)for(e=0;i>e;e++)t[e][r][1]/=n;else for(e=0;i>e;e++)t[e][r][1]=o}for(r=0;a>r;++r)s[r]=0;return s},zero:mi});uo.layout.histogram=function(){function t(t,a){for(var o,s,l=[],u=t.map(r,this),c=n.call(this,u,a),f=i.call(this,c,u,a),a=-1,h=u.length,p=f.length-1,d=e?1:1/h;++a0)for(a=-1;++a=c[0]&&s<=c[1]&&(o=l[uo.bisect(f,s,1,p)-1],o.y+=d,o.push(t[a]));return l}var e=!0,r=Number,n=ki,i=_i;return t.value=function(e){return arguments.length?(r=e,t):r},t.range=function(e){return arguments.length?(n=Lt(e),t):n},t.bins=function(e){return arguments.length?(i="number"==typeof e?function(t){return wi(t,e)}:Lt(e),t):i},t.frequency=function(r){return arguments.length?(e=!!r,t):e},t},uo.layout.pack=function(){function t(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,li(s,function(t){t.r=+c(t.value)}),li(s,Li),n){var f=n*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;li(s,function(t){t.r+=f}),li(s,Li),li(s,function(t){t.r-=f})}return zi(s,l/2,u/2,e?1:1/Math.max(2*s.r/l,2*s.r/u)),o}var e,r=uo.layout.hierarchy().sort(Ai),n=0,i=[1,1];return t.size=function(e){return arguments.length?(i=e,t):i},t.radius=function(r){return arguments.length?(e=null==r||"function"==typeof r?r:+r,t):e},t.padding=function(e){return arguments.length?(n=+e,t):n},oi(t,r)},uo.layout.tree=function(){function t(t,i){var c=o.call(this,t,i),f=c[0],h=e(f);if(li(h,r),h.parent.m=-h.z,si(h,n),u)si(f,a);else{var p=f,d=f,g=f;si(f,function(t){t.xd.x&&(d=t),t.depth>g.depth&&(g=t)});var v=s(p,d)/2-p.x,m=l[0]/(d.x+s(d,p)/2+v),y=l[1]/(g.depth||1);si(f,function(t){t.x=(t.x+v)*m,t.y=t.depth*y})}return c}function e(t){for(var e,r={A:null,children:[t]},n=[r];null!=(e=n.pop());)for(var i,a=e.children,o=0,s=a.length;s>o;++o)n.push((a[o]=i={_:a[o],parent:e,children:(i=a[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return r.children[0]}function r(t){var e=t.children,r=t.parent.children,n=t.i?r[t.i-1]:null;if(e.length){Ni(t);var a=(e[0].z+e[e.length-1].z)/2;n?(t.z=n.z+s(t._,n._),t.m=t.z-a):t.z=a}else n&&(t.z=n.z+s(t._,n._));t.parent.A=i(t,n,t.parent.A||r[0])}function n(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function i(t,e,r){if(e){for(var n,i=t,a=t,o=e,l=i.parent.children[0],u=i.m,c=a.m,f=o.m,h=l.m;o=Oi(o),i=ji(i),o&&i;)l=ji(l),a=Oi(a),a.a=t,n=o.z+f-i.z-u+s(o._,i._),n>0&&(Ii(Fi(o,t,r),t,n),u+=n,c+=n),f+=o.m,u+=i.m,h+=l.m,c+=a.m;o&&!Oi(a)&&(a.t=o,a.m+=f-c),i&&!ji(l)&&(l.t=i,l.m+=u-h,r=t)}return r}function a(t){t.x*=l[0],t.y=t.depth*l[1]}var o=uo.layout.hierarchy().sort(null).value(null),s=Ri,l=[1,1],u=null;return t.separation=function(e){return arguments.length?(s=e,t):s},t.size=function(e){return arguments.length?(u=null==(l=e)?a:null,t):u?null:l},t.nodeSize=function(e){return arguments.length?(u=null==(l=e)?null:a,t):u?l:null},oi(t,o)},uo.layout.cluster=function(){function t(t,a){ +var o,s=e.call(this,t,a),l=s[0],u=0;li(l,function(t){var e=t.children;e&&e.length?(t.x=Bi(e),t.y=Di(e)):(t.x=o?u+=r(t,o):0,t.y=0,o=t)});var c=Ui(l),f=Vi(l),h=c.x-r(c,f)/2,p=f.x+r(f,c)/2;return li(l,i?function(t){t.x=(t.x-l.x)*n[0],t.y=(l.y-t.y)*n[1]}:function(t){t.x=(t.x-h)/(p-h)*n[0],t.y=(1-(l.y?t.y/l.y:1))*n[1]}),s}var e=uo.layout.hierarchy().sort(null).value(null),r=Ri,n=[1,1],i=!1;return t.separation=function(e){return arguments.length?(r=e,t):r},t.size=function(e){return arguments.length?(i=null==(n=e),t):i?null:n},t.nodeSize=function(e){return arguments.length?(i=null!=(n=e),t):i?n:null},oi(t,e)},uo.layout.treemap=function(){function t(t,e){for(var r,n,i=-1,a=t.length;++ie?0:e),r.area=isNaN(n)||0>=n?0:n}function e(r){var a=r.children;if(a&&a.length){var o,s,l,u=f(r),c=[],h=a.slice(),d=1/0,g="slice"===p?u.dx:"dice"===p?u.dy:"slice-dice"===p?1&r.depth?u.dy:u.dx:Math.min(u.dx,u.dy);for(t(h,u.dx*u.dy/r.value),c.area=0;(l=h.length)>0;)c.push(o=h[l-1]),c.area+=o.area,"squarify"!==p||(s=n(c,g))<=d?(h.pop(),d=s):(c.area-=c.pop().area,i(c,g,u,!1),g=Math.min(u.dx,u.dy),c.length=c.area=0,d=1/0);c.length&&(i(c,g,u,!0),c.length=c.area=0),a.forEach(e)}}function r(e){var n=e.children;if(n&&n.length){var a,o=f(e),s=n.slice(),l=[];for(t(s,o.dx*o.dy/e.value),l.area=0;a=s.pop();)l.push(a),l.area+=a.area,null!=a.z&&(i(l,a.z?o.dx:o.dy,o,!s.length),l.length=l.area=0);n.forEach(r)}}function n(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++or&&(a=r),r>i&&(i=r));return n*=n,e*=e,n?Math.max(e*i*d/n,n/(e*a*d)):1/0}function i(t,e,r,n){var i,a=-1,o=t.length,s=r.x,u=r.y,c=e?l(t.area/e):0;if(e==r.dx){for((n||c>r.dy)&&(c=r.dy);++ar.dx)&&(c=r.dx);++ar&&(e=1),1>r&&(t=0),function(){var r,n,i;do r=2*Math.random()-1,n=2*Math.random()-1,i=r*r+n*n;while(!i||i>1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=uo.random.normal.apply(uo,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=uo.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;t>r;r++)e+=Math.random();return e}}},uo.scale={};var Tl={floor:x,ceil:x};uo.scale.linear=function(){return $i([0,1],[0,1],_n,!1)};var El={s:1,g:1,p:1,r:1,e:1};uo.scale.log=function(){return aa(uo.scale.linear().domain([0,1]),10,!0,[1,10])};var Ll=uo.format(".0e"),Sl={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};uo.scale.pow=function(){return oa(uo.scale.linear(),1,[0,1])},uo.scale.sqrt=function(){return uo.scale.pow().exponent(.5)},uo.scale.ordinal=function(){return la([],{t:"range",a:[[]]})},uo.scale.category10=function(){return uo.scale.ordinal().range(Cl)},uo.scale.category20=function(){return uo.scale.ordinal().range(zl)},uo.scale.category20b=function(){return uo.scale.ordinal().range(Pl)},uo.scale.category20c=function(){return uo.scale.ordinal().range(Rl)};var Cl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(_t),zl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(_t),Pl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(_t),Rl=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(_t);uo.scale.quantile=function(){return ua([],[])},uo.scale.quantize=function(){return ca(0,1,[0,1])},uo.scale.threshold=function(){return fa([.5],[0,1])},uo.scale.identity=function(){return ha([0,1])},uo.svg={},uo.svg.arc=function(){function t(){var t=Math.max(0,+r.apply(this,arguments)),u=Math.max(0,+n.apply(this,arguments)),c=o.apply(this,arguments)-Go,f=s.apply(this,arguments)-Go,h=Math.abs(f-c),p=c>f?0:1;if(t>u&&(d=u,u=t,t=d),h>=qo)return e(u,p)+(t?e(t,1-p):"")+"Z";var d,g,v,m,y,b,x,_,w,k,A,M,T=0,E=0,L=[];if((m=(+l.apply(this,arguments)||0)/2)&&(v=a===jl?Math.sqrt(t*t+u*u):+a.apply(this,arguments),p||(E*=-1),u&&(E=nt(v/u*Math.sin(m))),t&&(T=nt(v/t*Math.sin(m)))),u){y=u*Math.cos(c+E),b=u*Math.sin(c+E),x=u*Math.cos(f-E),_=u*Math.sin(f-E);var S=Math.abs(f-c-2*E)<=Uo?0:1;if(E&&ba(y,b,x,_)===p^S){var C=(c+f)/2;y=u*Math.cos(C),b=u*Math.sin(C),x=_=null}}else y=b=0;if(t){w=t*Math.cos(f-T),k=t*Math.sin(f-T),A=t*Math.cos(c+T),M=t*Math.sin(c+T);var z=Math.abs(c-f+2*T)<=Uo?0:1;if(T&&ba(w,k,A,M)===1-p^z){var P=(c+f)/2;w=t*Math.cos(P),k=t*Math.sin(P),A=M=null}}else w=k=0;if(h>Do&&(d=Math.min(Math.abs(u-t)/2,+i.apply(this,arguments)))>.001){g=u>t^p?0:1;var R=d,j=d;if(Uo>h){var O=null==A?[w,k]:null==x?[y,b]:Or([y,b],[A,M],[x,_],[w,k]),I=y-O[0],N=b-O[1],F=x-O[0],D=_-O[1],B=1/Math.sin(Math.acos((I*F+N*D)/(Math.sqrt(I*I+N*N)*Math.sqrt(F*F+D*D)))/2),U=Math.sqrt(O[0]*O[0]+O[1]*O[1]);j=Math.min(d,(t-U)/(B-1)),R=Math.min(d,(u-U)/(B+1))}if(null!=x){var V=xa(null==A?[w,k]:[A,M],[y,b],u,R,p),q=xa([x,_],[w,k],u,R,p);d===R?L.push("M",V[0],"A",R,",",R," 0 0,",g," ",V[1],"A",u,",",u," 0 ",1-p^ba(V[1][0],V[1][1],q[1][0],q[1][1]),",",p," ",q[1],"A",R,",",R," 0 0,",g," ",q[0]):L.push("M",V[0],"A",R,",",R," 0 1,",g," ",q[0])}else L.push("M",y,",",b);if(null!=A){var G=xa([y,b],[A,M],t,-j,p),H=xa([w,k],null==x?[y,b]:[x,_],t,-j,p);d===j?L.push("L",H[0],"A",j,",",j," 0 0,",g," ",H[1],"A",t,",",t," 0 ",p^ba(H[1][0],H[1][1],G[1][0],G[1][1]),",",1-p," ",G[1],"A",j,",",j," 0 0,",g," ",G[0]):L.push("L",H[0],"A",j,",",j," 0 0,",g," ",G[0])}else L.push("L",w,",",k)}else L.push("M",y,",",b),null!=x&&L.push("A",u,",",u," 0 ",S,",",p," ",x,",",_),L.push("L",w,",",k),null!=A&&L.push("A",t,",",t," 0 ",z,",",1-p," ",A,",",M);return L.push("Z"),L.join("")}function e(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}var r=da,n=ga,i=pa,a=jl,o=va,s=ma,l=ya;return t.innerRadius=function(e){return arguments.length?(r=Lt(e),t):r},t.outerRadius=function(e){return arguments.length?(n=Lt(e),t):n},t.cornerRadius=function(e){return arguments.length?(i=Lt(e),t):i},t.padRadius=function(e){return arguments.length?(a=e==jl?jl:Lt(e),t):a},t.startAngle=function(e){return arguments.length?(o=Lt(e),t):o},t.endAngle=function(e){return arguments.length?(s=Lt(e),t):s},t.padAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.centroid=function(){var t=(+r.apply(this,arguments)+ +n.apply(this,arguments))/2,e=(+o.apply(this,arguments)+ +s.apply(this,arguments))/2-Go;return[Math.cos(e)*t,Math.sin(e)*t]},t};var jl="auto";uo.svg.line=function(){return _a(x)};var Ol=uo.map({linear:wa,"linear-closed":ka,step:Aa,"step-before":Ma,"step-after":Ta,basis:Pa,"basis-open":Ra,"basis-closed":ja,bundle:Oa,cardinal:Sa,"cardinal-open":Ea,"cardinal-closed":La,monotone:Ua});Ol.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Il=[0,2/3,1/3,0],Nl=[0,1/3,2/3,0],Fl=[0,1/6,2/3,1/6];uo.svg.line.radial=function(){var t=_a(Va);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Ma.reverse=Ta,Ta.reverse=Ma,uo.svg.area=function(){return qa(x)},uo.svg.area.radial=function(){var t=qa(Va);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},uo.svg.chord=function(){function t(t,s){var l=e(this,a,t,s),u=e(this,o,t,s);return"M"+l.p0+n(l.r,l.p1,l.a1-l.a0)+(r(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+n(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function e(t,e,r,n){var i=e.call(t,r,n),a=s.call(t,i,n),o=l.call(t,i,n)-Go,c=u.call(t,i,n)-Go;return{r:a,a0:o,a1:c,p0:[a*Math.cos(o),a*Math.sin(o)],p1:[a*Math.cos(c),a*Math.sin(c)]}}function r(t,e){return t.a0==e.a0&&t.a1==e.a1}function n(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Uo)+",1 "+e}function i(t,e,r,n){return"Q 0,0 "+n}var a=xr,o=_r,s=Ga,l=va,u=ma;return t.radius=function(e){return arguments.length?(s=Lt(e),t):s},t.source=function(e){return arguments.length?(a=Lt(e),t):a},t.target=function(e){return arguments.length?(o=Lt(e),t):o},t.startAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.endAngle=function(e){return arguments.length?(u=Lt(e),t):u},t},uo.svg.diagonal=function(){function t(t,i){var a=e.call(this,t,i),o=r.call(this,t,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return l=l.map(n),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,r=_r,n=Ha;return t.source=function(r){return arguments.length?(e=Lt(r),t):e},t.target=function(e){return arguments.length?(r=Lt(e),t):r},t.projection=function(e){return arguments.length?(n=e,t):n},t},uo.svg.diagonal.radial=function(){var t=uo.svg.diagonal(),e=Ha,r=t.projection;return t.projection=function(t){return arguments.length?r(Ya(e=t)):e},t},uo.svg.symbol=function(){function t(t,n){return(Dl.get(e.call(this,t,n))||Za)(r.call(this,t,n))}var e=Wa,r=Xa;return t.type=function(r){return arguments.length?(e=Lt(r),t):e},t.size=function(e){return arguments.length?(r=Lt(e),t):r},t};var Dl=uo.map({circle:Za,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Ul)),r=e*Ul;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});uo.svg.symbolTypes=Dl.keys();var Bl=Math.sqrt(3),Ul=Math.tan(30*Ho);zo.transition=function(t){for(var e,r,n=Vl||++Yl,i=to(t),a=[],o=ql||{time:Date.now(),ease:Ln,delay:0,duration:250},s=-1,l=this.length;++sa;a++){i.push(e=[]);for(var r=this[a],s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return $a(i,this.namespace,this.id)},Hl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):H(this,null==e?function(e){e[n][r].tween.remove(t)}:function(i){i[n][r].tween.set(t,e)})},Hl.attr=function(t,e){function r(){this.removeAttribute(s)}function n(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?r:(t+="",function(){var e,r=this.getAttribute(s);return r!==t&&(e=o(r,t),function(t){this.setAttribute(s,e(t))})})}function a(t){return null==t?n:(t+="",function(){var e,r=this.getAttributeNS(s.space,s.local);return r!==t&&(e=o(r,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var o="transform"==t?Zn:_n,s=uo.ns.qualify(t);return Qa(this,"attr."+t,e,s.local?a:i)},Hl.attrTween=function(t,e){function r(t,r){var n=e.call(this,t,r,this.getAttribute(i));return n&&function(t){this.setAttribute(i,n(t))}}function n(t,r){var n=e.call(this,t,r,this.getAttributeNS(i.space,i.local));return n&&function(t){this.setAttributeNS(i.space,i.local,n(t))}}var i=uo.ns.qualify(t);return this.tween("attr."+t,i.local?n:r)},Hl.style=function(t,e,r){function i(){this.style.removeProperty(t)}function a(e){return null==e?i:(e+="",function(){var i,a=n(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(i=_n(a,e),function(e){this.style.setProperty(t,i(e),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(r in t)this.style(r,t[r],e);return this}r=""}return Qa(this,"style."+t,e,a)},Hl.styleTween=function(t,e,r){function i(i,a){var o=e.call(this,i,a,n(this).getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),r)}}return arguments.length<3&&(r=""),this.tween("style."+t,i)},Hl.text=function(t){return Qa(this,"text",t,Ja)},Hl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},Hl.ease=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].ease:("function"!=typeof t&&(t=uo.ease.apply(uo,arguments)),H(this,function(n){n[r][e].ease=t}))},Hl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:H(this,"function"==typeof t?function(n,i,a){n[r][e].delay=+t.call(n,n.__data__,i,a)}:(t=+t,function(n){n[r][e].delay=t}))},Hl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:H(this,"function"==typeof t?function(n,i,a){n[r][e].duration=Math.max(1,t.call(n,n.__data__,i,a))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},Hl.each=function(t,e){var r=this.id,n=this.namespace;if(arguments.length<2){var i=ql,a=Vl;try{Vl=r,H(this,function(e,i,a){ql=e[n][r],t.call(e,e.__data__,i,a)})}finally{ql=i,Vl=a}}else H(this,function(i){var a=i[n][r];(a.event||(a.event=uo.dispatch("start","end","interrupt"))).on(t,e)});return this},Hl.transition=function(){for(var t,e,r,n,i=this.id,a=++Yl,o=this.namespace,s=[],l=0,u=this.length;u>l;l++){s.push(t=[]);for(var e=this[l],c=0,f=e.length;f>c;c++)(r=e[c])&&(n=r[o][i],eo(r,c,o,a,{time:n.time,ease:n.ease,delay:n.delay+n.duration,duration:n.duration})),t.push(r)}return $a(s,o,a)},uo.svg.axis=function(){function t(t){t.each(function(){var t,u=uo.select(this),c=this.__chart__||r,f=this.__chart__=r.copy(),h=null==l?f.ticks?f.ticks.apply(f,s):f.domain():l,p=null==e?f.tickFormat?f.tickFormat.apply(f,s):x:e,d=u.selectAll(".tick").data(h,f),g=d.enter().insert("g",".domain").attr("class","tick").style("opacity",Do),v=uo.transition(d.exit()).style("opacity",Do).remove(),m=uo.transition(d.order()).style("opacity",1),y=Math.max(i,0)+o,b=Yi(f),_=u.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),uo.transition(_));g.append("line"),g.append("text");var k,A,M,T,E=g.select("line"),L=m.select("line"),S=d.select("text").text(p),C=g.select("text"),z=m.select("text"),P="top"===n||"left"===n?-1:1;if("bottom"===n||"top"===n?(t=ro,k="x",M="y",A="x2",T="y2",S.attr("dy",0>P?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+P*a+"V0H"+b[1]+"V"+P*a)):(t=no,k="y",M="x",A="y2",T="x2",S.attr("dy",".32em").style("text-anchor",0>P?"end":"start"),w.attr("d","M"+P*a+","+b[0]+"H0V"+b[1]+"H"+P*a)),E.attr(T,P*i),C.attr(M,P*y),L.attr(A,0).attr(T,P*i),z.attr(k,0).attr(M,P*y),f.rangeBand){var R=f,j=R.rangeBand()/2;c=f=function(t){return R(t)+j}}else c.rangeBand?c=f:v.call(t,f,c);g.call(t,c,f),m.call(t,f,f)})}var e,r=uo.scale.linear(),n=Xl,i=6,a=6,o=3,s=[10],l=null;return t.scale=function(e){return arguments.length?(r=e,t):r},t.orient=function(e){return arguments.length?(n=e in Wl?e+"":Xl,t):n},t.ticks=function(){return arguments.length?(s=fo(arguments),t):s},t.tickValues=function(e){return arguments.length?(l=e,t):l},t.tickFormat=function(r){return arguments.length?(e=r,t):e},t.tickSize=function(e){var r=arguments.length;return r?(i=+e,a=+arguments[r-1],t):i},t.innerTickSize=function(e){return arguments.length?(i=+e,t):i},t.outerTickSize=function(e){return arguments.length?(a=+e,t):a},t.tickPadding=function(e){return arguments.length?(o=+e,t):o},t.tickSubdivide=function(){return arguments.length&&t},t};var Xl="bottom",Wl={top:1,right:1,bottom:1,left:1};uo.svg.brush=function(){function t(n){n.each(function(){var n=uo.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",a).on("touchstart.brush",a),o=n.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),n.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=n.selectAll(".resize").data(g,x);s.exit().remove(),s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Zl[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),s.style("display",t.empty()?"none":null);var l,f=uo.transition(n),h=uo.transition(o);u&&(l=Yi(u),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(f)),c&&(l=Yi(c),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(f)),e(f)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+f[+/e$/.test(t)]+","+h[+/^s/.test(t)]+")"})}function r(t){t.select(".extent").attr("x",f[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",f[1]-f[0])}function i(t){t.select(".extent").attr("y",h[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function a(){function a(){32==uo.event.keyCode&&(S||(b=null,z[0]-=f[1],z[1]-=h[1],S=2),T())}function g(){32==uo.event.keyCode&&2==S&&(z[0]+=f[1],z[1]+=h[1],S=0,T())}function v(){var t=uo.mouse(_),n=!1;x&&(t[0]+=x[0],t[1]+=x[1]),S||(uo.event.altKey?(b||(b=[(f[0]+f[1])/2,(h[0]+h[1])/2]),z[0]=f[+(t[0]c?(i=n,n=c):i=c),g[0]!=n||g[1]!=i?(r?s=null:o=null,g[0]=n,g[1]=i,!0):void 0}function y(){v(),A.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null),uo.select("body").style("cursor",null),P.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),C(),k({type:"brushend"})}var b,x,_=this,w=uo.select(uo.event.target),k=l.of(_,arguments),A=uo.select(_),M=w.datum(),E=!/^(n|s)$/.test(M)&&u,L=!/^(e|w)$/.test(M)&&c,S=w.classed("extent"),C=$(_),z=uo.mouse(_),P=uo.select(n(_)).on("keydown.brush",a).on("keyup.brush",g);if(uo.event.changedTouches?P.on("touchmove.brush",v).on("touchend.brush",y):P.on("mousemove.brush",v).on("mouseup.brush",y),A.interrupt().selectAll("*").interrupt(),S)z[0]=f[0]-z[0],z[1]=h[0]-z[1];else if(M){var R=+/w$/.test(M),j=+/^n/.test(M);x=[f[1-R]-z[0],h[1-j]-z[1]],z[0]=f[R],z[1]=h[j]}else uo.event.altKey&&(b=z.slice());A.style("pointer-events","none").selectAll(".resize").style("display",null),uo.select("body").style("cursor",w.style("cursor")),k({type:"brushstart"}),v()}var o,s,l=L(t,"brushstart","brush","brushend"),u=null,c=null,f=[0,0],h=[0,0],p=!0,d=!0,g=Kl[0];return t.event=function(t){t.each(function(){var t=l.of(this,arguments),e={x:f,y:h,i:o,j:s},r=this.__chart__||e;this.__chart__=e,Vl?uo.select(this).transition().each("start.brush",function(){o=r.i,s=r.j,f=r.x,h=r.y,t({type:"brushstart"})}).tween("brush:brush",function(){var r=wn(f,e.x),n=wn(h,e.y);return o=s=null,function(i){f=e.x=r(i),h=e.y=n(i),t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i,s=e.j,t({type:"brush",mode:"resize"}),t({type:"brushend"})}):(t({type:"brushstart"}),t({type:"brush",mode:"resize"}),t({type:"brushend"}))})},t.x=function(e){return arguments.length?(u=e,g=Kl[!u<<1|!c],t):u},t.y=function(e){return arguments.length?(c=e,g=Kl[!u<<1|!c],t):c},t.clamp=function(e){return arguments.length?(u&&c?(p=!!e[0],d=!!e[1]):u?p=!!e:c&&(d=!!e),t):u&&c?[p,d]:u?p:c?d:null},t.extent=function(e){var r,n,i,a,l;return arguments.length?(u&&(r=e[0],n=e[1],c&&(r=r[0],n=n[0]),o=[r,n],u.invert&&(r=u(r),n=u(n)),r>n&&(l=r,r=n,n=l),r==f[0]&&n==f[1]||(f=[r,n])),c&&(i=e[0],a=e[1],u&&(i=i[1],a=a[1]),s=[i,a],c.invert&&(i=c(i),a=c(a)),i>a&&(l=i,i=a,a=l),i==h[0]&&a==h[1]||(h=[i,a])),t):(u&&(o?(r=o[0],n=o[1]):(r=f[0],n=f[1],u.invert&&(r=u.invert(r),n=u.invert(n)),r>n&&(l=r,r=n,n=l))),c&&(s?(i=s[0],a=s[1]):(i=h[0],a=h[1],c.invert&&(i=c.invert(i),a=c.invert(a)),i>a&&(l=i,i=a,a=l))),u&&c?[[r,i],[n,a]]:u?[r,n]:c&&[i,a])},t.clear=function(){return t.empty()||(f=[0,0],h=[0,0],o=s=null),t},t.empty=function(){return!!u&&f[0]==f[1]||!!c&&h[0]==h[1]},uo.rebind(t,l,"on")};var Zl={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Kl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],$l=vs.format=ws.timeFormat,Ql=$l.utc,Jl=Ql("%Y-%m-%dT%H:%M:%S.%LZ");$l.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?io:Jl,io.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},io.toString=Jl.toString,vs.second=Vt(function(t){return new ms(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),vs.seconds=vs.second.range,vs.seconds.utc=vs.second.utc.range,vs.minute=Vt(function(t){return new ms(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),vs.minutes=vs.minute.range,vs.minutes.utc=vs.minute.utc.range,vs.hour=Vt(function(t){var e=t.getTimezoneOffset()/60;return new ms(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),vs.hours=vs.hour.range,vs.hours.utc=vs.hour.utc.range,vs.month=Vt(function(t){return t=vs.day(t),t.setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),vs.months=vs.month.range,vs.months.utc=vs.month.utc.range;var tu=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],eu=[[vs.second,1],[vs.second,5],[vs.second,15],[vs.second,30],[vs.minute,1],[vs.minute,5],[vs.minute,15],[vs.minute,30],[vs.hour,1],[vs.hour,3],[vs.hour,6],[vs.hour,12],[vs.day,1],[vs.day,2],[vs.week,1],[vs.month,1],[vs.month,3],[vs.year,1]],ru=$l.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",ze]]),nu={range:function(t,e,r){return uo.range(Math.ceil(t/r)*r,+e,r).map(oo)},floor:x,ceil:x};eu.year=vs.year,vs.scale=function(){return ao(uo.scale.linear(),eu,ru)};var iu=eu.map(function(t){return[t[0].utc,t[1]]}),au=Ql.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",ze]]);iu.year=vs.year.utc,vs.scale.utc=function(){return ao(uo.scale.linear(),iu,au)},uo.text=St(function(t){return t.responseText}),uo.json=function(t,e){return Ct(t,"application/json",so,e)},uo.html=function(t,e){return Ct(t,"text/html",lo,e)},uo.xml=St(function(t){return t.responseXML}),"function"==typeof t&&t.amd?(this.d3=uo,t(uo)):"object"==typeof r&&r.exports?r.exports=uo:this.d3=uo}()},{}],83:[function(t,e,r){arguments[4][76][0].apply(r,arguments)},{dup:76,"robust-orientation":1040,"simplicial-complex":86}],84:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],85:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],86:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":84,dup:79,"union-find":85}],87:[function(t,e,r){"use strict";function n(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;n>o;++o)if(a=i,i=t[o],e(i,a)){if(o===r){r++;continue}t[r++]=i}return t.length=r,t}function i(t){for(var e=1,r=t.length,n=t[0],i=t[0],a=1;r>a;++a,i=n)if(i=n,n=t[a],n!==i){if(a===e){e++;continue}t[e++]=n}return t.length=e,t}function a(t,e,r){return 0===t.length?t:e?(r||t.sort(e),n(t,e)):(r||t.sort(),i(t))}e.exports=a},{}],88:[function(t,e,r){"use strict";function n(t,e){this.point=t,this.index=e}function i(t,e){for(var r=t.point,n=e.point,i=r.length,a=0;i>a;++a){var o=n[a]-r[a];if(o)return o}return 0}function a(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;t>a;++a){var o=n[a-1],s=n[a];i[a-1]=[o[1],s[1]]}return r&&i.push([-1,i[0][1]],[i[t-1][1],-1]),i}function o(t,e){var r=t.length;if(0===r)return[];var o=t[0].length;if(1>o)return[];if(1===o)return a(r,t,e);for(var u=new Array(r),c=1,f=0;r>f;++f){for(var h=t[f],p=new Array(o+1),d=0,g=0;o>g;++g){var v=h[g];p[g]=v,d+=v*v}p[o]=d,u[f]=new n(p,f),c=Math.max(d,c)}l(u,i),r=u.length;for(var m=new Array(r+o+1),y=new Array(r+o+1),b=(o+1)*(o+1)*c,x=new Array(o+1),f=0;o>=f;++f)x[f]=0;x[o]=b,m[0]=x.slice(),y[0]=-1;for(var f=0;o>=f;++f){var p=x.slice();p[f]=1,m[f+1]=p,y[f+1]=-1}for(var f=0;r>f;++f){var _=u[f];m[f+o+1]=_.point,y[f+o+1]=_.index}var w=s(m,!1);if(w=e?w.filter(function(t){for(var e=0,r=0;o>=r;++r){var n=y[t[r]];if(0>n&&++e>=2)return!1;t[r]=n}return!0}):w.filter(function(t){for(var e=0;o>=e;++e){var r=y[t[e]];if(0>r)return!1;t[e]=r}return!0}),1&o)for(var f=0;ft;t+=2){var e=at[t],r=at[t+1];e(r),at[t]=void 0,at[t+1]=void 0}Q=0}function g(){try{var t=e,r=t("vertx");return W=r.runOnLoop||r.runOnContext,c()}catch(n){return p()}}function v(t,e){var r=this,n=new this.constructor(y);void 0===n[lt]&&N(n);var i=r._state;if(i){var a=arguments[i-1];J(function(){j(i,n,a,r._result)})}else C(r,n,t,e);return n}function m(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var r=new e(y);return T(r,t),r}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function x(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return ht.error=e,ht}}function w(t,e,r,n){try{t.call(e,r,n)}catch(i){return i}}function k(t,e,r){J(function(t){var n=!1,i=w(r,e,function(r){n||(n=!0,e!==r?T(t,r):L(t,r))},function(e){n||(n=!0,S(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&i&&(n=!0,S(t,i))},t)}function A(t,e){e._state===ct?L(t,e._result):e._state===ft?S(t,e._result):C(e,void 0,function(e){T(t,e)},function(e){S(t,e)})}function M(t,e,r){e.constructor===t.constructor&&r===ot&&constructor.resolve===st?A(t,e):r===ht?S(t,ht.error):void 0===r?L(t,e):o(r)?k(t,e,r):L(t,e)}function T(t,e){t===e?S(t,b()):a(e)?M(t,e,_(e)):L(t,e)}function E(t){t._onerror&&t._onerror(t._result),z(t)}function L(t,e){t._state===ut&&(t._result=e,t._state=ct,0!==t._subscribers.length&&J(z,t))}function S(t,e){t._state===ut&&(t._state=ft,t._result=e,J(E,t))}function C(t,e,r,n){var i=t._subscribers,a=i.length;t._onerror=null,i[a]=e,i[a+ct]=r,i[a+ft]=n,0===a&&t._state&&J(z,t)}function z(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n,i,a=t._result,o=0;oa;a++)e.resolve(t[a]).then(r,n)}:function(t,e){e(new TypeError("You must pass an array to race."))})}function B(t){var e=this,r=new e(y);return S(r,t),r}function U(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function V(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function q(t){this[lt]=I(),this._result=this._state=void 0,this._subscribers=[],y!==t&&("function"!=typeof t&&U(),this instanceof q?O(this,t):V())}function G(t,e){this._instanceConstructor=t,this.promise=new t(y),this.promise[lt]||N(this.promise),$(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?L(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&L(this.promise,this._result))):S(this.promise,H())}function H(){return new Error("Array Methods must be provided an Array")}function Y(){var t;if("undefined"!=typeof i)t=i;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var r=t.Promise;r&&"[object Promise]"===Object.prototype.toString.call(r.resolve())&&!r.cast||(t.Promise=yt)}var X;X=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var W,Z,K,$=X,Q=0,J=function(t,e){at[Q]=t,at[Q+1]=e,Q+=2,2===Q&&(Z?Z(d):K())},tt="undefined"!=typeof window?window:void 0,et=tt||{},rt=et.MutationObserver||et.WebKitMutationObserver,nt="undefined"==typeof self&&"undefined"!=typeof n&&"[object process]"==={}.toString.call(n),it="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,at=new Array(1e3); +K=nt?u():rt?f():it?h():void 0===tt&&"function"==typeof e?g():p();var ot=v,st=m,lt=Math.random().toString(36).substring(16),ut=void 0,ct=1,ft=2,ht=new P,pt=new P,dt=0,gt=F,vt=D,mt=B,yt=q;q.all=gt,q.race=vt,q.resolve=st,q.reject=mt,q._setScheduler=s,q._setAsap=l,q._asap=J,q.prototype={constructor:q,then:ot,"catch":function(t){return this.then(null,t)}};var bt=G;G.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===ut&&t>r;r++)this._eachEntry(e[r],r)},G.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===st){var i=_(t);if(i===ot&&t._state!==ut)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(r===yt){var a=new r(y);M(a,t,i),this._willSettleAt(a,e)}else this._willSettleAt(new r(function(e){e(t)}),e)}else this._willSettleAt(n(t),e)},G.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===ut&&(this._remaining--,t===ft?S(n,r):this._result[e]=r),0===this._remaining&&L(n,this._result)},G.prototype._willSettleAt=function(t,e){var r=this;C(t,void 0,function(t){r._settledAt(ct,e,t)},function(t){r._settledAt(ft,e,t)})};var xt=Y,_t={Promise:yt,polyfill:xt};"function"==typeof t&&t.amd?t(function(){return _t}):"undefined"!=typeof r&&r.exports?r.exports=_t:"undefined"!=typeof this&&(this.ES6Promise=_t),xt()}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:70}],90:[function(t,e,r){"use strict";function n(t){for(var e,r=t.length,n=0;r>n;n++)if(e=t.charCodeAt(n),(9>e||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(8192>e||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(t=+t,0===t&&n(r))return!1}else if("number"!==e)return!1;return 1>t-t}},{}],91:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.shader=e,this.buffer=r,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.color=[0,0,0,1]}function i(t,e){var r=a(t.gl,l.vertex,l.fragment),i=o(t.gl),s=new n(t,r,i);return s.update(e),t.addObject(s),s}var a=t("gl-shader"),o=t("gl-buffer"),s=t("typedarray-pool"),l=t("./lib/shaders");e.exports=i;var u=[[1,0,0,1,0,0],[1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,1,0,0],[1,0,0,1,0,0],[1,0,-1,0,0,1],[1,0,-1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,1],[1,0,-1,0,0,1],[-1,0,-1,0,0,1],[-1,0,-1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,1],[-1,0,-1,0,0,1],[0,1,1,0,0,0],[0,1,-1,0,0,0],[0,-1,-1,0,0,0],[0,-1,-1,0,0,0],[0,1,1,0,0,0],[0,-1,1,0,0,0],[0,1,0,-1,1,0],[0,1,0,-1,-1,0],[0,1,0,1,-1,0],[0,1,0,1,1,0],[0,1,0,-1,1,0],[0,1,0,1,-1,0],[0,-1,0,-1,1,0],[0,-1,0,-1,-1,0],[0,-1,0,1,-1,0],[0,-1,0,1,1,0],[0,-1,0,-1,1,0],[0,-1,0,1,-1,0]],c=n.prototype;c.draw=function(){var t=[1,0,0,0,1,0,0,0,1],e=[1,1];return function(){var r=this.plot,n=this.shader,i=this.buffer,a=this.bounds,o=this.numPoints;if(o){var s=r.gl,l=r.dataBox,c=r.viewBox,f=r.pixelRatio,h=a[2]-a[0],p=a[3]-a[1],d=l[2]-l[0],g=l[3]-l[1];t[0]=2*h/d,t[4]=2*p/g,t[6]=2*(a[0]-l[0])/d-1,t[7]=2*(a[1]-l[1])/g-1;var v=c[2]-c[0],m=c[3]-c[1];e[0]=2*f/v,e[1]=2*f/m,i.bind(),n.bind(),n.uniforms.viewTransform=t,n.uniforms.pixelScale=e,n.uniforms.color=this.color,n.attributes.position.pointer(s.FLOAT,!1,16,0),n.attributes.pixelOffset.pointer(s.FLOAT,!1,16,8),s.drawArrays(s.TRIANGLES,0,o*u.length)}}}(),c.drawPick=function(t){return t},c.pick=function(t,e){return null},c.update=function(t){t=t||{};var e,r,n,i=t.positions||[],a=t.errors||[],o=1;"lineWidth"in t&&(o=+t.lineWidth);var l=5;"capSize"in t&&(l=+t.capSize),this.color=(t.color||[0,0,0,1]).slice();var c=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=this.numPoints=i.length>>1;for(e=0;f>e;++e)r=i[2*e],n=i[2*e+1],c[0]=Math.min(r,c[0]),c[1]=Math.min(n,c[1]),c[2]=Math.max(r,c[2]),c[3]=Math.max(n,c[3]);c[2]===c[0]&&(c[2]+=1),c[3]===c[1]&&(c[3]+=1);var h=1/(c[2]-c[0]),p=1/(c[3]-c[1]),d=c[0],g=c[1],v=s.mallocFloat32(f*u.length*4),m=0;for(e=0;f>e;++e){r=i[2*e],n=i[2*e+1];for(var y=a[4*e],b=a[4*e+1],x=a[4*e+2],_=a[4*e+3],w=0;wA?A*=y:A>0&&(A*=b),0>M?M*=x:M>0&&(M*=_),v[m++]=h*(r-d+A),v[m++]=p*(n-g+M),v[m++]=o*k[2]+(l+o)*k[4],v[m++]=o*k[3]+(l+o)*k[5]}}this.buffer.update(v),s.free(v)},c.dispose=function(){this.plot.removeObject(this),this.shader.dispose(),this.buffer.dispose()}},{"./lib/shaders":92,"gl-buffer":93,"gl-shader":94,"typedarray-pool":122}],92:[function(t,e,r){e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n",fragment:"precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"}},{}],93:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}function i(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(0>a)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function a(t,e){for(var r=l.malloc(t.length,e),n=t.length,i=0;n>i;++i)r[i]=t[i];return r}function o(t,e){for(var r=1,n=e.length-1;n>=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}function s(t,e,r,i){if(r=r||t.ARRAY_BUFFER,i=i||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(i!==t.DYNAMIC_DRAW&&i!==t.STATIC_DRAW&&i!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=t.createBuffer(),o=new n(t,r,a,0,i);return o.update(e),o}var l=t("typedarray-pool"),u=t("ndarray-ops"),c=t("ndarray"),f=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"],h=n.prototype;h.bind=function(){this.gl.bindBuffer(this.type,this.handle)},h.unbind=function(){this.gl.bindBuffer(this.type,null)},h.dispose=function(){this.gl.deleteBuffer(this.handle)},h.update=function(t,e){if("number"!=typeof e&&(e=-1),this.bind(),"object"==typeof t&&"undefined"!=typeof t.shape){var r=t.dtype;if(f.indexOf(r)<0&&(r="float32"),this.type===this.gl.ELEMENT_ARRAY_BUFFER){var n=gl.getExtension("OES_element_index_uint");r=n&&"uint16"!==r?"uint32":"uint16"}if(r===t.dtype&&o(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=i(this.gl,this.type,this.length,this.usage,t.data,e):this.length=i(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=l.malloc(t.size,r),h=c(s,t.shape);u.assign(h,t),0>e?this.length=i(this.gl,this.type,this.length,this.usage,s,e):this.length=i(this.gl,this.type,this.length,this.usage,s.subarray(0,t.size),e),l.free(s)}}else if(Array.isArray(t)){var p;p=this.type===this.gl.ELEMENT_ARRAY_BUFFER?a(t,"uint16"):a(t,"float32"),0>e?this.length=i(this.gl,this.type,this.length,this.usage,p,e):this.length=i(this.gl,this.type,this.length,this.usage,p.subarray(0,t.length),e),l.free(p)}else if("object"==typeof t&&"number"==typeof t.length)this.length=i(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");t=0|t,0>=t&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=s},{ndarray:1031,"ndarray-ops":1026,"typedarray-pool":122}],94:[function(t,e,r){"use strict";function n(t){this.gl=t,this._vref=this._fref=this._relink=this.vertShader=this.fragShader=this.program=this.attributes=this.uniforms=this.types=null}function i(t,e){return t.name=0){for(var A=0|k.type.charAt(k.type.length-1),M=new Array(A),T=0;A>T;++T)M[T]=_.length,x.push(k.name+"["+T+"]"),"number"==typeof k.location?_.push(k.location+T):Array.isArray(k.location)&&k.location.length===A&&"number"==typeof k.location[T]?_.push(0|k.location[T]):_.push(-1);b.push({name:k.name,type:k.type,locations:M})}else b.push({name:k.name,type:k.type,locations:[_.length]}),x.push(k.name),"number"==typeof k.location?_.push(0|k.location):_.push(-1)}for(var E=0,w=0;w<_.length;++w)if(_[w]<0){for(;_.indexOf(E)>=0;)E+=1;_[w]=E}var L=new Array(r.length);a(),p._relink=a,p.types={uniforms:l(r),attributes:l(n)},p.attributes=s(d,p,b,_),Object.defineProperty(p,"uniforms",o(d,p,r,L))},e.exports=a},{"./lib/GLError":95,"./lib/create-attributes":96,"./lib/create-uniforms":97,"./lib/reflect":98,"./lib/runtime-reflect":99,"./lib/shader-cache":100}],95:[function(t,e,r){function n(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}n.prototype=new Error,n.prototype.name="GLError",n.prototype.constructor=n,e.exports=n},{}],96:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}function i(t,e,r,i,a,o,s){for(var l=["gl","v"],u=[],c=0;a>c;++c)l.push("x"+c),u.push("x"+c);l.push("if(x0.length===void 0){return gl.vertexAttrib"+a+"f(v,"+u.join()+")}else{return gl.vertexAttrib"+a+"fv(v,x0)}");var f=Function.apply(null,l),h=new n(t,e,r,i,a,f);Object.defineProperty(o,s,{set:function(e){return t.disableVertexAttribArray(i[r]),f(t,i[r],e),e},get:function(){return h},enumerable:!0})}function a(t,e,r,n,a,o,s){for(var l=new Array(a),u=new Array(a),c=0;a>c;++c)i(t,e,r[c],n,a,l,c),u[c]=l[c];Object.defineProperty(l,"location",{set:function(t){if(Array.isArray(t))for(var e=0;a>e;++e)u[e].location=t[e];else for(var e=0;a>e;++e)u[e].location=t+e;return t},get:function(){for(var t=new Array(a),e=0;a>e;++e)t[e]=n[r[e]];return t},enumerable:!0}),l.pointer=function(e,i,o,s){e=e||t.FLOAT,i=!!i,o=o||a*a,s=s||0;for(var l=0;a>l;++l){var u=n[r[l]];t.vertexAttribPointer(u,a,e,i,o,s+l*a),t.enableVertexAttribArray(u)}};var f=new Array(a),h=t["vertexAttrib"+a+"fv"];Object.defineProperty(o,s,{set:function(e){for(var i=0;a>i;++i){var o=n[r[i]];if(t.disableVertexAttribArray(o),Array.isArray(e[0]))h.call(t,o,e[i]);else{for(var s=0;a>s;++s)f[s]=e[a*i+s];h.call(t,o,f)}}return e},get:function(){return l},enumerable:!0})}function o(t,e,r,n){for(var o={},l=0,u=r.length;u>l;++l){var c=r[l],f=c.name,h=c.type,p=c.locations;switch(h){case"bool":case"int":case"float":i(t,e,p[0],n,1,o,f);break;default:if(h.indexOf("vec")>=0){var d=h.charCodeAt(h.length-1)-48;if(2>d||d>4)throw new s("","Invalid data type for attribute "+f+": "+h);i(t,e,p[0],n,d,o,f)}else{if(!(h.indexOf("mat")>=0))throw new s("","Unknown data type for attribute "+f+": "+h);var d=h.charCodeAt(h.length-1)-48;if(2>d||d>4)throw new s("","Invalid data type for attribute "+f+": "+h);a(t,e,p,n,d,o,f)}}}return o}e.exports=o;var s=t("./GLError"),l=n.prototype;l.pointer=function(t,e,r,n){var i=this,a=i._gl,o=i._locations[i._index];a.vertexAttribPointer(o,i._dimension,t||a.FLOAT,!!e,r||0,n||0),a.enableVertexAttribArray(o)},l.set=function(t,e,r,n){return this._constFunc(this._locations[this._index],t,e,r,n)},Object.defineProperty(l,"location",{get:function(){return this._locations[this._index]},set:function(t){return t!==this._locations[this._index]&&(this._locations[this._index]=0|t,this._wrapper.program=null),0|t}})},{"./GLError":95}],97:[function(t,e,r){"use strict";function n(t){var e=new Function("y","return function(){return y}");return e(t)}function i(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e,r,a){function l(r){var n=new Function("gl","wrapper","locations","return function(){return gl.getUniform(wrapper.program,locations["+r+"])}");return n(t,e,a)}function u(t,e,r){switch(r){case"bool":case"int":case"sampler2D":case"samplerCube":return"gl.uniform1i(locations["+e+"],obj"+t+")";case"float":return"gl.uniform1f(locations["+e+"],obj"+t+")";default:var n=r.indexOf("vec");if(!(n>=0&&1>=n&&r.length===4+n)){if(0===r.indexOf("mat")&&4===r.length){var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new s("","Unknown uniform data type for "+name+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new s("","Unrecognized data type for vector "+name+": "+r)}}}function c(t,e){if("object"!=typeof e)return[[t,e]];var r=[];for(var n in e){var i=e[n],a=t;a+=parseInt(n)+""===n?"["+n+"]":"."+n,"object"==typeof i?r.push.apply(r,c(a,i)):r.push([a,i])}return r}function f(e){for(var n=["return function updateProperty(obj){"],i=c("",e),o=0;o=0&&1>=e&&t.length===4+e){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid data type");return"b"===t.charAt(0)?i(r,!1):i(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+t);return i(r*r,0)}throw new s("","Unknown uniform data type for "+name+": "+t)}}function p(t,e,i){if("object"==typeof i){var o=d(i);Object.defineProperty(t,e,{get:n(o),set:f(i),enumerable:!0,configurable:!1})}else a[i]?Object.defineProperty(t,e,{get:l(i),set:f(i),enumerable:!0,configurable:!1}):t[e]=h(r[i].type)}function d(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;ua;++a){var o=t.getActiveUniform(e,a);if(o){var s=n(t,o.type);if(o.size>1)for(var l=0;la;++a){var o=t.getActiveAttrib(e,a);o&&i.push({name:o.name,type:n(t,o.type)})}return i}r.uniforms=i,r.attributes=a;var o={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube"},s=null},{}],100:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.id=t,this.src=e,this.type=r,this.shader=n,this.count=a,this.programs=[],this.cache=o}function i(t){this.gl=t,this.shaders=[{},{}],this.programs={}}function a(t,e,r){var n=t.createShader(e);if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){var i=t.getShaderInfoLog(n);try{var a=f(i,r,e)}catch(o){throw console.warn("Failed to format compiler error: "+o),new c(i,"Error compiling shader:\n"+i)}throw new c(i,a.short,a.long)}return n}function o(t,e,r,n,i){var a=t.createProgram();t.attachShader(a,e),t.attachShader(a,r);for(var o=0;on;++n){var a=t.programs[r[n]];a&&(delete t.programs[n],e.deleteProgram(a))}e.deleteShader(this.shader),delete t.shaders[this.type===e.FRAGMENT_SHADER|0][this.src]}};var g=i.prototype;g.getShaderReference=function(t,e){var r=this.gl,i=this.shaders[t===r.FRAGMENT_SHADER|0],o=i[e];if(o&&r.isShader(o.shader))o.count+=1;else{var s=a(r,t,e);o=i[e]=new n(d++,e,t,s,[],1,this)}return o},g.getProgram=function(t,e,r,n){var i=[t.id,e.id,r.join(":"),n.join(":")].join("@"),a=this.programs[i];return a&&this.gl.isProgram(a)||(this.programs[i]=a=o(this.gl,t.shader,e.shader,r,n),t.programs.push(i),e.programs.push(i)),a}},{"./GLError":95,"gl-format-compiler-error":101,"weakmap-shim":119}],101:[function(t,e,r){function n(t,e,r){"use strict";var n=o(e)||"of unknown name (see npm glsl-shader-name)",l="unknown type";void 0!==r&&(l=r===a.FRAGMENT_SHADER?"fragment":"vertex");for(var u=i("Error compiling %s shader %s:\n",l,n),c=i("%s%s",u,t),f=t.split("\n"),h={},p=0;pa.length&&e>0&&(1&e&&(a+=t),e>>=1);)t+=t;return a.substr(0,r)}var i,a="";e.exports=n},{}],105:[function(t,e,r){e.exports={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34e3:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"}},{}],106:[function(t,e,r){var n=t("./1.0/numbers");e.exports=function(t){return n[t]}},{"./1.0/numbers":105}],107:[function(t,e,r){function n(t){for(var e=Array.isArray(t)?t:i(t),r=0;rF;){switch(e=F,B){case f:F=L();break;case h:F=E();break;case p:F=T();break;case d:F=S();break;case g:F=P();break;case w:F=z();break;case v:F=R();break;case c:F=j();break;case x:F=M();break;case u:F=A()}if(e!==F)switch(W[e]){case"\n":G=0,++q;break;default:++G}}return D+=F,W=W.slice(F),V}function n(t){return U.length&&e(U.join("")),B=_,e("(eof)"),V}function A(){return U=U.length?[]:U,"/"===I&&"*"===O?(H=D+F-1,B=f,I=O,F+1):"/"===I&&"/"===O?(H=D+F-1,B=h,I=O,F+1):"#"===O?(B=p,H=D+F,F):/\s/.test(O)?(B=x,H=D+F,F):(Y=/\d/.test(O),X=/[^\w_]/.test(O),H=D+F,B=Y?g:X?d:c,F)}function M(){return/[^\s]/g.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function T(){return"\r"!==O&&"\n"!==O||"\\"===I?(U.push(O),I=O,F+1):(e(U.join("")),B=u,F)}function E(){return T()}function L(){return"/"===O&&"*"===I?(U.push(O),e(U.join("")),B=u,F+1):(U.push(O),I=O,F+1)}function S(){if("."===I&&/\d/.test(O))return B=v,F;if("/"===I&&"*"===O)return B=f,F;if("/"===I&&"/"===O)return B=h,F;if("."===O&&U.length){for(;C(U););return B=v,F}if(";"===O||")"===O||"("===O){if(U.length)for(;C(U););return e(O),B=u,F+1}var t=2===U.length&&"="!==O;if(/[\w_\d\s]/.test(O)||t){for(;C(U););return B=u,F}return U.push(O),I=O,F+1}function C(t){for(var r,n,i=0;;){if(r=a.indexOf(t.slice(0,t.length+i).join("")),n=a[r],-1===r){if(i--+t.length>0)continue;n=t.slice(0,1).join("")}return e(n),H+=n.length,U=U.slice(n.length),U.length}}function z(){return/[^a-fA-F0-9]/.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function P(){return"."===O?(U.push(O),B=v,I=O,F+1):/[eE]/.test(O)?(U.push(O),B=v,I=O,F+1):"x"===O&&1===U.length&&"0"===U[0]?(B=w,U.push(O),I=O,F+1):/[^\d]/.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function R(){return"f"===O&&(U.push(O),I=O,F+=1),/[eE]/.test(O)?(U.push(O),I=O,F+1):"-"===O&&/[eE]/.test(I)?(U.push(O),I=O,F+1):/[^\d]/.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function j(){if(/[^\d\w_]/.test(O)){var t=U.join("");return B=K.indexOf(t)>-1?b:Z.indexOf(t)>-1?y:m,e(U.join("")),B=u,F}return U.push(O),I=O,F+1}var O,I,N,F=0,D=0,B=u,U=[],V=[],q=1,G=0,H=0,Y=!1,X=!1,W="";t=t||{};var Z=o,K=i;return"300 es"===t.version&&(Z=l,K=s),function(t){return V=[],null!==t?r(t.replace?t.replace(/\r\n/g,"\n"):t):n()}}e.exports=n;var i=t("./lib/literals"),a=t("./lib/operators"),o=t("./lib/builtins"),s=t("./lib/literals-300es"),l=t("./lib/builtins-300es"),u=999,c=9999,f=0,h=1,p=2,d=3,g=4,v=5,m=6,y=7,b=8,x=9,_=10,w=11,k=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":111,"./lib/builtins-300es":110,"./lib/literals":113,"./lib/literals-300es":112,"./lib/operators":114}],110:[function(t,e,r){var n=t("./builtins");n=n.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)}),e.exports=n.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"]); +},{"./builtins":111}],111:[function(t,e,r){e.exports=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]},{}],112:[function(t,e,r){var n=t("./literals");e.exports=n.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"])},{"./literals":113}],113:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],114:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],115:[function(t,e,r){function n(t,e){var r=i(e),n=[];return n=n.concat(r(t)),n=n.concat(r(null))}var i=t("./index");e.exports=n},{"./index":109}],116:[function(e,r,n){!function(e){function r(){var t=arguments[0],e=r.cache;return e[t]&&e.hasOwnProperty(t)||(e[t]=r.parse(t)),r.format.call(null,e[t],arguments)}function i(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()}function a(t,e){return Array(e+1).join(t)}var o={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};r.format=function(t,e){var n,s,l,u,c,f,h,p=1,d=t.length,g="",v=[],m=!0,y="";for(s=0;d>s;s++)if(g=i(t[s]),"string"===g)v[v.length]=t[s];else if("array"===g){if(u=t[s],u[2])for(n=e[p],l=0;l=0),u[8]){case"b":n=n.toString(2);break;case"c":n=String.fromCharCode(n);break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,u[6]?parseInt(u[6]):0);break;case"e":n=u[7]?n.toExponential(u[7]):n.toExponential();break;case"f":n=u[7]?parseFloat(n).toFixed(u[7]):parseFloat(n);break;case"g":n=u[7]?parseFloat(n).toPrecision(u[7]):parseFloat(n);break;case"o":n=n.toString(8);break;case"s":n=(n=String(n))&&u[7]?n.substring(0,u[7]):n;break;case"u":n>>>=0;break;case"x":n=n.toString(16);break;case"X":n=n.toString(16).toUpperCase()}o.json.test(u[8])?v[v.length]=n:(!o.number.test(u[8])||m&&!u[3]?y="":(y=m?"+":"-",n=n.toString().replace(o.sign,"")),f=u[4]?"0"===u[4]?"0":u[4].charAt(1):" ",h=u[6]-(y+n).length,c=u[6]&&h>0?a(f,h):"",v[v.length]=u[5]?y+n+c:"0"===f?y+c+n:c+y+n)}return v.join("")},r.cache={},r.parse=function(t){for(var e=t,r=[],n=[],i=0;e;){if(null!==(r=o.text.exec(e)))n[n.length]=r[0];else if(null!==(r=o.modulo.exec(e)))n[n.length]="%";else{if(null===(r=o.placeholder.exec(e)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){i|=1;var a=[],s=r[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a[a.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))a[a.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");a[a.length]=l[1]}r[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n[n.length]=r}e=e.substring(r[0].length)}return n};var s=function(t,e,n){return n=(e||[]).slice(0),n.splice(0,0,t),r.apply(null,n)};"undefined"!=typeof n?(n.sprintf=r,n.vsprintf=s):(e.sprintf=r,e.vsprintf=s,"function"==typeof t&&t.amd&&t(function(){return{sprintf:r,vsprintf:s}}))}("undefined"==typeof window?this:window)},{}],117:[function(t,e,r){function n(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:i(e,t)}}var i=t("./hidden-store.js");e.exports=n},{"./hidden-store.js":118}],118:[function(t,e,r){function n(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}e.exports=n},{}],119:[function(t,e,r){function n(){var t=i();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){t(e).value=r},has:function(e){return"value"in t(e)},"delete":function(e){return delete t(e).value}}}var i=t("./create-store.js");e.exports=n},{"./create-store.js":117}],120:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],121:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],122:[function(t,e,r){(function(e,n){"use strict";function i(t){if(t){var e=t.length||t.byteLength,r=y.log2(e);w[r].push(t)}}function a(t){i(t.buffer)}function o(t){var t=y.nextPow2(t),e=y.log2(t),r=w[e];return r.length>0?r.pop():new ArrayBuffer(t)}function s(t){return new Uint8Array(o(t),0,t)}function l(t){return new Uint16Array(o(2*t),0,t)}function u(t){return new Uint32Array(o(4*t),0,t)}function c(t){return new Int8Array(o(t),0,t)}function f(t){return new Int16Array(o(2*t),0,t)}function h(t){return new Int32Array(o(4*t),0,t)}function p(t){return new Float32Array(o(4*t),0,t)}function d(t){return new Float64Array(o(8*t),0,t)}function g(t){return x?new Uint8ClampedArray(o(t),0,t):s(t)}function v(t){return new DataView(o(t),0,t)}function m(t){t=y.nextPow2(t);var e=y.log2(t),r=k[e];return r.length>0?r.pop():new n(t)}var y=t("bit-twiddle"),b=t("dup");e.__TYPEDARRAY_POOL||(e.__TYPEDARRAY_POOL={UINT8:b([32,0]),UINT16:b([32,0]),UINT32:b([32,0]),INT8:b([32,0]),INT16:b([32,0]),INT32:b([32,0]),FLOAT:b([32,0]),DOUBLE:b([32,0]),DATA:b([32,0]),UINT8C:b([32,0]),BUFFER:b([32,0])});var x="undefined"!=typeof Uint8ClampedArray,_=e.__TYPEDARRAY_POOL;_.UINT8C||(_.UINT8C=b([32,0])),_.BUFFER||(_.BUFFER=b([32,0]));var w=_.DATA,k=_.BUFFER;r.free=function(t){if(n.isBuffer(t))k[y.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|y.log2(e);w[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=a,r.freeArrayBuffer=i,r.freeBuffer=function(t){k[y.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return o(t);switch(e){case"uint8":return s(t);case"uint16":return l(t);case"uint32":return u(t);case"int8":return c(t);case"int16":return f(t);case"int32":return h(t);case"float":case"float32":return p(t);case"double":case"float64":return d(t);case"uint8_clamped":return g(t);case"buffer":return m(t);case"data":case"dataview":return v(t);default:return null}return null},r.mallocArrayBuffer=o,r.mallocUint8=s,r.mallocUint16=l,r.mallocUint32=u,r.mallocInt8=c,r.mallocInt16=f,r.mallocInt32=h,r.mallocFloat32=r.mallocFloat=p,r.mallocFloat64=r.mallocDouble=d,r.mallocUint8Clamped=g,r.mallocDataView=v,r.mallocBuffer=m,r.clearCache=function(){for(var t=0;32>t;++t)_.UINT8[t].length=0,_.UINT16[t].length=0,_.UINT32[t].length=0,_.INT8[t].length=0,_.INT16[t].length=0,_.INT32[t].length=0,_.FLOAT[t].length=0,_.DOUBLE[t].length=0,_.UINT8C[t].length=0,w[t].length=0,k[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":120,buffer:65,dup:121}],123:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}function i(t,e){for(var r=0;3>r;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}function a(t,e,r,n){for(var i=h[n],a=0;a=1},f.isTransparent=function(){return this.opacity<1},f.drawTransparent=f.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||c,i=r.projection=t.projection||c;r.model=t.model||c,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var f=0;3>f;++f)e.lineWidth(this.lineWidth[f]),r.capSize=this.capSize[f]*u,e.drawArrays(e.LINES,this.lineOffset[f],this.lineCount[f]);this.vao.unbind()};var h=function(){for(var t=new Array(3),e=0;3>e;++e){for(var r=[],n=1;2>=n;++n)for(var i=-1;1>=i;i+=2){var a=(n+e)%3,o=[0,0,0];o[a]=i,r.push(o)}t[e]=r}return t}();f.update=function(t){t=t||{},"lineWidth"in t&&(this.lineWidth=t.lineWidth,Array.isArray(this.lineWidth)||(this.lineWidth=[this.lineWidth,this.lineWidth,this.lineWidth])),"capSize"in t&&(this.capSize=t.capSize,Array.isArray(this.capSize)||(this.capSize=[this.capSize,this.capSize,this.capSize])),"opacity"in t&&(this.opacity=t.opacity);var e=t.color||[[0,0,0],[0,0,0],[0,0,0]],r=t.position,n=t.error;if(Array.isArray(e[0])||(e=[e,e,e]),r&&n){var o=[],s=r.length,l=0;this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.lineCount=[0,0,0];for(var u=0;3>u;++u){this.lineOffset[u]=l;t:for(var c=0;s>c;++c){for(var f=r[c],h=0;3>h;++h)if(isNaN(f[h])||!isFinite(f[h]))continue t;var p=n[c],d=e[u];if(Array.isArray(d[0])&&(d=e[c]),3===d.length&&(d=[d[0],d[1],d[2],1]),!isNaN(p[0][u])&&!isNaN(p[1][u])){if(p[0][u]<0){var g=f.slice();g[u]+=p[0][u],o.push(f[0],f[1],f[2],d[0],d[1],d[2],d[3],0,0,0,g[0],g[1],g[2],d[0],d[1],d[2],d[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,d,u)}if(p[1][u]>0){var g=f.slice();g[u]+=p[1][u],o.push(f[0],f[1],f[2],d[0],d[1],d[2],d[3],0,0,0,g[0],g[1],g[2],d[0],d[1],d[2],d[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,d,u)}}}this.lineCount[u]=l-this.lineOffset[u]}this.buffer.update(o)}},f.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":158,"gl-buffer":124,"gl-vao":157}],124:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":127}],125:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],126:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],127:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":125,buffer:65,dup:122}],128:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":129,"./lib/create-attributes":130,"./lib/create-uniforms":131,"./lib/reflect":132,"./lib/runtime-reflect":133,"./lib/shader-cache":134,dup:94}],129:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],130:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":129,dup:96}],131:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":129,"./reflect":132,dup:97}],132:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],133:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],134:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":129,dup:100,"gl-format-compiler-error":135,"weakmap-shim":153}],135:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":136,dup:101,"gl-constants/lookup":140,"glsl-shader-name":141,"sprintf-js":150}],136:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":137}],137:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":138}],138:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],139:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],140:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":139,dup:106}],141:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":142,dup:107,"glsl-tokenizer":149}],142:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],143:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":145,"./lib/builtins-300es":144,"./lib/literals":147,"./lib/literals-300es":146,"./lib/operators":148,dup:109}],144:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":145,dup:110}],145:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],146:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":147,dup:112}],147:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],148:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],149:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":143,dup:115}],150:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],151:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":152,dup:117}],152:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],153:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":151,dup:119}],154:[function(t,e,r){"use strict";function n(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;ii;++i)t.disableVertexAttribArray(i)}else{t.bindBuffer(t.ARRAY_BUFFER,null);for(var i=0;n>i;++i)t.disableVertexAttribArray(i)}}e.exports=n},{}],155:[function(t,e,r){"use strict";function n(t){this.gl=t,this._elements=null,this._attributes=null,this._elementsType=t.UNSIGNED_SHORT}function i(t){return new n(t)}var a=t("./do-bind.js");n.prototype.bind=function(){a(this.gl,this._elements,this._attributes)},n.prototype.update=function(t,e,r){this._elements=e,this._attributes=t,this._elementsType=r||this.gl.UNSIGNED_SHORT},n.prototype.dispose=function(){},n.prototype.unbind=function(){},n.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._elements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=i},{"./do-bind.js":154}],156:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.location=t,this.dimension=e,this.a=r,this.b=n,this.c=i,this.d=a}function i(t,e,r){this.gl=t,this._ext=e,this.handle=r,this._attribs=[],this._useElements=!1,this._elementsType=t.UNSIGNED_SHORT}function a(t,e){return new i(t,e,e.createVertexArrayOES())}var o=t("./do-bind.js");n.prototype.bind=function(t){switch(this.dimension){case 1:t.vertexAttrib1f(this.location,this.a);break;case 2:t.vertexAttrib2f(this.location,this.a,this.b);break;case 3:t.vertexAttrib3f(this.location,this.a,this.b,this.c);break;case 4:t.vertexAttrib4f(this.location,this.a,this.b,this.c,this.d)}},i.prototype.bind=function(){this._ext.bindVertexArrayOES(this.handle);for(var t=0;t2&&!this.usingDashes){var C=this.mitreShader;C.bind();var z=C.uniforms;z.matrix=t,z.color=s,z.screenShape=e,z.radius=l*d,C.attributes.p.pointer(f.FLOAT,!1,48,0),f.drawArrays(f.POINTS,0,c/3|0)}}}}(),h.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0],r=[0,0,0,0];return function(n){var i=this.plot,a=this.pickShader,o=this.lineBuffer,s=this.pickBuffer,l=this.width,u=this.numPoints,c=this.bounds,f=this.vertCount,h=i.gl,p=i.viewBox,d=i.dataBox,g=i.pickPixelRatio,v=c[2]-c[0],m=c[3]-c[1],y=d[2]-d[0],b=d[3]-d[1],x=p[2]-p[0],_=p[3]-p[1];if(this.pickOffset=n,!f)return n+u;t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(c[0]-d[0])/y-1,t[7]=2*(c[1]-d[1])/b-1,e[0]=x,e[1]=_,r[0]=255&n,r[1]=n>>>8&255,r[2]=n>>>16&255,r[3]=n>>>24,a.bind();var w=a.uniforms;w.matrix=t,w.width=l*g,w.pickOffset=r,w.screenShape=e;var k=a.attributes;return o.bind(),k.a.pointer(h.FLOAT,!1,16,0),k.d.pointer(h.FLOAT,!1,16,8),s.bind(),k.pick0.pointer(h.UNSIGNED_BYTE,!1,8,0),k.pick1.pointer(h.UNSIGNED_BYTE,!1,8,4),h.drawArrays(h.TRIANGLES,0,f),n+u}}(),h.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.data;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},h.update=function(t){t=t||{};var e=this.plot.gl;!!t.connectGaps;this.color=(t.color||[0,0,1,1]).slice(),this.width=+(t.width||1),this.fill=(t.fill||[!1,!1,!1,!1]).slice(),this.fillColor=i(t.fillColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);for(var r=t.dashes||[1],n=0,a=0;a1,this.dashPattern=l(e,u(o,[n,1,4],[1,0,0])),this.dashPattern.minFilter=e.NEAREST,this.dashPattern.magFilter=e.NEAREST,this.dashLength=n,c.free(o);var p=t.positions;this.data=p;var d=this.bounds;d[0]=d[1]=1/0,d[2]=d[3]=-(1/0);var g=this.numPoints=p.length>>>1;if(0!==g){for(var a=0;g>a;++a){var v=p[2*a],m=p[2*a+1];isNaN(v)||isNaN(m)||(d[0]=Math.min(d[0],v),d[1]=Math.min(d[1],m),d[2]=Math.max(d[2],v),d[3]=Math.max(d[3],m))}d[0]===d[2]&&(d[2]+=1),d[3]===d[1]&&(d[3]+=1);for(var y=c.mallocFloat32(24*(g-1)),b=c.mallocUint32(12*(g-1)),x=y.length,_=b.length,s=g,w=0;s>1;){var k=--s,v=p[2*s],m=p[2*s+1],A=k-1,M=p[2*A],T=p[2*A+1];if(!(isNaN(v)||isNaN(m)||isNaN(M)||isNaN(T))){w+=1,v=(v-d[0])/(d[2]-d[0]),m=(m-d[1])/(d[3]-d[1]),M=(M-d[0])/(d[2]-d[0]),T=(T-d[1])/(d[3]-d[1]);var E=M-v,L=T-m,S=k|1<<24,C=k-1,z=k,P=k-1|1<<24;y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C}}this.vertCount=6*w,this.lineBuffer.update(y.subarray(x)),this.pickBuffer.update(b.subarray(_)),c.free(y),c.free(b)}},h.dispose=function(){this.plot.removeObject(this),this.lineBuffer.dispose(),this.pickBuffer.dispose(),this.lineShader.dispose(),this.mitreShader.dispose(),this.fillShader.dispose(),this.pickShader.dispose(),this.dashPattern.dispose()}},{"./lib/shaders":159,"gl-buffer":161,"gl-shader":162,"gl-texture2d":188,ndarray:1031,"typedarray-pool":191}],161:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":191}],162:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":163,"./lib/create-attributes":164,"./lib/create-uniforms":165,"./lib/reflect":166,"./lib/runtime-reflect":167,"./lib/shader-cache":168,dup:94}],163:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],164:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":163,dup:96}],165:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":163,"./reflect":166,dup:97}],166:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],167:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],168:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":163,dup:100,"gl-format-compiler-error":169,"weakmap-shim":187}],169:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":170,dup:101,"gl-constants/lookup":174,"glsl-shader-name":175,"sprintf-js":184}],170:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":171}],171:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":172}],172:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],173:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],174:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":173,dup:106}],175:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":176,dup:107,"glsl-tokenizer":183}],176:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],177:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":179,"./lib/builtins-300es":178,"./lib/literals":181,"./lib/literals-300es":180,"./lib/operators":182,dup:109}],178:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":179,dup:110}],179:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],180:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":181,dup:112}],181:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],182:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],183:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":177,dup:115}],184:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],185:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":186,dup:117}],186:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],187:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":185,dup:119}],188:[function(t,e,r){"use strict";function n(t){v=[t.LINEAR,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_NEAREST],m=[t.NEAREST,t.LINEAR,t.NEAREST_MIPMAP_NEAREST,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_LINEAR],y=[t.REPEAT,t.CLAMP_TO_EDGE,t.MIRRORED_REPEAT]}function i(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(0>e||e>i||0>r||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function a(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}function o(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function s(t,e,r,n,i,a,s,l){var u=l.dtype,c=l.shape.slice();if(c.length<2||c.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var f=0,h=0,v=o(c,l.stride.slice());"float32"===u?f=t.FLOAT:"float64"===u?(f=t.FLOAT,v=!1,u="float32"):"uint8"===u?f=t.UNSIGNED_BYTE:(f=t.UNSIGNED_BYTE,v=!1,u="uint8");var m=1;if(2===c.length)h=t.LUMINANCE,c=[c[0],c[1],1],l=p(l.data,c,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==c.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===c[2])h=t.ALPHA;else if(2===c[2])h=t.LUMINANCE_ALPHA;else if(3===c[2])h=t.RGB;else{if(4!==c[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}m=c[2]}if(h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i),h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=l.size,x=s.indexOf(n)<0;if(x&&s.push(n),f===a&&v)0===l.offset&&l.data.length===y?x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,l.data):x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,l.data.subarray(l.offset,l.offset+y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,l.data.subarray(l.offset,l.offset+y));else{var _;_=a===t.FLOAT?g.mallocFloat32(y):g.mallocUint8(y);var w=p(_,c,[c[2],c[2]*c[0],1]);f===t.FLOAT&&a===t.UNSIGNED_BYTE?b(w,l):d.assign(w,l),x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,_.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,_.subarray(0,y)),a===t.FLOAT?g.freeFloat32(_):g.freeUint8(_)}}function l(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function u(t,e,r,n,i){var o=t.getParameter(t.MAX_TEXTURE_SIZE);if(0>e||e>o||0>r||r>o)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var s=l(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new a(t,s,e,r,n,i)}function c(t,e,r,n){var i=l(t);return t.texImage2D(t.TEXTURE_2D,0,r,r,n,e),new a(t,i,0|e.width,0|e.height,r,n)}function f(t,e){var r=e.dtype,n=e.shape.slice(),i=t.getParameter(t.MAX_TEXTURE_SIZE);if(n[0]<0||n[0]>i||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var s=o(n,e.stride.slice()),u=0;"float32"===r?u=t.FLOAT:"float64"===r?(u=t.FLOAT,s=!1,r="float32"):"uint8"===r?u=t.UNSIGNED_BYTE:(u=t.UNSIGNED_BYTE,s=!1,r="uint8");var c=0;if(2===n.length)c=t.LUMINANCE,n=[n[0],n[1],1],e=p(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])c=t.ALPHA;else if(2===n[2])c=t.LUMINANCE_ALPHA;else if(3===n[2])c=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");c=t.RGBA}}u!==t.FLOAT||t.getExtension("OES_texture_float")||(u=t.UNSIGNED_BYTE,s=!1);var f,h,v=e.size;if(s)f=0===e.offset&&e.data.length===v?e.data:e.data.subarray(e.offset,e.offset+v);else{var m=[n[2],n[2]*n[0],1];h=g.malloc(v,r);var y=p(h,n,m,0);"float32"!==r&&"float64"!==r||u!==t.UNSIGNED_BYTE?d.assign(y,e):b(y,e),f=h.subarray(0,v)}var x=l(t);return t.texImage2D(t.TEXTURE_2D,0,c,n[0],n[1],0,c,u,f),s||g.free(h),new a(t,x,n[0],n[1],c,u)}function h(t){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(v||n(t),"number"==typeof arguments[1])return u(t,arguments[1],arguments[2],arguments[3]||t.RGBA,arguments[4]||t.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return u(t,0|arguments[1][0],0|arguments[1][1],arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if("object"==typeof arguments[1]){var e=arguments[1];if(e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e instanceof ImageData)return c(t,e,arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return f(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}var p=t("ndarray"),d=t("ndarray-ops"),g=t("typedarray-pool");e.exports=h;var v=null,m=null,y=null,b=function(t,e){d.muls(t,e,255)},x=a.prototype;Object.defineProperties(x,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;2>e;++e)if(y.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return i(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return t=0|t,i(this,t,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t=0|t,i(this,this._shape[0],t),t}}}),x.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},x.dispose=function(){this.gl.deleteTexture(this.handle)},x.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},x.setPixels=function(t,e,r,n){var i=this.gl;if(this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0,t instanceof HTMLCanvasElement||t instanceof ImageData||t instanceof HTMLImageElement||t instanceof HTMLVideoElement){var a=this._mipLevels.indexOf(n)<0;a?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,t),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,t)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||0>e||0>r)throw new Error("gl-texture2d: Texture dimensions are out of bounds");s(i,e,r,n,this.format,this.type,this._mipLevels,t)}}},{ndarray:1031,"ndarray-ops":1026,"typedarray-pool":191}],189:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],190:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],191:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":189,buffer:65,dup:122}],192:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}",s=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return n(t,i,a,null,s)},r.createPickShader=function(t){return n(t,i,o,null,s)}},{"gl-shader":199}],193:[function(t,e,r){"use strict";function n(t,e){for(var r=0,n=0;3>n;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function i(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;3>r;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function a(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function o(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}function s(t){var e=t.gl||t.scene&&t.scene.gl,r=g(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=v(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=l(e),a=u(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),s=p(new Array(1024),[256,1,4]),f=0;1024>f;++f)s.data[f]=255;var h=c(e,s);h.wrap=e.REPEAT;var d=new o(e,r,n,i,a,h);return d.update(t),d}e.exports=s;var l=t("gl-buffer"),u=t("gl-vao"),c=t("gl-texture2d"),f=t("glsl-read-float"),h=t("binary-search-bounds"),p=t("ndarray"),d=t("./lib/shaders"),g=d.createShader,v=d.createPickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],y=o.prototype;y.isTransparent=function(){return this.opacity<1},y.isOpaque=function(){return this.opacity>=1},y.pickSlots=1,y.setPickBase=function(t){this.pickId=t},y.drawTransparent=y.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,clipBounds:i(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,pickId:this.pickId,clipBounds:i(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.update=function(t){var e,r;this.dirty=!0;var i=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var a=t.position||t.positions;if(a){var o=t.color||t.colors||[0,0,0,1],s=t.lineWidth||1,l=[],u=[],c=[],f=0,d=0,g=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],v=!1;t:for(e=1;er;++r){if(isNaN(m[r])||isNaN(y[r])||!isFinite(m[r])||!isFinite(y[r])){if(!i&&l.length>0){for(var b=0;24>b;++b)l.push(l[l.length-12]);d+=2,v=!0}continue t}g[0][r]=Math.min(g[0][r],m[r],y[r]),g[1][r]=Math.max(g[1][r],m[r],y[r])}var x,_;Array.isArray(o[0])?(x=o[e-1],_=o[e]):x=_=o,3===x.length&&(x=[x[0],x[1],x[2],1]),3===_.length&&(_=[_[0],_[1],_[2],1]);var w;w=Array.isArray(s)?s[e-1]:s;var k=f;if(f+=n(m,y),v){for(r=0;2>r;++r)l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3]);d+=2,v=!1}l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3],m[0],m[1],m[2],y[0],y[1],y[2],k,-w,x[0],x[1],x[2],x[3],y[0],y[1],y[2],m[0],m[1],m[2],f,-w,_[0],_[1],_[2],_[3],y[0],y[1],y[2],m[0],m[1],m[2],f,w,_[0],_[1],_[2],_[3]),d+=4}if(this.buffer.update(l),u.push(f),c.push(a[a.length-1].slice()),this.bounds=g,this.vertexCount=d,this.points=c,this.arcLength=u,"dashes"in t){var A=t.dashes,M=A.slice();for(M.unshift(0),e=1;ee;++e){for(r=0;4>r;++r)T.set(e,0,r,0);1&h.le(M,M[M.length-1]*e/255)?T.set(e,0,0,0):T.set(e,0,0,255)}this.texture.setPixels(T)}}},y.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},y.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=f(t.value[0],t.value[1],t.value[2],0),r=h.le(this.arcLength,e);if(0>r)return null;if(r===this.arcLength.length-1)return new a(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],o=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),s=1-o,l=[0,0,0],u=0;3>u;++u)l[u]=s*n[u]+o*i[u];var c=Math.min(.5>o?r:r+1,this.points.length-1);return new a(e,l,c,this.points[c])}},{"./lib/shaders":192,"binary-search-bounds":194,"gl-buffer":195,"gl-texture2d":228,"gl-vao":232,"glsl-read-float":233,ndarray:1031}],194:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],195:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":198}],196:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],197:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],198:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":196,buffer:65,dup:122}],199:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":200,"./lib/create-attributes":201,"./lib/create-uniforms":202,"./lib/reflect":203,"./lib/runtime-reflect":204,"./lib/shader-cache":205,dup:94}],200:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],201:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":200,dup:96}],202:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":200,"./reflect":203,dup:97}],203:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],204:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],205:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":200,dup:100,"gl-format-compiler-error":206,"weakmap-shim":224}],206:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":207,dup:101,"gl-constants/lookup":211,"glsl-shader-name":212,"sprintf-js":221}],207:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":208}],208:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":209}],209:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],210:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],211:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":210,dup:106}],212:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":213,dup:107,"glsl-tokenizer":220}],213:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],214:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":216,"./lib/builtins-300es":215,"./lib/literals":218,"./lib/literals-300es":217,"./lib/operators":219,dup:109}],215:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":216,dup:110}],216:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],217:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":218,dup:112}],218:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],219:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],220:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":214,dup:115}],221:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],222:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":223,dup:117}],223:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],224:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":222,dup:119}],225:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],226:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],227:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":225,buffer:65,dup:122}],228:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":227}],229:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],230:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":229,dup:155}],231:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":229,dup:156}],232:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":230,"./lib/vao-native.js":231,dup:157}],233:[function(t,e,r){function n(t,e,r,n){return i[0]=n,i[1]=r,i[2]=e,i[3]=t,a[0]}e.exports=n;var i=new Uint8Array(4),a=new Float32Array(i.buffer)},{}],234:[function(t,e,r){function n(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}e.exports=n},{}],235:[function(t,e,r){function n(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],236:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],f=t[10],h=t[11],p=t[12],d=t[13],g=t[14],v=t[15],m=e*o-r*a,y=e*s-n*a,b=e*l-i*a,x=r*s-n*o,_=r*l-i*o,w=n*l-i*s,k=u*d-c*p,A=u*g-f*p,M=u*v-h*p,T=c*g-f*d,E=c*v-h*d,L=f*v-h*g;return m*L-y*E+b*T+x*M-_*A+w*k}e.exports=n},{}],237:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,u=r*o,c=n*o,f=n*s,h=i*o,p=i*s,d=i*l,g=a*o,v=a*s,m=a*l;return t[0]=1-f-d,t[1]=c+m,t[2]=h-v,t[3]=0,t[4]=c-m,t[5]=1-u-d,t[6]=p+g,t[7]=0,t[8]=h+v,t[9]=p-g,t[10]=1-u-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],238:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,f=n*l,h=n*u,p=i*l,d=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(p+g),t[1]=f+y,t[2]=h-m,t[3]=0,t[4]=f-y,t[5]=1-(c+g),t[6]=d+v,t[7]=0,t[8]=h+m,t[9]=d-v,t[10]=1-(c+p),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}e.exports=n},{}],239:[function(t,e,r){function n(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],240:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],u=e[7],c=e[8],f=e[9],h=e[10],p=e[11],d=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*u-a*o,_=n*l-i*s,w=n*u-a*s,k=i*u-a*l,A=c*g-f*d,M=c*v-h*d,T=c*m-p*d,E=f*v-h*g,L=f*m-p*g,S=h*m-p*v,C=y*S-b*L+x*E+_*T-w*M+k*A;return C?(C=1/C,t[0]=(s*S-l*L+u*E)*C,t[1]=(i*L-n*S-a*E)*C,t[2]=(g*k-v*w+m*_)*C,t[3]=(h*w-f*k-p*_)*C,t[4]=(l*T-o*S-u*M)*C,t[5]=(r*S-i*T+a*M)*C,t[6]=(v*x-d*k-m*b)*C,t[7]=(c*k-h*x+p*b)*C,t[8]=(o*L-s*T+u*A)*C,t[9]=(n*T-r*L-a*A)*C,t[10]=(d*w-g*x+m*y)*C,t[11]=(f*x-c*w-p*y)*C,t[12]=(s*M-o*E-l*A)*C,t[13]=(r*E-n*M+i*A)*C,t[14]=(g*b-d*_-v*y)*C,t[15]=(c*_-f*b+h*y)*C,t):null}e.exports=n},{}],241:[function(t,e,r){function n(t,e,r,n){var a,o,s,l,u,c,f,h,p,d,g=e[0],v=e[1],m=e[2],y=n[0],b=n[1],x=n[2],_=r[0],w=r[1],k=r[2];return Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6&&Math.abs(m-k)<1e-6?i(t):(f=g-_,h=v-w,p=m-k,d=1/Math.sqrt(f*f+h*h+p*p),f*=d,h*=d,p*=d,a=b*p-x*h,o=x*f-y*p,s=y*h-b*f,d=Math.sqrt(a*a+o*o+s*s),d?(d=1/d,a*=d,o*=d,s*=d):(a=0,o=0,s=0),l=h*s-p*o,u=p*a-f*s,c=f*o-h*a,d=Math.sqrt(l*l+u*u+c*c),d?(d=1/d,l*=d,u*=d,c*=d):(l=0,u=0,c=0),t[0]=a,t[1]=l,t[2]=f,t[3]=0,t[4]=o,t[5]=u,t[6]=h,t[7]=0,t[8]=s,t[9]=c,t[10]=p,t[11]=0,t[12]=-(a*g+o*v+s*m),t[13]=-(l*g+u*v+c*m),t[14]=-(f*g+h*v+p*m),t[15]=1,t)}var i=t("./identity");e.exports=n},{"./identity":239}],242:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],f=e[8],h=e[9],p=e[10],d=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*f+w*g,t[1]=b*i+x*l+_*h+w*v,t[2]=b*a+x*u+_*p+w*m,t[3]=b*o+x*c+_*d+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*f+w*g,t[5]=b*i+x*l+_*h+w*v,t[6]=b*a+x*u+_*p+w*m,t[7]=b*o+x*c+_*d+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*f+w*g,t[9]=b*i+x*l+_*h+w*v,t[10]=b*a+x*u+_*p+w*m,t[11]=b*o+x*c+_*d+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*f+w*g,t[13]=b*i+x*l+_*h+w*v,t[14]=b*a+x*u+_*p+w*m,t[15]=b*o+x*c+_*d+w*y,t}e.exports=n},{}],243:[function(t,e,r){function n(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t}e.exports=n},{}],244:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,u,c,f,h,p,d,g,v,m,y,b,x,_,w,k,A,M,T,E,L=n[0],S=n[1],C=n[2],z=Math.sqrt(L*L+S*S+C*C);return Math.abs(z)<1e-6?null:(z=1/z,L*=z,S*=z,C*=z,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],f=e[4],h=e[5],p=e[6],d=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=S*L*o+C*i,_=C*L*o-S*i,w=L*S*o-C*i,k=S*S*o+a,A=C*S*o+L*i,M=L*C*o+S*i,T=S*C*o-L*i,E=C*C*o+a,t[0]=s*b+f*x+g*_,t[1]=l*b+h*x+v*_,t[2]=u*b+p*x+m*_,t[3]=c*b+d*x+y*_,t[4]=s*w+f*k+g*A,t[5]=l*w+h*k+v*A,t[6]=u*w+p*k+m*A,t[7]=c*w+d*k+y*A,t[8]=s*M+f*T+g*E,t[9]=l*M+h*T+v*E,t[10]=u*M+p*T+m*E, +t[11]=c*M+d*T+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}e.exports=n},{}],245:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],u=e[8],c=e[9],f=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+u*n,t[5]=o*i+c*n,t[6]=s*i+f*n,t[7]=l*i+h*n,t[8]=u*i-a*n,t[9]=c*i-o*n,t[10]=f*i-s*n,t[11]=h*i-l*n,t}e.exports=n},{}],246:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[8],c=e[9],f=e[10],h=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-u*n,t[1]=o*i-c*n,t[2]=s*i-f*n,t[3]=l*i-h*n,t[8]=a*n+u*i,t[9]=o*n+c*i,t[10]=s*n+f*i,t[11]=l*n+h*i,t}e.exports=n},{}],247:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[4],c=e[5],f=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+u*n,t[1]=o*i+c*n,t[2]=s*i+f*n,t[3]=l*i+h*n,t[4]=u*i-a*n,t[5]=c*i-o*n,t[6]=f*i-s*n,t[7]=h*i-l*n,t}e.exports=n},{}],248:[function(t,e,r){function n(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}e.exports=n},{}],249:[function(t,e,r){function n(t,e,r){var n,i,a,o,s,l,u,c,f,h,p,d,g=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],f=e[8],h=e[9],p=e[10],d=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=u,t[7]=c,t[8]=f,t[9]=h,t[10]=p,t[11]=d,t[12]=n*g+s*v+f*m+e[12],t[13]=i*g+l*v+h*m+e[13],t[14]=a*g+u*v+p*m+e[14],t[15]=o*g+c*v+d*m+e[15]),t}e.exports=n},{}],250:[function(t,e,r){function n(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}e.exports=n},{}],251:[function(t,e,r){"use strict";function n(t,e){for(var r=[0,0,0,0],n=0;4>n;++n)for(var i=0;4>i;++i)r[i]+=t[4*n+i]*e[n];return r}function i(t,e,r,i,a){for(var o=n(i,n(r,n(e,[t[0],t[1],t[2],1]))),s=0;3>s;++s)o[s]/=o[3];return[.5*a[0]*(1+o[0]),.5*a[1]*(1-o[1])]}function a(t,e){if(2===t.length){for(var r=0,n=0,i=0;2>i;++i)r+=Math.pow(e[i]-t[0][i],2),n+=Math.pow(e[i]-t[1][i],2);return r=Math.sqrt(r),n=Math.sqrt(n),1e-6>r+n?[1,0]:[n/(r+n),r/(n+r)]}if(3===t.length){var a=[0,0];return u(t[0],t[1],t[2],e,a),l(t,a)}return[]}function o(t,e){for(var r=[0,0,0],n=0;no;++o)r[o]+=a*i[o];return r}function s(t,e,r,n,s,l){if(1===t.length)return[0,t[0].slice()];for(var u=new Array(t.length),c=0;cd;++d)p+=Math.pow(u[c][d]-e[d],2);h>p&&(h=p,f=c)}for(var g=a(u,e),v=0,c=0;3>c;++c){if(g[c]<-.001||g[c]>1.0001)return null;v+=g[c]}return Math.abs(v-1)>.001?null:[f,o(t,g),g]}var l=t("barycentric"),u=t("polytope-closest-point/lib/closest_point_2d.js");e.exports=s},{barycentric:254,"polytope-closest-point/lib/closest_point_2d.js":298}],252:[function(t,e,r){var n="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}",i="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}",a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",u="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}",c="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}",f="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}",h="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}",p="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n";r.meshShader={vertex:n,fragment:i,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:a,fragment:o,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:s,fragment:l,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:u,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:f,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:h,fragment:p,attributes:[{name:"position",type:"vec3"}]}},{}],253:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,u,c,f,h,p,d,g,v,m,y,b,x,_,w,k,A,M,T){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=c,this.triangleNormals=h,this.triangleUVs=f,this.triangleIds=u,this.triangleVAO=p,this.triangleCount=0,this.lineWidth=1,this.edgePositions=d,this.edgeColors=v,this.edgeUVs=m,this.edgeIds=g,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=b,this.pointColors=_,this.pointUVs=w,this.pointSizes=k,this.pointIds=x,this.pointVAO=A,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=M,this.contourVAO=T,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=O,this._view=O,this._projection=O,this._resolution=[1,1]}function i(t){for(var e=A({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;256>n;++n){for(var i=e[n],a=0;3>a;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return k(r,[256,256,4],[4,0,1])}function a(t,e,r){for(var n=new Array(e),i=0;e>i;++i)n[i]=0;for(var a=t.length,i=0;a>i;++i)for(var o=t[i],s=0;sn;++n)r[n]=t[n][2];return r}function s(t){var e=v(t,S);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.normal.location=4,e}function l(t){var e=v(t,C);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e}function u(t){var e=v(t,z);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function c(t){var e=v(t,P);return e.attributes.position.location=0,e.attributes.id.location=1,e}function f(t){var e=v(t,R);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function h(t){var e=v(t,j);return e.attributes.position.location=0,e}function p(t){var e=t.gl,r=s(e),i=l(e),a=u(e),o=c(e),p=f(e),d=h(e),g=b(e,k(new Uint8Array([255,255,255,255]),[1,1,4]));g.generateMipmap(),g.minFilter=e.LINEAR_MIPMAP_LINEAR,g.magFilter=e.LINEAR;var v=m(e),x=m(e),_=m(e),w=m(e),A=m(e),M=y(e,[{buffer:v,type:e.FLOAT,size:3},{buffer:A,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:x,type:e.FLOAT,size:4},{buffer:_,type:e.FLOAT,size:2},{buffer:w,type:e.FLOAT,size:3}]),T=m(e),E=m(e),L=m(e),S=m(e),C=y(e,[{buffer:T,type:e.FLOAT,size:3},{buffer:S,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:E,type:e.FLOAT,size:4},{buffer:L,type:e.FLOAT,size:2}]),z=m(e),P=m(e),R=m(e),j=m(e),O=m(e),I=y(e,[{buffer:z,type:e.FLOAT,size:3},{buffer:O,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:P,type:e.FLOAT,size:4},{buffer:R,type:e.FLOAT,size:2},{buffer:j,type:e.FLOAT,size:1}]),N=m(e),F=y(e,[{buffer:N,type:e.FLOAT,size:3}]),D=new n(e,g,r,i,a,o,p,d,v,A,x,_,w,M,T,S,E,L,C,z,O,P,R,j,I,N,F);return D.update(t),D}var d=1e-6,g=1e-6,v=t("gl-shader"),m=t("gl-buffer"),y=t("gl-vao"),b=t("gl-texture2d"),x=t("normals"),_=t("gl-mat4/multiply"),w=t("gl-mat4/invert"),k=t("ndarray"),A=t("colormap"),M=t("simplicial-complex-contour"),T=t("typedarray-pool"),E=t("./lib/shaders"),L=t("./lib/closest-point"),S=E.meshShader,C=E.wireShader,z=E.pointShader,P=E.pickShader,R=E.pointPickShader,j=E.contourShader,O=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],I=n.prototype;I.isOpaque=function(){return this.opacity>=1},I.isTransparent=function(){return this.opacity<1},I.pickSlots=1,I.setPickBase=function(t){this.pickId=t},I.highlight=function(t){if(!t||!this.contourEnable)return void(this.contourCount=0);for(var e=M(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=T.mallocFloat32(6*a),s=0,l=0;a>l;++l)for(var u=r[l],c=0;2>c;++c){var f=u[0];2===u.length&&(f=u[c]);for(var h=n[f][0],p=n[f][1],d=i[f],g=1-d,v=this.positions[h],m=this.positions[p],y=0;3>y;++y)o[s++]=d*v[y]+g*m[y]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),T.free(o)},I.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),t.texture?(this.texture.dispose(),this.texture=b(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(i(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions;if(n&&r){var s=[],l=[],u=[],c=[],f=[],h=[],p=[],v=[],m=[],y=[],_=[],w=[],k=[],A=[];this.cells=r,this.positions=n;var M=t.vertexNormals,T=t.cellNormals,E=void 0===t.vertexNormalsEpsilon?d:t.vertexNormalsEpsilon,L=void 0===t.faceNormalsEpsilon?g:t.faceNormalsEpsilon;t.useFacetNormals&&!T&&(T=x.faceNormals(r,n,L)),T||M||(M=x.vertexNormals(r,n,E));var S=t.vertexColors,C=t.cellColors,z=t.meshColor||[1,1,1,1],P=t.vertexUVs,R=t.vertexIntensity,j=t.cellUVs,O=t.cellIntensity,I=1/0,N=-(1/0);if(!P&&!j)if(R)for(var F=0;Fq;++q)!isNaN(V[q])&&isFinite(V[q])&&(this.bounds[0][q]=Math.min(this.bounds[0][q],V[q]),this.bounds[1][q]=Math.max(this.bounds[1][q],V[q]));var G=0,H=0,Y=0;t:for(var F=0;Fq;++q)if(isNaN(V[q])||!isFinite(V[q]))continue t;y.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?_.push(Z[0],Z[1],Z[2],1):_.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-I)/(N-I),0]:j?j[F]:O?[(O[F]-I)/(N-I),0]:[(V[2]-I)/(N-I),0],w.push(K[0],K[1]),B?k.push(B[W]):k.push(U),A.push(F),Y+=1;break;case 2:for(var q=0;2>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;2>q;++q){var W=X[q],V=n[W];h.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?p.push(Z[0],Z[1],Z[2],1):p.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-I)/(N-I),0]:j?j[F]:O?[(O[F]-I)/(N-I),0]:[(V[2]-I)/(N-I),0],v.push(K[0],K[1]),m.push(F)}H+=1;break;case 3:for(var q=0;3>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;3>q;++q){var W=X[q],V=n[W];s.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?l.push(Z[0],Z[1],Z[2],1):l.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-I)/(N-I),0]:j?j[F]:O?[(O[F]-I)/(N-I),0]:[(V[2]-I)/(N-I),0],c.push(K[0],K[1]);var Q;Q=M?M[W]:T[F],u.push(Q[0],Q[1],Q[2]),f.push(F)}G+=1}}this.pointCount=Y,this.edgeCount=H,this.triangleCount=G,this.pointPositions.update(y),this.pointColors.update(_),this.pointUVs.update(w),this.pointSizes.update(k),this.pointIds.update(new Uint32Array(A)),this.edgePositions.update(h),this.edgeColors.update(p),this.edgeUVs.update(v),this.edgeIds.update(new Uint32Array(m)),this.trianglePositions.update(s),this.triangleColors.update(l),this.triangleUVs.update(c),this.triangleNormals.update(u),this.triangleIds.update(new Uint32Array(f))}},I.drawTransparent=I.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||O,n=t.view||O,i=t.projection||O,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,contourColor:this.contourColor,texture:0};this.texture.bind(0);var l=new Array(16);_(l,s.view,s.model),_(l,s.projection,l),w(l,l);for(var o=0;3>o;++o)s.eyePosition[o]=l[12+o]/l[15];for(var u=l[15],o=0;3>o;++o)u+=this.lightPosition[o]*l[4*o+3];for(var o=0;3>o;++o){for(var c=l[12+o],f=0;3>f;++f)c+=l[4*f+o]*this.lightPosition[f];s.lightPosition[o]=c/u}if(this.triangleCount>0){var h=this.triShader;h.bind(),h.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}if(this.edgeCount>0&&this.lineWidth>0){var h=this.lineShader;h.bind(),h.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()}if(this.pointCount>0){var h=this.pointShader;h.bind(),h.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}if(this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0){var h=this.contourShader;h.bind(),h.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind()}},I.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||O,n=t.view||O,i=t.projection||O,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255},l=this.pickShader;if(l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0){var l=this.pointPickShader;l.bind(),l.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}},I.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;ao;++o){for(var s=new Array(r+1),l=0;r>=l;++l)s[l]=t[l][o];i[o]=s}i[r]=new Array(r+1);for(var o=0;r>=o;++o)i[r][o]=1;for(var u=new Array(r+1),o=0;r>o;++o)u[o]=e[o];u[r]=1;var c=a(i,u),f=n(c[r+1]);0===f&&(f=1);for(var h=new Array(r+1),o=0;r>=o;++o)h[o]=n(c[o])/f;return h}e.exports=i;var a=t("robust-linear-solve")},{"robust-linear-solve":255}],255:[function(t,e,r){arguments[4][51][0].apply(r,arguments)},{dup:51,"robust-determinant":261}],256:[function(t,e,r){arguments[4][52][0].apply(r,arguments)},{dup:52}],257:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],258:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":260,"two-sum":257}],259:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],260:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],261:[function(t,e,r){arguments[4][57][0].apply(r,arguments)},{dup:57,"robust-compress":256,"robust-scale":258,"robust-sum":259,"two-product":260}],262:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:0,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13, +rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]}},{}],263:[function(t,e,r){"use strict";function n(t){var e,r,n,u,c,f,h,p,d,g,v,m,y,b=[],x=[],_=[],w=[];if(o.isPlainObject(t)||(t={}),d=t.nshades||72,p=t.format||"hex",h=t.colormap,h||(h="jet"),"string"==typeof h){if(h=h.toLowerCase(),!l[h])throw Error(h+" not a supported colorscale");f=s(l[h])}else{if(!Array.isArray(h))throw Error("unsupported colormap option",h);f=s(h)}if(f.length>d)throw new Error(h+" map requires nshades to be at least size "+f.length);for(v=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:s(t.alpha):"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1],e=f.map(function(t){return Math.round(t.index*d)}),v[0]<0&&(v[0]=0),v[1]<0&&(v[0]=0),v[0]>1&&(v[0]=1),v[1]>1&&(v[0]=1),y=0;y=0&&r[3]<=1||(r[3]=v[0]+(v[1]-v[0])*m);for(y=0;yn;++n)e=t[n],e=e.toString(16),r+=("00"+e).substr(e.length);return r}function a(t){return"rgba("+t.join(",")+")"}var o=t("arraytools"),s=t("clone"),l=t("./colorScales");e.exports=n},{"./colorScales":262,arraytools:64,clone:264}],264:[function(t,e,r){(function(t){var r=function(){"use strict";function e(r,n,i,a){function s(r,i){if(null===r)return null;if(0==i)return r;var l,h;if("object"!=typeof r)return r;if(e.__isArray(r))l=[];else if(e.__isRegExp(r))l=new RegExp(r.source,o(r)),r.lastIndex&&(l.lastIndex=r.lastIndex);else if(e.__isDate(r))l=new Date(r.getTime());else{if(f&&t.isBuffer(r))return l=new t(r.length),r.copy(l),l;"undefined"==typeof a?(h=Object.getPrototypeOf(r),l=Object.create(h)):(l=Object.create(a),h=a)}if(n){var p=u.indexOf(r);if(-1!=p)return c[p];u.push(r),c.push(l)}for(var d in r){var g;h&&(g=Object.getOwnPropertyDescriptor(h,d)),g&&null==g.set||(l[d]=s(r[d],i-1))}return l}var l;"object"==typeof n&&(i=n.depth,a=n.prototype,l=n.filter,n=n.circular);var u=[],c=[],f="undefined"!=typeof t;return"undefined"==typeof n&&(n=!0),"undefined"==typeof i&&(i=1/0),s(r,i)}function r(t){return Object.prototype.toString.call(t)}function n(t){return"object"==typeof t&&"[object Date]"===r(t)}function i(t){return"object"==typeof t&&"[object Array]"===r(t)}function a(t){return"object"==typeof t&&"[object RegExp]"===r(t)}function o(t){var e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),e}return e.clonePrototype=function(t){if(null===t)return null;var e=function(){};return e.prototype=t,new e},e.__objToStr=r,e.__isDate=n,e.__isArray=i,e.__isRegExp=a,e.__getRegExpFlags=o,e}();"object"==typeof e&&e.exports&&(e.exports=r)}).call(this,t("buffer").Buffer)},{buffer:65}],265:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":306}],266:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":267,"./lib/create-attributes":268,"./lib/create-uniforms":269,"./lib/reflect":270,"./lib/runtime-reflect":271,"./lib/shader-cache":272,dup:94}],267:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],268:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":267,dup:96}],269:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":267,"./reflect":270,dup:97}],270:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],271:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],272:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":267,dup:100,"gl-format-compiler-error":273,"weakmap-shim":291}],273:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":274,dup:101,"gl-constants/lookup":278,"glsl-shader-name":279,"sprintf-js":288}],274:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":275}],275:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":276}],276:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],277:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],278:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":277,dup:106}],279:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":280,dup:107,"glsl-tokenizer":287}],280:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],281:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":283,"./lib/builtins-300es":282,"./lib/literals":285,"./lib/literals-300es":284,"./lib/operators":286,dup:109}],282:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":283,dup:110}],283:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],284:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":285,dup:112}],285:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],286:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],287:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":281,dup:115}],288:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],289:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":290,dup:117}],290:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],291:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":289,dup:119}],292:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":306}],293:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],294:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":293,dup:155}],295:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":293,dup:156}],296:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":294,"./lib/vao-native.js":295,dup:157}],297:[function(t,e,r){var n=1e-6,i=1e-6;r.vertexNormals=function(t,e,r){for(var i=e.length,a=new Array(i),o=void 0===r?n:r,s=0;i>s;++s)a[s]=[0,0,0];for(var s=0;sx;++x)v[x]=p[x]-d[x],m+=v[x]*v[x],y[x]=g[x]-d[x],b+=y[x]*y[x];if(m*b>o)for(var _=a[c],w=1/Math.sqrt(m*b),x=0;3>x;++x){var k=(x+1)%3,A=(x+2)%3;_[x]+=w*(y[k]*v[A]-y[A]*v[k])}}for(var s=0;i>s;++s){for(var _=a[s],M=0,x=0;3>x;++x)M+=_[x]*_[x];if(M>o)for(var w=1/Math.sqrt(M),x=0;3>x;++x)_[x]*=w;else for(var x=0;3>x;++x)_[x]=0}return a},r.faceNormals=function(t,e,r){for(var n=t.length,a=new Array(n),o=void 0===r?i:r,s=0;n>s;++s){for(var l=t[s],u=new Array(3),c=0;3>c;++c)u[c]=e[l[c]];for(var f=new Array(3),h=new Array(3),c=0;3>c;++c)f[c]=u[1][c]-u[0][c],h[c]=u[2][c]-u[0][c];for(var p=new Array(3),d=0,c=0;3>c;++c){var g=(c+1)%3,v=(c+2)%3;p[c]=f[g]*h[v]-f[v]*h[g],d+=p[c]*p[c]}d=d>o?1/Math.sqrt(d):0;for(var c=0;3>c;++c)p[c]*=d;a[s]=p}return a}},{}],298:[function(t,e,r){"use strict";function n(t,e,r,n,s){i.length=x+_)if(0>x)0>_&&0>h?(_=0,-h>=u?(x=1,y=u+2*h+d):(x=-h/u,y=h*x+d)):(x=0,p>=0?(_=0,y=d):-p>=f?(_=1,y=f+2*p+d):(_=-p/f,y=p*_+d));else if(0>_)_=0,h>=0?(x=0,y=d):-h>=u?(x=1,y=u+2*h+d):(x=-h/u,y=h*x+d);else{var w=1/b;x*=w,_*=w,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d}else{var k,A,M,T;0>x?(k=c+h,A=f+p,A>k?(M=A-k,T=u-2*c+f,M>=T?(x=1,_=0,y=u+2*h+d):(x=M/T,_=1-x,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d)):(x=0,0>=A?(_=1,y=f+2*p+d):p>=0?(_=0,y=d):(_=-p/f,y=p*_+d))):0>_?(k=c+p,A=u+h,A>k?(M=A-k,T=u-2*c+f,M>=T?(_=1,x=0,y=f+2*p+d):(_=M/T,x=1-_,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d)):(_=0,0>=A?(x=1,y=u+2*h+d):h>=0?(x=0,y=d):(x=-h/u,y=h*x+d))):(M=f+p-c-h,0>=M?(x=0,_=1,y=f+2*p+d):(T=u-2*c+f,M>=T?(x=1,_=0,y=u+2*h+d):(x=M/T,_=1-x,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d)))}for(var E=1-x-_,l=0;ly?0:y}var i=new Float64Array(4),a=new Float64Array(4),o=new Float64Array(4);e.exports=n},{}],299:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r=0|Math.max(r,t[n].length);return r-1}function i(t,e){for(var r=t.length,n=f.mallocUint8(r),i=0;r>i;++i)n[i]=t[i]o;++o)for(var s=t[o],e=s.length,l=0;e>l;++l)for(var u=0;l>u;++u){var p=s[u],d=s[l];i[a++]=0|Math.min(p,d),i[a++]=0|Math.max(p,d)}var g=a/2|0;h(c(i,[g,2]));for(var v=2,o=2;a>o;o+=2)i[o-2]===i[o]&&i[o-1]===i[o+1]||(i[v++]=i[o],i[v++]=i[o+1]);return c(i,[v/2|0,2])}function o(t,e,r,n){for(var i=t.data,a=t.shape[0],o=f.mallocDouble(a),s=0,l=0;a>l;++l){var u=i[2*l],h=i[2*l+1];if(r[u]!==r[h]){var p=e[u],d=e[h];i[2*s]=u,i[2*s+1]=h,o[s++]=(d-n)/(d-p)}}return t.shape[0]=s,c(o,[s])}function s(t,e){var r=f.mallocInt32(2*e),n=t.shape[0],i=t.data;r[0]=0;for(var a=0,o=0;n>o;++o){var s=i[2*o];if(s!==a){for(r[2*a+1]=o;++ai;++i)n[i]=[r[2*i],r[2*i+1]];return n}function u(t,e,r,u){r=r||0,"undefined"==typeof u&&(u=n(t));var c=t.length;if(0===c||1>u)return{cells:[],vertexIds:[],vertexWeights:[]};var h=i(e,+r),d=a(t,u),g=o(d,e,h,+r),v=s(d,0|e.length),m=p(u)(t,d.data,v,h),y=l(d),b=[].slice.call(g.data,0,g.shape[0]);return f.free(h),f.free(d.data),f.free(g.data),f.free(v),{cells:m,vertexIds:y,vertexWeights:b}}e.exports=u;var c=t("ndarray"),f=t("typedarray-pool"),h=t("ndarray-sort"),p=t("./lib/codegen")},{"./lib/codegen":300,ndarray:1031,"ndarray-sort":303,"typedarray-pool":306}],300:[function(t,e,r){"use strict";function n(t){function e(t){if(!(t.length<=0)){u.push("R.push(");for(var e=0;e0&&u.push(","),u.push("[");for(var n=0;n0&&u.push(","),u.push("B(C,E,c[",i[0],"],c[",i[1],"])")}u.push("]")}u.push(");")}}var r=0,n=new Array(t+1);n[0]=[[]];for(var i=1;t>=i;++i)for(var s=n[i]=o(i),l=0;l>1,v=E[2*m+1];","if(v===b){return m}","if(b1;--i){t+1>i&&u.push("else "),u.push("if(l===",i,"){");for(var c=[],l=0;i>l;++l)c.push("(S[c["+l+"]]<<"+l+")");u.push("var M=",c.join("+"),";if(M===0||M===",(1<i;++i)n[i]=0,i===e&&(n[i]+=.5),i===r&&(n[i]+=.5);return n}function i(t,e){if(0===e||e===(1<=a;++a)if(e&1<=s;++s)~e&1<n;++n)r[n]=i(t,n);return r}e.exports=a;var o=t("convex-hull")},{"convex-hull":71}],302:[function(t,e,r){"use strict";function n(t){switch(t){case"uint8":return[l.mallocUint8,l.freeUint8];case"uint16":return[l.mallocUint16,l.freeUint16];case"uint32":return[l.mallocUint32,l.freeUint32];case"int8":return[l.mallocInt8,l.freeInt8];case"int16":return[l.mallocInt16,l.freeInt16];case"int32":return[l.mallocInt32,l.freeInt32];case"float32":return[l.mallocFloat,l.freeFloat];case"float64":return[l.mallocDouble,l.freeDouble];default:return null}}function i(t){for(var e=[],r=0;t>r;++r)e.push("s"+r);for(var r=0;t>r;++r)e.push("n"+r);for(var r=1;t>r;++r)e.push("d"+r);for(var r=1;t>r;++r)e.push("e"+r);for(var r=1;t>r;++r)e.push("f"+r);return e}function a(t,e){function r(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function a(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}var o=["'use strict'"],s=["ndarrayInsertionSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(i(t.length)),u=n(e),c=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var f=[],h=1;h1){o.push("dptr=0;sptr=ptr");for(var h=t.length-1;h>=0;--h){var p=t[h];0!==p&&o.push(["for(i",p,"=0;i",p,"left){","dptr=0","sptr=cptr-s0");for(var h=1;hb){break __l}"].join(""));for(var h=t.length-1;h>=1;--h)o.push("sptr+=e"+h,"dptr+=f"+h,"}");o.push("dptr=cptr;sptr=cptr-s0");for(var h=t.length-1;h>=0;--h){var p=t[h];0!==p&&o.push(["for(i",p,"=0;i",p,"=0;--h){var p=t[h];0!==p&&o.push(["for(i",p,"=0;i",p,"left)&&("+r("cptr-s0")+">scratch)){",a("cptr",r("cptr-s0")),"cptr-=s0","}",a("cptr","scratch"));if(o.push("}"),t.length>1&&u&&o.push("free(scratch)"),o.push("} return "+s),u){var d=new Function("malloc","free",o.join("\n"));return d(u[0],u[1])}var d=new Function(o.join("\n"));return d()}function o(t,e,r){function a(t){return["(offset+",t,"*s0)"].join("")}function o(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function s(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}function l(e,r,n){if(1===e.length)_.push("ptr0="+a(e[0]));else for(var i=0;i=0;--i){var o=t[i];0!==o&&_.push(["for(i",o,"=0;i",o,"1)for(var i=0;i1?_.push("ptr_shift+=d"+o):_.push("ptr0+=d"+o),_.push("}"))}}function c(e,r,n,i){if(1===r.length)_.push("ptr0="+a(r[0]));else{for(var o=0;o1)for(var o=0;o=1;--o)n&&_.push("pivot_ptr+=f"+o),r.length>1?_.push("ptr_shift+=e"+o):_.push("ptr0+=e"+o),_.push("}")}function f(){t.length>1&&A&&_.push("free(pivot1)","free(pivot2)")}function h(e,r){var n="el"+e,i="el"+r;if(t.length>1){var s="__l"+ ++M;c(s,[n,i],!1,["comp=",o("ptr0"),"-",o("ptr1"),"\n","if(comp>0){tmp0=",n,";",n,"=",i,";",i,"=tmp0;break ",s,"}\n","if(comp<0){break ",s,"}"].join(""))}else _.push(["if(",o(a(n)),">",o(a(i)),"){tmp0=",n,";",n,"=",i,";",i,"=tmp0}"].join(""))}function p(e,r){t.length>1?l([e,r],!1,s("ptr0",o("ptr1"))):_.push(s(a(e),o(a(r))))}function d(e,r,n){if(t.length>1){var i="__l"+ ++M;c(i,[r],!0,[e,"=",o("ptr0"),"-pivot",n,"[pivot_ptr]\n","if(",e,"!==0){break ",i,"}"].join(""))}else _.push([e,"=",o(a(r)),"-pivot",n].join(""))}function g(e,r){t.length>1?l([e,r],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join("")):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join(""))}function v(e,r,n){t.length>1?(l([e,r,n],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join("")),_.push("++"+r,"--"+n)):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","ptr2=",a(n),"\n","++",r,"\n","--",n,"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join(""))}function m(t,e){g(t,e),_.push("--"+e)}function y(e,r,n){t.length>1?l([e,r],!0,[s("ptr0",o("ptr1")),"\n",s("ptr1",["pivot",n,"[pivot_ptr]"].join(""))].join("")):_.push(s(a(e),o(a(r))),s(a(r),"pivot"+n))}function b(e,r){_.push(["if((",r,"-",e,")<=",u,"){\n","insertionSort(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}else{\n",w,"(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}"].join(""))}function x(e,r,n){t.length>1?(_.push(["__l",++M,":while(true){"].join("")),l([e],!0,["if(",o("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",M,"}"].join("")),_.push(n,"}")):_.push(["while(",o(a(e)),"===pivot",r,"){",n,"}"].join(""))}var _=["'use strict'"],w=["ndarrayQuickSort",t.join("d"),e].join(""),k=["left","right","data","offset"].concat(i(t.length)),A=n(e),M=0;_.push(["function ",w,"(",k.join(","),"){"].join(""));var T=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var E=[],L=1;LL;++L)T.push("b_ptr"+L);T.push("ptr3","ptr4","ptr5","ptr6","ptr7","pivot_ptr","ptr_shift","elementSize="+E.join("*")),A?T.push("pivot1=malloc(elementSize)","pivot2=malloc(elementSize)"):T.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")}else T.push("pivot1","pivot2");if(_.push("var "+T.join(",")),h(1,2),h(4,5),h(1,3),h(2,3),h(1,4),h(3,4),h(2,5),h(2,3),h(4,5),t.length>1?l(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",o("ptr1"),"\n","pivot2[pivot_ptr]=",o("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",o("ptr0"),"\n","y=",o("ptr2"),"\n","z=",o("ptr4"),"\n",s("ptr5","x"),"\n",s("ptr6","y"),"\n",s("ptr7","z")].join("")):_.push(["pivot1=",o(a("el2")),"\n","pivot2=",o(a("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",o(a("el1")),"\n","y=",o(a("el3")),"\n","z=",o(a("el5")),"\n",s(a("index1"),"x"),"\n",s(a("index3"),"y"),"\n",s(a("index5"),"z")].join("")),p("index2","left"),p("index4","right"),_.push("if(pivots_are_equal){"),_.push("for(k=less;k<=great;++k){"),d("comp","k",1),_.push("if(comp===0){continue}"),_.push("if(comp<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),_.push("while(true){"),d("comp","great",1),_.push("if(comp>0){"),_.push("great--"),_.push("}else if(comp<0){"),v("k","less","great"),_.push("break"),_.push("}else{"),m("k","great"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}else{"),_.push("for(k=less;k<=great;++k){"),d("comp_pivot1","k",1),_.push("if(comp_pivot1<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),d("comp_pivot2","k",2),_.push("if(comp_pivot2>0){"),_.push("while(true){"),d("comp","great",2),_.push("if(comp>0){"),_.push("if(--greatindex5){"),x("less",1,"++less"),x("great",2,"--great"),_.push("for(k=less;k<=great;++k){"),d("comp_pivot1","k",1),_.push("if(comp_pivot1===0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),d("comp_pivot2","k",2),_.push("if(comp_pivot2===0){"),_.push("while(true){"),d("comp","great",2),_.push("if(comp===0){"),_.push("if(--great1&&A){var S=new Function("insertionSort","malloc","free",_.join("\n"));return S(r,A[0],A[1])}var S=new Function("insertionSort",_.join("\n"));return S(r)}function s(t,e){var r=["'use strict'"],n=["ndarraySortWrapper",t.join("d"),e].join(""),s=["array"];r.push(["function ",n,"(",s.join(","),"){"].join(""));for(var l=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"],c=0;c0?l.push(["d",v,"=s",v,"-d",d,"*n",d].join("")):l.push(["d",v,"=s",v].join("")),d=v);var p=t.length-1-c;0!==p&&(g>0?l.push(["e",p,"=s",p,"-e",g,"*n",g,",f",p,"=",f[p],"-f",g,"*n",g].join("")):l.push(["e",p,"=s",p,",f",p,"=",f[p]].join("")),g=p)}r.push("var "+l.join(","));var m=["0","n0-1","data","offset"].concat(i(t.length));r.push(["if(n0<=",u,"){","insertionSort(",m.join(","),")}else{","quickSort(",m.join(","),")}"].join("")),r.push("}return "+n);var y=new Function("insertionSort","quickSort",r.join("\n")),b=a(t,e),x=o(t,e,b);return y(b,x)}var l=t("typedarray-pool"),u=32;e.exports=s},{"typedarray-pool":306}],303:[function(t,e,r){"use strict";function n(t){var e=t.order,r=t.dtype,n=[e,r],o=n.join(":"),s=a[o];return s||(a[o]=s=i(e,r)),s(t),t}var i=t("./lib/compile_sort.js"),a={};e.exports=n},{"./lib/compile_sort.js":302}],304:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],305:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],306:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":304,buffer:65,dup:122}],307:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[0,0,0,1,1,0,1,1]),i=o(e,s.boxVert,s.lineFrag);return new n(t,r,i)}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawBox=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o){var s=this.plot,l=this.shader,u=s.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,l.uniforms.lo=t,l.uniforms.hi=e,l.uniforms.color=o,u.drawArrays(u.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":310,"gl-buffer":313,"gl-shader":328}],308:[function(t,e,r){"use strict";function n(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function i(t,e){return t-e}function a(t){var e=t.gl,r=o(e),i=s(e,u.gridVert,u.gridFrag),a=s(e,u.tickVert,u.gridFrag),l=new n(t,r,i,a);return l}e.exports=a;var o=t("gl-buffer"),s=t("gl-shader"),l=t("binary-search-bounds"),u=t("./shaders"),c=n.prototype;c.draw=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){for(var n=this.plot,i=this.vbo,a=this.shader,o=this.ticks,s=n.gl,l=n._tickBounds,u=n.dataBox,c=n.viewBox,f=n.gridLineWidth,h=n.gridLineColor,p=n.gridLineEnable,d=n.pixelRatio,g=0;2>g;++g){var v=l[g],m=l[g+2],y=m-v,b=.5*(u[g+2]+u[g]),x=u[g+2]-u[g];e[g]=2*y/x,t[g]=2*(v-b)/x}a.bind(),i.bind(),a.attributes.dataCoord.pointer(),a.uniforms.dataShift=t,a.uniforms.dataScale=e;for(var _=0,g=0;2>g;++g){r[0]=r[1]=0,r[g]=1,a.uniforms.dataAxis=r,a.uniforms.lineWidth=f[g]/(c[g+2]-c[g])*d,a.uniforms.color=h[g];var w=6*o[g].length;p[g]&&w&&s.drawArrays(s.TRIANGLES,_,w),_+=w}}}(),c.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],o=[0,0];return function(){for(var s=this.plot,u=this.vbo,c=this.tickShader,f=this.ticks,h=s.gl,p=s._tickBounds,d=s.dataBox,g=s.viewBox,v=s.pixelRatio,m=s.screenBox,y=m[2]-m[0],b=m[3]-m[1],x=g[2]-g[0],_=g[3]-g[1],w=0;2>w;++w){var k=p[w],A=p[w+2],M=A-k,T=.5*(d[w+2]+d[w]),E=d[w+2]-d[w];e[w]=2*M/E,t[w]=2*(k-T)/E}e[0]*=x/y,t[0]*=x/y,e[1]*=_/b,t[1]*=_/b,c.bind(),u.bind(),c.attributes.dataCoord.pointer();var L=c.uniforms;L.dataShift=t,L.dataScale=e;var S=s.tickMarkLength,C=s.tickMarkWidth,z=s.tickMarkColor,P=0,R=6*f[0].length,j=Math.min(l.ge(f[0],(d[0]-p[0])/(p[2]-p[0]),i),f[0].length),O=Math.min(l.gt(f[0],(d[2]-p[0])/(p[2]-p[0]),i),f[0].length),I=P+6*j,N=6*Math.max(0,O-j),F=Math.min(l.ge(f[1],(d[1]-p[1])/(p[3]-p[1]),i),f[1].length),D=Math.min(l.gt(f[1],(d[3]-p[1])/(p[3]-p[1]),i),f[1].length),B=R+6*F,U=6*Math.max(0,D-F);a[0]=2*(g[0]-S[1])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[1]*v/y,o[1]=C[1]*v/b,U&&(L.color=z[1],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[1]-S[0])/b-1,o[0]=C[0]*v/y,o[1]=S[0]*v/b,N&&(L.color=z[0],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,I,N)),a[0]=2*(g[2]+S[3])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[3]*v/y,o[1]=C[3]*v/b,U&&(L.color=z[3],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[3]+S[2])/b-1,o[0]=C[2]*v/y,o[1]=S[2]*v/b,N&&(L.color=z[2],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,I,N))}}(),c.update=function(){var t=[1,1,-1,-1,1,-1],e=[1,-1,1,1,-1,-1];return function(r){for(var n=r.ticks,i=r.bounds,a=new Float32Array(18*(n[0].length+n[1].length)),o=(this.plot.zeroLineEnable,0),s=[[],[]],l=0;2>l;++l)for(var u=s[l],c=n[l],f=i[l],h=i[l+2],p=0;pg;++g)a[o++]=d,a[o++]=t[g],a[o++]=e[g]}this.ticks=s,this.vbo.update(a)}}(),c.dispose=function(){this.vbo.dispose(),this.shader.dispose(),this.tickShader.dispose()}},{"./shaders":310,"binary-search-bounds":312,"gl-buffer":313,"gl-shader":328}],309:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[-1,-1,-1,1,1,-1,1,1]),i=o(e,s.lineVert,s.lineFrag),l=new n(t,r,i);return l}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawLine=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o,s){var l=this.plot,u=this.shader,c=l.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,u.uniforms.start=t,u.uniforms.end=e,u.uniforms.width=o*l.pixelRatio,u.uniforms.color=s,c.drawArrays(c.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":310,"gl-buffer":313,"gl-shader":328}],310:[function(t,e,r){"use strict";var n="precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n";e.exports={lineVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n",lineFrag:n,textVert:"#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n",textFrag:n,gridVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n",gridFrag:n,boxVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n",tickVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"}},{}],311:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r,this.tickOffset=[[],[]],this.tickX=[[],[]],this.labelOffset=[0,0],this.labelCount=[0,0]}function i(t){var e=t.gl,r=a(e),i=o(e,u.textVert,u.textFrag),s=new n(t,r,i);return s}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("text-cache"),l=t("binary-search-bounds"),u=t("./shaders"),c=n.prototype;c.drawTicks=function(){var t=[0,0],e=[0,0],r=[0,0];return function(n){var i=this.plot,a=this.shader,o=this.tickX[n],s=this.tickOffset[n],u=i.gl,c=i.viewBox,f=i.dataBox,h=i.screenBox,p=i.pixelRatio,d=i.tickEnable,g=i.tickPad,v=i.tickColor,m=i.tickAngle,y=(i.tickMarkLength, +i.labelEnable),b=i.labelPad,x=i.labelColor,_=i.labelAngle,w=this.labelOffset[n],k=this.labelCount[n],A=l.lt(o,f[n]),M=l.le(o,f[n+2]);t[0]=t[1]=0,t[n]=1,e[n]=(c[2+n]+c[n])/(h[2+n]-h[n])-1;var T=2/h[2+(1^n)]-h[1^n];e[1^n]=T*c[1^n]-1,d[n]&&(e[1^n]-=T*p*g[n],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n],a.uniforms.angle=m[n],u.drawArrays(u.TRIANGLES,s[A],s[M]-s[A]))),y[n]&&k&&(e[1^n]-=T*p*b[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=_[n],u.drawArrays(u.TRIANGLES,w,k)),e[1^n]=T*c[2+(1^n)]-1,d[n+2]&&(e[1^n]+=T*p*g[n+2],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n+2],a.uniforms.angle=m[n+2],u.drawArrays(u.TRIANGLES,s[A],s[M]-s[A]))),y[n+2]&&k&&(e[1^n]+=T*p*b[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=_[n+2],u.drawArrays(u.TRIANGLES,w,k))}}(),c.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,o=r.titleCenter,u=r.pixelRatio;if(this.titleCount){for(var c=0;2>c;++c)e[c]=2*(o[c]*u-a[c])/(a[2+c]-a[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),c.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var u=0;2>u;++u){var c=a[u],f=a[u+2],h=f-c,p=.5*(o[u+2]+o[u]),d=o[u+2]-o[u],g=l[u],v=l[u+2],m=v-g,y=s[u],b=s[u+2],x=b-y;e[u]=2*h/d*m/x,t[u]=2*(c-p)/d*m/x}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),c.update=function(t){for(var e=[],r=t.ticks,n=t.bounds,i=0;2>i;++i){for(var a=[Math.floor(e.length/3)],o=[-(1/0)],l=r[i],u=0;ui;++i){this.labelOffset[i]=Math.floor(e.length/3);for(var g=s(t.labelFont[i],t.labels[i]).data,d=t.labelSize[i],u=0;u>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],313:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":316}],314:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],315:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],316:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":314,buffer:65,dup:122}],317:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],318:[function(t,e,r){e.exports=t("cwise-compiler")},{"cwise-compiler":319}],319:[function(t,e,r){"use strict";function n(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function i(t){var e=new n;e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var i=0;i0)throw new Error("cwise: pre() block may not reference array args");if(i0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if("index"===o){if(e.indexArgs.push(i),i0)throw new Error("cwise: pre() block may not reference array index");if(i0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(e.shapeArgs.push(i),ir.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,a(e)}var a=t("./lib/thunk.js");e.exports=i},{"./lib/thunk.js":321}],320:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],u=[],c=0,f=0;for(n=0;a>n;++n)u.push(["i",n,"=0"].join(""));for(i=0;o>i;++i)for(n=0;a>n;++n)f=c,c=t[n],0===n?u.push(["d",i,"s",n,"=t",i,"p",c].join("")):u.push(["d",i,"s",n,"=(t",i,"p",c,"-s",f,"*t",i,"p",f,")"].join(""));for(l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"n;++n){for(f=c,c=t[n],i=0;o>i;++i)l.push(["p",i,"+=d",i,"s",n].join(""));s&&(n>0&&l.push(["index[",f,"]-=s",f].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function i(t,e,r,i){for(var a=e.length,o=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,u=[],c=0;o>c;++c)u.push(["var offset",c,"=p",c].join(""));for(var c=t;a>c;++c)u.push(["for(var j"+c+"=SS[",e[c],"]|0;j",c,">0;){"].join("")),u.push(["if(j",c,"<",s,"){"].join("")),u.push(["s",e[c],"=j",c].join("")),u.push(["j",c,"=0"].join("")),u.push(["}else{s",e[c],"=",s].join("")),u.push(["j",c,"-=",s,"}"].join("")),l&&u.push(["index[",e[c],"]=j",c].join(""));for(var c=0;o>c;++c){for(var f=["offset"+c],h=t;a>h;++h)f.push(["j",h,"*t",c,"p",e[h]].join(""));u.push(["p",c,"=(",f.join("+"),")"].join(""))}u.push(n(e,r,i));for(var c=t;a>c;++c)u.push("}");return u.join("\n")}function a(t){for(var e=0,r=t[0].length;r>e;){for(var n=1;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}function l(t,e){for(var r=e[1].length-Math.abs(t.arrayBlockIndices[0])|0,l=new Array(t.arrayArgs.length),c=new Array(t.arrayArgs.length),f=0;fy;++y)_.push(["s",y,"=SS[",y,"]"].join(""));for(var f=0;fy;++y)_.push(["t",f,"p",y,"=t",f,"[",d[f]+y,"]"].join(""));for(var y=0;y0&&_.push("shape=SS.slice(0)"),t.indexArgs.length>0){for(var w=new Array(r),f=0;r>f;++f)w[f]="0";_.push(["index=[",w.join(","),"]"].join(""))}for(var f=0;f3&&x.push(o(t.pre,t,c));var T=o(t.body,t,c),E=a(v);r>E?x.push(i(E,v[0],t,T)):x.push(n(v[0],t,T)),t.post.body.length>3&&x.push(o(t.post,t,c)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+x.join("\n")+"\n----------");var L=[t.funcName||"unnamed","_cwise_loop_",l[0].join("s"),"m",E,s(c)].join(""),S=new Function(["function ",L,"(",b.join(","),"){",x.join("\n"),"} return ",L].join(""));return S()}var u=t("uniq");e.exports=l},{uniq:322}],321:[function(t,e,r){"use strict";function n(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],u=[],c=0;c0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[c]))),u.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[c])+"]"))}t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),e.push("if (!("+u.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}"));for(var c=0;c=n;++n){for(var i=new Array(r),a=0;n>a;++a)i[a]=t.COLOR_ATTACHMENT0+a;for(var a=n;r>a;++a)i[a]=t.NONE;y[n]=i}}function o(t){switch(t){case d:throw new Error("gl-fbo: Framebuffer unsupported");case g:throw new Error("gl-fbo: Framebuffer incomplete attachment");case v:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case m:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function s(t,e,r,n,i,a){if(!n)return null;var o=p(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function l(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function u(t){var e=n(t.gl),r=t.gl,a=t.handle=r.createFramebuffer(),u=t._shape[0],c=t._shape[1],f=t.color.length,h=t._ext,p=t._useStencil,d=t._useDepth,g=t._colorType;r.bindFramebuffer(r.FRAMEBUFFER,a);for(var v=0;f>v;++v)t.color[v]=s(r,u,c,g,r.RGBA,r.COLOR_ATTACHMENT0+v);0===f?(t._color_rb=l(r,u,c,r.RGBA4,r.COLOR_ATTACHMENT0),h&&h.drawBuffersWEBGL(y[0])):f>1&&h.drawBuffersWEBGL(y[f]);var m=r.getExtension("WEBGL_depth_texture");m?p?t.depth=s(r,u,c,m.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):d&&(t.depth=s(r,u,c,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):d&&p?t._depth_rb=l(r,u,c,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):d?t._depth_rb=l(r,u,c,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):p&&(t._depth_rb=l(r,u,c,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var b=r.checkFramebufferStatus(r.FRAMEBUFFER);if(b!==r.FRAMEBUFFER_COMPLETE){t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null);for(var v=0;vl;++l)this.color[l]=null;this._color_rb=null,this.depth=null,this._depth_rb=null,this._colorType=n,this._useDepth=a,this._useStencil=o;var c=this,f=[0|e,0|r];Object.defineProperties(f,{0:{get:function(){return c._shape[0]},set:function(t){return c.width=t}},1:{get:function(){return c._shape[1]},set:function(t){return c.height=t}}}),this._shapeVector=f,u(this)}function f(t,e,r){if(t._destroyed)throw new Error("gl-fbo: Can't resize destroyed FBO");if(t._shape[0]!==e||t._shape[1]!==r){var a=t.gl,s=a.getParameter(a.MAX_RENDERBUFFER_SIZE);if(0>e||e>s||0>r||r>s)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var l=n(a),u=0;ue||e>o||0>r||r>o)throw new Error("gl-fbo: Parameters are too large for FBO");n=n||{};var s=1;if("color"in n){if(s=Math.max(0|n.color,0),0>s)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(s>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(s>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+s+" draw buffers")}}var l=t.UNSIGNED_BYTE,u=t.getExtension("OES_texture_float");if(n.float&&s>0){if(!u)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&s>0&&u&&(l=t.FLOAT);var f=!0;"depth"in n&&(f=!!n.depth);var h=!1;return"stencil"in n&&(h=!!n.stencil),new c(t,e,r,l,s,f,h,i)}var p=t("gl-texture2d");e.exports=h;var d,g,v,m,y=null,b=c.prototype;Object.defineProperties(b,{shape:{get:function(){return this._destroyed?[0,0]:this._shapeVector},set:function(t){if(Array.isArray(t)||(t=[0|t,0|t]),2!==t.length)throw new Error("gl-fbo: Shape vector must be length 2");var e=0|t[0],r=0|t[1];return f(this,e,r),[e,r]},enumerable:!1},width:{get:function(){return this._destroyed?0:this._shape[0]},set:function(t){return t=0|t,f(this,t,this._shape[1]),t},enumerable:!1},height:{get:function(){return this._destroyed?0:this._shape[1]},set:function(t){return t=0|t,f(this,this._shape[0],t),t},enumerable:!1}}),b.bind=function(){if(!this._destroyed){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.handle),t.viewport(0,0,this._shape[0],this._shape[1])}},b.dispose=function(){if(!this._destroyed){this._destroyed=!0;var t=this.gl;t.deleteFramebuffer(this.handle),this.handle=null,this.depth&&(this.depth.dispose(),this.depth=null),this._depth_rb&&(t.deleteRenderbuffer(this._depth_rb),this._depth_rb=null);for(var e=0;e_inline_1_arg0_||255>_inline_1_arg1_||255>_inline_1_arg2_||255>_inline_1_arg3_){var _inline_1_l=_inline_1_arg4_-_inline_1_arg6_[0],_inline_1_a=_inline_1_arg5_-_inline_1_arg6_[1],_inline_1_f=_inline_1_l*_inline_1_l+_inline_1_a*_inline_1_a;_inline_1_fthis.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(u(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),f.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},f.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},f.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),u=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=u)return null;var f=[o-a,u-s],h=l(this.buffer,[f[0],f[1],4],[4,4*i[0],1],4*(a+i[0]*s)),p=c(h.hi(f[0],f[1],1),r,r),d=p[0],g=p[1];if(0>d||Math.pow(this.radius,2)l;++l)for(var u=t[l],c=0;2>c;++c)a[c]=0|Math.min(a[c],u[c]),o[c]=0|Math.max(o[c],u[c]);var f=0;switch(n){case"center":f=-.5*(a[0]+o[0]);break;case"right":case"end":f=-o[0];break;case"left":case"start":f=-a[0];break;default:throw new Error("vectorize-text: Unrecognized textAlign: '"+n+"'")}var h=0;switch(i){case"hanging":case"top":h=-a[1];break;case"middle":h=-.5*(a[1]+o[1]);break;case"alphabetic":case"ideographic":h=-3*r;break;case"bottom":h=-o[1];break;default:throw new Error("vectorize-text: Unrecoginized textBaseline: '"+i+"'")}var p=1/r;return"lineHeight"in e?p*=+e.lineHeight:"width"in e?p=e.width/(o[0]-a[0]):"height"in e&&(p=e.height/(o[1]-a[1])),t.map(function(t){return[p*(t[0]+f),p*(t[1]+h)]})}function i(t,e,r,n){var i=0|Math.ceil(e.measureText(r).width+2*n);if(i>8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.heights)){if(n>i){var l=n;n=i,i=l,l=o,o=s,s=l}e.isConstraint(n,i)||a(t[n],t[i],t[o],t[s])<0&&r.push(n,i)}}function i(t,e){for(var r=[],i=t.length,o=e.stars,s=0;i>s;++s)for(var l=o[s],u=1;uc||e.isConstraint(s,c))){for(var f=l[u-1],h=-1,p=1;ph||a(t[s],t[c],t[f],t[h])<0&&r.push(s,c)}}for(;r.length>0;){for(var c=r.pop(),s=r.pop(),f=-1,h=-1,l=o[s],d=1;df||0>h||a(t[s],t[c],t[f],t[h])>=0||(e.flip(s,c),n(t,e,r,f,s,h),n(t,e,r,s,h,f),n(t,e,r,h,c,f),n(t,e,r,c,f,h))}}var a=t("robust-in-sphere")[4];t("binary-search-bounds");e.exports=i},{"binary-search-bounds":312,"robust-in-sphere":361}],358:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function i(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}function a(t,e){for(var r=t.cells(),a=r.length,o=0;a>o;++o){var s=r[o],l=s[0],u=s[1],c=s[2];c>u?l>u&&(s[0]=u,s[1]=c,s[2]=l):l>c&&(s[0]=c,s[1]=l,s[2]=u)}r.sort(i);for(var f=new Array(a),o=0;oo;++o)for(var s=r[o],y=0;3>y;++y){var l=s[y],u=s[(y+1)%3],b=d[3*o+y]=m.locate(u,l,t.opposite(u,l)),x=g[3*o+y]=t.isConstraint(l,u);0>b&&(x?p.push(o):(h.push(o),f[o]=1),e&&v.push([u,l,-1]))}return m}function o(t,e,r){for(var n=0,i=0;i0||l.length>0;){for(;s.length>0;){var p=s.pop();if(u[p]!==-i){u[p]=i;for(var d=(c[p],0);3>d;++d){var g=h[3*p+d];g>=0&&0===u[g]&&(f[3*p+d]?l.push(g):(s.push(g),u[g]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var m=o(c,u,e);return r?m.concat(n.boundary):m}var l=t("binary-search-bounds");e.exports=s;var u=n.prototype;u.locate=function(){var t=[0,0,0];return function(e,r,n){var a=e,o=r,s=n;return n>r?e>r&&(a=r,o=n,s=e):e>n&&(a=n,o=e,s=r), +0>a?-1:(t[0]=a,t[1]=o,t[2]=s,l.eq(this.cells,t,i))}}()},{"binary-search-bounds":312}],359:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.a=t,this.b=e,this.idx=r,this.lowerIds=n,this.upperIds=i}function i(t,e,r,n){this.a=t,this.b=e,this.type=r,this.idx=n}function a(t,e){var r=t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.type-e.type;return r?r:t.type!==d&&(r=p(t.a,t.b,e.b))?r:t.idx-e.idx}function o(t,e){return p(t.a,t.b,e)}function s(t,e,r,n,i){for(var a=h.lt(e,n,o),s=h.gt(e,n,o),l=a;s>l;++l){for(var u=e[l],c=u.lowerIds,f=c.length;f>1&&p(r[c[f-2]],r[c[f-1]],n)>0;)t.push([c[f-1],c[f-2],i]),f-=1;c.length=f,c.push(i);for(var d=u.upperIds,f=d.length;f>1&&p(r[d[f-2]],r[d[f-1]],n)<0;)t.push([d[f-2],d[f-1],i]),f-=1;d.length=f,d.push(i)}}function l(t,e){var r;return(r=t.a[0]f;++f)l.push(new i(t[f],null,d,f));for(var f=0;o>f;++f){var h=e[f],p=t[h[0]],m=t[h[1]];p[0]m[0]&&l.push(new i(m,p,v,f),new i(p,m,g,f))}l.sort(a);for(var y=l[0].a[0]-(1+Math.abs(l[0].a[0]))*Math.pow(2,-52),b=[new n([y,1],[y,0],-1,[],[],[],[])],x=[],f=0,_=l.length;_>f;++f){var w=l[f],k=w.type;k===d?s(x,b,t,w.a,w.idx):k===v?u(b,t,w):c(b,t,w)}return x}var h=t("binary-search-bounds"),p=t("robust-orientation")[3],d=0,g=1,v=2;e.exports=f},{"binary-search-bounds":312,"robust-orientation":1040}],360:[function(t,e,r){"use strict";function n(t,e){this.stars=t,this.edges=e}function i(t,e,r){for(var n=1,i=t.length;i>n;n+=2)if(t[n-1]===e&&t[n]===r)return t[n-1]=t[i-2],t[n]=t[i-1],void(t.length=i-2)}function a(t,e){for(var r=new Array(t),i=0;t>i;++i)r[i]=[];return new n(r,e)}var o=t("binary-search-bounds");e.exports=a;var s=n.prototype;s.isConstraint=function(){function t(t,e){return t[0]-e[0]||t[1]-e[1]}var e=[0,0];return function(r,n){return e[0]=Math.min(r,n),e[1]=Math.max(r,n),o.eq(this.edges,e,t)>=0}}(),s.removeTriangle=function(t,e,r){var n=this.stars;i(n[t],e,r),i(n[e],r,t),i(n[r],t,e)},s.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},s.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;i>n;n+=2)if(r[n]===t)return r[n-1];return-1},s.flip=function(t,e){var r=this.opposite(t,e),n=this.opposite(e,t);this.removeTriangle(t,e,r),this.removeTriangle(e,t,n),this.addTriangle(t,n,r),this.addTriangle(e,r,n)},s.edges=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2)e.push([i[a],i[a+1]]);return e},s.cells=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2){var s=i[a],l=i[a+1];rr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-2,"]"].join("")}return e}function a(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",a(t.slice(0,e)),",",a(t.slice(e)),")"].join("")}function o(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return o(e,t)}function s(t){return t&!0?"-":""}function l(t){if(2===t.length)return[["diff(",o(t[0][0],t[1][1]),",",o(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;rn;++n)r.push(["prod(m",t,"[",n,"],m",t,"[",n,"])"].join(""));return a(r)}function c(t){for(var e=[],r=[],o=i(t),s=0;t>s;++s)o[0][s]="1",o[t-1][s]="w"+s;for(var s=0;t>s;++s)0===(1&s)?e.push.apply(e,l(n(o,s))):r.push.apply(r,l(n(o,s)));for(var c=a(e),f=a(r),h="exactInSphere"+t,p=[],s=0;t>s;++s)p.push("m"+s);for(var d=["function ",h,"(",p.join(),"){"],s=0;t>s;++s){d.push("var w",s,"=",u(s,t),";");for(var g=0;t>g;++g)g!==s&&d.push("var w",s,"m",g,"=scale(w",s,",m",g,"[0]);")}d.push("var p=",c,",n=",f,",d=diff(p,n);return d[d.length-1];}return ",h);var x=new Function("sum","diff","prod","scale",d.join(""));return x(m,y,v,b)}function f(){return 0}function h(){return 0}function p(){return 0}function d(t){var e=_[t.length];return e||(e=_[t.length]=c(t.length)),e.apply(void 0,t)}function g(){for(;_.length<=x;)_.push(c(_.length));for(var t=[],r=["slow"],n=0;x>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function testInSphere(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;x>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var v=t("two-product"),m=t("robust-sum"),y=t("robust-subtract"),b=t("robust-scale"),x=6,_=[f,h,p];g()},{"robust-scale":363,"robust-subtract":364,"robust-sum":365,"two-product":366}],362:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],363:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":366,"two-sum":362}],364:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],-e[0]);var a,o,s=r+i,l=new Array(s),u=0,c=0,f=0,h=Math.abs,p=t[c],d=h(p),g=-e[f],v=h(g);v>d?(o=p,c+=1,r>c&&(p=t[c],d=h(p))):(o=g,f+=1,i>f&&(g=-e[f],v=h(g))),r>c&&v>d||f>=i?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>c&&i>f;)v>d?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>c;)a=p,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,c+=1,r>c&&(p=t[c]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=-e[f]);return M&&(l[u++]=M),T&&(l[u++]=T),u||(l[u++]=0),l.length=u,l}e.exports=i},{}],365:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],366:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],367:[function(t,e,r){"use strict";function n(t){var e=x(t),r=b(y(e),t);return 0>r?[e,w(e,1/0)]:r>0?[w(e,-(1/0)),e]:[e,e]}function i(t,e){for(var r=new Array(e.length),n=0;n=t.length)return o[e-t.length];var r=t[e];return[y(r[0]),y(r[1])]}for(var o=[],s=0;s=0;--s){var g=n[s],u=g[0],v=e[u],m=v[0],x=v[1],w=t[m],A=t[x];if((w[0]-A[0]||w[1]-A[1])<0){var M=m;m=x,x=M}v[0]=m;var T,E=v[1]=g[1];for(i&&(T=v[2]);s>0&&n[s-1][0]===u;){var g=n[--s],L=g[1];i?e.push([E,L,T]):e.push([E,L]),E=L}i?e.push([E,x,T]):e.push([E,x])}return o}function u(t,e,r){for(var i=t.length+e.length,a=new g(i),o=r,s=0;ss;++s){var d=a.find(s);d===s?(p[s]=f,t[f++]=t[s]):(h=!1,p[s]=-1)}if(t.length=f,h)return null;for(var s=0;i>s;++s)p[s]<0&&(p[s]=p[a.find(s)]);return p}function c(t,e){return t[0]-e[0]||t[1]-e[1]}function f(t,e){var r=t[0]-e[0]||t[1]-e[1];return r?r:t[2]e[2]?1:0}function h(t,e,r){if(0!==t.length){if(e)for(var n=0;n0||p.length>0}function d(t,e,r){var n,i=!1;if(r){n=e;for(var a=new Array(e.length),o=0;o0?r=r.shln(f):0>f&&(c=c.shln(-f)),l(r,c)}var i=t("./is-rat"),a=t("./lib/is-bn"),o=t("./lib/num-to-bn"),s=t("./lib/str-to-bn"),l=t("./lib/rationalize"),u=t("./div");e.exports=n},{"./div":371,"./is-rat":373,"./lib/is-bn":377,"./lib/num-to-bn":378,"./lib/rationalize":379,"./lib/str-to-bn":380}],373:[function(t,e,r){"use strict";function n(t){return Array.isArray(t)&&2===t.length&&i(t[0])&&i(t[1])}var i=t("./lib/is-bn");e.exports=n},{"./lib/is-bn":377}],374:[function(t,e,r){"use strict";function n(t){return t.cmp(new i(0))}var i=t("bn.js");e.exports=n},{"bn.js":383}],375:[function(t,e,r){"use strict";function n(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var n=0,i=0;e>i;i++){var a=r[i];n+=a*Math.pow(67108864,i)}return t.sign?-n:n}e.exports=n},{}],376:[function(t,e,r){"use strict";function n(t){var e=a(i.lo(t));if(32>e)return e;var r=a(i.hi(t));return r>20?52:r+32}var i=t("double-bits"),a=t("bit-twiddle").countTrailingZeros;e.exports=n},{"bit-twiddle":382,"double-bits":384}],377:[function(t,e,r){"use strict";function n(t){return t&&"object"==typeof t&&Boolean(t.words)}t("bn.js");e.exports=n},{"bn.js":383}],378:[function(t,e,r){"use strict";function n(t){var e=a.exponent(t);return 52>e?new i(t):new i(t*Math.pow(2,52-e)).shln(e-52)}var i=t("bn.js"),a=t("double-bits");e.exports=n},{"bn.js":383,"double-bits":384}],379:[function(t,e,r){"use strict";function n(t,e){var r=a(t),n=a(e);if(0===r)return[i(0),i(1)];if(0===n)return[i(0),i(0)];0>n&&(t=t.neg(),e=e.neg());var o=t.gcd(e);return o.cmpn(1)?[t.div(o),e.div(o)]:[t,e]}var i=t("./num-to-bn"),a=t("./bn-sign");e.exports=n},{"./bn-sign":374,"./num-to-bn":378}],380:[function(t,e,r){"use strict";function n(t){return new i(t)}var i=t("bn.js");e.exports=n},{"bn.js":383}],381:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[0]),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":379}],382:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],383:[function(t,e,r){!function(t,e){"use strict";function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){return null!==t&&"object"==typeof t&&Array.isArray(t.words)?t:(this.sign=!1,this.words=null,this.length=0,this.red=null,"le"!==e&&"be"!==e||(r=e,e=10),void(null!==t&&this._init(t||0,e||10,r||"be")))}function a(t,e,r){for(var n=0,i=Math.min(t.length,r),a=e;i>a;a++){var o=t.charCodeAt(a)-48;n<<=4,n|=o>=49&&54>=o?o-49+10:o>=17&&22>=o?o-17+10:15&o}return n}function o(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;a>o;o++){var s=t.charCodeAt(o)-48;i*=n,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}function s(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).ishln(this.n).isub(this.p),this.tmp=this._tmp()}function l(){s.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function u(){s.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function c(){s.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function f(){s.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function h(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else this.m=t,this.prime=null}function p(t){h.call(this,t),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).ishln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv.sign=!0,this.minv=this.minv.mod(this.r)}"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26,i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&36>=e),t=t.toString().replace(/\s+/g,"");var i=0;"-"===t[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.sign=!0),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){0>t&&(this.sign=!0,t=-t),67108864>t?(this.words=[67108863&t],this.length=1):4503599627370496>t?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(9007199254740992>t),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3){var s=t[i]|t[i-1]<<8|t[i-2]<<16;this.words[o]|=s<>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}else if("le"===n)for(var i=0,o=0;i>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6){var o=a(t,r,r+6);this.words[i]|=o<>>26-n&4194303,n+=24,n>=26&&(n-=26,i++)}if(r+6!==e){var o=a(t,e,r+6);this.words[i]|=o<>>26-n&4194303}this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;67108863>=i;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,s=a%n,l=Math.min(a,a-s)+r,u=0,c=r;l>c;c+=n)u=o(t,c,c+n,e),this.imuln(i),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u);if(0!==s){for(var f=1,u=o(t,c,t.length,e),c=0;s>c;c++)f*=e;this.imuln(f),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u)}},i.prototype.copy=function(t){t.words=new Array(this.length);for(var e=0;e1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.sign=!1),this},i.prototype.inspect=function(){return(this.red?""};var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],v=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(t,e){if(t=t||10,16===t||"hex"===t){for(var n="",i=0,e=0|e||1,a=0,o=0;o>>24-i&16777215,n=0!==a||o!==this.length-1?d[6-l.length]+l+n:l+n,i+=2,i>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!==0;)n="0"+n;return this.sign&&(n="-"+n),n}if(t===(0|t)&&t>=2&&36>=t){var u=g[t],c=v[t],n="",f=this.clone();for(f.sign=!1;0!==f.cmpn(0);){var h=f.modn(c).toString(t);f=f.idivn(c),n=0!==f.cmpn(0)?d[u-h.length]+h+n:h+n}return 0===this.cmpn(0)&&(n="0"+n),this.sign&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toArray=function(t){this.strip();var e=new Array(this.byteLength());e[0]=0;var r=this.clone();if("le"!==t)for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[e.length-n-1]=i}else for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[n]=i}return e},Math.clz32?i.prototype._countBits=function(t){return 32-Math.clz32(t)}:i.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0===(8191&e)&&(r+=13,e>>>=13),0===(127&e)&&(r+=7,e>>>=7),0===(15&e)&&(r+=4,e>>>=4),0===(3&e)&&(r+=2,e>>>=2),0===(1&e)&&r++,r},i.prototype.bitLength=function(){var t=0,e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(0===this.cmpn(0))return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.iand=function(t){this.sign=this.sign&&t.sign;var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.ixor=function(t){this.sign=this.sign||t.sign;var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);for(var n=t/26|0,i=t%26;this.length<=n;)this.words[this.length++]=0;return e?this.words[n]=this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26}for(;0!==i&&a>>26}if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(t.sign){t.sign=!1;var e=this.iadd(t);return t.sign=!0,e._normSign()}if(this.sign)return this.sign=!1,this.iadd(t),this.sign=!0,this._normSign();var r=this.cmp(t);if(0===r)return this.sign=!1,this.length=1,this.words[0]=0,this;var n,i;r>0?(n=this,i=t):(n=t,i=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e}for(;0!==a&&o>26,this.words[o]=67108863&e}if(0===a&&o>>26,a=67108863&r,o=Math.min(n,t.length-1),s=Math.max(0,n-this.length+1);o>=s;s++){var l=n-s,u=0|this.words[l],c=0|t.words[s],f=u*c,h=67108863&f;i=i+(f/67108864|0)|0,h=h+a|0,a=67108863&h,i=i+(h>>>26)|0}e.words[n]=a,r=i}return 0!==r?e.words[n]=r:e.length--,e.strip()},i.prototype._bigMulTo=function(t,e){e.sign=t.sign!==this.sign,e.length=this.length+t.length;for(var r=0,n=0,i=0;i=l;l++){var u=i-l,c=0|this.words[u],f=0|t.words[l],h=c*f,p=67108863&h;a=a+(h/67108864|0)|0,p=p+o|0,o=67108863&p,a=a+(p>>>26)|0,n+=a>>>26,a&=67108863}e.words[i]=o,r=a,a=n}return 0!==r?e.words[i]=r:e.length--,e.strip()},i.prototype.mulTo=function(t,e){var r;return r=this.length+t.length<63?this._smallMulTo(t,e):this._bigMulTo(t,e)},i.prototype.mul=function(t){var e=new i(null);return e.words=new Array(this.length+t.length),this.mulTo(t,e)},i.prototype.imul=function(t){if(0===this.cmpn(0)||0===t.cmpn(0))return this.words[0]=0,this.length=1,this;var e=this.length,r=t.length;this.sign=t.sign!==this.sign,this.length=this.length+t.length,this.words[this.length-1]=0;for(var n=this.length-2;n>=0;n--){for(var i=0,a=0,o=Math.min(n,r-1),s=Math.max(0,n-e+1);o>=s;s++){var l=n-s,u=this.words[l],c=t.words[s],f=u*c,h=67108863&f;i+=f/67108864|0,h+=a,a=67108863&h,i+=h>>>26}this.words[n]=a,this.words[n+1]+=i,i=0}for(var i=0,l=1;l>>26}return this.strip()},i.prototype.imuln=function(t){r("number"==typeof t);for(var e=0,n=0;n>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.mul(this)},i.prototype.ishln=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=67108863>>>26-e<<26-e;if(0!==e){for(var a=0,o=0;o>>26-e}a&&(this.words[o]=a,this.length++)}if(0!==n){for(var o=this.length-1;o>=0;o--)this.words[o+n]=this.words[o];for(var o=0;n>o;o++)this.words[o]=0;this.length+=n}return this.strip()},i.prototype.ishrn=function(t,e,n){r("number"==typeof t&&t>=0);var i;i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<u;u++)l.words[u]=this.words[u];l.length=o}if(0===o);else if(this.length>o){this.length-=o;for(var u=0;u=0&&(0!==c||u>=i);u--){var f=this.words[u];this.words[u]=c<<26-a|f>>>a,c=f&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip(),this},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(!this.sign,"imaskn works only with positive numbers"),0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<t?this.isubn(-t):this.sign?1===this.length&&this.words[0]=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),0>t)return this.iaddn(-t);if(this.sign)return this.sign=!1,this.iaddn(t),this.sign=!0,this;this.words[0]-=t;for(var e=0;e>26)-(u/67108864|0),this.words[i+n]=67108863&l}for(;i>26,this.words[i+n]=67108863&l}if(0===s)return this.strip();r(-1===s),s=0;for(var i=0;i>26,this.words[i]=67108863&l}return this.sign=!0,this.strip()},i.prototype._wordDiv=function(t,e){var r=this.length-t.length,n=this.clone(),a=t,o=a.words[a.length-1],s=this._countBits(o);r=26-s,0!==r&&(a=a.shln(r),n.ishln(r),o=a.words[a.length-1]);var l,u=n.length-a.length;if("mod"!==e){l=new i(null),l.length=u+1,l.words=new Array(l.length);for(var c=0;c=0;h--){var p=67108864*n.words[a.length+h]+n.words[a.length+h-1];for(p=Math.min(p/o|0,67108863),n._ishlnsubmul(a,p,h);n.sign;)p--,n.sign=!1,n._ishlnsubmul(a,1,h),0!==n.cmpn(0)&&(n.sign=!n.sign);l&&(l.words[h]=p)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.ishrn(r),{div:l?l:null,mod:n}},i.prototype.divmod=function(t,e){if(r(0!==t.cmpn(0)),this.sign&&!t.sign){var n,a,o=this.neg().divmod(t,e);return"mod"!==e&&(n=o.div.neg()),"div"!==e&&(a=0===o.mod.cmpn(0)?o.mod:t.sub(o.mod)),{div:n,mod:a}}if(!this.sign&&t.sign){var n,o=this.divmod(t.neg(),e);return"mod"!==e&&(n=o.div.neg()),{div:n,mod:o.mod}}return this.sign&&t.sign?this.neg().divmod(t.neg(),e):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e)},i.prototype.div=function(t){return this.divmod(t,"div").div},i.prototype.mod=function(t){return this.divmod(t,"mod").mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(0===e.mod.cmpn(0))return e.div;var r=e.div.sign?e.mod.isub(t):e.mod,n=t.shrn(1),i=t.andln(1),a=r.cmp(n);return 0>a||1===i&&0===a?e.div:e.div.sign?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(67108863>=t);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+this.words[i])%t;return n},i.prototype.idivn=function(t){r(67108863>=t);for(var e=0,n=this.length-1;n>=0;n--){var i=this.words[n]+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.ishrn(1),n.ishrn(1),++u;for(var c=n.clone(),f=e.clone();0!==e.cmpn(0);){for(;e.isEven();)e.ishrn(1),a.isEven()&&o.isEven()?(a.ishrn(1),o.ishrn(1)):(a.iadd(c).ishrn(1),o.isub(f).ishrn(1));for(;n.isEven();)n.ishrn(1),s.isEven()&&l.isEven()?(s.ishrn(1),l.ishrn(1)):(s.iadd(c).ishrn(1),l.isub(f).ishrn(1));e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.ishln(u)}},i.prototype._invmp=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(;e.isEven();)e.ishrn(1),a.isEven()?a.ishrn(1):a.iadd(s).ishrn(1);for(;n.isEven();)n.ishrn(1),o.isEven()?o.ishrn(1):o.iadd(s).ishrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(o)):(n.isub(e),o.isub(a))}return 0===e.cmpn(1)?a:o},i.prototype.gcd=function(t){if(0===this.cmpn(0))return t.clone();if(0===t.cmpn(0))return this.clone();var e=this.clone(),r=t.clone();e.sign=!1,r.sign=!1;for(var n=0;e.isEven()&&r.isEven();n++)e.ishrn(1),r.ishrn(1);for(;;){for(;e.isEven();)e.ishrn(1);for(;r.isEven();)r.ishrn(1);var i=e.cmp(r);if(0>i){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.ishln(n)},i.prototype.invm=function(t){return this.egcd(t).a.mod(t)},i.prototype.isEven=function(){return 0===(1&this.words[0])},i.prototype.isOdd=function(){ +return 1===(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<a;a++)this.words[a]=0;return this.words[n]|=i,this.length=n+1,this}for(var o=i,a=n;0!==o&&a>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},i.prototype.cmpn=function(t){var e=0>t;if(e&&(t=-t),this.sign&&!e)return-1;if(!this.sign&&e)return 1;t&=67108863,this.strip();var r;if(this.length>1)r=1;else{var n=this.words[0];r=n===t?0:t>n?-1:1}return this.sign&&(r=-r),r},i.prototype.cmp=function(t){if(this.sign&&!t.sign)return-1;if(!this.sign&&t.sign)return 1;var e=this.ucmp(t);return this.sign?-e:e},i.prototype.ucmp=function(t){if(this.length>t.length)return 1;if(this.length=0;r--){var n=this.words[r],i=t.words[r];if(n!==i){i>n?e=-1:n>i&&(e=1);break}}return e},i.red=function(t){return new h(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(!this.sign,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};s.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},s.prototype.ireduce=function(t){var e,r=t;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength();while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},s.prototype.split=function(t,e){t.ishrn(this.n,0,e)},s.prototype.imulK=function(t){return t.imul(this.k)},n(l,s),l.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;n>i;i++)e.words[i]=t.words[i];if(e.length=n,t.length<=9)return t.words[0]=0,void(t.length=1);var a=t.words[9];e.words[e.length++]=a&r;for(var i=10;i>>22,a=o}t.words[i-10]=a>>>22,t.length-=9},l.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e,r=0,n=0;n>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function y(t){if(m[t])return m[t];var y;if("k256"===t)y=new l;else if("p224"===t)y=new u;else if("p192"===t)y=new c;else{if("p25519"!==t)throw new Error("Unknown prime "+t);y=new f}return m[t]=y,y},h.prototype._verify1=function(t){r(!t.sign,"red works only with positives"),r(t.red,"red works only with red numbers")},h.prototype._verify2=function(t,e){r(!t.sign&&!e.sign,"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},h.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.mod(this.m)._forceRed(this)},h.prototype.neg=function(t){var e=t.clone();return e.sign=!e.sign,e.iadd(this.m)._forceRed(this)},h.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},h.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},h.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},h.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},h.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.shln(e))},h.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},h.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},h.prototype.isqr=function(t){return this.imul(t,t)},h.prototype.sqr=function(t){return this.mul(t,t)},h.prototype.sqrt=function(t){if(0===t.cmpn(0))return t.clone();var e=this.m.andln(3);if(r(e%2===1),3===e){var n=this.m.add(new i(1)).ishrn(2),a=this.pow(t,n);return a}for(var o=this.m.subn(1),s=0;0!==o.cmpn(0)&&0===o.andln(1);)s++,o.ishrn(1);r(0!==o.cmpn(0));var l=new i(1).toRed(this),u=l.redNeg(),c=this.m.subn(1).ishrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,o),a=this.pow(t,o.addn(1).ishrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(l);){for(var g=p,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(d>v);var m=this.pow(h,new i(1).ishln(d-v-1));a=a.redMul(m),h=m.redSqr(),p=p.redMul(h),d=v}return a},h.prototype.invm=function(t){var e=t._invmp(this.m);return e.sign?(e.sign=!1,this.imod(e).redNeg()):this.imod(e)},h.prototype.pow=function(t,e){var r=[];if(0===e.cmpn(0))return new i(1);for(var n=e.clone();0!==n.cmpn(0);)r.push(n.andln(1)),n.ishrn(1);for(var a=t,o=0;o=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},p.prototype.mul=function(t,e){if(0===t.cmpn(0)||0===e.cmpn(0))return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).ishrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},p.prototype.invm=function(t){var e=this.imod(t._invmp(this.m).mul(this.r2));return e._forceRed(this)}}("undefined"==typeof e||e,this)},{}],384:[function(t,e,r){(function(t){function r(t,e){return p[0]=t,p[1]=e,h[0]}function n(t){return h[0]=t,p[0]}function i(t){return h[0]=t,p[1]}function a(t,e){return p[1]=t,p[0]=e,h[0]}function o(t){return h[0]=t,p[1]}function s(t){return h[0]=t,p[0]}function l(t,e){return d.writeUInt32LE(t,0,!0),d.writeUInt32LE(e,4,!0),d.readDoubleLE(0,!0)}function u(t){return d.writeDoubleLE(t,0,!0),d.readUInt32LE(0,!0)}function c(t){return d.writeDoubleLE(t,0,!0),d.readUInt32LE(4,!0)}var f=!1;if("undefined"!=typeof Float64Array){var h=new Float64Array(1),p=new Uint32Array(h.buffer);h[0]=1,f=!0,1072693248===p[1]?(e.exports=function(t){return h[0]=t,[p[0],p[1]]},e.exports.pack=r,e.exports.lo=n,e.exports.hi=i):1072693248===p[0]?(e.exports=function(t){return h[0]=t,[p[1],p[0]]},e.exports.pack=a,e.exports.lo=o,e.exports.hi=s):f=!1}if(!f){var d=new t(8);e.exports=function(t){return d.writeDoubleLE(t,0,!0),[d.readUInt32LE(0,!0),d.readUInt32LE(4,!0)]},e.exports.pack=l,e.exports.lo=u,e.exports.hi=c}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){var r=e.exports.hi(t);return(r<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){var r=e.exports.hi(t);return!(2146435072&r)}}).call(this,t("buffer").Buffer)},{buffer:65}],385:[function(t,e,r){"use strict";function n(t){return i(t[0])*i(t[1])}var i=t("./lib/bn-sign");e.exports=n},{"./lib/bn-sign":374}],386:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":379}],387:[function(t,e,r){"use strict";function n(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.divmod(r),o=n.div,s=i(o),l=n.mod;if(0===l.cmpn(0))return s;if(s){var u=a(s)+4,c=i(l.shln(u).divRound(r));return 0>s&&(c=-c),s+c*Math.pow(2,-u)}var f=r.bitLength()-l.bitLength()+53,c=i(l.shln(f).divRound(r));return 1023>f?c*Math.pow(2,-f):(c*=Math.pow(2,-1023),c*Math.pow(2,1023-f))}var i=t("./lib/bn-to-num"),a=t("./lib/ctz");e.exports=n},{"./lib/bn-to-num":375,"./lib/ctz":376}],388:[function(t,e,r){"use strict";function n(t,e){for(var r=0;t>r;++r)if(!(e[r]<=e[r+t]))return!0;return!1}function i(t,e,r,i){for(var a=0,o=0,s=0,l=t.length;l>s;++s){var u=t[s];if(!n(e,u)){for(var c=0;2*e>c;++c)r[a++]=u[c];i[o++]=s}}return o}function a(t,e,r,n){var a=t.length,o=e.length;if(!(0>=a||0>=o)){var s=t[0].length>>>1;if(!(0>=s)){var l,u=f.mallocDouble(2*s*a),c=f.mallocInt32(a);if(a=i(t,s,u,c),a>0){if(1===s&&n)h.init(a),l=h.sweepComplete(s,r,0,a,u,c,0,a,u,c);else{var d=f.mallocDouble(2*s*o),g=f.mallocInt32(o);o=i(e,s,d,g),o>0&&(h.init(a+o),l=1===s?h.sweepBipartite(s,r,0,a,u,c,0,o,d,g):p(s,r,n,a,u,c,o,d,g),f.free(d),f.free(g))}f.free(u),f.free(c)}return l}}}function o(t,e){c.push([t,e])}function s(t){return c=[],a(t,t,o,!0),c}function l(t,e){return c=[],a(t,e,o,!1),c}function u(t,e,r){switch(arguments.length){case 1:return s(t);case 2:return"function"==typeof e?a(t,t,e,!0):l(t,e);case 3:return a(t,e,r,!1);default:throw new Error("box-intersect: Invalid arguments")}}e.exports=u;var c,f=t("typedarray-pool"),h=t("./lib/sweep"),p=t("./lib/intersect")},{"./lib/intersect":390,"./lib/sweep":394,"typedarray-pool":397}],389:[function(t,e,r){"use strict";function n(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",w.join(),"){","var ",u,"=2*",a,";"],l="for(var i="+c+","+d+"="+u+"*"+c+";i<"+f+";++i,"+d+"+="+u+"){var x0="+h+"["+o+"+"+d+"],x1="+h+"["+o+"+"+d+"+"+a+"],xi="+p+"[i];",k="for(var j="+g+","+b+"="+u+"*"+g+";j<"+v+";++j,"+b+"+="+u+"){var y0="+m+"["+o+"+"+b+"],"+(r?"y1="+m+"["+o+"+"+b+"+"+a+"],":"")+"yi="+y+"[j];";return t?i.push(l,_,":",k):i.push(k,_,":",l),r?i.push("if(y1"+v+"-"+g+"){"),t?(e(!0,!1),o.push("}else{"),e(!1,!1)):(o.push("if("+l+"){"),e(!0,!0),o.push("}else{"),e(!0,!1),o.push("}}else{if("+l+"){"),e(!1,!0),o.push("}else{"),e(!1,!1),o.push("}")),o.push("}}return "+r);var s=i.join("")+o.join(""),u=new Function(s);return u()}var a="d",o="ax",s="vv",l="fp",u="es",c="rs",f="re",h="rb",p="ri",d="rp",g="bs",v="be",m="bb",y="bi",b="bp",x="rv",_="Q",w=[a,o,s,c,f,h,p,g,v,m,y];r.partial=i(!1),r.full=i(!0)},{}],390:[function(t,e,r){"use strict";function n(t,e){var r=8*u.log2(e+1)*(t+1)|0,n=u.nextPow2(M*r);L.lengthS&&(l.free(S),S=l.mallocDouble(i))}function i(t,e,r,n,i,a,o,s,l){var u=M*t;L[u]=e,L[u+1]=r,L[u+2]=n,L[u+3]=i,L[u+4]=a,L[u+5]=o;var c=T*t;S[c]=s,S[c+1]=l}function a(t,e,r,n,i,a,o,s,l,u,c){var f=2*t,h=l*f,p=u[h+e];t:for(var d=i,g=i*f;a>d;++d,g+=f){var v=o[g+e],m=o[g+e+t];if(!(v>p||p>m||n&&p===v)){for(var y=s[d],b=e+1;t>b;++b){var v=o[g+b],m=o[g+b+t],x=u[h+b],_=u[h+b+t];if(x>m||v>_)continue t}var w;if(w=n?r(c,y):r(y,c),void 0!==w)return w}}}function o(t,e,r,n,i,a,o,s,l,u){var c=2*t,f=s*c,h=l[f+e];t:for(var p=n,d=n*c;i>p;++p,d+=c){var g=o[p];if(g!==u){var v=a[d+e],m=a[d+e+t];if(!(v>h||h>m)){for(var y=e+1;t>y;++y){var v=a[d+y],m=a[d+y+t],b=l[f+y],x=l[f+y+t];if(b>m||v>x)continue t}var _=r(g,u);if(void 0!==_)return _}}}}function s(t,e,r,s,l,u,c,g,E){n(t,s+c);var C,z=0,P=2*t;for(i(z++,0,0,s,0,c,r?16:0,-(1/0),1/0),r||i(z++,0,0,c,0,s,1,-(1/0),1/0);z>0;){z-=1;var R=z*M,j=L[R],O=L[R+1],I=L[R+2],N=L[R+3],F=L[R+4],D=L[R+5],B=z*T,U=S[B],V=S[B+1],q=1&D,G=!!(16&D),H=l,Y=u,X=g,W=E;if(q&&(H=g,Y=E,X=l,W=u),!(2&D&&(I=_(t,j,O,I,H,Y,V),O>=I)||4&D&&(O=w(t,j,O,I,H,Y,U),O>=I))){var Z=I-O,K=F-N;if(G){if(y>t*Z*(Z+K)){if(C=p.scanComplete(t,j,e,O,I,H,Y,N,F,X,W),void 0!==C)return C;continue}}else{if(t*Math.min(Z,K)t*Z*K){if(C=p.scanBipartite(t,j,e,q,O,I,H,Y,N,F,X,W),void 0!==C)return C;continue}}var $=b(t,j,O,I,H,Y,U,V);if($>O)if(v>t*($-O)){if(C=h(t,j+1,e,O,$,H,Y,N,F,X,W),void 0!==C)return C}else if(j===t-2){if(C=q?p.sweepBipartite(t,e,N,F,X,W,O,$,H,Y):p.sweepBipartite(t,e,O,$,H,Y,N,F,X,W),void 0!==C)return C}else i(z++,j+1,O,$,N,F,q,-(1/0),1/0),i(z++,j+1,N,F,O,$,1^q,-(1/0),1/0);if(I>$){var Q=d(t,j,N,F,X,W),J=X[P*Q+j],tt=x(t,j,Q,F,X,W,J);if(F>tt&&i(z++,j,$,I,tt,F,(4|q)+(G?16:0),J,V),Q>N&&i(z++,j,$,I,N,Q,(2|q)+(G?16:0),U,J),Q+1===tt){if(C=G?o(t,j,e,$,I,H,Y,Q,X,W[Q]):a(t,j,e,q,$,I,H,Y,Q,X,W[Q]),void 0!==C)return C}else if(tt>Q){var et;if(G){if(et=k(t,j,$,I,H,Y,J),et>$){var rt=x(t,j,$,et,H,Y,J);if(j===t-2){if(rt>$&&(C=p.sweepComplete(t,e,$,rt,H,Y,Q,tt,X,W),void 0!==C))return C;if(et>rt&&(C=p.sweepBipartite(t,e,rt,et,H,Y,Q,tt,X,W),void 0!==C))return C}else rt>$&&i(z++,j+1,$,rt,Q,tt,16,-(1/0),1/0),et>rt&&(i(z++,j+1,rt,et,Q,tt,0,-(1/0),1/0),i(z++,j+1,Q,tt,rt,et,1,-(1/0),1/0))}}else et=q?A(t,j,$,I,H,Y,J):k(t,j,$,I,H,Y,J),et>$&&(j===t-2?C=q?p.sweepBipartite(t,e,Q,tt,X,W,$,et,H,Y):p.sweepBipartite(t,e,$,et,H,Y,Q,tt,X,W):(i(z++,j+1,$,et,Q,tt,q,-(1/0),1/0),i(z++,j+1,Q,tt,$,et,1^q,-(1/0),1/0)))}}}}}e.exports=s;var l=t("typedarray-pool"),u=t("bit-twiddle"),c=t("./brute"),f=c.partial,h=c.full,p=t("./sweep"),d=t("./median"),g=t("./partition"),v=128,m=1<<22,y=1<<22,b=g("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]),x=g("lo===p0",["p0"]),_=g("lol;++l,s+=o)for(var u=i[s],c=l,f=o*(l-1);c>r&&i[f+e]>u;--c,f-=o){for(var h=f,p=f+o,d=0;o>d;++d,++h,++p){var g=i[h];i[h]=i[p],i[p]=g}var v=a[c];a[c]=a[c-1],a[c-1]=v}}function i(t,e,r,i,a,l){if(r+1>=i)return r;for(var u=r,c=i,f=i+r>>>1,h=2*t,p=f,d=a[h*f+e];c>u;){if(s>c-u){n(t,e,u,c,a,l),d=a[h*f+e];break}var g=c-u,v=Math.random()*g+u|0,m=a[h*v+e],y=Math.random()*g+u|0,b=a[h*y+e],x=Math.random()*g+u|0,_=a[h*x+e];b>=m?_>=b?(p=y,d=b):m>=_?(p=v,d=m):(p=x,d=_):b>=_?(p=y,d=b):_>=m?(p=v,d=m):(p=x,d=_);for(var w=h*(c-1),k=h*p,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[c-1];l[c-1]=l[p],l[p]=T,p=o(t,e,u,c-1,a,l,d);for(var w=h*(c-1),k=h*p,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[c-1];if(l[c-1]=l[p],l[p]=T,p>f){for(c=p-1;c>u&&a[h*(c-1)+e]===d;)c-=1;c+=1}else{if(!(f>p))break;for(u=p+1;c>u&&a[h*u+e]===d;)u+=1}}return o(t,e,r,f,a,l,a[h*f+e])}e.exports=i;var a=t("./partition"),o=a("lo=0&&n.push("lo=e[k+n]"),t.indexOf("hi")>=0&&n.push("hi=e[k+o]"),r.push(i.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)}e.exports=n;var i="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],393:[function(t,e,r){"use strict";function n(t,e){4*h>=e?i(0,e-1,t):f(0,e-1,t)}function i(t,e,r){for(var n=2*(t+1),i=t+1;e>=i;++i){for(var a=r[n++],o=r[n++],s=i,l=n-2;s-- >t;){var u=r[l-2],c=r[l-1];if(a>u)break;if(u===a&&o>c)break;r[l]=u,r[l+1]=c,l-=2}r[l]=a,r[l+1]=o}}function a(t,e,r){t*=2,e*=2;var n=r[t],i=r[t+1];r[t]=r[e],r[t+1]=r[e+1],r[e]=n,r[e+1]=i}function o(t,e,r){t*=2,e*=2,r[t]=r[e],r[t+1]=r[e+1]}function s(t,e,r,n){t*=2,e*=2,r*=2;var i=n[t],a=n[t+1];n[t]=n[e],n[t+1]=n[e+1],n[e]=n[r],n[e+1]=n[r+1],n[r]=i,n[r+1]=a}function l(t,e,r,n,i){t*=2,e*=2,i[t]=i[e],i[e]=r,i[t+1]=i[e+1],i[e+1]=n}function u(t,e,r){t*=2,e*=2;var n=r[t],i=r[e];return i>n?!1:n===i?r[t+1]>r[e+1]:!0}function c(t,e,r,n){t*=2;var i=n[t];return e>i?!0:i===e?n[t+1]>1,v=g-n,m=g+n,y=p,b=v,x=g,_=m,w=d,k=t+1,A=e-1,M=0;u(y,b,r)&&(M=y,y=b,b=M),u(_,w,r)&&(M=_,_=w,w=M),u(y,x,r)&&(M=y,y=x,x=M),u(b,x,r)&&(M=b,b=x,x=M),u(y,_,r)&&(M=y,y=_,_=M),u(x,_,r)&&(M=x,x=_,_=M),u(b,w,r)&&(M=b,b=w,w=M),u(b,x,r)&&(M=b,b=x,x=M),u(_,w,r)&&(M=_,_=w,w=M);for(var T=r[2*b],E=r[2*b+1],L=r[2*_],S=r[2*_+1],C=2*y,z=2*x,P=2*w,R=2*p,j=2*g,O=2*d,I=0;2>I;++I){var N=r[C+I],F=r[z+I],D=r[P+I];r[R+I]=N,r[j+I]=F,r[O+I]=D}o(v,t,r),o(m,e,r);for(var B=k;A>=B;++B)if(c(B,T,E,r))B!==k&&a(B,k,r),++k;else if(!c(B,L,S,r))for(;;){if(c(A,L,S,r)){c(A,T,E,r)?(s(B,k,A,r),++k,--A):(a(B,A,r),--A);break}if(--A=k-2-t?i(t,k-2,r):f(t,k-2,r),h>=e-(A+2)?i(A+2,e,r):f(A+2,e,r),h>=A-k?i(k,A,r):f(k,A,r)}e.exports=n;var h=32},{}],394:[function(t,e,r){"use strict";function n(t){var e=f.nextPow2(t);g.lengthk;++k){var A=s[k],M=b*k;_[d++]=o[M+x],_[d++]=-(A+1),_[d++]=o[M+w],_[d++]=A}for(var k=l;u>k;++k){var A=f[k]+p,T=b*k;_[d++]=c[T+x],_[d++]=-A,_[d++]=c[T+w],_[d++]=A}var E=d>>>1;h(_,E);for(var L=0,S=0,k=0;E>k;++k){var C=0|_[2*k+1];if(C>=p)C=C-p|0,i(m,y,S--,C);else if(C>=0)i(g,v,L--,C);else if(-p>=C){C=-C-p|0;for(var z=0;L>z;++z){var P=e(g[z],C);if(void 0!==P)return P}a(m,y,S++,C)}else{C=-C-1|0;for(var z=0;S>z;++z){var P=e(C,m[z]);if(void 0!==P)return P}a(g,v,L++,C)}}}function s(t,e,r,n,o,s,l,u,c,f){for(var p=0,d=2*t,w=t-1,k=d-1,A=r;n>A;++A){var M=s[A]+1<<1,T=d*A;_[p++]=o[T+w],_[p++]=-M,_[p++]=o[T+k],_[p++]=M}for(var A=l;u>A;++A){var M=f[A]+1<<1,E=d*A;_[p++]=c[E+w],_[p++]=1|-M,_[p++]=c[E+k],_[p++]=1|M}var L=p>>>1;h(_,L);for(var S=0,C=0,z=0,A=0;L>A;++A){var P=0|_[2*A+1],R=1&P;if(L-1>A&&P>>1===_[2*A+3]>>1&&(R=2,A+=1),0>P){for(var j=-(P>>1)-1,O=0;z>O;++O){var I=e(b[O],j);if(void 0!==I)return I}if(0!==R)for(var O=0;S>O;++O){var I=e(g[O],j);if(void 0!==I)return I}if(1!==R)for(var O=0;C>O;++O){var I=e(m[O],j);if(void 0!==I)return I}0===R?a(g,v,S++,j):1===R?a(m,y,C++,j):2===R&&a(b,x,z++,j)}else{var j=(P>>1)-1;0===R?i(g,v,S--,j):1===R?i(m,y,C--,j):2===R&&i(b,x,z--,j)}}}function l(t,e,r,n,o,s,l,u,c,f,d,m){var y=0,b=2*t,x=e,w=e+t,k=1,A=1;n?A=p:k=p;for(var M=o;s>M;++M){var T=M+k,E=b*M;_[y++]=l[E+x],_[y++]=-T,_[y++]=l[E+w],_[y++]=T}for(var M=c;f>M;++M){var T=M+A,L=b*M;_[y++]=d[L+x],_[y++]=-T}var S=y>>>1;h(_,S);for(var C=0,M=0;S>M;++M){var z=0|_[2*M+1];if(0>z){var T=-z,P=!1;if(T>=p?(P=!n,T-=p):(P=!!n,T-=1),P)a(g,v,C++,T);else{var R=m[T],j=b*T,O=d[j+e+1],I=d[j+e+1+t];t:for(var N=0;C>N;++N){var F=g[N],D=b*F;if(!(IB;++B)if(d[j+B+t]y;++y){var b=y+p,x=d*y;_[f++]=a[x+v],_[f++]=-b,_[f++]=a[x+m],_[f++]=b}for(var y=s;l>y;++y){var b=y+1,w=d*y;_[f++]=u[w+v],_[f++]=-b}var k=f>>>1;h(_,k);for(var A=0,y=0;k>y;++y){var M=0|_[2*y+1];if(0>M){var b=-M;if(b>=p)g[A++]=b-p;else{b-=1;var T=c[b],E=d*b,L=u[E+e+1],S=u[E+e+1+t];t:for(var C=0;A>C;++C){var z=g[C],P=o[z];if(P===T)break;var R=d*z;if(!(Sj;++j)if(u[E+j+t]=0;--C)if(g[C]===b){for(var j=C+1;A>j;++j)g[j-1]=g[j];break}--A}}}e.exports={init:n,sweepBipartite:o,sweepComplete:s,scanBipartite:l,scanComplete:u};var c=t("typedarray-pool"),f=t("bit-twiddle"),h=t("./sort"),p=1<<28,d=1024,g=c.mallocInt32(d),v=c.mallocInt32(d),m=c.mallocInt32(d),y=c.mallocInt32(d),b=c.mallocInt32(d),x=c.mallocInt32(d),_=c.mallocDouble(8*d)},{"./sort":393,"bit-twiddle":395,"typedarray-pool":397}],395:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],396:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],397:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":395,buffer:65,dup:122}],398:[function(t,e,r){arguments[4][61][0].apply(r,arguments)},{dup:61}],399:[function(t,e,r){"use strict";function n(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return 0>e?-a:a;var r=i.hi(t),n=i.lo(t);return e>t==t>0?n===o?(r+=1,n=0):n+=1:0===n?(n=o,r-=1):n-=1,i.pack(n,r)}var i=t("double-bits"),a=Math.pow(2,-1074),o=-1>>>0;e.exports=n},{"double-bits":400}],400:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],401:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/add");e.exports=n},{"big-rat/add":369}],402:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t.length),r=0;rs;++s)o[s]=a(t[s],r);return o}var i=t("big-rat"),a=t("big-rat/mul");e.exports=n},{"big-rat":372,"big-rat/mul":381}],404:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/sub");e.exports=n},{"big-rat/sub":386}],405:[function(t,e,r){"use strict";function n(t,e,r,n){for(var i=0;2>i;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],f=Math.min(u,c),h=Math.max(u,c);if(s>h||f>l)return!1}return!0}function i(t,e,r,i){var o=a(t,r,i),s=a(e,r,i);if(o>0&&s>0||0>o&&0>s)return!1;var l=a(r,t,e),u=a(i,t,e);return l>0&&u>0||0>l&&0>u?!1:0===o&&0===s&&0===l&&0===u?n(t,e,r,i):!0}e.exports=i;var a=t("robust-orientation")[3]},{"robust-orientation":1040}],406:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],407:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t,e.length),n=new Array(e.length),a=new Array(e.length),o=[],s=0;s=l&&o.push(s)}for(;o.length>0;){var u=o.pop();n[u]=!1;for(var c=r[u],s=0;sn;++n){var a=t[n];e=Math.max(e,a[0],a[1])}e=(0|e)+1}e=0|e;for(var o=new Array(e),n=0;e>n;++n)o[n]=[];for(var n=0;r>n;++n){var a=t[n];o[a[0]].push(a[1]),o[a[1]].push(a[0])}for(var s=0;e>s;++s)i(o[s],function(t,e){return t-e});return o}e.exports=n;var i=t("uniq")},{uniq:423}],409:[function(t,e,r){"use strict";function n(t,e){function r(t,e){var r=u[e][t[e]];r.splice(r.indexOf(t),1)}function n(t,n,a){for(var o,s,l,c=0;2>c;++c)if(u[c][n].length>0){o=u[c][n][0],l=c;break}s=o[1^l];for(var f=0;2>f;++f)for(var h=u[f][n],p=0;p0&&(o=d,s=g,l=f)}return a?s:(o&&r(o,l),s)}function a(t,a){var o=u[a][t][0],s=[t];r(o,a);for(var l=o[1^a];;){for(;l!==t;)s.push(l),l=n(s[s.length-2],l,!1);if(u[0][t].length+u[1][t].length===0)break;var c=s[s.length-1],f=t,h=s[1],p=n(c,f,!0);if(i(e[c],e[f],e[h],e[p])<0)break;s.push(t),l=n(c,f)}return s}function o(t,e){return e[1]===e[e.length-1]}for(var s=0|e.length,l=t.length,u=[new Array(s),new Array(s)],c=0;s>c;++c)u[0][c]=[],u[1][c]=[];for(var c=0;l>c;++c){var f=t[c];u[0][f[0]].push(f),u[1][f[1]].push(f)}for(var h=[],c=0;s>c;++c)u[0][c].length+u[1][c].length===0&&h.push([c]);for(var c=0;s>c;++c)for(var p=0;2>p;++p){for(var d=[];u[p][c].length>0;){var g=(u[0][c].length,a(c,p));o(d,g)?d.push.apply(d,g):(d.length>0&&h.push(d),d=g)}d.length>0&&h.push(d)}return h}e.exports=n;var i=t("compare-angle")},{"compare-angle":410}],410:[function(t,e,r){"use strict";function n(t,e,r){var n=s(t[0],-e[0]),i=s(t[1],-e[1]),a=s(r[0],-e[0]),o=s(r[1],-e[1]),c=u(l(n,a),l(i,o));return c[c.length-1]>=0}function i(t,e,r,i){var s=a(e,r,i);if(0===s){var l=o(a(t,e,r)),u=o(a(t,e,i));if(l===u){if(0===l){var c=n(t,e,r),f=n(t,e,i);return c===f?0:c?1:-1}return 0}return 0===u?l>0?-1:n(t,e,i)?-1:1:0===l?u>0?1:n(t,e,r)?1:-1:o(u-l)}var h=a(t,e,r);if(h>0)return s>0&&a(t,e,i)>0?1:-1;if(0>h)return s>0||a(t,e,i)>0?1:-1;var p=a(t,e,i);return p>0?1:n(t,e,r)?1:-1}e.exports=i;var a=t("robust-orientation"),o=t("signum"),s=t("two-sum"),l=t("robust-product"),u=t("robust-sum")},{"robust-orientation":1040,"robust-product":412,"robust-sum":421,signum:413,"two-sum":414}],411:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":422,"two-sum":414}],412:[function(t,e,r){"use strict";function n(t,e){if(1===t.length)return a(e,t[0]);if(1===e.length)return a(t,e[0]);if(0===t.length||0===e.length)return[0];var r=[0];if(t.lengtht?-1:t>0?1:0}},{}],414:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],415:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],416:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}function i(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function a(t,e){var r=d(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function o(t,e){var r=t.intervals([]);r.push(e),a(t,r)}function s(t,e){var r=t.intervals([]),n=r.indexOf(e);return 0>n?y:(r.splice(n,1),a(t,r),b)}function l(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function c(t,e){for(var r=0;r>1],a=[],o=[],s=[],r=0;r3*(e+1)?o(this,t):this.left.insert(t):this.left=d([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?o(this,t):this.right.insert(t):this.right=d([t]);else{var r=m.ge(this.leftPoints,t,h),n=m.ge(this.rightPoints,t,p);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1))return s(this,t);var n=this.left.remove(t);return n===x?(this.left=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(t[0]>this.mid){if(!this.right)return y;var a=this.left?this.left.count:0;if(4*a>3*(e-1))return s(this,t);var n=this.right.remove(t);return n===x?(this.right=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(1===this.count)return this.leftPoints[0]===t?x:y;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var o=this,l=this.left;l.right;)o=l,l=l.right;if(o===this)l.right=this.right;else{var u=this.left,n=this.right;o.count-=l.count,o.right=l.left,l.left=u,l.right=n}i(this,l),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?i(this,this.left):i(this,this.right);return b}for(var u=m.ge(this.leftPoints,t,h);uthis.mid){if(this.right){var r=this.right.queryPoint(t,e);if(r)return r}return u(this.rightPoints,t,e)}return c(this.leftPoints,e)},_.queryInterval=function(t,e,r){if(tthis.mid&&this.right){var n=this.right.queryInterval(t,e,r);if(n)return n}return ethis.mid?u(this.rightPoints,t,r):c(this.leftPoints,r)};var w=g.prototype;w.insert=function(t){this.root?this.root.insert(t):this.root=new n(t[0],null,null,[t],[t])},w.remove=function(t){if(this.root){var e=this.root.remove(t);return e===x&&(this.root=null),e!==y}return!1},w.queryPoint=function(t,e){return this.root?this.root.queryPoint(t,e):void 0; +},w.queryInterval=function(t,e,r){return e>=t&&this.root?this.root.queryInterval(t,e,r):void 0},Object.defineProperty(w,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(w,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":415}],417:[function(t,e,r){"use strict";function n(t,e){var r,n;if(e[0][0]e[1][0])){var i=Math.min(t[0][1],t[1][1]),o=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),l=Math.max(e[0][1],e[1][1]);return s>o?o-s:i>l?i-l:o-l}r=e[1],n=e[0]}var u,c;t[0][1]e[1][0]))return n(e,t);r=e[1],i=e[0]}var o,s;if(t[0][0]t[1][0]))return-n(t,e);o=t[1],s=t[0]}var l=a(r,i,s),u=a(r,i,o);if(0>l){if(0>=u)return l}else if(l>0){if(u>=0)return l}else if(u)return u;if(l=a(s,o,i),u=a(s,o,r),0>l){if(0>=u)return l}else if(l>0){if(u>=0)return l}else if(u)return u;return i[0]-s[0]}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":1040}],418:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function i(t){return new n(t._color,t.key,t.value,t.left,t.right,t._count)}function a(t,e){return new n(t,e.key,e.value,e.left,e.right,e._count)}function o(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function s(t,e){this._compare=t,this.root=e}function l(t,e){if(e.left){var r=l(t,e.left);if(r)return r}var r=t(e.key,e.value);return r?r:e.right?l(t,e.right):void 0}function u(t,e,r,n){var i=e(t,n.key);if(0>=i){if(n.left){var a=u(t,e,r,n.left);if(a)return a}var a=r(n.key,n.value);if(a)return a}return n.right?u(t,e,r,n.right):void 0}function c(t,e,r,n,i){var a,o=r(t,i.key),s=r(e,i.key);if(0>=o){if(i.left&&(a=c(t,e,r,n,i.left)))return a;if(s>0&&(a=n(i.key,i.value)))return a}return s>0&&i.right?c(t,e,r,n,i.right):void 0}function f(t,e){this.tree=t,this._stack=e}function h(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function p(t){for(var e,r,n,s,l=t.length-1;l>=0;--l){if(e=t[l],0===l)return void(e._color=m);if(r=t[l-1],r.left===e){if(n=r.right,n.right&&n.right._color===v){if(n=r.right=i(n),s=n.right=i(n.right),r.right=n.left,n.left=r,n.right=s,n._color=r._color,e._color=m,r._color=m,s._color=m,o(r),o(n),l>1){var u=t[l-2];u.left===r?u.left=n:u.right=n}return void(t[l-1]=n)}if(n.left&&n.left._color===v){if(n=r.right=i(n),s=n.left=i(n.left),r.right=s.left,n.left=s.right,s.left=r,s.right=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var u=t[l-2];u.left===r?u.left=s:u.right=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.right=a(v,n));r.right=a(v,n);continue}if(n=i(n),r.right=n.left,n.left=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var u=t[l-2];u.left===r?u.left=n:u.right=n}t[l-1]=n,t[l]=r,l+11){var u=t[l-2];u.right===r?u.right=n:u.left=n}return void(t[l-1]=n)}if(n.right&&n.right._color===v){if(n=r.left=i(n),s=n.right=i(n.right),r.left=s.right,n.right=s.left,s.right=r,s.left=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var u=t[l-2];u.right===r?u.right=s:u.left=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.left=a(v,n));r.left=a(v,n);continue}if(n=i(n),r.left=n.right,n.right=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var u=t[l-2];u.right===r?u.right=n:u.left=n}t[l-1]=n,t[l]=r,l+1t?-1:t>e?1:0}function g(t){return new s(t||d,null)}e.exports=g;var v=0,m=1,y=s.prototype;Object.defineProperty(y,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(y,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(y,"length",{get:function(){return this.root?this.root._count:0}}),y.insert=function(t,e){for(var r=this._compare,i=this.root,l=[],u=[];i;){var c=r(t,i.key);l.push(i),u.push(c),i=0>=c?i.left:i.right}l.push(new n(v,t,e,null,null,1));for(var f=l.length-2;f>=0;--f){var i=l[f];u[f]<=0?l[f]=new n(i._color,i.key,i.value,l[f+1],i.right,i._count+1):l[f]=new n(i._color,i.key,i.value,i.left,l[f+1],i._count+1)}for(var f=l.length-1;f>1;--f){var h=l[f-1],i=l[f];if(h._color===m||i._color===m)break;var p=l[f-2];if(p.left===h)if(h.left===i){var d=p.right;if(!d||d._color!==v){if(p._color=v,p.left=h.right,h._color=m,h.right=p,l[f-2]=h,l[f-1]=i,o(p),o(h),f>=3){var g=l[f-3];g.left===p?g.left=h:g.right=h}break}h._color=m,p.right=a(m,d),p._color=v,f-=1}else{var d=p.right;if(!d||d._color!==v){if(h.right=i.left,p._color=v,p.left=i.right,i._color=m,i.left=h,i.right=p,l[f-2]=i,l[f-1]=h,o(p),o(h),o(i),f>=3){var g=l[f-3];g.left===p?g.left=i:g.right=i}break}h._color=m,p.right=a(m,d),p._color=v,f-=1}else if(h.right===i){var d=p.left;if(!d||d._color!==v){if(p._color=v,p.right=h.left,h._color=m,h.left=p,l[f-2]=h,l[f-1]=i,o(p),o(h),f>=3){var g=l[f-3];g.right===p?g.right=h:g.left=h}break}h._color=m,p.left=a(m,d),p._color=v,f-=1}else{var d=p.left;if(!d||d._color!==v){if(h.left=i.right,p._color=v,p.right=i.left,i._color=m,i.right=h,i.left=p,l[f-2]=i,l[f-1]=h,o(p),o(h),o(i),f>=3){var g=l[f-3];g.right===p?g.right=i:g.left=i}break}h._color=m,p.left=a(m,d),p._color=v,f-=1}}return l[0]._color=m,new s(r,l[0])},y.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return l(t,this.root);case 2:return u(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return c(e,r,this._compare,t,this.root)}},Object.defineProperty(y,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new f(this,t)}}),Object.defineProperty(y,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new f(this,t)}}),y.at=function(t){if(0>t)return new f(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new f(this,[])},y.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>=a&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>a&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new f(this,n);r=0>=i?r.left:r.right}return new f(this,[])},y.remove=function(t){var e=this.find(t);return e?e.remove():this},y.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=0>=n?r.left:r.right}};var b=f.prototype;Object.defineProperty(b,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(b,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),b.clone=function(){return new f(this.tree,this._stack.slice())},b.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new n(r._color,r.key,r.value,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i){var r=t[i];r.left===t[i+1]?e[i]=new n(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count)}if(r=e[e.length-1],r.left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var o=e[a-1];e.push(new n(r._color,o.key,o.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(var i=e.length-2;i>=a;--i)r=e[i],e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count);e[a-1].left=e[a]}if(r=e[e.length-1],r._color===v){var l=e[e.length-2];l.left===r?l.left=null:l.right===r&&(l.right=null),e.pop();for(var i=0;i0?this._stack[this._stack.length-1].key:void 0},enumerable:!0}),Object.defineProperty(b,"value",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1].value:void 0},enumerable:!0}),Object.defineProperty(b,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),b.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),b.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),i=e[e.length-1];r[r.length-1]=new n(i._color,i.key,t,i.left,i.right,i._count);for(var a=e.length-2;a>=0;--a)i=e[a],i.left===e[a+1]?r[a]=new n(i._color,i.key,i.value,r[a+1],i.right,i._count):r[a]=new n(i._color,i.key,i.value,i.left,r[a+1],i._count);return new s(this.tree._compare,r[0])},b.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],419:[function(t,e,r){"use strict";function n(t,e,r){this.slabs=t,this.coordinates=e,this.horizontal=r}function i(t,e){return t.y-e}function a(t,e){for(var r=null;t;){var n,i,o=t.key;o[0][0]s)t=t.left;else if(s>0)if(e[0]!==o[1][0])r=t,t=t.right;else{var l=a(t.right,e);if(l)return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l=a(t.right,e);if(l)return l;t=t.left}}return r}function o(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function s(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}function l(t){for(var e=t.length,r=2*e,i=new Array(r),a=0;e>a;++a){var l=t[a],u=l[0][0]a;){for(var v=i[a].x,m=[];r>a;){var y=i[a];if(y.x!==v)break;a+=1,y.segment[0][0]===y.x&&y.segment[1][0]===y.x?y.create&&(y.segment[0][1]e)return-1;var r=(this.slabs[e],a(this.slabs[e],t)),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var o=null;if(r&&(o=r.key),e>0){var s=a(this.slabs[e-1],t);s&&(o?h(s.key,o)>0&&(o=s.key,n=s.value):(n=s.value,o=s.key))}var l=this.horizontal[e];if(l.length>0){var c=u.ge(l,t[1],i);if(c=l.length)return n;p=l[c]}}if(p.start)if(o){var d=f(o[0],o[1],[t[0],p.y]);o[0][0]>o[1][0]&&(d=-d),d>0&&(n=p.index)}else n=p.index;else p.y!==t[1]&&(n=p.index)}}}return n}},{"./lib/order-segments":417,"binary-search-bounds":415,"functional-red-black-tree":418,"robust-orientation":1040}],420:[function(t,e,r){function n(){return!0}function i(t){return function(e,r){var i=t[e];return i?!!i.queryPoint(r,n):!1}}function a(t){for(var e={},r=0;rn)return 1;var i=t[n];if(!i){if(!(n>0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=f(r,o[0],o[1]);if(o[0][0]s)i=i.left;else{if(!(s>0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(0>s))return 0;a=1,i=i.right}}return a}}function s(t){return 1}function l(t){return function(e){return t(e[0],e[1])?0:1}}function u(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}function c(t){for(var e=t.length,r=[],n=[],i=0;e>i;++i)for(var c=t[i],f=c.length,p=f-1,d=0;f>d;p=d++){var g=c[p],v=c[d];g[0]===v[0]?n.push([g,v]):r.push([g,v])}if(0===r.length)return 0===n.length?s:l(a(n));var m=h(r),y=o(m.slabs,m.coordinates);return 0===n.length?y:u(a(n),y)}e.exports=c;var f=t("robust-orientation")[3],h=t("slab-decomposition"),p=t("interval-tree-1d"),d=t("binary-search-bounds")},{"binary-search-bounds":415,"interval-tree-1d":416,"robust-orientation":1040,"slab-decomposition":419}],421:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],422:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],423:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],424:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function i(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=[];return e}function a(t,e){function r(t){for(var r=t.length,n=[0],i=0;r>i;++i){var a=e[t[i]],o=e[t[(i+1)%r]],s=u(-a[0],a[1]),l=u(-a[0],o[1]),f=u(o[0],a[1]),h=u(o[0],o[1]);n=c(n,c(c(s,l),c(f,h)))}return n[n.length-1]>0}function a(t){for(var e=t.length,r=0;e>r;++r)if(!j[t[r]])return!1;return!0}var p=h(t,e);t=p[0],e=p[1];for(var d=e.length,g=(t.length,o(t,e.length)),v=0;d>v;++v)if(g[v].length%2===1)throw new Error("planar-graph-to-polyline: graph must be manifold");var m=s(t,e);m=m.filter(r);for(var y=m.length,b=new Array(y),x=new Array(y),v=0;y>v;++v){b[v]=v;var _=new Array(y),w=m[v].map(function(t){return e[t]}),k=l([w]),A=0;t:for(var M=0;y>M;++M)if(_[M]=0,v!==M){for(var T=m[M],E=T.length,L=0;E>L;++L){var S=k(e[T[L]]);if(0!==S){0>S&&(_[M]=1,A+=1);continue t}}_[M]=1,A+=1}x[v]=[A,v,_]}x.sort(function(t,e){return e[0]-t[0]});for(var v=0;y>v;++v)for(var _=x[v],C=_[1],z=_[2],M=0;y>M;++M)z[M]&&(b[M]=C);for(var P=i(y),v=0;y>v;++v)P[v].push(b[v]),P[b[v]].push(v);for(var R={},j=n(d,!1),v=0;y>v;++v)for(var T=m[v],E=T.length,M=0;E>M;++M){var O=T[M],I=T[(M+1)%E],N=Math.min(O,I)+":"+Math.max(O,I);if(N in R){var F=R[N];P[F].push(v),P[v].push(F),j[O]=j[I]=!0}else R[N]=v}for(var D=[],B=n(y,-1),v=0;y>v;++v)b[v]!==v||a(m[v])?B[v]=-1:(D.push(v),B[v]=0);for(var p=[];D.length>0;){var U=D.pop(),V=P[U];f(V,function(t,e){return t-e});var q,G=V.length,H=B[U];if(0===H){var T=m[U];q=[T]}for(var v=0;G>v;++v){var Y=V[v];if(!(B[Y]>=0)&&(B[Y]=1^H,D.push(Y),0===H)){var T=m[Y];a(T)||(T.reverse(),q.push(T))}}0===H&&p.push(q)}return p}e.exports=a;var o=t("edges-to-adjacency-list"),s=t("planar-dual"),l=t("point-in-big-polygon"),u=t("two-product"),c=t("robust-sum"),f=t("uniq"),h=t("./lib/trim-leaves")},{"./lib/trim-leaves":407,"edges-to-adjacency-list":408,"planar-dual":409,"point-in-big-polygon":420,"robust-sum":421,"two-product":422,uniq:423}],425:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],426:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n,n.prototype.length=function(){return this.roots.length},n.prototype.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},n.prototype.find=function(t){for(var e=this.roots;e[t]!==t;){var r=e[t];e[t]=e[r],t=r}return t},n.prototype.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],427:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":425,dup:79,"union-find":426}],428:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.abs(a(t,e,r)),i=Math.sqrt(Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2));return n/i}function i(t,e,r){function i(t){if(x[t])return 1/0;var r=m[t],i=y[t];return 0>r||0>i?1/0:n(e[t],e[r],e[i])}function a(t,e){var r=M[t],n=M[e];M[t]=n,M[e]=r,T[r]=e,T[n]=t}function s(t){return b[M[t]]}function l(t){return 1&t?t-1>>1:(t>>1)-1}function u(t){for(var e=s(t);;){var r=e,n=2*t+1,i=2*(t+1),o=t;if(L>n){var l=s(n);r>l&&(o=n,r=l)}if(L>i){var u=s(i);r>u&&(o=i)}if(o===t)return t;a(t,o),t=o}}function c(t){for(var e=s(t);t>0;){var r=l(t);if(r>=0){var n=s(r);if(n>e){a(t,r),t=r;continue}}return t}}function f(){if(L>0){var t=M[0];return a(0,L-1),L-=1,u(0),t}return-1}function h(t,e){var r=M[t];return b[r]===e?t:(b[r]=-(1/0),c(t),f(),b[r]=e,L+=1,c(L-1))}function p(t){if(!x[t]){x[t]=!0;var e=m[t],r=y[t];m[r]>=0&&(m[r]=e),y[e]>=0&&(y[e]=r),T[e]>=0&&h(T[e],i(e)),T[r]>=0&&h(T[r],i(r))}}function d(t,e){if(t[e]<0)return e;var r=e,n=e;do{var i=t[n];if(!x[n]||0>i||i===n)break;if(n=i,i=t[n],!x[n]||0>i||i===n)break;n=i,r=t[r]}while(r!==n);for(var a=e;a!==n;a=t[a])t[a]=n;return n}for(var g=e.length,v=t.length,m=new Array(g),y=new Array(g),b=new Array(g),x=new Array(g),_=0;g>_;++_)m[_]=y[_]=-1,b[_]=1/0,x[_]=!1;for(var _=0;v>_;++_){var w=t[_];if(2!==w.length)throw new Error("Input must be a graph");var k=w[1],A=w[0];-1!==y[A]?y[A]=-2:y[A]=k,-1!==m[k]?m[k]=-2:m[k]=A}for(var M=[],T=new Array(g),_=0;g>_;++_){var E=b[_]=i(_);1/0>E?(T[_]=M.length,M.push(_)):T[_]=-1}for(var L=M.length,_=L>>1;_>=0;--_)u(_);for(;;){var S=f();if(0>S||b[S]>r)break;p(S)}for(var C=[],_=0;g>_;++_)x[_]||(T[_]=C.length,C.push(e[_].slice()));var z=(C.length,[]);return t.forEach(function(t){var e=d(m,t[0]),r=d(y,t[1]);if(e>=0&&r>=0&&e!==r){var n=T[e],i=T[r];n!==i&&z.push([n,i])}}),o.unique(o.normalize(z)),{positions:C,edges:z}}e.exports=i;var a=t("robust-orientation"),o=t("simplicial-complex")},{"robust-orientation":1040,"simplicial-complex":427}],429:[function(t,e,r){"use strict";function n(t){return"a"+t}function i(t){return"d"+t}function a(t,e){return"c"+t+"_"+e}function o(t){return"s"+t}function s(t,e){return"t"+t+"_"+e}function l(t){return"o"+t}function u(t){return"x"+t}function c(t){return"p"+t}function f(t,e){return"d"+t+"_"+e}function h(t){return"i"+t}function p(t,e){return"u"+t+"_"+e}function d(t){return"b"+t}function g(t){return"y"+t}function v(t){return"e"+t}function m(t){return"v"+t}function y(t,e,r){for(var n=0,i=0;t>i;++i)e&1<e;++e)F.push(c(e),"+=",p(e,x[t]),";");F.push("}")}function z(t){for(var e=t-1;e>=0;--e)S(e,0);for(var r=[],e=0;O>e;++e)L[e]?r.push(i(e)+".get("+c(e)+")"):r.push(i(e)+"["+c(e)+"]");for(var e=0;b>e;++e)r.push(u(e));F.push(k,"[",T,"++]=phase(",r.join(),");");for(var e=0;t>e;++e)C(e);for(var n=0;O>n;++n)F.push(c(n),"+=",p(n,x[t]),";")}function P(t){for(var e=0;O>e;++e)L[e]?F.push(a(e,0),"=",i(e),".get(",c(e),");"):F.push(a(e,0),"=",i(e),"[",c(e),"];");for(var r=[],e=0;O>e;++e)r.push(a(e,0));for(var e=0;b>e;++e)r.push(u(e));F.push(d(0),"=",k,"[",T,"]=phase(",r.join(),");");for(var n=1;1<n;++n)F.push(d(n),"=",k,"[",T,"+",v(n),"];");for(var o=[],n=1;1<n;++n)o.push("("+d(0)+"!=="+d(n)+")");F.push("if(",o.join("||"),"){");for(var s=[],e=0;I>e;++e)s.push(h(e));for(var e=0;O>e;++e){s.push(a(e,0));for(var n=1;1<n;++n)L[e]?F.push(a(e,n),"=",i(e),".get(",c(e),"+",f(e,n),");"):F.push(a(e,n),"=",i(e),"[",c(e),"+",f(e,n),"];"),s.push(a(e,n))}for(var e=0;1<e;++e)s.push(d(e));for(var e=0;b>e;++e)s.push(u(e));F.push("vertex(",s.join(),");",m(0),"=",w,"[",T,"]=",A,"++;");for(var l=(1<n;++n)if(0===(t&~(1<0;_=_-1&g)x.push(w+"["+T+"+"+v(_)+"]");x.push(m(0));for(var _=0;O>_;++_)1&n?x.push(a(_,l),a(_,g)):x.push(a(_,g),a(_,l));1&n?x.push(p,y):x.push(y,p);for(var _=0;b>_;++_)x.push(u(_));F.push("if(",p,"!==",y,"){","face(",x.join(),")}")}F.push("}",T,"+=1;")}function R(){for(var t=1;1<t;++t)F.push(E,"=",v(t),";",v(t),"=",g(t),";",g(t),"=",E,";")}function j(t,e){if(0>t)return void P(e);z(t),F.push("if(",o(x[t]),">0){",h(x[t]),"=1;"),j(t-1,e|1<r;++r)F.push(c(r),"+=",p(r,x[t]),";");t===I-1&&(F.push(T,"=0;"),R()),S(t,2),j(t-1,e),t===I-1&&(F.push("if(",h(x[I-1]),"&1){",T,"=0;}"),R()),C(t),F.push("}")}var O=L.length,I=x.length;if(2>I)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var N="extractContour"+x.join("_"),F=[],D=[],B=[],U=0;O>U;++U)B.push(n(U));for(var U=0;b>U;++U)B.push(u(U));for(var U=0;I>U;++U)D.push(o(U)+"="+n(0)+".shape["+U+"]|0");for(var U=0;O>U;++U){D.push(i(U)+"="+n(U)+".data",l(U)+"="+n(U)+".offset|0");for(var V=0;I>V;++V)D.push(s(U,V)+"="+n(U)+".stride["+V+"]|0")}for(var U=0;O>U;++U){D.push(c(U)+"="+l(U)),D.push(a(U,0));for(var V=1;1<V;++V){for(var q=[],G=0;I>G;++G)V&1<U;++U)for(var V=0;I>V;++V){var H=[s(U,x[V])];V>0&&H.push(s(U,x[V-1])+"*"+o(x[V-1])),D.push(p(U,x[V])+"=("+H.join("-")+")|0")}for(var U=0;I>U;++U)D.push(h(U)+"=0");D.push(A+"=0");for(var Y=["2"],U=I-2;U>=0;--U)Y.push(o(x[U]));D.push(M+"=("+Y.join("*")+")|0",k+"=mallocUint32("+M+")",w+"=mallocUint32("+M+")",T+"=0"),D.push(d(0)+"=0");for(var V=1;1<V;++V){for(var X=[],W=[],G=0;I>G;++G)V&1<n&&e("Must have at least one array argument");var i=t.scalarArguments||0;0>i&&e("Scalar arg count must be > 0"),"function"!=typeof t.vertex&&e("Must specify vertex creation function"),"function"!=typeof t.cell&&e("Must specify cell creation function"),"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;n>s;++s)a.indexOf(s)>=0?o[s]=!0:o[s]=!1;return b(t.vertex,t.cell,t.phase,i,r,o)}var _=t("typedarray-pool");e.exports=x;var w="V",k="P",A="N",M="Q",T="X",E="T"},{"typedarray-pool":432}],430:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],431:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],432:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":430,buffer:65,dup:122}],433:[function(t,e,r){function n(t){if(0>t)return Number("0/0");for(var e=s[0],r=s.length-1;r>0;--r)e+=s[r]/(t+r);var n=t+o+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}var i=7,a=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],o=607/128,s=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];e.exports=function l(t){if(.5>t)return Math.PI/(Math.sin(Math.PI*t)*l(1-t));if(t>100)return Math.exp(n(t));t-=1;for(var e=a[0],r=1;i+2>r;r++)e+=a[r]/(t+r);var o=t+i+.5;return Math.sqrt(2*Math.PI)*Math.pow(o,t+.5)*Math.exp(-o)*e},e.exports.log=n},{}],434:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],435:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],436:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":434,buffer:65,dup:122}],437:[function(t,e,r){"use strict";function n(t){var e=t.length;if(i>e){for(var r=1,n=0;e>n;++n)for(var o=0;n>o;++o)if(t[n]n;++n)s[n]=0;for(var r=1,n=0;e>n;++n)if(!s[n]){var l=1;s[n]=1;for(var o=t[n];o!==n;o=t[o]){if(s[o])return a.freeUint8(s),0;l+=1,s[o]=1}1&l||(r=-r)}return a.freeUint8(s),r}e.exports=n;var i=32,a=t("typedarray-pool")},{"typedarray-pool":436}],438:[function(t,e,r){"use strict";function n(t){var e=t.length;switch(e){case 0:case 1:return 0;case 2:return t[1]}var r,n,i,s=a.mallocUint32(e),l=a.mallocUint32(e),u=0;for(o(t,l),i=0;e>i;++i)s[i]=t[i];for(i=e-1;i>0;--i)n=l[i],r=s[i],s[i]=s[n],s[n]=r,l[i]=l[r],l[r]=n,u=(u+r)*i;return a.freeUint32(l),a.freeUint32(s),u}function i(t,e,r){switch(t){case 0:return r?r:[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}r=r||new Array(t);var n,i,a,o=1;for(r[0]=0,a=1;t>a;++a)r[a]=a,o=o*a|0;for(a=t-1;a>0;--a)n=e/o|0,e=e-n*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}var a=t("typedarray-pool"),o=t("invert-permutation");r.rank=n,r.unrank=i},{"invert-permutation":439,"typedarray-pool":442}],439:[function(t,e,r){"use strict";function n(t,e){e=e||new Array(t.length);for(var r=0;rt)return[];if(0===t)return[[0]];for(var e=0|Math.round(o(t+1)),r=[],n=0;e>n;++n){for(var s=i.unrank(t,n),l=[0],u=0,c=0;c= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":445}],445:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":447,dup:319}],446:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:448}],447:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":446,dup:321}],448:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],449:[function(t,e,r){"use strict";function n(t,e){var r=[];return e=+e||0,i(t.hi(t.shape[0]-1),r,e),r}e.exports=n;var i=t("./lib/zc-core")},{"./lib/zc-core":444}],450:[function(t,e,r){"use strict";function n(t,e){var r=t.length,n=["'use strict';"],i="surfaceNets"+t.join("_")+"d"+e;n.push("var contour=genContour({","order:[",t.join(),"],","scalarArguments: 3,","phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],l=[],u=0;r>u;++u)a.push("d"+u),l.push("d"+u);for(var u=0;1<u;++u)a.push("v"+u),l.push("v"+u);for(var u=0;1<u;++u)a.push("p"+u),l.push("p"+u);a.push("a","b","c"),l.push("a","c"),n.push("vertex:function vertexFunc(",a.join(),"){");for(var c=[],u=0;1<u;++u)c.push("(p"+u+"<<"+u+")");n.push("var m=(",c.join("+"),")|0;if(m===0||m===",(1<<(1<=1<<(1<>>7){");for(var u=0;1<<(1<u;++u){if(1<<(1<128&&u%128===0){f.length>0&&h.push("}}");var p="vExtra"+f.length;n.push("case ",u>>>7,":",p,"(m&0x7f,",l.join(),");break;"),h=["function ",p,"(m,",l.join(),"){switch(m){"],f.push(h)}h.push("case ",127&u,":");for(var d=new Array(r),g=new Array(r),v=new Array(r),m=new Array(r),y=0,b=0;r>b;++b)d[b]=[],g[b]=[],v[b]=0,m[b]=0;for(var b=0;1<b;++b)for(var x=0;r>x;++x){var _=b^1<b)&&!(u&1<<_)!=!(u&1<w?(d[x].push("-v"+b+"-v"+_),v[x]+=2):(d[x].push("v"+b+"+v"+_),v[x]-=2),y+=1;for(var k=0;r>k;++k)k!==x&&(_&1<x;++x)if(0===d[x].length)A.push("d"+x+"-0.5");else{var M="";v[x]<0?M=v[x]+"*c":v[x]>0&&(M="+"+v[x]+"*c");var T=.5*(d[x].length/y),E=.5+.5*(m[x]/y);A.push("d"+x+"-"+E+"-"+T+"*("+d[x].join("+")+M+")/("+g[x].join("+")+")")}h.push("a.push([",A.join(),"]);","break;")}n.push("}},"),f.length>0&&h.push("}}");for(var L=[],u=0;1<u;++u)L.push("v"+u);L.push("c0","c1","p0","p1","a","b","c"),n.push("cell:function cellFunc(",L.join(),"){");var S=s(r-1);n.push("if(p0){b.push(",S.map(function(t){return"["+t.map(function(t){return"v"+t})+"]"}).join(),")}else{b.push(",S.map(function(t){var e=t.slice();return e.reverse(),"["+e.map(function(t){return"v"+t})+"]"}).join(),")}}});function ",i,"(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ",i,";");for(var u=0;uo;++o)i[o]=[r[o]],a[o]=[o];return{positions:i,cells:a}}function a(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return i(t,e);var r=t.order.join()+"-"+t.dtype,a=u[r],e=+e||0;return a||(a=u[r]=n(t.order,t.dtype)),a(t,e)}e.exports=a;var o=t("ndarray-extract-contour"),s=t("triangulate-hypercube"),l=t("zero-crossings"),u={}},{"ndarray-extract-contour":429,"triangulate-hypercube":443,"zero-crossings":449}],451:[function(t,e,r){(function(r){"use strict";function n(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;ol;++l){var u=r[s[l]];n[i++]=u[0],n[i++]=u[1]+1.4, +a=Math.max(u[0],a)}return{data:n,shape:a}}function i(t,e){var r=s[t];r||(r=s[t]={" ":{data:new Float32Array(0),shape:.2}});var o=r[e];if(!o)if(e.length<=1||!/\d/.test(e))o=r[e]=n(a(e,{triangles:!0,font:t,textAlign:"left",textBaseline:"alphabetic"}));else{for(var l=e.split(/(\d|\s)/),u=new Array(l.length),c=0,f=0,h=0;h0&&(f+=.02);for(var p=new Float32Array(c),d=0,g=-.5*f,h=0;hd;++d)if(f[d]&&n[d]<=0&&n[d+2]>=0){var g=e[d]-n[d]*(e[d+2]-e[d])/(n[d+2]-n[d]);0===d?o.drawLine(g,e[1],g,e[3],p[d],h[d]):o.drawLine(e[0],g,e[2],g,p[d],h[d])}}for(var d=0;dd;++d)s.drawTicks(d);this.titleEnable&&s.drawTitle();for(var b=this.overlays,d=0;du;++u){var c=s[u].slice(0);0!==c.length&&(c.sort(a),l[u]=Math.min(l[u],c[0].x),l[u+2]=Math.max(l[u+2],c[c.length-1].x))}this.grid.update({bounds:l,ticks:s}),this.text.update({bounds:l,ticks:s,labels:t.labels||["x","y"],labelSize:t.labelSize||[12,12],labelFont:t.labelFont||["sans-serif","sans-serif"],title:t.title||"",titleSize:t.titleSize||18,titleFont:t.titleFont||"sans-serif"}),this.setDirty()},h.dispose=function(){this.box.dispose(),this.grid.dispose(),this.text.dispose(),this.line.dispose();for(var t=this.objects.length-1;t>=0;--t)this.objects[t].dispose();this.objects.length=0;for(var t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},h.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},h.removeObject=function(t){for(var e=this.objects,r=0;rh;++h)o=o&&l[h]===s[h],l[h]=s[h];var p=t.clientWidth===c&&t.clientHeight===f;return c=t.clientWidth,f=t.clientHeight,o?!p:(u=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){return n.setMode(t),n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return u},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var p=0,d=0;return o(t,function(e,r,a,o){var s=1/t.clientHeight,l=s*(r-p),c=s*(a-d),f=h.flipX?1:-1,g=h.flipY?1:-1,v=Math.PI*h.rotateSpeed,m=i();if(1&e)o.shift?n.rotate(m,0,0,-l*v):n.rotate(m,f*v*l,-g*v*c,0);else if(2&e)n.pan(m,-h.translateSpeed*l*u,h.translateSpeed*c*u,0);else if(4&e){var y=h.zoomSpeed*c/window.innerHeight*(m-n.lastT())*50;n.pan(m,0,0,u*(Math.exp(y)-1))}p=r,d=a}),s(t,function(t,e,r){var a=h.flipX?1:-1,o=h.flipY?1:-1,s=i();if(Math.abs(t)>Math.abs(e))n.rotate(s,0,0,-t*a*Math.PI*h.rotateSpeed/window.innerWidth);else{var l=h.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,u*(Math.exp(l)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],455:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":458}],456:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],457:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],458:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":456,buffer:65,dup:122}],459:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],460:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":459,dup:155}],461:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":459,dup:156}],462:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":460,"./lib/vao-native.js":461,dup:157}],463:[function(t,e,r){!function(){"use strict";function t(e){e.permitHostObjects___&&e.permitHostObjects___(t)}function r(t){return!(t.substr(0,p.length)==p&&"___"===t.substr(t.length-3))}function n(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[d];if(e&&e.key===t)return e;if(h(t)){e={key:t};try{return f(t,d,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(r){return}}}function i(t){return t.prototype=null,Object.freeze(t)}function a(){y||"undefined"==typeof console||(y=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}if("undefined"==typeof ses||!ses.ok||ses.ok()){"undefined"!=typeof ses&&(ses.weakMapPermitHostObjects=t);var o=!1;if("function"==typeof WeakMap){var s=WeakMap;if("undefined"!=typeof navigator&&/Firefox/.test(navigator.userAgent));else{var l=new s,u=Object.freeze({});if(l.set(u,1),1===l.get(u))return void(e.exports=WeakMap);o=!0}}var c=(Object.prototype.hasOwnProperty,Object.getOwnPropertyNames),f=Object.defineProperty,h=Object.isExtensible,p="weakmap:",d=p+"ident:"+Math.random()+"___";if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof ArrayBuffer&&"function"==typeof Uint8Array){var g=new ArrayBuffer(25),v=new Uint8Array(g);crypto.getRandomValues(v),d=p+"rand:"+Array.prototype.map.call(v,function(t){return(t%36).toString(36)}).join("")+"___"}if(f(Object,"getOwnPropertyNames",{value:function(t){return c(t).filter(r)}}),"getPropertyNames"in Object){var m=Object.getPropertyNames;f(Object,"getPropertyNames",{value:function(t){return m(t).filter(r)}})}!function(){var t=Object.freeze;f(Object,"freeze",{value:function(e){return n(e),t(e)}});var e=Object.seal;f(Object,"seal",{value:function(t){return n(t),e(t)}});var r=Object.preventExtensions;f(Object,"preventExtensions",{value:function(t){return n(t),r(t)}})}();var y=!1,b=0,x=function(){function t(t,e){var r,i=n(t);return i?u in i?i[u]:e:(r=s.indexOf(t),r>=0?l[r]:e)}function e(t){var e=n(t);return e?u in e:s.indexOf(t)>=0}function r(t,e){var r,i=n(t);return i?i[u]=e:(r=s.indexOf(t),r>=0?l[r]=e:(r=s.length,l[r]=e,s[r]=t)),this}function o(t){var e,r,i=n(t);return i?u in i&&delete i[u]:(e=s.indexOf(t),0>e?!1:(r=s.length-1,s[e]=void 0,l[e]=l[r],s[e]=s[r],s.length=r,l.length=r,!0))}this instanceof x||a();var s=[],l=[],u=b++;return Object.create(x.prototype,{get___:{value:i(t)},has___:{value:i(e)},set___:{value:i(r)},delete___:{value:i(o)}})};x.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},"delete":{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof s?!function(){function r(){function e(t,e){return c?u.has(t)?u.get(t):c.get___(t,e):u.get(t,e)}function r(t){return u.has(t)||(c?c.has___(t):!1)}function n(t){var e=!!u.delete(t);return c?c.delete___(t)||e:e}this instanceof x||a();var l,u=new s,c=void 0,f=!1;return l=o?function(t,e){return u.set(t,e),u.has(t)||(c||(c=new x),c.set(t,e)),this}:function(t,e){if(f)try{u.set(t,e)}catch(r){c||(c=new x),c.set___(t,e)}else u.set(t,e);return this},Object.create(x.prototype,{get___:{value:i(e)},has___:{value:i(r)},set___:{value:i(l)},delete___:{value:i(n)},permitHostObjects___:{value:i(function(e){if(e!==t)throw new Error("bogus call to permitHostObjects___");f=!0})}})}o&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=x.prototype,e.exports=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=x)}}()},{}],464:[function(t,e,r){"use strict";function n(t){var e=s.get(t);if(!e||!t.isBuffer(e._triangleBuffer.buffer)){var r=a(t,new Float32Array([-1,-1,-1,4,4,-1]));e=o(t,[{buffer:r,type:t.FLOAT,size:2}]),e._triangleBuffer=r,s.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}var i="undefined"==typeof WeakMap?t("weak-map"):WeakMap,a=t("gl-buffer"),o=t("gl-vao"),s=new i;e.exports=n},{"gl-buffer":455,"gl-vao":462,"weak-map":463}],465:[function(t,e,r){"use strict";function n(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function i(t){this.gl=t,this.pixelRatio=1,this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.autoTicks=!0,this.tickSpacing=[1,1,1],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[10,10,10],this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]},this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont="sans-serif",this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[10,10,10],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[0,0,0],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!1,!1,!1],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._firstInit=!0,this._text=null,this._lines=null,this._background=c(t)}function a(){this.primalOffset=[0,0,0],this.primalMinor=[0,0,0],this.mirrorOffset=[0,0,0],this.mirrorMinor=[0,0,0]}function o(t,e,r,n,i){for(var a=t.primalOffset,o=t.primalMinor,s=t.mirrorOffset,l=t.mirrorMinor,u=n[e],c=0;3>c;++c)if(e!==c){var f=a,h=s,p=o,d=l;u&1<0?(p[c]=-1,d[c]=0):(p[c]=0,d[c]=1)}}function s(t,e){var r=new i(t);return r.update(e),r}e.exports=s;var l=t("./lib/text.js"),u=t("./lib/lines.js"),c=t("./lib/background.js"),f=t("./lib/cube.js"),h=t("./lib/ticks.js"),p=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),d=i.prototype;d.update=function(t){function e(e,r,n){if(n in t){var i,a=t[n],o=this[n];(e?Array.isArray(a)&&Array.isArray(a[0]):Array.isArray(a))?this[n]=i=[r(a[0]),r(a[1]),r(a[2])]:this[n]=i=[r(a),r(a),r(a)];for(var s=0;3>s;++s)if(i[s]!==o[s])return!0}return!1}t=t||{};var r,n=e.bind(this,!1,Number),i=e.bind(this,!1,Boolean),a=e.bind(this,!1,String),o=e.bind(this,!0,function(t){if(Array.isArray(t)){if(3===t.length)return[+t[0],+t[1],+t[2],1];if(4===t.length)return[+t[0],+t[1],+t[2],+t[3]]}return[0,0,0,1]}),s=!1,c=!1;if("bounds"in t)for(var f=t.bounds,p=0;2>p;++p)for(var d=0;3>d;++d)f[p][d]!==this.bounds[p][d]&&(c=!0),this.bounds[p][d]=f[p][d];if("ticks"in t){r=t.ticks,s=!0,this.autoTicks=!1;for(var p=0;3>p;++p)this.tickSpacing[p]=0}else n("tickSpacing")&&(this.autoTicks=!0,c=!0);if(this._firstInit&&("ticks"in t||"tickSpacing"in t||(this.autoTicks=!0),c=!0,s=!0,this._firstInit=!1),c&&this.autoTicks&&(r=h.create(this.bounds,this.tickSpacing),s=!0),s){for(var p=0;3>p;++p)r[p].sort(function(t,e){return t.x-e.x});h.equal(r,this.ticks)?s=!1:this.ticks=r}i("tickEnable"),a("tickFont")&&(s=!0),n("tickSize"),n("tickAngle"),n("tickPad"),o("tickColor");var g=a("labels");a("labelFont")&&(g=!0),i("labelEnable"),n("labelSize"),n("labelPad"),o("labelColor"),i("lineEnable"),i("lineMirror"),n("lineWidth"),o("lineColor"),i("lineTickEnable"),i("lineTickMirror"),n("lineTickLength"),n("lineTickWidth"),o("lineTickColor"),i("gridEnable"),n("gridWidth"),o("gridColor"),i("zeroEnable"),o("zeroLineColor"),n("zeroLineWidth"),i("backgroundEnable"),o("backgroundColor"),this._text?this._text&&(g||s)&&this._text.update(this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont):this._text=l(this.gl,this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont),this._lines&&s&&(this._lines.dispose(),this._lines=null),this._lines||(this._lines=u(this.gl,this.bounds,this.ticks))};var g=[new a,new a,new a],v=[0,0,0],m={model:p,view:p,projection:p};d.isOpaque=function(){return!0},d.isTransparent=function(){return!1},d.drawTransparent=function(t){};var y=[0,0,0],b=[0,0,0],x=[0,0,0];d.draw=function(t){t=t||m;for(var e=this.gl,r=t.model||p,i=t.view||p,a=t.projection||p,s=this.bounds,l=f(r,i,a,s),u=l.cubeEdges,c=l.axis,h=i[12],d=i[13],_=i[14],w=i[15],k=this.pixelRatio*(a[3]*h+a[7]*d+a[11]*_+a[15]*w)/e.drawingBufferHeight,A=0;3>A;++A)this.lastCubeProps.cubeEdges[A]=u[A],this.lastCubeProps.axis[A]=c[A];for(var M=g,A=0;3>A;++A)o(g[A],A,this.bounds,u,c);for(var e=this.gl,T=v,A=0;3>A;++A)this.backgroundEnable[A]?T[A]=c[A]:T[A]=0;this._background.draw(r,i,a,s,T,this.backgroundColor),this._lines.bind(r,i,a,this);for(var A=0;3>A;++A){var E=[0,0,0];c[A]>0?E[A]=s[1][A]:E[A]=s[0][A];for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.gridEnable[S]&&this._lines.drawGrid(S,C,this.bounds,E,this.gridColor[S],this.gridWidth[S]*this.pixelRatio)}for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.zeroEnable[C]&&s[0][C]<=0&&s[1][C]>=0&&this._lines.drawZero(S,C,this.bounds,E,this.zeroLineColor[C],this.zeroLineWidth[C]*this.pixelRatio)}}for(var A=0;3>A;++A){this.lineEnable[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].primalOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio),this.lineMirror[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].mirrorOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio);for(var z=n(y,M[A].primalMinor),P=n(b,M[A].mirrorMinor),R=this.lineTickLength,L=0;3>L;++L){var j=k/r[5*L];z[L]*=R[L]*j,P[L]*=R[L]*j}this.lineTickEnable[A]&&this._lines.drawAxisTicks(A,M[A].primalOffset,z,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio),this.lineTickMirror[A]&&this._lines.drawAxisTicks(A,M[A].mirrorOffset,P,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio)}this._text.bind(r,i,a,this.pixelRatio);for(var A=0;3>A;++A){for(var O=M[A].primalMinor,I=n(x,M[A].primalOffset),L=0;3>L;++L)this.lineTickEnable[A]&&(I[L]+=k*O[L]*Math.max(this.lineTickLength[L],0)/r[5*L]);if(this.tickEnable[A]){for(var L=0;3>L;++L)I[L]+=k*O[L]*this.tickPad[L]/r[5*L];this._text.drawTicks(A,this.tickSize[A],this.tickAngle[A],I,this.tickColor[A])}if(this.labelEnable[A]){for(var L=0;3>L;++L)I[L]+=k*O[L]*this.labelPad[L]/r[5*L];I[A]+=.5*(s[0][A]+s[1][A]),this._text.drawLabel(A,this.labelSize[A],this.labelAngle[A],I,this.labelColor[A])}}},d.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":466,"./lib/cube.js":467,"./lib/lines.js":468,"./lib/text.js":470,"./lib/ticks.js":471}],466:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}function i(t){for(var e=[],r=[],i=0,l=0;3>l;++l)for(var u=(l+1)%3,c=(l+2)%3,f=[0,0,0],h=[0,0,0],p=-1;1>=p;p+=2){r.push(i,i+2,i+1,i+1,i+2,i+3),f[l]=p,h[l]=p;for(var d=-1;1>=d;d+=2){f[u]=d;for(var g=-1;1>=g;g+=2)f[c]=g,e.push(f[0],f[1],f[2],h[0],h[1],h[2]),i+=1}var v=u;u=c,c=v}var m=a(t,new Float32Array(e)),y=a(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),b=o(t,[{buffer:m,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:m,type:t.FLOAT,size:3,offset:12,stride:24}],y),x=s(t);return x.attributes.position.location=0,x.attributes.normal.location=1,new n(t,m,b,x)}e.exports=i;var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders").bg,l=n.prototype;l.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;3>s;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),l.disable(l.POLYGON_OFFSET_FILL)}},l.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":469,"gl-buffer":475,"gl-vao":480}],467:[function(t,e,r){"use strict";function n(t,e,r){for(var n=0;4>n;++n){t[n]=r[12+n];for(var i=0;3>i;++i)t[n]+=e[i]*r[4*i+n]}}function i(t){for(var e=0;eg;++g){p[2]=a[g][2];for(var b=0;2>b;++b){p[1]=a[b][1];for(var x=0;2>x;++x)p[0]=a[x][0],n(f[l],p,c),l+=1}}for(var _=-1,g=0;8>g;++g){for(var w=f[g][3],k=0;3>k;++k)h[g][k]=f[g][k]/w;0>w&&(0>_?_=g:h[g][2]_){_=0;for(var A=0;3>A;++A){for(var M=(A+2)%3,T=(A+1)%3,E=-1,L=-1,S=0;2>S;++S){var C=S<E||0>L)L>E&&(_|=1<S;++S){var C=S<E&&(_|=1<g;++g)g!==_&&g!==j&&(0>O?O=g:h[O][1]>h[g][1]&&(O=g));for(var I=-1,g=0;3>g;++g){var N=O^1<I&&(I=N);var T=h[N];T[0]g;++g){var N=O^1<F&&(F=N);var T=h[N];T[0]>h[F][0]&&(F=N)}}var D=v;D[0]=D[1]=D[2]=0,D[o.log2(I^O)]=O&I,D[o.log2(O^F)]=O&F;var B=7^F;B===_||B===j?(B=7^I,D[o.log2(F^B)]=B&F):D[o.log2(I^B)]=B&I;for(var U=m,V=_,A=0;3>A;++A)V&1<t;++t)f[t]=[1,1,1,1],h[t]=[1,1,1]}();var g=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]],v=[1,1,1],m=[0,0,0],y={cubeEdges:v,axis:m}},{"bit-twiddle":472,"gl-mat4/invert":240,"gl-mat4/multiply":242,"robust-orientation":1040,"split-polygon":482}],468:[function(t,e,r){"use strict";function n(t){return t[0]=t[1]=t[2]=0,t}function i(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function a(t,e,r,n,i,a,o,s){this.gl=t,this.vertBuffer=e,this.vao=r,this.shader=n,this.tickCount=i,this.tickOffset=a,this.gridCount=o,this.gridOffset=s}function o(t,e,r){var n=[],i=[0,0,0],o=[0,0,0],c=[0,0,0],f=[0,0,0];n.push(0,0,1,0,1,1,0,0,-1,0,0,-1,0,1,1,0,1,-1);for(var h=0;3>h;++h){for(var p=n.length/3|0,d=0;dh;++h)for(var d=c[h],g=2;g>=0;--g){var v=u[d[g]];s.push(l*v[0],-l*v[1],t)}}for(var s=(this.gl,[]),l=[0,0,0],u=[0,0,0],c=[0,0,0],p=[0,0,0],d=0;3>d;++d){c[d]=s.length/h|0,o(.5*(t[0][d]+t[1][d]),e[d],r),p[d]=(s.length/h|0)-c[d],l[d]=s.length/h|0;for(var g=0;g=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;0>o?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u=0|u);var c=""+l;if(0>o&&(c="-"+c),i){for(var f=""+u;f.lengthi;++i){for(var a=[],o=(.5*(t[0][i]+t[1][i]),0);o*e[i]<=t[1][i];++o)a.push({x:o*e[i],text:n(e[i],o)});for(var o=-1;o*e[i]>=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r}function a(t,e){for(var r=0;3>r;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;na?a=0:a>1&&(a=1);for(var o=1-a,s=t.length,l=new Array(s),u=0;s>u;++u)l[u]=a*t[u]+o*r[u];return l}function a(t,e){for(var r=[],a=[],o=n(t[t.length-1],e),s=t[t.length-1],l=t[0],u=0;uo&&c>0||o>0&&0>c){var f=i(s,c,l,o);r.push(f),a.push(f.slice())}0>c?a.push(l.slice()):c>0?r.push(l.slice()):(r.push(l.slice()),a.push(l.slice())),o=c}return{positive:r,negative:a}}function o(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&u>0||a>0&&0>u)&&r.push(i(o,u,s,a)),u>=0&&r.push(s.slice()),a=u}return r}function s(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&u>0||a>0&&0>u)&&r.push(i(o,u,s,a)),0>=u&&r.push(s.slice()),a=u}return r}var l=t("robust-dot-product"),u=t("robust-sum");e.exports=a,e.exports.positive=o,e.exports.negative=s},{"robust-dot-product":483,"robust-sum":485}],483:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t[0],e[0]),n=1;na;++a){for(var o=d,s=g,l=0;3>l;++l)s[l]=o[l]=r[l];s[3]=o[3]=1,s[a]+=1,f(s,s,e),s[3]<0&&(t[a]=1/0),o[a]-=1,f(o,o,e),o[3]<0&&(t[a]=1/0);var u=(o[0]/o[3]-s[0]/s[3])*n,c=(o[1]/o[3]-s[1]/s[3])*i;t[a]=.25*Math.sqrt(u*u+c*c)}return t}function a(t,e,r,n,a){var f=e.model||h,d=e.view||h,g=e.projection||h,y=t.bounds,a=a||l(f,d,g,y),b=a.axis;a.edges;u(p,d,f),u(p,g,p);for(var x=v,_=0;3>_;++_)x[_].lo=1/0,x[_].hi=-(1/0),x[_].pixelsPerDataUnit=1/0;var w=o(c(p,p));c(p,p);for(var k=0;3>k;++k){var A=(k+1)%3,M=(k+2)%3,T=m;t:for(var _=0;2>_;++_){var E=[];if(b[k]<0!=!!_){T[k]=y[_][k];for(var L=0;2>L;++L){T[A]=y[L^_][A];for(var S=0;2>S;++S)T[M]=y[S^L^_][M],E.push(T.slice())}for(var L=0;LS;++S)x[S].lo=Math.min(x[S].lo,M[S]),x[S].hi=Math.max(x[S].hi,M[S]),S!==k&&(x[S].pixelsPerDataUnit=Math.min(x[S].pixelsPerDataUnit,Math.abs(C[S])))}}}return x}e.exports=a;var o=t("extract-frustum-planes"),s=t("split-polygon"),l=t("./lib/cube.js"),u=t("gl-mat4/multiply"),c=t("gl-mat4/transpose"),f=t("gl-vec4/transformMat4"),h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),p=new Float32Array(16),d=[0,0,0,1],g=[0,0,0,1],v=[new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0)],m=[0,0,0]},{"./lib/cube.js":467,"extract-frustum-planes":474,"gl-mat4/multiply":242,"gl-mat4/transpose":250,"gl-vec4/transformMat4":481,"split-polygon":482}],576:[function(t,e,r){arguments[4][323][0].apply(r,arguments)},{dup:323,"gl-texture2d":580}],577:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],578:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],579:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":577,buffer:65,dup:122}],580:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":579}],581:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],582:[function(t,e,r){arguments[4][318][0].apply(r,arguments)},{"cwise-compiler":583,dup:318}],583:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":585,dup:319}],584:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:586}],585:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":584,dup:321}],586:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],587:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],588:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":581,buffer:65,dup:122}],589:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.coord=[t,e],this.id=r,this.value=n,this.distance=i}function i(t,e,r){this.gl=t,this.fbo=e,this.buffer=r,this._readTimeout=null;var n=this;this._readCallback=function(){n.gl&&(e.bind(),t.readPixels(0,0,e.shape[0],e.shape[1],t.RGBA,t.UNSIGNED_BYTE,n.buffer),n._readTimeout=null)}}function a(t,e){var r=o(t,e),n=s.mallocUint8(e[0]*e[1]*4);return new i(t,r,n)}e.exports=a;var o=t("gl-fbo"),s=t("typedarray-pool"),l=t("ndarray"),u=t("bit-twiddle").nextPow2,c=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(255>_inline_4_arg0_||255>_inline_4_arg1_||255>_inline_4_arg2_||255>_inline_4_arg3_){var _inline_4_l=_inline_4_arg4_-_inline_4_arg6_[0],_inline_4_a=_inline_4_arg5_-_inline_4_arg6_[1],_inline_4_f=_inline_4_l*_inline_4_l+_inline_4_a*_inline_4_a;_inline_4_fthis.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(u(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),f.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},f.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},f.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),u=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=u)return null;var f=[o-a,u-s],h=l(this.buffer,[f[0],f[1],4],[4,4*i[0],1],4*(a+i[0]*s)),p=c(h.hi(f[0],f[1],1),r,r),d=p[0],g=p[1];if(0>d||Math.pow(this.radius,2)d;++d)i&&i[d]<0?(u[d]=this.bounds[0][d],p[d]=this.bounds[1][d]):(u[d]=this.bounds[1][d],p[d]=this.bounds[0][d]);h[0]=e.drawingBufferWidth,h[1]=e.drawingBufferHeight,n.uniforms.model=a,n.uniforms.view=o,n.uniforms.projection=s,n.uniforms.coordinates=[this.position,u,p],n.uniforms.colors=this.colors,n.uniforms.screenShape=h;for(var d=0;3>d;++d)n.uniforms.lineWidth=this.lineWidth[d]*this.pixelRatio,this.enabled[d]&&(r.draw(e.TRIANGLES,6,6*d),this.drawSides[d]&&r.draw(e.TRIANGLES,12,18+12*d));r.unbind()},u.update=function(t){t&&("bounds"in t&&(this.bounds=t.bounds),"position"in t&&(this.position=t.position),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"colors"in t&&(this.colors=t.colors),"enabled"in t&&(this.enabled=t.enabled),"drawSides"in t&&(this.drawSides=t.drawSides))},u.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders/index":624,"gl-buffer":616,"gl-vao":623}],626:[function(t,e,r){"use strict";function n(){this.mouse=[-1,-1],this.screen=null,this.distance=1/0,this.index=null,this.dataCoordinate=null,this.dataPosition=null,this.object=null,this.data=null}function i(t,e){var r=null;try{r=t.getContext("webgl",e),r||(r=t.getContext("experimental-webgl",e))}catch(n){return null}return r}function a(t){var e=Math.round(Math.log(Math.abs(t))/Math.log(10));if(0>e){var r=Math.round(Math.pow(10,-e));return Math.ceil(t*r)/r}if(e>0){var r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function o(t){return"boolean"==typeof t?t:!0}function s(t){function e(){if(!_&&G.autoResize){var t=w.parentNode,e=1,r=1;t&&t!==document.body?(e=t.clientWidth,r=t.clientHeight):(e=window.innerWidth,r=window.innerHeight);var n=0|Math.ceil(e*G.pixelRatio),i=0|Math.ceil(r*G.pixelRatio);if(n!==w.width||i!==w.height){w.width=n,w.height=i;var a=w.style;a.position=a.position||"absolute",a.left="0px",a.top="0px",a.width=e+"px",a.height=r+"px",F=!0}}}function r(){for(var t=j.length,e=N.length,r=0;e>r;++r)I[r]=0;t:for(var r=0;t>r;++r){var n=j[r],i=n.pickSlots;if(i){for(var a=0;e>a;++a)if(I[a]+i<255){O[r]=a,n.setPickBase(I[a]+1),I[a]+=i;continue t}var o=h(A,q);O[r]=e,N.push(o),I.push(i),n.setPickBase(1),e+=1}else O[r]=-1}for(;e>0&&0===I[e-1];)I.pop(),N.pop().dispose()}function s(){return G.contextLost?!0:void(A.isContextLost()&&(G.contextLost=!0,G.mouseListener.enabled=!1,G.selection.object=null,G.oncontextloss&&G.oncontextloss()))}function y(){if(!s()){A.colorMask(!0,!0,!0,!0),A.depthMask(!0),A.disable(A.BLEND),A.enable(A.DEPTH_TEST);for(var t=j.length,e=N.length,r=0;e>r;++r){var n=N[r];n.shape=H,n.begin();for(var i=0;t>i;++i)if(O[i]===r){var a=j[i];a.drawPick&&(a.pixelRatio=1,a.drawPick(V))}n.end()}}}function b(){if(!s()){e();var t=G.camera.tick();V.view=G.camera.matrix,F=F||t,D=D||t,z.pixelRatio=G.pixelRatio,R.pixelRatio=G.pixelRatio;var r=j.length,n=W[0],i=W[1];n[0]=n[1]=n[2]=1/0,i[0]=i[1]=i[2]=-(1/0);for(var o=0;r>o;++o){var l=j[o];l.pixelRatio=G.pixelRatio,l.axes=G.axes,F=F||!!l.dirty,D=D||!!l.dirty;var u=l.bounds;if(u)for(var f=u[0],h=u[1],p=0;3>p;++p)n[p]=Math.min(n[p],f[p]),i[p]=Math.max(i[p],h[p])}var g=G.bounds;if(G.autoBounds)for(var p=0;3>p;++p){if(i[p]p;++p)b=b||Z[0][p]!==g[0][p]||Z[1][p]!==g[1][p],Z[0][p]=g[0][p],Z[1][p]=g[1][p];if(b){for(var x=[0,0,0],o=0;3>o;++o)x[o]=a((g[1][o]-g[0][o])/10);z.autoTicks?z.update({bounds:g,tickSpacing:x}):z.update({bounds:g})}D=D||b,F=F||b;var _=A.drawingBufferWidth,w=A.drawingBufferHeight;q[0]=_,q[1]=w,H[0]=0|Math.max(_/G.pixelRatio,1),H[1]=0|Math.max(w/G.pixelRatio,1),v(B,G.fovy,_/w,G.zNear,G.zFar);for(var o=0;16>o;++o)U[o]=0;U[15]=1;for(var k=0,o=0;3>o;++o)k=Math.max(k,g[1][o]-g[0][o]);for(var o=0;3>o;++o)G.autoScale?U[5*o]=G.aspect[o]/(g[1][o]-g[0][o]):U[5*o]=1/k,G.autoCenter&&(U[12+o]=.5*-U[5*o]*(g[0][o]+g[1][o])); +for(var o=0;r>o;++o){var l=j[o];l.axesBounds=g,G.clipToBounds&&(l.clipBounds=g)}if(T.object&&(G.snapToData?R.position=T.dataCoordinate:R.position=T.dataPosition,R.bounds=g),D&&(D=!1,y()),F){G.axesPixels=c(G.axes,V,_,w),G.onrender&&G.onrender(),A.bindFramebuffer(A.FRAMEBUFFER,null),A.viewport(0,0,_,w);var M=G.clearColor;A.clearColor(M[0],M[1],M[2],M[3]),A.clear(A.COLOR_BUFFER_BIT|A.DEPTH_BUFFER_BIT),A.depthMask(!0),A.colorMask(!0,!0,!0,!0),A.enable(A.DEPTH_TEST),A.depthFunc(A.LEQUAL),A.disable(A.BLEND),A.disable(A.CULL_FACE);var S=!1;z.enable&&(S=S||z.isTransparent(),z.draw(V)),R.axes=z,T.object&&R.draw(V),A.disable(A.CULL_FACE);for(var o=0;r>o;++o){var l=j[o];l.axes=z,l.pixelRatio=G.pixelRatio,l.isOpaque&&l.isOpaque()&&l.draw(V),l.isTransparent&&l.isTransparent()&&(S=!0)}if(S){E.shape=q,E.bind(),A.clear(A.DEPTH_BUFFER_BIT),A.colorMask(!1,!1,!1,!1),A.depthMask(!0),A.depthFunc(A.LESS),z.enable&&z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=j[o];l.isOpaque&&l.isOpaque()&&l.draw(V)}A.enable(A.BLEND),A.blendEquation(A.FUNC_ADD),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.colorMask(!0,!0,!0,!0),A.depthMask(!1),A.clearColor(0,0,0,0),A.clear(A.COLOR_BUFFER_BIT),z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=j[o];l.isTransparent&&l.isTransparent()&&l.drawTransparent(V)}A.bindFramebuffer(A.FRAMEBUFFER,null),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.disable(A.DEPTH_TEST),L.bind(),E.color[0].bind(0),L.uniforms.accumBuffer=0,d(A),A.disable(A.BLEND)}F=!1;for(var o=0;r>o;++o)j[o].dirty=!1}}}function x(){_||G.contextLost||(requestAnimationFrame(x),b())}t=t||{};var _=!1,w=(t.pixelRatio||parseFloat(window.devicePixelRatio),t.canvas);if(!w)if(w=document.createElement("canvas"),t.container){var k=t.container;k.appendChild(w)}else document.body.appendChild(w);var A=t.gl;if(A||(A=i(w,t.glOptions||{premultipliedAlpha:!0,antialias:!0})),!A)throw new Error("webgl not supported");var M=t.bounds||[[-10,-10,-10],[10,10,10]],T=new n,E=p(A,[A.drawingBufferWidth,A.drawingBufferHeight],{preferFloat:!0}),L=m(A),S=t.camera||{eye:[2,0,0],center:[0,0,0],up:[0,1,0],zoomMin:.1,zoomMax:100,mode:"turntable"},C=t.axes||{},z=u(A,C);z.enable=!C.disable;var P=t.spikes||{},R=f(A,P),j=[],O=[],I=[],N=[],F=!0,D=!0,B=new Array(16),U=new Array(16),V={view:null,projection:B,model:U},D=!0,q=[A.drawingBufferWidth,A.drawingBufferHeight],G={gl:A,contextLost:!1,pixelRatio:t.pixelRatio||parseFloat(window.devicePixelRatio),canvas:w,selection:T,camera:l(w,S),axes:z,axesPixels:null,spikes:R,bounds:M,objects:j,shape:q,aspect:t.aspectRatio||[1,1,1],pickRadius:t.pickRadius||10,zNear:t.zNear||.01,zFar:t.zFar||1e3,fovy:t.fovy||Math.PI/4,clearColor:t.clearColor||[0,0,0,0],autoResize:o(t.autoResize),autoBounds:o(t.autoBounds),autoScale:!!t.autoScale,autoCenter:o(t.autoCenter),clipToBounds:o(t.clipToBounds),snapToData:!!t.snapToData,onselect:t.onselect||null,onrender:t.onrender||null,onclick:t.onclick||null,cameraParams:V,oncontextloss:null,mouseListener:null},H=[A.drawingBufferWidth/G.pixelRatio|0,A.drawingBufferHeight/G.pixelRatio|0];G.autoResize&&e(),window.addEventListener("resize",e),G.update=function(t){_||(t=t||{},F=!0,D=!0)},G.add=function(t){_||(t.axes=z,j.push(t),O.push(-1),F=!0,D=!0,r())},G.remove=function(t){if(!_){var e=j.indexOf(t);0>e||(j.splice(e,1),O.pop(),F=!0,D=!0,r())}},G.dispose=function(){if(!_&&(_=!0,window.removeEventListener("resize",e),w.removeEventListener("webglcontextlost",s),G.mouseListener.enabled=!1,!G.contextLost)){z.dispose(),R.dispose();for(var t=0;ts;++s){var l=N[s].query(e,H[1]-r-1,G.pickRadius);if(l){if(l.distance>T.distance)continue;for(var u=0;i>u;++u){var c=j[u];if(O[u]===s){var f=c.pick(l);f&&(T.buttons=t,T.screen=l.coord,T.distance=l.distance,T.object=c,T.index=f.distance,T.dataPosition=f.position,T.dataCoordinate=f.dataCoordinate,T.data=f,o=!0)}}}}}a&&a!==T.object&&(a.highlight&&a.highlight(null),F=!0),T.object&&(T.object.highlight&&T.object.highlight(T.data),F=!0),o=o||T.object!==a,o&&G.onselect&&G.onselect(T),1&t&&!(1&X)&&G.onclick&&G.onclick(T),X=t}}),w.addEventListener("webglcontextlost",s);var W=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],Z=[W[0].slice(),W[1].slice()];return x(),G.redraw=function(){_||(F=!0,b())},G}e.exports=s;var l=t("3d-view-controls"),u=t("gl-axes3d"),c=t("gl-axes3d/properties"),f=t("gl-spikes3d"),h=t("gl-select-static"),p=t("gl-fbo"),d=t("a-big-triangle"),g=t("mouse-change"),v=t("gl-mat4/perspective"),m=t("./lib/shader")},{"./lib/shader":453,"3d-view-controls":454,"a-big-triangle":464,"gl-axes3d":465,"gl-axes3d/properties":575,"gl-fbo":576,"gl-mat4/perspective":243,"gl-select-static":589,"gl-spikes3d":625,"mouse-change":1004}],627:[function(t,e,r){"use strict";e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",fragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n",pickVertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",pickFragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n"}},{}],628:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":658}],629:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":630,"./lib/create-attributes":631,"./lib/create-uniforms":632,"./lib/reflect":633,"./lib/runtime-reflect":634,"./lib/shader-cache":635,dup:94}],630:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],631:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":630,dup:96}],632:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":630,"./reflect":633,dup:97}],633:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],634:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],635:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":630,dup:100,"gl-format-compiler-error":636,"weakmap-shim":654}],636:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":637,dup:101,"gl-constants/lookup":641,"glsl-shader-name":642,"sprintf-js":651}],637:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":638}],638:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":639}],639:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],640:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],641:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":640,dup:106}],642:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":643,dup:107,"glsl-tokenizer":650}],643:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],644:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":646,"./lib/builtins-300es":645,"./lib/literals":648,"./lib/literals-300es":647,"./lib/operators":649,dup:109}],645:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":646,dup:110}],646:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],647:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":648,dup:112}],648:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],649:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],650:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":644,dup:115}],651:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],652:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":653,dup:117}],653:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],654:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":652,dup:119}],655:[function(t,e,r){arguments[4][451][0].apply(r,arguments)},{_process:70,dup:451,"vectorize-text":659}],656:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],657:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],658:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":656,buffer:65,dup:122}],659:[function(t,e,r){arguments[4][354][0].apply(r,arguments)},{"./lib/vtext":660,dup:354}],660:[function(t,e,r){arguments[4][355][0].apply(r,arguments)},{cdt2d:661,"clean-pslg":673,dup:355,ndarray:1031,"planar-graph-to-polyline":728,"simplify-planar-graph":732,"surface-nets":745}],661:[function(t,e,r){arguments[4][356][0].apply(r,arguments)},{"./lib/delaunay":662,"./lib/filter":663,"./lib/monotone":664,"./lib/triangulation":665,dup:356}],662:[function(t,e,r){arguments[4][357][0].apply(r,arguments)},{"binary-search-bounds":666,dup:357,"robust-in-sphere":667}],663:[function(t,e,r){arguments[4][358][0].apply(r,arguments)},{"binary-search-bounds":666,dup:358}],664:[function(t,e,r){arguments[4][359][0].apply(r,arguments)},{"binary-search-bounds":666,dup:359,"robust-orientation":1040}],665:[function(t,e,r){arguments[4][360][0].apply(r,arguments)},{"binary-search-bounds":666,dup:360}],666:[function(t,e,r){arguments[4][312][0].apply(r,arguments)},{dup:312}],667:[function(t,e,r){arguments[4][361][0].apply(r,arguments)},{dup:361,"robust-scale":669,"robust-subtract":670,"robust-sum":671,"two-product":672}],668:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],669:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":672,"two-sum":668}],670:[function(t,e,r){arguments[4][364][0].apply(r,arguments)},{dup:364}],671:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],672:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],673:[function(t,e,r){arguments[4][367][0].apply(r,arguments)},{"./lib/rat-seg-intersect":674,"big-rat":678,"big-rat/cmp":676,"big-rat/to-float":693,"box-intersect":694,"compare-cell":702,dup:367,nextafter:703,"rat-vec":706,"robust-segment-intersect":709,"union-find":710}],674:[function(t,e,r){arguments[4][368][0].apply(r,arguments)},{"big-rat/div":677,"big-rat/mul":687,"big-rat/sign":691,"big-rat/sub":692,"big-rat/to-float":693,dup:368,"rat-vec/add":705,"rat-vec/muls":707,"rat-vec/sub":708}],675:[function(t,e,r){arguments[4][369][0].apply(r,arguments)},{"./lib/rationalize":685,dup:369}],676:[function(t,e,r){arguments[4][370][0].apply(r,arguments)},{dup:370}],677:[function(t,e,r){arguments[4][371][0].apply(r,arguments)},{"./lib/rationalize":685,dup:371}],678:[function(t,e,r){arguments[4][372][0].apply(r,arguments)},{"./div":677,"./is-rat":679,"./lib/is-bn":683,"./lib/num-to-bn":684,"./lib/rationalize":685,"./lib/str-to-bn":686,dup:372}],679:[function(t,e,r){arguments[4][373][0].apply(r,arguments)},{"./lib/is-bn":683,dup:373}],680:[function(t,e,r){arguments[4][374][0].apply(r,arguments)},{"bn.js":689,dup:374}],681:[function(t,e,r){arguments[4][375][0].apply(r,arguments)},{dup:375}],682:[function(t,e,r){arguments[4][376][0].apply(r,arguments)},{"bit-twiddle":688,"double-bits":690,dup:376}],683:[function(t,e,r){arguments[4][377][0].apply(r,arguments)},{"bn.js":689,dup:377}],684:[function(t,e,r){arguments[4][378][0].apply(r,arguments)},{"bn.js":689,"double-bits":690,dup:378}],685:[function(t,e,r){arguments[4][379][0].apply(r,arguments)},{"./bn-sign":680,"./num-to-bn":684,dup:379}],686:[function(t,e,r){arguments[4][380][0].apply(r,arguments)},{"bn.js":689,dup:380}],687:[function(t,e,r){arguments[4][381][0].apply(r,arguments)},{"./lib/rationalize":685,dup:381}],688:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],689:[function(t,e,r){arguments[4][383][0].apply(r,arguments)},{dup:383}],690:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],691:[function(t,e,r){arguments[4][385][0].apply(r,arguments)},{"./lib/bn-sign":680,dup:385}],692:[function(t,e,r){arguments[4][386][0].apply(r,arguments)},{"./lib/rationalize":685,dup:386}],693:[function(t,e,r){arguments[4][387][0].apply(r,arguments)},{"./lib/bn-to-num":681,"./lib/ctz":682,dup:387}],694:[function(t,e,r){arguments[4][388][0].apply(r,arguments)},{"./lib/intersect":696,"./lib/sweep":700,dup:388,"typedarray-pool":658}],695:[function(t,e,r){arguments[4][389][0].apply(r,arguments)},{dup:389}],696:[function(t,e,r){arguments[4][390][0].apply(r,arguments)},{"./brute":695,"./median":697,"./partition":698,"./sweep":700,"bit-twiddle":701,dup:390,"typedarray-pool":658}],697:[function(t,e,r){arguments[4][391][0].apply(r,arguments)},{"./partition":698,dup:391}],698:[function(t,e,r){arguments[4][392][0].apply(r,arguments)},{dup:392}],699:[function(t,e,r){arguments[4][393][0].apply(r,arguments)},{dup:393}],700:[function(t,e,r){arguments[4][394][0].apply(r,arguments)},{"./sort":699,"bit-twiddle":701,dup:394,"typedarray-pool":658}],701:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],702:[function(t,e,r){arguments[4][61][0].apply(r,arguments)},{dup:61}],703:[function(t,e,r){arguments[4][399][0].apply(r,arguments)},{"double-bits":704,dup:399}],704:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],705:[function(t,e,r){arguments[4][401][0].apply(r,arguments)},{"big-rat/add":675,dup:401}],706:[function(t,e,r){arguments[4][402][0].apply(r,arguments)},{"big-rat":678,dup:402}],707:[function(t,e,r){arguments[4][403][0].apply(r,arguments)},{"big-rat":678,"big-rat/mul":687,dup:403}],708:[function(t,e,r){arguments[4][404][0].apply(r,arguments)},{"big-rat/sub":692,dup:404}],709:[function(t,e,r){arguments[4][405][0].apply(r,arguments)},{dup:405,"robust-orientation":1040}],710:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],711:[function(t,e,r){arguments[4][407][0].apply(r,arguments)},{dup:407,"edges-to-adjacency-list":712}],712:[function(t,e,r){arguments[4][408][0].apply(r,arguments)},{dup:408,uniq:727}],713:[function(t,e,r){arguments[4][409][0].apply(r,arguments)},{"compare-angle":714,dup:409}],714:[function(t,e,r){arguments[4][410][0].apply(r,arguments)},{dup:410,"robust-orientation":1040,"robust-product":716,"robust-sum":725,signum:717,"two-sum":718}],715:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":726,"two-sum":718}],716:[function(t,e,r){arguments[4][412][0].apply(r,arguments)},{dup:412,"robust-scale":715,"robust-sum":725}],717:[function(t,e,r){arguments[4][413][0].apply(r,arguments)},{dup:413}],718:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],719:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],720:[function(t,e,r){arguments[4][416][0].apply(r,arguments)},{"binary-search-bounds":719,dup:416}],721:[function(t,e,r){arguments[4][417][0].apply(r,arguments)},{dup:417,"robust-orientation":1040}],722:[function(t,e,r){arguments[4][418][0].apply(r,arguments)},{dup:418}],723:[function(t,e,r){arguments[4][419][0].apply(r,arguments)},{"./lib/order-segments":721,"binary-search-bounds":719,dup:419,"functional-red-black-tree":722,"robust-orientation":1040}],724:[function(t,e,r){arguments[4][420][0].apply(r,arguments)},{"binary-search-bounds":719,dup:420,"interval-tree-1d":720,"robust-orientation":1040,"slab-decomposition":723}],725:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],726:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],727:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],728:[function(t,e,r){arguments[4][424][0].apply(r,arguments)},{"./lib/trim-leaves":711,dup:424,"edges-to-adjacency-list":712,"planar-dual":713,"point-in-big-polygon":724,"robust-sum":725,"two-product":726,uniq:727}],729:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],730:[function(t,e,r){arguments[4][426][0].apply(r,arguments)},{dup:426}],731:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":729,dup:79,"union-find":730}],732:[function(t,e,r){arguments[4][428][0].apply(r,arguments)},{dup:428,"robust-orientation":1040,"simplicial-complex":731}],733:[function(t,e,r){arguments[4][429][0].apply(r,arguments)},{dup:429,"typedarray-pool":658}],734:[function(t,e,r){arguments[4][433][0].apply(r,arguments)},{dup:433}],735:[function(t,e,r){arguments[4][437][0].apply(r,arguments)},{dup:437,"typedarray-pool":658}],736:[function(t,e,r){arguments[4][438][0].apply(r,arguments)},{dup:438,"invert-permutation":737,"typedarray-pool":658}],737:[function(t,e,r){arguments[4][439][0].apply(r,arguments)},{dup:439}],738:[function(t,e,r){arguments[4][443][0].apply(r,arguments)},{dup:443,gamma:734,"permutation-parity":735,"permutation-rank":736}],739:[function(t,e,r){arguments[4][444][0].apply(r,arguments)},{"cwise-compiler":740,dup:444}],740:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":742,dup:319}],741:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:743}],742:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":741,dup:321}],743:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],744:[function(t,e,r){arguments[4][449][0].apply(r,arguments)},{"./lib/zc-core":739,dup:449}],745:[function(t,e,r){arguments[4][450][0].apply(r,arguments)},{dup:450,"ndarray-extract-contour":733,"triangulate-hypercube":738,"zero-crossings":744}],746:[function(t,e,r){"use strict";function n(t){if(t in h)return h[t];var e=c(t,{polygons:!0,font:"sans-serif",textAlign:"left",textBaseline:"alphabetic"}),r=[],n=[];e.forEach(function(t){t.forEach(function(t){for(var e=0;eo;++o)i[o]=Math.min(i[o],r[a+o]),i[2+o]=Math.max(i[2+o],r[a+o]);return h[t]={coords:r,normals:n,bounds:i}}function i(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.offsetBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.numVertices=0,this.pickOffset=0,this.points=null}function a(t,e){var r=t.gl,n=o(r,f.vertex,f.fragment),a=o(r,f.pickVertex,f.pickFragment),l=s(r),u=s(r),c=s(r),h=s(r),p=new i(t,n,a,l,u,c,h);return p.update(e),t.addObject(p),p}e.exports=a;var o=t("gl-shader"),s=t("gl-buffer"),l=t("text-cache"),u=t("typedarray-pool"),c=t("vectorize-text"),f=t("./lib/shaders"),h={},p=i.prototype;!function(){function t(){var t=this.plot,n=this.bounds,i=t.viewBox,a=t.dataBox,o=t.pixelRatio,s=n[2]-n[0],l=n[3]-n[1],u=a[2]-a[0],c=a[3]-a[1];e[0]=2*s/u,e[4]=2*l/c,e[6]=2*(n[0]-a[0])/u-1,e[7]=2*(n[1]-a[1])/c-1;var f=i[2]-i[0],h=i[3]-i[1];r[0]=2*o/f,r[1]=2*o/h}var e=[1,0,0,0,1,0,0,0,1],r=[1,1];p.draw=function(){var n=this.plot,i=this.shader,a=this.numVertices;if(a){var o=n.gl;t.call(this),i.bind(),i.uniforms.pixelScale=r,i.uniforms.viewTransform=e,this.positionBuffer.bind(),i.attributes.position.pointer(),this.offsetBuffer.bind(),i.attributes.offset.pointer(),this.colorBuffer.bind(),i.attributes.color.pointer(o.UNSIGNED_BYTE,!0),o.drawArrays(o.TRIANGLES,0,a)}};var n=[0,0,0,0];p.drawPick=function(i){var a=this.plot,o=this.pickShader,s=this.numVertices,l=a.gl;if(this.pickOffset=i,!s)return i;for(var u=0;4>u;++u)n[u]=i>>8*u&255;return t.call(this),o.bind(),o.uniforms.pixelScale=r,o.uniforms.viewTransform=e,o.uniforms.pickOffset=n,this.positionBuffer.bind(),o.attributes.position.pointer(),this.offsetBuffer.bind(),o.attributes.offset.pointer(),this.idBuffer.bind(),o.attributes.id.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,s),i+this.numPoints}}(),p.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},p.update=function(t){t=t||{};var e=t.positions||[],r=t.colors||[],i=t.glyphs||[],a=t.sizes||[],o=t.borderWidths||[],s=t.borderColors||[];this.points=e;for(var c=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=0,h=0;h>1;for(var p=0;2>p;++p)c[p]=Math.min(c[p],e[2*h+p]),c[2+p]=Math.max(c[2+p],e[2*h+p])}c[0]===c[2]&&(c[2]+=1),c[3]===c[1]&&(c[3]+=1);for(var d=1/(c[2]-c[0]),g=1/(c[3]-c[1]),v=c[0],m=c[1],y=u.mallocFloat32(2*f),b=u.mallocFloat32(2*f),x=u.mallocUint8(4*f),_=u.mallocUint32(f),w=0,h=0;h=a?i(0,a-1,t,e,r,n):f(0,a-1,t,e,r,n)}function i(t,e,r,n,i,a){for(var o=t+1;e>=o;++o){for(var s=r[o],l=n[2*o],u=n[2*o+1],c=i[o],f=a[o],h=o;h>t;){var p=r[h-1],d=n[2*(h-1)];if((p-s||l-d)>=0)break;r[h]=p,n[2*h]=d,n[2*h+1]=n[2*h-1],i[h]=i[h-1],a[h]=a[h-1],h-=1}r[h]=s,n[2*h]=l,n[2*h+1]=u,i[h]=c,a[h]=f}}function a(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],u=i[t],c=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=u,a[e]=c}function o(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function s(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],u=i[2*t+1],c=a[t],f=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=u,a[r]=c,o[r]=f}function l(t,e,r,n,i,a,o,s,l,u,c){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],u[t]=u[e],c[t]=c[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,u[e]=a,c[e]=o}function u(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function c(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}function f(t,e,r,n,p,d){var g=(e-t+1)/6|0,v=t+g,m=e-g,y=t+e>>1,b=y-g,x=y+g,_=v,w=b,k=y,A=x,M=m,T=t+1,E=e-1,L=0;u(_,w,r,n,p,d)&&(L=_,_=w,w=L),u(A,M,r,n,p,d)&&(L=A,A=M,M=L),u(_,k,r,n,p,d)&&(L=_,_=k,k=L),u(w,k,r,n,p,d)&&(L=w,w=k,k=L),u(_,A,r,n,p,d)&&(L=_,_=A,A=L),u(k,A,r,n,p,d)&&(L=k,k=A,A=L),u(w,M,r,n,p,d)&&(L=w,w=M,M=L),u(w,k,r,n,p,d)&&(L=w,w=k,k=L),u(A,M,r,n,p,d)&&(L=A,A=M,M=L);var S=r[w],C=n[2*w],z=n[2*w+1],P=p[w],R=d[w],j=r[A],O=n[2*A],I=n[2*A+1],N=p[A],F=d[A],D=_,B=k,U=M,V=v,q=y,G=m,H=r[D],Y=r[B],X=r[U];r[V]=H,r[q]=Y,r[G]=X;for(var W=0;2>W;++W){var Z=n[2*D+W],K=n[2*B+W],$=n[2*U+W];n[2*V+W]=Z,n[2*q+W]=K,n[2*G+W]=$}var Q=p[D],J=p[B],tt=p[U];p[V]=Q,p[q]=J,p[G]=tt;var et=d[D],rt=d[B],nt=d[U];d[V]=et,d[q]=rt,d[G]=nt,o(b,t,r,n,p,d),o(x,e,r,n,p,d);for(var it=T;E>=it;++it)if(c(it,S,C,z,P,r,n,p))it!==T&&a(it,T,r,n,p,d),++T;else if(!c(it,j,O,I,N,r,n,p))for(;;){if(c(E,j,O,I,N,r,n,p)){c(E,S,C,z,P,r,n,p)?(s(it,T,E,r,n,p,d),++T,--E):(a(it,E,r,n,p,d),--E);break}if(--E=T-2-t?i(t,T-2,r,n,p,d):f(t,T-2,r,n,p,d),h>=e-(E+2)?i(E+2,e,r,n,p,d):f(E+2,e,r,n,p,d),h>=E-T?i(T,E,r,n,p,d):f(T,E,r,n,p,d)}e.exports=n;var h=32},{}],777:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s){for(var l=r,u=r;n>u;++u){var c=t[2*u],f=t[2*u+1],h=e[u];c>=i&&o>=c&&f>=a&&s>=f&&(u===l?l+=1:(t[2*u]=t[2*l],t[2*u+1]=t[2*l+1],e[u]=e[l],t[2*l]=c,t[2*l+1]=f,e[l]=h,l+=1))}return l}function i(t,e,r){this.pixelSize=t,this.offset=e,this.count=r}function a(t,e,r,a){function l(i,a,o,s,u,c){var f=.5*o,h=s+1,p=u-s;r[_]=p,x[_++]=c;for(var d=0;2>d;++d)for(var g=0;2>g;++g){var v=i+d*f,m=a+g*f,y=n(t,e,h,u,v,m,v+f,m+f);if(y!==h){if(y-h>=Math.max(.9*p,32)){var b=u+s>>>1;l(v,m,f,h,b,c+1),h=b}l(v,m,f,h,y,c+1),h=y}}}var u=t.length>>>1;if(1>u)return[];for(var c=1/0,f=1/0,h=-(1/0),p=-(1/0),d=0;u>d;++d){var g=t[2*d],v=t[2*d+1];c=Math.min(c,g),h=Math.max(h,g),f=Math.min(f,v),p=Math.max(p,v),e[d]=d}c===h&&(h+=1+Math.abs(h)),f===p&&(p+=1+Math.abs(h));var m=1/(h-c),y=1/(p-f),b=Math.max(h-c,p-f);a=a||[0,0,0,0],a[0]=c,a[1]=f,a[2]=h,a[3]=p;var x=o.mallocInt32(u),_=0;l(c,f,b,0,u,0),s(x,t,e,r,u);for(var w=[],k=0,A=u,_=u-1;_>=0;--_){t[2*_]=(t[2*_]-c)*m,t[2*_+1]=(t[2*_+1]-f)*y;var M=x[_];M!==k&&(w.push(new i(b*Math.pow(.5,M),_+1,A-(_+1))),A=_+1,k=M)}return w.push(new i(b*Math.pow(.5,M+1),0,A)),o.free(x),w}var o=t("typedarray-pool"),s=t("./lib/sort");e.exports=a},{"./lib/sort":776,"typedarray-pool":780}],778:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],779:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],780:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":778,buffer:65,dup:122}],781:[function(t,e,r){"use strict"; +function n(t,e,r,n,i,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.weightBuffer=n,this.shader=i,this.pickShader=a,this.scales=[],this.size=12,this.borderSize=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.pickOffset=0,this.points=null,this.xCoords=null}function i(t,e){var r=t.gl,i=o(r),s=o(r),l=o(r),u=a(r,c.pointVertex,c.pointFragment),f=a(r,c.pickVertex,c.pickFragment),h=new n(t,i,s,l,u,f);return h.update(e),t.addObject(h),h}var a=t("gl-shader"),o=t("gl-buffer"),s=t("binary-search-bounds"),l=t("snap-points-2d"),u=t("typedarray-pool"),c=t("./lib/shader");e.exports=i;var f=n.prototype;f.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.xCoords&&u.free(this.xCoords),this.plot.removeObject(this)},f.update=function(t){function e(e,r){return e in t?t[e]:r}t=t||{},this.size=e("size",12),this.color=e("color",[1,0,0,1]).slice(),this.borderSize=e("borderSize",1),this.borderColor=e("borderColor",[0,0,0,1]).slice(),this.xCoords&&u.free(this.xCoords);var r=t.positions,n=u.mallocFloat32(r.length),i=u.mallocInt32(r.length>>>1);n.set(r);var a=u.mallocFloat32(r.length);this.points=r,this.scales=l(n,i,a,this.bounds),this.offsetBuffer.update(n),this.pickBuffer.update(i),this.weightBuffer.update(a);for(var o=u.mallocFloat32(r.length>>>1),s=0,c=0;s>>1,this.pickOffset=0},f.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.scales,o=this.offsetBuffer,l=this.pickBuffer,u=this.bounds,c=this.size,f=this.borderSize,h=n.gl,p=n.pickPixelRatio,d=n.viewBox,g=n.dataBox;if(0===this.pointCount)return r;var v=u[2]-u[0],m=u[3]-u[1],y=g[2]-g[0],b=g[3]-g[1],x=(d[2]-d[0])*p/n.pixelRatio,_=(d[3]-d[1])*p/n.pixelRatio,w=Math.min(y/x,b/_);t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(u[0]-g[0])/y-1,t[7]=2*(u[1]-g[1])/b-1,this.pickOffset=r,e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,i.bind(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointSize=p*(c+f),i.uniforms.pickOffset=e,0===this.borderSize?i.uniforms.centerFraction=2:i.uniforms.centerFraction=c/(c+f+1.25),o.bind(),i.attributes.position.pointer(),l.bind(),i.attributes.pickId.pointer(h.UNSIGNED_BYTE);for(var k=this.xCoords,A=(g[0]-u[0]-w*c*p)/v,M=(g[2]-u[0]+w*c*p)/v,T=a.length-1;T>=0;--T){var E=a[T];if(!(E.pixelSize1)){var L=E.offset,S=E.count+L,C=s.ge(k,A,L,S-1),z=s.lt(k,M,C,S-1)+1;z>C&&h.drawArrays(h.POINTS,C,z-C)}}return r+this.pointCount}}(),f.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.scales,i=this.offsetBuffer,a=this.bounds,o=this.size,l=this.borderSize,u=e.gl,c=e.pixelRatio,f=e.viewBox,h=e.dataBox;if(0!==this.pointCount){var p=a[2]-a[0],d=a[3]-a[1],g=h[2]-h[0],v=h[3]-h[1],m=f[2]-f[0],y=f[3]-f[1],b=Math.min(g/m,v/y);t[0]=2*p/g,t[4]=2*d/v,t[6]=2*(a[0]-h[0])/g-1,t[7]=2*(a[1]-h[1])/v-1,r.bind(),r.uniforms.matrix=t,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointSize=c*(o+l),r.uniforms.useWeight=1,0===this.borderSize?r.uniforms.centerFraction=2:r.uniforms.centerFraction=o/(o+l+1.25),i.bind(),r.attributes.position.pointer(),this.weightBuffer.bind(),r.attributes.weight.pointer();for(var x=this.xCoords,_=(h[0]-a[0]-b*o*c)/p,w=(h[2]-a[0]+b*o*c)/p,k=!0,A=n.length-1;A>=0;--A){var M=n[A];if(!(M.pixelSize1)){var T=M.offset,E=M.count+T,L=s.ge(x,_,T,E-1),S=s.lt(x,w,L,E-1)+1;S>L&&u.drawArrays(u.POINTS,L,S-L),k&&(k=!1,r.uniforms.useWeight=0)}}}}}(),f.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":747,"binary-search-bounds":748,"gl-buffer":749,"gl-shader":750,"snap-points-2d":777,"typedarray-pool":780}],782:[function(t,e,r){"use strict";function n(t,e){var r=a[e];if(r||(r=a[e]={}),t in r)return r[t];for(var n=i(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),o=i(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),s=[[1/0,1/0],[-(1/0),-(1/0)]],l=0;lc;++c)s[0][c]=Math.min(s[0][c],u[c]),s[1][c]=Math.max(s[1][c],u[c]);return r[t]=[o,n,s]}var i=t("vectorize-text");e.exports=n;var a={}},{"vectorize-text":818}],783:[function(t,e,r){function n(t,e){var r=i(t,e),n=r.attributes;return n.position.location=0,n.color.location=1,n.glyph.location=2,n.id.location=3,r}var i=t("gl-shader"),a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n \n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n \n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * view * model * vec4(position, 1);\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n",u="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}",c=[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"glyph",type:"vec2"},{name:"id",type:"vec4"}],f={vertex:a,fragment:l,attributes:c},h={vertex:o,fragment:l,attributes:c},p={vertex:s,fragment:l,attributes:c},d={vertex:a,fragment:u,attributes:c},g={vertex:o,fragment:u,attributes:c},v={vertex:s,fragment:u,attributes:c};r.createPerspective=function(t){return n(t,f)},r.createOrtho=function(t){return n(t,h)},r.createProject=function(t){return n(t,p)},r.createPickPerspective=function(t){return n(t,d)},r.createPickOrtho=function(t){return n(t,g)},r.createPickProject=function(t){return n(t,v)}},{"gl-shader":785}],784:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":817}],785:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":786,"./lib/create-attributes":787,"./lib/create-uniforms":788,"./lib/reflect":789,"./lib/runtime-reflect":790,"./lib/shader-cache":791,dup:94}],786:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],787:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":786,dup:96}],788:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":786,"./reflect":789,dup:97}],789:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],790:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],791:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":786,dup:100,"gl-format-compiler-error":792,"weakmap-shim":810}],792:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":793,dup:101,"gl-constants/lookup":797,"glsl-shader-name":798,"sprintf-js":807}],793:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":794}],794:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":795}],795:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],796:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],797:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":796,dup:106}],798:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":799,dup:107,"glsl-tokenizer":806}],799:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],800:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":802,"./lib/builtins-300es":801,"./lib/literals":804,"./lib/literals-300es":803,"./lib/operators":805,dup:109}],801:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":802,dup:110}],802:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],803:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":804,dup:112}],804:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],805:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],806:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":800,dup:115}],807:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],808:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":809,dup:117}],809:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],810:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":808,dup:119}],811:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],812:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":811,dup:155}],813:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":811,dup:156}],814:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":812,"./lib/vao-native.js":813,dup:157}],815:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],816:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],817:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":815,buffer:65,dup:122}],818:[function(t,e,r){arguments[4][354][0].apply(r,arguments)},{"./lib/vtext":819,dup:354}],819:[function(t,e,r){arguments[4][355][0].apply(r,arguments)},{cdt2d:820,"clean-pslg":832,dup:355,ndarray:1031,"planar-graph-to-polyline":887,"simplify-planar-graph":891,"surface-nets":904}],820:[function(t,e,r){arguments[4][356][0].apply(r,arguments)},{"./lib/delaunay":821,"./lib/filter":822,"./lib/monotone":823,"./lib/triangulation":824,dup:356}],821:[function(t,e,r){arguments[4][357][0].apply(r,arguments)},{"binary-search-bounds":825,dup:357,"robust-in-sphere":826}],822:[function(t,e,r){arguments[4][358][0].apply(r,arguments)},{"binary-search-bounds":825,dup:358}],823:[function(t,e,r){arguments[4][359][0].apply(r,arguments)},{"binary-search-bounds":825,dup:359,"robust-orientation":1040}],824:[function(t,e,r){arguments[4][360][0].apply(r,arguments)},{"binary-search-bounds":825,dup:360}],825:[function(t,e,r){arguments[4][312][0].apply(r,arguments)},{dup:312}],826:[function(t,e,r){arguments[4][361][0].apply(r,arguments)},{dup:361,"robust-scale":828,"robust-subtract":829,"robust-sum":830,"two-product":831}],827:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],828:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":831,"two-sum":827}],829:[function(t,e,r){arguments[4][364][0].apply(r,arguments)},{dup:364}],830:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],831:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],832:[function(t,e,r){arguments[4][367][0].apply(r,arguments)},{"./lib/rat-seg-intersect":833,"big-rat":837,"big-rat/cmp":835,"big-rat/to-float":852,"box-intersect":853,"compare-cell":861,dup:367,nextafter:862,"rat-vec":865,"robust-segment-intersect":868,"union-find":869}],833:[function(t,e,r){arguments[4][368][0].apply(r,arguments)},{"big-rat/div":836,"big-rat/mul":846,"big-rat/sign":850,"big-rat/sub":851,"big-rat/to-float":852,dup:368,"rat-vec/add":864,"rat-vec/muls":866,"rat-vec/sub":867}],834:[function(t,e,r){arguments[4][369][0].apply(r,arguments)},{"./lib/rationalize":844,dup:369}],835:[function(t,e,r){arguments[4][370][0].apply(r,arguments)},{dup:370}],836:[function(t,e,r){arguments[4][371][0].apply(r,arguments)},{"./lib/rationalize":844,dup:371}],837:[function(t,e,r){arguments[4][372][0].apply(r,arguments)},{"./div":836,"./is-rat":838,"./lib/is-bn":842,"./lib/num-to-bn":843,"./lib/rationalize":844,"./lib/str-to-bn":845,dup:372}],838:[function(t,e,r){arguments[4][373][0].apply(r,arguments)},{"./lib/is-bn":842,dup:373}],839:[function(t,e,r){arguments[4][374][0].apply(r,arguments)},{"bn.js":848,dup:374}],840:[function(t,e,r){arguments[4][375][0].apply(r,arguments)},{dup:375}],841:[function(t,e,r){arguments[4][376][0].apply(r,arguments)},{"bit-twiddle":847,"double-bits":849,dup:376}],842:[function(t,e,r){arguments[4][377][0].apply(r,arguments)},{"bn.js":848,dup:377}],843:[function(t,e,r){arguments[4][378][0].apply(r,arguments)},{"bn.js":848,"double-bits":849,dup:378}],844:[function(t,e,r){arguments[4][379][0].apply(r,arguments)},{"./bn-sign":839,"./num-to-bn":843,dup:379}],845:[function(t,e,r){arguments[4][380][0].apply(r,arguments)},{"bn.js":848,dup:380}],846:[function(t,e,r){arguments[4][381][0].apply(r,arguments)},{"./lib/rationalize":844,dup:381}],847:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],848:[function(t,e,r){arguments[4][383][0].apply(r,arguments)},{dup:383}],849:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],850:[function(t,e,r){arguments[4][385][0].apply(r,arguments)},{"./lib/bn-sign":839,dup:385}],851:[function(t,e,r){arguments[4][386][0].apply(r,arguments)},{"./lib/rationalize":844,dup:386}],852:[function(t,e,r){arguments[4][387][0].apply(r,arguments)},{"./lib/bn-to-num":840,"./lib/ctz":841,dup:387}],853:[function(t,e,r){arguments[4][388][0].apply(r,arguments)},{"./lib/intersect":855,"./lib/sweep":859,dup:388,"typedarray-pool":817}],854:[function(t,e,r){arguments[4][389][0].apply(r,arguments)},{dup:389}],855:[function(t,e,r){arguments[4][390][0].apply(r,arguments)},{"./brute":854,"./median":856,"./partition":857,"./sweep":859,"bit-twiddle":860,dup:390,"typedarray-pool":817}],856:[function(t,e,r){arguments[4][391][0].apply(r,arguments)},{"./partition":857,dup:391}],857:[function(t,e,r){arguments[4][392][0].apply(r,arguments)},{dup:392}],858:[function(t,e,r){arguments[4][393][0].apply(r,arguments)},{dup:393}],859:[function(t,e,r){arguments[4][394][0].apply(r,arguments)},{"./sort":858,"bit-twiddle":860,dup:394,"typedarray-pool":817}],860:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],861:[function(t,e,r){arguments[4][61][0].apply(r,arguments)},{dup:61}],862:[function(t,e,r){arguments[4][399][0].apply(r,arguments)},{"double-bits":863,dup:399}],863:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],864:[function(t,e,r){arguments[4][401][0].apply(r,arguments)},{"big-rat/add":834,dup:401}],865:[function(t,e,r){arguments[4][402][0].apply(r,arguments)},{"big-rat":837,dup:402}],866:[function(t,e,r){arguments[4][403][0].apply(r,arguments)},{"big-rat":837,"big-rat/mul":846,dup:403}],867:[function(t,e,r){arguments[4][404][0].apply(r,arguments)},{"big-rat/sub":851,dup:404}],868:[function(t,e,r){arguments[4][405][0].apply(r,arguments)},{dup:405,"robust-orientation":1040}],869:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],870:[function(t,e,r){arguments[4][407][0].apply(r,arguments)},{dup:407,"edges-to-adjacency-list":871}],871:[function(t,e,r){arguments[4][408][0].apply(r,arguments)},{dup:408,uniq:886}],872:[function(t,e,r){arguments[4][409][0].apply(r,arguments)},{"compare-angle":873,dup:409}],873:[function(t,e,r){arguments[4][410][0].apply(r,arguments)},{dup:410,"robust-orientation":1040,"robust-product":875,"robust-sum":884,signum:876,"two-sum":877}],874:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":885,"two-sum":877}],875:[function(t,e,r){arguments[4][412][0].apply(r,arguments)},{dup:412,"robust-scale":874,"robust-sum":884}],876:[function(t,e,r){arguments[4][413][0].apply(r,arguments)},{dup:413}],877:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],878:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],879:[function(t,e,r){arguments[4][416][0].apply(r,arguments)},{"binary-search-bounds":878,dup:416}],880:[function(t,e,r){arguments[4][417][0].apply(r,arguments)},{dup:417,"robust-orientation":1040}],881:[function(t,e,r){arguments[4][418][0].apply(r,arguments)},{dup:418}],882:[function(t,e,r){arguments[4][419][0].apply(r,arguments)},{"./lib/order-segments":880,"binary-search-bounds":878,dup:419,"functional-red-black-tree":881,"robust-orientation":1040}],883:[function(t,e,r){arguments[4][420][0].apply(r,arguments)},{"binary-search-bounds":878,dup:420,"interval-tree-1d":879,"robust-orientation":1040,"slab-decomposition":882}],884:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],885:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],886:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],887:[function(t,e,r){arguments[4][424][0].apply(r,arguments)},{"./lib/trim-leaves":870,dup:424,"edges-to-adjacency-list":871,"planar-dual":872,"point-in-big-polygon":883,"robust-sum":884,"two-product":885,uniq:886}],888:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],889:[function(t,e,r){arguments[4][426][0].apply(r,arguments)},{dup:426}],890:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":888,dup:79,"union-find":889}],891:[function(t,e,r){arguments[4][428][0].apply(r,arguments)},{dup:428,"robust-orientation":1040,"simplicial-complex":890}],892:[function(t,e,r){arguments[4][429][0].apply(r,arguments)},{dup:429,"typedarray-pool":817}],893:[function(t,e,r){arguments[4][433][0].apply(r,arguments)},{dup:433}],894:[function(t,e,r){arguments[4][437][0].apply(r,arguments)},{dup:437,"typedarray-pool":817}],895:[function(t,e,r){arguments[4][438][0].apply(r,arguments)},{dup:438,"invert-permutation":896,"typedarray-pool":817}],896:[function(t,e,r){arguments[4][439][0].apply(r,arguments)},{dup:439}],897:[function(t,e,r){arguments[4][443][0].apply(r,arguments)},{dup:443,gamma:893,"permutation-parity":894,"permutation-rank":895}],898:[function(t,e,r){arguments[4][444][0].apply(r,arguments)},{"cwise-compiler":899,dup:444}],899:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":901,dup:319}],900:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:902}],901:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":900,dup:321}],902:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],903:[function(t,e,r){arguments[4][449][0].apply(r,arguments)},{"./lib/zc-core":898,dup:449}],904:[function(t,e,r){arguments[4][450][0].apply(r,arguments)},{dup:450,"ndarray-extract-contour":892,"triangulate-hypercube":897,"zero-crossings":903}],905:[function(t,e,r){"use strict";function n(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];return t[0]=e[0]*r+e[4]*n+e[8]*i+e[12]*a,t[1]=e[1]*r+e[5]*n+e[9]*i+e[13]*a,t[2]=e[2]*r+e[6]*n+e[10]*i+e[14]*a,t[3]=e[3]*r+e[7]*n+e[11]*i+e[15]*a,t}function i(t,e,r,i){return n(i,i,r),n(i,i,e),n(i,i,t)}function a(t,e){this.index=t,this.dataCoordinate=this.position=e}function o(t,e,r,n,i,o,s,l,u,c,f,h){this.gl=t,this.pixelRatio=1,this.shader=e,this.orthoShader=r,this.projectShader=n,this.pointBuffer=i,this.colorBuffer=o,this.glyphBuffer=s,this.idBuffer=l,this.vao=u,this.vertexCount=0,this.lineVertexCount=0,this.opacity=1,this.lineWidth=0,this.projectScale=[2/3,2/3,2/3],this.projectOpacity=[1,1,1],this.pickId=0,this.pickPerspectiveShader=c,this.pickOrthoShader=f,this.pickProjectShader=h,this.points=[],this._selectResult=new a(0,[0,0,0]),this.useOrtho=!0,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.axesProject=[!0,!0,!0],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.highlightId=[1,1,1,1],this.highlightScale=2,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.dirty=!0}function s(t){return t[0]=t[1]=t[2]=0,t}function l(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function u(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function c(t){for(var e=S,r=0;2>r;++r)for(var n=0;3>n;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}function f(t,e,r,n,a){var o,f=e.axesProject,h=e.gl,p=t.uniforms,d=r.model||x,g=r.view||x,v=r.projection||x,y=e.axesBounds,b=c(e.clipBounds);o=e.axes?e.axes.lastCubeProps.axis:[1,1,1],w[0]=2/h.drawingBufferWidth,w[1]=2/h.drawingBufferHeight,t.bind(),p.view=g,p.projection=v,p.screenSize=w,p.highlightId=e.highlightId,p.highlightScale=e.highlightScale,p.clipBounds=b,p.pickGroup=e.pickId/255,p.pixelRatio=e.pixelRatio;for(var _=0;3>_;++_)if(f[_]&&e.projectOpacity[_]<1===n){p.scale=e.projectScale[_],p.opacity=e.projectOpacity[_];for(var S=E,C=0;16>C;++C)S[C]=0;for(var C=0;4>C;++C)S[5*C]=1;S[5*_]=0,o[_]<0?S[12+_]=y[0][_]:S[12+_]=y[1][_],m(S,d,S),p.model=S;var z=(_+1)%3,P=(_+2)%3,R=s(k),j=s(A);R[z]=1,j[P]=1;var O=i(v,g,d,l(M,R)),I=i(v,g,d,l(T,j));if(Math.abs(O[1])>Math.abs(I[1])){var N=O;O=I,I=N,N=R,R=j,j=N;var F=z;z=P,P=F}O[0]<0&&(R[z]=-1),I[1]>0&&(j[P]=-1);for(var D=0,B=0,C=0;4>C;++C)D+=Math.pow(d[4*z+C],2),B+=Math.pow(d[4*P+C],2);R[z]/=Math.sqrt(D),j[P]/=Math.sqrt(B),p.axes[0]=R,p.axes[1]=j,p.fragClipBounds[0]=u(L,b[0],_,-1e8),p.fragClipBounds[1]=u(L,b[1],_,1e8),e.vao.draw(h.TRIANGLES,e.vertexCount),e.lineWidth>0&&(h.lineWidth(e.lineWidth),e.vao.draw(h.LINES,e.lineVertexCount,e.vertexCount))}}function h(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||x,s.view=n.view||x,s.projection=n.projection||x,w[0]=2/o.drawingBufferWidth,w[1]=2/o.drawingBufferHeight,s.screenSize=w,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=P,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}f(e,r,n,i,a),r.vao.unbind()}function p(t){var e=t.gl,r=y.createPerspective(e),n=y.createOrtho(e),i=y.createProject(e),a=y.createPickPerspective(e),s=y.createPickOrtho(e),l=y.createPickProject(e),u=d(e),c=d(e),f=d(e),h=d(e),p=g(e,[{buffer:u,size:3,type:e.FLOAT},{buffer:c,size:4,type:e.FLOAT},{buffer:f,size:2,type:e.FLOAT},{buffer:h,size:4,type:e.UNSIGNED_BYTE,normalized:!0}]),v=new o(e,r,n,i,u,c,f,h,p,a,s,l);return v.update(t),v}var d=t("gl-buffer"),g=t("gl-vao"),v=t("typedarray-pool"),m=t("gl-mat4/multiply"),y=t("./lib/shaders"),b=t("./lib/glyphs"),x=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];e.exports=p;var _=o.prototype;_.pickSlots=1,_.setPickBase=function(t){this.pickId=t},_.isTransparent=function(){if(this.opacity<1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]<1)return!0;return!1},_.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var w=[0,0],k=[0,0,0],A=[0,0,0],M=[0,0,0,1],T=[0,0,0,1],E=x.slice(),L=[0,0,0],S=[[0,0,0],[0,0,0]],C=[-1e8,-1e8,-1e8],z=[1e8,1e8,1e8],P=[C,z];_.draw=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!1,!1)},_.drawTransparent=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!0,!1)},_.drawPick=function(t){var e=this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader;h(e,this.pickProjectShader,this,t,!1,!0)},_.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||0>e)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;3>i;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},_.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},_.update=function(t){if(t=t||{},"perspective"in t&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{var r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-(1/0),-(1/0),-(1/0)],l=t.glyph,u=t.color,c=t.size,f=t.angle,h=t.lineColor,p=0,d=0,g=0,m=n.length;t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_)if(isNaN(x[_])||!isFinite(x[_]))continue t;var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];d+=3*k.cells.length,g+=2*A.edges.length}var T=d+g,E=v.mallocFloat(3*T),L=v.mallocFloat(4*T),S=v.mallocFloat(2*T),C=v.mallocUint32(T),z=[0,a[1]],P=0,R=d,j=[0,0,0,1],O=[0,0,0,1],I=Array.isArray(u)&&Array.isArray(u[0]),N=Array.isArray(h)&&Array.isArray(h[0]);t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_){if(isNaN(x[_])||!isFinite(x[_])){p+=1;continue t}s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_])}var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];if(Array.isArray(u)){var F;if(F=I?u[y]:u,3===F.length){for(var _=0;3>_;++_)j[_]=F[_];j[3]=1}else if(4===F.length)for(var _=0;4>_;++_)j[_]=F[_]}else j[0]=j[1]=j[2]=0,j[3]=1;if(Array.isArray(h)){var F;if(F=N?h[y]:h,3===F.length){for(var _=0;3>_;++_)O[_]=F[_];O[_]=1}else if(4===F.length)for(var _=0;4>_;++_)O[_]=F[_]}else O[0]=O[1]=O[2]=0,O[3]=1;var D=.5;Array.isArray(c)?D=+c[y]:c?D=+c:this.useOrtho&&(D=12);var B=0;Array.isArray(f)?B=+f[y]:f&&(B=+f);for(var U=Math.cos(B),V=Math.sin(B),x=n[y],_=0;3>_;++_)s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_]);a[0]<0?z[0]=a[0]*(1+M[1][0]):a[0]>0&&(z[0]=-a[0]*(1+M[0][0]));for(var q=k.cells,G=k.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*P+X]=x[X];for(var X=0;4>X;++X)L[4*P+X]=j[X];C[P]=p;var W=G[H[Y]];S[2*P]=D*(U*W[0]-V*W[1]+z[0]),S[2*P+1]=D*(V*W[0]+U*W[1]+z[1]),P+=1}for(var q=A.edges,G=A.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*R+X]=x[X];for(var X=0;4>X;++X)L[4*R+X]=O[X];C[R]=p;var W=G[H[Y]];S[2*R]=D*(U*W[0]-V*W[1]+z[0]),S[2*R+1]=D*(V*W[0]+U*W[1]+z[1]),R+=1}p+=1}this.vertexCount=d,this.lineVertexCount=g,this.pointBuffer.update(E),this.colorBuffer.update(L),this.glyphBuffer.update(S),this.idBuffer.update(new Uint32Array(C)),v.free(E),v.free(L),v.free(S),v.free(C),this.bounds=[o,s],this.points=n,this.pointCount=n.length}},_.dispose=function(){this.shader.dispose(),this.orthoShader.dispose(),this.pickPerspectiveShader.dispose(),this.pickOrthoShader.dispose(),this.vao.dispose(),this.pointBuffer.dispose(),this.colorBuffer.dispose(),this.glyphBuffer.dispose(),this.idBuffer.dispose()}},{"./lib/glyphs":782,"./lib/shaders":783,"gl-buffer":784,"gl-mat4/multiply":242,"gl-vao":814,"typedarray-pool":817}],906:[function(t,e,r){"use strict";r.boxVertex="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n",r.boxFragment="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n"},{}],907:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":910}],908:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],909:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],910:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":908,buffer:65,dup:122}],911:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":912,"./lib/create-attributes":913,"./lib/create-uniforms":914,"./lib/reflect":915,"./lib/runtime-reflect":916,"./lib/shader-cache":917,dup:94}],912:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],913:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":912,dup:96}],914:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":912,"./reflect":915,dup:97}],915:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],916:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],917:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":912,dup:100,"gl-format-compiler-error":918,"weakmap-shim":936}],918:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":919,dup:101,"gl-constants/lookup":923,"glsl-shader-name":924,"sprintf-js":933}],919:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":920}],920:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":921}],921:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],922:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],923:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":922,dup:106}],924:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":925,dup:107,"glsl-tokenizer":932}],925:[function(t,e,r){arguments[4][108][0].apply(r,arguments); +},{dup:108}],926:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":928,"./lib/builtins-300es":927,"./lib/literals":930,"./lib/literals-300es":929,"./lib/operators":931,dup:109}],927:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":928,dup:110}],928:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],929:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":930,dup:112}],930:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],931:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],932:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":926,dup:115}],933:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],934:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":935,dup:117}],935:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],936:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":934,dup:119}],937:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.boxBuffer=e,this.boxShader=r,this.enabled=!0,this.selectBox=[1/0,1/0,-(1/0),-(1/0)],this.borderColor=[0,0,0,1],this.innerFill=!1,this.innerColor=[0,0,0,.25],this.outerFill=!0,this.outerColor=[0,0,0,.5],this.borderWidth=10}function i(t,e){var r=t.gl,i=o(r,[0,0,0,1,1,0,1,1]),l=a(r,s.boxVertex,s.boxFragment),u=new n(t,i,l);return u.update(e),t.addOverlay(u),u}var a=t("gl-shader"),o=t("gl-buffer"),s=t("./lib/shaders");e.exports=i;var l=n.prototype;l.draw=function(){if(this.enabled){var t=this.plot,e=this.selectBox,r=this.borderWidth,n=(this.innerFill,this.innerColor),i=(this.outerFill,this.outerColor),a=this.borderColor,o=t.box,s=t.screenBox,l=t.dataBox,u=t.viewBox,c=t.pixelRatio,f=(e[0]-l[0])*(u[2]-u[0])/(l[2]-l[0])+u[0],h=(e[1]-l[1])*(u[3]-u[1])/(l[3]-l[1])+u[1],p=(e[2]-l[0])*(u[2]-u[0])/(l[2]-l[0])+u[0],d=(e[3]-l[1])*(u[3]-u[1])/(l[3]-l[1])+u[1];if(f=Math.max(f,u[0]),h=Math.max(h,u[1]),p=Math.min(p,u[2]),d=Math.min(d,u[3]),!(f>p||h>d)){o.bind();var g=s[2]-s[0],v=s[3]-s[1];if(this.outerFill&&(o.drawBox(0,0,g,h,i),o.drawBox(0,h,f,d,i),o.drawBox(0,d,g,v,i),o.drawBox(p,h,g,d,i)),this.innerFill&&o.drawBox(f,h,p,d,n),r>0){var m=r*c;o.drawBox(f-m,h-m,p+m,h+m,a),o.drawBox(f-m,d-m,p+m,d+m,a),o.drawBox(f-m,h-m,f+m,d+m,a),o.drawBox(p-m,h-m,p+m,d+m,a)}}}},l.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},l.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":906,"gl-buffer":907,"gl-shader":911}],938:[function(t,e,r){"use strict";function n(t){this.plot=t,this.enable=[!0,!0,!1,!1],this.width=[1,1,1,1],this.color=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.center=[1/0,1/0]}function i(t,e){var r=new n(t);return r.update(e),t.addOverlay(r),r}e.exports=i;var a=n.prototype;a.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},a.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),u=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,u,s[0],u,e[0],r[0]),t[1]&&a.drawLine(l,u,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,u,s[2],u,e[2],r[2]),t[3]&&a.drawLine(l,u,l,s[3],e[3],r[3])}},a.dispose=function(){this.plot.removeOverlay(this)}},{}],939:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n",s="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n";r.createShader=function(t){var e=n(t,i,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,i,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,o,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},r.createPickContourShader=function(t){var e=n(t,o,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e}},{"gl-shader":947}],940:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],941:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],942:[function(t,e,r){arguments[4][262][0].apply(r,arguments)},{dup:262}],943:[function(t,e,r){arguments[4][263][0].apply(r,arguments)},{"./colorScales":942,arraytools:64,clone:944,dup:263}],944:[function(t,e,r){arguments[4][264][0].apply(r,arguments)},{buffer:65,dup:264}],945:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],946:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":1002}],947:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":948,"./lib/create-attributes":949,"./lib/create-uniforms":950,"./lib/reflect":951,"./lib/runtime-reflect":952,"./lib/shader-cache":953,dup:94}],948:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],949:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":948,dup:96}],950:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":948,"./reflect":951,dup:97}],951:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],952:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],953:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":948,dup:100,"gl-format-compiler-error":954,"weakmap-shim":972}],954:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":955,dup:101,"gl-constants/lookup":959,"glsl-shader-name":960,"sprintf-js":969}],955:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":956}],956:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":957}],957:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],958:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],959:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":958,dup:106}],960:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":961,dup:107,"glsl-tokenizer":968}],961:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],962:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":964,"./lib/builtins-300es":963,"./lib/literals":966,"./lib/literals-300es":965,"./lib/operators":967,dup:109}],963:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":964,dup:110}],964:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],965:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":966,dup:112}],966:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],967:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],968:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":962,dup:115}],969:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],970:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":971,dup:117}],971:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],972:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":970,dup:119}],973:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":1002}],974:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],975:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":974,dup:155}],976:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":974,dup:156}],977:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":975,"./lib/vao-native.js":976,dup:157}],978:[function(t,e,r){"use strict";function n(t){if(t in l)return l[t];for(var e=[],r=0;t>r;++r)e.push("out",r,"s=0.5*(inp",r,"l-inp",r,"r);");for(var n=["array"],i=["junk"],r=0;t>r;++r){n.push("array"),i.push("out"+r+"s");var a=o(t);a[r]=-1,n.push({array:0,offset:a.slice()}),a[r]=1,n.push({array:0,offset:a.slice()}),i.push("inp"+r+"l","inp"+r+"r")}return l[t]=s({args:n,pre:c,post:c,body:{body:e.join(""),args:i.map(function(t){return{name:t,lvalue:0===t.indexOf("out"),rvalue:0===t.indexOf("inp"),count:"junk"!==t|0}}),thisVars:[],localVars:[]},funcName:"fdTemplate"+t})}function i(t){function e(e){for(var r=a-e.length,n=[],i=[],s=[],l=0;a>l;++l)e.indexOf(l+1)>=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),n.push("1"),i.push("s["+l+"]-2"));var u=".lo("+n.join()+").hi("+i.join()+")";if(0===n.length&&(u=""),r>0){o.push("if(1");for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push("&&s[",l,"]>2");o.push("){grad",r,"(src.pick(",s.join(),")",u);for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push(",dst.pick(",s.join(),",",l,")",u);o.push(");")}for(var l=0;l1){dst.set(",s.join(),",",c,",0.5*(src.get(",h.join(),")-src.get(",p.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):o.push("if(s[",c,"]>1){diff(",f,",src.pick(",h.join(),")",u,",src.pick(",p.join(),")",u,");}else{zero(",f,");};");break;case"mirror":0===r?o.push("dst.set(",s.join(),",",c,",0);"):o.push("zero(",f,");");break;case"wrap":var d=s.slice(),g=s.slice();e[l]<0?(d[c]="s["+c+"]-2",g[c]="0"):(d[c]="s["+c+"]-1",g[c]="1"),0===r?o.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",d.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):o.push("if(s[",c,"]>2){diff(",f,",src.pick(",d.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",f,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}r>0&&o.push("};")}var r=t.join(),i=u[r];if(i)return i;for(var a=t.length,o=["function gradient(dst,src){var s=src.shape.slice();"],s=0;1<
s;++s){for(var c=[],p=0;a>p;++p)s&1<=s;++s)v.push("grad"+s),m.push(n(s));v.push(o.join(""));var y=Function.apply(void 0,v),i=y.apply(void 0,m);return l[r]=i,i}function a(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r="string"==typeof r?o(e.dimension,r):o(e.dimension,"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;nr;++r)for(o=o||e.surfaceProject[r],n=0;3>n;++n)s=s||e.contourProject[r][n];for(r=0;3>r;++r){var l=D.projections[r];for(n=0;16>n;++n)l[n]=0;for(n=0;4>n;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],k(l,t.model,l);var u=D.clipBounds[r];for(i=0;2>i;++i)for(n=0;3>n;++n)u[i][n]=t.clipBounds[i][n];u[0][r]=-1e8,u[1][r]=1e8}return D.showSurface=o,D.showContour=s,D}function s(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=B;n.model=t.model||R,n.view=t.view||R,n.projection=t.projection||R,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=A(n.inverseModel,n.model);for(var i=0;2>i;++i)for(var a=n.clipBounds[i],s=0;3>s;++s)a[s]=Math.min(Math.max(this.clipBounds[i][s],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=V;var l=U;for(k(l,n.view,n.model),k(l,n.projection,l),A(l,l),i=0;3>i;++i)n.eyePosition[i]=l[12+i]/l[15];var u=l[15];for(i=0;3>i;++i)u+=this.lightPosition[i]*l[4*i+3];for(i=0;3>i;++i){var c=l[12+i];for(s=0;3>s;++s)c+=l[4*s+i]*this.lightPosition[s];n.lightPosition[i]=c/u}var f=o(n,this);if(f.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;3>i;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=f.projections[i],this._shader.uniforms.clipBounds=f.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(f.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var p=this._contourVAO;for(p.bind(),i=0;3>i;++i)for(h.uniforms.permutation=O[i],r.lineWidth(this.contourWidth[i]),s=0;si;++i)for(h.uniforms.model=f.projections[i],h.uniforms.clipBounds=f.clipBounds[i],s=0;3>s;++s)if(this.contourProject[i][s]){h.uniforms.permutation=O[s],r.lineWidth(this.contourWidth[s]);for(var d=0;di;++i)if(0!==this._dynamicCounts[i])for(h.uniforms.model=n.model,h.uniforms.clipBounds=n.clipBounds,h.uniforms.permutation=O[i],r.lineWidth(this.dynamicWidth[i]),h.uniforms.contourColor=this.dynamicColor[i],h.uniforms.contourTint=this.dynamicTint[i],h.uniforms.height=this.dynamicLevel[i],p.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]),s=0;3>s;++s)this.contourProject[s][i]&&(h.uniforms.model=f.projections[s],h.uniforms.clipBounds=f.clipBounds[s],p.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]));p.unbind()}}function l(t,e){var r=e.shape.slice(),n=t.shape.slice();b.assign(t.lo(1,1).hi(r[0],r[1]),e),b.assign(t.lo(1).hi(r[0],1),e.hi(r[0],1)),b.assign(t.lo(1,n[1]-1).hi(r[0],1),e.lo(0,r[1]-1).hi(r[0],1)),b.assign(t.lo(0,1).hi(1,r[1]),e.hi(1)),b.assign(t.lo(n[0]-1,1).hi(1,r[1]),e.lo(r[0]-1)),t.set(0,0,e.get(0,0)),t.set(0,n[1]-1,e.get(0,r[1]-1)),t.set(n[0]-1,0,e.get(r[0]-1,0)),t.set(n[0]-1,n[1]-1,e.get(r[0]-1,r[1]-1))}function u(t,e){return Array.isArray(t)?[e(t[0]),e(t[1]),e(t[2])]:[e(t),e(t),e(t)]}function c(t){return Array.isArray(t)?3===t.length?[t[0],t[1],t[2],1]:[t[0],t[1],t[2],t[3]]:[0,0,0,1]}function f(t){if(Array.isArray(t)){if(Array.isArray(t))return[c(t[0]),c(t[1]),c(t[2])];var e=c(t);return[e.slice(),e.slice(),e.slice()]}}function h(t){var e=t.gl,r=L(e),n=C(e),i=S(e),o=z(e),s=d(e),l=g(e,[{buffer:s,size:4,stride:P,offset:0},{buffer:s,size:3,stride:P,offset:16},{buffer:s,size:3,stride:P,offset:28}]),u=d(e),c=g(e,[{buffer:u,size:4,stride:20,offset:0},{buffer:u,size:1,stride:20,offset:16}]),f=d(e),h=g(e,[{buffer:f,size:2,type:e.FLOAT}]),p=v(e,1,I,e.RGBA,e.UNSIGNED_BYTE);p.minFilter=e.LINEAR,p.magFilter=e.LINEAR;var m=new a(e,[0,0],[[0,0,0],[0,0,0]],r,n,s,l,p,i,o,u,c,f,h),y={levels:[[],[],[]]};for(var b in t)y[b]=t[b];return y.colormap=y.colormap||"jet",m.update(y),m}e.exports=h;var p=t("bit-twiddle"),d=t("gl-buffer"),g=t("gl-vao"),v=t("gl-texture2d"),m=t("typedarray-pool"),y=t("colormap"),b=t("ndarray-ops"),x=t("ndarray-pack"),_=t("ndarray"),w=t("surface-nets"),k=t("gl-mat4/multiply"),A=t("gl-mat4/invert"),M=t("binary-search-bounds"),T=t("ndarray-gradient"),E=t("./lib/shaders"),L=E.createShader,S=E.createContourShader,C=E.createPickShader,z=E.createPickContourShader,P=40,R=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],j=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],O=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];!function(){for(var t=0;3>t;++t){var e=O[t],r=(t+1)%3,n=(t+2)%3;e[r+0]=1,e[n+3]=1,e[t+6]=1}}();var I=265,N=a.prototype;N.isTransparent=function(){return this.opacity<1},N.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},N.pickSlots=1,N.setPickBase=function(t){this.pickId=t};var F=[0,0,0],D={showSurface:!1,showContour:!1,projections:[R.slice(),R.slice(),R.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]},B={model:R,view:R,projection:R,inverseModel:R.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1},U=R.slice(),V=[1,0,0,0,1,0,0,0,1];N.draw=function(t){return s.call(this,t,!1)},N.drawTransparent=function(t){return s.call(this,t,!0)};var q={model:R,view:R,projection:R,inverseModel:R,clipBounds:[[0,0,0],[0,0,0]],height:0,shape:[0,0],pickId:0,lowerBound:[0,0,0],upperBound:[0,0,0],zOffset:0,permutation:[1,0,0,0,1,0,0,0,1],lightPosition:[0,0,0],eyePosition:[0,0,0]};N.drawPick=function(t){t=t||{};var e=this.gl;e.disable(e.CULL_FACE);var r=q;r.model=t.model||R,r.view=t.view||R,r.projection=t.projection||R,r.shape=this._field[2].shape,r.pickId=this.pickId/255,r.lowerBound=this.bounds[0],r.upperBound=this.bounds[1],r.permutation=V;for(var n=0;2>n;++n)for(var i=r.clipBounds[n],a=0;3>a;++a)i[a]=Math.min(Math.max(this.clipBounds[n][a],-1e8),1e8);var s=o(r,this);if(s.showSurface){for(this._pickShader.bind(),this._pickShader.uniforms=r,this._vao.bind(),this._vao.draw(e.TRIANGLES,this._vertexCount),n=0;3>n;++n)this.surfaceProject[n]&&(this._pickShader.uniforms.model=s.projections[n],this._pickShader.uniforms.clipBounds=s.clipBounds[n],this._vao.draw(e.TRIANGLES,this._vertexCount));this._vao.unbind()}if(s.showContour){var l=this._contourPickShader;l.bind(),l.uniforms=r;var u=this._contourVAO;for(u.bind(),a=0;3>a;++a)for(e.lineWidth(this.contourWidth[a]),l.uniforms.permutation=O[a],n=0;nn;++n)for(l.uniforms.model=s.projections[n],l.uniforms.clipBounds=s.clipBounds[n],a=0;3>a;++a)if(this.contourProject[n][a]){l.uniforms.permutation=O[a],e.lineWidth(this.contourWidth[a]);for(var c=0;c>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;2>c;++c)for(var f=c?a:1-a,h=0;2>h;++h)for(var p=h?l:1-l,d=i+c,g=s+h,v=f*p,m=0;3>m;++m)u[m]+=this._field[m].get(d,g)*v;for(var y=this._pickResult.level,b=0;3>b;++b)if(y[b]=M.le(this.contourLevels[b],u[b]),y[b]<0)this.contourLevels[b].length>0&&(y[b]=0);else if(y[b]Math.abs(_-u[b])&&(y[b]+=1)}for(r.index[0]=.5>a?i:i+1,r.index[1]=.5>l?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],m=0;3>m;++m)r.dataCoordinate[m]=this._field[m].get(r.index[0],r.index[1]);return r},N.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=u(t.contourWidth,Number)),"showContour"in t&&(this.showContour=u(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=u(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=f(t.contourColor)),"contourProject"in t&&(this.contourProject=u(t.contourProject,function(t){return u(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=f(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=u(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=u(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(m.freeFloat(this._field[2].data),this._field[2].data=m.mallocFloat(p.nextPow2(n))),this._field[2]=_(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),l(this._field[2],e),this.shape=e.shape.slice();for(var a=this.shape,o=0;2>o;++o)this._field[2].size>this._field[o].data.length&&(m.freeFloat(this._field[o].data),this._field[o].data=m.mallocFloat(this._field[2].size)),this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2]);if(t.coords){var s=t.coords;if(!Array.isArray(s)||3!==s.length)throw new Error("gl-surface: invalid coordinates for x/y"); +for(o=0;2>o;++o){var c=s[o];for(y=0;2>y;++y)if(c.shape[y]!==a[y])throw new Error("gl-surface: coords have incorrect shape");l(this._field[o],c)}}else if(t.ticks){var h=t.ticks;if(!Array.isArray(h)||2!==h.length)throw new Error("gl-surface: invalid ticks");for(o=0;2>o;++o){var d=h[o];if((Array.isArray(d)||d.length)&&(d=_(d)),d.shape[0]!==a[o])throw new Error("gl-surface: invalid tick length");var g=_(d.data,a);g.stride[o]=d.stride[0],g.stride[1^o]=0,l(this._field[o],g)}}else{for(o=0;2>o;++o){var v=[0,0];v[o]=1,this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2],v,0)}this._field[0].set(0,0,0);for(var y=0;yo;++o)T(x.pick(o),b[o],"mirror");var k=_(m.mallocFloat(3*b[2].size),[a[0]+2,a[1]+2,3]);for(o=0;oO?(O=Math.max(Math.abs(z),Math.abs(P),Math.abs(R)),1e-8>O?(R=1,P=z=0,O=1):O=1/O):O=1/Math.sqrt(O),k.set(o,y,0,z*O),k.set(o,y,1,P*O),k.set(o,y,2,R*O)}m.free(x.data);var I=[1/0,1/0,1/0],N=[-(1/0),-(1/0),-(1/0)],F=1/0,D=-(1/0),B=(a[0]-1)*(a[1]-1)*6,U=m.mallocFloat(p.nextPow2(10*B)),V=0,q=0;for(o=0;oG;++G)for(var H=0;2>H;++H)for(var Y=0;3>Y;++Y){var X=this._field[Y].get(1+o+G,1+y+H);if(isNaN(X)||!isFinite(X))continue t}for(Y=0;6>Y;++Y){var W=o+j[Y][0],Z=y+j[Y][1],K=this._field[0].get(W+1,Z+1),$=this._field[1].get(W+1,Z+1);X=this._field[2].get(W+1,Z+1);var Q=X;z=k.get(W+1,Z+1,0),P=k.get(W+1,Z+1,1),R=k.get(W+1,Z+1,2),t.intensity&&(Q=t.intensity.get(W,Z)),U[V++]=W,U[V++]=Z,U[V++]=K,U[V++]=$,U[V++]=X,U[V++]=0,U[V++]=Q,U[V++]=z,U[V++]=P,U[V++]=R,I[0]=Math.min(I[0],K),I[1]=Math.min(I[1],$),I[2]=Math.min(I[2],X),F=Math.min(F,Q),N[0]=Math.max(N[0],K),N[1]=Math.max(N[1],$),N[2]=Math.max(N[2],X),D=Math.max(D,Q),q+=1}}for(t.intensityBounds&&(F=+t.intensityBounds[0],D=+t.intensityBounds[1]),o=6;V>o;o+=10)U[o]=(U[o]-F)/(D-F);this._vertexCount=q,this._coordinateBuffer.update(U.subarray(0,V)),m.freeFloat(U),m.free(k.data),this.bounds=[I,N],this.intensity=t.intensity||this._field[2],this.intensityBounds[0]===F&&this.intensityBounds[1]===D||(r=!0),this.intensityBounds=[F,D]}if("levels"in t){var J=t.levels;for(J=Array.isArray(J[0])?J.slice():[[],[],J],o=0;3>o;++o)J[o]=J[o].slice(),J.sort(function(t,e){return t-e});t:for(o=0;3>o;++o){if(J[o].length!==this.contourLevels[o].length){r=!0;break}for(y=0;yet;++et){J=this.contourLevels[et];var rt=[],nt=[],it=[0,0,0];for(o=0;oY;++Y){var st=at.positions[ot[Y]],lt=st[0],ut=0|Math.floor(lt),ct=lt-ut,ft=st[1],ht=0|Math.floor(ft),pt=ft-ht,dt=!1;e:for(var gt=0;3>gt;++gt){it[gt]=0;var vt=(et+gt+1)%3;for(G=0;2>G;++G){var mt=G?ct:1-ct;for(W=0|Math.min(Math.max(ut+G,0),a[0]),H=0;2>H;++H){var yt=H?pt:1-pt;if(Z=0|Math.min(Math.max(ht+H,0),a[1]),X=2>gt?this._field[vt].get(W,Z):(this.intensity.get(W,Z)-this.intensityBounds[0])/(this.intensityBounds[1]-this.intensityBounds[0]),!isFinite(X)||isNaN(X)){dt=!0;break e}var bt=mt*yt;it[gt]+=bt*X}}}if(dt){if(Y>0){for(var xt=0;5>xt;++xt)tt.pop();q-=1}continue t}tt.push(it[0],it[1],st[0],st[1],it[2]),q+=1}}nt.push(q)}this._contourOffsets[et]=rt,this._contourCounts[et]=nt}var _t=m.mallocFloat(tt.length);for(o=0;ot;++t)m.freeFloat(this._field[t].data)},N.highlight=function(t){if(!t)return this._dynamicCounts=[0,0,0],this.dyanamicLevel=[NaN,NaN,NaN],void(this.highlightLevel=[-1,-1,-1]);for(var e=0;3>e;++e)this.enableHighlight[e]?this.highlightLevel[e]=t.level[e]:this.highlightLevel[e]=-1;var r;if(r=this.snapToData?t.dataCoordinate:t.position,this.enableDynamic[0]&&r[0]!==this.dynamicLevel[0]||this.enableDynamic[1]&&r[1]!==this.dynamicLevel[1]||this.enableDynamic[2]&&r[2]!==this.dynamicLevel[2]){for(var n=0,i=this.shape,a=m.mallocFloat(12*i[0]*i[1]),o=0;3>o;++o)if(this.enableDynamic[o]){this.dynamicLevel[o]=r[o];var s=(o+1)%3,l=(o+2)%3,u=this._field[o],c=this._field[s],f=this._field[l],h=(this.intensity,w(u,r[o])),p=h.cells,d=h.positions;for(this._dynamicOffsets[o]=n,e=0;ev;++v){var y=d[g[v]],b=+y[0],x=0|b,_=0|Math.min(x+1,i[0]),k=b-x,A=1-k,M=+y[1],T=0|M,E=0|Math.min(T+1,i[1]),L=M-T,S=1-L,C=A*S,z=A*L,P=k*S,R=k*L,j=C*c.get(x,T)+z*c.get(x,E)+P*c.get(_,T)+R*c.get(_,E),O=C*f.get(x,T)+z*f.get(x,E)+P*f.get(_,T)+R*f.get(_,E);if(isNaN(j)||isNaN(O)){v&&(n-=1);break}a[2*n+0]=j,a[2*n+1]=O,n+=1}this._dynamicCounts[o]=n-this._dynamicOffsets[o]}else this.dynamicLevel[o]=NaN,this._dynamicCounts[o]=0;this._dynamicBuffer.update(a.subarray(0,2*n)),m.freeFloat(a)}}},{"./lib/shaders":939,"binary-search-bounds":940,"bit-twiddle":941,colormap:943,"gl-buffer":946,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-texture2d":973,"gl-vao":977,ndarray:1031,"ndarray-gradient":978,"ndarray-ops":1026,"ndarray-pack":983,"surface-nets":1001,"typedarray-pool":1002}],1004:[function(t,e,r){"use strict";function n(t,e){function r(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==g.alt,g.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==g.shift,g.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==g.control,g.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==g.meta,g.meta=!!t.metaKey),e}function n(t,n){var a=i.x(n),o=i.y(n);"buttons"in n&&(t=0|n.buttons),(t!==h||a!==p||o!==d||r(n))&&(h=0|t,p=a||0,d=o||0,e&&e(h,p,d,g))}function a(t){n(0,t)}function o(){(h||p||d||g.shift||g.alt||g.meta||g.control)&&(p=d=0,h=0,g.shift=g.alt=g.control=g.meta=!1,e&&e(0,0,0,g))}function s(t){r(t)&&e&&e(h,p,d,g)}function l(t){0===i.buttons(t)?n(0,t):n(h,t)}function u(t){n(h|i.buttons(t),t)}function c(t){n(h&~i.buttons(t),t)}function f(){v||(v=!0,t.addEventListener("mousemove",l),t.addEventListener("mousedown",u),t.addEventListener("mouseup",c),t.addEventListener("mouseleave",a),t.addEventListener("mouseenter",a),t.addEventListener("mouseout",a),t.addEventListener("mouseover",a),t.addEventListener("blur",o),t.addEventListener("keyup",s),t.addEventListener("keydown",s),t.addEventListener("keypress",s),t!==window&&(window.addEventListener("blur",o),window.addEventListener("keyup",s),window.addEventListener("keydown",s),window.addEventListener("keypress",s)))}e||(e=t,t=window);var h=0,p=0,d=0,g={shift:!1,alt:!1,control:!1,meta:!1},v=!1;f();var m={element:t};return Object.defineProperties(m,{enabled:{get:function(){return v},set:function(t){t&&f()},enumerable:!0},buttons:{get:function(){return h},enumerable:!0},x:{get:function(){return p},enumerable:!0},y:{get:function(){return d},enumerable:!0},mods:{get:function(){return g},enumerable:!0}}),m}e.exports=n;var i=t("mouse-event")},{"mouse-event":1005}],1005:[function(t,e,r){"use strict";function n(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){var e=t.which;if(2===e)return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1<=0&&r=0&&r+1=0&&n=0&&n+1=0&&s=0&&s+1=0&&i=0&&i+1=0&&l=0&&l+1=0&&h=0&&h+1e;++e)r=+arguments[e+1],i[e]=Math.floor(r),a[e]=r-i[e],o[e]=0<=i[e]&&i[e]e;++e){for(u=1,c=t.offset,l=0;n>l;++l)if(e&1<r;++r){t[r]=o[(n+1)*n+r];for(var i=0;n>i;++i)t[r]+=o[(n+1)*i+r]*e[i]}for(var a=o[(n+1)*(n+1)-1],i=0;n>i;++i)a+=o[(n+1)*i+n]*e[i];for(var s=1/a,r=0;n>r;++r)t[r]*=s;return t}),t}var i=t("ndarray-warp"),a=t("gl-matrix-invert");e.exports=n},{"gl-matrix-invert":1015,"ndarray-warp":1024}],1026:[function(t,e,r){"use strict";function n(t){if(!t)return s;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in l){var e=l[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var u={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in u){var e=u[t];r[t]=a({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=a({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in c){var e=c[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var f=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=o({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=o({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=a({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=a({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=a({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=o({args:["array","array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":1027}],1027:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":1029,dup:319}],1028:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:1030}],1029:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":1028,dup:321}],1030:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],1031:[function(t,e,r){function n(t,e){return t[0]-e[0]}function i(){var t,e=this.stride,r=new Array(e.length);for(t=0;te&&(r="View_Nil"+t);var n="generic"===t;if(-1===e){var a="function "+r+"(a){this.data=a;};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+r+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+r+"(a){return new "+r+"(a);}",o=new Function(a);return o()}if(0===e){var a="function "+r+"(a,d) {this.data = a;this.offset = d};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+r+"_copy() {return new "+r+"(this.data,this.offset)};proto.pick=function "+r+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+r+"_get(){return "+(n?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+r+"_set(v){return "+(n?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+r+"(a,b,c,d){return new "+r+"(a,d)}",o=new Function("TrivialArray",a);return o(f[t][0])}var a=["'use strict'"],s=l(e),u=s.map(function(t){return"i"+t}),c="this.offset+"+s.map(function(t){return"this.stride["+t+"]*i"+t}).join("+"),h=s.map(function(t){return"b"+t}).join(","),p=s.map(function(t){return"c"+t}).join(",");a.push("function "+r+"(a,"+h+","+p+",d){this.data=a","this.shape=["+h+"]","this.stride=["+p+"]","this.offset=d|0}","var proto="+r+".prototype","proto.dtype='"+t+"'","proto.dimension="+e),a.push("Object.defineProperty(proto,'size',{get:function "+r+"_size(){return "+s.map(function(t){return"this.shape["+t+"]"}).join("*"),"}})"),1===e?a.push("proto.order=[0]"):(a.push("Object.defineProperty(proto,'order',{get:"),4>e?(a.push("function "+r+"_order(){"),2===e?a.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+u.join(",")+",v){"),n?a.push("return this.data.set("+c+",v)}"):a.push("return this.data["+c+"]=v}"),a.push("proto.get=function "+r+"_get("+u.join(",")+"){"),n?a.push("return this.data.get("+c+")}"):a.push("return this.data["+c+"]}"),a.push("proto.index=function "+r+"_index(",u.join(),"){return "+c+"}"),a.push("proto.hi=function "+r+"_hi("+u.join(",")+"){return new "+r+"(this.data,"+s.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+s.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var d=s.map(function(t){return"a"+t+"=this.shape["+t+"]"}),g=s.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+u.join(",")+"){var b=this.offset,d=0,"+d.join(",")+","+g.join(","));for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){d=i"+v+"|0;b+=c"+v+"*d;a"+v+"-=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+u.join(",")+"){var "+s.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+s.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'){d=i"+v+"|0;if(d<0){c+=b"+v+"*(a"+v+"-1);a"+v+"=ceil(-a"+v+"/d)}else{a"+v+"=ceil(a"+v+"/d)}b"+v+"*=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"b"+t}).join(",")+",c)}");for(var m=new Array(e),y=new Array(e),v=0;e>v;++v)m[v]="a[i"+v+"]",y[v]="b[i"+v+"]";a.push("proto.transpose=function "+r+"_transpose("+u+"){"+u.map(function(t,e){return t+"=("+t+"===undefined?"+e+":"+t+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+r+"(this.data,"+m.join(",")+","+y.join(",")+",this.offset)}"),a.push("proto.pick=function "+r+"_pick("+u+"){var a=[],b=[],c=this.offset");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){c=(c+this.stride["+v+"]*i"+v+")|0}else{a.push(this.shape["+v+"]);b.push(this.stride["+v+"])}");a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+s.map(function(t){return"shape["+t+"]"; +}).join(",")+","+s.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}");var o=new Function("CTOR_LIST","ORDER",a.join("\n"));return o(f[t],i)}function o(t){if(u(t))return"buffer";if(c)switch(Object.prototype.toString.call(t)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(t)?"array":"generic"}function s(t,e,r,n){if(void 0===t){var i=f.array[0];return i([])}"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var s=e.length;if(void 0===r){r=new Array(s);for(var l=s-1,u=1;l>=0;--l)r[l]=u,u*=e[l]}if(void 0===n){n=0;for(var l=0;s>l;++l)r[l]<0&&(n-=(e[l]-1)*r[l])}for(var c=o(t),h=f[c];h.length<=s+1;)h.push(a(c,h.length-1));var i=h[s+1];return i(t,e,r,n)}var l=t("iota-array"),u=t("is-buffer"),c="undefined"!=typeof Float64Array,f={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=s},{"iota-array":1032,"is-buffer":1033}],1032:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=r;return e}e.exports=n},{}],1033:[function(t,e,r){e.exports=function(t){return!(null==t||!(t._isBuffer||t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)))}},{}],1034:[function(t,e,r){(function(t){e.exports=t.performance&&t.performance.now?function(){return performance.now()}:Date.now||function(){return+new Date}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],1035:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],1036:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":1039,"two-sum":1035}],1037:[function(t,e,r){arguments[4][364][0].apply(r,arguments)},{dup:364}],1038:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],1039:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],1040:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-1,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;ru;++u)0===(1&u)?e.push.apply(e,s(n(a,u))):r.push.apply(r,s(n(a,u))),l.push("m"+u);var c=o(e),g=o(r),v="orientation"+t+"Exact",m=["function ",v,"(",l.join(),"){var p=",c,",n=",g,",d=sub(p,n);return d[d.length-1];};return ",v].join(""),y=new Function("sum","prod","scale","sub",m);return y(h,f,p,d)}function u(t){var e=_[t.length];return e||(e=_[t.length]=l(t.length)),e.apply(void 0,t)}function c(){for(;_.length<=g;)_.push(l(_.length));for(var t=[],r=["slow"],n=0;g>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;g>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var f=t("two-product"),h=t("robust-sum"),p=t("robust-scale"),d=t("robust-subtract"),g=5,v=1.1102230246251565e-16,m=(3+16*v)*v,y=(7+56*v)*v,b=l(3),x=l(4),_=[function(){return 0},function(){return 0},function(t,e){return e[0]-t[0]},function(t,e,r){var n,i=(t[1]-r[1])*(e[0]-r[0]),a=(t[0]-r[0])*(e[1]-r[1]),o=i-a;if(i>0){if(0>=a)return o;n=i+a}else{if(!(0>i))return o;if(a>=0)return o;n=-(i+a)}var s=m*n;return o>=s||-s>=o?o:b(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],p=a*u,d=o*l,g=o*s,v=i*u,m=i*l,b=a*s,_=c*(p-d)+f*(g-v)+h*(m-b),w=(Math.abs(p)+Math.abs(d))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(f)+(Math.abs(m)+Math.abs(b))*Math.abs(h),k=y*w;return _>k||-_>k?_:x(t,e,r,n)}];c()},{"robust-scale":1036,"robust-subtract":1037,"robust-sum":1038,"two-product":1039}],1041:[function(t,e,r){"use strict";function n(t){return t.split("").map(function(t){return t in i?i[t]:""}).join("")}e.exports=n;var i={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"}},{}],1042:[function(e,r,n){!function(){function e(t,r){if(t=t?t:"",r=r||{},t instanceof e)return t;if(!(this instanceof e))return new e(t,r);var i=n(t);this._originalInput=t,this._r=i.r,this._g=i.g,this._b=i.b,this._a=i.a,this._roundA=U(100*this._a)/100,this._format=r.format||i.format,this._gradientType=r.gradientType,this._r<1&&(this._r=U(this._r)),this._g<1&&(this._g=U(this._g)),this._b<1&&(this._b=U(this._b)),this._ok=i.ok,this._tc_id=D++}function n(t){var e={r:0,g:0,b:0},r=1,n=!1,a=!1;return"string"==typeof t&&(t=O(t)),"object"==typeof t&&(t.hasOwnProperty("r")&&t.hasOwnProperty("g")&&t.hasOwnProperty("b")?(e=i(t.r,t.g,t.b),n=!0,a="%"===String(t.r).substr(-1)?"prgb":"rgb"):t.hasOwnProperty("h")&&t.hasOwnProperty("s")&&t.hasOwnProperty("v")?(t.s=P(t.s),t.v=P(t.v),e=l(t.h,t.s,t.v),n=!0,a="hsv"):t.hasOwnProperty("h")&&t.hasOwnProperty("s")&&t.hasOwnProperty("l")&&(t.s=P(t.s),t.l=P(t.l),e=o(t.h,t.s,t.l),n=!0,a="hsl"),t.hasOwnProperty("a")&&(r=t.a)),r=M(r),{ok:n,format:t.format||a,r:V(255,q(e.r,0)),g:V(255,q(e.g,0)),b:V(255,q(e.b,0)),a:r}}function i(t,e,r){return{r:255*T(t,255),g:255*T(e,255),b:255*T(r,255)}}function a(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=(a+o)/2;if(a==o)n=i=0;else{var l=a-o;switch(i=s>.5?l/(2-a-o):l/(a+o),a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,l:s}}function o(t,e,r){function n(t,e,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?t+6*(e-t)*r:.5>r?e:2/3>r?t+(e-t)*(2/3-r)*6:t}var i,a,o;if(t=T(t,360),e=T(e,100),r=T(r,100),0===e)i=a=o=r;else{var s=.5>r?r*(1+e):r+e-r*e,l=2*r-s;i=n(l,s,t+1/3),a=n(l,s,t),o=n(l,s,t-1/3)}return{r:255*i,g:255*a,b:255*o}}function s(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=a,l=a-o;if(i=0===a?0:l/a,a==o)n=0;else{switch(a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,v:s}}function l(t,e,r){t=6*T(t,360),e=T(e,100),r=T(r,100);var n=B.floor(t),i=t-n,a=r*(1-e),o=r*(1-i*e),s=r*(1-(1-i)*e),l=n%6,u=[r,o,a,a,s,r][l],c=[s,r,r,o,a,a][l],f=[a,a,s,r,r,o][l];return{r:255*u,g:255*c,b:255*f}}function u(t,e,r,n){var i=[z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function c(t,e,r,n){var i=[z(R(n)),z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return i.join("")}function f(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s-=r/100,n.s=E(n.s),e(n)}function h(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s+=r/100,n.s=E(n.s),e(n)}function p(t){return e(t).desaturate(100)}function d(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l+=r/100,n.l=E(n.l),e(n)}function g(t,r){r=0===r?0:r||10;var n=e(t).toRgb();return n.r=q(0,V(255,n.r-U(255*-(r/100)))),n.g=q(0,V(255,n.g-U(255*-(r/100)))),n.b=q(0,V(255,n.b-U(255*-(r/100)))),e(n)}function v(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l-=r/100,n.l=E(n.l),e(n)}function m(t,r){var n=e(t).toHsl(),i=(U(n.h)+r)%360;return n.h=0>i?360+i:i,e(n)}function y(t){var r=e(t).toHsl();return r.h=(r.h+180)%360,e(r)}function b(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+120)%360,s:r.s,l:r.l}),e({h:(n+240)%360,s:r.s,l:r.l})]}function x(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+90)%360,s:r.s,l:r.l}),e({h:(n+180)%360,s:r.s,l:r.l}),e({h:(n+270)%360,s:r.s,l:r.l})]}function _(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+72)%360,s:r.s,l:r.l}),e({h:(n+216)%360,s:r.s,l:r.l})]}function w(t,r,n){r=r||6,n=n||30;var i=e(t).toHsl(),a=360/n,o=[e(t)];for(i.h=(i.h-(a*r>>1)+720)%360;--r;)i.h=(i.h+a)%360,o.push(e(i));return o}function k(t,r){r=r||6;for(var n=e(t).toHsv(),i=n.h,a=n.s,o=n.v,s=[],l=1/r;r--;)s.push(e({h:i,s:a,v:o})),o=(o+l)%1;return s}function A(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}function M(t){return t=parseFloat(t),(isNaN(t)||0>t||t>1)&&(t=1),t}function T(t,e){S(t)&&(t="100%");var r=C(t);return t=V(e,q(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),B.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function E(t){return V(1,q(0,t))}function L(t){return parseInt(t,16)}function S(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)}function C(t){return"string"==typeof t&&-1!=t.indexOf("%")}function z(t){return 1==t.length?"0"+t:""+t}function P(t){return 1>=t&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function j(t){return L(t)/255}function O(t){t=t.replace(N,"").replace(F,"").toLowerCase();var e=!1;if(H[t])t=H[t],e=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};var r;return(r=X.rgb.exec(t))?{r:r[1],g:r[2],b:r[3]}:(r=X.rgba.exec(t))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=X.hsl.exec(t))?{h:r[1],s:r[2],l:r[3]}:(r=X.hsla.exec(t))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=X.hsv.exec(t))?{h:r[1],s:r[2],v:r[3]}:(r=X.hsva.exec(t))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=X.hex8.exec(t))?{a:j(r[1]),r:L(r[2]),g:L(r[3]),b:L(r[4]),format:e?"name":"hex8"}:(r=X.hex6.exec(t))?{r:L(r[1]),g:L(r[2]),b:L(r[3]),format:e?"name":"hex"}:(r=X.hex3.exec(t))?{r:L(r[1]+""+r[1]),g:L(r[2]+""+r[2]),b:L(r[3]+""+r[3]),format:e?"name":"hex"}:!1}function I(t){var e,r;return t=t||{level:"AA",size:"small"},e=(t.level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA"),"small"!==r&&"large"!==r&&(r="small"),{level:e,size:r}}var N=/^\s+/,F=/\s+$/,D=0,B=Math,U=B.round,V=B.min,q=B.max,G=B.random;e.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n,i,a,o=this.toRgb();return t=o.r/255,e=o.g/255,r=o.b/255,n=.03928>=t?t/12.92:Math.pow((t+.055)/1.055,2.4),i=.03928>=e?e/12.92:Math.pow((e+.055)/1.055,2.4),a=.03928>=r?r/12.92:Math.pow((r+.055)/1.055,2.4),.2126*n+.7152*i+.0722*a},setAlpha:function(t){return this._a=M(t),this._roundA=U(100*this._a)/100,this},toHsv:function(){var t=s(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=s(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return u(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(){return c(this._r,this._g,this._b,this._a)},toHex8String:function(){return"#"+this.toHex8()},toRgb:function(){return{r:U(this._r),g:U(this._g),b:U(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+U(this._r)+", "+U(this._g)+", "+U(this._b)+")":"rgba("+U(this._r)+", "+U(this._g)+", "+U(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:U(100*T(this._r,255))+"%",g:U(100*T(this._g,255))+"%",b:U(100*T(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%)":"rgba("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":this._a<1?!1:Y[u(this._r,this._g,this._b,!0)]||!1},toFilter:function(t){var r="#"+c(this._r,this._g,this._b,this._a),n=r,i=this._gradientType?"GradientType = 1, ":"";if(t){var a=e(t);n=a.toHex8String()}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+r+",endColorstr="+n+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0,i=!e&&n&&("hex"===t||"hex6"===t||"hex3"===t||"name"===t);return i?"name"===t&&0===this._a?this.toName():this.toRgbString():("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString())},clone:function(){return e(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(d,arguments)},brighten:function(){return this._applyModification(g,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(f,arguments)},saturate:function(){return this._applyModification(h,arguments)},greyscale:function(){return this._applyModification(p,arguments)},spin:function(){return this._applyModification(m,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(w,arguments)},complement:function(){return this._applyCombination(y,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(b,arguments)},tetrad:function(){return this._applyCombination(x,arguments)}},e.fromRatio=function(t,r){if("object"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&("a"===i?n[i]=t[i]:n[i]=P(t[i]));t=n}return e(t,r)},e.equals=function(t,r){return t&&r?e(t).toRgbString()==e(r).toRgbString():!1},e.random=function(){return e.fromRatio({r:G(),g:G(),b:G()})},e.mix=function(t,r,n){n=0===n?0:n||50;var i,a=e(t).toRgb(),o=e(r).toRgb(),s=n/100,l=2*s-1,u=o.a-a.a;i=l*u==-1?l:(l+u)/(1+l*u),i=(i+1)/2;var c=1-i,f={r:o.r*i+a.r*c,g:o.g*i+a.g*c,b:o.b*i+a.b*c,a:o.a*s+a.a*(1-s)};return e(f)},e.readability=function(t,r){var n=e(t),i=e(r);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},e.isReadable=function(t,r,n){var i,a,o=e.readability(t,r);switch(a=!1,i=I(n),i.level+i.size){case"AAsmall":case"AAAlarge":a=o>=4.5;break;case"AAlarge":a=o>=3;break;case"AAAsmall":a=o>=7}return a},e.mostReadable=function(t,r,n){var i,a,o,s,l=null,u=0;n=n||{},a=n.includeFallbackColors,o=n.level,s=n.size;for(var c=0;cu&&(u=i,l=e(r[c]));return e.isReadable(t,l,{level:o,size:s})||!a?l:(n.includeFallbackColors=!1,e.mostReadable(t,["#fff","#000"],n))};var H=e.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Y=e.hexNames=A(H),X=function(){var t="[-\\+]?\\d+%?",e="[-\\+]?\\d*\\.\\d+%?",r="(?:"+e+")|(?:"+t+")",n="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?",i="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?";return{rgb:new RegExp("rgb"+n),rgba:new RegExp("rgba"+i),hsl:new RegExp("hsl"+n),hsla:new RegExp("hsla"+i),hsv:new RegExp("hsv"+n),hsva:new RegExp("hsva"+i),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();"undefined"!=typeof r&&r.exports?r.exports=e:"function"==typeof t&&t.amd?t(function(){return e}):window.tinycolor=e}()},{}],1043:[function(e,r,n){!function(e,i){"object"==typeof n&&"undefined"!=typeof r?i(n):"function"==typeof t&&t.amd?t(["exports"],i):i(e.topojson=e.topojson||{})}(this,function(t){"use strict";function e(){}function r(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0),t[0]=(r+=t[0])*i+o,t[1]=(n+=t[1])*a+s}}function n(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0);var l=Math.round((t[0]-o)/i),u=Math.round((t[1]-s)/a);t[0]=l-r,t[1]=u-n,r=l,n=u}}function i(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r}function a(t,e){for(var r=0,n=t.length;n>r;){var i=r+n>>>1;t[i]t?~t:t],a=0,o=n.length;o>a;++a)e.push(r=n[a].slice()),c(r,a);0>t&&i(e,o)}function a(t){return t=t.slice(),c(t,0),t}function o(t){for(var e=[],r=0,i=t.length;i>r;++r)n(t[r],e);return e.length<2&&e.push(e[0].slice()),e}function s(t){for(var e=o(t);e.length<4;)e.push(e[0].slice());return e}function l(t){return t.map(s)}function u(t){var e=t.type;return"GeometryCollection"===e?{type:e,geometries:t.geometries.map(u)}:e in h?{type:e,coordinates:h[e](t)}:null}var c=r(t.transform),f=t.arcs,h={Point:function(t){return a(t.coordinates)},MultiPoint:function(t){return t.coordinates.map(a)},LineString:function(t){return o(t.arcs)},MultiLineString:function(t){return t.arcs.map(o)},Polygon:function(t){return l(t.arcs)},MultiPolygon:function(t){return t.arcs.map(l)}};return u(e)}function u(t,e){function r(e){var r,n=t.arcs[0>e?~e:e],i=n[0];return t.transform?(r=[0,0],n.forEach(function(t){r[0]+=t[0],r[1]+=t[1]})):r=n[n.length-1],0>e?[r,i]:[i,r]}function n(t,e){for(var r in t){var n=t[r];delete e[n.start],delete n.start,delete n.end,n.forEach(function(t){i[0>t?~t:t]=1}),s.push(n)}}var i={},a={},o={},s=[],l=-1;return e.forEach(function(r,n){var i,a=t.arcs[0>r?~r:r];a.length<3&&!a[1][0]&&!a[1][1]&&(i=e[++l],e[l]=r,e[n]=i)}),e.forEach(function(t){var e,n,i=r(t),s=i[0],l=i[1];if(e=o[s])if(delete o[e.end],e.push(t),e.end=l,n=a[l]){delete a[n.start];var u=n===e?e:e.concat(n);a[u.start=e.start]=o[u.end=n.end]=u}else a[e.start]=o[e.end]=e;else if(e=a[l])if(delete a[e.start],e.unshift(t),e.start=s,n=o[s]){delete o[n.end];var c=n===e?e:n.concat(e);a[c.start=n.start]=o[c.end=e.end]=c}else a[e.start]=o[e.end]=e;else e=[t],a[e.start=s]=o[e.end=l]=e}),n(o,a),n(a,o),e.forEach(function(t){i[0>t?~t:t]||s.push([t])}),s}function c(t){return l(t,f.apply(this,arguments))}function f(t,e,r){function n(t){var e=0>t?~t:t;(c[e]||(c[e]=[])).push({i:t,g:l})}function i(t){t.forEach(n)}function a(t){t.forEach(i)}function o(t){"GeometryCollection"===t.type?t.geometries.forEach(o):t.type in f&&(l=t,f[t.type](t.arcs))}var s=[];if(arguments.length>1){var l,c=[],f={LineString:i,MultiLineString:a,Polygon:a,MultiPolygon:function(t){t.forEach(a)}};o(e),c.forEach(arguments.length<3?function(t){s.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&s.push(t[0].i)})}else for(var h=0,p=t.arcs.length;p>h;++h)s.push(h);return{type:"MultiLineString",arcs:u(t,s)}}function h(t){var e=t[0],r=t[1],n=t[2];return Math.abs((e[0]-n[0])*(r[1]-e[1])-(e[0]-r[0])*(n[1]-e[1]))}function p(t){for(var e,r=-1,n=t.length,i=t[n-1],a=0;++re?~e:e]||(i[e]=[])).push(t)})}),a.push(t)}function n(e){return Math.abs(p(l(t,{type:"Polygon",arcs:[e]}).coordinates[0]))}var i={},a=[],o=[];return e.forEach(function(t){"Polygon"===t.type?r(t.arcs):"MultiPolygon"===t.type&&t.arcs.forEach(r)}),a.forEach(function(t){if(!t._){var e=[],r=[t];for(t._=1,o.push(e);t=r.pop();)e.push(t),t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].forEach(function(t){t._||(t._=1,r.push(t))})})})}}),a.forEach(function(t){delete t._}),{type:"MultiPolygon",arcs:o.map(function(e){var r,a=[];if(e.forEach(function(t){t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].length<2&&a.push(t)})})}),a=u(t,a),(r=a.length)>1)for(var o,s,l=1,c=n(a[0]);r>l;++l)(o=n(a[l]))>c&&(s=a[0],a[0]=a[l],a[l]=s,c=o);return a})}}function v(t){function e(t,e){t.forEach(function(t){0>t&&(t=~t);var r=i[t];r?r.push(e):i[t]=[e]})}function r(t,r){t.forEach(function(t){e(t,r)})}function n(t,e){"GeometryCollection"===t.type?t.geometries.forEach(function(t){n(t,e)}):t.type in s&&s[t.type](t.arcs,e)}var i={},o=t.map(function(){return[]}),s={LineString:e,MultiLineString:r,Polygon:r,MultiPolygon:function(t,e){t.forEach(function(t){r(t,e)})}};t.forEach(n);for(var l in i)for(var u=i[l],c=u.length,f=0;c>f;++f)for(var h=f+1;c>h;++h){var p,d=u[f],g=u[h];(p=o[d])[l=a(p,g)]!==g&&p.splice(l,0,g),(p=o[g])[l=a(p,d)]!==d&&p.splice(l,0,d)}return o}function m(t,e){return t[1][2]-e[1][2]}function y(){function t(t,e){for(;e>0;){var r=(e+1>>1)-1,i=n[r];if(m(t,i)>=0)break;n[i._=e]=i,n[t._=e=r]=t}}function e(t,e){for(;;){var r=e+1<<1,a=r-1,o=e,s=n[o];if(i>a&&m(n[a],s)<0&&(s=n[o=a]),i>r&&m(n[r],s)<0&&(s=n[o=r]),o===e)break;n[s._=e]=s,n[t._=e=o]=t}}var r={},n=[],i=0;return r.push=function(e){return t(n[e._=i]=e,i++),i},r.pop=function(){if(!(0>=i)){var t,r=n[0];return--i>0&&(t=n[i],e(n[t._=0]=t,0)),r}},r.remove=function(r){var a,o=r._;if(n[o]===r)return o!==--i&&(a=n[i],(m(a,r)<0?t:e)(n[a._=o]=a,o)),o},r}function b(t,e){function i(t){s.remove(t),t[1][2]=e(t),s.push(t)}var a=r(t.transform),o=n(t.transform),s=y();return e||(e=h),t.arcs.forEach(function(t){var r,n,l,u,c=[],f=0;for(n=0,l=t.length;l>n;++n)u=t[n],a(t[n]=[u[0],u[1],1/0],n);for(n=1,l=t.length-1;l>n;++n)r=t.slice(n-1,n+2),r[1][2]=e(r),c.push(r),s.push(r);for(n=0,l=c.length;l>n;++n)r=c[n],r.previous=c[n-1],r.next=c[n+1];for(;r=s.pop();){var h=r.previous,p=r.next;r[1][2]h;h++){var p=l[h],d={_fullLayout:e},g=c.coerceRef(t,n,d,p),m=.5;if("paper"!==g){var y=c.getFromId(d,g);if(m=y.range[0]+m*(y.range[1]-y.range[0]),-1!==["date","category"].indexOf(y.type)&&"string"==typeof t[p]){var b;"date"===y.type?(b=u.dateTime2ms(t[p]),b!==!1&&(t[p]=b)):(y._categories||[]).length&&(b=y._categories.indexOf(t[p]),-1!==b&&(t[p]=b))}}r(p,m),s||r(p+"anchor")}return u.noneOrAll(t,n,["x","y"]),n}function i(t){var e=t._fullLayout;e.annotations.forEach(function(e){var r=c.getFromId(t,e.xref),n=c.getFromId(t,e.yref);if(r||n){var i=(e._xsize||0)/2,a=e._xshift||0,o=(e._ysize||0)/2,s=e._yshift||0,l=i-a,u=i+a,f=o-s,h=o+s;if(e.showarrow){var p=3*e.arrowsize*e.arrowwidth;l=Math.max(l,p),u=Math.max(u,p),f=Math.max(f,p),h=Math.max(h,p)}r&&r.autorange&&c.expand(r,[r.l2c(e.x)],{ppadplus:u,ppadminus:l}),n&&n.autorange&&c.expand(n,[n.l2c(e.y)],{ppadplus:h,ppadminus:f})}})}function a(t,e,r,n,i,a,o,s){var l=r-t,u=i-t,c=o-i,f=n-e,h=a-e,p=s-a,d=l*p-c*f;if(0===d)return null;var g=(u*p-c*h)/d,v=(u*f-l*h)/d;return 0>v||v>1||0>g||g>1?null:{x:t+l*g,y:e+f*g}}var o=t("d3"),s=t("fast-isnumeric"),l=t("../../plotly"),u=t("../../lib"),c=t("../../plots/cartesian/axes"),f=t("../color"),h=t("../drawing"),p=t("../../lib/svg_text_utils"),d=t("../../lib/setcursor"),g=t("../dragelement"),v=e.exports={};v.ARROWPATHS=t("./arrow_paths"),v.layoutAttributes=t("./attributes"),v.supplyLayoutDefaults=function(t,e){for(var r=t.annotations||[],i=e.annotations=[],a=0;at?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}tt.selectAll("tspan.line").attr({y:0,x:0});var n=W.select(".annotation-math-group"),i=!n.empty(),s=h.bBox((i?n:tt).node()),p=s.width,m=s.height,y=Math.round(p+2*$),b=Math.round(m+2*$);U._w=p,U._h=m;var x=!1;if(["x","y"].forEach(function(e){var n,i=c.getFromId(t,U[e+"ref"]||e),a=(H+("x"===e?0:90))*Math.PI/180,o=y*Math.abs(Math.cos(a))+b*Math.abs(Math.sin(a)),s=U[e+"anchor"];if(i){if(!i.autorange&&(U[e]-i.range[0])*(U[e]-i.range[1])>0)return void(x=!0);G[e]=i._offset+i.l2p(U[e]),n=.5}else n=U[e],"y"===e&&(n=1-n),G[e]="x"===e?S.l+S.w*n:S.t+S.h*n;var l=0;l=U.showarrow?U["a"+e]:o*r(n,s),G[e]+=l,U["_"+e+"type"]=i&&i.type,U["_"+e+"size"]=o,U["_"+e+"shift"]=l}),x)return void W.remove();var w,k;U.showarrow&&(w=u.constrain(G.x-U.ax,1,_.width-1),k=u.constrain(G.y-U.ay,1,_.height-1)),G.x=u.constrain(G.x,1,_.width-1),G.y=u.constrain(G.y,1,_.height-1);var A=$-s.top,M=$-s.left;i?n.select("svg").attr({x:$-1,y:$}):(tt.attr({x:M,y:A}),tt.selectAll("tspan.line").attr({y:A,x:M})),Q.call(h.setRect,Z/2,Z/2,y-Z,b-Z);var T=Math.round(G.x-y/2),E=Math.round(G.y-b/2);W.call(u.setTranslate,T,E);var L="annotations["+e+"]",C=function(r,n){o.select(t).selectAll('.annotation-arrow-g[data-index="'+e+'"]').remove();var i=G.x+r,s=G.y+n,c=u.rotationXYMatrix(H,i,s),h=u.apply2DTransform(c),p=u.apply2DTransform2(c),d=Q.attr("width")/2,m=Q.attr("height")/2,y=[[i-d,s-m,i-d,s+m],[i-d,s+m,i+d,s+m],[i+d,s+m,i+d,s-m],[i+d,s-m,i-d,s-m]].map(p);if(!y.reduce(function(t,e){return t^!!a(w,k,w+1e6,k+1e6,e[0],e[1],e[2],e[3])},!1)){y.forEach(function(t){var e=a(i,s,w,k,t[0],t[1],t[2],t[3]);e&&(i=e.x,s=e.y)});var b=U.arrowwidth,x=U.arrowcolor,_=Y.append("g").style({opacity:f.opacity(x) +}).classed("annotation-arrow-g",!0).attr("data-index",String(e)),A=_.append("path").attr("d","M"+i+","+s+"L"+w+","+k).style("stroke-width",b+"px").call(f.stroke,f.rgb(x));v.arrowhead(A,U.arrowhead,"end",U.arrowsize);var M=_.append("path").classed("annotation",!0).classed("anndrag",!0).attr({"data-index":String(e),d:"M3,3H-3V-3H3ZM0,0L"+(i-w)+","+(s-k),transform:"translate("+w+","+k+")"}).style("stroke-width",b+6+"px").call(f.stroke,"rgba(0,0,0,0)").call(f.fill,"rgba(0,0,0,0)");if(t._context.editable){var T,E,C;g.init({element:M.node(),prepFn:function(){var t=u.getTranslate(W);E=t.x,C=t.y,T={},V&&V.autorange&&(T[V._name+".autorange"]=!0),q&&q.autorange&&(T[q._name+".autorange"]=!0)},moveFn:function(t,e){_.attr("transform","translate("+t+","+e+")");var r=h(E,C),n=r[0]+t,i=r[1]+e;W.call(u.setTranslate,n,i),T[L+".x"]=V?U.x+t/V._m:(w+t-S.l)/S.w,T[L+".y"]=q?U.y+e/q._m:1-(k+e-S.t)/S.h,X.attr({transform:"rotate("+H+","+n+","+i+")"})},doneFn:function(e){if(e){l.relayout(t,T);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}};U.showarrow&&C(0,0);var z=u.rotationXYMatrix(H,G.x,G.y),P=u.apply2DTransform(z);if(t._context.editable){var R,j,O;g.init({element:W.node(),prepFn:function(){var t=u.getTranslate(W);R=t.x,j=t.y,O={}},moveFn:function(t,e){W.call(u.setTranslate,R+t,j+e);var r="pointer";if(U.showarrow)O[L+".ax"]=U.ax+t,O[L+".ay"]=U.ay+e,C(t,e);else{if(V)O[L+".x"]=U.x+t/V._m;else{var n=U._xsize/S.w,i=U.x+U._xshift/S.w-n/2;O[L+".x"]=g.align(i+t/S.w,n,0,1,U.xanchor)}if(q)O[L+".y"]=U.y+e/q._m;else{var a=U._ysize/S.h,o=U.y-U._yshift/S.h-a/2;O[L+".y"]=g.align(o-e/S.h,a,0,1,U.yanchor)}V&&q||(r=g.getCursor(V?.5:O[L+".x"],q?.5:O[L+".y"],U.xanchor,U.yanchor))}var s=P(R,j),l=s[0]+t,c=s[1]+e;W.call(u.setTranslate,R+t,j+e),X.attr({transform:"rotate("+H+","+l+","+c+")"}),d(W,r)},doneFn:function(e){if(d(W),e){l.relayout(t,O);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}var b,x=t.layout,_=t._fullLayout;if(!s(e)||-1===e){if(!e&&Array.isArray(i))return x.annotations=i,v.supplyLayoutDefaults(x,_),void v.drawAll(t);if("remove"===i)return delete x.annotations,_.annotations=[],void v.drawAll(t);if(r&&"add"!==i){for(b=0;b<_.annotations.length;b++)v.draw(t,b,r,i);return}e=_.annotations.length,_.annotations.push({})}if(!r&&i){if("remove"===i){for(_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove(),_.annotations.splice(e,1),x.annotations.splice(e,1),b=e;b<_.annotations.length;b++)_._infolayer.selectAll('.annotation[data-index="'+(b+1)+'"]').attr("data-index",String(b)),v.draw(t,b);return}if("add"===i||u.isPlainObject(i)){_.annotations.splice(e,0,{});var w=u.isPlainObject(i)?u.extendFlat({},i):{text:"New text"};for(x.annotations?x.annotations.splice(e,0,w):x.annotations=[w],b=_.annotations.length-1;b>e;b--)_._infolayer.selectAll('.annotation[data-index="'+(b-1)+'"]').attr("data-index",String(b)),v.draw(t,b)}}_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove();var k=x.annotations[e],A=_.annotations[e];if(k){var M={xref:k.xref,yref:k.yref},T={};"string"==typeof r&&r?T[r]=i:u.isPlainObject(r)&&(T=r);var E=Object.keys(T);for(b=0;bb;b++){var z=C[b];if(void 0===T[z]&&void 0!==k[z]){var P=c.getFromId(t,c.coerceRef(M,{},t,z)),R=c.getFromId(t,c.coerceRef(k,{},t,z)),j=k[z],O=A["_"+z+"type"];if(void 0!==T[z+"ref"]){var I="auto"===k[z+"anchor"],N="x"===z?S.w:S.h,F=(A["_"+z+"size"]||0)/(2*N);if(P&&R)j=(j-P.range[0])/(P.range[1]-P.range[0]),j=R.range[0]+j*(R.range[1]-R.range[0]);else if(P){if(j=(j-P.range[0])/(P.range[1]-P.range[0]),j=P.domain[0]+j*(P.domain[1]-P.domain[0]),I){var D=j+F,B=j-F;2/3>j+B?j=B:j+D>4/3&&(j=D)}}else R&&(I&&(1/3>j?j+=F:j>2/3&&(j-=F)),j=(j-R.domain[0])/(R.domain[1]-R.domain[0]),j=R.range[0]+j*(R.range[1]-R.range[0]))}R&&R===P&&O&&("log"===O&&"log"!==R.type?j=Math.pow(10,j):"log"!==O&&"log"===R.type&&(j=j>0?Math.log(j)/Math.LN10:void 0)),k[z]=j}}var U=n(k,_);_.annotations[e]=U;var V=c.getFromId(t,U.xref),q=c.getFromId(t,U.yref),G={x:0,y:0},H=+U.textangle||0,Y=_._infolayer.append("g").classed("annotation",!0).attr("data-index",String(e)).style("opacity",U.opacity).on("click",function(){t._dragging=!1,t.emit("plotly_clickannotation",{index:e,annotation:k,fullAnnotation:U})}),X=Y.append("g").classed("annotation-text-g",!0).attr("data-index",String(e)),W=X.append("g"),Z=U.borderwidth,K=U.borderpad,$=Z+K,Q=W.append("rect").attr("class","bg").style("stroke-width",Z+"px").call(f.stroke,U.bordercolor).call(f.fill,U.bgcolor),J=U.font,tt=W.append("text").classed("annotation",!0).attr("data-unformatted",U.text).text(U.text);t._context.editable?tt.call(p.makeEditable,W).call(m).on("edit",function(r){U.text=r,this.attr({"data-unformatted":U.text}),this.call(m);var n={};n["annotations["+e+"].text"]=U.text,V&&V.autorange&&(n[V._name+".autorange"]=!0),q&&q.autorange&&(n[q._name+".autorange"]=!0),l.relayout(t,n)}):tt.call(m),X.attr({transform:"rotate("+H+","+G.x+","+G.y+")"}).call(h.setPosition,G.x,G.y)}},v.arrowhead=function(t,e,r,n){s(n)||(n=1);var i=t.node(),a=v.ARROWPATHS[e||0];if(a){"string"==typeof r&&r||(r="end");var l,u,c,p,d=(h.getPx(t,"stroke-width")||1)*n,g=t.style("stroke")||f.defaultLine,m=t.style("stroke-opacity")||1,y=r.indexOf("start")>=0,b=r.indexOf("end")>=0,x=a.backoff*d;if("line"===i.nodeName){if(l={x:+t.attr("x1"),y:+t.attr("y1")},u={x:+t.attr("x2"),y:+t.attr("y2")},c=Math.atan2(l.y-u.y,l.x-u.x),p=c+Math.PI,x){var _=x*Math.cos(c),w=x*Math.sin(c);y&&(l.x-=_,l.y-=w,t.attr({x1:l.x,y1:l.y})),b&&(u.x+=_,u.y+=w,t.attr({x2:u.x,y2:u.y}))}}else if("path"===i.nodeName){var k=i.getTotalLength(),A="";if(y){var M=i.getPointAtLength(0),T=i.getPointAtLength(.1);c=Math.atan2(M.y-T.y,M.x-T.x),l=i.getPointAtLength(Math.min(x,k)),x&&(A="0px,"+x+"px,")}if(b){var E=i.getPointAtLength(k),L=i.getPointAtLength(k-.1);if(p=Math.atan2(E.y-L.y,E.x-L.x),u=i.getPointAtLength(Math.max(0,k-x)),x){var S=A?2*x:x;A+=k-S+"px,"+k+"px"}}else A&&(A+=k+"px");A&&t.style("stroke-dasharray",A)}var C=function(r,n){e>5&&(n=0),o.select(i.parentElement).append("path").attr({"class":t.attr("class"),d:a.path,transform:"translate("+r.x+","+r.y+")rotate("+180*n/Math.PI+")scale("+d+")"}).style({fill:g,opacity:m,"stroke-width":0})};y&&C(l,c),b&&C(u,p)}},v.calcAutorange=function(t){var e=t._fullLayout,r=e.annotations;if(r.length&&t._fullData.length){var n={};r.forEach(function(t){n[t.xref]=!0,n[t.yref]=!0});var a=c.list(t).filter(function(t){return t.autorange&&n[t._id]});if(a.length)return u.syncOrAsync([v.drawAll,i],t)}}},{"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../dragelement":1069,"../drawing":1071,"./arrow_paths":1044,"./attributes":1045,d3:82,"fast-isnumeric":90}],1047:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.lightFraction=1e3/11},{}],1048:[function(t,e,r){"use strict";function n(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}var i=t("tinycolor2"),a=t("fast-isnumeric"),o=e.exports={},s=t("./attributes");o.defaults=s.defaults,o.defaultLine=s.defaultLine,o.lightLine=s.lightLine,o.background=s.background,o.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},o.rgb=function(t){return o.tinyRGB(i(t))},o.opacity=function(t){return t?i(t).getAlpha():0},o.addOpacity=function(t,e){var r=i(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},o.combine=function(t,e){var r=i(t).toRgb();if(1===r.a)return i(t).toRgbString();var n=i(e||o.background).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},s={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return i(s).toRgbString()},o.stroke=function(t,e){var r=i(e);t.style({stroke:o.tinyRGB(r),"stroke-opacity":r.getAlpha()})},o.fill=function(t,e){var r=i(e);t.style({fill:o.tinyRGB(r),"fill-opacity":r.getAlpha()})},o.clean=function(t){if(t&&"object"==typeof t){var e,r,i,a,s=Object.keys(t);for(e=0;el&&(a[1]-=(ot-l)/2)):r.node()&&!r.classed("js-placeholder")&&(ot=h.bBox(e.node()).height),ot){if(ot+=5,"top"===x.titleside)Q.domain[1]-=ot/M.h,a[1]*=-1;else{Q.domain[0]+=ot/M.h;var c=Math.max(1,r.selectAll("tspan.line").size());a[1]+=(1-c)*l}e.attr("transform","translate("+a+")"),Q.setScale()}}it.selectAll(".cbfills,.cblines,.cbaxis").attr("transform","translate(0,"+Math.round(M.h*(1-Q.domain[1]))+")");var f=it.select(".cbfills").selectAll("rect.cbfill").data(S);f.enter().append("rect").classed("cbfill",!0).style("stroke","none"),f.exit().remove(),f.each(function(t,e){var r=[0===e?E[0]:(S[e]+S[e-1])/2,e===S.length-1?E[1]:(S[e]+S[e+1])/2].map(Q.c2p).map(Math.round);e!==S.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=z(t).replace("e-",""),o=i(a).toHexString();n.select(this).attr({x:Y,width:Math.max(D,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var p=it.select(".cblines").selectAll("path.cbline").data(x.line.color&&x.line.width?L:[]);return p.enter().append("path").classed("cbline",!0),p.exit().remove(),p.each(function(t){n.select(this).attr("d","M"+Y+","+(Math.round(Q.c2p(t))+x.line.width/2%1)+"h"+D).call(h.lineGroupStyle,x.line.width,C(t),x.line.dash)}),Q._axislayer.selectAll("g."+Q._id+"tick,path").remove(),Q._pos=Y+D+(x.outlinewidth||0)/2-("outside"===x.ticks?1:0),Q.side="right",u.syncOrAsync([function(){return s.doTicks(t,Q,!0)},function(){if(-1===["top","bottom"].indexOf(x.titleside)){var e=Q.titlefont.size,r=Q._offset+Q._length/2,i=M.l+(Q.position||0)*M.w+("right"===Q.side?10+e*(Q.showticklabels?1:.5):-10-e*(Q.showticklabels?.5:0));w("h"+Q._id+"title",{avoid:{selection:n.select(t).selectAll("g."+Q._id+"tick"),side:x.titleside,offsetLeft:M.l,offsetTop:M.t,maxShift:A.width},attributes:{x:i,y:r,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])}function w(e,r){var n,i=b();n=o.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var a={propContainer:Q,propName:n,traceIndex:i.index,dfltName:"colorscale",containerGroup:it.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;it.selectAll("."+s+",."+s+"-math-group").remove(),d.draw(t,e,c(a,r||{}))}function k(){var r=D+x.outlinewidth/2+h.bBox(Q._axislayer.node()).width;if(I=at.select("text"),I.node()&&!I.classed("js-placeholder")){var n,i=at.select(".h"+Q._id+"title-math-group").node();n=i&&-1!==["top","bottom"].indexOf(x.titleside)?h.bBox(i).width:h.bBox(at.node()).right-Y-M.l,r=Math.max(r,n)}var a=2*x.xpad+r+x.borderwidth+x.outlinewidth/2,s=Z-K;it.select(".cbbg").attr({x:Y-x.xpad-(x.borderwidth+x.outlinewidth)/2,y:K-G,width:Math.max(a,2),height:Math.max(s+2*G,2)}).call(p.fill,x.bgcolor).call(p.stroke,x.bordercolor).style({"stroke-width":x.borderwidth}),it.selectAll(".cboutline").attr({x:Y,y:K+x.ypad+("top"===x.titleside?ot:0),width:Math.max(D,2),height:Math.max(s-2*x.ypad-ot,2)}).call(p.stroke,x.outlinecolor).style({fill:"None","stroke-width":x.outlinewidth});var l=({center:.5,right:1}[x.xanchor]||0)*a;it.attr("transform","translate("+(M.l-l)+","+M.t+")"),o.autoMargin(t,e,{x:x.x,y:x.y,l:a*({right:1,center:.5}[x.xanchor]||0),r:a*({left:1,center:.5}[x.xanchor]||0),t:s*({bottom:1,middle:.5}[x.yanchor]||0),b:s*({top:1,middle:.5}[x.yanchor]||0)})}var A=t._fullLayout,M=A._size;if("function"!=typeof x.fillcolor&&"function"!=typeof x.line.color)return void A._infolayer.selectAll("g."+e).remove();var T,E=n.extent(("function"==typeof x.fillcolor?x.fillcolor:x.line.color).domain()),L=[],S=[],C="function"==typeof x.line.color?x.line.color:function(){return x.line.color},z="function"==typeof x.fillcolor?x.fillcolor:function(){return x.fillcolor},P=x.levels.end+x.levels.size/100,R=x.levels.size,j=1.001*E[0]-.001*E[1],O=1.001*E[1]-.001*E[0];for(T=x.levels.start;0>(T-P)*R;T+=R)T>j&&O>T&&L.push(T);if("function"==typeof x.fillcolor)if(x.filllevels)for(P=x.filllevels.end+x.filllevels.size/100,R=x.filllevels.size,T=x.filllevels.start;0>(T-P)*R;T+=R)T>E[0]&&T1){var nt=Math.pow(10,Math.floor(Math.log(rt)/Math.LN10));tt*=nt*u.roundUp(rt/nt,[2,5,10]),(Math.abs(x.levels.start)/x.levels.size+1e-6)%1<2e-6&&(Q.tick0=0)}Q.dtick=tt}Q.domain=[W+H,W+V-H],Q.setScale();var it=A._infolayer.selectAll("g."+e).data([0]);it.enter().append("g").classed(e,!0).each(function(){var t=n.select(this);t.append("rect").classed("cbbg",!0),t.append("g").classed("cbfills",!0),t.append("g").classed("cblines",!0),t.append("g").classed("cbaxis",!0).classed("crisp",!0),t.append("g").classed("cbtitleunshift",!0).append("g").classed("cbtitle",!0),t.append("rect").classed("cboutline",!0),t.select(".cbtitle").datum(0)}),it.attr("transform","translate("+Math.round(M.l)+","+Math.round(M.t)+")");var at=it.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(M.l)+",-"+Math.round(M.t)+")");Q._axislayer=it.select(".cbaxis");var ot=0;if(-1!==["top","bottom"].indexOf(x.titleside)){var st,lt=M.l+(x.x+q)*M.w,ut=Q.titlefont.size;st="top"===x.titleside?(1-(W+V-H))*M.h+M.t+3+.75*ut:(1-(W+H))*M.h+M.t-3-.25*ut,w(Q._id+"title",{attributes:{x:lt,y:st,"text-anchor":"start"}})}var ct=u.syncOrAsync([o.previousPromises,_,o.previousPromises,k],t);if(ct&&ct.then&&(t._promises||[]).push(ct),t._context.editable){var ft,ht,pt;l.init({element:it.node(),prepFn:function(){ft=it.attr("transform"),f(it)},moveFn:function(t,e){it.attr("transform",ft+" translate("+t+","+e+")"),ht=l.align(X+t/M.w,B,0,1,x.xanchor),pt=l.align(W-e/M.h,V,0,1,x.yanchor);var r=l.getCursor(ht,pt,x.xanchor,x.yanchor);f(it,r)},doneFn:function(e){f(it),e&&void 0!==ht&&void 0!==pt&&a.restyle(t,{"colorbar.x":ht,"colorbar.y":pt},b().index)}})}return ct}function b(){var r,n,i=e.substr(2);for(r=0;rc*f?i.RdBu:c>=0?i.Reds:i.Blues,l.colorscale=h,s.reversescale&&(h=a(h)),s.colorscale=h)}},{"../../lib":1127,"./flip_scale":1059,"./scales":1066}],1056:[function(t,e,r){"use strict";var n=t("./attributes"),i=t("../../lib/extend").extendDeep;e.exports=function(t){return{color:{valType:"color",arrayOk:!0},colorscale:i({},n.colorscale,{}),cauto:i({},n.zauto,{}),cmax:i({},n.zmax,{}),cmin:i({},n.zmin,{}),autocolorscale:i({},n.autocolorscale,{}),reversescale:i({},n.reversescale,{})}}},{"../../lib/extend":1122,"./attributes":1054}],1057:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":1066}],1058:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./is_valid_scale"),l=t("./flip_scale");e.exports=function(t,e,r,u,c){var f=c.prefix,h=c.cLetter,p=f.slice(0,f.length-1),d=f?i.nestedProperty(t,p).get()||{}:t,g=f?i.nestedProperty(e,p).get()||{}:e,v=d[h+"min"],m=d[h+"max"],y=d.colorscale,b=n(v)&&n(m)&&m>v;u(f+h+"auto",!b),u(f+h+"min"),u(f+h+"max");var x;void 0!==y&&(x=!s(y)),u(f+"autocolorscale",x);var _=u(f+"colorscale"),w=u(f+"reversescale");if(w&&(g.colorscale=l(_)),"marker.line."!==f){var k;f&&(k=a(d));var A=u(f+"showscale",k);A&&o(d,g,r)}}},{"../../lib":1127,"../colorbar/defaults":1050,"../colorbar/has_colorbar":1052,"./flip_scale":1059,"./is_valid_scale":1063,"fast-isnumeric":90}],1059:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n}},{}],1060:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./default_scale"),a=t("./is_valid_scale_array");e.exports=function(t,e){function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return e||(e=i),t?("string"==typeof t&&(r(),"string"==typeof t&&r()),a(t)?t:e):e}},{"./default_scale":1057,"./is_valid_scale_array":1064,"./scales":1066}],1061:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("./is_valid_scale");e.exports=function(t,e){var r=e?i.nestedProperty(t,e).get()||{}:t,o=r.color,s=!1;if(Array.isArray(o))for(var l=0;lh;h++)l=t[h],c[h]=e+l[0]*(r-e),f[h]=i(l[1]).toRgb();var p=n.scale.linear().domain(c).interpolate(n.interpolateObject).range(f);return function(t){if(a(t)){var n=o.constrain(t,e,r),l=p(n);return i(l).toRgbString()}return i(t).isValid()?t:s.defaultLine}}},{"../../lib":1127,"../color":1048,d3:82,"fast-isnumeric":90,tinycolor2:1042}],1066:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]]}},{}],1067:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=(t-r)/(n-r),o=a+e/(n-r),s=(a+o)/2;return"left"===i||"bottom"===i?a:"center"===i||"middle"===i?s:"right"===i||"top"===i?o:2/3-s>a?a:o>4/3-s?o:s}},{}],1068:[function(t,e,r){"use strict";var n=t("../../lib"),i=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,a){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===a?0:"middle"===a?1:"top"===a?2:n.constrain(Math.floor(3*e),0,2),i[e][t]}},{"../../lib":1127}],1069:[function(t,e,r){"use strict";function n(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function i(t){t._dragging=!1,t._replotPending&&a.plot(t)}var a=t("../../plotly"),o=t("../../lib"),s=t("../../plots/cartesian/constants"),l=e.exports={};l.align=t("./align"),l.getCursor=t("./cursor");var u=t("./unhover");l.unhover=u.wrapped,l.unhoverRaw=u.raw,l.init=function(t){function e(e){return d._dragged=!1,d._dragging=!0,u=e.clientX,c=e.clientY,p=e.target,f=(new Date).getTime(),f-d._mouseDownTimev&&(g=Math.max(g-1,1)),t.doneFn&&t.doneFn(d._dragged,g),!d._dragged){var r=document.createEvent("MouseEvents");r.initEvent("click",!0,!0),p.dispatchEvent(r)}return i(d),d._dragged=!1,o.pauseEvent(e)}var u,c,f,h,p,d=o.getPlotDiv(t.element)||{},g=1,v=s.DBLCLICKDELAY;d._mouseDownTime||(d._mouseDownTime=0),t.element.onmousedown=e,t.element.style.pointerEvents="all"}},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/constants":1155,"./align":1067,"./cursor":1068,"./unhover":1070}],1070:[function(t,e,r){"use strict";var n=t("../../lib/events"),i=e.exports={};i.wrapped=function(t,e,r){"string"==typeof t&&(t=document.getElementById(t)),t._hoverTimer&&(clearTimeout(t._hoverTimer),t._hoverTimer=void 0),i.raw(t,e,r)},i.raw=function(t,e){var r=t._fullLayout;e||(e={}),e.target&&n.triggerHandler(t,"plotly_beforehover",e)===!1||(r._hoverlayer.selectAll("g").remove(),e.target&&t._hoverdata&&t.emit("plotly_unhover",{points:t._hoverdata}),t._hoverdata=void 0)}},{"../../lib/events":1121}],1071:[function(t,e,r){"use strict";function n(t,e,r,n){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],u=Math.pow(a*a+o*o,x/2),c=Math.pow(s*s+l*l,x/2),f=(c*c*a-u*u*s)*n,h=(c*c*o-u*u*l)*n,p=3*c*(u+c),d=3*u*(u+c);return[[i.round(e[0]+(p&&f/p),2),i.round(e[1]+(p&&h/p),2)],[i.round(e[0]-(d&&f/d),2),i.round(e[1]-(d&&h/d),2)]]}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../plots/plots"),s=t("../color"),l=t("../colorscale"),u=t("../../lib"),c=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),h=t("../../traces/scatter/subtypes"),p=t("../../traces/scatter/make_bubble_size_func"),d=e.exports={}; +d.font=function(t,e,r,n){e&&e.family&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(s.fill,n)},d.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},d.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},d.setRect=function(t,e,r,n,i){t.call(d.setPosition,e,r).call(d.setSize,n,i)},d.translatePoints=function(t,e,r,n,o,s){var l=o&&(o||{}).duration>0;if(l)var u=t.size();t.each(function(t,c){var f=t.xp||e.c2p(t.x),h=t.yp||r.c2p(t.y),p=i.select(this);if(a(f)&&a(h))if("text"===this.nodeName)p.attr("x",f).attr("y",h);else if(l){var g;s?-1===s?g=p.style("opacity",1).transition().duration(o.duration).ease(o.easing).style("opacity",0).remove():1===s&&(g=p.attr("transform","translate("+f+","+h+")"),n&&g.call(d.pointStyle,n),g.style("opacity",0).transition().duration(o.duration).ease(o.easing).style("opacity",1)):(g=p.transition().delay(o.delay+o.cascade/u*c).duration(o.duration).ease(o.easing).attr("transform","translate("+f+","+h+")"),n&&g.call(d.pointStyle,n))}else p.attr("transform","translate("+f+","+h+")");else p.remove()})},d.getPx=function(t,e){return Number(t.style(e).replace(/px$/,""))},d.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:1>e?1:Math.round(e):r||0},d.lineGroupStyle=function(t,e,r,n){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,l=n||a.dash||"";i.select(this).call(s.stroke,r||a.color).call(d.dashLine,l,o)})},d.dashLine=function(t,e,r){var n=Math.max(r,3);"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},d.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=i.select(this);try{r.call(s.fill,e[0].trace.fillcolor)}catch(n){u.error(n,t),r.remove()}})};var g=t("./symbol_defs");d.symbolNames=[],d.symbolFuncs=[],d.symbolNeedLines={},d.symbolNoDot={},d.symbolList=[],Object.keys(g).forEach(function(t){var e=g[t];d.symbolList=d.symbolList.concat([e.n,t,e.n+100,t+"-open"]),d.symbolNames[e.n]=t,d.symbolFuncs[e.n]=e.f,e.needLine&&(d.symbolNeedLines[e.n]=!0),e.noDot?d.symbolNoDot[e.n]=!0:d.symbolList=d.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"])});var v=d.symbolNames.length,m="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";d.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),t=d.symbolNames.indexOf(t),t>=0&&(t+=e)}return t%100>=v||t>=400?0:Math.floor(Math.max(t,0))},d.pointStyle=function(t,e){if(t.size()){var r=e.marker,n=r.line;if(o.traceIs(e,"symbols")){var a=p(e);t.attr("d",function(t){var n;n="various"===t.ms||"various"===r.size?3:h.isBubble(e)?a(t.ms):(r.size||6)/2,t.mrc=n;var i=d.symbolNumber(t.mx||r.symbol)||0,o=i%100;return t.om=i%200>=100,d.symbolFuncs[o](n)+(i>=200?m:"")}).style("opacity",function(t){return(t.mo+1||r.opacity+1)-1})}var l=(e._input||{}).marker||{},u=d.tryColorscale(r,l,""),c=d.tryColorscale(r,l,"line.");t.each(function(t,e){var a,o,l;t.so?(l=n.outlierwidth,o=n.outliercolor,a=r.outliercolor):(l=(t.mlw+1||n.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,o="mlc"in t?t.mlcc=c(t.mlc):Array.isArray(n.color)?r.color[e]:n.color,a="mc"in t?t.mcc=u(t.mc):Array.isArray(r.color)?r.color[e]:r.color||"rgba(0,0,0,0)");var f=i.select(this);t.om?f.call(s.stroke,a).style({"stroke-width":(l||1)+"px",fill:"none"}):(f.style("stroke-width",l+"px").call(s.fill,a),l&&f.call(s.stroke,o))})}},d.tryColorscale=function(t,e,r){var n=u.nestedProperty(t,r+"color").get(),i=u.nestedProperty(t,r+"colorscale").get(),o=u.nestedProperty(t,r+"cauto").get(),s=u.nestedProperty(t,r+"cmin"),c=u.nestedProperty(t,r+"cmax"),f=s.get(),h=c.get();return i&&Array.isArray(n)?(!o&&a(f)&&a(h)||(f=1/0,h=-(1/0),n.forEach(function(t){a(t)&&(f>t&&(f=+t),t>h&&(h=+t))}),f>h&&(f=0,h=1),s.set(f),c.set(h),u.nestedProperty(e,r+"cmin").set(f),u.nestedProperty(e,r+"cmax").set(h)),l.makeScaleFunction(i,f,h)):u.identity};var y={start:1,end:-1,middle:0,bottom:1,top:-1},b=1.3;d.textPointStyle=function(t,e){t.each(function(t){var r=i.select(this),n=t.tx||e.text;if(!n||Array.isArray(n))return void r.remove();var o=t.tp||e.textposition,s=-1!==o.indexOf("top")?"top":-1!==o.indexOf("bottom")?"bottom":"middle",l=-1!==o.indexOf("left")?"end":-1!==o.indexOf("right")?"start":"middle",u=t.ts||e.textfont.size,f=t.mrc?t.mrc/.8+1:0;u=a(u)&&u>0?u:0,r.call(d.font,t.tf||e.textfont.family,u,t.tc||e.textfont.color).attr("text-anchor",l).text(n).call(c.convertToTspans);var h=i.select(this.parentNode),p=r.selectAll("tspan.line"),g=((p[0].length||1)-1)*b+1,v=y[l]*f,m=.75*u+y[s]*f+(y[s]-1)*g*u/2;h.attr("transform","translate("+v+","+m+")"),g>1&&p.attr({x:r.attr("x"),y:r.attr("y")})})};var x=.5;d.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,i="M"+t[0],a=[];for(r=1;rr;r++)o.push(n(t[r-1],t[r],t[r+1],e));for(o.push(n(t[a-1],t[a],t[0],e)),r=1;a>=r;r++)i+="C"+o[r-1][1]+" "+o[r][0]+" "+t[r];return i+="C"+o[a][1]+" "+o[0][0]+" "+t[0]+"Z"};var _={hv:function(t,e){return"H"+i.round(e[0],2)+"V"+i.round(e[1],2)},vh:function(t,e){return"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},hvh:function(t,e){return"H"+i.round((t[0]+e[0])/2,2)+"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},vhv:function(t,e){return"V"+i.round((t[1]+e[1])/2,2)+"H"+i.round(e[0],2)+"V"+i.round(e[1],2)}},w=function(t,e){return"L"+i.round(e[0],2)+","+i.round(e[1],2)};d.steps=function(t){var e=_[t]||w;return function(t){for(var r="M"+i.round(t[0][0],2)+","+i.round(t[0][1],2),n=1;n=A&&(i.selectAll("[data-bb]").attr("data-bb",null),k=[]),t.setAttribute("data-bb",k.length),k.push(l),u.extendFlat({},l)},d.setClipUrl=function(t,e){if(!e)return void t.attr("clip-path",null);var r="#"+e,n=i.select("base");n.size()&&n.attr("href")&&(r=window.location.href+r),t.attr("clip-path","url("+r+")")}},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plots/plots":1199,"../../traces/scatter/make_bubble_size_func":1315,"../../traces/scatter/subtypes":1322,"../color":1048,"../colorscale":1062,"./symbol_defs":1072,d3:82,"fast-isnumeric":90}],1072:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+","+r+"H"+e+"L0,-"+i+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+",-"+r+"H"+e+"L0,"+i+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M"+r+",-"+e+"V"+e+"L-"+i+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+r+",-"+e+"V"+e+"L"+i+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(t*-.309,2),o=n.round(.809*t,2);return"M"+e+","+a+"L"+r+","+o+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(e*-.309,2),u=n.round(.118*e,2),c=n.round(.809*e,2),f=n.round(.382*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+u+"L"+o+","+c+"L0,"+f+"L-"+o+","+c+"L-"+a+","+u+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0}}},{d3:82}],1073:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"]},symmetric:{valType:"boolean"},array:{valType:"data_array"},arrayminus:{valType:"data_array"},value:{valType:"number",min:0,dflt:10},valueminus:{valType:"number",min:0,dflt:10},traceref:{valType:"integer",min:0,dflt:0},tracerefminus:{valType:"integer",min:0,dflt:0},copy_ystyle:{valType:"boolean"},copy_zstyle:{valType:"boolean"},color:{valType:"color"},thickness:{valType:"number",min:0,dflt:2},width:{valType:"number",min:0},_deprecated:{opacity:{valType:"number"}}}},{}],1074:[function(t,e,r){"use strict";function n(t,e,r,n){var a=e["error_"+n]||{},l=a.visible&&-1!==["linear","log"].indexOf(r.type),u=[];if(l){for(var c=s(a),f=0;fs;s++)o[s]={x:r[s],y:i[s]};return o[0].trace=t,n.calc({calcdata:[o],_fullLayout:e}),o},n.plot=t("./plot"),n.style=t("./style"),n.hoverInfo=function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys)),(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}},{"./attributes":1073,"./calc":1074,"./defaults":1076,"./plot":1078,"./style":1079}],1078:[function(t,e,r){"use strict";function n(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../lib"),s=t("../../traces/scatter/subtypes");e.exports=function(t,e){var r=e.x(),l=e.y();t.each(function(t){var e=t[0].trace,u=e.error_x||{},c=e.error_y||{},f=s.hasMarkers(e)&&e.marker.maxdisplayed>0;if(c.visible||u.visible){var h=i.select(this).selectAll("g.errorbar").data(o.identity);h.enter().append("g").classed("errorbar",!0),h.each(function(t){var e=i.select(this),o=n(t,r,l);if(!f||t.vis){var s;if(c.visible&&a(o.x)&&a(o.yh)&&a(o.ys)){var h=c.width;s="M"+(o.x-h)+","+o.yh+"h"+2*h+"m-"+h+",0V"+o.ys,o.noYS||(s+="m-"+h+",0h"+2*h),e.append("path").classed("yerror",!0).attr("d",s)}if(u.visible&&a(o.y)&&a(o.xh)&&a(o.xs)){var p=(u.copy_ystyle?c:u).width;s="M"+o.xh+","+(o.y-p)+"v"+2*p+"m0,-"+p+"H"+o.xs,o.noXS||(s+="m0,-"+p+"v"+2*p),e.append("path").classed("xerror",!0).attr("d",s)}}})}})}},{"../../lib":1127,"../../traces/scatter/subtypes":1322,d3:82,"fast-isnumeric":90}],1079:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(i.stroke,r.color),a.copy_ystyle&&(a=r),o.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(i.stroke,a.color)})}},{"../color":1048,d3:82}],1080:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants");e.exports={_isLinkedToArray:!0,source:{valType:"string"},layer:{valType:"enumerated",values:["below","above"],dflt:"above"},sizex:{valType:"number",dflt:0},sizey:{valType:"number",dflt:0},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain"},opacity:{valType:"number",min:0,max:1,dflt:1},x:{valType:"number",dflt:0},y:{valType:"number",dflt:0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper"}}},{"../../plots/cartesian/constants":1155}],1081:[function(t,e,r){"use strict";function n(t,e,r){function n(r,n){return a.coerce(t,e,o,r,n)}e=e||{},n("source"),n("layer"),n("x"),n("y"),n("xanchor"),n("yanchor"),n("sizex"),n("sizey"),n("sizing"),n("opacity");for(var s=0;2>s;s++){var l={_fullLayout:r},u=["x","y"][s];i.coerceRef(t,e,l,u,"paper")}return e}var i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./attributes");e.exports=function(t,e){if(t.images&&Array.isArray(t.images))for(var r=t.images,i=e.images=[],a=0;a=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],1085:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat;e.exports={bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.defaultLine},borderwidth:{valType:"number",min:0,dflt:0},font:a({},n,{}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"]},tracegroupgap:{valType:"number",min:0,dflt:10},x:{valType:"number",min:-2,max:3,dflt:1.02},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"}}},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047}],1086:[function(t,e,r){"use strict";e.exports={scrollBarWidth:4,scrollBarHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],1087:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/plots"),a=t("./attributes"),o=t("./helpers");e.exports=function(t,e,r){function s(t,e){return n.coerce(h,p,a,t,e)}for(var l,u,c,f,h=t.legend||{},p=e.legend={},d=0,g="normal",v=0;v1);if(y!==!1){if(s("bgcolor",e.paper_bgcolor),s("bordercolor"),s("borderwidth"),n.coerceFont(s,"font",e.font),s("orientation"),"h"===p.orientation){var b=t.xaxis;b&&b.rangeslider&&b.rangeslider.visible?(l=0,c="left",u=1.1,f="bottom"):(l=0,c="left",u=-.1,f="top")}s("traceorder",g),o.isGrouped(e.legend)&&s("tracegroupgap"),s("x",l),s("xanchor",c),s("y",u),s("yanchor",f),n.noneOrAll(h,p,["x","y"])}}},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1085,"./helpers":1090}],1088:[function(t,e,r){"use strict";function n(t,e){function r(r){c.util.convertToTspans(r,function(){r.selectAll("tspan.line").attr({x:r.attr("x")}),t.call(a,e)})}var n=t.data()[0][0],i=e._fullLayout,o=n.trace,s=h.traceIs(o,"pie"),l=o.index,u=s?n.label:o.name,f=t.selectAll("text.legendtext").data([0]);f.enter().append("text").classed("legendtext",!0),f.attr({x:40,y:0,"data-unformatted":u}).style("text-anchor","start").classed("user-select-none",!0).call(d.font,i.legend.font).text(u),e._context.editable&&!s?f.call(c.util.makeEditable).call(r).on("edit",function(t){this.attr({"data-unformatted":t}),this.text(t).call(r),this.text()||(t=" "),c.restyle(e,"name",t,l)}):f.call(r)}function i(t,e){var r=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(g.fill,"rgba(0,0,0,0)"),n.on("click",function(){if(!e._dragged){var n,i,a=t.data()[0][0],o=e._fullData,s=a.trace,l=s.legendgroup,u=[];if(h.traceIs(s,"pie")){var f=a.label,p=r.indexOf(f);-1===p?r.push(f):r.splice(p,1),c.relayout(e,"hiddenlabels",r)}else{if(""===l)u=[s.index];else for(var d=0;dtspan"),p=h[0].length||1;r=l*p,n=c.node()&&d.bBox(c.node()).width;var g=l*(.3+(1-p)/2);c.attr("y",g),h.attr("y",g)}r=Math.max(r,16)+3,a.attr({x:0,y:-r/2,height:r}),i.height=r,i.width=n}function o(t,e,r){var n=t._fullLayout,i=n.legend,a=i.borderwidth,o=b.isGrouped(i);if(b.isVertical(i))o&&e.each(function(t,e){f.setTranslate(this,0,e*i.tracegroupgap)}),i.width=0,i.height=0,r.each(function(t){var e=t[0],r=e.height,n=e.width;f.setTranslate(this,a,5+a+i.height+r/2),i.height+=r,i.width=Math.max(i.width,n)}),i.width+=45+2*a,i.height+=10+2*a,o&&(i.height+=(i._lgroupsLength-1)*i.tracegroupgap),r.selectAll(".legendtoggle").attr("width",(t._context.editable?0:i.width)+40),i.width=Math.ceil(i.width),i.height=Math.ceil(i.height);else if(o){i.width=0,i.height=0;for(var s=[i.width],l=e.data(),c=0,h=l.length;h>c;c++){var p=l[c].map(function(t){return t[0].width}),d=40+Math.max.apply(null,p);i.width+=i.tracegroupgap+d,s.push(i.width)}e.each(function(t,e){f.setTranslate(this,s[e],0)}),e.each(function(){var t=u.select(this),e=t.selectAll("g.traces"),r=0;e.each(function(t){var e=t[0],n=e.height;f.setTranslate(this,0,5+a+r+n/2),r+=n}),i.height=Math.max(i.height,r)}),i.height+=10+2*a,i.width+=2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}else i.width=0,i.height=0,r.each(function(t){var e=t[0],r=40+e.width,n=i.tracegroupgap||5;f.setTranslate(this,a+i.width,5+a+e.height/2),i.width+=n+r,i.height=Math.max(i.height,e.height)}),i.width+=2*a,i.height+=10+2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}function s(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center");var i="top";x.isBottomAnchor(r)?i="bottom":x.isMiddleAnchor(r)&&(i="middle"),h.autoMargin(t,"legend",{x:r.x,y:r.y,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:r.height*({top:1,middle:.5}[i]||0),t:r.height*({bottom:1,middle:.5}[i]||0)})}function l(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center"),h.autoMargin(t,"legend",{x:r.x,y:.5,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:0,t:0})}var u=t("d3"),c=t("../../plotly"),f=t("../../lib"),h=t("../../plots/plots"),p=t("../dragelement"),d=t("../drawing"),g=t("../color"),v=t("./constants"),m=t("./get_legend_data"),y=t("./style"),b=t("./helpers"),x=t("./anchor_utils");e.exports=function(t){function e(t,e){T.attr("data-scroll",e).call(f.setTranslate,0,e),E.call(d.setRect,F,t,v.scrollBarWidth,v.scrollBarHeight),A.select("rect").attr({y:b.borderwidth-e})}var r=t._fullLayout,a="legend"+r._uid;if(r._infolayer&&t.calcdata){var b=r.legend,_=r.showlegend&&m(t.calcdata,b),w=r.hiddenlabels||[];if(!r.showlegend||!_.length)return r._infolayer.selectAll(".legend").remove(),r._topdefs.select("#"+a).remove(),void h.autoMargin(t,"legend");var k=r._infolayer.selectAll("g.legend").data([0]);k.enter().append("g").attr({"class":"legend","pointer-events":"all"});var A=r._topdefs.selectAll("#"+a).data([0]);A.enter().append("clipPath").attr("id",a).append("rect");var M=k.selectAll("rect.bg").data([0]);M.enter().append("rect").attr({"class":"bg","shape-rendering":"crispEdges"}).call(g.stroke,b.bordercolor).call(g.fill,b.bgcolor).style("stroke-width",b.borderwidth+"px");var T=k.selectAll("g.scrollbox").data([0]);T.enter().append("g").attr("class","scrollbox");var E=k.selectAll("rect.scrollbar").data([0]);E.enter().append("rect").attr({"class":"scrollbar",rx:20,ry:2,width:0,height:0}).call(g.fill,"#808BA4");var L=T.selectAll("g.groups").data(_);L.enter().append("g").attr("class","groups"),L.exit().remove();var S=L.selectAll("g.traces").data(f.identity);S.enter().append("g").attr("class","traces"),S.exit().remove(),S.call(y).style("opacity",function(t){var e=t[0].trace;return h.traceIs(e,"pie")?-1!==w.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){u.select(this).call(n,t).call(i,t)});var C=0!==k.enter().size();C&&(o(t,L,S),s(t));var z=0,P=r.width,R=0,j=r.height;o(t,L,S),b.height>j?l(t):s(t);var O=r._size,I=O.l+O.w*b.x,N=O.t+O.h*(1-b.y);x.isRightAnchor(b)?I-=b.width:x.isCenterAnchor(b)&&(I-=b.width/2),x.isBottomAnchor(b)?N-=b.height:x.isMiddleAnchor(b)&&(N-=b.height/2);var F=b.width,D=O.w;F>D?(I=O.l,F=D):(I+F>P&&(I=P-F),z>I&&(I=z),F=Math.min(P-I,b.width));var B=b.height,U=O.h;B>U?(N=O.t,B=U):(N+B>j&&(N=j-B),R>N&&(N=R),B=Math.min(j-N,b.height)),f.setTranslate(k,I,N);var V,q,G=B-v.scrollBarHeight-2*v.scrollBarMargin,H=b.height-B;if(b.height<=B||t._context.staticPlot)M.attr({ +width:F-b.borderwidth,height:B-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2}),f.setTranslate(T,0,0),A.select("rect").attr({width:F-2*b.borderwidth,height:B-2*b.borderwidth,x:b.borderwidth,y:b.borderwidth}),T.call(d.setClipUrl,a);else{V=v.scrollBarMargin,q=T.attr("data-scroll")||0,M.attr({width:F-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin,height:B-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2}),A.select("rect").attr({width:F-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin,height:B-2*b.borderwidth,x:b.borderwidth,y:b.borderwidth-q}),T.call(d.setClipUrl,a),C&&e(V,q),k.on("wheel",null),k.on("wheel",function(){q=f.constrain(T.attr("data-scroll")-u.event.deltaY/G*H,-H,0),V=v.scrollBarMargin-q/H*G,e(V,q),u.event.preventDefault()}),E.on(".drag",null),T.on(".drag",null);var Y=u.behavior.drag().on("drag",function(){V=f.constrain(u.event.y-v.scrollBarHeight/2,v.scrollBarMargin,v.scrollBarMargin+G),q=-(V-v.scrollBarMargin)/G*H,e(V,q)});E.call(Y),T.call(Y)}if(t._context.editable){var X,W,Z,K;k.classed("cursor-move",!0),p.init({element:k.node(),prepFn:function(){var t=f.getTranslate(k);Z=t.x,K=t.y},moveFn:function(t,e){var r=Z+t,n=K+e;f.setTranslate(k,r,n),X=p.align(r,0,O.l,O.l+O.w,b.xanchor),W=p.align(n,0,O.t+O.h,O.t,b.yanchor)},doneFn:function(e){e&&void 0!==X&&void 0!==W&&c.relayout(t,{"legend.x":X,"legend.y":W})}})}}}},{"../../lib":1127,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"./anchor_utils":1084,"./constants":1086,"./get_legend_data":1089,"./helpers":1090,"./style":1092,d3:82}],1089:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("./helpers");e.exports=function(t,e){function r(t,r){if(""!==t&&i.isGrouped(e))-1===l.indexOf(t)?(l.push(t),u=!0,s[t]=[[r]]):s[t].push([r]);else{var n="~~i"+f;l.push(n),s[n]=[[r]],f++}}var a,o,s={},l=[],u=!1,c={},f=0;for(a=0;aa;a++)m=s[l[a]],y[a]=i.isReversed(e)?m.reverse():m;else{for(y=[new Array(b)],a=0;b>a;a++)m=s[l[a]][0],y[0][i.isReversed(e)?b-a-1:a]=m;b=1}return e._lgroupsLength=b,y}},{"../../plots/plots":1199,"./helpers":1090}],1090:[function(t,e,r){"use strict";var n=t("../../plots/plots");r.legendGetsTrace=function(t){return t.visible&&n.traceIs(t,"showLegend")},r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{"../../plots/plots":1199}],1091:[function(t,e,r){"use strict";var n=e.exports={};n.layoutAttributes=t("./attributes"),n.supplyLayoutDefaults=t("./defaults"),n.draw=t("./draw"),n.style=t("./style")},{"./attributes":1085,"./defaults":1087,"./draw":1088,"./style":1092}],1092:[function(t,e,r){"use strict";function n(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,n=p.hasLines(e),i=l.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);i.enter().append("path").classed("js-fill",!0),i.exit().remove(),i.attr("d","M5,0h30v6h-30z").call(f.fillGroupStyle);var a=l.select(this).select(".legendlines").selectAll("path").data(n?[t]:[]);a.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),a.exit().remove(),a.call(f.lineGroupStyle)}function i(t){function e(t,e,r){var n=u.nestedProperty(o,t).get(),i=Array.isArray(n)&&e?e(n):n;if(r){if(ir[1])return r[1]}return i}function r(t){return t[0]}var n,i,a=t[0],o=a.trace,s=p.hasMarkers(o),c=p.hasText(o),h=p.hasLines(o);if(s||c||h){var d={},g={};s&&(d.mc=e("marker.color",r),d.mo=e("marker.opacity",u.mean,[.2,1]),d.ms=e("marker.size",u.mean,[2,16]),d.mlc=e("marker.line.color",r),d.mlw=e("marker.line.width",u.mean,[0,5]),g.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),h&&(g.line={width:e("line.width",r,[0,10])}),c&&(d.tx="Aa",d.tp=e("textposition",r),d.ts=10,d.tc=e("textfont.color",r),d.tf=e("textfont.family",r)),n=[u.minExtend(a,d)],i=u.minExtend(o,g)}var v=l.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(s?n:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(f.pointStyle,i),s&&(n[0].mrc=3);var y=v.selectAll("g.pointtext").data(c?n:[]);y.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),y.exit().remove(),y.selectAll("text").call(f.textPointStyle,i)}function a(t){var e=t[0].trace,r=e.marker||{},n=r.line||{},i=l.select(this).select("g.legendpoints").selectAll("path.legendbar").data(c.traceIs(e,"bar")?[t]:[]);i.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),i.exit().remove(),i.each(function(t){var e=(t.mlw+1||n.width+1)-1,i=l.select(this);i.style("stroke-width",e+"px").call(h.fill,t.mc||r.color),e&&i.call(h.stroke,t.mlc||n.color)})}function o(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendbox").data(c.traceIs(e,"box")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(t){var r=(t.lw+1||e.line.width+1)-1,n=l.select(this);n.style("stroke-width",r+"px").call(h.fill,t.fc||e.fillcolor),r&&n.call(h.stroke,t.lc||e.line.color)})}function s(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendpie").data(c.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(d,t[0],e)}var l=t("d3"),u=t("../../lib"),c=t("../../plots/plots"),f=t("../drawing"),h=t("../color"),p=t("../../traces/scatter/subtypes"),d=t("../../traces/pie/style_one");e.exports=function(t){t.each(function(t){var e=l.select(this),r=e.selectAll("g.legendfill").data([t]);r.enter().append("g").classed("legendfill",!0);var n=e.selectAll("g.legendlines").data([t]);n.enter().append("g").classed("legendlines",!0);var i=e.selectAll("g.legendsymbols").data([t]);i.enter().append("g").classed("legendsymbols",!0),i.style("opacity",t[0].trace.opacity),i.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(a).each(o).each(s).each(n).each(i)}},{"../../lib":1127,"../../plots/plots":1199,"../../traces/pie/style_one":1299,"../../traces/scatter/subtypes":1322,"../color":1048,"../drawing":1071,d3:82}],1093:[function(t,e,r){"use strict";function n(t,e){var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o={};if("zoom"===n){for(var s,l,c="in"===i?.5:2,h=(1+c)/2,p=(1-c)/2,d=u.Axes.list(t,null,!0),v=0;vy;y++){var b=s[y];h=m[b]={};for(var x=0;x1)return n(["resetViews","toggleHover"]),o(v,r);c&&(n(["zoom3d","pan3d","orbitRotation","tableRotation"]),n(["resetCameraDefault3d","resetCameraLastSave3d"]),n(["hoverClosest3d"])),h&&(n(["zoomInGeo","zoomOutGeo","resetGeo"]),n(["hoverClosestGeo"]));var m=i(s),y=[];return((u||d)&&!m||g)&&(y=["zoom2d","pan2d"]),(u||g)&&a(l)&&(y.push("select2d"),y.push("lasso2d")),y.length&&n(y),!u&&!d||m||g||n(["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]),u&&p?n(["toggleHover"]):d?n(["hoverClosestGl2d"]):u?n(["hoverClosestCartesian","hoverCompareCartesian"]):p&&n(["hoverClosestPie"]),o(v,r)}function i(t){for(var e=l.Axes.list({_fullLayout:t},null,!0),r=!0,n=0;n0);if(h){var p=i(e,r,s);l("x",p[0]),l("y",p[1]),a.noneOrAll(t,e,["x","y"]),l("xanchor"),l("yanchor"),a.coerceFont(l,"font",r.font),l("bgcolor"),l("bordercolor"),l("borderwidth")}}},{"../../lib":1127,"./attributes":1096,"./button_attributes":1097,"./constants":1098}],1100:[function(t,e,r){"use strict";function n(t){for(var e=m.list(t,"x",!0),r=[],n=0;ne){var r=e;e=t,t=r}s.setAttributes(w,{"data-min":t,"data-max":e}),s.setAttributes(R,{x:t,width:e-t}),s.setAttributes(M,{width:t}),s.setAttributes(T,{x:e,width:d-e}),s.setAttributes(E,{transform:"translate("+(t-v-1)+")"}),s.setAttributes(C,{transform:"translate("+e+")"})}var f=t._fullLayout,h=f._infolayer.selectAll("g.range-slider"),p=f.xaxis.rangeslider,d=f._size.w,g=(f.height-f.margin.b-f.margin.t)*p.thickness,v=2,m=Math.floor(p.borderwidth/2),y=f.margin.l,b=f.height-g-f.margin.b,x=0,_=d,w=document.createElementNS(o,"g");s.setAttributes(w,{"class":"range-slider","data-min":x,"data-max":_,"pointer-events":"all",transform:"translate("+y+","+b+")"});var k=document.createElementNS(o,"rect"),A=p.borderwidth%2===0?p.borderwidth:p.borderwidth-1;s.setAttributes(k,{fill:p.bgcolor,stroke:p.bordercolor,"stroke-width":p.borderwidth,height:g+A,width:d+A,transform:"translate(-"+m+", -"+m+")","shape-rendering":"crispEdges"});var M=document.createElementNS(o,"rect");s.setAttributes(M,{x:0,width:x,height:g,fill:"rgba(0,0,0,0.4)"});var T=document.createElementNS(o,"rect");s.setAttributes(T,{x:_,width:d-_,height:g,fill:"rgba(0,0,0,0.4)"});var E=document.createElementNS(o,"g"),L=document.createElementNS(o,"rect"),S=document.createElementNS(o,"rect");s.setAttributes(E,{transform:"translate("+(x-v-1)+")"}),s.setAttributes(L,{width:10,height:g,x:-6,fill:"transparent",cursor:"col-resize"}),s.setAttributes(S,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(E,[S,L]);var C=document.createElementNS(o,"g"),z=document.createElementNS(o,"rect"),P=document.createElementNS(o,"rect");s.setAttributes(C,{transform:"translate("+_+")"}),s.setAttributes(z,{width:10,height:g,x:-2,fill:"transparent",cursor:"col-resize"}),s.setAttributes(P,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(C,[P,z]);var R=document.createElementNS(o,"rect");s.setAttributes(R,{x:x,width:_-x,height:g,cursor:"ew-resize",fill:"transparent"}),w.addEventListener("mousedown",function(t){function r(t){var r,n,f=+t.clientX-a;switch(i){case R:w.style.cursor="ew-resize",r=+s+f,n=+l+f,c(r,n),u(e(r),e(n));break;case L:w.style.cursor="col-resize",r=+s+f,n=+l,c(r,n),u(e(r),e(n));break;case z:w.style.cursor="col-resize",r=+s,n=+l+f,c(r,n),u(e(r),e(n));break;default:w.style.cursor="ew-resize",r=o,n=o+f,c(r,n),u(e(r),e(n))}}function n(){window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n),w.style.cursor="auto"}var i=t.target,a=t.clientX,o=a-w.getBoundingClientRect().left,s=w.getAttribute("data-min"),l=w.getAttribute("data-max");window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)}),p.range||(p.range=i.getAutoRange(f.xaxis));var j=l(t,d,g);s.appendChildren(w,[k,j,M,T,R,E,C]),r(f.xaxis.range[0],f.xaxis.range[1]),h.data([0]).enter().append(function(){return p.setRange=r,w})}},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"./helpers":1106,"./range_plot":1108}],1105:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(t,e){return n.coerce(s,l,i,t,e)}if(t[r].rangeslider){var s="object"==typeof t[r].rangeslider?t[r].rangeslider:{},l=e[r].rangeslider={};if(o("bgcolor"),o("bordercolor"),o("borderwidth"),o("thickness"),o("visible"),o("range"),l.range&&!e[r].autorange){var u=l.range,c=e[r].range;u[0]=Math.min(u[0],c[0]),u[1]=Math.max(u[1],c[1])}else e[r]._needsExpand=!0;l.visible&&a.forEach(function(t){var r=e[t]||{};r.fixedrange=!0,e[t]=r})}}},{"../../lib":1127,"./attributes":1103}],1106:[function(t,e,r){"use strict";r.setAttributes=function(t,e){for(var r in e)t.setAttribute(r,e[r])},r.appendChildren=function(t,e){for(var r=0;rl;l++){var u=s[l],c={_fullLayout:e},f=x.coerceRef(t,n,c,u);if("path"!==o){var h=.25,p=.75;if("paper"!==f){var d=x.getFromId(c,f),g=a(d);h=g(d.range[0]+h*(d.range[1]-d.range[0])),p=g(d.range[0]+p*(d.range[1]-d.range[0]))}r(u+"0",h),r(u+"1",p)}}return"path"===o?r("path"):b.noneOrAll(t,n,["x0","x1","y0","y1"]),n}function i(t){return"category"===t.type?t.c2l:t.d2l}function a(t){return"category"===t.type?t.l2c:t.l2d}function o(t,e){t.layout.shapes=e,k.supplyLayoutDefaults(t.layout,t._fullLayout),k.drawAll(t)}function s(t){delete t.layout.shapes,t._fullLayout.shapes=[],k.drawAll(t)}function l(t,e,r){for(var n=0;ne;i--)h(t,i).selectAll('[data-index="'+(i-1)+'"]').attr("data-index",i),k.draw(t,i)}function f(t,e,r,o){function s(e){var r=e.append("path").attr(z).style("opacity",S.opacity).call(_.stroke,P).call(_.fill,S.fillcolor).call(w.dashLine,S.line.dash,S.line.width);C&&r.call(w.setClipUrl,"clip"+t._fullLayout._uid+C)}var l,u;h(t,e).selectAll('[data-index="'+e+'"]').remove();var c=t.layout.shapes[e];if(c){var f={xref:c.xref,yref:c.yref},d={};"string"==typeof r&&r?d[r]=o:b.isPlainObject(r)&&(d=r);var v=Object.keys(d);for(l=0;ll;l++){var k=y[l];if(void 0===d[k]&&void 0!==c[k]){var A,M=k.charAt(0),T=x.getFromId(t,x.coerceRef(f,{},t,M)),E=x.getFromId(t,x.coerceRef(c,{},t,M)),L=c[k];void 0!==d[M+"ref"]&&(T?(A=i(T)(L),L=(A-T.range[0])/(T.range[1]-T.range[0])):L=(L-E.domain[0])/(E.domain[1]-E.domain[0]),E?(A=E.range[0]+L*(E.range[1]-E.range[0]),L=a(E)(A)):L=T.domain[0]+L*(T.domain[1]-T.domain[0])),c[k]=L}}var S=n(c,t._fullLayout);t._fullLayout.shapes[e]=S;var C,z={"data-index":e,"fill-rule":"evenodd",d:g(t,S)},P=S.line.width?S.line.color:"rgba(0,0,0,0)";if("below"!==S.layer)C=(S.xref+S.yref).replace(/paper/g,""),s(t._fullLayout._shapeUpperLayer);else if("paper"===S.xref&&"paper"===S.yref)C="",s(t._fullLayout._shapeLowerLayer);else{var R,j=t._fullLayout._plots||{},O=Object.keys(j);for(l=0,u=O.length;u>l;l++)R=j[O[l]],C=O[l],p(t,S,R)&&s(R.shapelayer)}}}function h(t,e){var r=t._fullLayout.shapes[e],n=t._fullLayout._shapeUpperLayer;return r?"below"===r.layer&&(n="paper"===r.xref&&"paper"===r.yref?t._fullLayout._shapeLowerLayer:t._fullLayout._shapeSubplotLayer):b.log("getShapeLayer: undefined shape: index",e),n}function p(t,e,r){var n=y.Axes.getFromId(t,r.id,"x")._id,i=y.Axes.getFromId(t,r.id,"y")._id,a="below"===e.layer,o=n===e.xref||i===e.yref,s=!!r.shapelayer;return a&&o&&s}function d(t){return function(e){return t(e.replace("_"," "))}}function g(t,e){var r,n,a,o,s=e.type,l=x.getFromId(t,e.xref),u=x.getFromId(t,e.yref),c=t._fullLayout._size;if(l?(r=i(l),n=function(t){return l._offset+l.l2p(r(t,!0))}):n=function(t){return c.l+c.w*t},u?(a=i(u),o=function(t){return u._offset+u.l2p(a(t,!0))}):o=function(t){return c.t+c.h*(1-t)},"path"===s)return l&&"date"===l.type&&(n=d(n)),u&&"date"===u.type&&(o=d(o)),k.convertPath(e.path,n,o);var f=n(e.x0),h=n(e.x1),p=o(e.y0),g=o(e.y1);if("line"===s)return"M"+f+","+p+"L"+h+","+g;if("rect"===s)return"M"+f+","+p+"H"+h+"V"+g+"H"+f+"Z";var v=(f+h)/2,m=(p+g)/2,y=Math.abs(v-f),b=Math.abs(m-p),_="A"+y+","+b,w=v+y+","+m,A=v+","+(m-b);return"M"+w+_+" 0 1,1 "+A+_+" 0 0,1 "+w+"Z"}function v(t,e,r,n,i){var a="category"===t.type?Number:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var o,s,l,u,c,f=1/0,h=-(1/0),p=n.match(A);for("date"===t.type&&(a=d(a)),o=0;oc&&(f=c),c>h&&(h=c)));return h>=f?[f,h]:void 0}}var m=t("fast-isnumeric"),y=t("../../plotly"),b=t("../../lib"),x=t("../../plots/cartesian/axes"),_=t("../color"),w=t("../drawing"),k=e.exports={};k.layoutAttributes=t("./attributes"),k.supplyLayoutDefaults=function(t,e){for(var r=t.shapes||[],i=e.shapes=[],a=0;as&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),b.log("Ignoring extra params in segment "+t)),i+l})},k.calcAutorange=function(t){var e,r,n,i,a,o=t._fullLayout,s=o.shapes;if(s.length&&t._fullData.length)for(e=0;eh?r=h:(c.left-=b.offsetLeft,c.right-=b.offsetLeft,c.top-=b.offsetTop,c.bottom-=b.offsetTop,b.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(c,t,u)&&(r=Math.max(r,o*(t[b.side]-c[a])+u))}),r=Math.min(h,r)),r>0||0>h){var p={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[b.side];e.attr("transform","translate("+p+")")}}}function d(){E=0,L=!0,S=z,k._infolayer.select("."+e).attr({"data-unformatted":S}).text(S).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)})}var g=r.propContainer,v=r.propName,m=r.traceIndex,y=r.dfltName,b=r.avoid||{},x=r.attributes,_=r.transform,w=r.containerGroup,k=t._fullLayout,A=g.titlefont.family,M=g.titlefont.size,T=g.titlefont.color,E=1,L=!1,S=g.title.trim();""===S&&(E=0),S.match(/Click to enter .+ title/)&&(E=.2,L=!0),w||(w=k._infolayer.selectAll(".g-"+e).data([0]),w.enter().append("g").classed("g-"+e,!0));var C=w.selectAll("text").data([0]);C.enter().append("text"),C.text(S).attr("class",e),C.attr({"data-unformatted":S}).call(f);var z="Click to enter "+y+" title";t._context.editable?(S||d(),C.call(c.makeEditable).on("edit",function(e){void 0!==m?a.restyle(t,v,e,m):a.relayout(t,v,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(f)}).on("input",function(t){this.text(t||" ").attr(x).selectAll("tspan.line").attr(x)})):S&&!S.match(/Click to enter .+ title/)||C.remove(),C.classed("js-placeholder",L)}},{"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../drawing":1071,d3:82,"fast-isnumeric":90}],1112:[function(t,e,r){"use strict";e.exports={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}},{}],1113:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],1114:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],1115:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],1116:[function(t,e,r){"use strict";var n=t("./plotly");r.version="1.13.0",r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.animate=n.animate,r.relayout=n.relayout,r.redraw=n.redraw,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.setPlotConfig=t("./plot_api/set_plot_config"),r.register=n.register,r.toImage=t("./plot_api/to_image"),r.downloadImage=t("./snapshot/download"),r.Icons=t("../build/ploticon"),r.Plots=n.Plots,r.Fx=n.Fx,r.Snapshot=n.Snapshot,r.PlotSchema=n.PlotSchema,r.Queue=n.Queue,r.d3=t("d3")},{"../build/ploticon":2,"./plot_api/set_plot_config":1145,"./plot_api/to_image":1146,"./plotly":1147,"./snapshot/download":1214,d3:82}],1117:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],1118:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){Array.isArray(t)&&(e[r]=t[n])}},{}],1119:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("./nested_property"),o=t("../components/colorscale/get_scale"),s=(Object.keys(t("../components/colorscale/scales")),/^([2-9]|[1-9][0-9]+)$/);r.valObjects={data_array:{coerceFunction:function(t,e,r){Array.isArray(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)}},"boolean":{coerceFunction:function(t,e,r){t===!0||t===!1?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,i){!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if(n.strict===!0&&"string"!=typeof t)return void e.set(r);var i=String(t);void 0===t||n.noBlank===!0&&!i?e.set(r):e.set(i)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?(Math.abs(t)>180&&(t-=360*Math.round(t/360)),e.set(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r){var n=r.length;return"string"==typeof t&&t.substr(0,n)===r&&s.test(t.substr(n))?void e.set(t):void e.set(r)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"!=typeof t)return void e.set(r);if(-1!==n.extras.indexOf(t))return void e.set(t);for(var i=t.split("+"),a=0;a2)return!1;var l=o[0].split("-");if(l.length>3||3!==l.length&&o[1])return!1;if(4===l[0].length)r=Number(l[0]);else{if(2!==l[0].length)return!1;var u=(new Date).getFullYear();r=((Number(l[0])-u+70)%100+200)%100+u-70}return s(r)?1===l.length?new Date(r,0,1).getTime():(n=Number(l[1])-1,l[1].length>2||!(n>=0&&11>=n)?!1:2===l.length?new Date(r,n,1).getTime():(i=Number(l[2]),l[2].length>2||!(i>=1&&31>=i)?!1:(i=new Date(r,n,i).getTime(),o[1]?(l=o[1].split(":"),l.length>3?!1:(a=Number(l[0]),l[0].length>2||!(a>=0&&23>=a)?!1:(i+=36e5*a,1===l.length?i:(n=Number(l[1]),l[1].length>2||!(n>=0&&59>=n)?!1:(i+=6e4*n,2===l.length?i:(t=Number(l[2]),t>=0&&60>t?i+1e3*t:!1)))))):i))):!1},r.isDateTime=function(t){return r.dateTime2ms(t)!==!1},r.ms2DateTime=function(t,e){if("undefined"==typeof o)return void l.error("d3 is not defined.");e||(e=0);var r=new Date(t),i=o.time.format("%Y-%m-%d")(r);return 7776e6>e?(i+=" "+n(r.getHours(),2),432e6>e&&(i+=":"+n(r.getMinutes(),2),108e5>e&&(i+=":"+n(r.getSeconds(),2),3e5>e&&(i+="."+n(r.getMilliseconds(),3)))),i.replace(/([:\s]00)*\.?[0]*$/,"")):i};var u={H:["%H:%M:%S~%L","%H:%M:%S","%H:%M"],I:["%I:%M:%S~%L%p","%I:%M:%S%p","%I:%M%p"],D:["%H","%I%p","%Hh"]},c={Y:["%Y~%m~%d","%Y%m%d","%y%m%d","%m~%d~%Y","%d~%m~%Y"],Yb:["%b~%d~%Y","%d~%b~%Y","%Y~%d~%b","%Y~%b~%d"],y:["%m~%d~%y","%d~%m~%y","%y~%m~%d"],yb:["%b~%d~%y","%d~%b~%y","%y~%d~%b","%y~%b~%d"]},f=o.time.format.utc,h={Y:{H:["%Y~%m~%dT%H:%M:%S","%Y~%m~%dT%H:%M:%S~%L"].map(f),I:[],D:["%Y%m%d%H%M%S","%Y~%m","%m~%Y"].map(f)},Yb:{H:[],I:[],D:["%Y~%b","%b~%Y"].map(f)},y:{H:[],I:[],D:[]},yb:{H:[],I:[],D:[]}};["Y","Yb","y","yb"].forEach(function(t){c[t].forEach(function(e){h[t].D.push(f(e)),["H","I","D"].forEach(function(r){u[r].forEach(function(n){var i=h[t][r];i.push(f(e+"~"+n)),i.push(f(n+"~"+e))})})})});var p=/[a-z]*/g,d=function(t){return t.substr(0,3)},g=/(mon|tue|wed|thu|fri|sat|sun|the|of|st|nd|rd|th)/g,v=/[\s,\/\-\.\(\)]+/g,m=/~?([ap])~?m(~|$)/,y=function(t,e){return e+"m "},b=/\d\d\d\d/,x=/(^|~)[a-z]{3}/,_=/[ap]m/,w=/:/,k=/q([1-4])/,A=["31~mar","30~jun","30~sep","31~dec"],M=function(t,e){return A[e-1]},T=/ ?([+\-]\d\d:?\d\d|Z)$/;r.parseDate=function(t){if(t.getTime)return t;if("string"!=typeof t)return!1;t=t.toLowerCase().replace(p,d).replace(g,"").replace(v,"~").replace(m,y).replace(k,M).trim().replace(T,"");var e,r,n=null,o=i(t),s=a(t);e=h[o][s],r=e.length;for(var l=0;r>l&&!(n=e[l].parse(t));l++);if(!(n instanceof Date))return!1;var u=n.getTimezoneOffset();return n.setTime(n.getTime()+60*u*1e3),n}},{"../lib":1127,d3:82,"fast-isnumeric":90}],1121:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i={init:function(t){if(t._ev instanceof n)return t;var e=new n;return t._ev=e,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t.emit=function(r,n){"undefined"!=typeof jQuery&&jQuery(t).trigger(r,n),e.emit(r,n)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;ld;d++){o=t[d];for(s in o)l=h[s],u=o[s],e&&u&&(i(u)||(c=a(u)))?(c?(c=!1,f=l&&a(l)?l:[]):f=l&&i(l)?l:{},h[s]=n([f,u],e,r)):("undefined"!=typeof u||r)&&(h[s]=u)}return h}var i=t("./is_plain_object.js"),a=Array.isArray;r.extendFlat=function(){return n(arguments,!1,!1)},r.extendDeep=function(){return n(arguments,!0,!1)},r.extendDeepAll=function(){return n(arguments,!0,!0)}},{"./is_plain_object.js":1128}],1123:[function(t,e,r){"use strict";e.exports=function(t){for(var e=[],r=0;ry;y++)f=s(d,y),p=l(e,y),m[y]=n(f,p);else m=n(d,e);return m}var s=t("tinycolor2"),l=t("fast-isnumeric"),u=t("../components/colorscale/make_scale_function"),c=t("../components/color/attributes").defaultLine,f=t("./str2rgbarray"),h=1;e.exports=o},{"../components/color/attributes":1047,"../components/colorscale/make_scale_function":1065,"./str2rgbarray":1139,"fast-isnumeric":90,tinycolor2:1042}],1126:[function(t,e,r){"use strict";function n(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(e>r)break;t=t.slice(0,e)+l(t.slice(e+5,r))+t.slice(r+6)}return t}function i(t){return t.replace(/\/g,"\n")}function a(t){return t.replace(/\<.*\>/g,"")}function o(t){for(var e=0;(e=t.indexOf("&",e))>=0;){var r=t.indexOf(";",e);if(e>r)e+=1;else{var n=u[t.slice(e+1,r)];t=n?t.slice(0,e)+n+t.slice(r+1):t.slice(0,e)+t.slice(r+1)}}return t}function s(t){return""+o(a(n(i(t))))}var l=t("superscript-text"),u={mu:"\u03bc",amp:"&",lt:"<",gt:">"};e.exports=s},{"superscript-text":1041}],1127:[function(t,e,r){"use strict";var n=t("d3"),i=e.exports={};i.nestedProperty=t("./nested_property"),i.isPlainObject=t("./is_plain_object");var a=t("./coerce");i.valObjects=a.valObjects,i.coerce=a.coerce,i.coerce2=a.coerce2,i.coerceFont=a.coerceFont;var o=t("./dates");i.dateTime2ms=o.dateTime2ms,i.isDateTime=o.isDateTime,i.ms2DateTime=o.ms2DateTime,i.parseDate=o.parseDate;var s=t("./search");i.findBin=s.findBin,i.sorterAsc=s.sorterAsc,i.sorterDes=s.sorterDes,i.distinctVals=s.distinctVals,i.roundUp=s.roundUp;var l=t("./stats");i.aggNums=l.aggNums,i.len=l.len,i.mean=l.mean,i.variance=l.variance,i.stdev=l.stdev,i.interp=l.interp;var u=t("./matrix");i.init2dArray=u.init2dArray,i.transposeRagged=u.transposeRagged,i.dot=u.dot,i.translationMatrix=u.translationMatrix,i.rotationMatrix=u.rotationMatrix,i.rotationXYMatrix=u.rotationXYMatrix,i.apply2DTransform=u.apply2DTransform,i.apply2DTransform2=u.apply2DTransform2;var c=t("./extend");i.extendFlat=c.extendFlat,i.extendDeep=c.extendDeep,i.extendDeepAll=c.extendDeepAll;var f=t("./loggers");i.log=f.log,i.warn=f.warn,i.error=f.error,i.notifier=t("./notifier"),i.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},i.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},i.identity=function(t){return t},i.randstr=function h(t,e,r){if(r||(r=16),void 0===e&&(e=24),0>=e)return"0";var n,i,a,o=Math.log(Math.pow(2,e))/Math.log(r),s="";for(n=2;o===1/0;n*=2)o=Math.log(Math.pow(2,e/n))/Math.log(r)*n;var l=o-Math.floor(o);for(n=0;n-1||u!==1/0&&u>=Math.pow(2,e)?h(t,e,r):s},i.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={};return r.optionList=[],r._newoption=function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)},r["_"+e]=t,r},i.smooth=function(t,e){if(e=Math.round(e)||0,2>e)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;l>r;r++)u[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;o>r;r++){for(a=0,n=0;l>n;n++)i=r+n+1-e,-o>i?i-=s*Math.round(i/s):i>=s&&(i-=s*Math.floor(i/s)),0>i?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},i.syncOrAsync=function(t,e,r){function n(){return i.syncOrAsync(t,e,r)}for(var a,o;t.length;)if(o=t.splice(0,1)[0],a=o(e),a&&a.then)return a.then(n).then(void 0,i.promiseError);return r&&r(e)},i.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},i.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;ni;i++)e[i][r]=t[i]},i.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,o,s=3,l=Object.keys(t);for(n=0;n1?n+a[1]:"";if(i&&(a.length>1||o.length>4))for(;r.test(o);)o=o.replace(r,"$1"+i+"$2");return o+s},i.deepClone=function p(t,e,r){var n,i,a="__getDeepCircularCopy__";if(t!==Object(t))return t;var o,s=a in t,l=t[a];if(s&&"function"==typeof l)return l();if(t[a]=function(){return o},t instanceof Array){o=[];for(var u=0;u1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;en;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,i=t.length;for(e=0;i>e;e++)n=Math.max(n,t[e].length);var a=new Array(n);for(e=0;n>e;e++)for(a[e]=new Array(i),r=0;i>r;r++)a[e][r]=t[r][e];return a},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,i,a=t.length;if(t[0].length)for(n=new Array(a),i=0;a>i;i++)n[i]=r.dot(t[i],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),i=0;ii;i++)n+=t[i]*e[i];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],1131:[function(t,e,r){"use strict";function n(t,e){return function(){var r,i,a,o,s,l=t;for(o=0;o=0;e--){ +if(n=t[e],o=!1,Array.isArray(n))for(r=n.length-1;r>=0;r--)u(n[r])?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)u(n[a[r]])&&!i(n[a[r]],a[r])?delete n[a[r]]:o=!0;if(o)return}}function u(t){return void 0===t||null===t?!0:"object"!=typeof t?!1:Array.isArray(t)?!t.length:!Object.keys(t).length}function c(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}var f=t("fast-isnumeric");e.exports=function(t,e){if(f(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,l=e.split(".");sr||r>a||o>n||n>s?!1:!e||!u(t)}function r(t,e){var r=t[0],l=t[1];if(i>r||r>a||o>l||l>s)return!1;var u,c,f,h,p,d=n.length,g=n[0][0],v=n[0][1],m=0;for(u=1;d>u;u++)if(c=g,f=v,g=n[u][0],v=n[u][1],h=Math.min(c,g),!(h>r||r>Math.max(c,g)||l>Math.max(f,v)))if(l=l&&r!==h&&m++}return m%2===1}var n=t.slice(),i=n[0][0],a=i,o=n[0][1],s=o;n.push(n[0]);for(var l=1;la;a++)if(o=[t[a][0]-l[0],t[a][1]-l[1]],s=n(o,u),0>s||s>c||Math.abs(n(o,h))>i)return!0;return!1};i.filter=function(t,e){function r(r){t.push(r);var s=n.length,l=i;n.splice(o+1);for(var u=l+1;u1){var s=t.pop();r(s)}return{addPt:r,raw:t,filtered:n}}},{"./matrix":1130}],1134:[function(t,e,r){"use strict";function n(t,e){for(var r,n=[],a=0;a=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;rt}function i(t,e){return e>=t}function a(t,e){return t>e}function o(t,e){return t>=e}var s=t("fast-isnumeric"),l=t("../lib");r.findBin=function(t,e,r){if(s(e.start))return r?Math.ceil((t-e.start)/e.size)-1:Math.floor((t-e.start)/e.size);var u,c,f=0,h=e.length,p=0;for(c=e[e.length-1]>=e[0]?r?n:i:r?o:a;h>f&&p++<100;)u=Math.floor((f+h)/2),c(e[u],t)?f=u+1:h=u;return p>90&&l.log("Long binary search..."),f-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;n>s;s++)e[s+1]>e[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;a>i&&o++<100;)n=u((i+a)/2),e[n]<=t?i=n+s:a=n-l;return e[i]}},{"../lib":1127,"fast-isnumeric":90}],1136:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],1137:[function(t,e,r){"use strict";var n=t("../components/color"),i=function(){};e.exports=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=i);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=n.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1}},{"../components/color":1048}],1138:[function(t,e,r){"use strict";var n=t("fast-isnumeric");r.aggNums=function(t,e,i,a){var o,s;if(a||(a=i.length),n(e)||(e=!1),Array.isArray(i[0])){for(s=new Array(a),o=0;a>o;o++)s[o]=r.aggNums(t,e,i[o]);i=s}for(o=0;a>o;o++)n(e)?n(i[o])&&(e=t(+e,+i[o])):e=i[o];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.variance=function(t,e,i){return e||(e=r.len(t)),n(i)||(i=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-i,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if(e=e*t.length-.5,0>e)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"fast-isnumeric":90}],1139:[function(t,e,r){"use strict";function n(t){return t=i(t),a.str2RgbaArray(t.toRgbString())}var i=t("tinycolor2"),a=t("arraytools");e.exports=n},{arraytools:64,tinycolor2:1042}],1140:[function(t,e,r){"use strict";function n(t,e){return t.node().getBoundingClientRect()[e]}function i(t){return t.replace(/(<|<|<)/g,"\\lt ").replace(/(>|>|>)/g,"\\gt ")}function a(t,e,r){var n="math-output-"+l.Lib.randstr([],64),a=u.select("body").append("div").attr({id:n}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text(i(t));MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var e=u.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())c.log("There was an error in the tex syntax.",t),r();else{var n=a.select("svg").node().getBoundingClientRect();r(a.select(".MathJax_SVG"),e,n)}a.remove()})}function o(t){for(var e=l.util.html_entity_decode(t),r=e.split(/(<[^<>]*>)/).map(function(t){var e=t.match(/<(\/?)([^ >]*)\s*(.*)>/i),r=e&&e[2].toLowerCase(),n=p[r];if(void 0!==n){var i=e[1],a=e[3],o=a.match(/^style\s*=\s*"([^"]+)"\s*/i);if("a"===r){if(i)return"";if("href"!==a.substr(0,4).toLowerCase())return"";var s=document.createElement("a");return s.href=a.substr(4).replace(/["'=]/g,""),-1===d.indexOf(s.protocol)?"":'"}if("br"===r)return"
";if(i)return"sup"===r?'':"sub"===r?'':"";var u=""}return l.util.xml_entity_encode(t).replace(/");i>0;i=r.indexOf("
",i+1))n.push(i);var a=0;n.forEach(function(t){for(var e=t+a,n=r.slice(0,e),i="",o=n.length-1;o>=0;o--){var s=n[o].match(/<(\/?).*>/i);if(s&&"
"!==n[o]){s[1]||(i=n[o]);break}}i&&(r.splice(e+1,0,i),r.splice(e,0,""),a+=2)});var o=r.join(""),s=o.split(/
/gi);return s.length>1&&(r=s.map(function(t,e){return''+t+""})),r.join("")}function s(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}var l=t("../plotly"),u=t("d3"),c=t("../lib"),f=t("../constants/xmlns_namespaces"),h=e.exports={};u.selection.prototype.appendSVG=function(t){for(var e=['',t,""].join(""),r=(new DOMParser).parseFromString(e,"application/xml"),n=r.documentElement.firstChild;n;)this.node().appendChild(this.node().ownerDocument.importNode(n,!0)),n=n.nextSibling;return r.querySelector("parsererror")?(c.log(r.querySelector("parsererror div").textContent),null):u.select(this.node().lastChild)},h.html_entity_decode=function(t){var e=u.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"<"===t?"<":"&rt;"===t?">":e.html(t).text()});return e.remove(),r},h.xml_entity_encode=function(t){return t.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")},h.convertToTspans=function(t,e){function r(){p.empty()||(d=c.attr("class")+"-math",p.select("svg."+d).remove()),t.text("").style({visibility:"visible","white-space":"pre"}),h=t.appendSVG(s),h||t.text(i),t.select("a").size()&&t.style("pointer-events","all"),e&&e.call(c)}var i=t.text(),s=o(i),c=t,f=!c.attr("data-notex")&&s.match(/([^$]*)([$]+[^$]*[$]+)([^$]*)/),h=i,p=u.select(c.node().parentNode);if(!p.empty()){var d=c.attr("class")?c.attr("class").split(" ")[0]:"text";d+="-math",p.selectAll("svg."+d).remove(),p.selectAll("g."+d+"-group").remove(),t.style({visibility:null});for(var g=t.node();g&&g.removeAttribute;g=g.parentNode)g.removeAttribute("data-bb");if(f){var v=l.Lib.getPlotDiv(c.node());(v&&v._promises||[]).push(new Promise(function(t){c.style({visibility:"hidden"});var i={fontSize:parseInt(c.style("font-size"),10)};a(f[2],i,function(i,a,o){p.selectAll("svg."+d).remove(),p.selectAll("g."+d+"-group").remove();var s=i&&i.select("svg");if(!s||!s.node())return r(),void t();var l=p.append("g").classed(d+"-group",!0).attr({"pointer-events":"none"});l.node().appendChild(s.node()),a&&a.node()&&s.node().insertBefore(a.node().cloneNode(!0),s.node().firstChild),s.attr({"class":d,height:o.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var u=c.style("fill")||"black";s.select("g").attr({fill:u,stroke:u});var f=n(s,"width"),h=n(s,"height"),g=+c.attr("x")-f*{start:0,middle:.5,end:1}[c.attr("text-anchor")||"start"],v=parseInt(c.style("font-size"),10)||n(c,"height"),m=-v/4;"y"===d[0]?(l.attr({transform:"rotate("+[-90,+c.attr("x"),+c.attr("y")]+") translate("+[-f/2,m-h/2]+")"}),s.attr({x:+c.attr("x"),y:+c.attr("y")})):"l"===d[0]?s.attr({x:c.attr("x"),y:m-h/2}):"a"===d[0]?s.attr({x:0,y:m}):s.attr({x:g,y:+c.attr("y")+m-h/2}),e&&e.call(c,l),t(l)})}))}else r();return t}};var p={sup:'font-size:70%" dy="-0.6em',sub:'font-size:70%" dy="0.3em',b:"font-weight:bold",i:"font-style:italic",a:"",span:"",br:"",em:"font-style:italic;font-weight:bold"},d=["http:","https:","mailto:"],g=new RegExp("]*)?/?>","g");h.plainText=function(t){return(t||"").replace(g," ")},h.makeEditable=function(t,e,r){function n(){a(),o.style({opacity:0});var t,e=h.attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&u.select(o.node().parentNode).select(t).style({opacity:0})}function i(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}function a(){var t=u.select(l.Lib.getPlotDiv(o.node())),e=t.select(".svg-container"),n=e.append("div");n.classed("plugin-editable editable",!0).style({position:"absolute","font-family":o.style("font-family")||"Arial","font-size":o.style("font-size")||12,color:r.fill||o.style("fill")||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-parseFloat(o.style("font-size"))/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||o.attr("data-unformatted")).call(s(o,e,r)).on("blur",function(){o.text(this.textContent).style({opacity:1});var t,e=u.select(this).attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&u.select(o.node().parentNode).select(t).style({opacity:0});var r=this.textContent;u.select(this).transition().duration(0).remove(),u.select(document).on("mouseup",null),c.edit.call(o,r)}).on("focus",function(){var t=this;u.select(document).on("mouseup",function(){return u.event.target===t?!1:void(document.activeElement===n.node()&&n.node().blur())})}).on("keyup",function(){27===u.event.which?(o.style({opacity:1}),u.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),c.cancel.call(o,this.textContent)):(c.input.call(o,this.textContent),u.select(this).call(s(o,e,r)))}).on("keydown",function(){13===u.event.which&&this.blur()}).call(i)}r||(r={});var o=this,c=u.dispatch("edit","input","cancel"),f=u.select(this.node()).style({"pointer-events":"all"}),h=e||f;return e&&f.style({"pointer-events":"none"}),r.immediate?n():h.on("click",n),u.rebind(this,c,"on")}},{"../constants/xmlns_namespaces":1115,"../lib":1127,"../plotly":1147,d3:82}],1141:[function(t,e,r){"use strict";var n=e.exports={},i=t("../plots/geo/constants").locationmodeToLayer,a=t("topojson").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../plots/geo/constants":1169,topojson:1043}],1142:[function(t,e,r){"use strict";function n(t){var e;if("string"==typeof t){if(e=document.getElementById(t),null===e)throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t}function i(t,e){t._fullLayout._paperdiv.style("background","white"),R.defaultConfig.setBackground(t,e)}function a(t,e){t._context||(t._context=j.extendFlat({},R.defaultConfig));var r=t._context;e&&(Object.keys(e).forEach(function(t){t in r&&("setBackground"===t&&"opaque"===e[t]?r[t]=i:r[t]=e[t])}),e.plot3dPixelRatio&&!r.plotGlPixelRatio&&(r.plotGlPixelRatio=r.plot3dPixelRatio)),r.staticPlot&&(r.editable=!1,r.autosizable=!1,r.scrollZoom=!1,r.doubleClick=!1,r.showTips=!1,r.showLink=!1,r.displayModeBar=!1)}function o(t,e,r){var n=C.select(t).selectAll(".plot-container").data([0]);n.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=n.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e),r&&(t.layout=r),R.micropolar.manager.fillLayout(t),"initial"===t._fullLayout.autosize&&t._context.autosizable&&(w(t,{}),t._fullLayout.autosize=r.autosize=!0),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=R.micropolar.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var a=t.framework.svg(),o=1,s=t._fullLayout.title;""!==s&&s||(o=0);var l="Click to enter title",u=function(){this.call(R.util.convertToTspans)},c=a.select(".title-group text").call(u);if(t._context.editable){c.attr({"data-unformatted":s}),s&&s!==l||(o=.2,c.attr({"data-unformatted":l}).text(l).style({opacity:o}).on("mouseover.opacity",function(){C.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){C.select(this).transition().duration(1e3).style("opacity",0)}));var f=function(){this.call(R.util.makeEditable).on("edit",function(e){t.framework({layout:{title:e}}),this.attr({"data-unformatted":e}).text(e).call(u),this.call(f)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(u)})};c.call(f)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),N.addLinks(t),Promise.resolve()}function s(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1);var n=R.Axes.list({_fullLayout:t});for(e=0;ee;e++){var o=t.annotations[e];o.ref&&("paper"===o.ref?(o.xref="paper",o.yref="paper"):"data"===o.ref&&(o.xref="x",o.yref="y"),delete o.ref),l(o,"xref"),l(o,"yref")}void 0===t.shapes||Array.isArray(t.shapes)||(j.warn("Shapes must be an array."),delete t.shapes);var s=(t.shapes||[]).length;for(e=0;s>e;e++){var u=t.shapes[e];l(u,"xref"),l(u,"yref")}var c=t.legend;c&&(c.x>3?(c.x=1.02,c.xanchor="left"):c.x<-2&&(c.x=-.02,c.xanchor="right"),c.y>3?(c.y=1.02,c.yanchor="bottom"):c.y<-2&&(c.y=-.02,c.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var h=N.getSubplotIds(t,"gl3d");for(e=0;er;++r)b[r]=v[e]+m*y[2+4*r];p.camera={eye:{x:b[0],y:b[1],z:b[2]},center:{x:v[0],y:v[1],z:v[2]},up:{x:y[1],y:y[5],z:y[9]}},delete p.cameraposition}}return D.clean(t),t}function l(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=R.Axes.cleanId(r,n))}function u(t,e){for(var r=[],n=(t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid})),i=0;ia&&(s=j.randstr(n),-1!==r.indexOf(s));a++);o.uid=j.randstr(n),n.push(o.uid)}if(r.push(o.uid),"histogramy"===o.type&&"xbins"in o&&!("ybins"in o)&&(o.ybins=o.xbins,delete o.xbins),o.error_y&&"opacity"in o.error_y){var l=D.defaults,u=o.error_y.color||(N.traceIs(o,"bar")?D.defaultLine:l[i%l.length]);o.error_y.color=D.addOpacity(D.rgb(u),D.opacity(u)*o.error_y.opacity),delete o.error_y.opacity}if("bardir"in o&&("h"!==o.bardir||!N.traceIs(o,"bar")&&"histogram"!==o.type.substr(0,9)||(o.orientation="h",x(o)),delete o.bardir),"histogramy"===o.type&&x(o),"histogramx"!==o.type&&"histogramy"!==o.type||(o.type="histogram"),"scl"in o&&(o.colorscale=o.scl,delete o.scl),"reversescl"in o&&(o.reversescale=o.reversescl,delete o.reversescl),o.xaxis&&(o.xaxis=R.Axes.cleanId(o.xaxis,"x")),o.yaxis&&(o.yaxis=R.Axes.cleanId(o.yaxis,"y")),N.traceIs(o,"gl3d")&&o.scene&&(o.scene=N.subplotsRegistry.gl3d.cleanId(o.scene)),N.traceIs(o,"pie")||(Array.isArray(o.textposition)?o.textposition=o.textposition.map(c):o.textposition&&(o.textposition=c(o.textposition))),N.traceIs(o,"2dMap")&&("YIGnBu"===o.colorscale&&(o.colorscale="YlGnBu"),"YIOrRd"===o.colorscale&&(o.colorscale="YlOrRd")),N.traceIs(o,"markerColorscale")&&o.marker){var h=o.marker;"YIGnBu"===h.colorscale&&(h.colorscale="YlGnBu"),"YIOrRd"===h.colorscale&&(h.colorscale="YlOrRd")}if("surface"===o.type&&j.isPlainObject(o.contours)){var p=["x","y","z"];for(a=0;an?a.push(i+n):a.push(n);return a}function d(t,e,r){var n,i;for(n=0;n=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||0>i&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function g(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),d(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&d(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function v(t,e,r){var n,i;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n=0&&l0){var s=_(t._boundingBoxMargins),l=s.left+s.right,u=s.bottom+s.top,c=a._container.node().getBoundingClientRect(),f=1-2*o.frameMargins;i=Math.round(f*(c.width-l)),n=Math.round(f*(c.height-u))}else r=window.getComputedStyle(t),n=parseFloat(r.height)||a.height,i=parseFloat(r.width)||a.width;return Math.abs(a.width-i)>1||Math.abs(a.height-n)>1?(a.height=t.layout.height=n,a.width=t.layout.width=i):"initial"!==a.autosize&&(delete e.autosize,a.autosize=t.layout.autosize=!0),N.sanitizeMargins(a),e}function k(t){var e=C.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),"initial"===r.autosize&&(w(t,{}),r.autosize=!0,t.layout.autosize=!0),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([0]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._geocontainer=r._paperdiv.selectAll(".geo-container").data([0]),r._geocontainer.enter().append("div").classed("geo-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var n=[];C.selectAll("defs").each(function(){this.id&&n.push(this.id.split("-")[1])}),r._uid=j.randstr(n)}r._paperdiv.selectAll(".main-svg").attr(Z.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=i.append("g").classed("imagelayer",!0),r._shapeLowerLayer=i.append("g").classed("shapelayer",!0);var a=R.Axes.getSubplots(t);a.join("")!==Object.keys(t._fullLayout._plots||{}).join("")&&A(t,a),r._has("cartesian")&&M(t,a),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0);var o=r._paper.selectAll(".layer-subplot");r._imageSubplotLayer=o.selectAll(".imagelayer"),r._shapeSubplotLayer=o.selectAll(".shapelayer");var s=r._paper.append("g").classed("layer-above",!0);r._imageUpperLayer=s.append("g").classed("imagelayer",!0),r._shapeUpperLayer=s.append("g").classed("shapelayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0),r._geoimages=r._paper.append("g").classed("geoimages",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework");var l=j.syncOrAsync([T,function(){return R.Axes.doTicks(t,"redraw")},F.init],t);return l&&l.then&&t._promises.push(l),l}function A(t,e){function r(e,r){return function(){return R.Axes.getFromId(t,e,r)}}for(var n,i,a=t._fullLayout._plots={},o=0;o=0;e--)t.data[e][i]||(r=t._fullData[e].type,n=R.PlotSchema.get().traces[r],t.data[e]=j.deepCloneTrace(t.data[e],n),t.data[e][i]=!0)}var C=t("d3"),z=t("gl-mat4/fromQuat"),P=t("fast-isnumeric"),R=t("../plotly"),j=t("../lib"),O=t("../lib/events"),I=t("../lib/queue"),N=t("../plots/plots"),F=t("../plots/cartesian/graph_interact"),D=t("../components/color"),B=t("../components/drawing"),U=t("../components/errorbars"),V=t("../components/images"),q=t("../components/legend"),G=t("../components/rangeslider"),H=t("../components/rangeselector"),Y=t("../components/shapes"),X=t("../components/titles"),W=t("../components/modebar/manage"),Z=t("../constants/xmlns_namespaces");R.plot=function(t,e,r,i){function l(){var e,r,n,i=t.calcdata;for(q.draw(t),H.draw(t),e=0;e0,_=R.Axes.getSubplots(t).join(""),w=Object.keys(t._fullLayout._plots||{}).join(""),A=w===_;x?t.framework===k&&!b&&A||(t.framework=k,k(t)):A?b&&k(t):(t.framework=k,k(t)),b&&R.Axes.saveRangeInitial(t);var M=t._fullLayout,E=!t.calcdata||t.calcdata.length!==(t.data||[]).length;E&&h(t);for(var L=0;LY.range[0]?[1,2]:[2,1]);else{var X=Y.range[0],Z=Y.range[1];"log"===P?(0>=X&&0>=Z&&i(U+".autorange",!0),0>=X?X=Z/1e6:0>=Z&&(Z=X/1e6),i(U+".range[0]",Math.log(X)/Math.LN10),i(U+".range[1]",Math.log(Z)/Math.LN10)):(i(U+".range[0]",Math.pow(10,X)),i(U+".range[1]",Math.pow(10,Z)))}else i(U+".autorange",!0)}if("reverse"===D)G.range?G.range.reverse():(i(U+".autorange",!0),G.range=[1,0]),H.autorange?_=!0:x=!0;else if("annotations"===z.parts[0]||"shapes"===z.parts[0]){var K=z.parts[1],$=z.parts[0],Q=d[$]||[],J=R[j.titleCase($)],tt=Q[K]||{};2===z.parts.length&&("add"===v[C]||j.isPlainObject(v[C])?E[C]="remove":"remove"===v[C]?-1===K?(E[$]=Q,delete E[C]):E[C]=tt:j.log("???",v)),!a(tt,"x")&&!a(tt,"y")||j.containsAny(C,["color","opacity","align","dash"])||(_=!0),J.draw(t,K,z.parts.slice(2).join("."),v[C]),delete v[C]}else if("images"===z.parts[0]){var et=j.objectFromPath(C,P);j.extendDeepAll(t.layout,et),V.supplyLayoutDefaults(t.layout,t._fullLayout),V.draw(t)}else if("mapbox"===z.parts[0]&&"layers"===z.parts[1]){j.extendDeepAll(t.layout,j.objectFromPath(C,P));var nt=(t._fullLayout.mapbox||{}).layers||[],it=z.parts[2]+1-nt.length;for(p=0;it>p;p++)nt.push({});x=!0}else 0===z.parts[0].indexOf("scene")?x=!0:0===z.parts[0].indexOf("geo")?x=!0:0===z.parts[0].indexOf("ternary")?x=!0:!g._has("gl2d")||-1===C.indexOf("axis")&&"plot_bgcolor"!==z.parts[0]?"hiddenlabels"===C?_=!0:-1!==z.parts[0].indexOf("legend")?m=!0:-1!==C.indexOf("title")?y=!0:-1!==z.parts[0].indexOf("bgcolor")?b=!0:z.parts.length>1&&j.containsAny(z.parts[1],["tick","exponent","grid","zeroline"])?y=!0:-1!==C.indexOf(".linewidth")&&-1!==C.indexOf("axis")?y=b=!0:z.parts.length>1&&-1!==z.parts[1].indexOf("line")?b=!0:z.parts.length>1&&"mirror"===z.parts[1]?y=b=!0:"margin.pad"===C?y=b=!0:"margin"===z.parts[0]||"autorange"===z.parts[1]||"rangemode"===z.parts[1]||"type"===z.parts[1]||"domain"===z.parts[1]||C.match(/^(bar|box|font)/)?_=!0:-1!==["hovermode","dragmode"].indexOf(C)?k=!0:-1===["hovermode","dragmode","height","width","autosize"].indexOf(C)&&(x=!0):x=!0,z.set(P)}I&&I.add(t,rt,[t,E],rt,[t,M]),v.autosize&&(v=w(t,v)),(v.height||v.width||v.autosize)&&(_=!0);var at=Object.keys(v),ot=[N.previousPromises];if(x||_)ot.push(function(){return t.layout=void 0,_&&(t.calcdata=void 0),R.plot(t,"",d)});else if(at.length&&(N.supplyDefaults(t),g=t._fullLayout,m&&ot.push(function(){return q.draw(t),N.previousPromises(t)}),b&&ot.push(T),y&&ot.push(function(){return R.Axes.doTicks(t,"redraw"),L(t),N.previousPromises(t)}),k)){var st;for(W(t),st=N.getSubplotIds(g,"gl3d"),p=0;p1)};u(r.width)&&u(r.height)||s(new Error("Height and width should be pixel values."));var c=n.clone(e,{format:"png",height:r.height,width:r.width}),f=c.td;f.style.position="absolute",f.style.left="-5000px",document.body.appendChild(f);var h=n.getRedrawFunc(f);a.plot(f,c.data,c.layout,c.config).then(h).then(l).then(function(e){t(e)}).catch(function(t){s(t)})});return s}var i=t("fast-isnumeric"),a=t("../plotly"),o=t("../lib");e.exports=n},{"../lib":1127,"../plotly":1147,"../snapshot":1216,"fast-isnumeric":90}],1147:[function(t,e,r){"use strict";t("es6-promise").polyfill(),r.Lib=t("./lib"),r.util=t("./lib/svg_text_utils"),r.Queue=t("./lib/queue"),t("../build/plotcss"),r.MathJaxConfig=t("./fonts/mathjax_config"),r.defaultConfig=t("./plot_api/plot_config");var n=r.Plots=t("./plots/plots");r.Axes=t("./plots/cartesian/axes"),r.Fx=t("./plots/cartesian/graph_interact"),r.micropolar=t("./plots/polar/micropolar"),r.Color=t("./components/color"),r.Drawing=t("./components/drawing"),r.Colorscale=t("./components/colorscale"),r.Colorbar=t("./components/colorbar"),r.ErrorBars=t("./components/errorbars"),r.Annotations=t("./components/annotations"),r.Shapes=t("./components/shapes"),r.Legend=t("./components/legend"),r.Images=t("./components/images"),r.ModeBar=t("./components/modebar"),r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;eu&&c>e&&(void 0===i[r]?a[f]=T.tickText(t,e):a[f]=s(t,e,String(i[r])),f++);return f=864e5?t._tickround="d":r>=36e5?t._tickround="H":r>=6e4?t._tickround="M":r>=1e3?t._tickround="S":t._tickround=3-Math.round(Math.log(r/2)/Math.LN10);else{b(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01),e="log"===t.type?Math.pow(10,Math.max(t.range[0],t.range[1])):Math.max(Math.abs(t.range[0]),Math.abs(t.range[1]));var n=Math.floor(Math.log(e)/Math.LN10+.01);Math.abs(n)>3&&("SI"===t.exponentformat||"B"===t.exponentformat?t._tickexponent=3*Math.round((n-1)/3):t._tickexponent=n); +}else"M"===r.charAt(0)?t._tickround=2===r.length?"m":"y":t._tickround=null}function o(t,e){var r=t.match(U),n=new Date(e);if(r){var i=Math.min(+r[1]||6,6),a=String(e/1e3%1+2.0000005).substr(2,i).replace(/0+$/,"")||"0";return y.time.format(t.replace(U,a))(n)}return y.time.format(t)(n)}function s(t,e,r){var n=t.tickfont||t._gd._fullLayout.font;return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}function l(t,e,r,n){var i,a=e.x,s=t._tickround,l=new Date(a),u="";r&&t.hoverformat?i=o(t.hoverformat,a):t.tickformat?i=o(t.tickformat,a):(n&&(b(s)?s+=2:s={y:"m",m:"d",d:"H",H:"M",M:"S",S:2}[s]),"y"===s?i=O(l):"m"===s?i=I(l):(a!==t._tmin||r||(u="
"+O(l)),"d"===s?i=N(l):"H"===s?i=F(l):(a!==t._tmin||r||(u="
"+N(l)+", "+O(l)),i=D(l),"M"!==s&&(i+=B(l),"S"!==s&&(i+=h(m(a/1e3,1),t,"none",r).substr(1)))))),e.text=i+u}function u(t,e,r,n,i){var a=t.dtick,o=e.x;if(!n||"string"==typeof a&&"L"===a.charAt(0)||(a="L3"),t.tickformat||"string"==typeof a&&"L"===a.charAt(0))e.text=h(Math.pow(10,o),t,i,n);else if(b(a)||"D"===a.charAt(0)&&m(o+.01,1)<.1)if(-1!==["e","E","power"].indexOf(t.exponentformat)){var s=Math.round(o);0===s?e.text=1:1===s?e.text="10":s>1?e.text="10"+s+"":e.text="10\u2212"+-s+"",e.fontSize*=1.25}else e.text=h(Math.pow(10,o),t,"","fakehover"),"D1"===a&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6);else{if("D"!==a.charAt(0))throw"unrecognized dtick "+String(a);e.text=String(Math.round(Math.pow(10,m(o,1)))),e.fontSize*=.75}if("D1"===t.dtick){var l=String(e.text).charAt(0);"0"!==l&&"1"!==l||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(0>o?.5:.25)))}}function c(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r=""),e.text=String(r)}function f(t,e,r,n,i){"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide"),e.text=h(e.x,t,i,n)}function h(t,e,r,n){var i=0>t,o=e._tickround,s=r||e.exponentformat||"B",l=e._tickexponent,u=e.tickformat;if(n){var c={exponentformat:e.exponentformat,dtick:"none"===e.showexponent?e.dtick:b(t)?Math.abs(t)||1:1,range:"none"===e.showexponent?e.range:[0,t||1]};a(c),o=(Number(c._tickround)||0)+4,l=c._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return y.format(u)(t).replace(/-/g,"\u2212");var f=Math.pow(10,-o)/2;if("none"===s&&(l=0),t=Math.abs(t),f>t)t="0",i=!1;else{if(t+=f,l&&(t*=Math.pow(10,-l),o+=l),0===o)t=String(Math.floor(t));else if(0>o){t=String(Math.round(t)),t=t.substr(0,t.length+o);for(var h=o;0>h;h++)t+="0"}else{t=String(t);var p=t.indexOf(".")+1;p&&(t=t.substr(0,p+o).replace(/\.?0+$/,""))}t=_.numSeparate(t,e._gd._fullLayout.separators)}if(l&&"hide"!==s){var d;d=0>l?"\u2212"+-l:"power"!==s?"+"+l:String(l),"e"===s||("SI"===s||"B"===s)&&(l>12||-15>l)?t+="e"+d:"E"===s?t+="E"+d:"power"===s?t+="×10"+d+"":"B"===s&&9===l?t+="B":"SI"!==s&&"B"!==s||(t+=V[l/3+5])}return i?"\u2212"+t:t}function p(t,e){var r,n,i=[];for(r=0;r1)for(n=1;n2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},T.getAutoRange=function(t){var e,r=[],n=t._min[0].val,i=t._max[0].val;for(e=1;e0&&c>0&&f/c>h&&(l=o,u=s,h=f/c);return n===i?r=p?[n+1,"normal"!==t.rangemode?0:n-1]:["normal"!==t.rangemode?0:n-1,n+1]:h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode&&l.val>=0?l={val:0,pad:0}:"nonnegative"===t.rangemode&&(l.val-h*l.pad<0&&(l={val:0,pad:0}),u.val<0&&(u={val:1,pad:0})),h=(u.val-l.val)/(t._length-l.pad-u.pad)),r=[l.val-h*l.pad,u.val+h*u.pad],r[0]===r[1]&&(r=[r[0]-1,r[0]+1]),p&&r.reverse()),r},T.doAutoRange=function(t){t._length||t.setScale();var e=t._min&&t._max&&t._min.length&&t._max.length;if(t.autorange&&e){t.range=T.getAutoRange(t);var r=t._gd.layout[t._name];r||(t._gd.layout[t._name]=r={}),r!==t&&(r.range=t.range.slice(),r.autorange=t.autorange)}},T.saveRangeInitial=function(t,e){for(var r=T.list(t,"",!0),n=!1,i=0;id&&(d=g/10),u=t.c2l(d),c=t.c2l(g),y&&(u=Math.min(0,u),c=Math.max(0,c)),n(u)){for(p=!0,o=0;o=h?p=!1:s.val>=u&&s.pad<=h&&(t._min.splice(o,1),o--);p&&t._min.push({val:u,pad:y&&0===u?0:h})}if(n(c)){for(p=!0,o=0;o=c&&s.pad>=f?p=!1:s.val<=c&&s.pad<=f&&(t._max.splice(o,1),o--);p&&t._max.push({val:c,pad:y&&0===c?0:f})}}}if((t.autorange||t._needsExpand)&&e){t._min||(t._min=[]),t._max||(t._max=[]),r||(r={}),t._m||t.setScale();var a,o,s,l,u,c,f,h,p,d,g,v=e.length,m=r.padded?.05*t._length:0,y=r.tozero&&("linear"===t.type||"-"===t.type),x=n((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),_=n((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),w=n(r.vpadplus||r.vpad),k=n(r.vpadminus||r.vpad);for(a=0;6>a;a++)i(a);for(a=v-1;a>5;a--)i(a)}},T.autoBin=function(t,e,r,n){function i(t){return(1+100*(t-p)/f.dtick)%100<2}var a=_.aggNums(Math.min,null,t),o=_.aggNums(Math.max,null,t);if("category"===e.type)return{start:a-.5,end:o+.5,size:1};var s;if(r)s=(o-a)/r;else{var l=_.distinctVals(t),u=Math.pow(10,Math.floor(Math.log(l.minDiff)/Math.LN10)),c=u*_.roundUp(l.minDiff/u,[.9,1.9,4.9,9.9],!0);s=Math.max(c,2*_.stdev(t)/Math.pow(t.length,n?.25:.4))}var f={type:"log"===e.type?"linear":e.type,range:[a,o]};T.autoTicks(f,s);var h,p=T.tickIncrement(T.tickFirst(f),f.dtick,"reverse");if("number"==typeof f.dtick){for(var d=0,g=0,v=0,m=0,y=0;yg&&(d>.3*x||i(a)||i(o))){var w=f.dtick/2;p+=a>p+w?w:-w}var k=1+Math.floor((o-p)/f.dtick);h=p+k*f.dtick}else for(h=p;o>=h;)h=T.tickIncrement(h,f.dtick);return{start:p,end:h,size:f.dtick}},T.calcTicks=function(t){if("array"===t.tickmode)return n(t);if("auto"===t.tickmode||!t.dtick){var e,r=t.nticks;r||("category"===t.type?(e=t.tickfont?1.2*(t.tickfont.size||12):15,r=t._length/e):(e="y"===t._id.charAt(0)?40:80,r=_.constrain(t._length/e,4,9)+1)),T.autoTicks(t,Math.abs(t.range[1]-t.range[0])/r),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t._forceTick0)}t.tick0||(t.tick0="date"===t.type?new Date(2e3,0,1).getTime():0),a(t),t._tmin=T.tickFirst(t);var i=t.range[1]=s:s>=l)&&(o.push(l),!(o.length>1e3));l=T.tickIncrement(l,t.dtick,i));t._tmax=o[o.length-1];for(var u=new Array(o.length),c=0;c157788e5?(e/=315576e5,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="M"+12*i(e,r,S)):e>12096e5?(e/=26298e5,t.dtick="M"+i(e,1,C)):e>432e5?(t.dtick=i(e,864e5,P),t.tick0=new Date(2e3,0,2).getTime()):e>18e5?t.dtick=i(e,36e5,C):e>3e4?t.dtick=i(e,6e4,z):e>500?t.dtick=i(e,1e3,z):(r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));else if("log"===t.type)if(t.tick0=0,e>.7)t.dtick=Math.ceil(e);else if(Math.abs(t.range[1]-t.range[0])<1){var n=1.5*Math.abs((t.range[1]-t.range[0])/e);e=Math.abs(Math.pow(10,t.range[1])-Math.pow(10,t.range[0]))/n,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="L"+i(e,r,S)}else t.dtick=e>.3?"D2":"D1";else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):(t.tick0=0,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));if(0===t.dtick&&(t.dtick=1),!b(t.dtick)&&"string"!=typeof t.dtick){var a=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(a)}},T.tickIncrement=function(t,e,r){var n=r?-1:1;if(b(e))return t+n*e;var i=e.charAt(0),a=n*Number(e.substr(1));if("M"===i){var o=new Date(t);return o.setMonth(o.getMonth()+a)}if("L"===i)return Math.log(Math.pow(10,t)+a)/Math.LN10;if("D"===i){var s="D2"===e?j:R,l=t+.01*n,u=_.roundUp(m(l,1),s,r);return Math.floor(l)+Math.log(y.round(Math.pow(10,u),1))/Math.LN10}throw"unrecognized dtick "+String(e)},T.tickFirst=function(t){var e=t.range[1]n:n>u;)u=T.tickIncrement(u,i,e);return u}if("L"===c)return Math.log(r((Math.pow(10,n)-a)/f)*f+a)/Math.LN10;if("D"===c){var h="D2"===i?j:R,p=_.roundUp(m(n,1),h,e);return Math.floor(n)+Math.log(y.round(Math.pow(10,p),1))/Math.LN10}throw"unrecognized dtick "+String(i)};var O=y.time.format("%Y"),I=y.time.format("%b %Y"),N=y.time.format("%b %-d"),F=y.time.format("%b %-d %Hh"),D=y.time.format("%H:%M"),B=y.time.format(":%S"),U=/%(\d?)f/g;T.tickText=function(t,e,r){function n(n){var i;return void 0===n?!0:r?"none"===n:(i={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==i)}var i,a,o=s(t,e),h="array"===t.tickmode,p=r||h;if(h&&Array.isArray(t.ticktext)){var d=Math.abs(t.range[1]-t.range[0])/1e4;for(a=0;a1&&er&&(A=90),i(c,A)}u._lastangle=A}return o(e),e+" done"}function l(){u._boundingBox=r.node().getBoundingClientRect()}var c=r.selectAll("g."+C).data(L,S);if(!u.showticklabels||!b(n))return c.remove(),void o(e);var f,h,d,m,x;"x"===v?(x="bottom"===B?1:-1,f=function(t){return t.dx+O*x},m=n+(j+R)*x,h=function(t){return t.dy+m+t.fontSize*("bottom"===B?1:-.5)},d=function(t){return b(t)&&0!==t&&180!==t?0>t*x?"end":"start":"middle"}):(x="right"===B?1:-1,h=function(t){return t.dy+t.fontSize/2-O*x},f=function(t){return t.dx+n+(j+R+(90===Math.abs(u.tickangle)?t.fontSize/2:0))*x},d=function(t){return b(t)&&90===Math.abs(t)?"middle":"right"===B?"start":"end"});var k=0,A=0,T=[];c.enter().append("g").classed(C,1).append("text").attr("text-anchor","middle").each(function(e){var r=y.select(this),n=t._promises.length;r.call(M.setPosition,f(e),h(e)).call(M.font,e.font,e.fontSize,e.fontColor).text(e.text).call(w.convertToTspans),n=t._promises[n],n?T.push(t._promises.pop().then(function(){i(r,u.tickangle)})):i(r,u.tickangle)}),c.exit().remove(),c.each(function(t){k=Math.max(k,t.fontSize)}),i(c,u._lastangle||u.tickangle);var E=_.syncOrAsync([a,s,l]);return E&&E.then&&t._promises.push(E),E}function o(e){if(!r){var n,i,a,o,s=E.getFromId(t,e),l=y.select(t).selectAll("g."+e+"tick"),u={selection:l,side:s.side},f=e.charAt(0),h=t._fullLayout._size,p=1.5,d=s.titlefont.size;if(l.size()){var g=y.select(l.node().parentNode).attr("transform").match(/translate\(([-\.\d]+),([-\.\d]+)\)/);g&&(u.offsetLeft=+g[1],u.offsetTop=+g[2])}"x"===f?(i="free"===s.anchor?{_offset:h.t+(1-(s.position||0))*h.h,_length:0}:E.getFromId(t,s.anchor),a=s._offset+s._length/2,o=i._offset+("top"===s.side?-10-d*(p+(s.showticklabels?1:0)):i._length+10+d*(p+(s.showticklabels?1.5:.5))),s.rangeslider&&s.rangeslider.visible&&s._boundingBox&&(o+=(c.height-c.margin.b-c.margin.t)*s.rangeslider.thickness+s._boundingBox.height),u.side||(u.side="bottom")):(i="free"===s.anchor?{_offset:h.l+(s.position||0)*h.w,_length:0}:E.getFromId(t,s.anchor),o=s._offset+s._length/2,a=i._offset+("right"===s.side?i._length+10+d*(p+(s.showticklabels?1:.5)):-10-d*(p+(s.showticklabels?.5:0))),n={rotate:"-90",offset:0},u.side||(u.side="left")),k.draw(t,e+"title",{propContainer:s,propName:s._name+".title",dfltName:f.toUpperCase()+" axis",avoid:u,transform:n,attributes:{x:a,y:o,"text-anchor":"middle"}})}}function s(t,e){return t.visible!==!0||t.xaxis+t.yaxis!==e?!1:x.Plots.traceIs(t,"bar")&&t.orientation==={x:"h",y:"v"}[v]?!0:t.fill&&t.fill.charAt(t.fill.length-1)===v}function l(e,r,i){var a=e.gridlayer,o=e.zerolinelayer,l=e["hidegrid"+v]?[]:V,c=u._gridpath||"M0,0"+("x"===v?"v":"h")+r._length,f=a.selectAll("path."+z).data(u.showgrid===!1?[]:l,S);if(f.enter().append("path").classed(z,1).classed("crisp",1).attr("d",c).each(function(t){u.zeroline&&("linear"===u.type||"-"===u.type)&&Math.abs(t.x)g;g++){var y=u.mirrors[o._id+h[g]];"ticks"!==y&&"labels"!==y||(f[g]=!0)}return void 0!==n[2]&&(f[2]=!0),f.forEach(function(t,e){var r=n[e],i=U[e];t&&b(r)&&(p+=d(r+R*i,i*u.ticklen))}),i(r,p),l(e,o,t),a(r,n[3])}}).filter(function(t){return t&&t.then});return G.length?Promise.all(G):0},T.swap=function(t,e){for(var r=p(t,e),n=0;n2*n}function c(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}var f=t("fast-isnumeric"),h=t("tinycolor2").mix,p=t("../../lib"),d=t("../plots"),g=t("../../components/color/attributes").lightFraction,v=t("./layout_attributes"),m=t("./tick_value_defaults"),y=t("./tick_mark_defaults"),b=t("./tick_label_defaults"),x=t("./category_order_defaults"),_=t("./set_convert"),w=t("./ordered_categories"),k=t("./clean_datum"),A=t("./axis_ids");e.exports=function(t,e,r,i){function a(r,n){return p.coerce2(t,e,v,r,n)}var o=i.letter,s=i.font||{},l="Click to enter "+(i.title||o.toUpperCase()+" axis")+" title";i.name&&(e._name=i.name,e._id=A.name2id(i.name));var u=r("type");"-"===u&&(n(e,i.data),"-"===e.type?e.type="linear":u=t.type=e.type),_(e);var c=r("color"),d=c===t.color?c:s.color;r("title",l),p.coerceFont(r,"titlefont",{family:s.family,size:Math.round(1.2*s.size),color:d});var k=2===(t.range||[]).length&&f(t.range[0])&&f(t.range[1]),M=r("autorange",!k);M&&r("rangemode");var T=r("range",[-1,"x"===o?6:4]);T[0]===T[1]&&(e.range=[T[0]-1,T[0]+1]),p.noneOrAll(t.range,e.range,[0,1]),r("fixedrange"),m(t,e,r,u),b(t,e,r,u,i),y(t,e,r,i),x(t,e,r);var E=a("linecolor",c),L=a("linewidth"),S=r("showline",!!E||!!L);S||(delete e.linecolor,delete e.linewidth),(S||e.ticks)&&r("mirror");var C=a("gridcolor",h(c,i.bgColor,g).toRgbString()),z=a("gridwidth"),P=r("showgrid",i.showGrid||!!C||!!z);P||(delete e.gridcolor,delete e.gridwidth);var R=a("zerolinecolor",c),j=a("zerolinewidth"),O=r("zeroline",i.showGrid||!!R||!!j);return O||(delete e.zerolinecolor,delete e.zerolinewidth),e._initialCategories="category"===u?w(o,e.categoryorder,e.categoryarray,i.data):[],e}},{"../../components/color/attributes":1047,"../../lib":1127,"../plots":1199,"./axis_ids":1152,"./category_order_defaults":1153,"./clean_datum":1154,"./layout_attributes":1159,"./ordered_categories":1161,"./set_convert":1164,"./tick_label_defaults":1165,"./tick_mark_defaults":1166,"./tick_value_defaults":1167,"fast-isnumeric":90,tinycolor2:1042}],1152:[function(t,e,r){"use strict";function n(t,e,r){function n(t,r){for(var n=Object.keys(t),i=/^[xyz]axis[0-9]*/,a=[],o=0;o0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}},{}],1154:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t){try{if("object"==typeof t&&null!==t&&t.getTime)return i.ms2DateTime(t);if("string"!=typeof t&&!n(t))return"";t=t.toString().replace(/['"%,$# ]/g,"")}catch(e){i.error(e,t)}return t}},{"../../lib":1127,"fast-isnumeric":90}],1155:[function(t,e,r){"use strict";e.exports={idRegex:{x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},attrRegex:{x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},BADNUM:void 0,xAxisMatch:/^xaxis[0-9]*$/,yAxisMatch:/^yaxis[0-9]*$/,AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,DBLCLICKDELAY:300,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,MAXDIST:20,YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,BENDPX:1.5,REDRAWDELAY:50}},{}],1156:[function(t,e,r){"use strict";function n(t,e){var r,n=t.range[e],i=Math.abs(n-t.range[1-e]);return"date"===t.type?u.ms2DateTime(n,i):"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,o.format("."+r+"g")(Math.pow(10,n))):(r=Math.floor(Math.log(Math.abs(n))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,o.format("."+String(r)+"g")(n))}function i(t,e){return t?"nsew"===t?"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}function a(t){o.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var o=t("d3"),s=t("tinycolor2"),l=t("../../plotly"),u=t("../../lib"),c=t("../../lib/svg_text_utils"),f=t("../../components/color"),h=t("../../components/drawing"),p=t("../../lib/setcursor"),d=t("../../components/dragelement"),g=t("./axes"),v=t("./select"),m=t("./constants"),y=!0;e.exports=function(t,e,r,o,b,x,_,w){function k(t,e){for(var r=0;r.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+ht+", "+pt+")").attr("d",ot+"Z"),ct=ft.append("path").attr("class","zoombox-corners").style({fill:f.background,stroke:f.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+ht+", "+pt+")").attr("d","M0,0Z"),T();for(var a=0;ai?(lt="",it.r=it.l,it.t=it.b,ct.attr("d","M0,0Z")):(it.t=0,it.b=V,lt="x",ct.attr("d","M"+(it.l-.5)+","+(nt-G-.5)+"h-3v"+(2*G+1)+"h3ZM"+(it.r+.5)+","+(nt-G-.5)+"h3v"+(2*G+1)+"h-3Z")):!Z||i.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),ct.transition().style("opacity",1).duration(200),st=!0)}function L(t,e,r){var n,i,a;for(n=0;nzoom back out","long"),y=!1)))}function C(e,r){var i=1===(_+w).length;if(e)O();else if(2!==r||i){if(1===r&&i){var a=_?B[0]:D[0],o="s"===_||"w"===w?0:1,s=a._name+".range["+o+"]",u=n(a,o),f="left",h="middle"; +if(a.fixedrange)return;_?(h="n"===_?"top":"bottom","right"===a.side&&(f="right")):"e"===w&&(f="right"),J.call(c.makeEditable,null,{immediate:!0,background:N.paper_bgcolor,text:String(u),fill:a.tickfont?a.tickfont.color:"#444",horizontalAlign:f,verticalAlign:h}).on("edit",function(e){var r="category"===a.type?a.c2l(e):a.d2l(e);void 0!==r&&l.relayout(t,s,r)})}}else j()}function z(e){function r(t,e,r){if(!t.fixedrange){A(t.range);var n=t.range,i=n[0]+(n[1]-n[0])*e;t.range=[i+(n[0]-i)*r,i+(n[1]-i)*r]}}if(t._context.scrollZoom||N._enablescrollzoom){var n=t.querySelector(".plotly");if(!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(gt);var i=-e.deltaY;if(isFinite(i)||(i=e.wheelDelta/10),!isFinite(i))return void u.log("Did not find wheel motion attributes: ",e);var a,o=Math.exp(-Math.min(Math.max(i,-20),20)/100),s=mt.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(e.clientX-s.left)/s.width,c=dt[0]+dt[2]*l,f=(s.bottom-e.clientY)/s.height,h=dt[1]+dt[3]*(1-f);if(w){for(a=0;a=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function i(t,e,r){for(var i=1-e,a=0,o=0;o0;n--)r.push(e);return r}function i(t,e){for(var r=[],n=0;nT;T++){var E=a[T],L=p[E];if(L)A[T]=w.getFromId(t,L.xaxis._id),M[T]=w.getFromId(t,L.yaxis._id);else{var S=o[E]._subplot;A[T]=S.xaxis,M[T]=S.yaxis}}var C=e.hovermode||o.hovermode;if(-1===["x","y","closest"].indexOf(C)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return _.unhoverRaw(t,e);var z,P,R,j,O,I,N,F,D,B,U,V,q=[],G=[];if(Array.isArray(e))for(C="array",R=0;RH||H>X.width||0>Y||Y>X.height)return _.unhoverRaw(t,e)}else H="xpx"in e?e.xpx:A[0]._length/2,Y="ypx"in e?e.ypx:M[0]._length/2;if(z="xval"in e?n(a,e.xval):i(A,H),P="yval"in e?n(a,e.yval):i(M,Y),!g(z[0])||!g(P[0]))return v.warn("Plotly.Fx.hover failed",e,t),_.unhoverRaw(t,e)}var W=1/0;for(j=0;j1||-1!==I.hoverinfo.indexOf("name")?I.name:void 0,index:!1,distance:Math.min(W,k.MAXDIST),color:b.defaultLine,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},V=q.length,"array"===F){var Z=e[j];"pointNumber"in Z?(U.index=Z.pointNumber,F="closest"):(F="","xval"in Z&&(D=Z.xval,F="x"),"yval"in Z&&(B=Z.yval,F=F?"closest":"y"))}else D=z[N],B=P[N];if(I._module&&I._module.hoverPoints){var K=I._module.hoverPoints(U,D,B,F);if(K)for(var $,Q=0;QV&&(q.splice(0,V),W=q[0].distance)}if(0===q.length)return _.unhoverRaw(t,e);var J="y"===C&&G.length>1;q.sort(function(t,e){return t.distance-e.distance});var tt=b.combine(o.plot_bgcolor||b.background,o.paper_bgcolor),et={hovermode:C,rotateLabels:J,bgColor:tt,container:o._hoverlayer,outerContainer:o._paperdiv},rt=u(q,et);c(q,J?"xa":"ya"),f(rt,J);var nt=t._hoverdata,it=[];for(R=0;R128?"#000":b.background;if(t.name&&void 0===t.zLabelVal){var c=document.createElement("p");c.innerHTML=t.name,r=c.textContent||"",r.length>15&&(r=r.substr(0,12)+"...")}void 0!==t.extraText&&(n+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(n+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(n+="y: "+t.yLabel+"
"),n+=(n?"z: ":"")+t.zLabel):M&&t[i+"Label"]===g?n=t[("x"===i?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(n=t.yLabel):n=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(n+=(n?"
":"")+t.text),""===n&&(""===r&&e.remove(),n=r);var f=e.select("text.nums").style("fill",u).call(x.setPosition,0,0).text(n).attr("data-notex",1).call(y.convertToTspans);f.selectAll("tspan.line").call(x.setPosition,0,0);var h=e.select("text.name"),v=0;r&&r!==n?(h.style("fill",l).text(r).call(x.setPosition,0,0).attr("data-notex",1).call(y.convertToTspans),h.selectAll("tspan.line").call(x.setPosition,0,0),v=h.node().getBoundingClientRect().width+2*P):(h.remove(),e.select("rect").remove()),e.select("path").style({fill:l,stroke:u});var m,k,E=f.node().getBoundingClientRect(),L=t.xa._offset+(t.x0+t.x1)/2,S=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),R=Math.abs(t.y1-t.y0),j=E.width+z+P+v;t.ty0=_-E.top,t.bx=E.width+2*P,t.by=E.height+2*P,t.anchor="start",t.txwidth=E.width,t.tx2width=v,t.offset=0,a?(t.pos=L,m=A>=S+R/2+j,k=S-R/2-j>=0,"top"!==t.idealAlign&&m||!k?m?(S+=R/2,t.anchor="start"):t.anchor="middle":(S-=R/2,t.anchor="end")):(t.pos=S,m=w>=L+C/2+j,k=L-C/2-j>=0,"left"!==t.idealAlign&&m||!k?m?(L+=C/2,t.anchor="start"):t.anchor="middle":(L-=C/2,t.anchor="end")),f.attr("text-anchor",t.anchor),v&&h.attr("text-anchor",t.anchor),e.attr("transform","translate("+L+","+S+")"+(a?"rotate("+T+")":""))}),S}function c(t,e){function r(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(.01>a)){if(-.01>i){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(0>=u);o--)l=t[o],l.pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=u);o++)if(l=t[o],l.pos=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(0>=u);o--)l=t[o],l.pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(var n,i,a,o,s,l,u,c=0,f=t.map(function(t,r){var n=t[e];return[{i:r,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===n._id.charAt(0)?L:1)/2,pmin:n._offset,pmax:n._offset+n._length}]}).sort(function(t,e){return t[0].posref-e[0].posref});!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&d.pmin===g.pmin&&d.pmax===g.pmax){for(s=p.length-1;s>=0;s--)p[s].dp+=i;for(h.push.apply(h,p),f.splice(o+1,1),u=0,s=h.length-1;s>=0;s--)u+=h[s].dp;for(a=u/h.length,s=h.length-1;s>=0;s--)h[s].dp-=a;n=!1}else o++}f.forEach(r)}for(o=f.length-1;o>=0;o--){var v=f[o];for(s=v.length-1;s>=0;s--){var m=v[s],y=t[m.i];y.offset=m.dp,y.del=m.del}}}function f(t,e){t.each(function(t){var r=p.select(this);if(t.del)return void r.remove();var n="end"===t.anchor?-1:1,i=r.select("text.nums"),a={start:1,end:-1,middle:0}[t.anchor],o=a*(z+P),s=o+a*(t.txwidth+P),l=0,u=t.offset;"middle"===t.anchor&&(o-=t.tx2width/2,s-=t.tx2width/2),e&&(u*=-C,l=t.offset*S),r.select("path").attr("d","middle"===t.anchor?"M-"+t.bx/2+",-"+t.by/2+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(n*z+l)+","+(z+u)+"v"+(t.by/2-z)+"h"+n*t.bx+"v-"+t.by+"H"+(n*z+l)+"V"+(u-z)+"Z"),i.call(x.setPosition,o+l,u+t.ty0-t.by/2+P).selectAll("tspan.line").attr({x:i.attr("x"),y:i.attr("y")}),t.tx2width&&(r.select("text.name, text.name tspan.line").call(x.setPosition,s+a*P+l,u+t.ty0-t.by/2+P),r.select("rect").call(x.setRect,s+(a-1)*t.tx2width/2+l,u-t.by/2-1,t.tx2width,t.by+2))})}function h(t,e,r){if(!e.target)return!1;if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}var p=t("d3"),d=t("tinycolor2"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../lib/events"),y=t("../../lib/svg_text_utils"),b=t("../../components/color"),x=t("../../components/drawing"),_=t("../../components/dragelement"),w=t("./axes"),k=t("./constants"),A=t("./dragbox"),M=e.exports={};M.unhover=_.unhover,M.layoutAttributes={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom"},hovermode:{valType:"enumerated",values:["x","y","closest",!1]}},M.supplyLayoutDefaults=function(t,e,r){function n(r,n){return v.coerce(t,e,M.layoutAttributes,r,n)}n("dragmode");var i;if(e._has("cartesian")){var a=e._isHoriz=M.isHoriz(r);i=a?"y":"x"}else i="closest";n("hovermode",i)},M.isHoriz=function(t){for(var e=!0,r=0;rt._lastHoverTime+k.HOVERMINTIME?(o(t,e,r),void(t._lastHoverTime=Date.now())):void(t._hoverTimer=setTimeout(function(){o(t,e,r),t._lastHoverTime=Date.now(),t._hoverTimer=void 0},k.HOVERMINTIME))},M.getDistanceFunction=function(t,e,r,n){return"closest"===t?n||a(e,r):"x"===t?e:r},M.getClosest=function(t,e,r){if(r.index!==!1)r.index>=0&&r.indext*e||0===t?k.MAXDIST*(.6-.3/Math.max(3,Math.abs(t-e))):1/0}},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/events":1121,"../../lib/svg_text_utils":1140,"./axes":1150,"./constants":1155,"./dragbox":1156,d3:82,"fast-isnumeric":90,tinycolor2:1042}],1158:[function(t,e,r){"use strict";var n=t("../plots"),i=(t("d3"),t("./constants"));r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=i.idRegex,r.attrRegex=i.attrRegex,r.attributes=t("./attributes"),r.plot=function(t,e,r){function i(t,e){for(var r=[],n=0;nf[1]-.01&&(e.domain=[0,1]),i.noneOrAll(t.domain,e.domain,[0,1])}return e}},{"../../lib":1127,"fast-isnumeric":90}],1163:[function(t,e,r){"use strict";function n(t){return t._id}var i=t("../../lib/polygon"),a=t("../../components/color"),o=t("./axes"),s=t("./constants"),l=i.filter,u=i.tester,c=s.MINSELECT;e.exports=function(t,e,r,i,f){function h(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function p(t,e){return t-e}var d,g=i.gd._fullLayout._zoomlayer,v=i.element.getBoundingClientRect(),m=i.plotinfo.x()._offset,y=i.plotinfo.y()._offset,b=e-v.left,x=r-v.top,_=b,w=x,k="M"+b+","+x,A=i.xaxes[0]._length,M=i.yaxes[0]._length,T=i.xaxes.map(n),E=i.yaxes.map(n),L=i.xaxes.concat(i.yaxes);"lasso"===f&&(d=l([[b,x]],s.BENDPX));var S=g.selectAll("path.select-outline").data([1,2]);S.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t}).attr("transform","translate("+m+", "+y+")").attr("d",k+"Z");var C,z,P,R,j,O=g.append("path").attr("class","zoombox-corners").style({fill:a.background,stroke:a.defaultLine,"stroke-width":1}).attr("transform","translate("+m+", "+y+")").attr("d","M0,0Z"),I=[],N=i.gd,F=[];for(C=0;C0)return Math.log(e)/Math.LN10;if(0>=e&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*c*Math.abs(n-i))}return o.BADNUM}function r(t){return Math.pow(10,t)}function u(t){return i(t)?Number(t):o.BADNUM}var c=10;if(t.c2l="log"===t.type?e:u,t.l2c="log"===t.type?r:u,t.l2d=function(e){return t.c2d(t.l2c(e))},t.p2d=function(e){return t.l2d(t.p2l(e))},t.setScale=function(){var e,r=t._gd._fullLayout._size;if(t._categories||(t._categories=[]),t.overlaying){var n=l.getFromId(t._gd,t.overlaying);t.domain=n.domain}for(t.range&&2===t.range.length&&t.range[0]!==t.range[1]||(t.range=[-1,1]),e=0;2>e;e++)i(t.range[e])||(t.range[e]=i(t.range[1-e])?t.range[1-e]*(e?10:.1):e?1:-1),t.range[e]<-(Number.MAX_VALUE/2)?t.range[e]=-(Number.MAX_VALUE/2):t.range[e]>Number.MAX_VALUE/2&&(t.range[e]=Number.MAX_VALUE/2);if("y"===t._id.charAt(0)?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[0]-t.range[1]),t._b=-t._m*t.range[1]):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[1]-t.range[0]),t._b=-t._m*t.range[0]),!isFinite(t._m)||!isFinite(t._b))throw a.notifier("Something went wrong with axis scaling","long"),t._gd._replotting=!1, +new Error("axis scaling")},t.l2p=function(e){return i(e)?n.round(t._b+t._m*e,2):o.BADNUM},t.p2l=function(e){return(e-t._b)/t._m},t.c2p=function(e,r){return t.l2p(t.c2l(e,r))},t.p2c=function(e){return t.l2c(t.p2l(e))},-1!==["linear","log","-"].indexOf(t.type))t.c2d=u,t.d2c=function(t){return t=s(t),i(t)?Number(t):o.BADNUM},t.d2l=function(e,r){return"log"===t.type?t.c2l(t.d2c(e),r):t.d2c(e)};else if("date"===t.type){if(t.c2d=function(t){return i(t)?a.ms2DateTime(t):o.BADNUM},t.d2c=function(t){return i(t)?Number(t):a.dateTime2ms(t)},t.d2l=t.d2c,t.range&&t.range.length>1)try{var f=t.range.map(a.dateTime2ms);!i(t.range[0])&&i(f[0])&&(t.range[0]=f[0]),!i(t.range[1])&&i(f[1])&&(t.range[1]=f[1])}catch(h){a.error(h,t.range)}}else"category"===t.type&&(t.c2d=function(e){return t._categories[Math.round(e)]},t.d2c=function(e){null!==e&&void 0!==e&&-1===t._categories.indexOf(e)&&t._categories.push(e);var r=t._categories.indexOf(e);return-1===r?o.BADNUM:r},t.d2l=t.d2c);t.makeCalcdata=function(e,r){var n,i,a;if(r in e)for(n=e[r],i=new Array(n.length),a=0;an?"0":"1.0"}var r=this.framework,n=r.select("g.choroplethlayer"),i=r.select("g.scattergeolayer"),a=this.projection,o=this.path,s=this.clipAngle;r.selectAll("path.basepath").attr("d",o),r.selectAll("path.graticulepath").attr("d",o),n.selectAll("path.choroplethlocation").attr("d",o),n.selectAll("path.basepath").attr("d",o),i.selectAll("path.js-line").attr("d",o),null!==s?(i.selectAll("path.point").style("opacity",e).attr("transform",t),i.selectAll("text").style("opacity",e).attr("transform",t)):(i.selectAll("path.point").attr("transform",t),i.selectAll("text").attr("transform",t))}},{"../../components/color":1048,"../../components/drawing":1071,"../../constants/xmlns_namespaces":1115,"../../lib/filter_visible":1123,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"./constants":1169,"./projections":1177,"./set_scale":1178,"./zoom":1179,"./zoom_reset":1180,d3:82,topojson:1043}],1171:[function(t,e,r){"use strict";var n=t("./geo"),i=t("../../plots/plots");r.name="geo",r.attr="geo",r.idRoot="geo",r.idRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"geo");void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var o=0;o=n}function a(t,e){for(var r=e[0],n=e[1],i=!1,a=0,o=t.length,s=o-1;o>a;s=a++){var l=t[a],u=l[0],c=l[1],f=t[s],h=f[0],p=f[1];c>n^p>n&&(h-u)*(n-c)/(p-c)+u>r&&(i=!i)}return i}function o(t){return t?t/Math.sin(t):1}function s(t){return t>1?P:-1>t?-P:Math.asin(t)}function l(t){return t>1?0:-1>t?z:Math.acos(t)}function u(t,e){var r=(2+P)*Math.sin(e);e/=2;for(var n=0,i=1/0;10>n&&Math.abs(i)>S;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(z*(4+z))*t*(1+Math.cos(e)),2*Math.sqrt(z/(4+z))*Math.sin(e)]}function c(t,e){function r(r,n){var i=N(r/e,n);return i[0]*=t,i}return arguments.length<2&&(e=t),1===e?N:e===1/0?h:(r.invert=function(r,n){var i=N.invert(r/t,n);return i[0]*=e,i},r)}function f(){var t=2,e=I(c),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}function h(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function p(t,e){return[3*t/(2*z)*Math.sqrt(z*z/3-e*e),e]}function d(t,e){return[t,1.25*Math.log(Math.tan(z/4+.4*e))]}function g(t){return function(e){var r,n=t*Math.sin(e),i=30;do e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e));while(Math.abs(r)>S&&--i>0);return e/2}}function v(t,e,r){function n(r,n){return[t*r*Math.cos(n=i(n)),e*Math.sin(n)]}var i=g(r);return n.invert=function(n,i){var a=s(i/e);return[n/(t*Math.cos(a)),s((2*a+Math.sin(2*a))/r)]},n}function m(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(-.013791+n*(.003971*r-.001529*n))),e*(1.007226+r*(.015085+n*(-.044475+.028874*r-.005916*n)))]}function y(t,e){var r,n=Math.min(18,36*Math.abs(e)/z),i=Math.floor(n),a=n-i,o=(r=D[i])[0],s=r[1],l=(r=D[++i])[0],u=r[1],c=(r=D[Math.min(19,++i)])[0],f=r[1];return[t*(l+a*(c-o)/2+a*a*(c-2*l+o)/2),(e>0?P:-P)*(u+a*(f-s)/2+a*a*(f-2*u+s)/2)]}function b(t,e){return[t*Math.cos(e),e]}function x(t,e){var r=Math.cos(e),n=o(l(r*Math.cos(t/=2)));return[2*r*Math.sin(t)*n,Math.sin(e)*n]}function _(t,e){var r=x(t,e);return[(r[0]+t/P)/2,(r[1]+e)/2]}t.geo.project=function(t,e){var n=e.stream;if(!n)throw new Error("not yet supported");return(t&&w.hasOwnProperty(t.type)?w[t.type]:r)(t,n)};var w={Feature:e,FeatureCollection:function(t,r){return{type:"FeatureCollection",features:t.features.map(function(t){return e(t,r)})}}},k=[],A=[],M={point:function(t,e){k.push([t,e])},result:function(){var t=k.length?k.length<2?{type:"Point",coordinates:k[0]}:{type:"MultiPoint",coordinates:k}:null;return k=[],t}},T={lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){k.length&&(A.push(k),k=[])},result:function(){var t=A.length?A.length<2?{type:"LineString",coordinates:A[0]}:{type:"MultiLineString",coordinates:A}:null;return A=[],t}},E={polygonStart:n,lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){var t=k.length;if(t){do k.push(k[0].slice());while(++t<4);A.push(k),k=[]}},polygonEnd:n,result:function(){if(!A.length)return null;var t=[],e=[];return A.forEach(function(r){i(r)?t.push([r]):e.push(r)}),e.forEach(function(e){var r=e[0];t.some(function(t){return a(t[0],r)?(t.push(e),!0):void 0})||t.push([e])}),A=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},L={Point:M,MultiPoint:M,LineString:T,MultiLineString:T,Polygon:E,MultiPolygon:E,Sphere:E},S=1e-6,C=S*S,z=Math.PI,P=z/2,R=(Math.sqrt(z),z/180),j=180/z,O=t.geo.projection,I=t.geo.projectionMutator;t.geo.interrupt=function(e){function r(t,r){for(var n=0>r?-1:1,i=l[+(0>r)],a=0,o=i.length-1;o>a&&t>i[a][2][0];++a);var s=e(t-i[a][1][0],r);return s[0]+=e(i[a][1][0],n*r>n*i[a][0][1]?i[a][0][1]:r)[0],s}function n(){s=l.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})})}function i(){for(var e=1e-6,r=[],n=0,i=l[0].length;i>n;++n){var o=l[0][n],s=180*o[0][0]/z,u=180*o[0][1]/z,c=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[s+e,u+e],[s+e,c-e],[f-e,c-e],[f-e,h+e]],30))}for(var n=l[1].length-1;n>=0;--n){var o=l[1][n],s=180*o[0][0]/z,u=180*o[0][1]/z,c=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[f-e,h-e],[f-e,c+e],[s+e,c+e],[s+e,u-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}function a(t,e){for(var r,n,i,a=-1,o=t.length,s=t[0],l=[];++au;++u)l.push([s[0]+u*n,s[1]+u*i]);s=r}return l.push(r),l}function o(t,e){return Math.abs(t[0]-e[0])n)],a=l[+(0>n)],u=0,c=i.length;c>u;++u){var f=i[u];if(f[0][0]<=t&&tS&&--i>0);return[t/(.8707+(a=n*n)*(-.131979+a*(-.013791+a*a*a*(.003971-.001529*a)))),n]},(t.geo.naturalEarth=function(){return O(m)}).raw=m;var D=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];D.forEach(function(t){t[1]*=1.0144}),y.invert=function(t,e){var r=e/P,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],u=l-o,c=l-2*s+o,f=2*(Math.abs(r)-s)/u,h=c/u,p=f*(1-h*f*(1-2*h*f));if(p>=0||1===a){n=(e>=0?5:-5)*(p+i);var d,g=50;do i=Math.min(18,Math.abs(n)/5),a=Math.floor(i),p=i-a,o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],n-=(d=(e>=0?P:-P)*(s+p*(l-o)/2+p*p*(l-2*s+o)/2)-e)*j;while(Math.abs(d)>C&&--g>0);break}}while(--a>=0);var v=D[a][0],m=D[a+1][0],y=D[Math.min(19,a+2)][0];return[t/(m+p*(y-v)/2+p*p*(y-2*m+v)/2),n*R]},(t.geo.robinson=function(){return O(y)}).raw=y,b.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return O(b)}).raw=b,x.invert=function(t,e){if(!(t*t+4*e*e>z*z+S)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),u=Math.cos(r/2),c=Math.sin(n),f=Math.cos(n),h=Math.sin(2*n),p=c*c,d=f*f,g=s*s,v=1-d*u*u,m=v?l(f*u)*Math.sqrt(a=1/v):a=0,y=2*m*f*s-t,b=m*c-e,x=a*(d*g+m*f*u*p),_=a*(.5*o*h-2*m*c*s),w=.25*a*(h*s-m*c*d*o),k=a*(p*u+m*g*f),A=_*w-k*x;if(!A)break;var M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return O(x)}).raw=x,_.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),u=Math.sin(2*n),c=s*s,f=o*o,h=Math.sin(r),p=Math.cos(r/2),d=Math.sin(r/2),g=d*d,v=1-f*p*p,m=v?l(o*p)*Math.sqrt(a=1/v):a=0,y=.5*(2*m*o*d+r/P)-t,b=.5*(m*s+n)-e,x=.5*a*(f*g+m*o*p*c)+.5/P,_=a*(h*u/4-m*s*d),w=.125*a*(u*d-m*s*f*h),k=.5*a*(c*p+m*g*o)+.5,A=_*w-k*x,M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return O(_)}).raw=_}e.exports=n},{}],1178:[function(t,e,r){"use strict";function n(t,e){var r=t.projection,n=t.lonaxis,o=t.lataxis,l=t.domain,u=t.framewidth||0,c=e.w*(l.x[1]-l.x[0]),f=e.h*(l.y[1]-l.y[0]),h=n.range[0]+s,p=n.range[1]-s,d=o.range[0]+s,g=o.range[1]-s,v=n._fullRange[0]+s,m=n._fullRange[1]-s,y=o._fullRange[0]+s,b=o._fullRange[1]-s;r._translate0=[e.l+c/2,e.t+f/2];var x=p-h,_=g-d,w=[h+x/2,d+_/2],k=r._rotate;r._center=[w[0]+k[0],w[1]+k[1]];var A=function(e){function n(t){return Math.min(_*c/(t[1][0]-t[0][0]),_*f/(t[1][1]-t[0][1]))}var o,s,l,x,_=e.scale(),w=r._translate0,k=i(h,d,p,g),A=i(v,y,m,b);l=a(e,k),o=n(l),x=a(e,A),r._fullScale=n(x),e.scale(o),l=a(e,k),s=[w[0]-l[0][0]+u,w[1]-l[0][1]+u],r._translate=s,e.translate(s),l=a(e,k),t._isAlbersUsa||e.clipExtent(l),o=r.scale*o,r._scale=o,t._width=Math.round(l[1][0])+u,t._height=Math.round(l[1][1])+u,t._marginX=(c-Math.round(l[1][0]))/2,t._marginY=(f-Math.round(l[1][1]))/2};return A}function i(t,e,r,n){var i=(r-t)/4;return{type:"Polygon",coordinates:[[[t,e],[t,n],[t+i,n],[t+2*i,n],[t+3*i,n],[r,n],[r,e],[r-i,e],[r-2*i,e],[r-3*i,e],[t,e]]]}}function a(t,e){return o.geo.path().projection(t).bounds(e)}var o=t("d3"),s=t("./constants").clipPad;e.exports=n},{"./constants":1169,d3:82}],1179:[function(t,e,r){"use strict";function n(t,e){var r;return(r=e._isScoped?a:e._clipAngle?s:o)(t,e.projection)}function i(t,e){var r=e._fullScale;return _.behavior.zoom().translate(t.translate()).scale(t.scale()).scaleExtent([.5*r,100*r])}function a(t,e){function r(){_.select(this).style(A)}function n(){o.scale(_.event.scale).translate(_.event.translate),t.render()}function a(){_.select(this).style(M)}var o=t.projection,s=i(o,e);return s.on("zoomstart",r).on("zoom",n).on("zoomend",a),s}function o(t,e){function r(t){return v.invert(t)}function n(t){var e=v(r(t));return Math.abs(e[0]-t[0])>y||Math.abs(e[1]-t[1])>y}function a(){_.select(this).style(A),l=_.mouse(this),u=v.rotate(),c=v.translate(),f=u,h=r(l)}function o(){return p=_.mouse(this),n(l)?(m.scale(v.scale()),void m.translate(v.translate())):(v.scale(_.event.scale),v.translate([c[0],_.event.translate[1]]),h?r(p)&&(g=r(p),d=[f[0]+(g[0]-h[0]),u[1],u[2]],v.rotate(d),f=d):(l=p,h=r(l)),void t.render())}function s(){_.select(this).style(M)}var l,u,c,f,h,p,d,g,v=t.projection,m=i(v,e),y=2;return m.on("zoomstart",a).on("zoom",o).on("zoomend",s),m}function s(t,e){function r(t){m++||t({type:"zoomstart"})}function n(t){t({type:"zoom"})}function a(t){--m||t({type:"zoomend"})}var o,s=t.projection,p={r:s.rotate(),k:s.scale()},d=i(s,e),g=x(d,"zoomstart","zoom","zoomend"),m=0,y=d.on;return d.on("zoomstart",function(){_.select(this).style(A);var t=_.mouse(this),e=s.rotate(),i=e,a=s.translate(),m=u(e);o=l(s,t),y.call(d,"zoom",function(){var r=_.mouse(this);if(s.scale(p.k=_.event.scale),o){if(l(s,r)){s.rotate(e).translate(a);var u=l(s,r),d=f(o,u),y=v(c(m,d)),b=p.r=h(y,o,i);isFinite(b[0])&&isFinite(b[1])&&isFinite(b[2])||(b=i),s.rotate(b),i=b}}else t=r,o=l(s,t);n(g.of(this,arguments))}),r(g.of(this,arguments))}).on("zoomend",function(){_.select(this).style(M),y.call(d,"zoom",null),a(g.of(this,arguments))}).on("zoom.redraw",function(){t.render()}),_.rebind(d,g,"on")}function l(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&m(r)}function u(t){var e=.5*t[0]*w,r=.5*t[1]*w,n=.5*t[2]*w,i=Math.sin(e),a=Math.cos(e),o=Math.sin(r),s=Math.cos(r),l=Math.sin(n),u=Math.cos(n);return[a*s*u+i*o*l,i*s*u-a*o*l,a*o*u+i*s*l,a*s*l-i*o*u]}function c(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],l=e[2],u=e[3];return[r*o-n*s-i*l-a*u,r*s+n*o+i*u-a*l,r*l-n*u+i*o+a*s,r*u+n*l-i*s+a*o]}function f(t,e){if(t&&e){var r=b(t,e),n=Math.sqrt(y(r,r)),i=.5*Math.acos(Math.max(-1,Math.min(1,y(t,e)))),a=Math.sin(i)/n;return n&&[Math.cos(i),r[2]*a,-r[1]*a,r[0]*a]}}function h(t,e,r){var n=g(e,2,t[0]);n=g(n,1,t[1]),n=g(n,0,t[2]-r[2]);var i,a,o=e[0],s=e[1],l=e[2],u=n[0],c=n[1],f=n[2],h=Math.atan2(s,o)*k,d=Math.sqrt(o*o+s*s);Math.abs(c)>d?(a=(c>0?90:-90)-h,i=0):(a=Math.asin(c/d)*k-h,i=Math.sqrt(d*d-c*c));var v=180-a-2*h,m=(Math.atan2(f,u)-Math.atan2(l,i))*k,y=(Math.atan2(f,u)-Math.atan2(l,-i))*k,b=p(r[0],r[1],a,m),x=p(r[0],r[1],v,y);return x>=b?[a,m,r[2]]:[v,y,r[2]]}function p(t,e,r,n){var i=d(r-t),a=d(n-e);return Math.sqrt(i*i+a*a)}function d(t){return(t%360+540)%360-180}function g(t,e,r){var n=r*w,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function v(t){return[Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),1-2*(t[1]*t[1]+t[2]*t[2]))*k,Math.asin(Math.max(-1,Math.min(1,2*(t[0]*t[2]-t[3]*t[1]))))*k,Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),1-2*(t[2]*t[2]+t[3]*t[3]))*k]}function m(t){var e=t[0]*w,r=t[1]*w,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function y(t,e){for(var r=0,n=0,i=t.length;i>n;++n)r+=t[n]*e[n];return r}function b(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function x(t){for(var e=0,r=arguments.length,n=[];++ep;++p){for(e=u[p],r=t[this.scene[e]._name],n=/Click to enter .+ title/.test(r.title)?"":r.title,d=0;2>=d;d+=2)this.labelEnable[p+d]=!1,this.labels[p+d]=o(n),this.labelColor[p+d]=s(r.titlefont.color),this.labelFont[p+d]=r.titlefont.family,this.labelSize[p+d]=r.titlefont.size,this.labelPad[p+d]=this.getLabelPad(e,r),this.tickEnable[p+d]=!1,this.tickColor[p+d]=s((r.tickfont||{}).color),this.tickAngle[p+d]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[p+d]=this.getTickPad(r),this.tickMarkLength[p+d]=0,this.tickMarkWidth[p+d]=r.tickwidth||0,this.tickMarkColor[p+d]=s(r.tickcolor),this.borderLineEnable[p+d]=!1,this.borderLineColor[p+d]=s(r.linecolor),this.borderLineWidth[p+d]=r.linewidth||0;c=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!c,l=this.hasAxisInAltrPos(e,r)&&!c,i=r.mirror||!1,f=c?-1!==String(i).indexOf("all"):!!i,h=c?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[p]=!0:l&&(this.labelEnable[p+2]=!0),a?this.tickEnable[p]=r.showticklabels:l&&(this.tickEnable[p+2]=r.showticklabels),(a||f)&&(this.borderLineEnable[p]=r.showline),(l||f)&&(this.borderLineEnable[p+2]=r.showline),(a||h)&&(this.tickMarkLength[p]=this.getTickMarkLength(r)),(l||h)&&(this.tickMarkLength[p+2]=this.getTickMarkLength(r)),this.gridLineEnable[p]=r.showgrid,this.gridLineColor[p]=s(r.gridcolor),this.gridLineWidth[p]=r.gridwidth,this.zeroLineEnable[p]=r.zeroline,this.zeroLineColor[p]=s(r.zerolinecolor),this.zeroLineWidth[p]=r.zerolinewidth}},l.hasSharedAxis=function(t){var e=this.scene,r=a.Plots.getSubplotIds(e.fullLayout,"gl2d"),n=a.Axes.findSubplotsWithAxis(r,t);return 0!==n.indexOf(e.id)},l.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},l.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},l.getLabelPad=function(t,e){var r=1.5,n=e.titlefont.size,i=e.showticklabels;return"xaxis"===t?"top"===e.side?-10+n*(r+(i?1:0)):-10+n*(r+(i?.5:0)):"yaxis"===t?"right"===e.side?10+n*(r+(i?1:.5)):10+n*(r+(i?.5:0)):void 0},l.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},l.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e},e.exports=i},{"../../lib/html2unicode":1126,"../../lib/str2rgbarray":1139,"../../plotly":1147}],1183:[function(t,e,r){"use strict";var n=t("./scene2d"),i=t("../plots"),a=t("../../constants/xmlns_namespaces");r.name="gl2d",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex={x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},r.attrRegex={x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},r.attributes=t("../cartesian/attributes"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"gl2d"),o=0;or;++r){var n=t[r],i=e[r];if(n.length!==i.length)return!0;for(var a=0;ao;++o,--s)for(var l=0;r>l;++l)for(var u=0;4>u;++u){var c=i[4*(r*o+l)+u];i[4*(r*o+l)+u]=i[4*(r*s+l)+u],i[4*(r*s+l)+u]=c}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),p=h.createImageData(r,n);p.data.set(i),h.putImageData(p,0,0);var d;switch(t){case"jpeg":d=f.toDataURL("image/jpeg");break;case"webp":d=f.toDataURL("image/webp");break;default:d=f.toDataURL("image/png")}return this.staticPlot&&this.container.removeChild(a),d},m.computeTickMarks=function(){this.xaxis._length=this.glplot.viewBox[2]-this.glplot.viewBox[0],this.yaxis._length=this.glplot.viewBox[3]-this.glplot.viewBox[1];for(var t=[s.calcTicks(this.xaxis),s.calcTicks(this.yaxis)],e=0;2>e;++e)for(var r=0;rk;++k)w[k]=Math.min(w[k],a.bounds[k]),w[k+2]=Math.max(w[k+2],a.bounds[k+2])}var A;for(n=0;2>n;++n)w[n]>w[n+2]&&(w[n]=-1,w[n+2]=1),A=this[v[n]],A._length=y.viewBox[n+2]-y.viewBox[n],s.doAutoRange(A);y.ticks=this.computeTickMarks();var M=this.xaxis.range,T=this.yaxis.range;y.dataBox=[M[0],T[0],M[1],T[1]],y.merge(r),o.update(y),this.glplot.draw()},m.draw=function(){if(!this.stopped){requestAnimationFrame(this.redraw);var t=this.glplot,e=this.camera,r=e.mouseListener,n=this.fullLayout;this.cameraChanged();var i=r.x*t.pixelRatio,a=this.canvas.height-t.pixelRatio*r.y;if(e.boxEnabled&&"zoom"===n.dragmode)this.selectBox.enabled=!0,this.selectBox.selectBox=[Math.min(e.boxStart[0],e.boxEnd[0]),Math.min(e.boxStart[1],e.boxEnd[1]),Math.max(e.boxStart[0],e.boxEnd[0]),Math.max(e.boxStart[1],e.boxEnd[1])],t.setDirty();else{this.selectBox.enabled=!1;var o=n._size,s=this.xaxis.domain,u=this.yaxis.domain,c=t.pick(i/t.pixelRatio+o.l+s[0]*o.w,a/t.pixelRatio-(o.t+(1-u[1])*o.h));if(c&&n.hovermode){var f=c.object._trace.handlePick(c);if(f&&(!this.lastPickResult||this.lastPickResult.trace!==f.trace||this.lastPickResult.dataCoord[0]!==f.dataCoord[0]||this.lastPickResult.dataCoord[1]!==f.dataCoord[1])){var h=this.lastPickResult=f;this.spikes.update({center:c.dataCoord}),h.screenCoord=[((t.viewBox[2]-t.viewBox[0])*(c.dataCoord[0]-t.dataBox[0])/(t.dataBox[2]-t.dataBox[0])+t.viewBox[0])/t.pixelRatio,(this.canvas.height-(t.viewBox[3]-t.viewBox[1])*(c.dataCoord[1]-t.dataBox[1])/(t.dataBox[3]-t.dataBox[1])-t.viewBox[1])/t.pixelRatio];var p=h.hoverinfo;if("all"!==p){var d=p.split("+");-1===d.indexOf("x")&&(h.traceCoord[0]=void 0),-1===d.indexOf("y")&&(h.traceCoord[1]=void 0),-1===d.indexOf("z")&&(h.traceCoord[2]=void 0),-1===d.indexOf("text")&&(h.textLabel=void 0),-1===d.indexOf("name")&&(h.name=void 0)}l.loneHover({x:h.screenCoord[0],y:h.screenCoord[1],xLabel:this.hoverFormatter("xaxis",h.traceCoord[0]),yLabel:this.hoverFormatter("yaxis",h.traceCoord[1]),zLabel:h.traceCoord[2],text:h.textLabel,name:h.name,color:h.color},{container:this.svgContainer}),this.lastPickResult={dataCoord:c.dataCoord}}}else!c&&this.lastPickResult&&(this.spikes.update({}),this.lastPickResult=null,l.loneUnhover(this.svgContainer))}t.draw()}},m.hoverFormatter=function(t,e){if(void 0!==e){var r=this[t];return s.tickText(r,r.c2l(e),"hover").text}}},{"../../lib/html2unicode":1126,"../../lib/show_no_webgl_msg":1137,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"./camera":1181,"./convert":1182,"gl-plot2d":452,"gl-select-box":937,"gl-spikes2d":938}],1185:[function(t,e,r){"use strict";function n(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]),"zoomMin"in e&&(r[0]=e.zoomMin),"zoomMax"in e&&(r[1]=e.zoomMax);var n=a({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],u=0,c=t.clientWidth,f=t.clientHeight,h={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=i(),r=this.delay,a=e-2*r;n.idle(e-r),n.recalcMatrix(a),n.flush(e-(100+2*r));for(var o=!0,s=n.computedMatrix,h=0;16>h;++h)o=o&&l[h]===s[h],l[h]=s[h];var p=t.clientWidth===c&&t.clientHeight===f;return c=t.clientWidth,f=t.clientHeight,o?!p:(u=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),a=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var o=i();n._active.lookAt(o,r,a,e),n._active.lookAt(o+500,r,a,[0,0,1]),n._active.flush(o)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return u},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var p=0,d=0;return o(t,function(e,r,a,o){var s="rotate"===h.keyBindingMode,l="pan"===h.keyBindingMode,c="zoom"===h.keyBindingMode,f=!!o.control,g=!!o.alt,v=!!o.shift,m=!!(1&e),y=!!(2&e),b=!!(4&e),x=1/t.clientHeight,_=x*(r-p),w=x*(a-d),k=h.flipX?1:-1,A=h.flipY?1:-1,M=i(),T=Math.PI*h.rotateSpeed;if((s&&m&&!f&&!g&&!v||m&&!f&&!g&&v)&&n.rotate(M,k*T*_,-A*T*w,0),(l&&m&&!f&&!g&&!v||y||m&&f&&!g&&!v)&&n.pan(M,-h.translateSpeed*_*u,h.translateSpeed*w*u,0),c&&m&&!f&&!g&&!v||b||m&&!f&&g&&!v){var E=-h.zoomSpeed*w/window.innerHeight*(M-n.lastT())*100;n.pan(M,0,0,u*(Math.exp(E)-1))}return p=r,d=a,!0}),s(t,function(t,e){var r=h.flipX?1:-1,a=h.flipY?1:-1,o=i();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*h.rotateSpeed/window.innerWidth);else{var s=-h.zoomSpeed*a*e/window.innerHeight*(o-n.lastT())/100;n.pan(o,0,0,u*(Math.exp(s)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],1186:[function(t,e,r){"use strict";function n(t,e){for(var r=0;3>r;++r){var n=s[r];e[n]._gd=t}}var i=t("./scene"),a=t("../plots"),o=t("../../constants/xmlns_namespaces"),s=["xaxis","yaxis","zaxis"];r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,o=a.getSubplotIds(e,"gl3d");e._paperdiv.style({width:e.width+"px",height:e.height+"px"}),t._context.setBackground(t,e.paper_bgcolor);for(var s=0;sr;++r){var n=t[u[r]];e.labels[r]=o(n.title),"titlefont"in n&&(n.titlefont.color&&(e.labelColor[r]=s(n.titlefont.color)),n.titlefont.family&&(e.labelFont[r]=n.titlefont.family),n.titlefont.size&&(e.labelSize[r]=n.titlefont.size)),"showline"in n&&(e.lineEnable[r]=n.showline),"linecolor"in n&&(e.lineColor[r]=s(n.linecolor)),"linewidth"in n&&(e.lineWidth[r]=n.linewidth),"showgrid"in n&&(e.gridEnable[r]=n.showgrid),"gridcolor"in n&&(e.gridColor[r]=s(n.gridcolor)),"gridwidth"in n&&(e.gridWidth[r]=n.gridwidth),"log"===n.type?e.zeroEnable[r]=!1:"zeroline"in n&&(e.zeroEnable[r]=n.zeroline),"zerolinecolor"in n&&(e.zeroLineColor[r]=s(n.zerolinecolor)),"zerolinewidth"in n&&(e.zeroLineWidth[r]=n.zerolinewidth),"ticks"in n&&n.ticks?e.lineTickEnable[r]=!0:e.lineTickEnable[r]=!1,"ticklen"in n&&(e.lineTickLength[r]=e._defaultLineTickLength[r]=n.ticklen),"tickcolor"in n&&(e.lineTickColor[r]=s(n.tickcolor)),"tickwidth"in n&&(e.lineTickWidth[r]=n.tickwidth),"tickangle"in n&&(e.tickAngle[r]="auto"===n.tickangle?0:Math.PI*-n.tickangle/180),"showticklabels"in n&&(e.tickEnable[r]=n.showticklabels),"tickfont"in n&&(n.tickfont.color&&(e.tickColor[r]=s(n.tickfont.color)),n.tickfont.family&&(e.tickFont[r]=n.tickfont.family),n.tickfont.size&&(e.tickSize[r]=n.tickfont.size)),"mirror"in n?-1!==["ticks","all","allticks"].indexOf(n.mirror)?(e.lineTickMirror[r]=!0,e.lineMirror[r]=!0):n.mirror===!0?(e.lineTickMirror[r]=!1,e.lineMirror[r]=!0):(e.lineTickMirror[r]=!1,e.lineMirror[r]=!1):e.lineMirror[r]=!1,"showbackground"in n&&n.showbackground!==!1?(e.backgroundEnable[r]=!0,e.backgroundColor[r]=s(n.backgroundcolor)):e.backgroundEnable[r]=!1}},e.exports=i},{"../../../lib/html2unicode":1126,"../../../lib/str2rgbarray":1139,arraytools:64}],1191:[function(t,e,r){"use strict";function n(t,e,r,n){for(var a=r("bgcolor"),l=i.combine(a,n.paper_bgcolor),u=Object.keys(o.camera),c=0;ce;++e){var r=t[o[e]];this.enabled[e]=r.showspikes,this.colors[e]=a(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness}},e.exports=i},{"../../../lib/str2rgbarray":1139}],1194:[function(t,e,r){"use strict";function n(t){for(var e=new Array(3),r=0;3>r;++r){for(var n=t[r],i=new Array(n.length),a=0;ac;++c){var f=i[s[c]];if(f._length=(r[c].hi-r[c].lo)*r[c].pixelsPerDataUnit/t.dataScale[c],Math.abs(f._length)===1/0)u[c]=[];else{f.range[0]=r[c].lo/t.dataScale[c],f.range[1]=r[c].hi/t.dataScale[c],f._m=1/(t.dataScale[c]*r[c].pixelsPerDataUnit),f.range[0]===f.range[1]&&(f.range[0]-=1,f.range[1]+=1);var h=f.tickmode;if("auto"===f.tickmode){f.tickmode="linear";var p=f.nticks||a.Lib.constrain(f._length/40,4,9);a.Axes.autoTicks(f,Math.abs(f.range[1]-f.range[0])/p)}for(var d=a.Axes.calcTicks(f),g=0;gc;++c){l[c]=.5*(t.glplot.bounds[0][c]+t.glplot.bounds[1][c]);for(var g=0;2>g;++g)e.bounds[g][c]=t.glplot.bounds[g][c]}t.contourLevels=n(u)}e.exports=i;var a=t("../../../plotly"),o=t("../../../lib/html2unicode"),s=["xaxis","yaxis","zaxis"],l=[0,0,0]},{"../../../lib/html2unicode":1126,"../../../plotly":1147}],1195:[function(t,e,r){"use strict";function n(t,e){var r,n,i=[0,0,0,0];for(r=0;4>r;++r)for(n=0;4>n;++n)i[n]+=t[4*r+n]*e[r];return i}function i(t,e){var r=n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])));return r}e.exports=i},{}],1196:[function(t,e,r){"use strict";function n(t){function e(e,r){if("string"==typeof r)return r;var n=t.fullSceneLayout[e];return g.tickText(n,n.c2l(r),"hover").text}var r,n=t.svgContainer,i=t.container.getBoundingClientRect(),a=i.width,o=i.height;n.setAttributeNS(null,"viewBox","0 0 "+a+" "+o),n.setAttributeNS(null,"width",a),n.setAttributeNS(null,"height",o),A(t),t.glplot.axes.update(t.axesOptions);for(var s=Object.keys(t.traces),l=null,u=t.glplot.selection,c=0;ca;++a)l=c[T[a]],_(l);t?Array.isArray(t)||(t=[t]):t=[];var h=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]];for(a=0;ao;++o)h[0][o]>h[1][o]?p[o]=1:h[1][o]===h[0][o]?p[o]=1:p[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=p,a=0;aa;++a){if(l=c[T[a]],u=l.type,u in x?(x[u].acc*=p[a],x[u].count+=1):x[u]={acc:p[a],count:1},l.autorange){for(y[0][a]=1/0,y[1][a]=-(1/0),o=0;oy[1][a])y[0][a]=-1,y[1][a]=1;else{var k=y[1][a]-y[0][a];y[0][a]-=k/32,y[1][a]+=k/32}}else{var A=c[T[a]].range;y[0][a]=A[0],y[1][a]=A[1]}y[0][a]===y[1][a]&&(y[0][a]-=1,y[1][a]+=1),b[a]=y[1][a]-y[0][a],this.glplot.bounds[0][a]=y[0][a]*p[a],this.glplot.bounds[1][a]=y[1][a]*p[a]}var M=[1,1,1];for(a=0;3>a;++a){l=c[T[a]],u=l.type;var E=x[u];M[a]=Math.pow(E.acc,1/E.count)/p[a]}var L,S=4;if("auto"===c.aspectmode)L=Math.max.apply(null,M)/Math.min.apply(null,M)<=S?M:[1,1,1];else if("cube"===c.aspectmode)L=[1,1,1];else if("data"===c.aspectmode)L=M;else{if("manual"!==c.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var C=c.aspectratio;L=[C.x,C.y,C.z]}c.aspectratio.x=f.aspectratio.x=L[0],c.aspectratio.y=f.aspectratio.y=L[1],c.aspectratio.z=f.aspectratio.z=L[2],this.glplot.aspect=L;var z=c.domain||null,P=e._size||null;if(z&&P){var R=this.container.style;R.position="absolute",R.left=P.l+z.x[0]*P.w+"px",R.top=P.t+(1-z.y[1])*P.h+"px",R.width=P.w*(z.x[1]-z.x[0])+"px",R.height=P.h*(z.y[1]-z.y[0])+"px"}this.glplot.redraw()}},M.destroy=function(){this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null},M.setCameraToDefault=function(){this.setCamera({eye:{x:1.25,y:1.25,z:1.25},center:{x:0,y:0,z:0},up:{x:0,y:0,z:1}})},M.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),u(this.glplot.camera)},M.setCamera=function(t){var e={};e[this.id]=t,this.glplot.camera.lookAt.apply(this,l(t)),this.graphDiv.emit("plotly_relayout",e)},M.saveCamera=function(t){function e(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}var r=this.getCamera(),n=p.nestedProperty(t,this.id+".camera"),i=n.get(),a=!1;if(void 0===i)a=!0;else for(var o=0;3>o;o++)for(var s=0;3>s;s++)if(!e(r,i,o,s)){a=!0;break}return a&&n.set(r),a},M.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},M.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(c),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;o>a;++a,--o)for(var s=0;r>s;++s)for(var l=0;4>l;++l){var u=i[4*(r*a+s)+l];i[4*(r*a+s)+l]=i[4*(r*o+s)+l],i[4*(r*o+s)+l]=u}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),p=h.createImageData(r,n);p.data.set(i),h.putImageData(p,0,0);var d;switch(t){case"jpeg":d=f.toDataURL("image/jpeg");break;case"webp":d=f.toDataURL("image/webp");break;default:d=f.toDataURL("image/png")}return this.staticMode&&this.container.removeChild(c),d},e.exports=a},{"../../lib":1127,"../../lib/show_no_webgl_msg":1137,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/plots":1199,"./camera":1185,"./layout/convert":1190,"./layout/spikes":1193,"./layout/tick_marks":1194,"./project":1195,"./set_convert":1197,"gl-plot3d":626}],1197:[function(t,e,r){"use strict";var n=t("../cartesian/axes"),i=function(){};e.exports=function(t){n.setConvert(t),t.setScale=i}},{"../cartesian/axes":1150}],1198:[function(t,e,r){"use strict";var n=t("../plotly"),i=t("./font_attributes"),a=t("../components/color/attributes"),o=n.Lib.extendFlat;e.exports={font:{family:o({},i.family,{dflt:'"Open Sans", verdana, arial, sans-serif'}),size:o({},i.size,{dflt:12}),color:o({},i.color,{dflt:a.defaultLine})},title:{valType:"string",dflt:"Click to enter Plot title"},titlefont:o({},i,{}),autosize:{valType:"enumerated",values:[!0,!1,"initial"]},width:{valType:"number",min:10,dflt:700},height:{valType:"number",min:10,dflt:450},margin:{l:{valType:"number",min:0,dflt:80},r:{valType:"number",min:0,dflt:80},t:{valType:"number",min:0,dflt:100},b:{valType:"number",min:0,dflt:80},pad:{valType:"number",min:0,dflt:0},autoexpand:{valType:"boolean",dflt:!0}},paper_bgcolor:{valType:"color",dflt:a.background},plot_bgcolor:{valType:"color",dflt:a.background},separators:{valType:"string",dflt:".,"},hidesources:{valType:"boolean",dflt:!1},smith:{valType:"enumerated",values:[!1],dflt:!1},showlegend:{valType:"boolean"},_composedModules:{"*":"Fx"},_nestedModules:{xaxis:"Axes",yaxis:"Axes",scene:"gl3d",geo:"geo",legend:"Legend",annotations:"Annotations",shapes:"Shapes",images:"Images",ternary:"ternary",mapbox:"mapbox"}}},{"../components/color/attributes":1047,"../plotly":1147,"./font_attributes":1168}],1199:[function(t,e,r){"use strict";function n(t){return"object"==typeof t&&(t=t.type),t}function i(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#","class":"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){f.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}function a(t,e){for(var r,n=Object.keys(e),i=0;i=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var s=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),u=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&i(t,s),l.text(s.text()&&u.text()?" - ":"")},f.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=o.select(t).append("div").attr("id","hiddenform").style("display","none"),n=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"}),i=n.append("input").attr({type:"text",name:"data"});return i.node().value=f.graphJson(t,!1,"keepdata"),n.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1},f.supplyDefaults=function(t){var e,r,n=t._fullLayout||{},i=t._fullLayout={},o=t.layout||{},s=t._fullData||[],c=t._fullData=[],h=t.data||[],p=i._modules=[],d=i._basePlotModules=[];for(f.supplyLayoutGlobalDefaults(o,i),i._dataLength=h.length,e=0;ea&&(e=(r-1)/(i.l+i.r),i.l=Math.floor(e*i.l),i.r=Math.floor(e*i.r)),0>o&&(e=(n-1)/(i.t+i.b),i.t=Math.floor(e*i.t),i.b=Math.floor(e*i.b))}},f.autoMargin=function(t,e,r){var n=t._fullLayout;if(n._pushmargin||(n._pushmargin={}),n.margin.autoexpand!==!1){if(r){var i=void 0===r.pad?12:r.pad;r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];t._replotting||f.doAutoMargin(t)}},f.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),a=Math.max(e.margin.r||0,0),o=Math.max(e.margin.t||0,0),u=Math.max(e.margin.b||0,0),c=e._pushmargin;return e.margin.autoexpand!==!1&&(c.base={l:{val:0,size:i},r:{val:1,size:a},t:{val:1,size:o},b:{val:0,size:u}},Object.keys(c).forEach(function(t){var r=c[t].l||{},n=c[t].b||{},l=r.val,f=r.size,h=n.val,p=n.size;Object.keys(c).forEach(function(t){if(s(f)&&c[t].r){var r=c[t].r.val,n=c[t].r.size;if(r>l){var d=(f*r+(n-e.width)*l)/(r-l),g=(n*(1-l)+(f-e.width)*(1-r))/(r-l);d>=0&&g>=0&&d+g>i+a&&(i=d,a=g)}}if(s(p)&&c[t].t){var v=c[t].t.val,m=c[t].t.size;if(v>h){var y=(p*v+(m-e.height)*h)/(v-h),b=(m*(1-h)+(p-e.height)*(1-v))/(v-h);y>=0&&b>=0&&y+b>u+o&&(u=y,o=b)}}})})),r.l=Math.round(i),r.r=Math.round(a),r.t=Math.round(o),r.b=Math.round(u),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,t._replotting||"{}"===n||n===JSON.stringify(e._size)?void 0:l.plot(t)},f.graphJson=function(t,e,r,n,i){function a(t){if("function"==typeof t)return null;if(u.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0&&!u.isPlainObject(t.stream))continue}else if("keepall"!==r&&(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0))continue;i[e]=a(t[e])}return i}return Array.isArray(t)?t.map(a):t&&t.getTime?u.ms2DateTime(t):t}(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&f.supplyDefaults(t);var o=i?t._fullData:t.data,s=i?t._fullLayout:t.layout,l={data:(o||[]).map(function(t){var r=a(t);return e&&delete r.fit,r})};return e||(l.layout=a(s)),t.framework&&t.framework.isPolar&&(l=t.framework.getConfig()),"object"===n?l:JSON.stringify(l)}},{"../components/color":1048,"../lib":1127,"../plotly":1147,"./attributes":1148,"./font_attributes":1168,"./layout_attributes":1198,d3:82,"fast-isnumeric":90}],1200:[function(t,e,r){"use strict";var n=t("../../traces/scatter/attributes"),i=n.marker;e.exports={r:n.r,t:n.t,marker:{color:i.color,size:i.size,symbol:i.symbol,opacity:i.opacity}}},{"../../traces/scatter/attributes":1301}],1201:[function(t,e,r){"use strict";function n(t,e){var r={showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}};return a({},e,r)}var i=t("../cartesian/layout_attributes"),a=t("../../lib/extend").extendFlat,o=a({},i.domain,{});e.exports={radialaxis:n("radial",{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:n("angular",{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}}},{"../../lib/extend":1122,"../cartesian/layout_attributes":1159}],1202:[function(t,e,r){var n=t("../../plotly"),i=t("d3"),a=e.exports={version:"0.2.2",manager:t("./micropolar_manager")},o=n.Lib.extendDeepAll;a.Axis=function(){function t(t){r=t||r;var u=l.data,f=l.layout;return("string"==typeof r||r.nodeName)&&(r=i.select(r)),r.datum(u).each(function(t,r){function l(t,e){return s(t)%360+f.orientation}var u=t.slice();c={data:a.util.cloneJson(u),layout:a.util.cloneJson(f)};var h=0;u.forEach(function(t,e){t.color||(t.color=f.defaultColorRange[h],h=(h+1)%f.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:i.rgb(t.color).darker().toString()),c.data[e].color=t.color,c.data[e].strokeColor=t.strokeColor,c.data[e].strokeDash=t.strokeDash,c.data[e].strokeSize=t.strokeSize});var p=u.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||r===!0}),d=!1,g=p.map(function(t,e){return d=d||"undefined"!=typeof t.groupId,t});if(d){var v=i.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),m=[],y=v.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],m.push(r),r=a.util.sumArrays(t.r,r)}),t.values});p=i.merge(y)}p.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var b=Math.min(f.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2;b=Math.max(10,b);var x,_=[f.margin.left+b,f.margin.top+b];if(d){var w=i.max(a.util.sumArrays(a.util.arrayLast(p).r[0],a.util.arrayLast(m)));x=[0,w]}else x=i.extent(a.util.flattenArray(p.map(function(t,e){return t.r})));f.radialAxis.domain!=a.DATAEXTENT&&(x[0]=0),n=i.scale.linear().domain(f.radialAxis.domain!=a.DATAEXTENT&&f.radialAxis.domain?f.radialAxis.domain:x).range([0,b]),c.layout.radialAxis.domain=n.domain();var k,A=a.util.flattenArray(p.map(function(t,e){return t.t})),M="string"==typeof A[0];M&&(A=a.util.deduplicate(A),k=A.slice(),A=i.range(A.length),p=p.map(function(t,e){var r=t;return t.t=[A],d&&(r.yStack=t.yStack),r}));var T=p.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===p.length,E=null===f.needsEndSpacing?M||!T:f.needsEndSpacing,L=f.angularAxis.domain&&f.angularAxis.domain!=a.DATAEXTENT&&!M&&f.angularAxis.domain[0]>=0,S=L?f.angularAxis.domain:i.extent(A),C=Math.abs(A[1]-A[0]);T&&!M&&(C=0);var z=S.slice();E&&M&&(z[1]+=C);var P=f.angularAxis.ticksCount||4;P>8&&(P=P/(P/8)+P%8),f.angularAxis.ticksStep&&(P=(z[1]-z[0])/P);var R=f.angularAxis.ticksStep||(z[1]-z[0])/(P*(f.minorTicks+1));k&&(R=Math.max(Math.round(R),1)),z[2]||(z[2]=R);var j=i.range.apply(this,z);if(j=j.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=i.scale.linear().domain(z.slice(0,2)).range("clockwise"===f.direction?[0,360]:[360,0]),c.layout.angularAxis.domain=s.domain(),c.layout.angularAxis.endPadding=E?C:0,e=i.select(this).select("svg.chart-root"),"undefined"==typeof e||e.empty()){var O="' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '",I=(new DOMParser).parseFromString(O,"application/xml"),N=this.appendChild(this.ownerDocument.importNode(I.documentElement,!0));e=i.select(N)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var F,D=e.select(".chart-group"),B={fill:"none",stroke:f.tickColor},U={"font-size":f.font.size,"font-family":f.font.family,fill:f.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+f.font.outlineColor}).join(",")};if(f.showLegend){F=e.select(".legend-group").attr({transform:"translate("+[b,f.margin.top]+")"}).style({display:"block"});var V=p.map(function(t,e){var r=a.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});a.Legend().config({data:p.map(function(t,e){return t.name||"Element"+e}),legendConfig:o({},a.Legend.defaultConfig().legendConfig,{container:F,elements:V,reverseOrder:f.legend.reverseOrder})})();var q=F.node().getBBox();b=Math.min(f.width-q.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2,b=Math.max(10,b),_=[f.margin.left+b,f.margin.top+b],n.range([0,b]),c.layout.radialAxis.domain=n.domain(),F.attr("transform","translate("+[_[0]+b,_[1]-b]+")")}else F=e.select(".legend-group").style({display:"none"});e.attr({width:f.width,height:f.height}).style({opacity:f.opacity}),D.attr("transform","translate("+_+")").style({cursor:"crosshair"});var G=[(f.width-(f.margin.left+f.margin.right+2*b+(q?q.width:0)))/2,(f.height-(f.margin.top+f.margin.bottom+2*b))/2];if(G[0]=Math.max(0,G[0]),G[1]=Math.max(0,G[1]),e.select(".outer-group").attr("transform","translate("+G+")"),f.title){var H=e.select("g.title-group text").style(U).text(f.title),Y=H.node().getBBox();H.attr({x:_[0]-Y.width/2,y:_[1]-b-20})}var X=e.select(".radial.axis-group");if(f.radialAxis.gridLinesVisible){var W=X.selectAll("circle.grid-circle").data(n.ticks(5));W.enter().append("circle").attr({"class":"grid-circle"}).style(B),W.attr("r",n),W.exit().remove()}X.select("circle.outside-circle").attr({r:b}).style(B);var Z=e.select("circle.background-circle").attr({r:b}).style({fill:f.backgroundColor,stroke:f.stroke});if(f.radialAxis.visible){var K=i.svg.axis().scale(n).ticks(5).tickSize(5);X.call(K).attr({transform:"rotate("+f.radialAxis.orientation+")"}),X.selectAll(".domain").style(B),X.selectAll("g>text").text(function(t,e){return this.textContent+f.radialAxis.ticksSuffix}).style(U).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===f.radialAxis.tickOrientation?"rotate("+-f.radialAxis.orientation+") translate("+[0,U["font-size"]]+")":"translate("+[0,U["font-size"]]+")"}}),X.selectAll("g>line").style({stroke:"black"})}var $=e.select(".angular.axis-group").selectAll("g.angular-tick").data(j),Q=$.enter().append("g").classed("angular-tick",!0);$.attr({transform:function(t,e){return"rotate("+l(t,e)+")"}}).style({display:f.angularAxis.visible?"block":"none"}),$.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(f.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(f.minorTicks+1)==0)}).style(B),Q.selectAll(".minor").style({stroke:f.minorTickColor}),$.select("line.grid-line").attr({x1:f.tickLength?b-f.tickLength:0,x2:b}).style({display:f.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(U);var J=$.select("text.axis-text").attr({x:b+f.labelOffset,dy:".35em",transform:function(t,e){var r=l(t,e),n=b+f.labelOffset,i=f.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?270>r&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(180>=r&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:f.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(f.minorTicks+1)!=0?"":k?k[t]+f.angularAxis.ticksSuffix:t+f.angularAxis.ticksSuffix}).style(U);f.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(f.minorTicks+1)!=0?"":f.angularAxis.rewriteTicks(this.textContent,e)});var tt=i.max(D.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));F.attr({transform:"translate("+[b+tt,f.margin.top]+")"});var et=e.select("g.geometry-group").selectAll("g").size()>0,rt=e.select("g.geometry-group").selectAll("g.geometry").data(p);if(rt.enter().append("g").attr({"class":function(t,e){return"geometry geometry"+e}}),rt.exit().remove(),p[0]||et){var nt=[];p.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=s,r.container=rt.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=f.orientation,r.direction=f.direction,r.index=e,nt.push({data:t,geometryConfig:r})});var it=i.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(nt),at=[];it.forEach(function(t,e){"unstacked"===t.key?at=at.concat(t.values.map(function(t,e){return[t]})):at.push(t.values)}),at.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return o(a[r].defaultConfig(),t)});a[r]().config(n)()})}var ot,st,lt=e.select(".guides-group"),ut=e.select(".tooltips-group"),ct=a.tooltipPanel().config({container:ut,fontSize:8})(),ft=a.tooltipPanel().config({container:ut,fontSize:8})(),ht=a.tooltipPanel().config({container:ut,hasTick:!0})();if(!M){var pt=lt.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});D.on("mousemove.angular-guide",function(t,e){var r=a.util.getMousePos(Z).angle;pt.attr({x2:-b,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-f.orientation)%360;ot=s.invert(n);var i=a.util.convertToCartesian(b+12,r+180);ct.text(a.util.round(ot)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){lt.select("line").style({opacity:0})})}var dt=lt.select("circle").style({stroke:"grey",fill:"none"});D.on("mousemove.radial-guide",function(t,e){var r=a.util.getMousePos(Z).radius;dt.attr({r:r}).style({opacity:.5}),st=n.invert(a.util.getMousePos(Z).radius);var i=a.util.convertToCartesian(r,f.radialAxis.orientation);ft.text(a.util.round(st)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){dt.style({opacity:0}),ht.hide(),ct.hide(),ft.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(t,r){var n=i.select(this),o=n.style("fill"),s="black",l=n.style("opacity")||1;if(n.attr({"data-opacity":l}),"none"!=o){n.attr({"data-fill":o}),s=i.hsl(o).darker().toString(),n.style({fill:s,opacity:1});var u={t:a.util.round(t[0]),r:a.util.round(t[1])};M&&(u.t=k[t[0]]);var c="t: "+u.t+", r: "+u.r,f=this.getBoundingClientRect(),h=e.node().getBoundingClientRect(),p=[f.left+f.width/2-G[0]-h.left,f.top+f.height/2-G[1]-h.top];ht.config({color:s}).text(c),ht.move(p)}else o=n.style("stroke"),n.attr({"data-stroke":o}),s=i.hsl(o).darker().toString(),n.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){return 0!=i.event.which?!1:void(i.select(this).attr("data-fill")&&ht.show()); +}).on("mouseout.tooltip",function(t,e){ht.hide();var r=i.select(this),n=r.attr("data-fill");n?r.style({fill:n,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})}),h}var e,r,n,s,l={data:[],layout:{}},u={},c={},f=i.dispatch("hover"),h={};return h.render=function(e){return t(e),this},h.config=function(t){if(!arguments.length)return l;var e=a.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),o(l.data[e],a.Axis.defaultConfig().data[0]),o(l.data[e],t)}),o(l.layout,a.Axis.defaultConfig().layout),o(l.layout,e.layout),this},h.getLiveConfig=function(){return c},h.getinputConfig=function(){return u},h.radialScale=function(t){return n},h.angularScale=function(t){return s},h.svg=function(){return e},i.rebind(h,f,"on"),h},a.Axis.defaultConfig=function(t,e){var r={data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:i.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}};return r},a.util={},a.DATAEXTENT="dataExtent",a.AREA="AreaChart",a.LINE="LinePlot",a.DOT="DotPlot",a.BAR="BarChart",a.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},a.util._extend=function(t,e){for(var r in t)e[r]=t[r]},a.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},a.util.dataFromEquation2=function(t,e){var r=e||6,n=i.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180,i=t(n);return[e,i]});return n},a.util.dataFromEquation=function(t,e,r){var n=e||6,a=[],o=[];i.range(0,360+n,n).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},a.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return i.range(e).map(function(t,e){return r[e]||r[0]})},a.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=a.util.ensureArray(t[e],r)}),t},a.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},a.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},a.util.sumArrays=function(t,e){return i.zip(t,e).map(function(t,e){return i.sum(t)})},a.util.arrayLast=function(t){return t[t.length-1]},a.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},a.util.flattenArray=function(t){for(var e=[];!a.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},a.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},a.util.convertToCartesian=function(t,e){var r=e*Math.PI/180,n=t*Math.cos(r),i=t*Math.sin(r);return[n,i]},a.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},a.util.getMousePos=function(t){var e=i.mouse(t.node()),r=e[0],n=e[1],a={};return a.x=r,a.y=n,a.pos=e,a.angle=180*(Math.atan2(n,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+n*n),a},a.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;a>i;i++)e=t[i],e in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},a.util.duplicates=function(t){return Object.keys(a.util.duplicatesCount(t))},a.util.translator=function(t,e,r,n){if(n){var i=r.slice();r=e,e=i}var a=e.reduce(function(t,e){return"undefined"!=typeof t?t[e]:void 0},t);"undefined"!=typeof a&&(e.reduce(function(t,r,n){return"undefined"!=typeof t?(n===e.length-1&&delete t[r],t[r]):void 0},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=a),t[e]},t))},a.PolyChart=function(){function t(){var t=r[0].geometryConfig,e=t.container;"string"==typeof e&&(e=i.select(e)),e.datum(r).each(function(e,r){function n(e,r){var n=t.radialScale(e[1]),i=(t.angularScale(e[0])+t.orientation)*Math.PI/180;return{r:n,t:i}}function a(t){var e=t.r*Math.cos(t.t),r=t.r*Math.sin(t.t);return{x:e,y:r}}var o=!!e[0].data.yStack,l=e.map(function(t,e){return o?i.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):i.zip(t.data.t[0],t.data.r[0])}),u=t.angularScale,c=t.radialScale.domain()[0],f={};f.bar=function(r,n,a){var o=e[a].data,s=t.radialScale(r[1])-t.radialScale(0),l=t.radialScale(r[2]||0),c=o.barWidth;i.select(this).attr({"class":"mark bar",d:"M"+[[s+l,-c/2],[s+l,c/2],[l,c/2],[l,-c/2]].join("L")+"Z",transform:function(e,r){return"rotate("+(t.orientation+u(e[0]))+")"}})},f.dot=function(t,r,o){var s=t[2]?[t[0],t[1]+t[2]]:t,l=i.svg.symbol().size(e[o].data.dotSize).type(e[o].data.dotType)(t,r);i.select(this).attr({"class":"mark dot",d:l,transform:function(t,e){var r=a(n(s));return"translate("+[r.x,r.y]+")"}})};var h=i.svg.line.radial().interpolate(e[0].data.lineInterpolation).radius(function(e){return t.radialScale(e[1])}).angle(function(e){return t.angularScale(e[0])*Math.PI/180});f.line=function(r,n,a){var o=r[2]?l[a].map(function(t,e){return[t[0],t[1]+t[2]]}):l[a];if(i.select(this).each(f.dot).style({opacity:function(t,r){return+e[a].data.dotVisible},fill:v.stroke(r,n,a)}).attr({"class":"mark dot"}),!(n>0)){var s=i.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({"class":"line",d:h(o),transform:function(e,r){return"rotate("+(t.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return v.fill(r,n,a)},"fill-opacity":0,stroke:function(t,e){return v.stroke(r,n,a)},"stroke-width":function(t,e){return v["stroke-width"](r,n,a)},"stroke-dasharray":function(t,e){return v["stroke-dasharray"](r,n,a)},opacity:function(t,e){return v.opacity(r,n,a)},display:function(t,e){return v.display(r,n,a)}})}};var p=t.angularScale.range(),d=Math.abs(p[1]-p[0])/l[0].length*Math.PI/180,g=i.svg.arc().startAngle(function(t){return-d/2}).endAngle(function(t){return d/2}).innerRadius(function(e){return t.radialScale(c+(e[2]||0))}).outerRadius(function(e){return t.radialScale(c+(e[2]||0))+t.radialScale(e[1])});f.arc=function(e,r,n){i.select(this).attr({"class":"mark arc",d:g,transform:function(e,r){return"rotate("+(t.orientation+u(e[0])+90)+")"}})};var v={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,n){return s[e[n].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return"undefined"==typeof e[n].data.visible||e[n].data.visible?"block":"none"}},m=i.select(this).selectAll("g.layer").data(l);m.enter().append("g").attr({"class":"layer"});var y=m.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({"class":"mark"}),y.style(v).each(f[t.geometryType]),y.exit().remove(),m.exit().remove()})}var e,r=[a.PolyChart.defaultConfig()],n=i.dispatch("hover"),s={solid:"none",dash:[5,2],dot:[2,5]};return t.config=function(t){return arguments.length?(t.forEach(function(t,e){r[e]||(r[e]={}),o(r[e],a.PolyChart.defaultConfig()),o(r[e],t)}),this):r},t.getColorScale=function(){return e},i.rebind(t,n,"on"),t},a.PolyChart.defaultConfig=function(){var t={data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:i.scale.category20()}};return t},a.BarChart=function(){return a.PolyChart()},a.BarChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"bar"}};return t},a.AreaChart=function(){return a.PolyChart()},a.AreaChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"arc"}};return t},a.DotPlot=function(){return a.PolyChart()},a.DotPlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"dot",dotType:"circle"}};return t},a.LinePlot=function(){return a.PolyChart()},a.LinePlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"line"}};return t},a.Legend=function(){function t(){var r=e.legendConfig,n=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=o({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=i.merge(n);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||"undefined"==typeof r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var s=r.container;("string"==typeof s||s.nodeName)&&(s=i.select(s));var l=a.map(function(t,e){return t.color}),u=r.fontSize,c=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,f=c?r.height:u*a.length,h=s.classed("legend-group",!0),p=h.selectAll("svg").data([0]),d=p.enter().append("svg").attr({width:300,height:f+u,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var g=i.range(a.length),v=i.scale[c?"linear":"ordinal"]().domain(g).range(l),m=i.scale[c?"linear":"ordinal"]().domain(g)[c?"range":"rangePoints"]([0,f]),y=function(t,e){var r=3*e;return"line"===t?"M"+[[-e/2,-e/12],[e/2,-e/12],[e/2,e/12],[-e/2,e/12]]+"Z":-1!=i.svg.symbolTypes.indexOf(t)?i.svg.symbol().type(t).size(r)():i.svg.symbol().type("square").size(r)()};if(c){var b=p.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);b.enter().append("stop"),b.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),p.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var x=p.select(".legend-marks").selectAll("path.legend-mark").data(a);x.enter().append("path").classed("legend-mark",!0),x.attr({transform:function(t,e){return"translate("+[u/2,m(e)+u/2]+")"},d:function(t,e){var r=t.symbol;return y(r,u)},fill:function(t,e){return v(e)}}),x.exit().remove()}var _=i.svg.axis().scale(m).orient("right"),w=p.select("g.legend-axis").attr({transform:"translate("+[c?r.colorBandWidth:u,u/2]+")"}).call(_);return w.selectAll(".domain").style({fill:"none",stroke:"none"}),w.selectAll("line").style({fill:"none",stroke:c?r.textColor:"none"}),w.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),t}var e=a.Legend.defaultConfig(),r=i.dispatch("hover");return t.config=function(t){return arguments.length?(o(e,t),this):e},i.rebind(t,r,"on"),t},a.Legend.defaultConfig=function(t,e){var r={data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}};return r},a.tooltipPanel=function(){var t,e,r,n={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+a.tooltipPanel.uid++,l=10,u=function(){t=n.container.selectAll("g."+s).data([0]);var i=t.enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=i.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=i.append("text").attr({dx:n.padding+l,dy:.3*+n.fontSize}),u};return u.text=function(a){var o=i.hsl(n.color).l,s=o>=.5?"#aaa":"white",c=o>=.5?"black":"white",f=a||"";e.style({fill:c,"font-size":n.fontSize+"px"}).text(f);var h=n.padding,p=e.node().getBBox(),d={fill:n.color,stroke:s,"stroke-width":"2px"},g=p.width+2*h+l,v=p.height+2*h;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[n.hasTick?0:l,0],[l,v/4],[l,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(d),t.attr({transform:"translate("+[l,-v/2+2*h]+")"}),t.style({display:"block"}),u},u.move=function(e){return t?(t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),u):void 0},u.hide=function(){return t?(t.style({display:"none"}),u):void 0},u.show=function(){return t?(t.style({display:"block"}),u):void 0},u.config=function(t){return o(n,t),u},u},a.tooltipPanel.uid=1,a.adapter={},a.adapter.plotly=function(){var t={};return t.convert=function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=o({},t),i=[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]];return i.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",n.dotVisible===!0?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var n=a.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var i=n.indexOf(t.geometry);-1!=i&&(r.data[e].groupId=i)})}if(t.layout){var s=o({},t.layout),l=[[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]];if(l.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&"undefined"!=typeof s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&"undefined"!=typeof s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&"undefined"!=typeof s.margin.t){var u=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],f={};i.entries(s.margin).forEach(function(t,e){f[c[u.indexOf(t.key)]]=t.value}),s.margin=f}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r},t}},{"../../plotly":1147,"./micropolar_manager":1203,d3:82}],1203:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("d3"),a=t("./undo_manager"),o=e.exports={},s=n.Lib.extendDeepAll;o.framework=function(t){function e(e,a){return a&&(f=a),i.select(i.select(f).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),r=r?s(r,e):e,u||(u=n.micropolar.Axis()),c=n.micropolar.adapter.plotly().convert(r),u.config(c).render(f),t.data=r.data,t.layout=r.layout,o.fillLayout(t),r}var r,l,u,c,f,h=new a;return e.isPolar=!0,e.svg=function(){return u.svg()},e.getConfig=function(){return r},e.getLiveConfig=function(){return n.micropolar.adapter.plotly().convert(u.getLiveConfig(),!0)},e.getLiveScales=function(){return{t:u.angularScale(),r:u.radialScale()}},e.setUndoPoint=function(){var t=this,e=n.micropolar.util.cloneJson(r);!function(e,r){h.add({undo:function(){r&&t(r)},redo:function(){t(e)}})}(e,l),l=n.micropolar.util.cloneJson(e)},e.undo=function(){h.undo()},e.redo=function(){h.redo()},e},o.fillLayout=function(t){var e=i.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:n.Color.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../plotly":1147,"./undo_manager":1204,d3:82}],1204:[function(t,e,r){"use strict";e.exports=function(){function t(t,e){return t?(i=!0,t[e](),i=!1,this):this}var e,r=[],n=-1,i=!1;return{add:function(t){return i?this:(r.splice(n+1,r.length-n),r.push(t),n=r.length-1,this)},setCallback:function(t){e=t},undo:function(){var i=r[n];return i?(t(i,"undo"),n-=1,e&&e(i.undo),this):this},redo:function(){var i=r[n+1];return i?(t(i,"redo"),n+=1,e&&e(i.redo),this):this},clear:function(){r=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return ng;g++){var v=p[g];s=t[v]?t[v]:t[v]={},e[v]=l={},o("domain."+h,[g/d,(g+1)/d]),o("domain."+{x:"y",y:"x"}[h]),a.id=v,f(s,l,o,a)}}},{"../lib":1127,"./plots":1199}],1206:[function(t,e,r){"use strict";var n=t("./ternary"),i=t("../../plots/plots");r.name="ternary",r.attr="subplot",r.idRoot="ternary",r.idRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"ternary"),o=0;o=o&&(p.min=0,d.min=0,g.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}var i=t("../../../components/color"),a=t("../../subplot_defaults"),o=t("./layout_attributes"),s=t("./axis_defaults"),l=["aaxis","baxis","caxis"];e.exports=function(t,e,r){a(t,e,r,{type:"ternary",attributes:o,handleDefaults:n,font:e.font,paper_bgcolor:e.paper_bgcolor})}},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1209,"./layout_attributes":1211}],1211:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("./axis_attributes");e.exports={domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},bgcolor:{valType:"color",dflt:n.background},sum:{valType:"number",dflt:1,min:0},aaxis:i,baxis:i,caxis:i}},{"../../../components/color/attributes":1047,"./axis_attributes":1208}],1212:[function(t,e,r){"use strict";function n(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework()}function i(t){a.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var a=t("d3"),o=t("tinycolor2"),s=t("../../plotly"),l=t("../../lib"),u=t("../../components/color"),c=t("../../components/drawing"),f=t("../cartesian/set_convert"),h=t("../../lib/extend").extendFlat,p=t("../cartesian/axes"),d=t("../../lib/filter_visible"),g=t("../../components/dragelement"),v=t("../../components/titles"),m=t("../cartesian/select"),y=t("../cartesian/constants"),b=t("../cartesian/graph_interact");e.exports=n;var x=n.prototype;x.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={}},x.plot=function(t,e){var r,n=this,i=e[n.id],a=e._size;l.getPlotDiv(n.plotContainer.node())!==n.graphDiv&&(n.init(n.graphDiv._fullLayout),n.makeFramework()),n.adjustLayout(i,a);var o=n.traceHash,s={};for(r=0;r_*y?(a=y,i=a*_):(i=m,a=i/_),o=g*i/m,s=v*a/y,r=e.l+e.w*p-i/2,n=e.t+e.h*(1-d)-a/2,l.x0=r,l.y0=n,l.w=i,l.h=a,l.sum=b,l.xaxis={type:"linear",range:[x+2*k-b,b-x-2*w],domain:[p-o/2,p+o/2],_id:"x",_gd:l.graphDiv},f(l.xaxis),l.xaxis.setScale(),l.yaxis={type:"linear",range:[x,b-w-k],domain:[d-s/2,d+s/2],_id:"y",_gd:l.graphDiv},f(l.yaxis),l.yaxis.setScale();var A=l.yaxis.domain[0],M=l.aaxis=h({},t.aaxis,{range:[x,b-w-k],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[A,A+s*_],_axislayer:l.layers.aaxis,_gridlayer:l.layers.agrid,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2});f(M);var T=l.baxis=h({},t.baxis,{range:[b-x-k,w],side:"bottom",_counterangle:30,domain:l.xaxis.domain,_axislayer:l.layers.baxis,_gridlayer:l.layers.bgrid,_counteraxis:l.aaxis,_pos:0,_gd:l.graphDiv,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a});f(T),M._counteraxis=T;var E=l.caxis=h({},t.caxis,{range:[b-x-w,k],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[A,A+s*_],_axislayer:l.layers.caxis,_gridlayer:l.layers.cgrid,_counteraxis:l.baxis,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2});f(E);var L="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDef.select("path").attr("d",L),l.layers.plotbg.select("path").attr("d",L);var S="translate("+r+","+n+")";l.plotContainer.selectAll(".scatterlayer,.maplayer,.zoom").attr("transform",S);var C="translate("+r+","+(n+a)+")";l.layers.baxis.attr("transform",C),l.layers.bgrid.attr("transform",C);var z="translate("+(r+i/2)+","+n+")rotate(30)";l.layers.aaxis.attr("transform",z),l.layers.agrid.attr("transform",z);var P="translate("+(r+i/2)+","+n+")rotate(-30)";l.layers.caxis.attr("transform",P),l.layers.cgrid.attr("transform",P),l.drawAxes(!0),l.plotContainer.selectAll(".crisp").classed("crisp",!1);var R=l.layers.axlines;R.select(".aline").attr("d",M.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(u.stroke,M.linecolor||"#000").style("stroke-width",(M.linewidth||0)+"px"),R.select(".bline").attr("d",T.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(u.stroke,T.linecolor||"#000").style("stroke-width",(T.linewidth||0)+"px"),R.select(".cline").attr("d",E.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(u.stroke,E.linecolor||"#000").style("stroke-width",(E.linewidth||0)+"px")},x.drawAxes=function(t){var e=this,r=e.graphDiv,n=e.id.substr(7)+"title",i=e.aaxis,a=e.baxis,o=e.caxis;if(p.doTicks(r,i,!0),p.doTicks(r,a,!0),p.doTicks(r,o,!0),t){var s=Math.max(i.showticklabels?i.tickfont.size/2:0,(o.showticklabels?.75*o.tickfont.size:0)+("outside"===o.ticks?.87*o.ticklen:0));v.draw(r,"a"+n,{propContainer:i,propName:e.id+".aaxis.title",dfltName:"Component A",attributes:{x:e.x0+e.w/2,y:e.y0-i.titlefont.size/3-s,"text-anchor":"middle"}});var l=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;v.draw(r,"b"+n,{propContainer:a,propName:e.id+".baxis.title",dfltName:"Component B",attributes:{x:e.x0-l,y:e.y0+e.h+.83*a.titlefont.size+l,"text-anchor":"middle"}}),v.draw(r,"c"+n,{propContainer:o,propName:e.id+".caxis.title",dfltName:"Component C",attributes:{x:e.x0+e.w+l,y:e.y0+e.h+.83*o.titlefont.size+l,"text-anchor":"middle"}})}};var w=y.MINZOOM/2+.87,k="m-0.87,.5h"+w+"v3h-"+(w+5.2)+"l"+(w/2+2.6)+",-"+(.87*w+4.5)+"l2.6,1.5l-"+w/2+","+.87*w+"Z",A="m0.87,.5h-"+w+"v3h"+(w+5.2)+"l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-2.6,1.5l"+w/2+","+.87*w+"Z",M="m0,1l"+w/2+","+.87*w+"l2.6,-1.5l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-"+(w/2+2.6)+","+(.87*w+4.5)+"l2.6,1.5l"+w/2+",-"+.87*w+"Z",T="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",E=!0;x.initInteractions=function(){function t(t,e,r){var n=N.getBoundingClientRect();x=e-n.left,w=r-n.top,L={a:I.aaxis.range[0],b:I.baxis.range[1],c:I.caxis.range[1]},C=L,S=I.aaxis.range[1]-L.a,z=o(I.graphDiv._fullLayout[I.id].bgcolor).getLuminance(),P="M0,"+I.h+"L"+I.w/2+", 0L"+I.w+","+I.h+"Z",R=!1,j=D.append("path").attr("class","zoombox").style({fill:z>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",P),O=D.append("path").attr("class","zoombox-corners").style({fill:u.background,stroke:u.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),d()}function e(t,e){return 1-e/I.h}function r(t,e){return 1-(t+(I.h-e)/Math.sqrt(3))/I.w}function n(t,e){return(t-(I.h-e)/Math.sqrt(3))/I.w}function a(t,i){var a=x+t,o=w+i,s=Math.max(0,Math.min(1,e(x,w),e(a,o))),l=Math.max(0,Math.min(1,r(x,w),r(a,o))),u=Math.max(0,Math.min(1,n(x,w),n(a,o))),c=(s/2+u)*I.w,f=(1-s/2-l)*I.w,h=(c+f)/2,p=f-c,d=(1-s)*I.h,g=d-p/_;p.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),O.transition().style("opacity",1).duration(200),R=!0)}function c(t,e){if(C===L)return 2===e&&v(),i(F);i(F);var r={};r[I.id+".aaxis.min"]=C.a,r[I.id+".baxis.min"]=C.b,r[I.id+".caxis.min"]=C.c,s.relayout(F,r),E&&F.data&&F._context.showTips&&(l.notifier("Double-click to
zoom back out","long"),E=!1)}function f(){L={a:I.aaxis.range[0],b:I.baxis.range[1],c:I.caxis.range[1]},C=L}function h(t,e){var r=t/I.xaxis._m,n=e/I.yaxis._m;C={a:L.a-n,b:L.b+(r+n)/2,c:L.c-(r-n)/2};var i=[C.a,C.b,C.c].sort(),a={a:i.indexOf(C.a),b:i.indexOf(C.b),c:i.indexOf(C.c)};i[0]<0&&(i[1]+i[0]/2<0?(i[2]+=i[0]+i[1],i[0]=i[1]=0):(i[2]+=i[0]/2,i[1]+=i[0]/2,i[0]=0),C={a:i[a.a],b:i[a.b],c:i[a.c]},e=(L.a-C.a)*I.yaxis._m,t=(L.c-C.c-L.b+C.b)*I.xaxis._m);var o="translate("+(I.x0+t)+","+(I.y0+e)+")";I.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",o),I.aaxis.range=[C.a,I.sum-C.b-C.c],I.baxis.range=[I.sum-C.a-C.c,C.b], +I.caxis.range=[I.sum-C.a-C.b,C.c],I.drawAxes(!1),I.plotContainer.selectAll(".crisp").classed("crisp",!1)}function p(t,e){if(t){var r={};r[I.id+".aaxis.min"]=C.a,r[I.id+".baxis.min"]=C.b,r[I.id+".caxis.min"]=C.c,s.relayout(F,r)}else 2===e&&v()}function d(){I.plotContainer.selectAll(".select-outline").remove()}function v(){var t={};t[I.id+".aaxis.min"]=0,t[I.id+".baxis.min"]=0,t[I.id+".caxis.min"]=0,F.emit("plotly_doubleclick",null),s.relayout(F,t)}var x,w,L,S,C,z,P,R,j,O,I=this,N=I.layers.plotbg.select("path").node(),F=I.graphDiv,D=I.layers.zoom,B={element:N,gd:F,plotinfo:{plot:D},doubleclick:v,subplot:I.id,prepFn:function(e,r,n){B.xaxes=[I.xaxis],B.yaxes=[I.yaxis];var i=F._fullLayout.dragmode;e.shiftKey&&(i="pan"===i?"zoom":"pan"),"lasso"===i?B.minDrag=1:B.minDrag=void 0,"zoom"===i?(B.moveFn=a,B.doneFn=c,t(e,r,n)):"pan"===i?(B.moveFn=h,B.doneFn=p,f(),d()):"select"!==i&&"lasso"!==i||m(e,r,n,B,i)}};g.init(B),N.onmousemove=function(t){b.hover(F,t,I.id),F._fullLayout._lasthover=N,F._fullLayout._hoversubplot=I.id},N.onmouseout=function(t){F._dragging||g.unhover(F,t)},N.onclick=function(t){b.click(F,t)}}},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/extend":1122,"../../lib/filter_visible":1123,"../../plotly":1147,"../cartesian/axes":1150,"../cartesian/constants":1155,"../cartesian/graph_interact":1157,"../cartesian/select":1163,"../cartesian/set_convert":1164,d3:82,tinycolor2:1042}],1213:[function(t,e,r){"use strict";function n(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}function i(t){var e=["xaxis","yaxis","zaxis"];return e.indexOf(t.slice(0,5))>-1}var a=t("../plotly"),o=a.Lib.extendFlat,s=a.Lib.extendDeep;e.exports=function(t,e){t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var r,l=t.data,u=t.layout,c=s([],l),f=s({},u,n(e.tileClass));if(e.width&&(f.width=e.width),e.height&&(f.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){f.annotations=[];var h=Object.keys(f);for(r=0;rl;l++)n(r[l])&&p.push({p:r[l],s:s[l],b:0});return a(e,"marker")&&o(e,e.marker.color,"marker","c"),a(e,"marker.line")&&o(e,e.marker.line.color,"marker.line","c"),p}},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1223:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../scatter/xy_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,u){function c(r,i){return n.coerce(t,e,l,r,i)}var f=a(t,e,c);return f?(c("orientation",e.x&&!e.y?"h":"v"),c("text"),o(t,e,c,r,u),s(t,e,i.defaultLine,{axis:"y"}),void s(t,e,i.defaultLine,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"../scatter/xy_defaults":1324,"./attributes":1221}],1224:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../components/errorbars"),a=t("../../components/color");e.exports=function(t,e,r,o){var s,l=t.cd,u=l[0].trace,c=l[0].t,f=t.xa,h=t.ya,p="closest"===o?c.barwidth/2:c.dbar*(1-f._gd._fullLayout.bargap)/2;s="closest"!==o?function(t){return t.p}:"h"===u.orientation?function(t){return t.y}:function(t){return t.x};var d,g;"h"===u.orientation?(d=function(t){return n.inbox(t.b-e,t.x-e)+(t.x-e)/(t.x-t.b)},g=function(t){var e=s(t)-r;return n.inbox(e-p,e+p)}):(g=function(t){return n.inbox(t.b-r,t.y-r)+(t.y-r)/(t.y-t.b)},d=function(t){var r=s(t)-e;return n.inbox(r-p,r+p)});var v=n.getDistanceFunction(o,d,g);if(n.getClosest(l,v,t),t.index!==!1){var m=l[t.index],y=m.mcc||u.marker.color,b=m.mlcc||u.marker.line.color,x=m.mlw||u.marker.line.width;return a.opacity(y)?t.color=y:a.opacity(b)&&x&&(t.color=b),"h"===u.orientation?(t.x0=t.x1=f.c2p(m.x,!0),t.xLabelVal=m.s,t.y0=h.c2p(s(m)-p,!0),t.y1=h.c2p(s(m)+p,!0),t.yLabelVal=m.p):(t.y0=t.y1=h.c2p(m.y,!0),t.yLabelVal=m.s,t.x0=f.c2p(s(m)-p,!0),t.x1=f.c2p(s(m)+p,!0),t.xLabelVal=m.p),m.tx&&(t.text=m.tx),i.hoverInfo(m,u,t),[t]}}},{"../../components/color":1048,"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157}],1225:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","oriented","markerColorscale","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../scatter/colorbar":1304,"./arrays_to_calcdata":1220,"./attributes":1221,"./calc":1222,"./defaults":1223,"./hover":1224,"./layout_attributes":1226,"./layout_defaults":1227,"./plot":1228,"./set_positions":1229,"./style":1230}],1226:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:""},bargap:{valType:"number",min:0,max:1},bargroupgap:{valType:"number",min:0,max:1,dflt:0}}},{}],1227:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function s(r,n){return a.coerce(t,e,o,r,n)}for(var l=!1,u=!1,c=!1,f={},h=0;h=2?a(t):t>e?Math.ceil(t):Math.floor(t)}var h,p,d,g;if("h"===s.orientation?(d=c.c2p(r.poffset+e.p,!0),g=c.c2p(r.poffset+e.p+r.barwidth,!0),h=u.c2p(e.b,!0),p=u.c2p(e.s+e.b,!0)):(h=u.c2p(r.poffset+e.p,!0),p=u.c2p(r.poffset+e.p+r.barwidth,!0),g=c.c2p(e.s+e.b,!0),d=c.c2p(e.b,!0)),!(i(h)&&i(p)&&i(d)&&i(g)&&h!==p&&d!==g))return void n.select(this).remove();var v=(e.mlw+1||s.marker.line.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,m=n.round(v/2%1,2);if(!t._context.staticPlot){var y=o.opacity(e.mc||s.marker.color),b=1>y||v>.01?a:l;h=b(h,p),p=b(p,h),d=b(d,g),g=b(g,d)}n.select(this).attr("d","M"+h+","+d+"V"+g+"H"+p+"V"+d+"Z")})}),h.call(s.plot,e)}},{"../../components/color":1048,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1220,d3:82,"fast-isnumeric":90}],1229:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axes"),o=t("../../lib");e.exports=function(t,e){var r,s,l=t._fullLayout,u=e.x(),c=e.y();["v","h"].forEach(function(f){function h(e){function r(t){t[d]=t.p+h}var n=[];e.forEach(function(e){t.calcdata[e].forEach(function(t){n.push(t.p)})});var i=o.distinctVals(n),s=i.vals,u=i.minDiff,c=!1,f=[];"group"===l.barmode&&e.forEach(function(e){c||(t.calcdata[e].forEach(function(t){c||f.forEach(function(e){Math.abs(t.p-e)_&&(S=!0,M=_),_>A+R&&(S=!0,A=_))}a.expand(m,[M,A],{tozero:!0,padded:S})}else{var j=function(t){return t[g]=t.s,t.s};for(r=0;r1||0===s.bargap&&0===s.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),e.selectAll("g.points").each(function(t){var e=t[0].trace,r=e.marker,o=r.line,s=(e._input||{}).marker||{},l=a.tryColorscale(r,s,""),u=a.tryColorscale(r,s,"line.");n.select(this).selectAll("path").each(function(t){var e,a,s=(t.mlw+1||o.width+1)-1,c=n.select(this);e="mc"in t?t.mcc=l(t.mc):Array.isArray(r.color)?i.defaultLine:r.color,c.style("stroke-width",s+"px").call(i.fill,e),s&&(a="mlc"in t?t.mlcc=u(t.mlc):Array.isArray(o.color)?i.defaultLine:o.color,c.call(i.stroke,a))})}),e.call(o.style)}},{"../../components/color":1048,"../../components/drawing":1071,"../../components/errorbars":1077,d3:82}],1231:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width")}},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061}],1232:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/color/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=o.line;e.exports={y:{valType:"data_array"},x:{valType:"data_array"},x0:{valType:"any"},y0:{valType:"any"},whiskerwidth:{valType:"number",min:0,max:1,dflt:.5},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1},jitter:{valType:"number",min:0,max:1},pointpos:{valType:"number",min:-2,max:2},orientation:{valType:"enumerated",values:["v","h"]},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)"},symbol:a({},o.symbol,{arrayOk:!1}),opacity:a({},o.opacity,{arrayOk:!1,dflt:1}),size:a({},o.size,{arrayOk:!1}),color:a({},o.color,{arrayOk:!1}),line:{color:a({},s.color,{arrayOk:!1,dflt:i.defaultLine}),width:a({},s.width,{arrayOk:!1,dflt:0}),outliercolor:{valType:"color"},outlierwidth:{valType:"number",min:0,dflt:1}}},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2}},fillcolor:n.fillcolor}},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../scatter/attributes":1301}],1233:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes");e.exports=function(t,e){function r(t,e,r,a,o){var s;return r in e?d=a.makeCalcdata(e,r):(s=r+"0"in e?e[r+"0"]:"name"in e&&("category"===a.type||n(e.name)&&-1!==["linear","log"].indexOf(a.type)||i.isDateTime(e.name)&&"date"===a.type)?e.name:t.numboxes,s=a.d2c(s),d=o.map(function(){return s})),d}function o(t,e,r,a,o){var s,l,u,c,f=a.length,h=e.length,p=[],d=[];for(s=0;f>s;++s)l=a[s],t[s]={pos:l},d[s]=l-o,p[s]=[];for(d.push(a[f-1]+o),s=0;h>s;++s)c=e[s],n(c)&&(u=i.findBin(r[s],d),u>=0&&h>u&&p[u].push(c));return p}function s(t,e){var r,n,a,o;for(o=0;o1,m=r.dPos*(1-h.boxgap)*(1-h.boxgroupgap)/(v?t.numboxes:1),y=v?2*r.dPos*(-.5+(r.boxnum+.5)/t.numboxes)*(1-h.boxgap):0,b=m*g.whiskerwidth;return g.visible!==!0||r.emptybox?void a.select(this).remove():("h"===g.orientation?(l=d,f=p):(l=p,f=d),r.bPos=y,r.bdPos=m,n(),a.select(this).selectAll("path.box").data(o.identity).enter().append("path").attr("class","box").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=l.c2p(t.pos+y-b,!0),s=l.c2p(t.pos+y+b,!0),u=f.c2p(t.q1,!0),c=f.c2p(t.q3,!0),h=o.constrain(f.c2p(t.med,!0),Math.min(u,c)+1,Math.max(u,c)-1),p=f.c2p(g.boxpoints===!1?t.min:t.lf,!0),d=f.c2p(g.boxpoints===!1?t.max:t.uf,!0);"h"===g.orientation?a.select(this).attr("d","M"+h+","+r+"V"+n+"M"+u+","+r+"V"+n+"H"+c+"V"+r+"ZM"+u+","+e+"H"+p+"M"+c+","+e+"H"+d+(0===g.whiskerwidth?"":"M"+p+","+i+"V"+s+"M"+d+","+i+"V"+s)):a.select(this).attr("d","M"+r+","+h+"H"+n+"M"+r+","+u+"H"+n+"V"+c+"H"+r+"ZM"+e+","+u+"V"+p+"M"+e+","+c+"V"+d+(0===g.whiskerwidth?"":"M"+i+","+p+"H"+s+"M"+i+","+d+"H"+s))}),g.boxpoints&&a.select(this).selectAll("g.points").data(function(t){return t.forEach(function(t){t.t=r,t.trace=g}),t}).enter().append("g").attr("class","points").selectAll("path").data(function(t){var e,r,n,a,s,l,f,h="all"===g.boxpoints?t.val:t.val.filter(function(e){return et.uf}),p=(t.q3-t.q1)*c,d=[],v=0;if(g.jitter){for(e=0;et.lo&&(n.so=!0),n})}).enter().append("path").call(s.translatePoints,p,d),void(g.boxmean&&a.select(this).selectAll("path.mean").data(o.identity).enter().append("path").attr("class","mean").style("fill","none").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=f.c2p(t.mean,!0),o=f.c2p(t.mean-t.sd,!0),s=f.c2p(t.mean+t.sd,!0);"h"===g.orientation?a.select(this).attr("d","M"+i+","+r+"V"+n+("sd"!==g.boxmean?"":"m0,0L"+o+","+e+"L"+i+","+r+"L"+s+","+e+"Z")):a.select(this).attr("d","M"+r+","+i+"H"+n+("sd"!==g.boxmean?"":"m0,0L"+e+","+o+"L"+r+","+i+"L"+e+","+s+"Z"))})))})}},{"../../components/drawing":1071,"../../lib":1127,d3:82}],1240:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib");e.exports=function(t,e){var r,o,s,l,u=t._fullLayout,c=e.x(),f=e.y(),h=["v","h"];for(o=0;ol&&(e.z=c.slice(0,l)),s("locationmode"),s("text"),s("marker.line.color"),s("marker.line.width"),i(t,e,o,s,{prefix:"",cLetter:"z"}),void s("hoverinfo",1===o._dataLength?"location+z+text":void 0)):void(e.visible=!1)}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1242}],1245:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./plot").plot,n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":1171,"../heatmap/colorbar":1259,"./attributes":1242,"./calc":1243,"./defaults":1244,"./plot":1246}],1246:[function(t,e,r){"use strict";function n(t,e){function r(e){var r=t.mockAxis;return o.tickText(r,r.c2l(e),"hover").text}var n=e.hoverinfo;if("none"===n)return function(t){delete t.nameLabel, +delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("name"),s=-1!==i.indexOf("location"),l=-1!==i.indexOf("z"),u=-1!==i.indexOf("text"),c=!a&&s;return function(t){var n=[];c?t.nameLabel=t.id:(a&&(t.nameLabel=e.name),s&&n.push(t.id)),l&&n.push(r(t.z)),u&&n.push(t.tx),t.textLabel=n.join("
")}}function i(t){return function(e,r){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:r,location:e.id,z:e.z}]}}}var a=t("d3"),o=t("../../plots/cartesian/axes"),s=t("../../plots/cartesian/graph_interact"),l=t("../../components/color"),u=t("../../components/drawing"),c=t("../../components/colorscale/get_scale"),f=t("../../components/colorscale/make_scale_function"),h=t("../../lib/topojson_utils").getTopojsonFeatures,p=t("../../lib/geo_location_utils").locationToFeature,d=t("../../lib/array_to_calc_item"),g=t("../../plots/geo/constants"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){for(var r,n=[],i=t.locations,a=i.length,o=h(t,e),s=(t.marker||{}).line||{},l=0;a>l;l++)r=p(t.locationmode,i[l],o),void 0!==r&&(r.z=t.z[l],void 0!==t.text&&(r.tx=t.text[l]),d(s.color,r,"mlc",l),d(s.width,r,"mlw",l),n.push(r));return n.length>0&&(n[0].trace=t),n},m.plot=function(t,e,r){var o,l=t.framework,u=l.select("g.choroplethlayer"),c=l.select("g.baselayer"),f=l.select("g.baselayeroverchoropleth"),h=g.baseLayersOverChoropleth,p=u.selectAll("g.trace.choropleth").data(e,function(t){return t.uid});p.enter().append("g").attr("class","trace choropleth"),p.exit().remove(),p.each(function(e){function r(e,r){if(t.showHover){var n=t.projection(e.properties.ct);u(e),s.loneHover({x:n[0],y:n[1],name:e.nameLabel,text:e.textLabel},{container:t.hoverContainer.node()}),f=c(e,r),t.graphDiv.emit("plotly_hover",f)}}function o(e,r){t.graphDiv.emit("plotly_click",c(e,r))}var l=m.calcGeoJSON(e,t.topojson),u=n(t,e),c=i(e),f=null,h=a.select(this).selectAll("path.choroplethlocation").data(l);h.enter().append("path").classed("choroplethlocation",!0).on("mouseover",r).on("click",o).on("mouseout",function(){s.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",f)}).on("mousedown",function(){s.loneUnhover(t.hoverContainer)}).on("mouseup",r),h.exit().remove()}),f.selectAll("*").remove();for(var d=0;dr;r++)e=f[r],p[r]=e[0]*(t.zmax-t.zmin)+t.zmin,d[r]=e[1];var g=n.extent([t.zmin,t.zmax,a.start,a.start+l*(u-1)]),v=g[t.zminr;r++)e=f[r],p[r]=(e[0]*(u+c-1)-c/2)*l+o,d[r]=e[1];var y=n.scale.linear().interpolate(n.interpolateRgb).domain(p).range(d);return y}},{"../../components/colorscale/get_scale":1060,d3:82}],1254:[function(t,e,r){"use strict";function n(t,e,r){var n=r[0].trace,a=r[0].x,s=r[0].y,u=n.contours,c=n.uid,f=e.x(),h=e.y(),v=t._fullLayout,b="contour"+c,x=i(u,e,r[0]);if(n.visible!==!0)return v._paper.selectAll("."+b+",.hm"+c).remove(),void v._infolayer.selectAll(".cb"+c).remove();"heatmap"===u.coloring?(n.zauto&&n.autocontour===!1&&(n._input.zmin=n.zmin=u.start-u.size/2,n._input.zmax=n.zmax=n.zmin+x.length*u.size),k(t,e,[r])):v._paper.selectAll(".hm"+c).remove(),o(x),l(x);var _=f.c2p(a[0],!0),w=f.c2p(a[a.length-1],!0),A=h.c2p(s[0],!0),M=h.c2p(s[s.length-1],!0),T=[[_,M],[w,M],[w,A],[_,A]],E=p(e,r,b);d(E,T,u),g(E,x,T,u),m(E,x,u),y(E,e,r[0],T)}function i(t,e,r){for(var n=t.size||1,i=[],a=t.start;at?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);if(5===r||10===r){var n=(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4;return t>n?5===r?713:1114:5===r?104:208}return 15===r?0:r}function o(t){var e,r,n,i,o,s,l,u,c,f=t[0].z,h=f.length,p=f[0].length,d=2===h||2===p;for(r=0;h-1>r;r++)for(i=[],0===r&&(i=i.concat(A)),r===h-2&&(i=i.concat(M)),e=0;p-1>e;e++)for(n=i.slice(),0===e&&(n=n.concat(T)),e===p-2&&(n=n.concat(E)),o=e+","+r,s=[[f[r][e],f[r][e+1]],[f[r+1][e],f[r+1][e+1]]],c=0;ci;i++){if(s>20?(s=S[s][(l[0]||l[1])<0?0:1],t.crossings[o]=C[s]):delete t.crossings[o],l=L[s],!l){_.log("Found bad marching index:",s,e,t.level);break}if(p.push(h(t,e,l)),e[0]+=l[0],e[1]+=l[1],c(p[p.length-1],p[p.length-2])&&p.pop(),o=e.join(","),o===a&&l.join(",")===d||r&&(l[0]&&(e[0]<0||e[0]>v-2)||l[1]&&(e[1]<0||e[1]>g-2)))break;s=t.crossings[o]}1e4===i&&_.log("Infinite loop in contour?");var m,y,b,x,w,k,A,M=c(p[0],p[p.length-1]),T=0,E=.2*t.smoothing,z=[],P=0;for(i=1;i=P;i--)if(m=z[i],R>m){for(b=0,y=i-1;y>=P&&m+z[y]b&&m+z[b]e;)e++,r=Object.keys(i.crossings)[0].split(",").map(Number),s(i,r);1e4===e&&_.log("Infinite loop in contour?")}}function u(t,e,r){var n=0,i=0;return t>20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==A.indexOf(t)?i=1:-1!==T.indexOf(t)?n=1:-1!==M.indexOf(t)?i=-1:n=-1,[n,i]}function c(t,e){return Math.abs(t[0]-e[0])<.01&&Math.abs(t[1]-e[1])<.01}function f(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}function h(t,e,r){var n=e[0]+Math.max(r[0],0),i=e[1]+Math.max(r[1],0),a=t.z[i][n],o=t.xaxis,s=t.yaxis;if(r[1]){var l=(t.level-a)/(t.z[i][n+1]-a);return[o.c2p((1-l)*t.x[n]+l*t.x[n+1],!0),s.c2p(t.y[i],!0)]}var u=(t.level-a)/(t.z[i+1][n]-a);return[o.c2p(t.x[n],!0),s.c2p((1-u)*t.y[i]+u*t.y[i+1],!0)]}function p(t,e,r){var n=t.plot.select(".maplayer").selectAll("g.contour."+r).data(e);return n.enter().append("g").classed("contour",!0).classed(r,!0),n.exit().remove(),n}function d(t,e,r){var n=t.selectAll("g.contourbg").data([0]);n.enter().append("g").classed("contourbg",!0);var i=n.selectAll("path").data("fill"===r.coloring?[0]:[]);i.enter().append("path"),i.exit().remove(),i.attr("d","M"+e.join("L")+"Z").style("stroke","none")}function g(t,e,r,n){var i=t.selectAll("g.contourfill").data([0]);i.enter().append("g").classed("contourfill",!0);var a=i.selectAll("path").data("fill"===n.coloring?e:[]);a.enter().append("path"),a.exit().remove(),a.each(function(t){var e=v(t,r);e?x.select(this).attr("d",e).style("stroke","none"):x.select(this).remove()})}function v(t,e){function r(t){return Math.abs(t[1]-e[0][1])<.01}function n(t){return Math.abs(t[1]-e[2][1])<.01}function i(t){return Math.abs(t[0]-e[0][0])<.01}function a(t){return Math.abs(t[0]-e[2][0])<.01}for(var o,s,l,u,c,f,h=t.edgepaths.length||t.z[0][0]l;l++){if(!o){_.log("Missing end?",p,t);break}for(r(o)&&!a(o)?s=e[1]:i(o)?s=e[0]:n(o)?s=e[3]:a(o)&&(s=e[2]),c=0;c=0&&(s=v,u=c):Math.abs(o[1]-s[1])<.01?Math.abs(o[1]-v[1])<.01&&(v[0]-o[0])*(s[0]-v[0])>=0&&(s=v,u=c):_.log("endpt to newendpt is not vert. or horz.",o,s,v)}if(o=s,u>=0)break;h+="L"+s}if(u===t.edgepaths.length){_.log("unclosed perimeter path");break}p=u,g=-1===d.indexOf(p),g&&(p=d[0],h+="Z")}for(p=0;pe;e++)s.push(1);for(e=0;a>e;e++)i.push(s.slice());for(e=0;eo;o++)for(n=i(l,o),c[o]=new Array(n),s=0;n>s;s++)c[o][s]=e(a(l,o,s));return c}function i(t,e,r,n,i,a){var o,s,l,u=[],c=h.traceIs(t,"contour"),f=h.traceIs(t,"histogram"),p=h.traceIs(t,"gl2d");if(Array.isArray(e)&&!f&&"category"!==a.type){e=e.map(a.d2c);var d=e.length;if(!(i>=d))return c?e.slice(0,i):e.slice(0,i+1);if(c||p)u=e.slice(0,i);else if(1===i)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],l=1;d>l;l++)u.push(.5*(e[l-1]+e[l]));u.push(1.5*e[d-1]-.5*e[d-2])}if(i>d){var g=u[u.length-1],v=g-u[u.length-2];for(l=d;i>l;l++)g+=v,u.push(g)}}else for(s=n||1,o=void 0===r?0:f||"category"===a.type?r:a.d2c(r),l=c||p?0:-.5;i>l;l++)u.push(o+s*l);return u}function a(t){return.5-.25*Math.min(1,.5*t)}function o(t,e,r){var n,i,o=1;if(Array.isArray(r))for(n=0;nn&&o>y;n++)o=l(t,e,a(o));return o>y&&c.log("interp2d didn't converge quickly",o),t}function s(t){var e,r,n,i,a,o,s,l,u=[],c={},f=[],h=t[0],p=[],d=[0,0,0],g=m(t);for(r=0;rn;n++)void 0===p[n]&&(o=(void 0!==p[n-1]?1:0)+(void 0!==p[n+1]?1:0)+(void 0!==e[n]?1:0)+(void 0!==h[n]?1:0),o?(0===r&&o++,0===n&&o++,r===t.length-1&&o++,n===p.length-1&&o++,4>o&&(c[[r,n]]=[r,n,o]),u.push([r,n,o])):f.push([r,n]));for(;f.length;){for(s={},l=!1,a=f.length-1;a>=0;a--)i=f[a],r=i[0],n=i[1],o=((c[[r-1,n]]||d)[2]+(c[[r+1,n]]||d)[2]+(c[[r,n-1]]||d)[2]+(c[[r,n+1]]||d)[2])/20,o&&(s[i]=[r,n,o],f.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)c[i]=s[i],u.push(s[i])}return u.sort(function(t,e){return e[2]-t[2]})}function l(t,e,r){var n,i,a,o,s,l,u,c,f,h,p,d,g,v=0;for(o=0;os;s++)l=b[s],u=t[i+l[0]],u&&(c=u[a+l[1]],void 0!==c&&(0===h?d=g=c:(d=Math.min(d,c),g=Math.max(g,c)),f++,h+=c));if(0===f)throw"iterateInterp2d order is wrong: no defined neighbors";t[i][a]=h/f,void 0===p?4>f&&(v=1):(t[i][a]=(1+r)*t[i][a]-r*p,g>d&&(v=Math.max(v,Math.abs(t[i][a]-p)/(g-d))))}return v}var u=t("fast-isnumeric"),c=t("../../lib"),f=t("../../plots/cartesian/axes"),h=t("../../plots/plots"),p=t("../histogram2d/calc"),d=t("../../components/colorscale/calc"),g=t("./has_columns"),v=t("./convert_column_xyz"),m=t("./max_row_length");e.exports=function(t,e){function r(t){E=e._input.zsmooth=e.zsmooth=!1,c.notifier("cannot fast-zsmooth: "+t)}var a,l,u,y,b,x,_,w,k=f.getFromId(t,e.xaxis||"x"),A=f.getFromId(t,e.yaxis||"y"),M=h.traceIs(e,"contour"),T=h.traceIs(e,"histogram"),E=M?"best":e.zsmooth;if(k._minDtick=0,A._minDtick=0,T){var L=p(t,e);a=L.x,l=L.x0,u=L.dx,y=L.y,b=L.y0,x=L.dy,_=L.z}else g(e)&&v(e,k,A),a=e.x?k.makeCalcdata(e,"x"):[],y=e.y?A.makeCalcdata(e,"y"):[],l=e.x0||0,u=e.dx||1,b=e.y0||0,x=e.dy||1,_=n(e),(M||e.connectgaps)&&(e._emptypoints=s(_),e._interpz=o(_,e._emptypoints,e._interpz));if("fast"===E)if("log"===k.type||"log"===A.type)r("log axis found");else if(!T){if(a.length){var S=(a[a.length-1]-a[0])/(a.length-1),C=Math.abs(S/100);for(w=0;wC){r("x scale is not linear");break}}if(y.length&&"fast"===E){var z=(y[y.length-1]-y[0])/(y.length-1),P=Math.abs(z/100);for(w=0;wP){r("y scale is not linear");break}}}var R=m(_),j="scaled"===e.xtype?"":e.x,O=i(e,j,l,u,R,k),I="scaled"===e.ytype?"":e.y,N=i(e,I,b,x,_.length,A);f.expand(k,O),f.expand(A,N);var F={x:O,y:N,z:_};if(d(e,_,"","z"),M&&e.contours&&"heatmap"===e.contours.coloring){var D="contour"===e.type?"heatmap":"histogram2d";F.xfill=i(D,j,l,u,R,k),F.yfill=i(D,I,b,x,_.length,A)}return[F]};var y=.01,b=[[-1,0],[1,0],[0,-1],[0,1]]},{"../../components/colorscale/calc":1055,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"../histogram2d/calc":1278,"./convert_column_xyz":1260,"./has_columns":1262,"./max_row_length":1265,"fast-isnumeric":90}],1259:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,u="cb"+r.uid,c=s(r.colorscale),f=r.zmin,h=r.zmax;if(i(f)||(f=a.aggNums(Math.min,null,r.z)),i(h)||(h=a.aggNums(Math.max,null,r.z)),t._fullLayout._infolayer.selectAll("."+u).remove(),!r.showscale)return void o.autoMargin(t,u);var p=e[0].t.cb=l(t,u);p.fillcolor(n.scale.linear().domain(c.map(function(t){return f+t[0]*(h-f)})).range(c.map(function(t){return t[1]}))).filllevels({start:f,end:h,size:(h-f)/254}).options(r.colorbar)()}},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,d3:82,"fast-isnumeric":90}],1260:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a=t.x.slice(),o=t.y.slice(),s=t.z,l=t.text,u=Math.min(a.length,o.length,s.length),c=void 0!==l&&!Array.isArray(l[0]);for(ui;i++)a[i]=e.d2c(a[i]),o[i]=r.d2c(o[i]);var f,h,p,d=n.distinctVals(a),g=d.vals,v=n.distinctVals(o),m=v.vals,y=n.init2dArray(m.length,g.length);for(c&&(p=n.init2dArray(m.length,g.length)),i=0;u>i;i++)f=n.findBin(a[i]+d.minDiff/2,g),h=n.findBin(o[i]+v.minDiff/2,m),y[h][f]=s[i],c&&(p[h][f]=l[i]);t.x=g,t.y=m,t.z=y,c&&(t.text=p)}},{"../../lib":1127}],1261:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./has_columns"),a=t("./xyz_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function u(r,i){return n.coerce(t,e,s,r,i)}var c=a(t,e,u);return c?(u("text"),u("zsmooth"),u("connectgaps",i(e)&&e.zsmooth!==!1),void o(t,e,l,u,{prefix:"",cLetter:"z"})):void(e.visible=!1)}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1257,"./has_columns":1262,"./xyz_defaults":1268}],1262:[function(t,e,r){"use strict";e.exports=function(t){return!Array.isArray(t.z[0])}},{}],1263:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../lib");e.exports=function(t,e,r,a,o){if(!(t.distanceu||u>=m[0].length||0>c||c>m.length)return}else{if(n.inbox(e-g[0],e-g[g.length-1])>n.MAXDIST||n.inbox(r-v[0],r-v[v.length-1])>n.MAXDIST)return;if(o){var w;for(b=[2*g[0]-g[1]],w=1;w0;)_=v.c2p(C[M]),M--;for(x>_&&(w=_,_=x,x=w,I=!0),M=0;void 0===k&&M0;)A=m.c2p(z[M]),M--;if(k>A&&(w=k,k=A,A=w,N=!0),P&&(C=r[0].xfill,z=r[0].yfill),"fast"!==R){var F="best"===R?0:.5;x=Math.max(-F*v._length,x),_=Math.min((1+F)*v._length,_),k=Math.max(-F*m._length,k),A=Math.min((1+F)*m._length,A)}var D=Math.round(_-x),B=Math.round(A-k);if(!(0>=D||0>=B)){var U,V;"fast"===R?(U=O,V=j):(U=D,V=B);var q=document.createElement("canvas");q.width=U,q.height=V;var G,H,Y=q.getContext("2d"),X=i.scale.linear().domain(S.map(function(t){return t[0]})).range(S.map(function(t){var e=a(t[1]).toRgb();return[e.r,e.g,e.b,e.a]})).clamp(!0);"fast"===R?(G=I?function(t){return O-1-t}:o.identity,H=N?function(t){return j-1-t}:o.identity):(G=function(t){return o.constrain(Math.round(v.c2p(C[t])-x),0,D)},H=function(t){return o.constrain(Math.round(m.c2p(z[t])-k),0,B)});var W,Z,K,$,Q,J,tt=H(0),et=[tt,tt],rt=I?0:1,nt=N?0:1,it=0,at=0,ot=0,st=0;if(R){var lt=0,ut=new Uint8Array(D*B*4);if("best"===R){var ct,ft,ht,pt=new Array(C.length),dt=new Array(z.length),gt=new Array(D);for(M=0;MM;M++)gt[M]=n(M,pt);for(Z=0;B>Z;Z++)for(ct=n(Z,dt),ft=T[ct.bin0],ht=T[ct.bin1],M=0;D>M;M++,lt+=4)J=p(ft,ht,gt[M],ct),h(ut,lt,J)}else for(Z=0;j>Z;Z++)for(Q=T[Z],et=H(Z),M=0;D>M;M++)J=f(Q[M],1),lt=4*(et*D+G(M)),h(ut,lt,J);var vt=Y.createImageData(D,B);vt.data.set(ut),Y.putImageData(vt,0,0)}else for(Z=0;j>Z;Z++)if(Q=T[Z],et.reverse(),et[nt]=H(Z+1),et[0]!==et[1]&&void 0!==et[0]&&void 0!==et[1])for(K=G(0),W=[K,K],M=0;O>M;M++)W.reverse(),W[rt]=G(M+1),W[0]!==W[1]&&void 0!==W[0]&&void 0!==W[1]&&($=Q[M],J=f($,(W[1]-W[0])*(et[1]-et[0])),Y.fillStyle="rgba("+J.join(",")+")",Y.fillRect(W[0],et[0],W[1]-W[0],et[1]-et[0]));at=Math.round(at/it),ot=Math.round(ot/it),st=Math.round(st/it);var mt=a("rgb("+at+","+ot+","+st+")");t._hmpixcount=(t._hmpixcount||0)+it,t._hmlumcount=(t._hmlumcount||0)+it*mt.getLuminance();var yt=e.plot.select(".imagelayer").selectAll("g.hm."+b).data([0]);yt.enter().append("g").classed("hm",!0).classed(b,!0),yt.exit().remove();var bt=yt.selectAll("image").data(r);bt.enter().append("svg:image"),bt.exit().remove(),bt.attr({xmlns:u.svg,"xlink:href":q.toDataURL("image/png"),height:B,width:D,x:x,y:k,preserveAspectRatio:"none"})}}var i=t("d3"),a=t("tinycolor2"),o=t("../../lib"),s=t("../../plots/plots"),l=t("../../components/colorscale/get_scale"),u=t("../../constants/xmlns_namespaces"),c=t("./max_row_length");e.exports=function(t,e,r){for(var i=0;i0&&(n=!0);for(var s=0;si;i++)e[i]?(t[i]/=e[i],n+=t[i]):t[i]=null;return n}},{}],1271:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){var e=r(t+"bins.start"),n=r(t+"bins.end"),i=r("autobin"+t,!(e&&n));r(i?"nbins"+t:t+"bins.size")}),e}},{}],1272:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,i){var a=i[e];return n(a)?(a=Number(a),r[t]+=a,a):0},avg:function(t,e,r,i,a){ +var o=i[e];return n(o)&&(o=Number(o),r[t]+=o,a[t]++),0},min:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]>a)return r[t]=a,a-r[t]}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]r&&u.length<5e3;)g=a.tickIncrement(r,b.size),u.push((r+g)/2),c.push(S),x&&_.push(r),E&&w.push(1/(g-r)),P&&k.push(0),r=g;var R=c.length;for(r=0;r=0&&R>m&&(A+=C(m,r,c,y,k));P&&(A=l(c,k)),z&&z(c,A,w);var j=Math.min(u.length,c.length),O=[],I=0,N=j-1;for(r=0;j>r;r++)if(c[r]){I=r;break}for(r=j-1;r>I;r--)if(c[r]){N=r;break}for(r=I;N>=r;r++)n(u[r])&&n(c[r])&&O.push({p:u[r],s:c[r],b:0});return O}}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./average":1270,"./bin_functions":1272,"./norm_functions":1276,"fast-isnumeric":90}],1274:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("./bin_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,u){function c(r,i){return n.coerce(t,e,l,r,i)}var f=c("x"),h=c("y");c("text");var p=c("orientation",h&&!f?"h":"v"),d=e["v"===p?"x":"y"];if(!d||!d.length)return void(e.visible=!1);var g=e["h"===p?"x":"y"];g&&c("histfunc");var v="h"===p?["y"]:["x"];a(t,e,c,v),o(t,e,c,r,u),s(t,e,i.defaultLine,{axis:"y"}),s(t,e,i.defaultLine,{axis:"x",inherit:"y"})}},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"./attributes":1269,"./bin_defaults":1271}],1275:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.style=t("../bar/style"),n.colorbar=t("../scatter/colorbar"),n.hoverPoints=t("../bar/hover"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../bar/hover":1224,"../bar/layout_attributes":1226,"../bar/layout_defaults":1227,"../bar/plot":1228,"../bar/set_positions":1229,"../bar/style":1230,"../scatter/colorbar":1304,"./attributes":1269,"./calc":1273,"./defaults":1274}],1276:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,i=0;r>i;i++)t[i]*=n},probability:function(t,e){for(var r=t.length,n=0;r>n;n++)t[n]/=e},density:function(t,e,r,n){var i=t.length;n=n||1;for(var a=0;i>a;a++)t[a]*=r[a]*n},"probability density":function(t,e,r,n){var i=t.length;n&&(e/=n);for(var a=0;i>a;a++)t[a]*=r[a]/e}}},{}],1277:[function(t,e,r){"use strict";var n=t("../histogram/attributes"),i=t("../heatmap/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports=o({},{x:n.x,y:n.y,z:{valType:"data_array"},marker:{color:{valType:"data_array"}},histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zsmooth:i.zsmooth,_nestedModules:{colorbar:"Colorbar"}},a,{autocolorscale:o({},a.autocolorscale,{dflt:!1})})},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../histogram/attributes":1269}],1278:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../histogram/bin_functions"),o=t("../histogram/norm_functions"),s=t("../histogram/average");e.exports=function(t,e){var r,l,u,c,f,h,p=i.getFromId(t,e.xaxis||"x"),d=e.x?p.makeCalcdata(e,"x"):[],g=i.getFromId(t,e.yaxis||"y"),v=e.y?g.makeCalcdata(e,"y"):[],m=Math.min(d.length,v.length);d.length>m&&d.splice(m,d.length-m),v.length>m&&v.splice(m,v.length-m),!e.autobinx&&"xbins"in e||(e.xbins=i.autoBin(d,p,e.nbinsx,"2d"),"histogram2dcontour"===e.type&&(e.xbins.start-=e.xbins.size,e.xbins.end+=e.xbins.size),e._input.xbins=e.xbins),!e.autobiny&&"ybins"in e||(e.ybins=i.autoBin(v,g,e.nbinsy,"2d"),"histogram2dcontour"===e.type&&(e.ybins.start-=e.ybins.size,e.ybins.end+=e.ybins.size),e._input.ybins=e.ybins),f=[];var y,b,x=[],_=[],w="string"==typeof e.xbins.size?[]:e.xbins,k="string"==typeof e.xbins.size?[]:e.ybins,A=0,M=[],T=e.histnorm,E=e.histfunc,L=-1!==T.indexOf("density"),S="max"===E||"min"===E,C=S?null:0,z=a.count,P=o[T],R=!1,j=[],O=[],I="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";I&&"count"!==E&&(R="avg"===E,z=a[E]);var N=e.xbins,F=N.end+(N.start-i.tickIncrement(N.start,N.size))/1e6;for(h=N.start;F>h;h=i.tickIncrement(h,N.size))x.push(C),Array.isArray(w)&&w.push(h),R&&_.push(0);Array.isArray(w)&&w.push(h);var D=x.length;for(r=e.xbins.start,l=(h-r)/D,r+=l/2,N=e.ybins,F=N.end+(N.start-i.tickIncrement(N.start,N.size))/1e6,h=N.start;F>h;h=i.tickIncrement(h,N.size))f.push(x.concat()),Array.isArray(k)&&k.push(h),R&&M.push(_.concat());Array.isArray(k)&&k.push(h);var B=f.length;for(u=e.ybins.start,c=(h-u)/B,u+=c/2,L&&(j=x.map(function(t,e){return Array.isArray(w)?1/(w[e+1]-w[e]):1/l}),O=f.map(function(t,e){return Array.isArray(k)?1/(k[e+1]-k[e]):1/c})),h=0;m>h;h++)y=n.findBin(d[h],w),b=n.findBin(v[h],k),y>=0&&D>y&&b>=0&&B>b&&(A+=z(y,h,f[b],I,M[b]));if(R)for(b=0;B>b;b++)A+=s(f[b],M[b]);if(P)for(b=0;B>b;b++)P(f[b],A,j,O[b]);return{x:d,x0:r,dx:l,y:v,y0:u,dy:c,z:f}}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../histogram/average":1270,"../histogram/bin_functions":1272,"../histogram/norm_functions":1276}],1279:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./sample_defaults"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r){function s(r,i){return n.coerce(t,e,o,r,i)}i(t,e,s),s("zsmooth"),a(t,e,r,s,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1277,"./sample_defaults":1281}],1280:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../heatmap/calc"),n.plot=t("../heatmap/plot"),n.colorbar=t("../heatmap/colorbar"),n.style=t("../heatmap/style"),n.hoverPoints=t("../heatmap/hover"),n.moduleType="trace",n.name="histogram2d",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../heatmap/calc":1258,"../heatmap/colorbar":1259,"../heatmap/hover":1263,"../heatmap/plot":1266,"../heatmap/style":1267,"./attributes":1277,"./defaults":1279}],1281:[function(t,e,r){"use strict";var n=t("../histogram/bin_defaults");e.exports=function(t,e,r){var i=r("x"),a=r("y");if(!(i&&i.length&&a&&a.length))return void(e.visible=!1);var o=r("z")||r("marker.color");o&&r("histfunc");var s=["x","y"];n(t,e,r,s)}},{"../histogram/bin_defaults":1271}],1282:[function(t,e,r){"use strict";var n=t("../histogram2d/attributes"),i=t("../contour/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports=o({},{x:n.x,y:n.y,z:n.z,marker:n.marker,histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,autocontour:i.autocontour,ncontours:i.ncontours,contours:i.contours,line:i.line,_nestedModules:{colorbar:"Colorbar"}},a)},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../contour/attributes":1247,"../histogram2d/attributes":1277}],1283:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../histogram2d/sample_defaults"),a=t("../contour/style_defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}i(t,e,l);var u=n.coerce2(t,e,o,"contours.start"),c=n.coerce2(t,e,o,"contours.end"),f=l("autocontour",!(u&&c));l(f?"ncontours":"contours.size"),a(t,e,l,s)}},{"../../lib":1127,"../contour/style_defaults":1256,"../histogram2d/sample_defaults":1281,"./attributes":1282}],1284:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../contour/calc"),n.plot=t("../contour/plot"),n.style=t("../contour/style"),n.colorbar=t("../contour/colorbar"),n.hoverPoints=t("../contour/hover"),n.moduleType="trace",n.name="histogram2dcontour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","contour","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../contour/calc":1248,"../contour/colorbar":1249,"../contour/hover":1251,"../contour/plot":1254,"../contour/style":1255,"./attributes":1282,"./defaults":1283}],1285:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../surface/attributes"),a=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},i:{valType:"data_array"},j:{valType:"data_array"},k:{valType:"data_array"},delaunayaxis:{valType:"enumerated",values:["x","y","z"],dflt:"z"},alphahull:{valType:"number",dflt:-1},intensity:{valType:"data_array"},color:{valType:"color"},vertexcolor:{valType:"data_array"},facecolor:{valType:"data_array"},opacity:a({},i.opacity),flatshading:{valType:"boolean",dflt:!1},contour:{show:a({},i.contours.x.show,{}),color:a({},i.contours.x.color),width:a({},i.contours.x.width)},colorscale:n.colorscale,reversescale:n.reversescale,showscale:n.showscale,lightposition:{x:a({},i.lightposition.x,{dflt:1e5}),y:a({},i.lightposition.y,{dflt:1e5}),z:a({},i.lightposition.z,{dflt:0})},lighting:a({},{vertexnormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-12},facenormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-6}},i.lighting),_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../surface/attributes":1348}],1286:[function(t,e,r){"use strict";function n(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.color="#fff",this.data=null,this.showContour=!1}function i(t){return t.map(function(t){var e=t[0],r=u(t[1]),n=r.toRgb();return{index:e,rgb:[n.r,n.g,n.b,1]}})}function a(t){return t.map(p)}function o(t,e,r){for(var n=new Array(t.length),i=0;i0)s=f(t.alphahull,l);else{var u=["x","y","z"].indexOf(t.delaunayaxis);s=c(l.map(function(t){return[t[(u+1)%3],t[(u+2)%3]]}))}var d={positions:l,cells:s,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:p(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",d.vertexIntensity=t.intensity,d.colormap=i(t.colorscale)):t.vertexcolor?(this.color=t.vertexcolors[0],d.vertexColors=a(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],d.cellColors=a(t.facecolor)):(this.color=t.color,d.meshColor=p(t.color)),this.mesh.update(d)},d.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=s},{"../../lib/str2rgbarray":1139,"alpha-shape":46,"convex-hull":71,"delaunay-triangulate":88,"gl-mesh3d":253,tinycolor2:1042}],1287:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorbar/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}function l(t){var e=t.map(function(t){var e=s(t);return e&&Array.isArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var u=l(["x","y","z"]),c=l(["i","j","k"]);return u?(c&&c.forEach(function(t){for(var e=0;el||(u=d[r],void 0!==u&&""!==u||(u=r),u=String(u),void 0===y[u]&&(y[u]=!0,c=a(e.marker.colors[r]),c.isValid()?(c=o.addOpacity(c,c.getAlpha()),m[u]||(m[u]=c)):m[u]?c=m[u]:(c=!1,b=!0),f=-1!==_.indexOf(u),f||(x+=l),g.push({v:l,label:u,color:c,i:r,hidden:f}))));if(e.sort&&g.sort(function(t,e){return e.v-t.v}),b)for(r=0;r")}return g};var l},{"../../components/color":1048,"./helpers":1293,"fast-isnumeric":90,tinycolor2:1042}],1292:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}var s=n.coerceFont,l=o("values");if(!Array.isArray(l)||!l.length)return void(e.visible=!1);var u=o("labels");Array.isArray(u)||(o("label0"),o("dlabel"));var c=o("marker.line.width");c&&o("marker.line.color");var f=o("marker.colors");Array.isArray(f)||(e.marker.colors=[]),o("scalegroup");var h=o("text"),p=o("textinfo",Array.isArray(h)?"text+percent":"percent");if(o("hoverinfo",1===a._dataLength?"label+text+value+percent":void 0),p&&"none"!==p){var d=o("textposition"),g=Array.isArray(d)||"auto"===d,v=g||"inside"===d,m=g||"outside"===d;if(v||m){var y=s(o,"textfont",a.font);v&&s(o,"insidetextfont",y),m&&s(o,"outsidetextfont",y)}}o("domain.x"),o("domain.y"),o("hole"),o("sort"),o("direction"),o("rotation"),o("pull")}},{"../../lib":1127,"./attributes":1289}],1293:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)}},{"../../lib":1127}],1294:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":1289,"./base_plot":1290,"./calc":1291,"./defaults":1292,"./layout_attributes":1295,"./layout_defaults":1296,"./plot":1297,"./style":1298,"./style_one":1299}],1295:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array"}}},{}],1296:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e){function r(r,a){return n.coerce(t,e,i,r,a)}r("hiddenlabels")}},{"../../lib":1127,"./layout_attributes":1295}],1297:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,o=Math.PI*Math.min(e.v/r.vTotal,.5),s=1-r.trace.hole,l=i(e,r),u={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(u.scale>=1)return u;var c=a+1/(2*Math.tan(o)),f=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),s/(Math.sqrt(a*a+s/2)+a)),h={scale:2*f/t.height,rCenter:Math.cos(f/r.r)-f*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},p=1/a,d=p+1/(2*Math.tan(o)),g=r.r*Math.min(1/(Math.sqrt(d*d+.5)+d),s/(Math.sqrt(p*p+s/2)+p)),v={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},m=v.scale>h.scale?v:h;return u.scale<1&&m.scale>u.scale?m:u}function i(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function a(t,e){var r=e.pxmid[0],n=e.pxmid[1],i=t.width/2,a=t.height/2;return 0>r&&(i*=-1),0>n&&(a*=-1),{scale:1,rCenter:1,rotate:0,x:i+Math.abs(a)*(i>0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}function o(t,e){function r(t,e){return t.pxmid[1]-e.pxmid[1]}function n(t,e){return e.pxmid[1]-t.pxmid[1]}function i(t,r){r||(r={});var n,i,a,s,h,p,g=r.labelExtraY+(o?r.yLabelMax:r.yLabelMin),v=o?t.yLabelMin:t.yLabelMax,m=o?t.yLabelMax:t.yLabelMin,y=t.cyFinal+u(t.px0[1],t.px1[1]),b=g-v;if(b*f>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(i=0;i=e.pull[a.i]||((t.pxmid[1]-a.pxmid[1])*f>0?(s=a.cyFinal+u(a.px0[1],a.px1[1]),b=s-v-t.labelExtraY,b*f>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-y)*f>0&&(n=3*c*Math.abs(i-d.indexOf(t)),h=a.cxFinal+l(a.px0[0],a.px1[0]),p=h+n-(t.cxFinal+t.pxmid[0])-t.labelExtraX,p*c>0&&(t.labelExtraX+=p)))}var a,o,s,l,u,c,f,h,p,d,g,v,m;for(o=0;2>o;o++)for(s=o?r:n,u=o?Math.max:Math.min,f=o?1:-1,a=0;2>a;a++){for(l=a?Math.max:Math.min,c=a?1:-1,h=t[o][a],h.sort(s),p=t[1-o][a],d=p.concat(h),v=[],g=0;gc&&(c=s.pull[a]);o.r=Math.min(r/u(s.tilt,Math.sin(l),s.depth),n/u(s.tilt,Math.cos(l),s.depth))/(2+2*c),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===p.indexOf(s.scalegroup)&&p.push(s.scalegroup)}for(a=0;af.vTotal/2?1:0)}function u(t,e,r){if(!t)return 1;var n=Math.sin(t*Math.PI/180);return Math.max(.01,r*n*Math.abs(e)+2*Math.sqrt(1-n*n*e*e))}var c=t("d3"),f=t("../../plots/cartesian/graph_interact"),h=t("../../components/color"),p=t("../../components/drawing"),d=t("../../lib/svg_text_utils"),g=t("./helpers");e.exports=function(t,e){var r=t._fullLayout;s(e,r._size);var u=r._pielayer.selectAll("g.trace").data(e);u.enter().append("g").attr({"stroke-linejoin":"round","class":"trace"}),u.exit().remove(),u.order(),u.each(function(e){var s=c.select(this),u=e[0],v=u.trace,m=0,y=(v.depth||0)*u.r*Math.sin(m)/2,b=v.tiltaxis||0,x=b*Math.PI/180,_=[y*Math.sin(x),y*Math.cos(x)],w=u.r*Math.cos(m),k=s.selectAll("g.part").data(v.tilt?["top","sides"]:["top"]);k.enter().append("g").attr("class",function(t){return t+" part"}),k.exit().remove(),k.order(),l(e),s.selectAll(".top").each(function(){var s=c.select(this).selectAll("g.slice").data(e);s.enter().append("g").classed("slice",!0),s.exit().remove();var l=[[[],[]],[[],[]]],m=!1;s.each(function(o){function s(e){var n=t._fullLayout,a=t._fullData[v.index],s=a.hoverinfo;if("all"===s&&(s="label+text+value+percent+name"),!t._dragging&&n.hovermode!==!1&&"none"!==s&&s){var l=i(o,u),c=k+o.pxmid[0]*(1-l),h=A+o.pxmid[1]*(1-l),p=r.separators,d=[];-1!==s.indexOf("label")&&d.push(o.label),a.text&&a.text[o.i]&&-1!==s.indexOf("text")&&d.push(a.text[o.i]),-1!==s.indexOf("value")&&d.push(g.formatPieValue(o.v,p)),-1!==s.indexOf("percent")&&d.push(g.formatPiePercent(o.v/u.vTotal,p)),f.loneHover({x0:c-l*u.r,x1:c+l*u.r,y:h,text:d.join("
"),name:-1!==s.indexOf("name")?a.name:void 0,color:o.color,idealAlign:o.pxmid[0]<0?"left":"right"},{container:n._hoverlayer.node(),outerContainer:n._paper.node()}),f.hover(t,e,"pie"),E=!0}}function h(e){t.emit("plotly_unhover",{points:[e]}),E&&(f.loneUnhover(r._hoverlayer.node()),E=!1)}function y(){t._hoverdata=[o],t._hoverdata.trace=e.trace,f.click(t,{target:!0})}function x(t,e,r,n){return"a"+n*u.r+","+n*w+" "+b+" "+o.largeArc+(r?" 1 ":" 0 ")+n*(e[0]-t[0])+","+n*(e[1]-t[1])}if(o.hidden)return void c.select(this).selectAll("path,g").remove();l[o.pxmid[1]<0?0:1][o.pxmid[0]<0?0:1].push(o);var k=u.cx+_[0],A=u.cy+_[1],M=c.select(this),T=M.selectAll("path.surface").data([o]),E=!1;if(T.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),M.select("path.textline").remove(),M.on("mouseover",s).on("mouseout",h).on("click",y),v.pull){var L=+(Array.isArray(v.pull)?v.pull[o.i]:v.pull)||0;L>0&&(k+=L*o.pxmid[0],A+=L*o.pxmid[1])}o.cxFinal=k,o.cyFinal=A;var S=v.hole;if(o.v===u.vTotal){var C="M"+(k+o.px0[0])+","+(A+o.px0[1])+x(o.px0,o.pxmid,!0,1)+x(o.pxmid,o.px0,!0,1)+"Z";S?T.attr("d","M"+(k+S*o.px0[0])+","+(A+S*o.px0[1])+x(o.px0,o.pxmid,!1,S)+x(o.pxmid,o.px0,!1,S)+"Z"+C):T.attr("d",C)}else{var z=x(o.px0,o.px1,!0,1);if(S){var P=1-S;T.attr("d","M"+(k+S*o.px1[0])+","+(A+S*o.px1[1])+x(o.px1,o.px0,!1,S)+"l"+P*o.px0[0]+","+P*o.px0[1]+z+"Z")}else T.attr("d","M"+k+","+A+"l"+o.px0[0]+","+o.px0[1]+z+"Z")}var R=Array.isArray(v.textposition)?v.textposition[o.i]:v.textposition,j=M.selectAll("g.slicetext").data(o.text&&"none"!==R?[0]:[]);j.enter().append("g").classed("slicetext",!0),j.exit().remove(),j.each(function(){var t=c.select(this).selectAll("text").data([0]);t.enter().append("text").attr("data-notex",1),t.exit().remove(),t.text(o.text).attr({"class":"slicetext",transform:"","data-bb":"","text-anchor":"middle",x:0,y:0}).call(p.font,"outside"===R?v.outsidetextfont:v.insidetextfont).call(d.convertToTspans),t.selectAll("tspan.line").attr({x:0,y:0});var e,r=p.bBox(t.node());"outside"===R?e=a(r,o):(e=n(r,o,u),"auto"===R&&e.scale<1&&(t.call(p.font,v.outsidetextfont),v.outsidetextfont.family===v.insidetextfont.family&&v.outsidetextfont.size===v.insidetextfont.size||(t.attr({"data-bb":""}),r=p.bBox(t.node())),e=a(r,o)));var i=k+o.pxmid[0]*e.rCenter+(e.x||0),s=A+o.pxmid[1]*e.rCenter+(e.y||0);e.outside&&(o.yLabelMin=s-r.height/2,o.yLabelMid=s,o.yLabelMax=s+r.height/2,o.labelExtraX=0,o.labelExtraY=0,m=!0),t.attr("transform","translate("+i+","+s+")"+(e.scale<1?"scale("+e.scale+")":"")+(e.rotate?"rotate("+e.rotate+")":"")+"translate("+-(r.left+r.right)/2+","+-(r.top+r.bottom)/2+")")})}),m&&o(l,v),s.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=c.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var n=t.cxFinal+t.pxmid[0],i=t.cyFinal+t.pxmid[1],a="M"+n+","+i,o=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],l=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);a+=Math.abs(s)>Math.abs(l)?"l"+l*t.pxmid[0]/t.pxmid[1]+","+l+"H"+(n+t.labelExtraX+o):"l"+t.labelExtraX+","+s+"v"+(l-s)+"h"+o}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+o;e.append("path").classed("textline",!0).call(h.stroke,v.outsidetextfont.color).attr({"stroke-width":Math.min(2,v.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){u.selectAll("tspan").each(function(){var t=c.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/svg_text_utils":1140,"../../plots/cartesian/graph_interact":1157,"./helpers":1293,d3:82}],1298:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0],r=e.trace,a=n.select(this);a.style({opacity:r.opacity}),a.selectAll(".top path.surface").each(function(t){n.select(this).call(i,t,r)})})}},{"./style_one":1299,d3:82}],1299:[function(t,e,r){"use strict";var n=t("../../components/color");e.exports=function(t,e,r){var i=r.marker.line.color;Array.isArray(i)&&(i=i[e.i]||n.defaultLine);var a=r.marker.line.width||0;Array.isArray(a)&&(a=a[e.i]||0),t.style({"stroke-width":a,fill:e.color}).call(n.stroke,i)}},{"../../components/color":1048}],1300:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){var e=t[0].trace,r=e.marker;if(n.mergeArray(e.text,t,"tx"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf")),r&&r.line){var i=r.line;n.mergeArray(r.opacity,t,"mo"),n.mergeArray(r.symbol,t,"mx"),n.mergeArray(r.color,t,"mc"),n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw")}}},{"../../lib":1127}],1301:[function(t,e,r){"use strict";var n=t("../../components/colorscale/color_attributes"),i=t("../../components/drawing"),a=(t("./constants"),t("../../lib/extend").extendFlat);e.exports={x:{valType:"data_array"},x0:{valType:"any",dflt:0},dx:{valType:"number",dflt:1},y:{valType:"data_array"},y0:{valType:"any",dflt:0},dy:{valType:"number",dflt:1},key:{valType:"data_array"},text:{valType:"string",dflt:"",arrayOk:!0},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"]},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear"},smoothing:{valType:"number",min:0,max:1.3,dflt:1},dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid"}},connectgaps:{valType:"boolean",dflt:!1},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none"},fillcolor:{valType:"color"},marker:a({},{symbol:{valType:"enumerated",values:i.symbolList,dflt:"circle",arrayOk:!0},opacity:{valType:"number",min:0,max:1,arrayOk:!0},size:{valType:"number",min:0,dflt:6,arrayOk:!0},maxdisplayed:{valType:"number",min:0,dflt:0},sizeref:{valType:"number",dflt:1},sizemin:{valType:"number",min:0,dflt:0},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter"},showscale:{valType:"boolean",dflt:!1},line:a({},{width:{valType:"number",min:0,arrayOk:!0}},n("marker.line"))},n("marker")),textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0},textfont:{family:{valType:"string",noBlank:!0,strict:!0,arrayOk:!0},size:{valType:"number",min:1,arrayOk:!0},color:{valType:"color",arrayOk:!0}},r:{valType:"data_array"},t:{valType:"data_array"},_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":1056, +"../../components/drawing":1071,"../../lib/extend":1122,"./constants":1305}],1302:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./subtypes"),s=t("./marker_colorscale_calc");e.exports=function(t,e){var r,l,u,c=i.getFromId(t,e.xaxis||"x"),f=i.getFromId(t,e.yaxis||"y"),h=c.makeCalcdata(e,"x"),p=f.makeCalcdata(e,"y"),d=Math.min(h.length,p.length);c._minDtick=0,f._minDtick=0,h.length>d&&h.splice(d,h.length-d),p.length>d&&p.splice(d,p.length-d);var g={padded:!0},v={padded:!0};if(o.hasMarkers(e)){if(r=e.marker,l=r.size,Array.isArray(l)){var m={type:"linear"};i.setConvert(m),l=m.makeCalcdata(e.marker,"size"),l.length>d&&l.splice(d,l.length-d)}var y,b=1.6*(e.marker.sizeref||1);y="area"===e.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/b),3)}:function(t){return Math.max((t||0)/b,3)},g.ppad=v.ppad=Array.isArray(l)?l.map(y):y(l)}s(e),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||h[0]===h[d-1]&&p[0]===p[d-1]?e.error_y.visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(o.hasMarkers(e)||o.hasText(e))||(g.padded=!1,g.ppad=0):g.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||h[0]===h[d-1]&&p[0]===p[d-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(v.padded=!1):v.tozero=!0,i.expand(c,h,g),i.expand(f,p,v);var x=new Array(d);for(u=0;d>u;u++)x[u]=n(h[u])&&n(p[u])?{x:h[u],y:p[u]}:{x:!1,y:!1},e.key&&void 0!==e.key[u]&&(x[u].key=e.key[u]);return void 0!==typeof l&&a.mergeArray(l,x,"ms"),t.firstscatter=!1,x}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./marker_colorscale_calc":1316,"./subtypes":1322,"fast-isnumeric":90}],1303:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i,a;for(e=0;e=0;i--)if(a=t[i],"scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}},{}],1304:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,u=r.marker,c="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+c).remove(),void 0===u||!u.showscale)return void o.autoMargin(t,c);var f=s(u.colorscale),h=u.color,p=u.cmin,d=u.cmax;i(p)||(p=a.aggNums(Math.min,null,h)),i(d)||(d=a.aggNums(Math.max,null,h));var g=e[0].t.cb=l(t,c);g.fillcolor(n.scale.linear().domain(f.map(function(t){return p+t[0]*(d-p)})).range(f.map(function(t){return t[1]}))).filllevels({start:p,end:d,size:(d-p)/254}).options(u.colorbar)()}},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,d3:82,"fast-isnumeric":90}],1305:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20}},{}],1306:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./constants"),o=t("./subtypes"),s=t("./xy_defaults"),l=t("./marker_defaults"),u=t("./line_defaults"),c=t("./line_shape_defaults"),f=t("./text_defaults"),h=t("./fillcolor_defaults"),p=t("../../components/errorbars/defaults");e.exports=function(t,e,r,d){function g(r,a){return n.coerce(t,e,i,r,a)}var v=s(t,e,g),m=vi(f))break;l=f,y=g[0]*d[0]+g[1]*d[1],y>v?(v=y,u=f,p=!1):m>y&&(m=y,c=f,p=!0)}if(p?(C[z++]=u,l!==c&&(C[z++]=c)):(c!==s&&(C[z++]=c),l!==u&&(C[z++]=u)),C[z++]=l,o>=t.length||!f)break;C[z++]=f,s=f}}else C[z++]=u}E.push(C.slice(0,z))}return E}},{"../../plots/cartesian/axes":1150}],1313:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=r("line.shape");"spline"===n&&r("line.smoothing")}},{}],1314:[function(t,e,r){"use strict";var n=t("../../plots/plots");e.exports=function(t,e,r){var i,a,o,s=(t._fullLayout,e.x()),l=e.y(),u=null;for(i=0;i0?Math.max(e,i):0}}},{"fast-isnumeric":90}],1316:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t){if(a.hasMarkers(t)){var e=t.marker;n(t,"marker")&&i(t,e.color,"marker","c"),n(t,"marker.line")&&i(t,e.line.color,"marker.line","c")}}},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1317:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l){var u,c=o.isBubble(t),f=(t.line||{}).color;f&&(r=f),l("marker.symbol"),l("marker.opacity",c?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),u=f&&e.marker.color!==f?f:c?n.background:n.defaultLine,l("marker.line.color",u),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",c?1:0),c&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode"))}},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1318:[function(t,e,r){"use strict";function n(t){return t[0].trace.uid}function i(t,e,r,n){var i;e.selectAll("g.trace").each(function(t){var e=s.select(this);i=t[0].trace,"tozero"===i.fill.substr(0,6)||"toself"===i.fill||"to"===i.fill.substr(0,2)&&!i._prevtrace?(i._ownFill=e.select(".js-fill.js-tozero"),i._ownFill.size()||(i._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),i._ownFill=null),i._nexttrace?(i._nextFill=e.select(".js-fill.js-tonext"),i._nextFill.size()||(i._nextFill=e.insert("path",":first-child").attr("class","js-fill js-tonext"))):(e.selectAll(".js-fill.js-tonext").remove(),i._nextFill=null)})}function a(t,e,r,n,i){function a(t){return t.transition().duration(i.duration).ease(i.easing)}function d(t){return t.filter(function(t){return t.vis})}function g(t){return t.key}function v(t){return t.key?g:void 0}function m(t){var e=t[0].trace,r=s.select(this),n=f.hasMarkers(e),a=f.hasText(e);if(!n&&!a||e.visible!==!0)r.remove();else{if(n){var o=r.selectAll("path.point").data(e.marker.maxdisplayed?d:l.identity,v(e));o.enter().append("path").classed("point",!0).call(u.pointStyle,e).call(u.translatePoints,y,b,e,i,1),o.transition().call(u.translatePoints,y,b,e,i,0).call(u.pointStyle,e),o.exit().call(u.translatePoints,y,b,e,i,-1)}a&&r.selectAll("g").data(e.marker.maxdisplayed?d:l.identity).enter().append("g").append("text").call(u.translatePoints,y,b,e,i,1)}}o(t,e,r);var y=e.x(),b=e.y(),x=r[0].trace,_=x.line,w=s.select(n);if(w.call(c.plot,e),x.visible===!0){var k,A,M=x.fill.charAt(x.fill.length-1);"x"!==M&&"y"!==M&&(M=""),r[0].node3=w,h(r);var T="",E=x._prevtrace;E&&(T=E._revpath||"",A=E._nextFill);var L,S,C,z,P,R="",j="";if(k=x._ownFill,f.hasLines(x)||"none"!==x.fill){A&&A.datum(r),-1!==["hv","vh","hvh","vhv"].indexOf(_.shape)?(C=u.steps(_.shape),z=u.steps(_.shape.split("").reverse().join(""))):C=z="spline"===_.shape?function(t){var e=t[t.length-1];return t[0][0]===e[0]&&t[0][1]===e[1]?u.smoothclosed(t.slice(1),_.smoothing):u.smoothopen(t,_.smoothing)}:function(t){return"M"+t.join("L")},P=function(t){return z(t.reverse())};var O=p(r,{xaxis:y,yaxis:b,connectGaps:x.connectgaps,baseTolerance:Math.max(_.width||1,3)/4,linear:"linear"===_.shape});if(O.length){for(var I=O[0][0],N=O[O.length-1],F=N[N.length-1],D=0;D1){var U=w.selectAll(".js-line").data([r]);U.enter().append("path").classed("js-line",!0).attr("d",L),a(U).attr("d",L)}}k?I&&F&&(M?("y"===M?I[1]=F[1]=b.c2p(0,!0):"x"===M&&(I[0]=F[0]=y.c2p(0,!0)),a(k).attr("d",R+"L"+F+"L"+I+"Z")):a(k).attr("d",R+"Z")):"tonext"===x.fill.substr(0,6)&&R&&T&&("tonext"===x.fill?a(A).attr("d",R+"Z"+T+"Z"):a(A).attr("d",R+"L"+T.substr(1)+"Z"))}x._revpath=j}var V=w.selectAll(".points").data([r]);V.enter().append("g").classed("points",!0).each(m),V.transition().duration(0).each(m),V.exit().remove()}}function o(t,e,r){var n=e.x(),i=e.y(),a=s.extent(n.range.map(n.l2c)),o=s.extent(i.range.map(i.l2c)),l=0,u=r[0].trace;if(f.hasMarkers(u)){var c=u.marker.maxdisplayed;if(0!==c){var h=r.filter(function(t){return t.x>=a[0]&&t.x<=a[1]&&t.y>=o[0]&&t.y<=o[1]}),p=Math.ceil(h.length/c),d=0;r.forEach(function(t,e){var r=t[0].trace;f.hasMarkers(r)&&r.marker.maxdisplayed>0&&l>e&&d++});var g=Math.round(d*p/3+Math.floor(d/3)*p/7.1);r.forEach(function(t){delete t.vis}),h.forEach(function(t,e){0===Math.round((e+g)%p)&&(t.vis=!0)})}}}var s=t("d3"),l=t("../../lib"),u=t("../../components/drawing"),c=t("../../components/errorbars"),f=t("./subtypes"),h=t("./arrays_to_calcdata"),p=t("./line_points"),d=t("./link_traces");e.exports=function(t,e,r,o,s){var u,c,f,h=l.extendFlat({},s||{});h=l.extendFlat({duration:0,easing:"in-out-cubic",cascade:0,delay:0},h);h.duration>0;if(o)f=!0;else{for(u=0,o=[];un?1:-1})}},{"../../components/drawing":1071,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1300,"./line_points":1312,"./link_traces":1314,"./subtypes":1322,d3:82}],1319:[function(t,e,r){"use strict";var n=t("./subtypes"),i=.2;e.exports=function(t,e){var r,a,o,s,l=t.cd,u=t.xaxis,c=t.yaxis,f=[],h=l[0].trace,p=h.index,d=h.marker;if(n.hasMarkers(h)||n.hasText(h)){var g=Array.isArray(d.opacity)?1:d.opacity;if(e===!1)for(r=0;rs;s++){for(var l=[[0,0,0],[0,0,0]],u=0;3>u;u++)if(r[u])for(var c=0;2>c;c++)l[c][u]=r[u][s][c];o[s]=l}return o}var o=t("../../components/errorbars/compute_error");e.exports=a},{"../../components/errorbars/compute_error":1075}],1328:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.linePlot=null,this.scatterPlot=null,this.errorBars=null,this.textMarkers=null,this.delaunayMesh=null,this.color=null,this.mode="",this.dataPoints=[],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.textLabels=null,this.data=null}function i(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;ni;i++){var a=t[i];a&&a.copy_zstyle!==!1&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=b(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}function o(t){var e=[0,0];return Array.isArray(t)?[0,-1]:(t.indexOf("bottom")>=0&&(e[1]+=1),t.indexOf("top")>=0&&(e[1]-=1),t.indexOf("left")>=0&&(e[0]-=1),t.indexOf("right")>=0&&(e[0]+=1),e)}function s(t,e){return e(4*t)}function l(t){return k[t]}function u(t,e,r,n,i){var a=null;if(Array.isArray(t)){a=[];for(var o=0;e>o;o++)void 0===t[o]?a[o]=n:a[o]=r(t[o],i)}else a=r(t,y.identity);return a}function c(t,e){var r,n,i,c,f,h,p=[],d=t.fullSceneLayout,g=t.dataScale,v=d.xaxis,m=d.yaxis,w=d.zaxis,k=e.marker,M=e.line,T=e.x||[],E=e.y||[],L=e.z||[],S=T.length;for(n=0;S>n;n++)i=v.d2l(T[n])*g[0],c=m.d2l(E[n])*g[1],f=w.d2l(L[n])*g[2],p[n]=[i,c,f];if(Array.isArray(e.text))h=e.text;else if(void 0!==e.text)for(h=new Array(S),n=0;S>n;n++)h[n]=e.text;if(r={position:p,mode:e.mode,text:h},"line"in e&&(r.lineColor=b(M.color),r.lineWidth=M.width,r.lineDashes=M.dash),"marker"in e){var C=_(e);r.scatterColor=x(k,1,S),r.scatterSize=u(k.size,S,s,20,C),r.scatterMarker=u(k.symbol,S,l,"\u25cf"),r.scatterLineWidth=k.line.width,r.scatterLineColor=x(k.line,1,S),r.scatterAngle=0}"textposition"in e&&(r.textOffset=o(e.textposition),r.textColor=x(e.textfont,1,S),r.textSize=u(e.textfont.size,S,y.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var z=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;3>n;++n){var P=e.projection[z[n]];(r.project[n]=P.show)&&(r.projectOpacity[n]=P.opacity,r.projectScale[n]=P.scale)}r.errorBounds=A(e,g);var R=a([e.error_x,e.error_y,e.error_z]);return r.errorColor=R.color,r.errorLineWidth=R.lineWidth,r.errorCapSize=R.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=b(e.surfacecolor),r}function f(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}function h(t,e){var r=new n(t,e.uid);return r.update(e),r}var p=t("gl-line3d"),d=t("gl-scatter3d"),g=t("gl-error3d"),v=t("gl-mesh3d"),m=t("delaunay-triangulate"),y=t("../../lib"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/make_bubble_size_func"),w=t("../../constants/gl3d_dashes"),k=t("../../constants/gl_markers"),A=t("./calc_errors"),M=n.prototype;M.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels&&void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel="";var e=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},M.update=function(t){var e,r,n,a,o=this.scene.glplot.gl,s=w.solid;this.data=t;var l=c(this.scene,t);"mode"in l&&(this.mode=l.mode),"lineDashes"in l&&l.lineDashes in w&&(s=w[l.lineDashes]),this.color=f(l.scatterColor)||f(l.lineColor),this.dataPoints=l.position,e={gl:o,position:l.position,color:l.lineColor,lineWidth:l.lineWidth||1,dashes:s[0],dashScale:s[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=p(e),this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var u=t.opacity;if(t.marker&&t.marker.opacity&&(u*=t.marker.opacity),r={gl:o,position:l.position,color:l.scatterColor,size:l.scatterSize,glyph:l.scatterMarker,opacity:u,orthographic:!0,lineWidth:l.scatterLineWidth,lineColor:l.scatterLineColor,project:l.project,projectScale:l.projectScale,projectOpacity:l.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=d(r),this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),a={gl:o,position:l.position,glyph:l.text,color:l.textColor,size:l.textSize,angle:l.textAngle,alignment:l.textOffset,font:l.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=l.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(a):(this.textMarkers=d(a),this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:o,position:l.position,color:l.errorColor,error:l.errorBounds,lineWidth:l.errorLineWidth,capSize:l.errorCapSize,opacity:t.opacity},this.errorBars?l.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):l.errorBounds&&(this.errorBars=g(n),this.scene.glplot.add(this.errorBars)),l.delaunayAxis>=0){var h=i(l.position,l.delaunayColor,l.delaunayAxis);h.opacity=t.opacity,this.delaunayMesh?this.delaunayMesh.update(h):(h.gl=o,this.delaunayMesh=v(h),this.scene.glplot.add(this.delaunayMesh))}else this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose(),this.delaunayMesh=null)},M.dispose=function(){this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose()),this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose()),this.errorBars&&(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose()),this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose()),this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose())},e.exports=h},{"../../constants/gl3d_dashes":1113,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../scatter/make_bubble_size_func":1315,"./calc_errors":1327,"delaunay-triangulate":88,"gl-error3d":123,"gl-line3d":193,"gl-mesh3d":253,"gl-scatter3d":905}],1329:[function(t,e,r){"use strict";function n(t,e,r){var n=0,i=r("x"),a=r("y"),o=r("z");return i&&a&&o&&(n=Math.min(i.length,a.length,o.length),n=0&&h("surfacecolor",d||g);for(var v=["x","y","z"],m=0;3>m;++m){var y="projection."+v[m];h(y+".show")&&(h(y+".opacity"),h(y+".scale"))}u(t,e,r,{axis:"z"}),u(t,e,r,{axis:"y",inherit:"z"}),u(t,e,r,{axis:"x",inherit:"z"})}},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1325}],1330:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../constants/gl_markers":1114,"../../plots/gl3d":1186,"../scatter/colorbar":1304,"./attributes":1325,"./calc":1326,"./convert":1328,"./defaults":1329}],1331:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../components/colorscale/color_attributes"),o=t("../../lib/extend").extendFlat,s=n.marker,l=n.line,u=s.line;e.exports={lon:{valType:"data_array"},lat:{valType:"data_array"},locations:{valType:"data_array"},locationmode:{valType:"enumerated",values:["ISO-3","USA-states","country names"],dflt:"ISO-3"},mode:o({},n.mode,{dflt:"markers"}),text:o({},n.text,{}),line:{color:l.color,width:l.width,dash:l.dash},marker:o({},{symbol:s.symbol,opacity:s.opacity,size:s.size,sizeref:s.sizeref,sizemin:s.sizemin,sizemode:s.sizemode,showscale:s.showscale,line:o({},{width:u.width},a("marker.line"))},a("marker")),textfont:n.textfont,textposition:n.textposition,hoverinfo:o({},i.hoverinfo,{flags:["lon","lat","location","text","name"]}),_nestedModules:{"marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1332:[function(t,e,r){"use strict";var n=t("../scatter/marker_colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(e),r}},{"../scatter/marker_colorscale_calc":1316}],1333:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=0,o=r("locations");return o?(r("locationmode"),a=o.length):(n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length),an;n++)r[n]=[t.lon[n],t.lat[n]];return{type:"LineString",coordinates:r,trace:t}}function a(t,e){function r(e){var r=t.mockAxis;return u.tickText(r,r.c2l(e),"hover").text+"\xb0"}var n=e.hoverinfo;if("none"===n)return function(t){delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("location")&&Array.isArray(e.locations),o=-1!==i.indexOf("lon"),s=-1!==i.indexOf("lat"),l=-1!==i.indexOf("text");return function(t){var n=[];a?n.push(t.location):o&&s?n.push("("+r(t.lon)+", "+r(t.lat)+")"):o?n.push("lon: "+r(t.lon)):s&&n.push("lat: "+r(t.lat)),l&&n.push(t.tx||e.text),t.textLabel=n.join("
")}}function o(t){var e=Array.isArray(t.locations);return function(r,n){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:n,lon:r.lon,lat:r.lat,location:e?r.location:null}]}}}var s=t("d3"),l=t("../../plots/cartesian/graph_interact"),u=t("../../plots/cartesian/axes"),c=t("../../lib/topojson_utils").getTopojsonFeatures,f=t("../../lib/geo_location_utils").locationToFeature,h=t("../../lib/array_to_calc_item"),p=t("../../components/color"),d=t("../../components/drawing"),g=t("../scatter/subtypes"),v=t("./attributes"),m=e.exports={}; +m.calcGeoJSON=function(t,e){var r,i,a,o,s=[],l=Array.isArray(t.locations);l?(o=t.locations,r=o.length,i=c(t,e),a=function(t,e){var r=f(t.locationmode,o[e],i);return void 0!==r?r.properties.ct:void 0}):(r=t.lon.length,a=function(t,e){return[t.lon[e],t.lat[e]]});for(var u=0;r>u;u++){var h=a(t,u);if(h){var p={lon:h[0],lat:h[1],location:l?t.locations[u]:null};n(t,p,u),s.push(p)}}return s.length>0&&(s[0].trace=t),s},m.plot=function(t,e){var r=t.framework.select(".scattergeolayer").selectAll("g.trace.scattergeo").data(e,function(t){return t.uid});r.enter().append("g").attr("class","trace scattergeo"),r.exit().remove(),r.selectAll("*").remove(),r.each(function(t){var e=s.select(this);g.hasLines(t)&&e.selectAll("path.js-line").data([i(t)]).enter().append("path").classed("js-line",!0)}),r.each(function(e){function r(r,n){if(t.showHover){var i=t.projection([r.lon,r.lat]);h(r),l.loneHover({x:i[0],y:i[1],name:v?e.name:void 0,text:r.textLabel,color:r.mc||(e.marker||{}).color},{container:t.hoverContainer.node()}),y=p(r,n),t.graphDiv.emit("plotly_hover",y)}}function n(e,r){t.graphDiv.emit("plotly_click",p(e,r))}var i=s.select(this),u=g.hasMarkers(e),c=g.hasText(e);if(u||c){var f=m.calcGeoJSON(e,t.topojson),h=a(t,e),p=o(e),d=e.hoverinfo,v="all"===d||-1!==d.indexOf("name"),y=null;u&&i.selectAll("path.point").data(f).enter().append("path").classed("point",!0).on("mouseover",r).on("click",n).on("mouseout",function(){l.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",y)}).on("mousedown",function(){l.loneUnhover(t.hoverContainer)}).on("mouseup",r),c&&i.selectAll("g").data(f).enter().append("g").append("text")}}),m.style(t)},m.style=function(t){var e=t.framework.selectAll("g.trace.scattergeo");e.style("opacity",function(t){return t.opacity}),e.each(function(t){s.select(this).selectAll("path.point").call(d.pointStyle,t),s.select(this).selectAll("text").call(d.textPointStyle,t)}),e.selectAll("path.js-line").style("fill","none").each(function(t){var e=t.trace,r=e.line||{};s.select(this).call(p.stroke,r.color).call(d.dashLine,r.dash||"",r.width||0)})}},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../scatter/subtypes":1322,"./attributes":1331,d3:82}],1336:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/colorscale/color_attributes"),a=t("../../constants/gl2d_dashes"),o=t("../../constants/gl_markers"),s=t("../../lib/extend").extendFlat,l=t("../../lib/extend").extendDeep,u=n.line,c=n.marker,f=c.line;e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:s({},n.text,{}),mode:{valType:"flaglist",flags:["lines","markers"],extras:["none"]},line:{color:u.color,width:u.width,dash:{valType:"enumerated",values:Object.keys(a),dflt:"solid"}},marker:l({},i("marker"),{symbol:{valType:"enumerated",values:Object.keys(o),dflt:"circle",arrayOk:!0},size:c.size,sizeref:c.sizeref,sizemin:c.sizemin,sizemode:c.sizemode,opacity:c.opacity,showscale:c.showscale,line:l({},i("marker.line"),{width:f.width})}),connectgaps:n.connectgaps,fill:s({},n.fill,{values:["none","tozeroy","tozerox"]}),fillcolor:n.fillcolor,_nestedModules:{error_x:"ErrorBars",error_y:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":1056,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1337:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.connectgaps=!0,this.idToIndex=[],this.bounds=[0,0,0,0],this.hasLines=!1,this.lineOptions={positions:new Float32Array(0),color:[0,0,0,1],width:1,fill:[!1,!1,!1,!1],fillColor:[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],dashes:[1]},this.line=p(t.glplot,this.lineOptions),this.line._trace=this,this.hasErrorX=!1,this.errorXOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorX=d(t.glplot,this.errorXOptions),this.errorX._trace=this,this.hasErrorY=!1,this.errorYOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorY=d(t.glplot,this.errorYOptions),this.errorY._trace=this,this.hasMarkers=!1,this.scatterOptions={positions:new Float32Array(0),sizes:[],colors:[],glyphs:[],borderWidths:[],borderColors:[],size:12,color:[0,0,0,1],borderSize:1,borderColor:[0,0,0,1]},this.scatter=f(t.glplot,this.scatterOptions),this.scatter._trace=this,this.fancyScatter=h(t.glplot,this.scatterOptions),this.fancyScatter._trace=this}function i(t,e,r){return Array.isArray(e)||(e=[e]),a(t,e,r)}function a(t,e,r){for(var n=new Array(r),i=e[0],a=0;r>a;++a)n[a]=t(a>=e.length?i:e[a]);return n}function o(t,e,r){return l(S(t,r),L(e,r),r)}function s(t,e,r,n){var i=x(t,e,n);return i=Array.isArray(i[0])?i:a(v.identity,[i],n),l(i,L(r,n),n)}function l(t,e,r){for(var n=new Array(4*r),i=0;r>i;++i){for(var a=0;3>a;++a)n[4*i+a]=t[i][a];n[4*i+3]=t[i][3]*e[i]}return n}function u(t,e){if(void 0===Float32Array.slice){for(var r=new Float32Array(e),n=0;e>n;n++)r[n]=t[n];return r}return t.slice(0,e)}function c(t,e){var r=new n(t,e.uid);return r.update(e),r}var f=t("gl-scatter2d"),h=t("gl-scatter2d-fancy"),p=t("gl-line2d"),d=t("gl-error2d"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../plots/cartesian/axes"),y=t("../../components/errorbars"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/subtypes"),w=t("../scatter/make_bubble_size_func"),k=t("../scatter/get_trace_color"),A=t("../../constants/gl_markers"),M=t("../../constants/gl2d_dashes"),T=["xaxis","yaxis"],E=n.prototype;E.handlePick=function(t){var e=t.pointId;return(t.object!==this.line||this.connectgaps)&&(e=this.idToIndex[t.pointId]),{trace:this,dataCoord:t.dataCoord,traceCoord:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:Array.isArray(this.color)?this.color[e]:this.color,name:this.name,hoverinfo:this.hoverinfo}},E.isFancy=function(t){if("linear"!==this.scene.xaxis.type)return!0;if("linear"!==this.scene.yaxis.type)return!0;if(!t.x||!t.y)return!0;if(this.hasMarkers){var e=t.marker||{};if(Array.isArray(e.symbol)||"circle"!==e.symbol||Array.isArray(e.size)||Array.isArray(e.color)||Array.isArray(e.line.width)||Array.isArray(e.line.color)||Array.isArray(e.opacity))return!0}return this.hasLines&&!this.connectgaps?!0:this.hasErrorX?!0:!!this.hasErrorY};var L=i.bind(null,function(t){return+t}),S=i.bind(null,b),C=i.bind(null,function(t){return A[t]||"\u25cf"});E.update=function(t){t.visible!==!0?(this.hasLines=!1,this.hasErrorX=!1,this.hasErrorY=!1,this.hasMarkers=!1):(this.hasLines=_.hasLines(t),this.hasErrorX=t.error_x.visible===!0,this.hasErrorY=t.error_y.visible===!0,this.hasMarkers=_.hasMarkers(t)),this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.connectgaps=!!t.connectgaps,this.isFancy(t)?this.updateFancy(t):this.updateFast(t),this.color=k(t,{})},E.updateFast=function(t){for(var e,r,n=this.xData=this.pickXData=t.x,i=this.yData=this.pickYData=t.y,a=n.length,o=new Array(a),s=new Float32Array(2*a),l=this.bounds,c=0,f=0,h=0;a>h;++h)e=n[h],r=i[h],g(e)&&g(r)&&(o[c++]=h,s[f++]=e,s[f++]=r,l[0]=Math.min(l[0],e),l[1]=Math.min(l[1],r),l[2]=Math.max(l[2],e),l[3]=Math.max(l[3],r));s=u(s,f),this.idToIndex=o,this.updateLines(t,s),this.updateError("X",t),this.updateError("Y",t);var p;if(this.hasMarkers){this.scatterOptions.positions=s;var d=b(t.marker.color),v=b(t.marker.line.color),m=t.opacity*t.marker.opacity;d[3]*=m,this.scatterOptions.color=d,v[3]*=m,this.scatterOptions.borderColor=v,p=t.marker.size,this.scatterOptions.size=p,this.scatterOptions.borderSize=t.marker.line.width,this.scatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions),this.expandAxesFast(l,p)},E.updateFancy=function(t){var e=this.scene,r=e.xaxis,n=e.yaxis,a=this.bounds,o=this.pickXData=r.makeCalcdata(t,"x").slice(),l=this.pickYData=n.makeCalcdata(t,"y").slice();this.xData=o.slice(),this.yData=l.slice();var c,f,h,p,d,g,v,m,b=y.calcFromTrace(t,e.fullLayout),x=o.length,_=new Array(x),k=new Float32Array(2*x),A=new Float32Array(4*x),M=new Float32Array(4*x),T=0,E=0,S=0,z=0,P="log"===r.type?function(t){return r.d2l(t)}:function(t){return t},R="log"===n.type?function(t){return n.d2l(t)}:function(t){return t};for(c=0;x>c;++c)this.xData[c]=h=P(o[c]),this.yData[c]=p=R(l[c]),isNaN(h)||isNaN(p)||(_[T++]=c,k[E++]=h,k[E++]=p,d=A[S++]=h-b[c].xs||0,g=A[S++]=b[c].xh-h||0,A[S++]=0,A[S++]=0,M[z++]=0,M[z++]=0,v=M[z++]=p-b[c].ys||0,m=M[z++]=b[c].yh-p||0,a[0]=Math.min(a[0],h-d),a[1]=Math.min(a[1],p-v),a[2]=Math.max(a[2],h+g),a[3]=Math.max(a[3],p+m));k=u(k,E),this.idToIndex=_,this.updateLines(t,k),this.updateError("X",t,k,A),this.updateError("Y",t,k,M);var j;if(this.hasMarkers){this.scatterOptions.positions=k,this.scatterOptions.sizes=new Array(T),this.scatterOptions.glyphs=new Array(T),this.scatterOptions.borderWidths=new Array(T),this.scatterOptions.colors=new Array(4*T),this.scatterOptions.borderColors=new Array(4*T);var O,I=w(t),N=t.marker,F=N.opacity,D=t.opacity,B=s(N,F,D,x),U=C(N.symbol,x),V=L(N.line.width,x),q=s(N.line,F,D,x);for(j=i(I,N.size,x),c=0;T>c;++c)for(O=_[c],this.scatterOptions.sizes[c]=4*j[O],this.scatterOptions.glyphs[c]=U[O],this.scatterOptions.borderWidths[c]=.5*V[O],f=0;4>f;++f)this.scatterOptions.colors[4*c+f]=B[4*O+f],this.scatterOptions.borderColors[4*c+f]=q[4*O+f];this.fancyScatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions),this.expandAxesFancy(o,l,j)},E.updateLines=function(t,e){var r;if(this.hasLines){var n=e;if(!t.connectgaps){var i=0,a=this.xData,s=this.yData;for(n=new Float32Array(2*a.length),r=0;ro;o++)r=this.scene[T[o]],n=r._min,n||(n=[]),n.push({val:t[o],pad:a}),i=r._max,i||(i=[]),i.push({val:t[o+2],pad:a})},E.expandAxesFancy=function(t,e,r){var n=this.scene,i={padded:!0,ppad:r};m.expand(n.xaxis,t,i),m.expand(n.yaxis,e,i)},E.dispose=function(){this.line.dispose(),this.errorX.dispose(),this.errorY.dispose(),this.scatter.dispose(),this.fancyScatter.dispose()},e.exports=c},{"../../components/errorbars":1077,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../scatter/get_trace_color":1308,"../scatter/make_bubble_size_func":1315,"../scatter/subtypes":1322,"fast-isnumeric":90,"gl-error2d":91,"gl-line2d":160,"gl-scatter2d":781,"gl-scatter2d-fancy":746}],1338:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/xy_defaults"),s=t("../scatter/marker_defaults"),l=t("../scatter/line_defaults"),u=t("../scatter/fillcolor_defaults"),c=t("../../components/errorbars/defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function p(r,i){return n.coerce(t,e,f,r,i)}var d=o(t,e,p);return d?(p("text"),p("mode",dr;r++)y=e.a[r],b=e.b[r],x=e.c[r],n(y)&&n(b)&&n(x)?(y=+y,b=+b,x=+x,_=v/(y+b+x),1!==_&&(y*=_,b*=_,x*=_),k=y,w=x-b,M[r]={x:w,y:k,a:y,b:b,c:x}):M[r]={x:!1,y:!1};var T,E;if(o.hasMarkers(e)&&(T=e.marker,E=T.size,Array.isArray(E))){var L={type:"linear"};i.setConvert(L),E=L.makeCalcdata(e.marker,"size"),E.length>A&&E.splice(A,E.length-A)}return s(e),void 0!==typeof E&&a.mergeArray(E,M,"ms"),M}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../scatter/marker_colorscale_calc":1316,"../scatter/subtypes":1322,"fast-isnumeric":90}],1342:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/line_shape_defaults"),u=t("../scatter/text_defaults"),c=t("../scatter/fillcolor_defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function p(r,i){return n.coerce(t,e,f,r,i)}var d,g=p("a"),v=p("b"),m=p("c");if(g?(d=g.length,v?(d=Math.min(d,v.length),m&&(d=Math.min(d,m.length))):d=m?Math.min(d,m.length):0):v&&m&&(d=Math.min(v.length,m.length)),!d)return void(e.visible=!1);g&&d"),s}}},{"../../plots/cartesian/axes":1150,"../scatter/hover":1309}],1344:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scatterternary",n.basePlotModule=t("../../plots/ternary"),n.categories=["ternary","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../plots/ternary":1206,"../scatter/colorbar":1304,"./attributes":1340,"./calc":1341,"./defaults":1342,"./hover":1343,"./plot":1345,"./select":1346,"./style":1347}],1345:[function(t,e,r){"use strict";var n=t("../scatter/plot");e.exports=function(t,e){var r=t.plotContainer;r.select(".scatterlayer").selectAll("*").remove();for(var i={x:function(){return t.xaxis},y:function(){return t.yaxis},plot:r},a=new Array(e.length),o=t.graphDiv.calcdata,s=0;se){for(var r=g/e,n=[0|Math.floor(t[0].shape[0]*r+1),0|Math.floor(t[0].shape[1]*r+1)],i=n[0]*n[1],o=0;or;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},v.update=function(t){var e,r=this.scene,n=r.fullSceneLayout,a=this.surface,s=t.opacity,l=i(t.colorscale,s),c=t.z,h=t.x,p=t.y,g=n.xaxis,v=n.yaxis,m=n.zaxis,y=r.dataScale,b=c[0].length,x=c.length,_=[u(new Float32Array(b*x),[b,x]),u(new Float32Array(b*x),[b,x]),u(new Float32Array(b*x),[b,x])],w=_[0],k=_[1],A=r.contourLevels;this.data=t,f(_[2],function(t,e){return m.d2l(c[e][t])*y[2]}),Array.isArray(h[0])?f(w,function(t,e){return g.d2l(h[e][t])*y[0]}):f(w,function(t){return g.d2l(h[t])*y[0]}),Array.isArray(p[0])?f(k,function(t,e){return v.d2l(p[e][t])*y[1]}):f(k,function(t,e){return v.d2l(p[e])*y[1]});var M={colormap:l,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:1};if(M.intensityBounds=[t.cmin,t.cmax],t.surfacecolor){var T=u(new Float32Array(b*x),[b,x]);f(T,function(e,r){return t.surfacecolor[r][e]}),_.push(T)}else M.intensityBounds[0]*=y[2],M.intensityBounds[1]*=y[2];this.dataScale=o(_),t.surfacecolor&&(M.intensity=_.pop()),"opacity"in t&&t.opacity<1&&(M.opacity=.25*t.opacity);var E=[!0,!0,!0],L=["x","y","z"];for(e=0;3>e;++e){var S=t.contours[L[e]];E[e]=S.highlight,M.showContour[e]=S.show||S.highlight,M.showContour[e]&&(M.contourProject[e]=[S.project.x,S.project.y,S.project.z],S.show?(this.showContour[e]=!0,M.levels[e]=A[e],a.highlightColor[e]=M.contourColor[e]=d(S.color),S.usecolormap?a.highlightTint[e]=M.contourTint[e]=0:a.highlightTint[e]=M.contourTint[e]=1,M.contourWidth[e]=S.width):this.showContour[e]=!1,S.highlight&&(M.dynamicColor[e]=d(S.highlightcolor),M.dynamicWidth[e]=S.highlightwidth))}M.coords=_,a.update(M),a.visible=t.visible,a.enableDynamic=E,a.snapToData=!0,"lighting"in t&&(a.ambientLight=t.lighting.ambient,a.diffuseLight=t.lighting.diffuse,a.specularLight=t.lighting.specular,a.roughness=t.lighting.roughness,a.fresnel=t.lighting.fresnel),"lightposition"in t&&(a.lightPosition=[t.lightposition.x,t.lightposition.y,t.lightposition.z]),s&&1>s&&(a.supportsTransparency=!0)},v.dispose=function(){this.scene.glplot.remove(this.surface),this.surface.dispose()},e.exports=s},{"../../lib/str2rgbarray":1139,"gl-surface3d":1003,ndarray:1031,"ndarray-fill":1009,"ndarray-homography":1025,"ndarray-ops":1026,tinycolor2:1042}],1352:[function(t,e,r){"use strict";function n(t,e,r){e in t&&!(r in t)&&(t[r]=t[e])}var i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}var u,c,f=l("z");if(!f)return void(e.visible=!1);var h=f[0].length,p=f.length;if(l("x"),l("y"),!Array.isArray(e.x))for(e.x=[],u=0;h>u;++u)e.x[u]=u;if(l("text"),!Array.isArray(e.y))for(e.y=[],u=0;p>u;++u)e.y[u]=u;["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lightposition.x","lightposition.y","lightposition.z","hidesurface","opacity"].forEach(function(t){l(t)});var d=l("surfacecolor");l("colorscale");var g=["x","y","z"];for(u=0;3>u;++u){var v="contours."+g[u],m=l(v+".show"),y=l(v+".highlight");if(m||y)for(c=0;3>c;++c)l(v+".project."+g[c]);m&&(l(v+".color"),l(v+".width"),l(v+".usecolormap")),y&&(l(v+".highlightcolor"),l(v+".highlightwidth"))}d||(n(t,"zmin","cmin"),n(t,"zmax","cmax"),n(t,"zauto","cauto")),a(t,e,s,l,{prefix:"",cLetter:"c"})}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1348}],1353:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("./colorbar"),n.calc=t("./calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="surface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","noOpacity"],n.meta={},e.exports=n},{"../../plots/gl3d":1186,"./attributes":1348,"./calc":1349,"./colorbar":1350,"./convert":1351,"./defaults":1352}]},{},[12])(12)}); \ No newline at end of file From 821c57ef75347fc07e4350926f7a302b9bf3be49 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Thu, 16 Jun 2016 13:09:51 -0400 Subject: [PATCH 15/21] Object persistence for error bars --- src/components/errorbars/plot.js | 47 ++++++++++++++++++++++++++------ src/plot_api/plot_api.js | 11 +++++++- src/traces/scatter/plot.js | 13 +++++---- 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/src/components/errorbars/plot.js b/src/components/errorbars/plot.js index 3f44ed58df1..9bf9610e1f5 100644 --- a/src/components/errorbars/plot.js +++ b/src/components/errorbars/plot.js @@ -14,12 +14,17 @@ var isNumeric = require('fast-isnumeric'); var Lib = require('../../lib'); var subTypes = require('../../traces/scatter/subtypes'); +var styleError = require('./style'); -module.exports = function plot(traces, plotinfo) { +module.exports = function plot(traces, plotinfo, transitionConfig) { var xa = plotinfo.x(), ya = plotinfo.y(); + + transitionConfig = transitionConfig || {}; + var hasAnimation = isNumeric(transitionConfig.duration) && transitionConfig.duration > 0 + traces.each(function(d) { var trace = d[0].trace, // || {} is in case the trace (specifically scatterternary) @@ -42,7 +47,9 @@ module.exports = function plot(traces, plotinfo) { errorbars.enter().append('g') .classed('errorbar', true); - errorbars.each(function(d) { + errorbars.exit().remove(); + + errorbars.each(function(d, i) { var errorbar = d3.select(this); var coords = errorCoords(d, xa, ya); @@ -59,11 +66,23 @@ module.exports = function plot(traces, plotinfo) { coords.yh + 'h' + (2 * yw) + // hat 'm-' + yw + ',0V' + coords.ys; // bar + if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe - errorbar.append('path') - .classed('yerror', true) - .attr('d', path); + var yerror = errorbar.select('path.yerror'); + + if (!yerror.size()) { + yerror = errorbar.append('path') + .classed('yerror', true); + } else if (hasAnimation) { + yerror = yerror.transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .delay(transitionConfig.delay) + + } + + yerror.attr('d', path); } if(xObj.visible && isNumeric(coords.y) && @@ -77,11 +96,23 @@ module.exports = function plot(traces, plotinfo) { if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe - errorbar.append('path') - .classed('xerror', true) - .attr('d', path); + var xerror = errorbar.select('path.xerror'); + + if (!xerror.size()) { + xerror = errorbar.append('path') + .classed('xerror', true); + } else if (hasAnimation) { + xerror = xerror.transition() + .duration(transitionConfig.duration) + .ease(transitionConfig.easing) + .delay(transitionConfig.delay) + } + + xerror.attr('d', path); } }); + + d3.select(this).call(styleError); }); }; diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index b3a960e840e..41cd4dd5e5f 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1575,19 +1575,28 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { Lib.nestedProperty(curData, ai).set(value); } - var traceIdx = traces[i]; if (gd.data[traceIdx].marker && gd.data[traceIdx].marker.size) { gd._fullData[traceIdx].marker.size = gd.data[traceIdx].marker.size } + if (gd.data[traceIdx].error_y && gd.data[traceIdx].error_y.array) { + gd._fullData[traceIdx].error_y.array = gd.data[traceIdx].error_y.array + } + if (gd.data[traceIdx].error_x && gd.data[traceIdx].error_x.array) { + gd._fullData[traceIdx].error_x.array = gd.data[traceIdx].error_x.array + } gd._fullData[traceIdx].x = gd.data[traceIdx].x; gd._fullData[traceIdx].y = gd.data[traceIdx].y; gd._fullData[traceIdx].z = gd.data[traceIdx].z; gd._fullData[traceIdx].key = gd.data[traceIdx].key; + gd._fullData[traceIdx].r = gd.data[traceIdx].r; + gd._fullData[traceIdx].t = gd.data[traceIdx].t; } doCalcdata(gd, animatedTraces); + ErrorBars.calc(gd); + function doSetPositions () { var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'); var modules = fullLayout._modules; diff --git a/src/traces/scatter/plot.js b/src/traces/scatter/plot.js index b15f49a798d..afd44d8c34a 100644 --- a/src/traces/scatter/plot.js +++ b/src/traces/scatter/plot.js @@ -62,14 +62,12 @@ module.exports = function plot(gd, plotinfo, cdscatter, traces, transitionOpts) createFills(gd, scatterlayer, cdscatter, traces) traceEnter.each(function(d) { - //console.log('enter:', d[0].trace.uid); plotOne(gd, plotinfo, d, this, transitionConfig) }); traceJoin.transition() .duration(0) .each(function(d) { - //console.log('transition:', d[0].trace.uid); plotOne(gd, plotinfo, d, this, transitionConfig) }); @@ -148,7 +146,7 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { // (so error bars can find them along with bars) // error bars are at the bottom - tr.call(ErrorBars.plot, plotinfo); + tr.call(ErrorBars.plot, plotinfo, transitionConfig); if(trace.visible !== true) return; @@ -314,6 +312,7 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { } } + var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; function makePoints (d) { var trace = d[0].trace, @@ -336,8 +335,12 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 0) .call(Drawing.pointStyle, trace) - join.exit() - .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); + if (hasTransition) { + join.exit() + .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); + } else { + join.exit().remove(); + } } if(showText) { s.selectAll('g') From a655a4b16bbaf5b526684a2bcfe13842459c59f8 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Fri, 17 Jun 2016 11:06:04 -0400 Subject: [PATCH 16/21] Error bar transitions --- src/components/errorbars/plot.js | 53 +++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/src/components/errorbars/plot.js b/src/components/errorbars/plot.js index 9bf9610e1f5..40243835044 100644 --- a/src/components/errorbars/plot.js +++ b/src/components/errorbars/plot.js @@ -34,6 +34,12 @@ module.exports = function plot(traces, plotinfo, transitionConfig) { xObj = trace.error_x || {}, yObj = trace.error_y || {}; + var keyFunc; + + if (trace.key) { + keyFunc = function (d) { return d.key }; + } + var sparse = ( subTypes.hasMarkers(trace) && trace.marker.maxdisplayed > 0 @@ -41,15 +47,25 @@ module.exports = function plot(traces, plotinfo, transitionConfig) { if(!yObj.visible && !xObj.visible) return; + var errorbars = d3.select(this).selectAll('g.errorbar') - .data(Lib.identity); + .data(Lib.identity, keyFunc); errorbars.enter().append('g') .classed('errorbar', true); - errorbars.exit().remove(); + if (hasAnimation) { + errorbars.exit() + .style('opacity', 1) + .transition() + .duration(transitionConfig.duration) + .style('opacity', 0) + .remove(); + } else { + errorbars.exit().remove(); + } - errorbars.each(function(d, i) { + errorbars.each(function(d) { var errorbar = d3.select(this); var coords = errorCoords(d, xa, ya); @@ -71,21 +87,32 @@ module.exports = function plot(traces, plotinfo, transitionConfig) { var yerror = errorbar.select('path.yerror'); - if (!yerror.size()) { + var isNew = !yerror.size(); + + if (isNew) { yerror = errorbar.append('path') .classed('yerror', true); + + if (hasAnimation) { + yerror = yerror.style('opacity', 0); + } } else if (hasAnimation) { yerror = yerror.transition() .duration(transitionConfig.duration) .ease(transitionConfig.easing) .delay(transitionConfig.delay) - } yerror.attr('d', path); + + if (isNew && hasAnimation) { + yerror = yerror.transition() + .duration(transitionConfig.duration) + .style('opacity', 1); + } } - if(xObj.visible && isNumeric(coords.y) && + if(xObj.visible && isNumeric(coords.x) && isNumeric(coords.xh) && isNumeric(coords.xs)) { var xw = (xObj.copy_ystyle ? yObj : xObj).width; @@ -98,9 +125,15 @@ module.exports = function plot(traces, plotinfo, transitionConfig) { var xerror = errorbar.select('path.xerror'); - if (!xerror.size()) { + var isNew = !xerror.size(); + + if (isNew) { xerror = errorbar.append('path') .classed('xerror', true); + + if (hasAnimation) { + xerror = xerror.style('opacity', 0); + } } else if (hasAnimation) { xerror = xerror.transition() .duration(transitionConfig.duration) @@ -109,6 +142,12 @@ module.exports = function plot(traces, plotinfo, transitionConfig) { } xerror.attr('d', path); + + if (isNew && hasAnimation) { + xerror = xerror.transition() + .duration(transitionConfig.duration) + .style('opacity', 1); + } } }); From c978b46ccbb460bdb397f94963ffd1e969286bf5 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Mon, 20 Jun 2016 12:10:18 -0400 Subject: [PATCH 17/21] First cut at scale transitions --- src/plot_api/plot_api.js | 20 +- src/plots/cartesian/index.js | 2 + src/plots/cartesian/transition_axes.js | 262 +++++++++++++++++++++++++ 3 files changed, 279 insertions(+), 5 deletions(-) create mode 100644 src/plots/cartesian/transition_axes.js diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 41cd4dd5e5f..4fe6299c97a 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1528,7 +1528,7 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { // 3. update gl._fullData // 4. doCalcdata // 5. begin animation -Plotly.animate = function animate (gd, newData, transitionOpts, traces) { +Plotly.animate = function animate (gd, newData, transitionOpts, traces, newLayout) { gd = getGraphDiv(gd); var fullLayout = gd._fullLayout; @@ -1597,7 +1597,7 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { ErrorBars.calc(gd); - function doSetPositions () { + /*function doSetPositions () { var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'); var modules = fullLayout._modules; @@ -1615,18 +1615,28 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces) { if(_module.setPositions) _module.setPositions(gd, subplotInfo); } } - } + }*/ - doSetPositions(); + //doSetPositions(); var restyleList = []; + var relayoutList = []; function doAnimations () { var a, i, j; var basePlotModules = fullLayout._basePlotModules; - for(j = 0; j < basePlotModules.length; j++) { + for (j = 0; j < basePlotModules.length; j++) { basePlotModules[j].plot(gd, animatedTraces, transitionOpts); } + + if (newLayout) { + for (j = 0; j < basePlotModules.length; j++) { + if (basePlotModules[j].transitionAxes) { + basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts); + } + } + } + if (!transitionOpts.leadingEdgeRestyle) { return new Promise(function(resolve, reject) { setTimeout(resolve, transitionOpts.duration); diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index 544ac495ca4..500c477b0d2 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -27,6 +27,8 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); +exports.transitionAxes = require('./transition_axes'); + exports.plot = function(gd, traces, transitionOpts) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), diff --git a/src/plots/cartesian/transition_axes.js b/src/plots/cartesian/transition_axes.js new file mode 100644 index 00000000000..15bf0e4cf73 --- /dev/null +++ b/src/plots/cartesian/transition_axes.js @@ -0,0 +1,262 @@ +/** +* Copyright 2012-2016, Plotly, Inc. +* All rights reserved. +* +* This source code is licensed under the MIT license found in the +* LICENSE file in the root directory of this source tree. +*/ + + +'use strict'; + +var d3 = require('d3'); +var isNumeric = require('fast-isnumeric'); + +var Plotly = require('../../plotly'); +var Lib = require('../../lib'); +var svgTextUtils = require('../../lib/svg_text_utils'); +var Titles = require('../../components/titles'); +var Color = require('../../components/color'); +var Drawing = require('../../components/drawing'); +var Axes = require('./axes'); + +var axisRegex = /((x|y)([2-9]|[1-9][0-9]+)?)axis$/; + +module.exports = function transitionAxes(gd, newLayout, transitionConfig) { + var fullLayout = gd._fullLayout; + var axes = []; + + function computeUpdates (layout) { + var ai, attrList, match, to, axis, update, i; + var updates = {}; + + for (ai in layout) { + var attrList = ai.split('.'); + var match = attrList[0].match(axisRegex); + if (match) { + var axisName = match[1]; + axis = fullLayout[axisName + 'axis']; + update = {}; + + if (Array.isArray(layout[ai])) { + update.to = layout[ai].slice(0); + } else { + if (Array.isArray(layout[ai].range)) { + update.to = layout[ai].range.slice(0); + } + } + if (!update.to) continue; + + update.axis = axis; + update.length = axis._length; + + axes.push(axisName); + + updates[axisName] = update; + } + } + + return updates; + } + + function computeAffectedSubplots (fullLayout, updatedAxisIds) { + var plotName; + var plotinfos = fullLayout._plots; + var affectedSubplots = []; + + for (plotName in plotinfos) { + var plotinfo = plotinfos[plotName]; + + if (affectedSubplots.indexOf(plotinfo) !== -1) continue; + + var x = plotinfo.xaxis._id; + var y = plotinfo.yaxis._id; + + if (updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) { + affectedSubplots.push(plotinfo); + } + } + + return affectedSubplots; + } + + var updates = computeUpdates(newLayout); + var updatedAxisIds = Object.keys(updates); + var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds); + var easeFn = d3.ease(transitionConfig.easing); + + function ticksAndAnnotations(xa, ya) { + var activeAxIds = [], + i; + + activeAxIds = [xa._id, ya._id]; + + for(i = 0; i < activeAxIds.length; i++) { + Axes.doTicks(gd, activeAxIds[i], true); + } + + function redrawObjs(objArray, module) { + var obji; + for(i = 0; i < objArray.length; i++) { + obji = objArray[i]; + if((activeAxIds.indexOf(obji.xref) !== -1) || + (activeAxIds.indexOf(obji.yref) !== -1)) { + module.draw(gd, i); + } + } + } + + redrawObjs(fullLayout.annotations || [], Plotly.Annotations); + redrawObjs(fullLayout.shapes || [], Plotly.Shapes); + redrawObjs(fullLayout.images || [], Plotly.Images); + } + + function unsetSubplotTransform (subplot) { + var xa2 = subplot.x(); + var ya2 = subplot.y(); + + var viewBox = [0, 0, xa2._length, ya2._length]; + + var editX = true; + var editY = true; + + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; + + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; + + fullLayout._defs.selectAll('#' + subplot.clipId) + .call(Lib.setTranslate, clipDx, clipDy) + .call(Lib.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + + subplot.plot + .call(Lib.setTranslate, plotDx, plotDy) + .call(Lib.setScale, xScaleFactor, yScaleFactor); + + } + + function updateSubplot (subplot, progress) { + var axis, r0, r1; + var xUpdate = updates[subplot.xaxis._id]; + var yUpdate = updates[subplot.yaxis._id]; + + var viewBox = []; + + if (xUpdate) { + axis = xUpdate.axis; + r0 = axis._r; + r1 = xUpdate.to; + viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length; + var dx1 = r0[1] - r0[0]; + var dx2 = r1[1] - r1[0]; + + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + + viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1); + } else { + viewBox[0] = 0; + viewBox[2] = subplot.xaxis._length; + } + + if (yUpdate) { + axis = yUpdate.axis; + r0 = axis._r; + r1 = yUpdate.to; + viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length; + var dy1 = r0[1] - r0[0]; + var dy2 = r1[1] - r1[0]; + + axis.range[0] = r0[0] * (1 - progress) + progress * r1[0]; + axis.range[1] = r0[1] * (1 - progress) + progress * r1[1]; + + viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1); + } else { + viewBox[1] = 0; + viewBox[3] = subplot.yaxis._length; + } + + ticksAndAnnotations(subplot.x(), subplot.y()); + + + var xa2 = subplot.x(); + var ya2 = subplot.y(); + + var editX = !!xUpdate; + var editY = !!yUpdate; + + var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, + yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + + var clipDx = editX ? viewBox[0] : 0, + clipDy = editY ? viewBox[1] : 0; + + var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, + fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + + var plotDx = xa2._offset - fracDx, + plotDy = ya2._offset - fracDy; + + fullLayout._defs.selectAll('#' + subplot.clipId) + .call(Lib.setTranslate, clipDx, clipDy) + .call(Lib.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + + subplot.plot + .call(Lib.setTranslate, plotDx, plotDy) + .call(Lib.setScale, xScaleFactor, yScaleFactor); + } + + // transitionTail - finish a drag event with a redraw + function transitionTail() { + var attrs = {}; + // revert to the previous axis settings, then apply the new ones + // through relayout - this lets relayout manage undo/redo + for(var i = 0; i < updatedAxisIds.length; i++) { + var axi = updates[updatedAxisIds[i]].axis; + if(axi._r[0] !== axi.range[0]) attrs[axi._name + '.range[0]'] = axi.range[0]; + if(axi._r[1] !== axi.range[1]) attrs[axi._name + '.range[1]'] = axi.range[1]; + + axi.range = axi._r.slice(); + } + + for (var i = 0; i < affectedSubplots.length; i++) { + unsetSubplotTransform(affectedSubplots[i]); + } + + Plotly.relayout(gd, attrs); + } + + return new Promise(function (resolve, reject) { + var t1, t2, raf; + + function doFrame () { + t2 = Date.now(); + + var tInterp = Math.min(1, (t2 - t1) / transitionConfig.duration); + var progress = easeFn(tInterp); + + for (var i = 0; i < affectedSubplots.length; i++) { + updateSubplot(affectedSubplots[i], progress); + } + + if (t2 - t1 > transitionConfig.duration) { + raf = cancelAnimationFrame(doFrame); + transitionTail(); + resolve(); + } else { + raf = requestAnimationFrame(doFrame); + resolve(); + } + } + + t1 = Date.now(); + raf = requestAnimationFrame(doFrame); + }); +} From 51672d8125b99800ebbe6ddce884d9fb450017b2 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Mon, 20 Jun 2016 12:35:42 -0400 Subject: [PATCH 18/21] Undo build --- dist/plotly-geo-assets.js | 4 +- dist/plotly-with-meta.js | 87773 +++++++++++++++++------------------- dist/plotly.js | 87506 +++++++++++++++++------------------ dist/plotly.min.js | 82 +- 4 files changed, 85144 insertions(+), 90221 deletions(-) diff --git a/dist/plotly-geo-assets.js b/dist/plotly-geo-assets.js index a7541601693..790d06749e3 100644 --- a/dist/plotly-geo-assets.js +++ b/dist/plotly-geo-assets.js @@ -1,5 +1,5 @@ /** -* plotly.js v1.13.0 +* plotly.js v1.12.0 * Copyright 2012-2016, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -69,7 +69,7 @@ var saneTopojson = require('sane-topojson'); // package version injected by `npm run preprocess` -exports.version = '1.13.0'; +exports.version = '1.12.0'; exports.topojson = saneTopojson; diff --git a/dist/plotly-with-meta.js b/dist/plotly-with-meta.js index ec9126e0053..3faaf5d5bf9 100644 --- a/dist/plotly-with-meta.js +++ b/dist/plotly-with-meta.js @@ -1,5 +1,5 @@ /** -* plotly.js v1.13.0 +* plotly.js v1.12.0 * Copyright 2012-2016, Plotly, Inc. * All rights reserved. * Licensed under the MIT license @@ -68,7 +68,7 @@ for(var selector in rules) { Plotly.Lib.addStyleRule(fullSelector, rules[selector]); } -},{"../src/plotly":1147}],2:[function(require,module,exports){ +},{"../src/plotly":400}],2:[function(require,module,exports){ 'use strict'; module.exports = { @@ -199,7 +199,7 @@ module.exports = { module.exports = require('../src/traces/bar'); -},{"../src/traces/bar":1225}],4:[function(require,module,exports){ +},{"../src/traces/bar":478}],4:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -210,7 +210,7 @@ module.exports = require('../src/traces/bar'); module.exports = require('../src/traces/box'); -},{"../src/traces/box":1236}],5:[function(require,module,exports){ +},{"../src/traces/box":489}],5:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -221,7 +221,7 @@ module.exports = require('../src/traces/box'); module.exports = require('../src/traces/choropleth'); -},{"../src/traces/choropleth":1245}],6:[function(require,module,exports){ +},{"../src/traces/choropleth":498}],6:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -232,7 +232,7 @@ module.exports = require('../src/traces/choropleth'); module.exports = require('../src/traces/contour'); -},{"../src/traces/contour":1252}],7:[function(require,module,exports){ +},{"../src/traces/contour":505}],7:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -243,7 +243,7 @@ module.exports = require('../src/traces/contour'); module.exports = require('../src/core'); -},{"../src/core":1116}],8:[function(require,module,exports){ +},{"../src/core":370}],8:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -254,7 +254,7 @@ module.exports = require('../src/core'); module.exports = require('../src/traces/heatmap'); -},{"../src/traces/heatmap":1264}],9:[function(require,module,exports){ +},{"../src/traces/heatmap":517}],9:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -265,7 +265,7 @@ module.exports = require('../src/traces/heatmap'); module.exports = require('../src/traces/histogram'); -},{"../src/traces/histogram":1275}],10:[function(require,module,exports){ +},{"../src/traces/histogram":528}],10:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -276,7 +276,7 @@ module.exports = require('../src/traces/histogram'); module.exports = require('../src/traces/histogram2d'); -},{"../src/traces/histogram2d":1280}],11:[function(require,module,exports){ +},{"../src/traces/histogram2d":533}],11:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -287,7 +287,7 @@ module.exports = require('../src/traces/histogram2d'); module.exports = require('../src/traces/histogram2dcontour'); -},{"../src/traces/histogram2dcontour":1284}],12:[function(require,module,exports){ +},{"../src/traces/histogram2dcontour":537}],12:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -336,7 +336,7 @@ module.exports = Core; module.exports = require('../src/traces/mesh3d'); -},{"../src/traces/mesh3d":1288}],14:[function(require,module,exports){ +},{"../src/traces/mesh3d":541}],14:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -347,7 +347,7 @@ module.exports = require('../src/traces/mesh3d'); module.exports = require('../src/traces/pie'); -},{"../src/traces/pie":1294}],15:[function(require,module,exports){ +},{"../src/traces/pie":547}],15:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -358,7 +358,7 @@ module.exports = require('../src/traces/pie'); module.exports = require('../src/traces/scatter3d'); -},{"../src/traces/scatter3d":1330}],16:[function(require,module,exports){ +},{"../src/traces/scatter3d":581}],16:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -369,7 +369,7 @@ module.exports = require('../src/traces/scatter3d'); module.exports = require('../src/traces/scattergeo'); -},{"../src/traces/scattergeo":1334}],17:[function(require,module,exports){ +},{"../src/traces/scattergeo":585}],17:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -380,7 +380,7 @@ module.exports = require('../src/traces/scattergeo'); module.exports = require('../src/traces/scattergl'); -},{"../src/traces/scattergl":1339}],18:[function(require,module,exports){ +},{"../src/traces/scattergl":590}],18:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -391,7 +391,7 @@ module.exports = require('../src/traces/scattergl'); module.exports = require('../src/traces/scatterternary'); -},{"../src/traces/scatterternary":1344}],19:[function(require,module,exports){ +},{"../src/traces/scatterternary":595}],19:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -402,206 +402,300 @@ module.exports = require('../src/traces/scatterternary'); module.exports = require('../src/traces/surface'); -},{"../src/traces/surface":1353}],20:[function(require,module,exports){ +},{"../src/traces/surface":604}],20:[function(require,module,exports){ 'use strict' -var bsearch = require('binary-search-bounds') -var m4interp = require('mat4-interpolate') -var invert44 = require('gl-mat4/invert') -var rotateX = require('gl-mat4/rotateX') -var rotateY = require('gl-mat4/rotateY') -var rotateZ = require('gl-mat4/rotateZ') -var lookAt = require('gl-mat4/lookAt') -var translate = require('gl-mat4/translate') -var scale = require('gl-mat4/scale') -var normalize = require('gl-vec3/normalize') +module.exports = createFilteredVector -var DEFAULT_CENTER = [0,0,0] +var cubicHermite = require('cubic-hermite') +var bsearch = require('binary-search-bounds') -module.exports = createMatrixCameraController +function clamp(lo, hi, x) { + return Math.min(hi, Math.max(lo, x)) +} -function MatrixCameraController(initialMatrix) { - this._components = initialMatrix.slice() - this._time = [0] - this.prevMatrix = initialMatrix.slice() - this.nextMatrix = initialMatrix.slice() - this.computedMatrix = initialMatrix.slice() - this.computedInverse = initialMatrix.slice() - this.computedEye = [0,0,0] - this.computedUp = [0,0,0] - this.computedCenter = [0,0,0] - this.computedRadius = [0] - this._limits = [-Infinity, Infinity] +function FilteredVector(state0, velocity0, t0) { + this.dimension = state0.length + this.bounds = [ new Array(this.dimension), new Array(this.dimension) ] + for(var i=0; i= n-1) { + var ptr = state.length-1 + var tf = t - time[n-1] + for(var i=0; i= n-1) { + var ptr = state.length-1 + var tf = t - time[n-1] + for(var i=0; i=0; --i) { + if(velocity[--ptr]) { + return false + } } + return true } -proto.idle = function(t) { - if(t < this.lastT()) { +proto.jump = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t < t0 || arguments.length !== d+1) { return } - var mc = this._components - var ptr = mc.length-16 - for(var i=0; i<16; ++i) { - mc.push(mc[ptr++]) + var state = this._state + var velocity = this._velocity + var ptr = state.length-this.dimension + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + this._time.push(t0, t) + for(var j=0; j<2; ++j) { + for(var i=0; i0; --i) { + state.push(clamp(lo[i-1], hi[i-1], arguments[i])) + velocity.push(0) + } } -proto.flush = function(t) { - var idx = bsearch.gt(this._time, t) - 2 - if(idx < 0) { +proto.push = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t < t0 || arguments.length !== d+1) { return } - this._time.slice(0, idx) - this._components.slice(0, 16*idx) -} - -proto.lastT = function() { - return this._time[this._time.length-1] -} - -proto.lookAt = function(t, eye, center, up) { - this.recalcMatrix(t) - eye = eye || this.computedEye - center = center || DEFAULT_CENTER - up = up || this.computedUp - this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) - var d2 = 0.0 - for(var i=0; i<3; ++i) { - d2 += Math.pow(center[i] - eye[i], 2) + var state = this._state + var velocity = this._velocity + var ptr = state.length-this.dimension + var dt = t - t0 + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var sf = (dt > 1e-6) ? 1/dt : 0 + this._time.push(t) + for(var i=d; i>0; --i) { + var xc = clamp(lo[i-1], hi[i-1], arguments[i]) + state.push(xc) + velocity.push((xc - state[ptr++]) * sf) } - d2 = Math.log(Math.sqrt(d2)) - this.computedRadius[0] = d2 -} - -proto.rotate = function(t, yaw, pitch, roll) { - this.recalcMatrix(t) - var mat = this.computedInverse - if(yaw) rotateY(mat, mat, yaw) - if(pitch) rotateX(mat, mat, pitch) - if(roll) rotateZ(mat, mat, roll) - this.setMatrix(t, invert44(this.computedMatrix, mat)) -} - -var tvec = [0,0,0] - -proto.pan = function(t, dx, dy, dz) { - tvec[0] = -(dx || 0.0) - tvec[1] = -(dy || 0.0) - tvec[2] = -(dz || 0.0) - this.recalcMatrix(t) - var mat = this.computedInverse - translate(mat, mat, tvec) - this.setMatrix(t, invert44(mat, mat)) } -proto.translate = function(t, dx, dy, dz) { - tvec[0] = dx || 0.0 - tvec[1] = dy || 0.0 - tvec[2] = dz || 0.0 - this.recalcMatrix(t) - var mat = this.computedMatrix - translate(mat, mat, tvec) - this.setMatrix(t, mat) +proto.set = function(t) { + var d = this.dimension + if(t < this.lastT() || arguments.length !== d+1) { + return + } + var state = this._state + var velocity = this._velocity + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + this._time.push(t) + for(var i=d; i>0; --i) { + state.push(clamp(lo[i-1], hi[i-1], arguments[i])) + velocity.push(0) + } } -proto.setMatrix = function(t, mat) { - if(t < this.lastT()) { +proto.move = function(t) { + var t0 = this.lastT() + var d = this.dimension + if(t <= t0 || arguments.length !== d+1) { return } + var state = this._state + var velocity = this._velocity + var statePtr = state.length - this.dimension + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var dt = t - t0 + var sf = (dt > 1e-6) ? 1/dt : 0.0 this._time.push(t) - for(var i=0; i<16; ++i) { - this._components.push(mat[i]) + for(var i=d; i>0; --i) { + var dx = arguments[i] + state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx)) + velocity.push(dx * sf) } } -proto.setDistance = function(t, d) { - this.computedRadius[0] = d +proto.idle = function(t) { + var t0 = this.lastT() + if(t < t0) { + return + } + var d = this.dimension + var state = this._state + var velocity = this._velocity + var statePtr = state.length-d + var bounds = this.bounds + var lo = bounds[0] + var hi = bounds[1] + var dt = t - t0 + this._time.push(t) + for(var i=d-1; i>=0; --i) { + state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) + velocity.push(0) + statePtr += 1 + } } -proto.setDistanceLimits = function(a,b) { - var lim = this._limits - lim[0] = a - lim[1] = b +function getZero(d) { + var result = new Array(d) + for(var i=0; i=0; --i) { + f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i] + } + return f + } + return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1 +} + +function cubicHermite(p0, v0, p1, v1, t, f) { + var ti = (t-1), t2 = t*t, ti2 = ti*ti, + h00 = (1+2*t)*ti2, + h10 = t*ti2, + h01 = t2*(3-2*t), + h11 = t2*ti + if(p0.length) { + if(!f) { + f = new Array(p0.length) + } + for(var i=p0.length-1; i>=0; --i) { + f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i] + } + return f + } + return h00*p0 + h10*v0 + h01*p1 + h11*v1 +} + +module.exports = cubicHermite +module.exports.derivative = dcubicHermite +},{}],23:[function(require,module,exports){ module.exports = cross; /** @@ -683,7 +817,7 @@ function cross(out, a, b) { out[2] = ax * by - ay * bx return out } -},{}],23:[function(require,module,exports){ +},{}],24:[function(require,module,exports){ module.exports = dot; /** @@ -696,7 +830,7 @@ module.exports = dot; function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] } -},{}],24:[function(require,module,exports){ +},{}],25:[function(require,module,exports){ module.exports = length; /** @@ -711,7 +845,7 @@ function length(a) { z = a[2] return Math.sqrt(x*x + y*y + z*z) } -},{}],25:[function(require,module,exports){ +},{}],26:[function(require,module,exports){ module.exports = lerp; /** @@ -732,7 +866,7 @@ function lerp(out, a, b, t) { out[2] = az + t * (b[2] - az) return out } -},{}],26:[function(require,module,exports){ +},{}],27:[function(require,module,exports){ module.exports = normalize; /** @@ -756,60 +890,261 @@ function normalize(out, a) { } return out } -},{}],27:[function(require,module,exports){ -var lerp = require('gl-vec3/lerp') - -var recompose = require('mat4-recompose') -var decompose = require('mat4-decompose') -var determinant = require('gl-mat4/determinant') -var slerp = require('quat-slerp') - -var state0 = state() -var state1 = state() -var tmp = state() - -module.exports = interpolate -function interpolate(out, start, end, alpha) { - if (determinant(start) === 0 || determinant(end) === 0) - return false - - //decompose the start and end matrices into individual components - var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) - var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) - if (!r0 || !r1) - return false +},{}],28:[function(require,module,exports){ +'use strict' +var bsearch = require('binary-search-bounds') +var m4interp = require('mat4-interpolate') +var invert44 = require('gl-mat4/invert') +var rotateX = require('gl-mat4/rotateX') +var rotateY = require('gl-mat4/rotateY') +var rotateZ = require('gl-mat4/rotateZ') +var lookAt = require('gl-mat4/lookAt') +var translate = require('gl-mat4/translate') +var scale = require('gl-mat4/scale') +var normalize = require('gl-vec3/normalize') - //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) - lerp(tmp.translate, state0.translate, state1.translate, alpha) - lerp(tmp.skew, state0.skew, state1.skew, alpha) - lerp(tmp.scale, state0.scale, state1.scale, alpha) - lerp(tmp.perspective, state0.perspective, state1.perspective, alpha) - slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha) +var DEFAULT_CENTER = [0,0,0] - //and recompose into our 'out' matrix - recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion) - return true -} +module.exports = createMatrixCameraController -function state() { - return { - translate: vec3(), - scale: vec3(1), - skew: vec3(), - perspective: vec4(), - quaternion: vec4() - } +function MatrixCameraController(initialMatrix) { + this._components = initialMatrix.slice() + this._time = [0] + this.prevMatrix = initialMatrix.slice() + this.nextMatrix = initialMatrix.slice() + this.computedMatrix = initialMatrix.slice() + this.computedInverse = initialMatrix.slice() + this.computedEye = [0,0,0] + this.computedUp = [0,0,0] + this.computedCenter = [0,0,0] + this.computedRadius = [0] + this._limits = [-Infinity, Infinity] } -function vec3(n) { - return [n||0,n||0,n||0] -} +var proto = MatrixCameraController.prototype -function vec4() { - return [0,0,0,1] -} -},{"gl-mat4/determinant":236,"gl-vec3/lerp":25,"mat4-decompose":28,"mat4-recompose":30,"quat-slerp":31}],28:[function(require,module,exports){ +proto.recalcMatrix = function(t) { + var time = this._time + var tidx = bsearch.le(time, t) + var mat = this.computedMatrix + if(tidx < 0) { + return + } + var comps = this._components + if(tidx === time.length-1) { + var ptr = 16*tidx + for(var i=0; i<16; ++i) { + mat[i] = comps[ptr++] + } + } else { + var dt = (time[tidx+1] - time[tidx]) + var ptr = 16*tidx + var prev = this.prevMatrix + var allEqual = true + for(var i=0; i<16; ++i) { + prev[i] = comps[ptr++] + } + var next = this.nextMatrix + for(var i=0; i<16; ++i) { + next[i] = comps[ptr++] + allEqual = allEqual && (prev[i] === next[i]) + } + if(dt < 1e-6 || allEqual) { + for(var i=0; i<16; ++i) { + mat[i] = prev[i] + } + } else { + m4interp(mat, prev, next, (t - time[tidx])/dt) + } + } + + var up = this.computedUp + up[0] = mat[1] + up[1] = mat[5] + up[2] = mat[6] + normalize(up, up) + + var imat = this.computedInverse + invert44(imat, mat) + var eye = this.computedEye + var w = imat[15] + eye[0] = imat[12]/w + eye[1] = imat[13]/w + eye[2] = imat[14]/w + + var center = this.computedCenter + var radius = Math.exp(this.computedRadius[0]) + for(var i=0; i<3; ++i) { + center[i] = eye[i] - mat[2+4*i] * radius + } +} + +proto.idle = function(t) { + if(t < this.lastT()) { + return + } + var mc = this._components + var ptr = mc.length-16 + for(var i=0; i<16; ++i) { + mc.push(mc[ptr++]) + } + this._time.push(t) +} + +proto.flush = function(t) { + var idx = bsearch.gt(this._time, t) - 2 + if(idx < 0) { + return + } + this._time.slice(0, idx) + this._components.slice(0, 16*idx) +} + +proto.lastT = function() { + return this._time[this._time.length-1] +} + +proto.lookAt = function(t, eye, center, up) { + this.recalcMatrix(t) + eye = eye || this.computedEye + center = center || DEFAULT_CENTER + up = up || this.computedUp + this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up)) + var d2 = 0.0 + for(var i=0; i<3; ++i) { + d2 += Math.pow(center[i] - eye[i], 2) + } + d2 = Math.log(Math.sqrt(d2)) + this.computedRadius[0] = d2 +} + +proto.rotate = function(t, yaw, pitch, roll) { + this.recalcMatrix(t) + var mat = this.computedInverse + if(yaw) rotateY(mat, mat, yaw) + if(pitch) rotateX(mat, mat, pitch) + if(roll) rotateZ(mat, mat, roll) + this.setMatrix(t, invert44(this.computedMatrix, mat)) +} + +var tvec = [0,0,0] + +proto.pan = function(t, dx, dy, dz) { + tvec[0] = -(dx || 0.0) + tvec[1] = -(dy || 0.0) + tvec[2] = -(dz || 0.0) + this.recalcMatrix(t) + var mat = this.computedInverse + translate(mat, mat, tvec) + this.setMatrix(t, invert44(mat, mat)) +} + +proto.translate = function(t, dx, dy, dz) { + tvec[0] = dx || 0.0 + tvec[1] = dy || 0.0 + tvec[2] = dz || 0.0 + this.recalcMatrix(t) + var mat = this.computedMatrix + translate(mat, mat, tvec) + this.setMatrix(t, mat) +} + +proto.setMatrix = function(t, mat) { + if(t < this.lastT()) { + return + } + this._time.push(t) + for(var i=0; i<16; ++i) { + this._components.push(mat[i]) + } +} + +proto.setDistance = function(t, d) { + this.computedRadius[0] = d +} + +proto.setDistanceLimits = function(a,b) { + var lim = this._limits + lim[0] = a + lim[1] = b +} + +proto.getDistanceLimits = function(out) { + var lim = this._limits + if(out) { + out[0] = lim[0] + out[1] = lim[1] + return out + } + return lim +} + +function createMatrixCameraController(options) { + options = options || {} + var matrix = options.matrix || + [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] + return new MatrixCameraController(matrix) +} +},{"binary-search-bounds":29,"gl-mat4/invert":137,"gl-mat4/lookAt":138,"gl-mat4/rotateX":142,"gl-mat4/rotateY":143,"gl-mat4/rotateZ":144,"gl-mat4/scale":145,"gl-mat4/translate":146,"gl-vec3/normalize":27,"mat4-interpolate":30}],29:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],30:[function(require,module,exports){ +var lerp = require('gl-vec3/lerp') + +var recompose = require('mat4-recompose') +var decompose = require('mat4-decompose') +var determinant = require('gl-mat4/determinant') +var slerp = require('quat-slerp') + +var state0 = state() +var state1 = state() +var tmp = state() + +module.exports = interpolate +function interpolate(out, start, end, alpha) { + if (determinant(start) === 0 || determinant(end) === 0) + return false + + //decompose the start and end matrices into individual components + var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion) + var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion) + if (!r0 || !r1) + return false + + + //now lerp/slerp the start and end components into a temporary lerp(tmptranslate, state0.translate, state1.translate, alpha) + lerp(tmp.translate, state0.translate, state1.translate, alpha) + lerp(tmp.skew, state0.skew, state1.skew, alpha) + lerp(tmp.scale, state0.scale, state1.scale, alpha) + lerp(tmp.perspective, state0.perspective, state1.perspective, alpha) + slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha) + + //and recompose into our 'out' matrix + recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion) + return true +} + +function state() { + return { + translate: vec3(), + scale: vec3(1), + skew: vec3(), + perspective: vec4(), + quaternion: vec4() + } +} + +function vec3(n) { + return [n||0,n||0,n||0] +} + +function vec4() { + return [0,0,0,1] +} +},{"gl-mat4/determinant":133,"gl-vec3/lerp":26,"mat4-decompose":31,"mat4-recompose":33,"quat-slerp":34}],31:[function(require,module,exports){ /*jshint unused:true*/ /* Input: matrix ; a 4x4 matrix @@ -989,7 +1324,7 @@ function combine(out, a, b, scale1, scale2) { out[1] = a[1] * scale1 + b[1] * scale2 out[2] = a[2] * scale1 + b[2] * scale2 } -},{"./normalize":29,"gl-mat4/clone":234,"gl-mat4/create":235,"gl-mat4/determinant":236,"gl-mat4/invert":240,"gl-mat4/transpose":250,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],29:[function(require,module,exports){ +},{"./normalize":32,"gl-mat4/clone":131,"gl-mat4/create":132,"gl-mat4/determinant":133,"gl-mat4/invert":137,"gl-mat4/transpose":147,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/length":25,"gl-vec3/normalize":27}],32:[function(require,module,exports){ module.exports = function normalize(out, mat) { var m44 = mat[15] // Cannot normalize. @@ -1000,7 +1335,7 @@ module.exports = function normalize(out, mat) { out[i] = mat[i] * scale return true } -},{}],30:[function(require,module,exports){ +},{}],33:[function(require,module,exports){ /* Input: translation ; a 3 component vector scale ; a 3 component vector @@ -1061,9 +1396,9 @@ module.exports = function recomposeMat4(matrix, translation, scale, skew, perspe mat4.scale(matrix, matrix, scale) return matrix } -},{"gl-mat4/create":235,"gl-mat4/fromRotationTranslation":238,"gl-mat4/identity":239,"gl-mat4/multiply":242,"gl-mat4/scale":248,"gl-mat4/translate":249}],31:[function(require,module,exports){ +},{"gl-mat4/create":132,"gl-mat4/fromRotationTranslation":135,"gl-mat4/identity":136,"gl-mat4/multiply":139,"gl-mat4/scale":145,"gl-mat4/translate":146}],34:[function(require,module,exports){ module.exports = require('gl-quat/slerp') -},{"gl-quat/slerp":32}],32:[function(require,module,exports){ +},{"gl-quat/slerp":35}],35:[function(require,module,exports){ module.exports = slerp /** @@ -1116,7 +1451,7 @@ function slerp (out, a, b, t) { return out } -},{}],33:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ 'use strict' module.exports = quatFromFrame @@ -1158,455 +1493,120 @@ function quatFromFrame( } return out } -},{}],34:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ 'use strict' -module.exports = createFilteredVector - -var cubicHermite = require('cubic-hermite') -var bsearch = require('binary-search-bounds') +module.exports = createOrbitController -function clamp(lo, hi, x) { - return Math.min(hi, Math.max(lo, x)) -} +var filterVector = require('filtered-vector') +var lookAt = require('gl-mat4/lookAt') +var mat4FromQuat = require('gl-mat4/fromQuat') +var invert44 = require('gl-mat4/invert') +var quatFromFrame = require('./lib/quatFromFrame') -function FilteredVector(state0, velocity0, t0) { - this.dimension = state0.length - this.bounds = [ new Array(this.dimension), new Array(this.dimension) ] - for(var i=0; i= n-1) { - var ptr = state.length-1 - var tf = t - time[n-1] - for(var i=0; i 1e-6) { + out[0] = ax/al + out[1] = ay/al + out[2] = az/al + out[3] = aw/al } else { - var ptr = d * (idx+1) - 1 - var t0 = time[idx] - var t1 = time[idx+1] - var dt = (t1 - t0) || 1.0 - var x0 = this._scratch[1] - var x1 = this._scratch[2] - var v0 = this._scratch[3] - var v1 = this._scratch[4] - var steady = true - for(var i=0; i= n-1) { - var ptr = state.length-1 - var tf = t - time[n-1] - for(var i=0; i=0; --i) { - if(velocity[--ptr]) { - return false +proto.recalcMatrix = function(t) { + this.radius.curve(t) + this.center.curve(t) + this.rotation.curve(t) + + var quat = this.computedRotation + normalize4(quat, quat) + + var mat = this.computedMatrix + mat4FromQuat(mat, quat) + + var center = this.computedCenter + var eye = this.computedEye + var up = this.computedUp + var radius = Math.exp(this.computedRadius[0]) + + eye[0] = center[0] + radius * mat[2] + eye[1] = center[1] + radius * mat[6] + eye[2] = center[2] + radius * mat[10] + up[0] = mat[1] + up[1] = mat[5] + up[2] = mat[9] + + for(var i=0; i<3; ++i) { + var rr = 0.0 + for(var j=0; j<3; ++j) { + rr += mat[i+4*j] * eye[j] } + mat[12+i] = -rr } - return true } -proto.jump = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t < t0 || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var ptr = state.length-this.dimension - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - this._time.push(t0, t) - for(var j=0; j<2; ++j) { - for(var i=0; i0; --i) { - state.push(clamp(lo[i-1], hi[i-1], arguments[i])) - velocity.push(0) - } + return m } -proto.push = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t < t0 || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var ptr = state.length-this.dimension - var dt = t - t0 - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var sf = (dt > 1e-6) ? 1/dt : 0 - this._time.push(t) - for(var i=d; i>0; --i) { - var xc = clamp(lo[i-1], hi[i-1], arguments[i]) - state.push(xc) - velocity.push((xc - state[ptr++]) * sf) - } +proto.idle = function(t) { + this.center.idle(t) + this.radius.idle(t) + this.rotation.idle(t) } -proto.set = function(t) { - var d = this.dimension - if(t < this.lastT() || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - this._time.push(t) - for(var i=d; i>0; --i) { - state.push(clamp(lo[i-1], hi[i-1], arguments[i])) - velocity.push(0) - } -} - -proto.move = function(t) { - var t0 = this.lastT() - var d = this.dimension - if(t <= t0 || arguments.length !== d+1) { - return - } - var state = this._state - var velocity = this._velocity - var statePtr = state.length - this.dimension - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var dt = t - t0 - var sf = (dt > 1e-6) ? 1/dt : 0.0 - this._time.push(t) - for(var i=d; i>0; --i) { - var dx = arguments[i] - state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx)) - velocity.push(dx * sf) - } -} - -proto.idle = function(t) { - var t0 = this.lastT() - if(t < t0) { - return - } - var d = this.dimension - var state = this._state - var velocity = this._velocity - var statePtr = state.length-d - var bounds = this.bounds - var lo = bounds[0] - var hi = bounds[1] - var dt = t - t0 - this._time.push(t) - for(var i=d-1; i>=0; --i) { - state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr])) - velocity.push(0) - statePtr += 1 - } -} - -function getZero(d) { - var result = new Array(d) - for(var i=0; i=0; --i) { - f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i] - } - return f - } - return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1 -} - -function cubicHermite(p0, v0, p1, v1, t, f) { - var ti = (t-1), t2 = t*t, ti2 = ti*ti, - h00 = (1+2*t)*ti2, - h10 = t*ti2, - h01 = t2*(3-2*t), - h11 = t2*ti - if(p0.length) { - if(!f) { - f = new Array(p0.length) - } - for(var i=p0.length-1; i>=0; --i) { - f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i] - } - return f - } - return h00*p0 + h10*v0 + h01*p1 + h11*v1 -} - -module.exports = cubicHermite -module.exports.derivative = dcubicHermite -},{}],37:[function(require,module,exports){ -'use strict' - -module.exports = createOrbitController - -var filterVector = require('filtered-vector') -var lookAt = require('gl-mat4/lookAt') -var mat4FromQuat = require('gl-mat4/fromQuat') -var invert44 = require('gl-mat4/invert') -var quatFromFrame = require('./lib/quatFromFrame') - -function len3(x,y,z) { - return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) -} - -function len4(w,x,y,z) { - return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2)) -} - -function normalize4(out, a) { - var ax = a[0] - var ay = a[1] - var az = a[2] - var aw = a[3] - var al = len4(ax, ay, az, aw) - if(al > 1e-6) { - out[0] = ax/al - out[1] = ay/al - out[2] = az/al - out[3] = aw/al - } else { - out[0] = out[1] = out[2] = 0.0 - out[3] = 1.0 - } -} - -function OrbitCameraController(initQuat, initCenter, initRadius) { - this.radius = filterVector([initRadius]) - this.center = filterVector(initCenter) - this.rotation = filterVector(initQuat) - - this.computedRadius = this.radius.curve(0) - this.computedCenter = this.center.curve(0) - this.computedRotation = this.rotation.curve(0) - this.computedUp = [0.1,0,0] - this.computedEye = [0.1,0,0] - this.computedMatrix = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] - - this.recalcMatrix(0) -} - -var proto = OrbitCameraController.prototype - -proto.lastT = function() { - return Math.max( - this.radius.lastT(), - this.center.lastT(), - this.rotation.lastT()) -} - -proto.recalcMatrix = function(t) { - this.radius.curve(t) - this.center.curve(t) - this.rotation.curve(t) - - var quat = this.computedRotation - normalize4(quat, quat) - - var mat = this.computedMatrix - mat4FromQuat(mat, quat) - - var center = this.computedCenter - var eye = this.computedEye - var up = this.computedUp - var radius = Math.exp(this.computedRadius[0]) - - eye[0] = center[0] + radius * mat[2] - eye[1] = center[1] + radius * mat[6] - eye[2] = center[2] + radius * mat[10] - up[0] = mat[1] - up[1] = mat[5] - up[2] = mat[9] - - for(var i=0; i<3; ++i) { - var rr = 0.0 - for(var j=0; j<3; ++j) { - rr += mat[i+4*j] * eye[j] - } - mat[12+i] = -rr - } -} - -proto.getMatrix = function(t, result) { - this.recalcMatrix(t) - var m = this.computedMatrix - if(result) { - for(var i=0; i<16; ++i) { - result[i] = m[i] - } - return result - } - return m -} - -proto.idle = function(t) { - this.center.idle(t) - this.radius.idle(t) - this.rotation.idle(t) -} - -proto.flush = function(t) { - this.center.flush(t) - this.radius.flush(t) - this.rotation.flush(t) +proto.flush = function(t) { + this.center.flush(t) + this.radius.flush(t) + this.rotation.flush(t) } proto.pan = function(t, dx, dy, dz) { @@ -1887,19 +1887,7 @@ function createOrbitController(options) { return result } -},{"./lib/quatFromFrame":33,"filtered-vector":34,"gl-mat4/fromQuat":237,"gl-mat4/invert":240,"gl-mat4/lookAt":241}],38:[function(require,module,exports){ -arguments[4][34][0].apply(exports,arguments) -},{"binary-search-bounds":39,"cubic-hermite":40,"dup":34}],39:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],40:[function(require,module,exports){ -arguments[4][36][0].apply(exports,arguments) -},{"dup":36}],41:[function(require,module,exports){ -arguments[4][22][0].apply(exports,arguments) -},{"dup":22}],42:[function(require,module,exports){ -arguments[4][23][0].apply(exports,arguments) -},{"dup":23}],43:[function(require,module,exports){ -arguments[4][26][0].apply(exports,arguments) -},{"dup":26}],44:[function(require,module,exports){ +},{"./lib/quatFromFrame":36,"filtered-vector":20,"gl-mat4/fromQuat":134,"gl-mat4/invert":137,"gl-mat4/lookAt":138}],38:[function(require,module,exports){ 'use strict' module.exports = createTurntableController @@ -2472,7 +2460,7 @@ function createTurntableController(options) { theta, phi) } -},{"filtered-vector":38,"gl-mat4/invert":240,"gl-mat4/rotate":244,"gl-vec3/cross":41,"gl-vec3/dot":42,"gl-vec3/normalize":43}],45:[function(require,module,exports){ +},{"filtered-vector":20,"gl-mat4/invert":137,"gl-mat4/rotate":141,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/normalize":27}],39:[function(require,module,exports){ 'use strict' module.exports = createViewController @@ -2595,7 +2583,7 @@ function createViewController(options) { matrix: matrix }, mode) } -},{"matrix-camera-controller":20,"orbit-camera-controller":37,"turntable-camera-controller":44}],46:[function(require,module,exports){ +},{"matrix-camera-controller":28,"orbit-camera-controller":37,"turntable-camera-controller":38}],40:[function(require,module,exports){ module.exports = alphaShape var ac = require('alpha-complex') @@ -2604,7 +2592,7 @@ var bnd = require('simplicial-complex-boundary') function alphaShape(alpha, points) { return bnd(ac(alpha, points)) } -},{"alpha-complex":47,"simplicial-complex-boundary":58}],47:[function(require,module,exports){ +},{"alpha-complex":41,"simplicial-complex-boundary":44}],41:[function(require,module,exports){ 'use strict' module.exports = alphaComplex @@ -2621,7 +2609,7 @@ function alphaComplex(alpha, points) { return circumradius(simplex) * alpha < 1 }) } -},{"circumradius":48,"delaunay-triangulate":88}],48:[function(require,module,exports){ +},{"circumradius":42,"delaunay-triangulate":114}],42:[function(require,module,exports){ module.exports = circumradius var circumcenter = require('circumcenter') @@ -2637,7 +2625,7 @@ function circumradius(points) { } return Math.sqrt(avgDist / points.length) } -},{"circumcenter":49}],49:[function(require,module,exports){ +},{"circumcenter":43}],43:[function(require,module,exports){ "use strict" var dup = require("dup") @@ -2706,885 +2694,504 @@ function circumcenter(points) { circumcenter.barycenetric = barycentricCircumcenter module.exports = circumcenter -},{"dup":50,"robust-linear-solve":51}],50:[function(require,module,exports){ +},{"dup":115,"robust-linear-solve":256}],44:[function(require,module,exports){ +'use strict' + +module.exports = boundary + +var bnd = require('boundary-cells') +var reduce = require('reduce-simplicial-complex') + +function boundary(cells) { + return reduce(bnd(cells)) +} + +},{"boundary-cells":45,"reduce-simplicial-complex":48}],45:[function(require,module,exports){ "use strict" -function dupe_array(count, value, i) { - var c = count[i]|0 - if(c <= 0) { - return [] +module.exports = boundary + +function boundary(cells) { + var n = cells.length + var sz = 0 + for(var i=0; i 0) { - return dupe_number(count|0, value) - } - break - case "object": - if(typeof (count.length) === "number") { - return dupe_array(count, value, 0) +module.exports = orientation + +function orientation(s) { + var p = 1 + for(var i=1; i 0) { - code.push(",") - } - code.push("[") - for(var k=0; k 0) { - code.push(",") - } - if(k === i) { - code.push("+b[", j, "]") - } else { - code.push("+A[", j, "][", k, "]") - } + var c = cells[i] + var o = orientation(c) + if(o === 0) { + continue + } + if(ptr > 0) { + var f = cells[ptr-1] + if(compareCell(c, f) === 0 && + orientation(f) !== o) { + ptr -= 1 + continue } - code.push("]") } - code.push("]),") - } - code.push("det(A)]}return ", funcName) - var proc = new Function("det", code.join("")) - if(n < 6) { - return proc(determinant[n]) + cells[ptr++] = c } - return proc(determinant) + cells.length = ptr + return cells } -function robustLinearSolve0d() { - return [ 0 ] -} +},{"cell-orientation":46,"compare-cell":101,"compare-oriented-cell":47}],49:[function(require,module,exports){ +'use strict'; -function robustLinearSolve1d(A, b) { - return [ [ b[0] ], [ A[0][0] ] ] -} +var arraytools = function () { -var CACHE = [ - robustLinearSolve0d, - robustLinearSolve1d -] + var that = {}; -function generateDispatch() { - while(CACHE.length < NUM_EXPAND) { - CACHE.push(generateSolver(CACHE.length)) - } - var procArgs = [] - var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] - for(var i=0; i=0; --i) { - var a = Q - var b = e[i] - Q = a + b - var bv = Q - a - var q = b - bv - if(q) { - e[--bottom] = Q - Q = q + function sum (A) { + var acc = 0; + accumulate(A, acc); + function accumulate(x) { + for (var i = 0; i < x.length; i++) { + if (Array.isArray(x[i])) + accumulate(x[i], acc); + else + acc += x[i]; + } } + return acc; } - var top = 0 - for(var i=bottom; i1 or 0->255 rgb array + var rgb, + match; -function linearExpansionSum(e, f) { - var ne = e.length|0 - var nf = f.length|0 - if(ne === 1 && nf === 1) { - return scalarScalar(e[0], f[0]) - } - var n = ne + nf - var g = new Array(n) - var count = 0 - var eptr = 0 - var fptr = 0 - var abs = Math.abs - var ei = e[eptr] - var ea = abs(ei) - var fi = f[fptr] - var fa = abs(fi) - var a, b - if(ea < fa) { - b = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - b = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } - } - if((eptr < ne && ea < fa) || (fptr >= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) + if (typeof str !== 'string') return str; + + rgb = []; + // hex notation + if (str[0] === '#') { + str = str.substr(1) // remove hash + if (str.length === 3) str += str // fff -> ffffff + match = parseInt(str, 16); + rgb[0] = ((match >> 16) & 255); + rgb[1] = ((match >> 8) & 255); + rgb[2] = (match & 255); } - } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = f[fptr] - fa = abs(fi) - } + + // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation + else if (RGB_REGEX.test(str)) { + match = str.match(RGB_GROUP_REGEX); + rgb[0] = parseInt(match[1]); + rgb[1] = parseInt(match[2]); + rgb[2] = parseInt(match[3]); } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + + if (!twoFiftySix) { + for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x + + + return rgb; } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y + + + function str2RgbaArray(str, twoFiftySix) { + // convert hex or rbg strings to 0->1 or 0->255 rgb array + var rgb, + match; + + if (typeof str !== 'string') return str; + + rgb = []; + // hex notation + if (str[0] === '#') { + str = str.substr(1) // remove hash + if (str.length === 3) str += str // fff -> ffffff + match = parseInt(str, 16); + rgb[0] = ((match >> 16) & 255); + rgb[1] = ((match >> 8) & 255); + rgb[2] = (match & 255); } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] + + // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation + else if (RGB_REGEX.test(str)) { + match = str.match(RGB_GROUP_REGEX); + rgb[0] = parseInt(match[1]); + rgb[1] = parseInt(match[2]); + rgb[2] = parseInt(match[3]); + if (match[4]) rgb[3] = parseFloat(match[4]); + else rgb[3] = 1.0; } - } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = f[fptr] + + + + if (!twoFiftySix) { + for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 } - } - if(q0) { - g[count++] = q0 - } - if(q1) { - g[count++] = q1 - } - if(!count) { - g[count++] = 0.0 - } - g.length = count - return g -} -},{}],56:[function(require,module,exports){ -"use strict" -module.exports = twoProduct -var SPLITTER = +(Math.pow(2, 27) + 1.0) + return rgb; + } -function twoProduct(a, b, result) { - var x = a * b - var c = SPLITTER * a - var abig = c - a - var ahi = c - abig - var alo = a - ahi - var d = SPLITTER * b - var bbig = d - b - var bhi = d - bbig - var blo = b - bhi - var err1 = x - (ahi * bhi) - var err2 = err1 - (alo * bhi) - var err3 = err2 - (ahi * blo) - var y = alo * blo - err3 + that.isPlainObject = isPlainObject; + that.linspace = linspace; + that.zip3 = zip3; + that.sum = sum; + that.zip = zip; + that.isEqual = isEqual; + that.copy2D = copy2D; + that.copy1D = copy1D; + that.str2RgbArray = str2RgbArray; + that.str2RgbaArray = str2RgbaArray; - if(result) { - result[0] = y - result[1] = x - return result - } + return that - return [ y, x ] } -},{}],57:[function(require,module,exports){ -"use strict" -var twoProduct = require("two-product") -var robustSum = require("robust-sum") -var robustScale = require("robust-scale") -var compress = require("robust-compress") -var NUM_EXPANDED = 6 +module.exports = arraytools(); -function cofactor(m, c) { - var result = new Array(m.length-1) - for(var i=1; i 0) - (v < 0); } -function sign(n) { - if(n & 1) { - return "-" - } - return "" +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; } -function generateSum(expr) { - if(expr.length === 1) { - return expr[0] - } else if(expr.length === 2) { - return ["sum(", expr[0], ",", expr[1], ")"].join("") - } else { - var m = expr.length>>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); } -function determinant(m) { - if(m.length === 2) { - return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") - } else { - var expr = [] - for(var i=0; i 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} -function generateDispatch() { - while(CACHE.length < NUM_EXPANDED) { - CACHE.push(compileDeterminant(CACHE.length)) - } - var procArgs = [] - var code = ["function robustDeterminant(m){switch(m.length){"] - for(var i=0; i= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; } -generateDispatch() -},{"robust-compress":52,"robust-scale":54,"robust-sum":55,"two-product":56}],58:[function(require,module,exports){ -'use strict' +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} -module.exports = boundary +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; -var bnd = require('boundary-cells') -var reduce = require('reduce-simplicial-complex') +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} -function boundary(cells) { - return reduce(bnd(cells)) +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); } -},{"boundary-cells":59,"reduce-simplicial-complex":63}],59:[function(require,module,exports){ -'use strict' +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} -module.exports = boundary +var REVERSE_TABLE = new Array(256); -function boundary (cells) { - var i, j, k - var n = cells.length - var sz = 0 - for (i = 0; i < n; ++i) { - sz += cells[i].length - } - var result = new Array(sz) - var ptr = 0 - for (i = 0; i < n; ++i) { - var c = cells[i] - var d = c.length - for (j = 0; j < d; ++j) { - var b = result[ptr++] = new Array(d - 1) - var p = 0 - for (k = 0; k < d; ++k) { - if (k === j) { - continue - } - b[p++] = c[k] - } - if (j & 1) { - var tmp = b[1] - b[1] = b[0] - b[0] = tmp - } +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; } + tab[i] = (r << s) & 0xff; } - return result +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; } -},{}],60:[function(require,module,exports){ -'use strict' +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; -module.exports = orientation + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; -function orientation(s) { - var p = 1 - for(var i=1; i>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; } -},{}],62:[function(require,module,exports){ -'use strict' - -var compareCells = require('compare-cell') -var parity = require('cell-orientation') -module.exports = compareOrientedCells +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; -function compareOrientedCells(a, b) { - return compareCells(a, b) || parity(a) - parity(b) + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); } -},{"cell-orientation":60,"compare-cell":61}],63:[function(require,module,exports){ -'use strict' - -var compareCell = require('compare-cell') -var compareOrientedCell = require('compare-oriented-cell') -var orientation = require('cell-orientation') - -module.exports = reduceCellComplex - -function reduceCellComplex(cells) { - cells.sort(compareOrientedCell) - var n = cells.length - var ptr = 0 - for(var i=0; i 0) { - var f = cells[ptr-1] - if(compareCell(c, f) === 0 && - orientation(f) !== o) { - ptr -= 1 - continue - } - } - cells[ptr++] = c - } - cells.length = ptr - return cells +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; } -},{"cell-orientation":60,"compare-cell":61,"compare-oriented-cell":62}],64:[function(require,module,exports){ -'use strict'; - -var arraytools = function () { - - var that = {}; - - var RGB_REGEX = /^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/; - var RGB_GROUP_REGEX = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/; - - function isPlainObject (v) { - return !Array.isArray(v) && v !== null && typeof v === 'object'; - } - - function linspace (start, end, num) { - var inc = (end - start) / Math.max(num - 1, 1); - var a = []; - for( var ii = 0; ii < num; ii++) - a.push(start + ii*inc); - return a; - } - - function zip () { - var arrays = [].slice.call(arguments); - var lengths = arrays.map(function (a) {return a.length;}); - var len = Math.min.apply(null, lengths); - var zipped = []; - for (var i = 0; i < len; i++) { - zipped[i] = []; - for (var j = 0; j < arrays.length; ++j) { - zipped[i][j] = arrays[j][i]; - } - } - return zipped; - } - - function zip3 (a, b, c) { - var len = Math.min.apply(null, [a.length, b.length, c.length]); - var result = []; - for (var n = 0; n < len; n++) { - result.push([a[n], b[n], c[n]]); - } - return result; - } - - function sum (A) { - var acc = 0; - accumulate(A, acc); - function accumulate(x) { - for (var i = 0; i < x.length; i++) { - if (Array.isArray(x[i])) - accumulate(x[i], acc); - else - acc += x[i]; - } - } - return acc; - } - - function copy2D (arr) { - var carr = []; - for (var i = 0; i < arr.length; ++i) { - carr[i] = []; - for (var j = 0; j < arr[i].length; ++j) { - carr[i][j] = arr[i][j]; - } - } - - return carr; - } - - - function copy1D (arr) { - var carr = []; - for (var i = 0; i < arr.length; ++i) { - carr[i] = arr[i]; - } - - return carr; - } - - - function isEqual(arr1, arr2) { - if(arr1.length !== arr2.length) - return false; - for(var i = arr1.length; i--;) { - if(arr1[i] !== arr2[i]) - return false; - } - - return true; - } - - - function str2RgbArray(str, twoFiftySix) { - // convert hex or rbg strings to 0->1 or 0->255 rgb array - var rgb, - match; - - if (typeof str !== 'string') return str; - - rgb = []; - // hex notation - if (str[0] === '#') { - str = str.substr(1) // remove hash - if (str.length === 3) str += str // fff -> ffffff - match = parseInt(str, 16); - rgb[0] = ((match >> 16) & 255); - rgb[1] = ((match >> 8) & 255); - rgb[2] = (match & 255); - } - - // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation - else if (RGB_REGEX.test(str)) { - match = str.match(RGB_GROUP_REGEX); - rgb[0] = parseInt(match[1]); - rgb[1] = parseInt(match[2]); - rgb[2] = parseInt(match[3]); - } - - if (!twoFiftySix) { - for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 - } - - - return rgb; - } - - - function str2RgbaArray(str, twoFiftySix) { - // convert hex or rbg strings to 0->1 or 0->255 rgb array - var rgb, - match; - - if (typeof str !== 'string') return str; - - rgb = []; - // hex notation - if (str[0] === '#') { - str = str.substr(1) // remove hash - if (str.length === 3) str += str // fff -> ffffff - match = parseInt(str, 16); - rgb[0] = ((match >> 16) & 255); - rgb[1] = ((match >> 8) & 255); - rgb[2] = (match & 255); - } - - // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation - else if (RGB_REGEX.test(str)) { - match = str.match(RGB_GROUP_REGEX); - rgb[0] = parseInt(match[1]); - rgb[1] = parseInt(match[2]); - rgb[2] = parseInt(match[3]); - if (match[4]) rgb[3] = parseFloat(match[4]); - else rgb[3] = 1.0; - } - - - - if (!twoFiftySix) { - for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255 - } - - - return rgb; - } - - - - - - that.isPlainObject = isPlainObject; - that.linspace = linspace; - that.zip3 = zip3; - that.sum = sum; - that.zip = zip; - that.isEqual = isEqual; - that.copy2D = copy2D; - that.copy1D = copy1D; - that.str2RgbArray = str2RgbArray; - that.str2RgbaArray = str2RgbaArray; - - return that - +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); } -module.exports = arraytools(); - -},{}],65:[function(require,module,exports){ +},{}],51:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. @@ -3603,6 +3210,9 @@ var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: @@ -3632,11 +3242,6 @@ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() -/* - * Export kMaxLength after typed array support is determined. - */ -exports.kMaxLength = kMaxLength() - function typedArraySupport () { try { var arr = new Uint8Array(1) @@ -3655,25 +3260,6 @@ function kMaxLength () { : 0x3fffffff } -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that -} - /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of @@ -3683,25 +3269,31 @@ function createBuffer (that, length) { * * The `Uint8Array` prototype remains unmodified. */ +function Buffer (arg) { + if (!(this instanceof Buffer)) { + // Avoid going through an ArgumentsAdaptorTrampoline in the common case. + if (arguments.length > 1) return new Buffer(arg, arguments[1]) + return new Buffer(arg) + } -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + this.length = 0 + this.parent = undefined } // Common case. if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) + return fromNumber(this, arg) } - return from(this, arg, encodingOrOffset, length) -} -Buffer.poolSize = 8192 // not used by this implementation + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + } + + // Unusual. + return fromObject(this, arg) +} // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { @@ -3709,182 +3301,151 @@ Buffer._augment = function (arr) { return arr } -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') +function fromNumber (that, length) { + that = allocate(that, length < 0 ? 0 : checked(length) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < length; i++) { + that[i] = 0 + } } + return that +} - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) - return fromObject(that, value) + that.write(string, encoding) + return that } -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -} +function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } -} + if (isArray(object)) return fromArray(that, object) -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') } -} -function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) + if (typeof ArrayBuffer !== 'undefined') { + if (object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) + } + if (object instanceof ArrayBuffer) { + return fromArrayBuffer(that, object) + } } - return createBuffer(that, size) + + if (object.length) return fromArrayLike(that, object) + + return fromJsonObject(that, object) } -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) +function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that } -function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; i++) { - that[i] = 0 - } +function fromArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } return that } -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) +// Duplicate of fromArray() to keep fromArray() monomorphic. +function fromTypedArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + // Truncating the elements is probably not what people expect from typed + // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior + // of the old Buffer constructor. + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that } -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } +function fromArrayBuffer (that, array) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(array) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromTypedArray(that, new Uint8Array(array)) } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - that.write(string, encoding) return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 - that = createBuffer(that, length) + that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer +// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. +// Returns a zero-length buffer for inputs that don't conform to the spec. +function fromJsonObject (that, object) { + var array + var length = 0 - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') + if (object.type === 'Buffer' && isArray(object.data)) { + array = object.data + length = checked(array.length) | 0 } + that = allocate(that, length) - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 } + return that +} - if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) } +} else { + // pre-set for values that may exist in the future + Buffer.prototype.length = undefined + Buffer.prototype.parent = undefined +} +function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance - that = array + that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that -} - -function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that + that.length = length } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } + var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 + if (fromPool) that.parent = rootParent - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + return that } function checked (length) { @@ -3897,11 +3458,12 @@ function checked (length) { return length | 0 } -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) +function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf } Buffer.isBuffer = function isBuffer (b) { @@ -3918,12 +3480,17 @@ Buffer.compare = function compare (a, b) { var x = a.length var y = b.length - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } + var i = 0 + var len = Math.min(x, y) + while (i < len) { + if (a[i] !== b[i]) break + + ++i + } + + if (i !== len) { + x = a[i] + y = b[i] } if (x < y) return -1 @@ -3951,12 +3518,10 @@ Buffer.isEncoding = function isEncoding (encoding) { } Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { - return Buffer.alloc(0) + return new Buffer(0) } var i @@ -3967,30 +3532,18 @@ Buffer.concat = function concat (list, length) { } } - var buffer = Buffer.allocUnsafe(length) + var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length + var item = list[i] + item.copy(buf, pos) + pos += item.length } - return buffer + return buf } function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } + if (typeof string !== 'string') string = '' + string var len = string.length if (len === 0) return 0 @@ -4007,7 +3560,6 @@ function byteLength (string, encoding) { return len case 'utf8': case 'utf-8': - case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': @@ -4030,39 +3582,13 @@ Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' while (true) { switch (encoding) { @@ -4100,35 +3626,6 @@ function slowToString (encoding, start, end) { // Buffer instances. Buffer.prototype._isBuffer = true -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' @@ -4152,145 +3649,51 @@ Buffer.prototype.inspect = function inspect () { return '' } -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } +Buffer.prototype.compare = function compare (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return 0 + return Buffer.compare(this, b) +} - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } +Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 - if (thisStart >= thisEnd && start >= end) { - return 0 + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + if (val.length === 0) return -1 // special case: looking for empty string always fails + return String.prototype.indexOf.call(this, val, byteOffset) } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -function arrayIndexOf (arr, val, byteOffset, encoding) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var foundIndex = -1 - for (var i = 0; byteOffset + i < arrLength; i++) { - if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - return -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset >>= 0 - - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 - - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - if (Buffer.isBuffer(val)) { - // special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(this, val, byteOffset, encoding) + return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } - return arrayIndexOf(this, [ val ], byteOffset, encoding) + return arrayIndexOf(this, [ val ], byteOffset) } - throw new TypeError('val must be string, number or Buffer') -} + function arrayIndexOf (arr, val, byteOffset) { + var foundIndex = -1 + for (var i = 0; byteOffset + i < arr.length; i++) { + if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + } else { + foundIndex = -1 + } + } + return -1 + } -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 + throw new TypeError('val must be string, number or Buffer') } function hexWrite (buf, string, offset, length) { @@ -4314,7 +3717,7 @@ function hexWrite (buf, string, offset, length) { } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i + if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i @@ -4363,16 +3766,17 @@ Buffer.prototype.write = function write (string, offset, length, encoding) { } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) + var swap = encoding + encoding = offset + offset = length | 0 + length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') + throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' @@ -4597,6 +4001,8 @@ Buffer.prototype.slice = function slice (start, end) { } } + if (newBuf.length) newBuf.parent = this.parent || this + return newBuf } @@ -4765,19 +4171,16 @@ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { } function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 @@ -4793,10 +4196,7 @@ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, value = +value offset = offset | 0 byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 @@ -4899,12 +4299,9 @@ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, no var i = 0 var mul = 1 - var sub = 0 + var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -4922,12 +4319,9 @@ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, no var i = byteLength - 1 var mul = 1 - var sub = 0 + var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } @@ -5002,8 +4396,8 @@ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) } function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { @@ -5087,63 +4481,31 @@ Buffer.prototype.copy = function copy (target, targetStart, start, end) { return len } -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length - if (end <= start) { - return this - } + if (end < start) throw new RangeError('end < start') - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return - if (!val) val = 0 + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i - if (typeof val === 'number') { + if (typeof value === 'number') { for (i = start; i < end; i++) { - this[i] = val + this[i] = value } } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) + var bytes = utf8ToBytes(value.toString()) var len = bytes.length - for (i = 0; i < end - start; i++) { - this[i + start] = bytes[i % len] + for (i = start; i < end; i++) { + this[i] = bytes[i % len] } } @@ -5294,12 +4656,8 @@ function blitBuffer (src, dst, offset, length) { return i } -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"base64-js":66,"ieee754":67,"isarray":68}],66:[function(require,module,exports){ +},{"base64-js":52,"ieee754":53,"isarray":54}],52:[function(require,module,exports){ 'use strict' exports.toByteArray = toByteArray @@ -5310,12 +4668,17 @@ var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array function init () { + var i var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { + var len = code.length + + for (i = 0; i < len; i++) { lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i } + for (i = 0; i < len; ++i) { + revLookup[code.charCodeAt(i)] = i + } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 } @@ -5347,8 +4710,8 @@ function toByteArray (b64) { for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] - arr[L++] = (tmp >> 16) & 0xFF - arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = (tmp & 0xFF0000) >> 16 + arr[L++] = (tmp & 0xFF00) >> 8 arr[L++] = tmp & 0xFF } @@ -5410,7 +4773,7 @@ function fromByteArray (uint8) { return parts.join('') } -},{}],67:[function(require,module,exports){ +},{}],53:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 @@ -5496,14 +4859,14 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { buffer[offset + i - d] |= s * 128 } -},{}],68:[function(require,module,exports){ +},{}],54:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; -},{}],69:[function(require,module,exports){ +},{}],55:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -5803,44 +5166,16 @@ function isUndefined(arg) { return arg === void 0; } -},{}],70:[function(require,module,exports){ +},{}],56:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -(function () { - try { - cachedSetTimeout = setTimeout; - } catch (e) { - cachedSetTimeout = function () { - throw new Error('setTimeout is not defined'); - } - } - try { - cachedClearTimeout = clearTimeout; - } catch (e) { - cachedClearTimeout = function () { - throw new Error('clearTimeout is not defined'); - } - } -} ()) var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); @@ -5856,7 +5191,7 @@ function drainQueue() { if (draining) { return; } - var timeout = cachedSetTimeout(cleanUpNextTick); + var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; @@ -5873,7 +5208,7 @@ function drainQueue() { } currentQueue = null; draining = false; - cachedClearTimeout(timeout); + clearTimeout(timeout); } process.nextTick = function (fun) { @@ -5885,7 +5220,7 @@ process.nextTick = function (fun) { } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { - cachedSetTimeout(drainQueue, 0); + setTimeout(drainQueue, 0); } }; @@ -5924,46334 +5259,44982 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],71:[function(require,module,exports){ -"use strict" +},{}],57:[function(require,module,exports){ +'use strict' -var convexHull1d = require('./lib/ch1d') -var convexHull2d = require('./lib/ch2d') -var convexHullnd = require('./lib/chnd') +var monotoneTriangulate = require('./lib/monotone') +var makeIndex = require('./lib/triangulation') +var delaunayFlip = require('./lib/delaunay') +var filterTriangulation = require('./lib/filter') -module.exports = convexHull +module.exports = cdt2d -function convexHull(points) { - var n = points.length - if(n === 0) { - return [] - } else if(n === 1) { - return [[0]] +function canonicalizeEdge(e) { + return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] +} + +function compareEdge(a, b) { + return a[0]-b[0] || a[1]-b[1] +} + +function canonicalizeEdges(edges) { + return edges.map(canonicalizeEdge).sort(compareEdge) +} + +function getDefault(options, property, dflt) { + if(property in options) { + return options[property] } - var d = points[0].length - if(d === 0) { + return dflt +} + +function cdt2d(points, edges, options) { + + if(!Array.isArray(edges)) { + options = edges || {} + edges = [] + } else { + options = options || {} + edges = edges || [] + } + + //Parse out options + var delaunay = !!getDefault(options, 'delaunay', true) + var interior = !!getDefault(options, 'interior', true) + var exterior = !!getDefault(options, 'exterior', true) + var infinity = !!getDefault(options, 'infinity', false) + + //Handle trivial case + if((!interior && !exterior) || points.length === 0) { return [] - } else if(d === 1) { - return convexHull1d(points) - } else if(d === 2) { - return convexHull2d(points) } - return convexHullnd(points, d) -} -},{"./lib/ch1d":72,"./lib/ch2d":73,"./lib/chnd":74}],72:[function(require,module,exports){ -"use strict" -module.exports = convexHull1d + //Construct initial triangulation + var cells = monotoneTriangulate(points, edges) -function convexHull1d(points) { - var lo = 0 - var hi = 0 - for(var i=1; i points[hi][0]) { - hi = i + + //Run edge flipping + if(delaunay) { + delaunayFlip(points, triangulation) } - } - if(lo < hi) { - return [[lo], [hi]] - } else if(lo > hi) { - return [[hi], [lo]] + + //Filter points + if(!exterior) { + return filterTriangulation(triangulation, -1) + } else if(!interior) { + return filterTriangulation(triangulation, 1, infinity) + } else if(infinity) { + return filterTriangulation(triangulation, 0, infinity) + } else { + return triangulation.cells() + } + } else { - return [[lo]] + return cells } } -},{}],73:[function(require,module,exports){ + +},{"./lib/delaunay":58,"./lib/filter":59,"./lib/monotone":60,"./lib/triangulation":61}],58:[function(require,module,exports){ 'use strict' -module.exports = convexHull2D +var inCircle = require('robust-in-sphere')[4] +var bsearch = require('binary-search-bounds') -var monotoneHull = require('monotone-convex-hull-2d') +module.exports = delaunayRefine -function convexHull2D(points) { - var hull = monotoneHull(points) - var h = hull.length - if(h <= 2) { - return [] +function testFlip(points, triangulation, stack, a, b, x) { + var y = triangulation.opposite(a, b) + + //Test boundary edge + if(y < 0) { + return } - var edges = new Array(h) - var a = hull[h-1] - for(var i=0; i= front[k]) { - x += 1 - } + //Find opposite edge + var x = star[j-1], y = -1 + for(var k=1; k 0) { + var b = stack.pop() + var a = stack.pop() -function linearlyIndependent(points, d) { - var nhull = new Array(d+1) - for(var i=0; i= 0) { + continue } + + //Flip the edge + triangulation.flip(a, b) + + //Test flipping neighboring edges + testFlip(points, triangulation, stack, x, a, y) + testFlip(points, triangulation, stack, a, y, x) + testFlip(points, triangulation, stack, y, b, x) + testFlip(points, triangulation, stack, b, x, y) } - return index } -},{"robust-orientation":1040}],76:[function(require,module,exports){ -"use strict" - -//High level idea: -// 1. Use Clarkson's incremental construction to find convex hull -// 2. Point location in triangulation by jump and walk -module.exports = incrementalConvexHull +},{"binary-search-bounds":62,"robust-in-sphere":63}],59:[function(require,module,exports){ +'use strict' -var orient = require("robust-orientation") -var compareCell = require("simplicial-complex").compareCells +var bsearch = require('binary-search-bounds') -function compareInt(a, b) { - return a - b -} +module.exports = classifyFaces -function Simplex(vertices, adjacent, boundary) { - this.vertices = vertices - this.adjacent = adjacent - this.boundary = boundary - this.lastVisited = -1 +function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) { + this.cells = cells + this.neighbor = neighbor + this.flags = flags + this.constraint = constraint + this.active = active + this.next = next + this.boundary = boundary } -Simplex.prototype.flip = function() { - var t = this.vertices[0] - this.vertices[0] = this.vertices[1] - this.vertices[1] = t - var u = this.adjacent[0] - this.adjacent[0] = this.adjacent[1] - this.adjacent[1] = u -} +var proto = FaceIndex.prototype -function GlueFacet(vertices, cell, index) { - this.vertices = vertices - this.cell = cell - this.index = index +function compareCell(a, b) { + return a[0] - b[0] || + a[1] - b[1] || + a[2] - b[2] } -function compareGlue(a, b) { - return compareCell(a.vertices, b.vertices) -} +proto.locate = (function() { + var key = [0,0,0] + return function(a, b, c) { + var x = a, y = b, z = c + if(b < c) { + if(b < a) { + x = b + y = c + z = a + } + } else if(c < a) { + x = c + y = a + z = b + } + if(x < 0) { + return -1 + } + key[0] = x + key[1] = y + key[2] = z + return bsearch.eq(this.cells, key, compareCell) + } +})() -function bakeOrient(d) { - var code = ["function orient(){var tuple=this.tuple;return test("] - for(var i=0; i<=d; ++i) { - if(i > 0) { - code.push(",") +function indexCells(triangulation, infinity) { + //First get cells and canonicalize + var cells = triangulation.cells() + var nc = cells.length + for(var i=0; i 0) { - cell = toVisit.pop() - var cellVerts = cell.vertices - var cellAdj = cell.adjacent - for(var i=0; i<=d; ++i) { - var neighbor = cellAdj[i] - if(!neighbor.boundary || neighbor.lastVisited <= -n) { - continue - } - var nv = neighbor.vertices - for(var j=0; j<=d; ++j) { - var vv = nv[j] - if(vv < 0) { - tuple[j] = point + var index = new FaceIndex( + cells, + neighbor, + constraint, + flags, + active, + next, + boundary) + for(var i=0; i 0) { - return neighbor - } - neighbor.lastVisited = -n - if(o === 0) { - toVisit.push(neighbor) } } } - return null + return index } -proto.walk = function(point, random) { - //Alias local properties - var n = this.vertices.length - 1 - var d = this.dimension - var verts = this.vertices - var tuple = this.tuple - - //Compute initial jump cell - var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1) - var cell = this.interior[ initIndex ] +function filterCells(cells, flags, target) { + var ptr = 0 + for(var i=0; i= n) { + var side = 1 + var active = index.active + var next = index.next + var flags = index.flags + var cells = index.cells + var constraint = index.constraint + var neighbor = index.neighbor + + while(active.length > 0 || next.length > 0) { + while(active.length > 0) { + var t = active.pop() + if(flags[t] === -side) { continue } - var prev = tuple[i] - tuple[i] = point - var o = this.orient() - tuple[i] = prev - if(o < 0) { - cell = neighbor - continue outerLoop - } else { - if(!neighbor.boundary) { - neighbor.lastVisited = n - } else { - neighbor.lastVisited = -n + flags[t] = side + var c = cells[t] + for(var j=0; j<3; ++j) { + var f = neighbor[3*t+j] + if(f >= 0 && flags[f] === 0) { + if(constraint[3*t+j]) { + next.push(f) + } else { + active.push(f) + flags[f] = side + } } } } - return + + //Swap arrays and loop + var tmp = next + next = active + active = tmp + next.length = 0 + side = -side } - return cell + var result = filterCells(cells, flags, target) + if(infinity) { + return result.concat(index.boundary) + } + return result } -proto.addPeaks = function(point, cell) { - var n = this.vertices.length - 1 - var d = this.dimension - var verts = this.vertices - var tuple = this.tuple - var interior = this.interior - var simplices = this.simplices +},{"binary-search-bounds":62}],60:[function(require,module,exports){ +'use strict' - //Walking finished at boundary, time to add peaks - var tovisit = [ cell ] +var bsearch = require('binary-search-bounds') +var orient = require('robust-orientation')[3] - //Stretch initial boundary cell into a peak - cell.lastVisited = n - cell.vertices[cell.vertices.indexOf(-1)] = n - cell.boundary = false - interior.push(cell) +var EVENT_POINT = 0 +var EVENT_END = 1 +var EVENT_START = 2 - //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done - var glueFacets = [] +module.exports = monotoneTriangulate - //Do a traversal of the boundary walking outward from starting peak - while(tovisit.length > 0) { - //Pop off peak and walk over adjacent cells - var cell = tovisit.pop() - var cellVerts = cell.vertices - var cellAdj = cell.adjacent - var indexOfN = cellVerts.indexOf(n) - if(indexOfN < 0) { - continue +//A partial convex hull fragment, made of two unimonotone polygons +function PartialHull(a, b, idx, lowerIds, upperIds) { + this.a = a + this.b = b + this.idx = idx + this.lowerIds = lowerIds + this.upperIds = upperIds +} + +//An event in the sweep line procedure +function Event(a, b, type, idx) { + this.a = a + this.b = b + this.type = type + this.idx = idx +} + +//This is used to compare events for the sweep line procedure +// Points are: +// 1. sorted lexicographically +// 2. sorted by type (point < end < start) +// 3. segments sorted by winding order +// 4. sorted by index +function compareEvent(a, b) { + var d = + (a.a[0] - b.a[0]) || + (a.a[1] - b.a[1]) || + (a.type - b.type) + if(d) { return d } + if(a.type !== EVENT_POINT) { + d = orient(a.a, a.b, b.b) + if(d) { return d } + } + return a.idx - b.idx +} + +function testPoint(hull, p) { + return orient(hull.a, hull.b, p) +} + +function addPoint(cells, hulls, points, p, idx) { + var lo = bsearch.lt(hulls, p, testPoint) + var hi = bsearch.gt(hulls, p, testPoint) + for(var i=lo; i 1 && orient( + points[lowerIds[m-2]], + points[lowerIds[m-1]], + p) > 0) { + cells.push( + [lowerIds[m-1], + lowerIds[m-2], + idx]) + m -= 1 } + lowerIds.length = m + lowerIds.push(idx) - for(var i=0; i<=d; ++i) { - if(i === indexOfN) { - continue - } + //Insert p into upper hull + var upperIds = hull.upperIds + var m = upperIds.length + while(m > 1 && orient( + points[upperIds[m-2]], + points[upperIds[m-1]], + p) < 0) { + cells.push( + [upperIds[m-2], + upperIds[m-1], + idx]) + m -= 1 + } + upperIds.length = m + upperIds.push(idx) + } +} - //For each boundary neighbor of the cell - var neighbor = cellAdj[i] - if(!neighbor.boundary || neighbor.lastVisited >= n) { - continue - } +function findSplit(hull, edge) { + var d + if(hull.a[0] < edge.a[0]) { + d = orient(hull.a, hull.b, edge.a) + } else { + d = orient(edge.b, edge.a, hull.a) + } + if(d) { return d } + if(edge.b[0] < hull.b[0]) { + d = orient(hull.a, hull.b, edge.b) + } else { + d = orient(edge.b, edge.a, hull.b) + } + return d || hull.idx - edge.idx +} - var nv = neighbor.vertices +function splitHulls(hulls, points, event) { + var splitIdx = bsearch.le(hulls, event, findSplit) + var hull = hulls[splitIdx] + var upperIds = hull.upperIds + var x = upperIds[upperIds.length-1] + hull.upperIds = [x] + hulls.splice(splitIdx+1, 0, + new PartialHull(event.a, event.b, event.idx, [x], upperIds)) +} - //Test if neighbor is a peak - if(neighbor.lastVisited !== -n) { - //Compute orientation of p relative to each boundary peak - var indexOfNeg1 = 0 - for(var j=0; j<=d; ++j) { - if(nv[j] < 0) { - indexOfNeg1 = j - tuple[j] = point - } else { - tuple[j] = verts[nv[j]] - } - } - var o = this.orient() - //Test if neighbor cell is also a peak - if(o > 0) { - nv[indexOfNeg1] = n - neighbor.boundary = false - interior.push(neighbor) - tovisit.push(neighbor) - neighbor.lastVisited = n - continue - } else { - neighbor.lastVisited = -n - } - } +function mergeHulls(hulls, points, event) { + //Swap pointers for merge search + var tmp = event.a + event.a = event.b + event.b = tmp + var mergeIdx = bsearch.eq(hulls, event, findSplit) + var upper = hulls[mergeIdx] + var lower = hulls[mergeIdx-1] + lower.upperIds = upper.upperIds + hulls.splice(mergeIdx, 1) +} - var na = neighbor.adjacent - //Otherwise, replace neighbor with new face - var vverts = cellVerts.slice() - var vadj = cellAdj.slice() - var ncell = new Simplex(vverts, vadj, true) - simplices.push(ncell) +function monotoneTriangulate(points, edges) { - //Connect to neighbor - var opposite = na.indexOf(cell) - if(opposite < 0) { - continue - } - na[opposite] = ncell - vadj[indexOfN] = neighbor + var numPoints = points.length + var numEdges = edges.length - //Connect to cell - vverts[i] = -1 - vadj[i] = cell - cellAdj[i] = ncell + var events = [] - //Flip facet - ncell.flip() + //Create point events + for(var i=0; i b[0]) { + events.push( + new Event(b, a, EVENT_START, i), + new Event(a, b, EVENT_END, i)) } } - //Glue boundary facets together - glueFacets.sort(compareGlue) + //Sort events + events.sort(compareEvent) - for(var i=0; i+1= 0 + } +})() + +proto.removeTriangle = function(i, j, k) { + var stars = this.stars + removePair(stars[i], j, k) + removePair(stars[j], k, i) + removePair(stars[k], i, j) } -//Extract all boundary cells -proto.boundary = function() { - var d = this.dimension - var boundary = [] - var cells = this.simplices - var nc = cells.length - for(var i=0; i= 0) { - bcell[ptr++] = cv[j] - } else { - parity = j&1 - } - } - if(parity === (d&1)) { - var t = bcell[0] - bcell[0] = bcell[1] - bcell[1] = t - } - boundary.push(bcell) - } - } - return boundary +proto.addTriangle = function(i, j, k) { + var stars = this.stars + stars[i].push(j, k) + stars[j].push(k, i) + stars[k].push(i, j) } -function incrementalConvexHull(points, randomSearch) { - var n = points.length - if(n === 0) { - throw new Error("Must have at least d+1 points") - } - var d = points[0].length - if(n <= d) { - throw new Error("Must input at least d+1 points") +proto.opposite = function(j, i) { + var list = this.stars[i] + for(var k=1, n=list.length; k 0) - (v < 0); -} +},{"binary-search-bounds":62}],62:[function(require,module,exports){ +"use strict" -//Computes absolute value of integer -exports.abs = function(v) { - var mask = v >> (INT_BITS-1); - return (v ^ mask) - mask; +function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) { + var code = [ + "function ", funcName, "(a,l,h,", extraArgs.join(","), "){", +earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"), +";while(l<=h){\ +var m=(l+h)>>>1,x=a[m]"] + if(earlyOut) { + if(predicate.indexOf("c") < 0) { + code.push(";if(x===y){return m}else if(x<=y){") + } else { + code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") + } + } else { + code.push(";if(", predicate, "){i=m;") + } + if(reversed) { + code.push("l=m+1}else{h=m-1}") + } else { + code.push("h=m-1}else{l=m+1}") + } + code.push("}") + if(earlyOut) { + code.push("return -1};") + } else { + code.push("return i};") + } + return code.join("") } -//Computes minimum of integers x and y -exports.min = function(x, y) { - return y ^ ((x ^ y) & -(x < y)); +function compileBoundsSearch(predicate, reversed, suffix, earlyOut) { + var result = new Function([ + compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut), + compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), +"function dispatchBsearch", suffix, "(a,y,c,l,h){\ +if(typeof(c)==='function'){\ +return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ +}else{\ +return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ +}}\ +return dispatchBsearch", suffix].join("")) + return result() } -//Computes maximum of integers x and y -exports.max = function(x, y) { - return x ^ ((x ^ y) & -(x < y)); +module.exports = { + ge: compileBoundsSearch(">=", false, "GE"), + gt: compileBoundsSearch(">", false, "GT"), + lt: compileBoundsSearch("<", true, "LT"), + le: compileBoundsSearch("<=", true, "LE"), + eq: compileBoundsSearch("-", true, "EQ", true) } -//Checks if a number is a power of two -exports.isPow2 = function(v) { - return !(v & (v-1)) && (!!v); -} +},{}],63:[function(require,module,exports){ +"use strict" -//Computes log base 2 of v -exports.log2 = function(v) { - var r, shift; - r = (v > 0xFFFF) << 4; v >>>= r; - shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; - shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; - shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; - return r | (v >> 1); -} +var twoProduct = require("two-product") +var robustSum = require("robust-sum") +var robustDiff = require("robust-subtract") +var robustScale = require("robust-scale") -//Computes log base 10 of v -exports.log10 = function(v) { - return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : - (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : - (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; -} +var NUM_EXPAND = 6 -//Counts number of bits -exports.popCount = function(v) { - v = v - ((v >>> 1) & 0x55555555); - v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); - return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +function cofactor(m, c) { + var result = new Array(m.length-1) + for(var i=1; i>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; +function generateSum(expr) { + if(expr.length === 1) { + return expr[0] + } else if(expr.length === 2) { + return ["sum(", expr[0], ",", expr[1], ")"].join("") + } else { + var m = expr.length>>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") + } } -//Rounds down to previous power of 2 -exports.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v>>>1); +function makeProduct(a, b) { + if(a.charAt(0) === "m") { + if(b.charAt(0) === "w") { + var toks = a.split("[") + return ["w", b.substr(1), "m", toks[0].substr(1)].join("") + } else { + return ["prod(", a, ",", b, ")"].join("") + } + } else { + return makeProduct(b, a) + } } -//Computes parity of word -exports.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 0xf; - return (0x6996 >>> v) & 1; +function sign(s) { + if(s & 1 !== 0) { + return "-" + } + return "" } -var REVERSE_TABLE = new Array(256); - -(function(tab) { - for(var i=0; i<256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; +function determinant(m) { + if(m.length === 2) { + return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] + } else { + var expr = [] + for(var i=0; i>> 8) & 0xff] << 16) | - (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | - REVERSE_TABLE[(v >>> 24) & 0xff]; } -//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes -exports.interleave2 = function(x, y) { - x &= 0xFFFF; - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y &= 0xFFFF; - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); +function makeSquare(d, n) { + var terms = [] + for(var i=0; i>> n) & 0x55555555; - v = (v | (v >>> 1)) & 0x33333333; - v = (v | (v >>> 2)) & 0x0F0F0F0F; - v = (v | (v >>> 4)) & 0x00FF00FF; - v = (v | (v >>> 16)) & 0x000FFFF; - return (v << 16) >> 16; +function orientation(n) { + var pos = [] + var neg = [] + var m = matrix(n) + for(var i=0; i>> n) & 1227133513; - v = (v | (v>>>2)) & 3272356035; - v = (v | (v>>>4)) & 251719695; - v = (v | (v>>>8)) & 4278190335; - v = (v | (v>>>16)) & 0x3FF; - return (v<<22)>>22; -} +var CACHED = [ + inSphere0, + inSphere1, + inSphere2 +] -//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) -exports.nextCombination = function(v) { - var t = v | (v - 1); - return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +function slowInSphere(args) { + var proc = CACHED[args.length] + if(!proc) { + proc = CACHED[args.length] = orientation(args.length) + } + return proc.apply(undefined, args) } +function generateInSphereTest() { + while(CACHED.length <= NUM_EXPAND) { + CACHED.push(orientation(CACHED.length)) + } + var args = [] + var procArgs = ["slow"] + for(var i=0; i<=NUM_EXPAND; ++i) { + args.push("a" + i) + procArgs.push("o" + i) + } + var code = [ + "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" + ] + for(var i=2; i<=NUM_EXPAND; ++i) { + code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") + } + code.push("}var s=new Array(arguments.length);for(var i=0;i 0) { + return [nextafter(f, -Infinity), f] } else { - roots[yr] = xr; - ++ranks[xr]; + return [f, f] } } -},{}],79:[function(require,module,exports){ -"use strict"; "use restrict"; -var bits = require("bit-twiddle") - , UnionFind = require("union-find") +//Convert a list of edges in a pslg to bounding boxes +function boundEdges(points, edges) { + var bounds = new Array(edges.length) + for(var i=0; i= floatPoints.length) { + return ratPoints[idx-floatPoints.length] + } + var p = floatPoints[idx] + return [ rat(p[0]), rat(p[1]) ] } -} -exports.compareCells = compareCells + junctions.sort(function(a, b) { + if(a[0] !== b[0]) { + return a[0] - b[0] + } + var u = getPoint(a[1]) + var v = getPoint(b[1]) + return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1]) + }) -function compareZipped(a, b) { - return compareCells(a[0], b[0]) -} + //Split edges along junctions + for(var i=junctions.length-1; i>=0; --i) { + var junction = junctions[i] + var e = junction[0] -//Puts a cell complex into normal order for the purposes of findCell queries -function normalize(cells, attr) { - if(attr) { - var len = cells.length - var zipped = new Array(len) - for(var i=0; i 0 && junctions[i-1][0] === e) { + var junction = junctions[--i] + var next = junction[1] + if(useColor) { + edges.push([last, next, color]) + } else { + edges.push([last, next]) } - cells[ptr++] = a + last = next } - } - cells.length = ptr - return cells -} -exports.unique = unique; -//Finds a cell in a normalized cell complex -function findCell(cells, c) { - var lo = 0 - , hi = cells.length-1 - , r = -1 - while (lo <= hi) { - var mid = (lo + hi) >> 1 - , s = compareCells(cells[mid], c) - if(s <= 0) { - if(s === 0) { - r = mid - } - lo = mid + 1 - } else if(s > 0) { - hi = mid - 1 + //Add final edge + if(useColor) { + edges.push([last, t, color]) + } else { + edges.push([last, t]) } } - return r + + //Return constructed rational points + return ratPoints } -exports.findCell = findCell; -//Builds an index for an n-cell. This is more general than dual, but less efficient -function incidence(from_cells, to_cells) { - var index = new Array(from_cells.length) - for(var i=0, il=index.length; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { - break - } - } + + //Link all points with over lapping boxes + boxIntersect(bounds, function(i, j) { + uf.link(i, j) + }) + + //Call find on each point to get a relabeling + var ptr = 0 + var noDupes = true + var labels = new Array(numPoints) + for(var i=0; i>> k) & 1) { - b.push(c[k]) - } - } - result.push(b) - } +function compareLex2(a,b) { return (a[0]-b[0]) || (a[1]-b[1]) } +function compareLex3(a,b) { + var d = (a[0] - b[0]) || (a[1] - b[1]) + if(d) { + return d } - return normalize(result) + if(a[2] < b[2]) { + return -1 + } else if(a[2] > b[2]) { + return 1 + } + return 0 } -exports.explode = explode -//Enumerates all of the n-cells of a cell complex -function skeleton(cells, n) { - if(n < 0) { - return [] +//Remove duplicate edge labels +function dedupEdges(edges, labels, useColor) { + if(edges.length === 0) { + return } - var result = [] - , k0 = (1<<(n+1))-1 - for(var i=0; i 0 || tjunctions.length > 0) + } + + // More iterations necessary + return true +} + +//Main loop, runs PSLG clean up until completion +function cleanPSLG(points, edges, colors) { + var modified = false + + //If using colors, augment edges with color data + var prevEdges + if(colors) { + prevEdges = edges + var augEdges = new Array(edges.length) + for(var i=0; i 0) { + a = a.shln(shift) + } else if(shift < 0) { + b = b.shln(-shift) + } + return rationalize(a, b) } -//Computes connected components for a cell complex -function connectedComponents(cells, vertex_count) { - if(vertex_count) { - return connectedComponents_dense(cells, vertex_count) - } - return connectedComponents_sparse(cells) +},{"./div":68,"./is-rat":70,"./lib/is-bn":74,"./lib/num-to-bn":75,"./lib/rationalize":76,"./lib/str-to-bn":77}],70:[function(require,module,exports){ +'use strict' + +var isBN = require('./lib/is-bn') + +module.exports = isRat + +function isRat(x) { + return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1]) } -exports.connectedComponents = connectedComponents -},{"bit-twiddle":77,"union-find":78}],80:[function(require,module,exports){ +},{"./lib/is-bn":74}],71:[function(require,module,exports){ 'use strict' -module.exports = monotoneConvexHull2D +var bn = require('bn.js') -var orient = require('robust-orientation')[3] +module.exports = sign -function monotoneConvexHull2D(points) { - var n = points.length +function sign(x) { + return x.cmp(new bn(0)) +} - if(n < 3) { - var result = new Array(n) - for(var i=0; i 20) { + return 52 } + return h + 32 +} - //Sort point indices along x-axis - var sorted = new Array(n) - for(var i=0; i 1 && orient( - points[lower[m-2]], - points[lower[m-1]], - p) <= 0) { - m -= 1 - lower.pop() - } - lower.push(idx) +module.exports = rationalize - //Insert into upper list - m = upper.length - while(m > 1 && orient( - points[upper[m-2]], - points[upper[m-1]], - p) >= 0) { - m -= 1 - upper.pop() - } - upper.push(idx) +function rationalize(numer, denom) { + var snumer = sign(numer) + var sdenom = sign(denom) + if(snumer === 0) { + return [num2bn(0), num2bn(1)] + } + if(sdenom === 0) { + return [num2bn(0), num2bn(0)] + } + if(sdenom < 0) { + numer = numer.neg() + denom = denom.neg() + } + var d = numer.gcd(denom) + if(d.cmpn(1)) { + return [ numer.div(d), denom.div(d) ] } + return [ numer, denom ] +} - //Merge lists together - var result = new Array(upper.length + lower.length - 2) - var ptr = 0 - for(var i=0, nl=lower.length; i0; --j) { - result[ptr++] = upper[j] + + this.sign = false; + this.words = null; + this.length = 0; + + // Reduction context + this.red = null; + + if (base === 'le' || base === 'be') { + endian = base; + base = 10; } - //Return result - return result + if (number !== null) + this._init(number || 0, base || 10, endian || 'be'); } -},{"robust-orientation":1040}],81:[function(require,module,exports){ -module.exports = { - AFG: "afghan", - ALA: "\\b\\wland", - ALB: "albania", - DZA: "algeria", - ASM: "^(?=.*americ).*samoa", - AND: "andorra", - AGO: "angola", - AIA: "anguill?a", - ATA: "antarctica", - ATG: "antigua", - ARG: "argentin", - ARM: "armenia", - ABW: "^(?!.*bonaire).*\\baruba", - AUS: "australia", - AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp", - AZE: "azerbaijan", - BHS: "bahamas", - BHR: "bahrain", - BGD: "bangladesh|^(?=.*east).*paki?stan", - BRB: "barbados", - BLR: "belarus|byelo", - BEL: "^(?!.*luxem).*belgium", - BLZ: "belize|^(?=.*british).*honduras", - BEN: "benin|dahome", - BMU: "bermuda", - BTN: "bhutan", - BOL: "bolivia", - BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands", - BIH: "herzegovina|bosnia", - BWA: "botswana|bechuana", - BVT: "bouvet", - BRA: "brazil", - IOT: "british.?indian.?ocean", - BRN: "brunei", - BGR: "bulgaria", - BFA: "burkina|\\bfaso|upper.?volta", - BDI: "burundi", - KHM: "cambodia|kampuchea|khmer", - CMR: "cameroon", - CAN: "canada", - CPV: "verde", - CYM: "cayman", - CAF: "\\bcentral.african.republic", - TCD: "\\bchad", - CHL: "\\bchile", - CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china", - CXR: "christmas", - CCK: "\\bcocos|keeling", - COL: "colombia", - COM: "comoro", - COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc", - COG: "^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo", - COK: "\\bcook", - CRI: "costa.?rica", - CIV: "ivoire|ivory", - HRV: "croatia", - CUB: "\\bcuba", - CUW: "^(?!.*bonaire).*\\bcura(c|ç)ao", - CYP: "cyprus", - CZE: "^(?=.*rep).*czech|czechia|bohemia", - CSK: "czechoslovakia", - DNK: "denmark", - DJI: "djibouti", - DMA: "dominica(?!n)", - DOM: "dominican.rep", - ECU: "ecuador", - EGY: "egypt", - SLV: "el.?salvador", - GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea", - ERI: "eritrea", - EST: "estonia", - ETH: "ethiopia|abyssinia", - FLK: "falkland|malvinas", - FRO: "faroe|faeroe", - FJI: "fiji", - FIN: "finland", - FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul", - GUF: "^(?=.*french).*guiana", - PYF: "french.?polynesia|tahiti", - ATF: "french.?southern", - GAB: "gabon", - GMB: "gambia", - GEO: "^(?!.*south).*georgia", - DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany", - DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german", - GHA: "ghana|gold.?coast", - GIB: "gibraltar", - GRC: "greece|hellenic|hellas", - GRL: "greenland", - GRD: "grenada", - GLP: "guadeloupe", - GUM: "\\bguam", - GTM: "guatemala", - GGY: "guernsey", - GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea", - GNB: "bissau|^(?=.*portu).*guinea", - GUY: "guyana|british.?guiana", - HTI: "haiti", - HMD: "heard.*mcdonald", - VAT: "holy.?see|vatican|papal.?st", - HND: "^(?!.*brit).*honduras", - HKG: "hong.?kong", - HUN: "^(?!.*austr).*hungary", - ISL: "iceland", - IND: "india(?!.*ocea)", - IDN: "indonesia", - IRN: "\\biran|persia", - IRQ: "\\biraq|mesopotamia", - IRL: "ireland", - IMN: "^(?=.*isle).*\\bman", - ISR: "israel", - ITA: "italy", - JAM: "jamaica", - JPN: "japan", - JEY: "jersey", - JOR: "jordan", - KAZ: "kazak", - KEN: "kenya|british.?east.?africa|east.?africa.?prot", - KIR: "kiribati", - PRK: "^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk", - KOR: "^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea", - KWT: "kuwait", - KGZ: "kyrgyz|kirghiz", - LAO: "\\blaos?\\b", - LVA: "latvia", - LBN: "lebanon", - LSO: "lesotho|basuto", - LBR: "liberia", - LBY: "libya", - LIE: "liechtenstein", - LTU: "lithuania", - LUX: "^(?!.*belg).*luxem", - MAC: "maca(o|u)", - MKD: "macedonia|fyrom", - MDG: "madagascar|malagasy", - MWI: "malawi|nyasa", - MYS: "malaysia", - MDV: "maldive", - MLI: "\\bmali\\b", - MLT: "\\bmalta", - MHL: "marshall", - MTQ: "martinique", - MRT: "mauritania", - MUS: "mauritius", - MYT: "\\bmayotte", - MEX: "\\bmexic", - FSM: "micronesia", - MDA: "moldov|b(a|e)ssarabia", - MCO: "monaco", - MNG: "mongolia", - MNE: "^(?!.*serbia).*montenegro", - MSR: "montserrat", - MAR: "morocco|\\bmaroc", - MOZ: "mozambique", - MMR: "myanmar|burma", - NAM: "namibia", - NRU: "nauru", - NPL: "nepal", - NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands", - ANT: "^(?=.*\\bant).*(nether|dutch)", - NCL: "new.?caledonia", - NZL: "new.?zealand", - NIC: "nicaragua", - NER: "\\bniger(?!ia)", - NGA: "nigeria", - NIU: "niue", - NFK: "norfolk", - MNP: "mariana", - NOR: "norway", - OMN: "\\boman|trucial", - PAK: "^(?!.*east).*paki?stan", - PLW: "palau", - PSE: "palestin|\\bgaza|west.?bank", - PAN: "panama", - PNG: "papua|new.?guinea", - PRY: "paraguay", - PER: "peru", - PHL: "philippines", - PCN: "pitcairn", - POL: "poland", - PRT: "portugal", - PRI: "puerto.?rico", - QAT: "qatar", - REU: "r(e|é)union", - ROU: "r(o|u|ou)mania", - RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics", - RWA: "rwanda", - BLM: "barth(e|é)lemy", - SHN: "helena", - KNA: "kitts|\\bnevis", - LCA: "\\blucia", - MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)", - SPM: "miquelon", - VCT: "vincent", - WSM: "^(?!.*amer).*samoa", - SMR: "san.?marino", - STP: "\\bs(a|ã)o.?tom(e|é)", - SAU: "\\bsa\\w*.?arabia", - SEN: "senegal", - SRB: "^(?!.*monte).*serbia", - SYC: "seychell", - SLE: "sierra", - SGP: "singapore", - SXM: "^(?!.*martin)(?!.*saba).*maarten", - SVK: "^(?!.*cze).*slovak", - SVN: "slovenia", - SLB: "solomon", - SOM: "somali", - ZAF: "\\bs\\w*.?africa", - SGS: "south.?georgia|sandwich", - SSD: "\\bs\\w*.?sudan", - ESP: "spain", - LKA: "sri.?lanka|ceylon", - SDN: "^(?!.*\\bs(?!u)).*sudan", - SUR: "surinam|dutch.?guiana", - SJM: "svalbard", - SWZ: "swaziland", - SWE: "sweden", - CHE: "switz|swiss", - SYR: "syria", - TWN: "taiwan|taipei|formosa", - TJK: "tajik", - TZA: "tanzania", - THA: "thailand|\\bsiam", - TLS: "^(?=.*leste).*timor|^(?=.*east).*timor", - TGO: "togo", - TKL: "tokelau", - TON: "tonga", - TTO: "trinidad|tobago", - TUN: "tunisia", - TUR: "turkey", - TKM: "turkmen", - TCA: "turks", - TUV: "tuvalu", - UGA: "uganda", - UKR: "ukrain", - ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em", - GBR: "united.?kingdom|britain|^u\\.?k\\.?$", - USA: "united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)", - UMI: "minor.?outlying.?is", - URY: "uruguay", - UZB: "uzbek", - VUT: "vanuatu|new.?hebrides", - VEN: "venezuela", - VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam", - VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin", - VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin", - WLF: "futuna|wallis", - ESH: "western.sahara", - YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen", - YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen", - YUG: "yugoslavia", - ZMB: "zambia|northern.?rhodesia", - EAZ: "zanzibar", - ZWE: "zimbabwe|^(?!.*northern).*rhodesia" -}; +if (typeof module === 'object') + module.exports = BN; +else + exports.BN = BN; -},{}],82:[function(require,module,exports){ -!function() { - var d3 = { - version: "3.5.17" - }; - var d3_arraySlice = [].slice, d3_array = function(list) { - return d3_arraySlice.call(list); - }; - var d3_document = this.document; - function d3_documentElement(node) { - return node && (node.ownerDocument || node.document || node).documentElement; - } - function d3_window(node) { - return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); +BN.BN = BN; +BN.wordSize = 26; + +BN.prototype._init = function init(number, base, endian) { + if (typeof number === 'number') { + return this._initNumber(number, base, endian); + } else if (typeof number === 'object') { + return this._initArray(number, base, endian); } - if (d3_document) { - try { - d3_array(d3_document.documentElement.childNodes)[0].nodeType; - } catch (e) { - d3_array = function(list) { - var i = list.length, array = new Array(i); - while (i--) array[i] = list[i]; - return array; - }; - } + if (base === 'hex') + base = 16; + assert(base === (base | 0) && base >= 2 && base <= 36); + + number = number.toString().replace(/\s+/g, ''); + var start = 0; + if (number[0] === '-') + start++; + + if (base === 16) + this._parseHex(number, start); + else + this._parseBase(number, base, start); + + if (number[0] === '-') + this.sign = true; + + this.strip(); + + if (endian !== 'le') + return; + + this._initArray(this.toArray(), base, endian); +}; + +BN.prototype._initNumber = function _initNumber(number, base, endian) { + if (number < 0) { + this.sign = true; + number = -number; } - if (!Date.now) Date.now = function() { - return +new Date(); - }; - if (d3_document) { - try { - d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); - } catch (error) { - var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; - d3_element_prototype.setAttribute = function(name, value) { - d3_element_setAttribute.call(this, name, value + ""); - }; - d3_element_prototype.setAttributeNS = function(space, local, value) { - d3_element_setAttributeNS.call(this, space, local, value + ""); - }; - d3_style_prototype.setProperty = function(name, value, priority) { - d3_style_setProperty.call(this, name, value + "", priority); - }; - } + if (number < 0x4000000) { + this.words = [ number & 0x3ffffff ]; + this.length = 1; + } else if (number < 0x10000000000000) { + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff + ]; + this.length = 2; + } else { + assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) + this.words = [ + number & 0x3ffffff, + (number / 0x4000000) & 0x3ffffff, + 1 + ]; + this.length = 3; } - d3.ascending = d3_ascending; - function d3_ascending(a, b) { - return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + + if (endian !== 'le') + return; + + // Reverse the bytes + this._initArray(this.toArray(), base, endian); +}; + +BN.prototype._initArray = function _initArray(number, base, endian) { + // Perhaps a Uint8Array + assert(typeof number.length === 'number'); + if (number.length <= 0) { + this.words = [ 0 ]; + this.length = 1; + return this; } - d3.descending = function(a, b) { - return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; - }; - d3.min = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array[i]) != null && a > b) a = b; - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; - } - return a; - }; - d3.max = function(array, f) { - var i = -1, n = array.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array[i]) != null && b > a) a = b; - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = b; - break; + + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + var off = 0; + if (endian === 'be') { + for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { + var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; } - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; } - return a; - }; - d3.extent = function(array, f) { - var i = -1, n = array.length, a, b, c; - if (arguments.length === 1) { - while (++i < n) if ((b = array[i]) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = array[i]) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } else { - while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = f.call(array, array[i], i)) != null) { - if (a > b) a = b; - if (c < b) c = b; + } else if (endian === 'le') { + for (var i = 0, j = 0; i < number.length; i += 3) { + var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; } } - return [ a, c ]; - }; - function d3_number(x) { - return x === null ? NaN : +x; } - function d3_numeric(x) { - return !isNaN(x); + return this.strip(); +}; + +function parseHex(str, start, end) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r <<= 4; + + // 'a' - 'f' + if (c >= 49 && c <= 54) + r |= c - 49 + 0xa; + + // 'A' - 'F' + else if (c >= 17 && c <= 22) + r |= c - 17 + 0xa; + + // '0' - '9' + else + r |= c & 0xf; } - d3.sum = function(array, f) { - var s = 0, n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = +array[i])) s += a; - } else { - while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; - } - return s; - }; - d3.mean = function(array, f) { - var s = 0, n = array.length, a, i = -1, j = n; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; - } - if (j) return s / j; - }; - d3.quantile = function(values, p) { - var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; - return e ? v + e * (values[h] - v) : v; - }; - d3.median = function(array, f) { - var numbers = [], n = array.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); - } - if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); - }; - d3.variance = function(array, f) { - var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; - if (arguments.length === 1) { - while (++i < n) { - if (d3_numeric(a = d3_number(array[i]))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } else { - while (++i < n) { - if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } + return r; +} + +BN.prototype._parseHex = function _parseHex(number, start) { + // Create possibly bigger array to ensure that it fits the number + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + this.words[i] = 0; + + // Scan 24-bit chunks and add them to the number + var off = 0; + for (var i = number.length - 6, j = 0; i >= start; i -= 6) { + var w = parseHex(number, i, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + off += 24; + if (off >= 26) { + off -= 26; + j++; } - if (j > 1) return s / (j - 1); - }; - d3.deviation = function() { - var v = d3.variance.apply(this, arguments); - return v ? Math.sqrt(v) : v; - }; - function d3_bisector(compare) { - return { - left: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; - } - return lo; - }, - right: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; - } - return lo; - } - }; } - var d3_bisect = d3_bisector(d3_ascending); - d3.bisectLeft = d3_bisect.left; - d3.bisect = d3.bisectRight = d3_bisect.right; - d3.bisector = function(f) { - return d3_bisector(f.length === 1 ? function(d, x) { - return d3_ascending(f(d), x); - } : f); - }; - d3.shuffle = function(array, i0, i1) { - if ((m = arguments.length) < 3) { - i1 = array.length; - if (m < 2) i0 = 0; + if (i + 6 !== start) { + var w = parseHex(number, start, i + 6); + this.words[j] |= (w << off) & 0x3ffffff; + this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + } + this.strip(); +}; + +function parseBase(str, start, end, mul) { + var r = 0; + var len = Math.min(str.length, end); + for (var i = start; i < len; i++) { + var c = str.charCodeAt(i) - 48; + + r *= mul; + + // 'a' + if (c >= 49) + r += c - 49 + 0xa; + + // 'A' + else if (c >= 17) + r += c - 17 + 0xa; + + // '0' - '9' + else + r += c; + } + return r; +} + +BN.prototype._parseBase = function _parseBase(number, base, start) { + // Initialize as zero + this.words = [ 0 ]; + this.length = 1; + + // Find length of limb in base + for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) + limbLen++; + limbLen--; + limbPow = (limbPow / base) | 0; + + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + + var word = 0; + for (var i = start; i < end; i += limbLen) { + word = parseBase(number, i, i + limbLen, base); + + this.imuln(limbPow); + if (this.words[0] + word < 0x4000000) + this.words[0] += word; + else + this._iaddn(word); + } + + if (mod !== 0) { + var pow = 1; + var word = parseBase(number, i, number.length, base); + + for (var i = 0; i < mod; i++) + pow *= base; + this.imuln(pow); + if (this.words[0] + word < 0x4000000) + this.words[0] += word; + else + this._iaddn(word); + } +}; + +BN.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for (var i = 0; i < this.length; i++) + dest.words[i] = this.words[i]; + dest.length = this.length; + dest.sign = this.sign; + dest.red = this.red; +}; + +BN.prototype.clone = function clone() { + var r = new BN(null); + this.copy(r); + return r; +}; + +// Remove leading `0` from `this` +BN.prototype.strip = function strip() { + while (this.length > 1 && this.words[this.length - 1] === 0) + this.length--; + return this._normSign(); +}; + +BN.prototype._normSign = function _normSign() { + // -0 = 0 + if (this.length === 1 && this.words[0] === 0) + this.sign = false; + return this; +}; + +BN.prototype.inspect = function inspect() { + return (this.red ? ''; +}; + +/* + +var zeros = []; +var groupSizes = []; +var groupBases = []; + +var s = ''; +var i = -1; +while (++i < BN.wordSize) { + zeros[i] = s; + s += '0'; +} +groupSizes[0] = 0; +groupSizes[1] = 0; +groupBases[0] = 0; +groupBases[1] = 0; +var base = 2 - 1; +while (++base < 36 + 1) { + var groupSize = 0; + var groupBase = 1; + while (groupBase < (1 << BN.wordSize) / base) { + groupBase *= base; + groupSize += 1; + } + groupSizes[base] = groupSize; + groupBases[base] = groupBase; +} + +*/ + +var zeros = [ + '', + '0', + '00', + '000', + '0000', + '00000', + '000000', + '0000000', + '00000000', + '000000000', + '0000000000', + '00000000000', + '000000000000', + '0000000000000', + '00000000000000', + '000000000000000', + '0000000000000000', + '00000000000000000', + '000000000000000000', + '0000000000000000000', + '00000000000000000000', + '000000000000000000000', + '0000000000000000000000', + '00000000000000000000000', + '000000000000000000000000', + '0000000000000000000000000' +]; + +var groupSizes = [ + 0, 0, + 25, 16, 12, 11, 10, 9, 8, + 8, 7, 7, 7, 7, 6, 6, + 6, 6, 6, 6, 6, 5, 5, + 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5 +]; + +var groupBases = [ + 0, 0, + 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, + 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, + 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, + 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, + 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 +]; + +BN.prototype.toString = function toString(base, padding) { + base = base || 10; + if (base === 16 || base === 'hex') { + var out = ''; + var off = 0; + var padding = padding | 0 || 1; + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i]; + var word = (((w << off) | carry) & 0xffffff).toString(16); + carry = (w >>> (24 - off)) & 0xffffff; + if (carry !== 0 || i !== this.length - 1) + out = zeros[6 - word.length] + word + out; + else + out = word + out; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } } - var m = i1 - i0, t, i; - while (m) { - i = Math.random() * m-- | 0; - t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; + if (carry !== 0) + out = carry.toString(16) + out; + while (out.length % padding !== 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else if (base === (base | 0) && base >= 2 && base <= 36) { + // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); + var groupSize = groupSizes[base]; + // var groupBase = Math.pow(base, groupSize); + var groupBase = groupBases[base]; + var out = ''; + var c = this.clone(); + c.sign = false; + while (c.cmpn(0) !== 0) { + var r = c.modn(groupBase).toString(base); + c = c.idivn(groupBase); + + if (c.cmpn(0) !== 0) + out = zeros[groupSize - r.length] + r + out; + else + out = r + out; } - return array; - }; - d3.permute = function(array, indexes) { - var i = indexes.length, permutes = new Array(i); - while (i--) permutes[i] = array[indexes[i]]; - return permutes; - }; - d3.pairs = function(array) { - var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); - while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; - return pairs; - }; - d3.transpose = function(matrix) { - if (!(n = matrix.length)) return []; - for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { - for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { - row[j] = matrix[j][i]; - } + if (this.cmpn(0) === 0) + out = '0' + out; + if (this.sign) + out = '-' + out; + return out; + } else { + assert(false, 'Base should be between 2 and 36'); + } +}; + +BN.prototype.toJSON = function toJSON() { + return this.toString(16); +}; + +BN.prototype.toArray = function toArray(endian) { + this.strip(); + var res = new Array(this.byteLength()); + res[0] = 0; + + var q = this.clone(); + if (endian !== 'le') { + // Assume big-endian + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); + + res[res.length - i - 1] = b; + } + } else { + // Assume little-endian + for (var i = 0; q.cmpn(0) !== 0; i++) { + var b = q.andln(0xff); + q.ishrn(8); + + res[i] = b; } - return transpose; - }; - function d3_transposeLength(d) { - return d.length; } - d3.zip = function() { - return d3.transpose(arguments); - }; - d3.keys = function(map) { - var keys = []; - for (var key in map) keys.push(key); - return keys; - }; - d3.values = function(map) { - var values = []; - for (var key in map) values.push(map[key]); - return values; - }; - d3.entries = function(map) { - var entries = []; - for (var key in map) entries.push({ - key: key, - value: map[key] - }); - return entries; + + return res; +}; + +if (Math.clz32) { + BN.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); }; - d3.merge = function(arrays) { - var n = arrays.length, m, i = -1, j = 0, merged, array; - while (++i < n) j += arrays[i].length; - merged = new Array(j); - while (--n >= 0) { - array = arrays[n]; - m = array.length; - while (--m >= 0) { - merged[--j] = array[m]; - } +} else { + BN.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 0x1000) { + r += 13; + t >>>= 13; } - return merged; - }; - var abs = Math.abs; - d3.range = function(start, stop, step) { - if (arguments.length < 3) { - step = 1; - if (arguments.length < 2) { - stop = start; - start = 0; - } + if (t >= 0x40) { + r += 7; + t >>>= 7; } - if ((stop - start) / step === Infinity) throw new Error("infinite range"); - var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; - start *= k, stop *= k, step *= k; - if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); - return range; - }; - function d3_range_integerScale(x) { - var k = 1; - while (x * k % 1) k *= 10; - return k; - } - function d3_class(ctor, properties) { - for (var key in properties) { - Object.defineProperty(ctor.prototype, key, { - value: properties[key], - enumerable: false - }); + if (t >= 0x8) { + r += 4; + t >>>= 4; } - } - d3.map = function(object, f) { - var map = new d3_Map(); - if (object instanceof d3_Map) { - object.forEach(function(key, value) { - map.set(key, value); - }); - } else if (Array.isArray(object)) { - var i = -1, n = object.length, o; - if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); - } else { - for (var key in object) map.set(key, object[key]); + if (t >= 0x02) { + r += 2; + t >>>= 2; } - return map; + return r + t; }; - function d3_Map() { - this._ = Object.create(null); - } - var d3_map_proto = "__proto__", d3_map_zero = "\x00"; - d3_class(d3_Map, { - has: d3_map_has, - get: function(key) { - return this._[d3_map_escape(key)]; - }, - set: function(key, value) { - return this._[d3_map_escape(key)] = value; - }, - remove: d3_map_remove, - keys: d3_map_keys, - values: function() { - var values = []; - for (var key in this._) values.push(this._[key]); - return values; - }, - entries: function() { - var entries = []; - for (var key in this._) entries.push({ - key: d3_map_unescape(key), - value: this._[key] - }); - return entries; - }, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); - } - }); - function d3_map_escape(key) { - return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; - } - function d3_map_unescape(key) { - return (key += "")[0] === d3_map_zero ? key.slice(1) : key; - } - function d3_map_has(key) { - return d3_map_escape(key) in this._; +} + +BN.prototype._zeroBits = function _zeroBits(w) { + // Short-cut + if (w === 0) + return 26; + + var t = w; + var r = 0; + if ((t & 0x1fff) === 0) { + r += 13; + t >>>= 13; } - function d3_map_remove(key) { - return (key = d3_map_escape(key)) in this._ && delete this._[key]; + if ((t & 0x7f) === 0) { + r += 7; + t >>>= 7; } - function d3_map_keys() { - var keys = []; - for (var key in this._) keys.push(d3_map_unescape(key)); - return keys; + if ((t & 0xf) === 0) { + r += 4; + t >>>= 4; } - function d3_map_size() { - var size = 0; - for (var key in this._) ++size; - return size; + if ((t & 0x3) === 0) { + r += 2; + t >>>= 2; } - function d3_map_empty() { - for (var key in this._) return false; - return true; + if ((t & 0x1) === 0) + r++; + return r; +}; + +// Return number of used bits in a BN +BN.prototype.bitLength = function bitLength() { + var hi = 0; + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; +}; + +// Number of trailing zero bits +BN.prototype.zeroBits = function zeroBits() { + if (this.cmpn(0) === 0) + return 0; + + var r = 0; + for (var i = 0; i < this.length; i++) { + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) + break; } - d3.nest = function() { - var nest = {}, keys = [], sortKeys = [], sortValues, rollup; - function map(mapType, array, depth) { - if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; - var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; - while (++i < n) { - if (values = valuesByKey.get(keyValue = key(object = array[i]))) { - values.push(object); - } else { - valuesByKey.set(keyValue, [ object ]); - } - } - if (mapType) { - object = mapType(); - setter = function(keyValue, values) { - object.set(keyValue, map(mapType, values, depth)); - }; - } else { - object = {}; - setter = function(keyValue, values) { - object[keyValue] = map(mapType, values, depth); - }; - } - valuesByKey.forEach(setter); - return object; - } - function entries(map, depth) { - if (depth >= keys.length) return map; - var array = [], sortKey = sortKeys[depth++]; - map.forEach(function(key, keyMap) { - array.push({ - key: key, - values: entries(keyMap, depth) - }); - }); - return sortKey ? array.sort(function(a, b) { - return sortKey(a.key, b.key); - }) : array; - } - nest.map = function(array, mapType) { - return map(mapType, array, 0); - }; - nest.entries = function(array) { - return entries(map(d3.map, array, 0), 0); - }; - nest.key = function(d) { - keys.push(d); - return nest; - }; - nest.sortKeys = function(order) { - sortKeys[keys.length - 1] = order; - return nest; - }; - nest.sortValues = function(order) { - sortValues = order; - return nest; - }; - nest.rollup = function(f) { - rollup = f; - return nest; - }; - return nest; - }; - d3.set = function(array) { - var set = new d3_Set(); - if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); - return set; - }; - function d3_Set() { - this._ = Object.create(null); + return r; +}; + +BN.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); +}; + +// Return negative clone of `this` +BN.prototype.neg = function neg() { + if (this.cmpn(0) === 0) + return this.clone(); + + var r = this.clone(); + r.sign = !this.sign; + return r; +}; + + +// Or `num` with `this` in-place +BN.prototype.ior = function ior(num) { + this.sign = this.sign || num.sign; + + while (this.length < num.length) + this.words[this.length++] = 0; + + for (var i = 0; i < num.length; i++) + this.words[i] = this.words[i] | num.words[i]; + + return this.strip(); +}; + + +// Or `num` with `this` +BN.prototype.or = function or(num) { + if (this.length > num.length) + return this.clone().ior(num); + else + return num.clone().ior(this); +}; + + +// And `num` with `this` in-place +BN.prototype.iand = function iand(num) { + this.sign = this.sign && num.sign; + + // b = min-length(num, this) + var b; + if (this.length > num.length) + b = num; + else + b = this; + + for (var i = 0; i < b.length; i++) + this.words[i] = this.words[i] & num.words[i]; + + this.length = b.length; + + return this.strip(); +}; + + +// And `num` with `this` +BN.prototype.and = function and(num) { + if (this.length > num.length) + return this.clone().iand(num); + else + return num.clone().iand(this); +}; + + +// Xor `num` with `this` in-place +BN.prototype.ixor = function ixor(num) { + this.sign = this.sign || num.sign; + + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - d3_class(d3_Set, { - has: d3_map_has, - add: function(key) { - this._[d3_map_escape(key += "")] = true; - return key; - }, - remove: d3_map_remove, - values: d3_map_keys, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key)); - } - }); - d3.behavior = {}; - function d3_identity(d) { - return d; + + for (var i = 0; i < b.length; i++) + this.words[i] = a.words[i] ^ b.words[i]; + + if (this !== a) + for (; i < a.length; i++) + this.words[i] = a.words[i]; + + this.length = a.length; + + return this.strip(); +}; + + +// Xor `num` with `this` +BN.prototype.xor = function xor(num) { + if (this.length > num.length) + return this.clone().ixor(num); + else + return num.clone().ixor(this); +}; + + +// Set `bit` of `this` +BN.prototype.setn = function setn(bit, val) { + assert(typeof bit === 'number' && bit >= 0); + + var off = (bit / 26) | 0; + var wbit = bit % 26; + + while (this.length <= off) + this.words[this.length++] = 0; + + if (val) + this.words[off] = this.words[off] | (1 << wbit); + else + this.words[off] = this.words[off] & ~(1 << wbit); + + return this.strip(); +}; + + +// Add `num` to `this` in-place +BN.prototype.iadd = function iadd(num) { + // negative + positive + if (this.sign && !num.sign) { + this.sign = false; + var r = this.isub(num); + this.sign = !this.sign; + return this._normSign(); + + // positive + negative + } else if (!this.sign && num.sign) { + num.sign = false; + var r = this.isub(num); + num.sign = true; + return r._normSign(); } - d3.rebind = function(target, source) { - var i = 1, n = arguments.length, method; - while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); - return target; - }; - function d3_rebind(target, source, method) { - return function() { - var value = method.apply(source, arguments); - return value === source ? target : value; - }; + + // a.length > b.length + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; } - function d3_vendorSymbol(object, name) { - if (name in object) return name; - name = name.charAt(0).toUpperCase() + name.slice(1); - for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { - var prefixName = d3_vendorPrefixes[i] + name; - if (prefixName in object) return prefixName; - } + + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] + b.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; } - var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; - function d3_noop() {} - d3.dispatch = function() { - var dispatch = new d3_dispatch(), i = -1, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - return dispatch; - }; - function d3_dispatch() {} - d3_dispatch.prototype.on = function(type, listener) { - var i = type.indexOf("."), name = ""; - if (i >= 0) { - name = type.slice(i + 1); - type = type.slice(0, i); - } - if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); - if (arguments.length === 2) { - if (listener == null) for (type in this) { - if (this.hasOwnProperty(type)) this[type].on(name, null); - } - return this; - } - }; - function d3_dispatch_event(dispatch) { - var listeners = [], listenerByName = new d3_Map(); - function event() { - var z = listeners, i = -1, n = z.length, l; - while (++i < n) if (l = z[i].on) l.apply(this, arguments); - return dispatch; - } - event.on = function(name, listener) { - var l = listenerByName.get(name), i; - if (arguments.length < 2) return l && l.on; - if (l) { - l.on = null; - listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); - listenerByName.remove(name); - } - if (listener) listeners.push(listenerByName.set(name, { - on: listener - })); - return dispatch; - }; - return event; + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + this.words[i] = r & 0x3ffffff; + carry = r >>> 26; } - d3.event = null; - function d3_eventPreventDefault() { - d3.event.preventDefault(); + + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + // Copy the rest of the words + } else if (a !== this) { + for (; i < a.length; i++) + this.words[i] = a.words[i]; } - function d3_eventSource() { - var e = d3.event, s; - while (s = e.sourceEvent) e = s; - return e; + + return this; +}; + +// Add `num` to `this` +BN.prototype.add = function add(num) { + if (num.sign && !this.sign) { + num.sign = false; + var res = this.sub(num); + num.sign = true; + return res; + } else if (!num.sign && this.sign) { + this.sign = false; + var res = num.sub(this); + this.sign = true; + return res; } - function d3_eventDispatch(target) { - var dispatch = new d3_dispatch(), i = 0, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - dispatch.of = function(thiz, argumentz) { - return function(e1) { - try { - var e0 = e1.sourceEvent = d3.event; - e1.target = target; - d3.event = e1; - dispatch[e1.type].apply(thiz, argumentz); - } finally { - d3.event = e0; - } - }; - }; - return dispatch; + + if (this.length > num.length) + return this.clone().iadd(num); + else + return num.clone().iadd(this); +}; + +// Subtract `num` from `this` in-place +BN.prototype.isub = function isub(num) { + // this - (-num) = this + num + if (num.sign) { + num.sign = false; + var r = this.iadd(num); + num.sign = true; + return r._normSign(); + + // -this - num = -(this + num) + } else if (this.sign) { + this.sign = false; + this.iadd(num); + this.sign = true; + return this._normSign(); } - d3.requote = function(s) { - return s.replace(d3_requote_re, "\\$&"); - }; - var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; - var d3_subclass = {}.__proto__ ? function(object, prototype) { - object.__proto__ = prototype; - } : function(object, prototype) { - for (var property in prototype) object[property] = prototype[property]; - }; - function d3_selection(groups) { - d3_subclass(groups, d3_selectionPrototype); - return groups; + + // At this point both numbers are positive + var cmp = this.cmp(num); + + // Optimization - zeroify + if (cmp === 0) { + this.sign = false; + this.length = 1; + this.words[0] = 0; + return this; } - var d3_select = function(s, n) { - return n.querySelector(s); - }, d3_selectAll = function(s, n) { - return n.querySelectorAll(s); - }, d3_selectMatches = function(n, s) { - var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; - d3_selectMatches = function(n, s) { - return d3_selectMatcher.call(n, s); - }; - return d3_selectMatches(n, s); - }; - if (typeof Sizzle === "function") { - d3_select = function(s, n) { - return Sizzle(s, n)[0] || null; - }; - d3_selectAll = Sizzle; - d3_selectMatches = Sizzle.matchesSelector; + + // a > b + var a; + var b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; } - d3.selection = function() { - return d3.select(d3_document.documentElement); - }; - var d3_selectionPrototype = d3.selection.prototype = []; - d3_selectionPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, group, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(subnode = selector.call(node, node.__data__, i, j)); - if (subnode && "__data__" in node) subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selector(selector) { - return typeof selector === "function" ? selector : function() { - return d3_select(selector, this); - }; + + var carry = 0; + for (var i = 0; i < b.length; i++) { + var r = a.words[i] - b.words[i] + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; } - d3_selectionPrototype.selectAll = function(selector) { - var subgroups = [], subgroup, node; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); - subgroup.parentNode = node; - } + for (; carry !== 0 && i < a.length; i++) { + var r = a.words[i] + carry; + carry = r >> 26; + this.words[i] = r & 0x3ffffff; + } + + // Copy rest of the words + if (carry === 0 && i < a.length && a !== this) + for (; i < a.length; i++) + this.words[i] = a.words[i]; + this.length = Math.max(this.length, i); + + if (a !== this) + this.sign = true; + + return this.strip(); +}; + +// Subtract `num` from `this` +BN.prototype.sub = function sub(num) { + return this.clone().isub(num); +}; + +/* +// NOTE: This could be potentionally used to generate loop-less multiplications +function _genCombMulTo(alen, blen) { + var len = alen + blen - 1; + var src = [ + 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + + 'mask = 0x3ffffff, shift = 0x4000000;', + 'out.length = ' + len + ';' + ]; + for (var k = 0; k < len; k++) { + var minJ = Math.max(0, k - alen + 1); + var maxJ = Math.min(k, blen - 1); + + for (var j = minJ; j <= maxJ; j++) { + var i = k - j; + var mul = 'a[' + i + '] * b[' + j + ']'; + + if (j === minJ) { + src.push('w = ' + mul + ' + c;'); + src.push('c = (w / shift) | 0;'); + } else { + src.push('w += ' + mul + ';'); + src.push('c += (w / shift) | 0;'); } + src.push('w &= mask;'); } - return d3_selection(subgroups); - }; - function d3_selection_selectorAll(selector) { - return typeof selector === "function" ? selector : function() { - return d3_selectAll(selector, this); - }; + src.push('o[' + k + '] = w;'); } - var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; - var d3_nsPrefix = { - svg: "http://www.w3.org/2000/svg", - xhtml: d3_nsXhtml, - xlink: "http://www.w3.org/1999/xlink", - xml: "http://www.w3.org/XML/1998/namespace", - xmlns: "http://www.w3.org/2000/xmlns/" - }; - d3.ns = { - prefix: d3_nsPrefix, - qualify: function(name) { - var i = name.indexOf(":"), prefix = name; - if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); - return d3_nsPrefix.hasOwnProperty(prefix) ? { - space: d3_nsPrefix[prefix], - local: name - } : name; - } - }; - d3_selectionPrototype.attr = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(); - name = d3.ns.qualify(name); - return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); - } - for (value in name) this.each(d3_selection_attr(value, name[value])); - return this; - } - return this.each(d3_selection_attr(name, value)); - }; - function d3_selection_attr(name, value) { - name = d3.ns.qualify(name); - function attrNull() { - this.removeAttribute(name); - } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); - } - function attrConstant() { - this.setAttribute(name, value); - } - function attrConstantNS() { - this.setAttributeNS(name.space, name.local, value); - } - function attrFunction() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); - } - function attrFunctionNS() { - var x = value.apply(this, arguments); - if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + src.push('if (c !== 0) {', + ' o[' + k + '] = c;', + ' out.length++;', + '}', + 'return out;'); + + return src.join('\n'); +} +*/ + +BN.prototype._smallMulTo = function _smallMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; + + var carry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = carry >>> 26; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; } - return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; + out.words[k] = rword; + carry = ncarry; } - function d3_collapse(s) { - return s.trim().replace(/\s+/g, " "); + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; } - d3_selectionPrototype.classed = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") { - var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; - if (value = node.classList) { - while (++i < n) if (!value.contains(name[i])) return false; - } else { - value = node.getAttribute("class"); - while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; - } - return true; - } - for (value in name) this.each(d3_selection_classed(value, name[value])); - return this; + + return out.strip(); +}; + +BN.prototype._bigMulTo = function _bigMulTo(num, out) { + out.sign = num.sign !== this.sign; + out.length = this.length + num.length; + + var carry = 0; + var hncarry = 0; + for (var k = 0; k < out.length - 1; k++) { + // Sum all words with the same `i + j = k` and accumulate `ncarry`, + // note that ncarry could be >= 0x3ffffff + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 0x3ffffff; + var maxJ = Math.min(k, num.length - 1); + for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + + var lo = r & 0x3ffffff; + ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; + lo = (lo + rword) | 0; + rword = lo & 0x3ffffff; + ncarry = (ncarry + (lo >>> 26)) | 0; + + hncarry += ncarry >>> 26; + ncarry &= 0x3ffffff; } - return this.each(d3_selection_classed(name, value)); - }; - function d3_selection_classedRe(name) { - return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); - } - function d3_selection_classes(name) { - return (name + "").trim().split(/^|\s+/); + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; } - function d3_selection_classed(name, value) { - name = d3_selection_classes(name).map(d3_selection_classedName); - var n = name.length; - function classedConstant() { - var i = -1; - while (++i < n) name[i](this, value); - } - function classedFunction() { - var i = -1, x = value.apply(this, arguments); - while (++i < n) name[i](this, x); - } - return typeof value === "function" ? classedFunction : classedConstant; + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; } - function d3_selection_classedName(name) { - var re = d3_selection_classedRe(name); - return function(node, value) { - if (c = node.classList) return value ? c.add(name) : c.remove(name); - var c = node.getAttribute("class") || ""; - if (value) { - re.lastIndex = 0; - if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); - } else { - node.setAttribute("class", d3_collapse(c.replace(re, " "))); - } - }; + + return out.strip(); +}; + +BN.prototype.mulTo = function mulTo(num, out) { + var res; + if (this.length + num.length < 63) + res = this._smallMulTo(num, out); + else + res = this._bigMulTo(num, out); + return res; +}; + +// Multiply `this` by `num` +BN.prototype.mul = function mul(num) { + var out = new BN(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); +}; + +// In-place Multiplication +BN.prototype.imul = function imul(num) { + if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { + this.words[0] = 0; + this.length = 1; + return this; } - d3_selectionPrototype.style = function(name, value, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); - return this; - } - if (n < 2) { - var node = this.node(); - return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); - } - priority = ""; - } - return this.each(d3_selection_style(name, value, priority)); - }; - function d3_selection_style(name, value, priority) { - function styleNull() { - this.style.removeProperty(name); - } - function styleConstant() { - this.style.setProperty(name, value, priority); - } - function styleFunction() { - var x = value.apply(this, arguments); - if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + + var tlen = this.length; + var nlen = num.length; + + this.sign = num.sign !== this.sign; + this.length = this.length + num.length; + this.words[this.length - 1] = 0; + + for (var k = this.length - 2; k >= 0; k--) { + // Sum all words with the same `i + j = k` and accumulate `carry`, + // note that carry could be >= 0x3ffffff + var carry = 0; + var rword = 0; + var maxJ = Math.min(k, nlen - 1); + for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { + var i = k - j; + var a = this.words[i]; + var b = num.words[j]; + var r = a * b; + + var lo = r & 0x3ffffff; + carry += (r / 0x4000000) | 0; + lo += rword; + rword = lo & 0x3ffffff; + carry += lo >>> 26; } - return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; + this.words[k] = rword; + this.words[k + 1] += carry; + carry = 0; } - d3_selectionPrototype.property = function(name, value) { - if (arguments.length < 2) { - if (typeof name === "string") return this.node()[name]; - for (value in name) this.each(d3_selection_property(value, name[value])); - return this; - } - return this.each(d3_selection_property(name, value)); - }; - function d3_selection_property(name, value) { - function propertyNull() { - delete this[name]; - } - function propertyConstant() { - this[name] = value; - } - function propertyFunction() { - var x = value.apply(this, arguments); - if (x == null) delete this[name]; else this[name] = x; - } - return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; + + // Propagate overflows + var carry = 0; + for (var i = 1; i < this.length; i++) { + var w = this.words[i] + carry; + this.words[i] = w & 0x3ffffff; + carry = w >>> 26; } - d3_selectionPrototype.text = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.textContent = v == null ? "" : v; - } : value == null ? function() { - this.textContent = ""; - } : function() { - this.textContent = value; - }) : this.node().textContent; - }; - d3_selectionPrototype.html = function(value) { - return arguments.length ? this.each(typeof value === "function" ? function() { - var v = value.apply(this, arguments); - this.innerHTML = v == null ? "" : v; - } : value == null ? function() { - this.innerHTML = ""; - } : function() { - this.innerHTML = value; - }) : this.node().innerHTML; - }; - d3_selectionPrototype.append = function(name) { - name = d3_selection_creator(name); - return this.select(function() { - return this.appendChild(name.apply(this, arguments)); - }); - }; - function d3_selection_creator(name) { - function create() { - var document = this.ownerDocument, namespace = this.namespaceURI; - return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); - } - function createNS() { - return this.ownerDocument.createElementNS(name.space, name.local); - } - return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; + + return this.strip(); +}; + +BN.prototype.imuln = function imuln(num) { + assert(typeof num === 'number'); + + // Carry + var carry = 0; + for (var i = 0; i < this.length; i++) { + var w = this.words[i] * num; + var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); + carry >>= 26; + carry += (w / 0x4000000) | 0; + // NOTE: lo is 27bit maximum + carry += lo >>> 26; + this.words[i] = lo & 0x3ffffff; } - d3_selectionPrototype.insert = function(name, before) { - name = d3_selection_creator(name); - before = d3_selection_selector(before); - return this.select(function() { - return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); - }); - }; - d3_selectionPrototype.remove = function() { - return this.each(d3_selectionRemove); - }; - function d3_selectionRemove() { - var parent = this.parentNode; - if (parent) parent.removeChild(this); + + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - d3_selectionPrototype.data = function(value, key) { - var i = -1, n = this.length, group, node; - if (!arguments.length) { - value = new Array(n = (group = this[0]).length); - while (++i < n) { - if (node = group[i]) { - value[i] = node.__data__; - } - } - return value; - } - function bind(group, groupData) { - var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; - if (key) { - var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; - for (i = -1; ++i < n; ) { - if (node = group[i]) { - if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { - exitNodes[i] = node; - } else { - nodeByKeyValue.set(keyValue, node); - } - keyValues[i] = keyValue; - } - } - for (i = -1; ++i < m; ) { - if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { - enterNodes[i] = d3_selection_dataNode(nodeData); - } else if (node !== true) { - updateNodes[i] = node; - node.__data__ = nodeData; - } - nodeByKeyValue.set(keyValue, true); - } - for (i = -1; ++i < n; ) { - if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { - exitNodes[i] = group[i]; - } - } - } else { - for (i = -1; ++i < n0; ) { - node = group[i]; - nodeData = groupData[i]; - if (node) { - node.__data__ = nodeData; - updateNodes[i] = node; - } else { - enterNodes[i] = d3_selection_dataNode(nodeData); - } - } - for (;i < m; ++i) { - enterNodes[i] = d3_selection_dataNode(groupData[i]); - } - for (;i < n; ++i) { - exitNodes[i] = group[i]; - } - } - enterNodes.update = updateNodes; - enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; - enter.push(enterNodes); - update.push(updateNodes); - exit.push(exitNodes); + + return this; +}; + +BN.prototype.muln = function muln(num) { + return this.clone().imuln(num); +}; + +// `this` * `this` +BN.prototype.sqr = function sqr() { + return this.mul(this); +}; + +// `this` * `this` in-place +BN.prototype.isqr = function isqr() { + return this.mul(this); +}; + +// Shift-left in-place +BN.prototype.ishln = function ishln(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); + + if (r !== 0) { + var carry = 0; + for (var i = 0; i < this.length; i++) { + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] - newCarry) << r; + this.words[i] = c | carry; + carry = newCarry >>> (26 - r); } - var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); - if (typeof value === "function") { - while (++i < n) { - bind(group = this[i], value.call(group, group.parentNode.__data__, i)); - } - } else { - while (++i < n) { - bind(group = this[i], value); - } + if (carry) { + this.words[i] = carry; + this.length++; } - update.enter = function() { - return enter; - }; - update.exit = function() { - return exit; - }; - return update; - }; - function d3_selection_dataNode(data) { - return { - __data__: data - }; } - d3_selectionPrototype.datum = function(value) { - return arguments.length ? this.property("__data__", value) : this.property("__data__"); - }; - d3_selectionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_filter(selector) { - return function() { - return d3_selectMatches(this, selector); - }; + + if (s !== 0) { + for (var i = this.length - 1; i >= 0; i--) + this.words[i + s] = this.words[i]; + for (var i = 0; i < s; i++) + this.words[i] = 0; + this.length += s; } - d3_selectionPrototype.order = function() { - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { - if (node = group[i]) { - if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); - next = node; - } - } - } - return this; - }; - d3_selectionPrototype.sort = function(comparator) { - comparator = d3_selection_sortComparator.apply(this, arguments); - for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); - return this.order(); - }; - function d3_selection_sortComparator(comparator) { - if (!arguments.length) comparator = d3_ascending; - return function(a, b) { - return a && b ? comparator(a.__data__, b.__data__) : !a - !b; - }; + + return this.strip(); +}; + +// Shift-right in-place +// NOTE: `hint` is a lowest bit before trailing zeroes +// NOTE: if `extended` is present - it will be filled with destroyed bits +BN.prototype.ishrn = function ishrn(bits, hint, extended) { + assert(typeof bits === 'number' && bits >= 0); + var h; + if (hint) + h = (hint - (hint % 26)) / 26; + else + h = 0; + + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + var maskedWords = extended; + + h -= s; + h = Math.max(0, h); + + // Extended mode, copy masked part + if (maskedWords) { + for (var i = 0; i < s; i++) + maskedWords.words[i] = this.words[i]; + maskedWords.length = s; } - d3_selectionPrototype.each = function(callback) { - return d3_selection_each(this, function(node, i, j) { - callback.call(node, node.__data__, i, j); - }); - }; - function d3_selection_each(groups, callback) { - for (var j = 0, m = groups.length; j < m; j++) { - for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { - if (node = group[i]) callback(node, i, j); - } + + if (s === 0) { + // No-op, we should not move anything at all + } else if (this.length > s) { + this.length -= s; + for (var i = 0; i < this.length; i++) + this.words[i] = this.words[i + s]; + } else { + this.words[0] = 0; + this.length = 1; + } + + var carry = 0; + for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { + var word = this.words[i]; + this.words[i] = (carry << (26 - r)) | (word >>> r); + carry = word & mask; + } + + // Push carried bits as a mask + if (maskedWords && carry !== 0) + maskedWords.words[maskedWords.length++] = carry; + + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + + this.strip(); + + return this; +}; + +// Shift-left +BN.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); +}; + +// Shift-right +BN.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); +}; + +// Test if n bit is set +BN.prototype.testn = function testn(bit) { + assert(typeof bit === 'number' && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + return false; + } + + // Check bit and return + var w = this.words[s]; + + return !!(w & q); +}; + +// Return only lowers bits of number (in-place) +BN.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === 'number' && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + + assert(!this.sign, 'imaskn works only with positive numbers'); + + if (r !== 0) + s++; + this.length = Math.min(s, this.length); + + if (r !== 0) { + var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); + this.words[this.length - 1] &= mask; + } + + return this.strip(); +}; + +// Return only lowers bits of number +BN.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); +}; + +// Add plain number `num` to `this` +BN.prototype.iaddn = function iaddn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.isubn(-num); + + // Possible sign change + if (this.sign) { + if (this.length === 1 && this.words[0] < num) { + this.words[0] = num - this.words[0]; + this.sign = false; + return this; } - return groups; + + this.sign = false; + this.isubn(num); + this.sign = true; + return this; } - d3_selectionPrototype.call = function(callback) { - var args = d3_array(arguments); - callback.apply(args[0] = this, args); + + // Add without checks + return this._iaddn(num); +}; + +BN.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + + // Carry + for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { + this.words[i] -= 0x4000000; + if (i === this.length - 1) + this.words[i + 1] = 1; + else + this.words[i + 1]++; + } + this.length = Math.max(this.length, i + 1); + + return this; +}; + +// Subtract plain number `num` from `this` +BN.prototype.isubn = function isubn(num) { + assert(typeof num === 'number'); + if (num < 0) + return this.iaddn(-num); + + if (this.sign) { + this.sign = false; + this.iaddn(num); + this.sign = true; return this; - }; - d3_selectionPrototype.empty = function() { - return !this.node(); - }; - d3_selectionPrototype.node = function() { - for (var j = 0, m = this.length; j < m; j++) { - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - var node = group[i]; - if (node) return node; - } - } - return null; - }; - d3_selectionPrototype.size = function() { - var n = 0; - d3_selection_each(this, function() { - ++n; - }); - return n; - }; - function d3_selection_enter(selection) { - d3_subclass(selection, d3_selection_enterPrototype); - return selection; } - var d3_selection_enterPrototype = []; - d3.selection.enter = d3_selection_enter; - d3.selection.enter.prototype = d3_selection_enterPrototype; - d3_selection_enterPrototype.append = d3_selectionPrototype.append; - d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; - d3_selection_enterPrototype.node = d3_selectionPrototype.node; - d3_selection_enterPrototype.call = d3_selectionPrototype.call; - d3_selection_enterPrototype.size = d3_selectionPrototype.size; - d3_selection_enterPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, upgroup, group, node; - for (var j = -1, m = this.length; ++j < m; ) { - upgroup = (group = this[j]).update; - subgroups.push(subgroup = []); - subgroup.parentNode = group.parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); - subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - d3_selection_enterPrototype.insert = function(name, before) { - if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); - return d3_selectionPrototype.insert.call(this, name, before); - }; - function d3_selection_enterInsertBefore(enter) { - var i0, j0; - return function(d, i, j) { - var group = enter[j].update, n = group.length, node; - if (j != j0) j0 = j, i0 = 0; - if (i >= i0) i0 = i + 1; - while (!(node = group[i0]) && ++i0 < n) ; - return node; - }; + + this.words[0] -= num; + + // Carry + for (var i = 0; i < this.length && this.words[i] < 0; i++) { + this.words[i] += 0x4000000; + this.words[i + 1] -= 1; } - d3.select = function(node) { - var group; - if (typeof node === "string") { - group = [ d3_select(node, d3_document) ]; - group.parentNode = d3_document.documentElement; - } else { - group = [ node ]; - group.parentNode = d3_documentElement(node); - } - return d3_selection([ group ]); - }; - d3.selectAll = function(nodes) { - var group; - if (typeof nodes === "string") { - group = d3_array(d3_selectAll(nodes, d3_document)); - group.parentNode = d3_document.documentElement; - } else { - group = d3_array(nodes); - group.parentNode = null; - } - return d3_selection([ group ]); - }; - d3_selectionPrototype.on = function(type, listener, capture) { - var n = arguments.length; - if (n < 3) { - if (typeof type !== "string") { - if (n < 2) listener = false; - for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); - return this; - } - if (n < 2) return (n = this.node()["__on" + type]) && n._; - capture = false; - } - return this.each(d3_selection_on(type, listener, capture)); - }; - function d3_selection_on(type, listener, capture) { - var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; - if (i > 0) type = type.slice(0, i); - var filter = d3_selection_onFilters.get(type); - if (filter) type = filter, wrap = d3_selection_onFilter; - function onRemove() { - var l = this[name]; - if (l) { - this.removeEventListener(type, l, l.$); - delete this[name]; - } - } - function onAdd() { - var l = wrap(listener, d3_array(arguments)); - onRemove.call(this); - this.addEventListener(type, this[name] = l, l.$ = capture); - l._ = listener; - } - function removeAll() { - var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; - for (var name in this) { - if (match = name.match(re)) { - var l = this[name]; - this.removeEventListener(match[1], l, l.$); - delete this[name]; - } - } - } - return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; + + return this.strip(); +}; + +BN.prototype.addn = function addn(num) { + return this.clone().iaddn(num); +}; + +BN.prototype.subn = function subn(num) { + return this.clone().isubn(num); +}; + +BN.prototype.iabs = function iabs() { + this.sign = false; + + return this; +}; + +BN.prototype.abs = function abs() { + return this.clone().iabs(); +}; + +BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + // Bigger storage is needed + var len = num.length + shift; + var i; + if (this.words.length < len) { + var t = new Array(len); + for (var i = 0; i < this.length; i++) + t[i] = this.words[i]; + this.words = t; + } else { + i = this.length; } - var d3_selection_onFilters = d3.map({ - mouseenter: "mouseover", - mouseleave: "mouseout" - }); - if (d3_document) { - d3_selection_onFilters.forEach(function(k) { - if ("on" + k in d3_document) d3_selection_onFilters.remove(k); - }); + + // Zeroify rest + this.length = Math.max(this.length, len); + for (; i < this.length; i++) + this.words[i] = 0; + + var carry = 0; + for (var i = 0; i < num.length; i++) { + var w = this.words[i + shift] + carry; + var right = num.words[i] * mul; + w -= right & 0x3ffffff; + carry = (w >> 26) - ((right / 0x4000000) | 0); + this.words[i + shift] = w & 0x3ffffff; } - function d3_selection_onListener(listener, argumentz) { - return function(e) { - var o = d3.event; - d3.event = e; - argumentz[0] = this.__data__; - try { - listener.apply(this, argumentz); - } finally { - d3.event = o; - } - }; + for (; i < this.length - shift; i++) { + var w = this.words[i + shift] + carry; + carry = w >> 26; + this.words[i + shift] = w & 0x3ffffff; } - function d3_selection_onFilter(listener, argumentz) { - var l = d3_selection_onListener(listener, argumentz); - return function(e) { - var target = this, related = e.relatedTarget; - if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { - l.call(target, e); - } - }; + + if (carry === 0) + return this.strip(); + + // Subtraction overflow + assert(carry === -1); + carry = 0; + for (var i = 0; i < this.length; i++) { + var w = -this.words[i] + carry; + carry = w >> 26; + this.words[i] = w & 0x3ffffff; } - var d3_event_dragSelect, d3_event_dragId = 0; - function d3_event_dragSuppress(node) { - var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); - if (d3_event_dragSelect == null) { - d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); - } - if (d3_event_dragSelect) { - var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; - style[d3_event_dragSelect] = "none"; - } - return function(suppressClick) { - w.on(name, null); - if (d3_event_dragSelect) style[d3_event_dragSelect] = select; - if (suppressClick) { - var off = function() { - w.on(click, null); - }; - w.on(click, function() { - d3_eventPreventDefault(); - off(); - }, true); - setTimeout(off, 0); - } - }; + this.sign = true; + + return this.strip(); +}; + +BN.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + + var a = this.clone(); + var b = num; + + // Normalize + var bhi = b.words[b.length - 1]; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.shln(shift); + a.ishln(shift); + bhi = b.words[b.length - 1]; } - d3.mouse = function(container) { - return d3_mousePoint(container, d3_eventSource()); - }; - var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; - function d3_mousePoint(container, e) { - if (e.changedTouches) e = e.changedTouches[0]; - var svg = container.ownerSVGElement || container; - if (svg.createSVGPoint) { - var point = svg.createSVGPoint(); - if (d3_mouse_bug44083 < 0) { - var window = d3_window(container); - if (window.scrollX || window.scrollY) { - svg = d3.select("body").append("svg").style({ - position: "absolute", - top: 0, - left: 0, - margin: 0, - padding: 0, - border: "none" - }, "important"); - var ctm = svg[0][0].getScreenCTM(); - d3_mouse_bug44083 = !(ctm.f || ctm.e); - svg.remove(); - } - } - if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, - point.y = e.clientY; - point = point.matrixTransform(container.getScreenCTM().inverse()); - return [ point.x, point.y ]; + + // Initialize quotient + var m = a.length - b.length; + var q; + + if (mode !== 'mod') { + q = new BN(null); + q.length = m + 1; + q.words = new Array(q.length); + for (var i = 0; i < q.length; i++) + q.words[i] = 0; + } + + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (!diff.sign) { + a = diff; + if (q) + q.words[m] = 1; + } + + for (var j = m - 1; j >= 0; j--) { + var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1]; + + // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max + // (0x7ffffff) + qj = Math.min((qj / bhi) | 0, 0x3ffffff); + + a._ishlnsubmul(b, qj, j); + while (a.sign) { + qj--; + a.sign = false; + a._ishlnsubmul(b, 1, j); + if (a.cmpn(0) !== 0) + a.sign = !a.sign; } - var rect = container.getBoundingClientRect(); - return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + if (q) + q.words[j] = qj; } - d3.touch = function(container, touches, identifier) { - if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; - if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { - if ((touch = touches[i]).identifier === identifier) { - return d3_mousePoint(container, touch); + if (q) + q.strip(); + a.strip(); + + // Denormalize + if (mode !== 'div' && shift !== 0) + a.ishrn(shift); + return { div: q ? q : null, mod: a }; +}; + +BN.prototype.divmod = function divmod(num, mode) { + assert(num.cmpn(0) !== 0); + + if (this.sign && !num.sign) { + var res = this.neg().divmod(num, mode); + var div; + var mod; + if (mode !== 'mod') + div = res.div.neg(); + if (mode !== 'div') + mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); + return { + div: div, + mod: mod + }; + } else if (!this.sign && num.sign) { + var res = this.divmod(num.neg(), mode); + var div; + if (mode !== 'mod') + div = res.div.neg(); + return { div: div, mod: res.mod }; + } else if (this.sign && num.sign) { + return this.neg().divmod(num.neg(), mode); + } + + // Both numbers are positive at this point + + // Strip both numbers to approximate shift value + if (num.length > this.length || this.cmp(num) < 0) + return { div: new BN(0), mod: this }; + + // Very short reduction + if (num.length === 1) { + if (mode === 'div') + return { div: this.divn(num.words[0]), mod: null }; + else if (mode === 'mod') + return { div: null, mod: new BN(this.modn(num.words[0])) }; + return { + div: this.divn(num.words[0]), + mod: new BN(this.modn(num.words[0])) + }; + } + + return this._wordDiv(num, mode); +}; + +// Find `this` / `num` +BN.prototype.div = function div(num) { + return this.divmod(num, 'div').div; +}; + +// Find `this` % `num` +BN.prototype.mod = function mod(num) { + return this.divmod(num, 'mod').mod; +}; + +// Find Round(`this` / `num`) +BN.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + + // Fast case - exact division + if (dm.mod.cmpn(0) === 0) + return dm.div; + + var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; + + var half = num.shrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + + // Round down + if (cmp < 0 || r2 === 1 && cmp === 0) + return dm.div; + + // Round up + return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); +}; + +BN.prototype.modn = function modn(num) { + assert(num <= 0x3ffffff); + var p = (1 << 26) % num; + + var acc = 0; + for (var i = this.length - 1; i >= 0; i--) + acc = (p * acc + this.words[i]) % num; + + return acc; +}; + +// In-place division by number +BN.prototype.idivn = function idivn(num) { + assert(num <= 0x3ffffff); + + var carry = 0; + for (var i = this.length - 1; i >= 0; i--) { + var w = this.words[i] + carry * 0x4000000; + this.words[i] = (w / num) | 0; + carry = w % num; + } + + return this.strip(); +}; + +BN.prototype.divn = function divn(num) { + return this.clone().idivn(num); +}; + +BN.prototype.egcd = function egcd(p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); + + var x = this; + var y = p.clone(); + + if (x.sign) + x = x.mod(p); + else + x = x.clone(); + + // A * x + B * y = x + var A = new BN(1); + var B = new BN(0); + + // C * x + D * y = y + var C = new BN(0); + var D = new BN(1); + + var g = 0; + + while (x.isEven() && y.isEven()) { + x.ishrn(1); + y.ishrn(1); + ++g; + } + + var yp = y.clone(); + var xp = x.clone(); + + while (x.cmpn(0) !== 0) { + while (x.isEven()) { + x.ishrn(1); + if (A.isEven() && B.isEven()) { + A.ishrn(1); + B.ishrn(1); + } else { + A.iadd(yp).ishrn(1); + B.isub(xp).ishrn(1); } } - }; - d3.behavior.drag = function() { - var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); - function drag() { - this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + + while (y.isEven()) { + y.ishrn(1); + if (C.isEven() && D.isEven()) { + C.ishrn(1); + D.ishrn(1); + } else { + C.iadd(yp).ishrn(1); + D.isub(xp).ishrn(1); + } } - function dragstart(id, position, subject, move, end) { - return function() { - var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); - if (origin) { - dragOffset = origin.apply(that, arguments); - dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; - } else { - dragOffset = [ 0, 0 ]; - } - dispatch({ - type: "dragstart" - }); - function moved() { - var position1 = position(parent, dragId), dx, dy; - if (!position1) return; - dx = position1[0] - position0[0]; - dy = position1[1] - position0[1]; - dragged |= dx | dy; - position0 = position1; - dispatch({ - type: "drag", - x: position1[0] + dragOffset[0], - y: position1[1] + dragOffset[1], - dx: dx, - dy: dy - }); - } - function ended() { - if (!position(parent, dragId)) return; - dragSubject.on(move + dragName, null).on(end + dragName, null); - dragRestore(dragged); - dispatch({ - type: "dragend" - }); - } - }; + + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); } - drag.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return drag; - }; - return d3.rebind(drag, event, "on"); - }; - function d3_behavior_dragTouchId() { - return d3.event.changedTouches[0].identifier; } - d3.touches = function(container, touches) { - if (arguments.length < 2) touches = d3_eventSource().touches; - return touches ? d3_array(touches).map(function(touch) { - var point = d3_mousePoint(container, touch); - point.identifier = touch.identifier; - return point; - }) : []; + + return { + a: C, + b: D, + gcd: y.ishln(g) }; - var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; - function d3_sgn(x) { - return x > 0 ? 1 : x < 0 ? -1 : 0; - } - function d3_cross2d(a, b, c) { - return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); +}; + +// This is reduced incarnation of the binary EEA +// above, designated to invert members of the +// _prime_ fields F(p) at a maximal speed +BN.prototype._invmp = function _invmp(p) { + assert(!p.sign); + assert(p.cmpn(0) !== 0); + + var a = this; + var b = p.clone(); + + if (a.sign) + a = a.mod(p); + else + a = a.clone(); + + var x1 = new BN(1); + var x2 = new BN(0); + + var delta = b.clone(); + + while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { + while (a.isEven()) { + a.ishrn(1); + if (x1.isEven()) + x1.ishrn(1); + else + x1.iadd(delta).ishrn(1); + } + while (b.isEven()) { + b.ishrn(1); + if (x2.isEven()) + x2.ishrn(1); + else + x2.iadd(delta).ishrn(1); + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } } - function d3_acos(x) { - return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + if (a.cmpn(1) === 0) + return x1; + else + return x2; +}; + +BN.prototype.gcd = function gcd(num) { + if (this.cmpn(0) === 0) + return num.clone(); + if (num.cmpn(0) === 0) + return this.clone(); + + var a = this.clone(); + var b = num.clone(); + a.sign = false; + b.sign = false; + + // Remove common factor of two + for (var shift = 0; a.isEven() && b.isEven(); shift++) { + a.ishrn(1); + b.ishrn(1); } - function d3_asin(x) { - return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + + do { + while (a.isEven()) + a.ishrn(1); + while (b.isEven()) + b.ishrn(1); + + var r = a.cmp(b); + if (r < 0) { + // Swap `a` and `b` to make `a` always bigger than `b` + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + + a.isub(b); + } while (true); + + return b.ishln(shift); +}; + +// Invert number in the field F(num) +BN.prototype.invm = function invm(num) { + return this.egcd(num).a.mod(num); +}; + +BN.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; +}; + +BN.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; +}; + +// And first word and num +BN.prototype.andln = function andln(num) { + return this.words[0] & num; +}; + +// Increment at the bit position in-line +BN.prototype.bincn = function bincn(bit) { + assert(typeof bit === 'number'); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + + // Fast case: bit is much higher than all existing words + if (this.length <= s) { + for (var i = this.length; i < s + 1; i++) + this.words[i] = 0; + this.words[s] |= q; + this.length = s + 1; + return this; } - function d3_sinh(x) { - return ((x = Math.exp(x)) - 1 / x) / 2; + + // Add bit and propagate, if needed + var carry = q; + for (var i = s; carry !== 0 && i < this.length; i++) { + var w = this.words[i]; + w += carry; + carry = w >>> 26; + w &= 0x3ffffff; + this.words[i] = w; } - function d3_cosh(x) { - return ((x = Math.exp(x)) + 1 / x) / 2; + if (carry !== 0) { + this.words[i] = carry; + this.length++; } - function d3_tanh(x) { - return ((x = Math.exp(2 * x)) - 1) / (x + 1); + return this; +}; + +BN.prototype.cmpn = function cmpn(num) { + var sign = num < 0; + if (sign) + num = -num; + + if (this.sign && !sign) + return -1; + else if (!this.sign && sign) + return 1; + + num &= 0x3ffffff; + this.strip(); + + var res; + if (this.length > 1) { + res = 1; + } else { + var w = this.words[0]; + res = w === num ? 0 : w < num ? -1 : 1; } - function d3_haversin(x) { - return (x = Math.sin(x / 2)) * x; + if (this.sign) + res = -res; + return res; +}; + +// Compare two numbers and return: +// 1 - if `this` > `num` +// 0 - if `this` == `num` +// -1 - if `this` < `num` +BN.prototype.cmp = function cmp(num) { + if (this.sign && !num.sign) + return -1; + else if (!this.sign && num.sign) + return 1; + + var res = this.ucmp(num); + if (this.sign) + return -res; + else + return res; +}; + +// Unsigned comparison +BN.prototype.ucmp = function ucmp(num) { + // At this point both numbers have the same sign + if (this.length > num.length) + return 1; + else if (this.length < num.length) + return -1; + + var res = 0; + for (var i = this.length - 1; i >= 0; i--) { + var a = this.words[i]; + var b = num.words[i]; + + if (a === b) + continue; + if (a < b) + res = -1; + else if (a > b) + res = 1; + break; } - var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; - d3.interpolateZoom = function(p0, p1) { - var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; - if (d2 < ε2) { - S = Math.log(w1 / w0) / ρ; - i = function(t) { - return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; - }; - } else { - var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); - S = (r1 - r0) / ρ; - i = function(t) { - var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); - return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; - }; - } - i.duration = S * 1e3; - return i; - }; - d3.behavior.zoom = function() { - var view = { - x: 0, - y: 0, - k: 1 - }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; - if (!d3_behavior_zoomWheel) { - d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); - }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return d3.event.wheelDelta; - }, "mousewheel") : (d3_behavior_zoomDelta = function() { - return -d3.event.detail; - }, "MozMousePixelScroll"); - } - function zoom(g) { - g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); - } - zoom.event = function(g) { - g.each(function() { - var dispatch = event.of(this, arguments), view1 = view; - if (d3_transitionInheritId) { - d3.select(this).transition().each("start.zoom", function() { - view = this.__chart__ || { - x: 0, - y: 0, - k: 1 - }; - zoomstarted(dispatch); - }).tween("zoom:zoom", function() { - var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); - return function(t) { - var l = i(t), k = dx / l[2]; - this.__chart__ = view = { - x: cx - l[0] * k, - y: cy - l[1] * k, - k: k - }; - zoomed(dispatch); - }; - }).each("interrupt.zoom", function() { - zoomended(dispatch); - }).each("end.zoom", function() { - zoomended(dispatch); - }); - } else { - this.__chart__ = view; - zoomstarted(dispatch); - zoomed(dispatch); - zoomended(dispatch); - } - }); - }; - zoom.translate = function(_) { - if (!arguments.length) return [ view.x, view.y ]; - view = { - x: +_[0], - y: +_[1], - k: view.k - }; - rescale(); - return zoom; - }; - zoom.scale = function(_) { - if (!arguments.length) return view.k; - view = { - x: view.x, - y: view.y, - k: null - }; - scaleTo(+_); - rescale(); - return zoom; - }; - zoom.scaleExtent = function(_) { - if (!arguments.length) return scaleExtent; - scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; - return zoom; - }; - zoom.center = function(_) { - if (!arguments.length) return center; - center = _ && [ +_[0], +_[1] ]; - return zoom; - }; - zoom.size = function(_) { - if (!arguments.length) return size; - size = _ && [ +_[0], +_[1] ]; - return zoom; - }; - zoom.duration = function(_) { - if (!arguments.length) return duration; - duration = +_; - return zoom; - }; - zoom.x = function(z) { - if (!arguments.length) return x1; - x1 = z; - x0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; - }; - zoom.y = function(z) { - if (!arguments.length) return y1; - y1 = z; - y0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom; - }; - function location(p) { - return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; - } - function point(l) { - return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; - } - function scaleTo(s) { - view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); - } - function translateTo(p, l) { - l = point(l); - view.x += p[0] - l[0]; - view.y += p[1] - l[1]; - } - function zoomTo(that, p, l, k) { - that.__chart__ = { - x: view.x, - y: view.y, - k: view.k - }; - scaleTo(Math.pow(2, k)); - translateTo(center0 = p, l); - that = d3.select(that); - if (duration > 0) that = that.transition().duration(duration); - that.call(zoom.event); - } - function rescale() { - if (x1) x1.domain(x0.range().map(function(x) { - return (x - view.x) / view.k; - }).map(x0.invert)); - if (y1) y1.domain(y0.range().map(function(y) { - return (y - view.y) / view.k; - }).map(y0.invert)); - } - function zoomstarted(dispatch) { - if (!zooming++) dispatch({ - type: "zoomstart" - }); - } - function zoomed(dispatch) { - rescale(); - dispatch({ - type: "zoom", - scale: view.k, - translate: [ view.x, view.y ] - }); - } - function zoomended(dispatch) { - if (!--zooming) dispatch({ - type: "zoomend" - }), center0 = null; - } - function mousedowned() { - var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); - d3_selection_interrupt.call(that); - zoomstarted(dispatch); - function moved() { - dragged = 1; - translateTo(d3.mouse(that), location0); - zoomed(dispatch); - } - function ended() { - subject.on(mousemove, null).on(mouseup, null); - dragRestore(dragged); - zoomended(dispatch); - } - } - function touchstarted() { - var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); - started(); - zoomstarted(dispatch); - subject.on(mousedown, null).on(touchstart, started); - function relocate() { - var touches = d3.touches(that); - scale0 = view.k; - touches.forEach(function(t) { - if (t.identifier in locations0) locations0[t.identifier] = location(t); - }); - return touches; - } - function started() { - var target = d3.event.target; - d3.select(target).on(touchmove, moved).on(touchend, ended); - targets.push(target); - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - locations0[changed[i].identifier] = null; - } - var touches = relocate(), now = Date.now(); - if (touches.length === 1) { - if (now - touchtime < 500) { - var p = touches[0]; - zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); - d3_eventPreventDefault(); - } - touchtime = now; - } else if (touches.length > 1) { - var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; - distance0 = dx * dx + dy * dy; - } - } - function moved() { - var touches = d3.touches(that), p0, l0, p1, l1; - d3_selection_interrupt.call(that); - for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { - p1 = touches[i]; - if (l1 = locations0[p1.identifier]) { - if (l0) break; - p0 = p1, l0 = l1; - } - } - if (l1) { - var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); - p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; - l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; - scaleTo(scale1 * scale0); - } - touchtime = null; - translateTo(p0, l0); - zoomed(dispatch); - } - function ended() { - if (d3.event.touches.length) { - var changed = d3.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - delete locations0[changed[i].identifier]; - } - for (var identifier in locations0) { - return void relocate(); - } - } - d3.selectAll(targets).on(zoomName, null); - subject.on(mousedown, mousedowned).on(touchstart, touchstarted); - dragRestore(); - zoomended(dispatch); - } - } - function mousewheeled() { - var dispatch = event.of(this, arguments); - if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), - translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); - mousewheelTimer = setTimeout(function() { - mousewheelTimer = null; - zoomended(dispatch); - }, 50); - d3_eventPreventDefault(); - scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); - translateTo(center0, translate0); - zoomed(dispatch); - } - function dblclicked() { - var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; - zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); - } - return d3.rebind(zoom, event, "on"); - }; - var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; - d3.color = d3_color; - function d3_color() {} - d3_color.prototype.toString = function() { - return this.rgb() + ""; - }; - d3.hsl = d3_hsl; - function d3_hsl(h, s, l) { - return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); + return res; +}; + +// +// A reduce context, could be using montgomery or something better, depending +// on the `m` itself. +// +BN.red = function red(num) { + return new Red(num); +}; + +BN.prototype.toRed = function toRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + assert(!this.sign, 'red works only with positives'); + return ctx.convertTo(this)._forceRed(ctx); +}; + +BN.prototype.fromRed = function fromRed() { + assert(this.red, 'fromRed works only with numbers in reduction context'); + return this.red.convertFrom(this); +}; + +BN.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; +}; + +BN.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, 'Already a number in reduction context'); + return this._forceRed(ctx); +}; + +BN.prototype.redAdd = function redAdd(num) { + assert(this.red, 'redAdd works only with red numbers'); + return this.red.add(this, num); +}; + +BN.prototype.redIAdd = function redIAdd(num) { + assert(this.red, 'redIAdd works only with red numbers'); + return this.red.iadd(this, num); +}; + +BN.prototype.redSub = function redSub(num) { + assert(this.red, 'redSub works only with red numbers'); + return this.red.sub(this, num); +}; + +BN.prototype.redISub = function redISub(num) { + assert(this.red, 'redISub works only with red numbers'); + return this.red.isub(this, num); +}; + +BN.prototype.redShl = function redShl(num) { + assert(this.red, 'redShl works only with red numbers'); + return this.red.shl(this, num); +}; + +BN.prototype.redMul = function redMul(num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.mul(this, num); +}; + +BN.prototype.redIMul = function redIMul(num) { + assert(this.red, 'redMul works only with red numbers'); + this.red._verify2(this, num); + return this.red.imul(this, num); +}; + +BN.prototype.redSqr = function redSqr() { + assert(this.red, 'redSqr works only with red numbers'); + this.red._verify1(this); + return this.red.sqr(this); +}; + +BN.prototype.redISqr = function redISqr() { + assert(this.red, 'redISqr works only with red numbers'); + this.red._verify1(this); + return this.red.isqr(this); +}; + +// Square root over p +BN.prototype.redSqrt = function redSqrt() { + assert(this.red, 'redSqrt works only with red numbers'); + this.red._verify1(this); + return this.red.sqrt(this); +}; + +BN.prototype.redInvm = function redInvm() { + assert(this.red, 'redInvm works only with red numbers'); + this.red._verify1(this); + return this.red.invm(this); +}; + +// Return negative clone of `this` % `red modulo` +BN.prototype.redNeg = function redNeg() { + assert(this.red, 'redNeg works only with red numbers'); + this.red._verify1(this); + return this.red.neg(this); +}; + +BN.prototype.redPow = function redPow(num) { + assert(this.red && !num.red, 'redPow(normalNum)'); + this.red._verify1(this); + return this.red.pow(this, num); +}; + +// Prime numbers with efficient reduction +var primes = { + k256: null, + p224: null, + p192: null, + p25519: null +}; + +// Pseudo-Mersenne prime +function MPrime(name, p) { + // P = 2 ^ N - K + this.name = name; + this.p = new BN(p, 16); + this.n = this.p.bitLength(); + this.k = new BN(1).ishln(this.n).isub(this.p); + + this.tmp = this._tmp(); +} + +MPrime.prototype._tmp = function _tmp() { + var tmp = new BN(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; +}; + +MPrime.prototype.ireduce = function ireduce(num) { + // Assumes that `num` is less than `P^2` + // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) + var r = num; + var rlen; + + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + } while (rlen > this.n); + + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + r.strip(); } - var d3_hslPrototype = d3_hsl.prototype = new d3_color(); - d3_hslPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, this.l / k); - }; - d3_hslPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, k * this.l); - }; - d3_hslPrototype.rgb = function() { - return d3_hsl_rgb(this.h, this.s, this.l); - }; - function d3_hsl_rgb(h, s, l) { - var m1, m2; - h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; - s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; - l = l < 0 ? 0 : l > 1 ? 1 : l; - m2 = l <= .5 ? l * (1 + s) : l + s - l * s; - m1 = 2 * l - m2; - function v(h) { - if (h > 360) h -= 360; else if (h < 0) h += 360; - if (h < 60) return m1 + (m2 - m1) * h / 60; - if (h < 180) return m2; - if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; - return m1; - } - function vv(h) { - return Math.round(v(h) * 255); - } - return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + + return r; +}; + +MPrime.prototype.split = function split(input, out) { + input.ishrn(this.n, 0, out); +}; + +MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); +}; + +function K256() { + MPrime.call( + this, + 'k256', + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); +} +inherits(K256, MPrime); + +K256.prototype.split = function split(input, output) { + // 256 = 9 * 26 + 22 + var mask = 0x3fffff; + + var outLen = Math.min(input.length, 9); + for (var i = 0; i < outLen; i++) + output.words[i] = input.words[i]; + output.length = outLen; + + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; } - d3.hcl = d3_hcl; - function d3_hcl(h, c, l) { - return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); + + // Shift by 9 limbs + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + + for (var i = 10; i < input.length; i++) { + var next = input.words[i]; + input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); + prev = next; } - var d3_hclPrototype = d3_hcl.prototype = new d3_color(); - d3_hclPrototype.brighter = function(k) { - return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); - }; - d3_hclPrototype.darker = function(k) { - return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); - }; - d3_hclPrototype.rgb = function() { - return d3_hcl_lab(this.h, this.c, this.l).rgb(); - }; - function d3_hcl_lab(h, c, l) { - if (isNaN(h)) h = 0; - if (isNaN(c)) c = 0; - return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + input.words[i - 10] = prev >>> 22; + input.length -= 9; +}; + +K256.prototype.imulK = function imulK(num) { + // K = 0x1000003d1 = [ 0x40, 0x3d1 ] + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + + // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 + var hi; + var lo = 0; + for (var i = 0; i < num.length; i++) { + var w = num.words[i]; + hi = w * 0x40; + lo += w * 0x3d1; + hi += (lo / 0x4000000) | 0; + lo &= 0x3ffffff; + + num.words[i] = lo; + + lo = hi; } - d3.lab = d3_lab; - function d3_lab(l, a, b) { - return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + + // Fast length reduction + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) + num.length--; } - var d3_lab_K = 18; - var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; - var d3_labPrototype = d3_lab.prototype = new d3_color(); - d3_labPrototype.brighter = function(k) { - return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.darker = function(k) { - return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.rgb = function() { - return d3_lab_rgb(this.l, this.a, this.b); - }; - function d3_lab_rgb(l, a, b) { - var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; - x = d3_lab_xyz(x) * d3_lab_X; - y = d3_lab_xyz(y) * d3_lab_Y; - z = d3_lab_xyz(z) * d3_lab_Z; - return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + return num; +}; + +function P224() { + MPrime.call( + this, + 'p224', + 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); +} +inherits(P224, MPrime); + +function P192() { + MPrime.call( + this, + 'p192', + 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); +} +inherits(P192, MPrime); + +function P25519() { + // 2 ^ 255 - 19 + MPrime.call( + this, + '25519', + '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); +} +inherits(P25519, MPrime); + +P25519.prototype.imulK = function imulK(num) { + // K = 0x13 + var carry = 0; + for (var i = 0; i < num.length; i++) { + var hi = num.words[i] * 0x13 + carry; + var lo = hi & 0x3ffffff; + hi >>>= 26; + + num.words[i] = lo; + carry = hi; } - function d3_lab_hcl(l, a, b) { - return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + if (carry !== 0) + num.words[num.length++] = carry; + return num; +}; + +// Exported mostly for testing purposes, use plain name instead +BN._prime = function prime(name) { + // Cached version of prime + if (primes[name]) + return primes[name]; + + var prime; + if (name === 'k256') + prime = new K256(); + else if (name === 'p224') + prime = new P224(); + else if (name === 'p192') + prime = new P192(); + else if (name === 'p25519') + prime = new P25519(); + else + throw new Error('Unknown prime ' + name); + primes[name] = prime; + + return prime; +}; + +// +// Base reduction engine +// +function Red(m) { + if (typeof m === 'string') { + var prime = BN._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + this.m = m; + this.prime = null; } - function d3_lab_xyz(x) { - return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; +} + +Red.prototype._verify1 = function _verify1(a) { + assert(!a.sign, 'red works only with positives'); + assert(a.red, 'red works only with red numbers'); +}; + +Red.prototype._verify2 = function _verify2(a, b) { + assert(!a.sign && !b.sign, 'red works only with positives'); + assert(a.red && a.red === b.red, + 'red works only with red numbers'); +}; + +Red.prototype.imod = function imod(a) { + if (this.prime) + return this.prime.ireduce(a)._forceRed(this); + return a.mod(this.m)._forceRed(this); +}; + +Red.prototype.neg = function neg(a) { + var r = a.clone(); + r.sign = !r.sign; + return r.iadd(this.m)._forceRed(this); +}; + +Red.prototype.add = function add(a, b) { + this._verify2(a, b); + + var res = a.add(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res._forceRed(this); +}; + +Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) + res.isub(this.m); + return res; +}; + +Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + + var res = a.sub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res._forceRed(this); +}; + +Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + + var res = a.isub(b); + if (res.cmpn(0) < 0) + res.iadd(this.m); + return res; +}; + +Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.shln(num)); +}; + +Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); +}; + +Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); +}; + +Red.prototype.isqr = function isqr(a) { + return this.imul(a, a); +}; + +Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); +}; + +Red.prototype.sqrt = function sqrt(a) { + if (a.cmpn(0) === 0) + return a.clone(); + + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + + // Fast case + if (mod3 === 3) { + var pow = this.m.add(new BN(1)).ishrn(2); + var r = this.pow(a, pow); + return r; } - function d3_xyz_lab(x) { - return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + + // Tonelli-Shanks algorithm (Totally unoptimized and slow) + // + // Find Q and S, that Q * 2 ^ S = (P - 1) + var q = this.m.subn(1); + var s = 0; + while (q.cmpn(0) !== 0 && q.andln(1) === 0) { + s++; + q.ishrn(1); } - function d3_xyz_rgb(r) { - return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + assert(q.cmpn(0) !== 0); + + var one = new BN(1).toRed(this); + var nOne = one.redNeg(); + + // Find quadratic non-residue + // NOTE: Max is such because of generalized Riemann hypothesis. + var lpow = this.m.subn(1).ishrn(1); + var z = this.m.bitLength(); + z = new BN(2 * z * z).toRed(this); + while (this.pow(z, lpow).cmp(nOne) !== 0) + z.redIAdd(nOne); + + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).ishrn(1)); + var t = this.pow(a, q); + var m = s; + while (t.cmp(one) !== 0) { + var tmp = t; + for (var i = 0; tmp.cmp(one) !== 0; i++) + tmp = tmp.redSqr(); + assert(i < m); + var b = this.pow(c, new BN(1).ishln(m - i - 1)); + + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; } - d3.rgb = d3_rgb; - function d3_rgb(r, g, b) { - return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + + return r; +}; + +Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.sign) { + inv.sign = false; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); } - function d3_rgbNumber(value) { - return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); +}; + +Red.prototype.pow = function pow(a, num) { + var w = []; + + if (num.cmpn(0) === 0) + return new BN(1); + + var q = num.clone(); + + while (q.cmpn(0) !== 0) { + w.push(q.andln(1)); + q.ishrn(1); } - function d3_rgbString(value) { - return d3_rgbNumber(value) + ""; + + // Skip leading zeroes + var res = a; + for (var i = 0; i < w.length; i++, res = this.sqr(res)) + if (w[i] !== 0) + break; + + if (++i < w.length) { + for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { + if (w[i] === 0) + continue; + res = this.mul(res, q); + } } - var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); - d3_rgbPrototype.brighter = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - var r = this.r, g = this.g, b = this.b, i = 30; - if (!r && !g && !b) return new d3_rgb(i, i, i); - if (r && r < i) r = i; - if (g && g < i) g = i; - if (b && b < i) b = i; - return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); - }; - d3_rgbPrototype.darker = function(k) { - k = Math.pow(.7, arguments.length ? k : 1); - return new d3_rgb(k * this.r, k * this.g, k * this.b); - }; - d3_rgbPrototype.hsl = function() { - return d3_rgb_hsl(this.r, this.g, this.b); - }; - d3_rgbPrototype.toString = function() { - return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); - }; - function d3_rgb_hex(v) { - return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + + return res; +}; + +Red.prototype.convertTo = function convertTo(num) { + var r = num.mod(this.m); + if (r === num) + return r.clone(); + else + return r; +}; + +Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; +}; + +// +// Montgomery method engine +// + +BN.mont = function mont(num) { + return new Mont(num); +}; + +function Mont(m) { + Red.call(this, m); + + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) + this.shift += 26 - (this.shift % 26); + this.r = new BN(1).ishln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv.sign = true; + this.minv = this.minv.mod(this.r); +} +inherits(Mont, Red); + +Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.shln(this.shift)); +}; + +Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; +}; + +Mont.prototype.imul = function imul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { + a.words[0] = 0; + a.length = 1; + return a; } - function d3_rgb_parse(format, rgb, hsl) { - var r = 0, g = 0, b = 0, m1, m2, color; - m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); - if (m1) { - m2 = m1[2].split(","); - switch (m1[1]) { - case "hsl": - { - return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); - } - case "rgb": - { - return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); - } - } - } - if (color = d3_rgb_names.get(format)) { - return rgb(color.r, color.g, color.b); + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); + + return res._forceRed(this); +}; + +Mont.prototype.mul = function mul(a, b) { + if (a.cmpn(0) === 0 || b.cmpn(0) === 0) + return new BN(0)._forceRed(this); + + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).ishrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) + res = u.isub(this.m); + else if (u.cmpn(0) < 0) + res = u.iadd(this.m); + + return res._forceRed(this); +}; + +Mont.prototype.invm = function invm(a) { + // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); +}; + +})(typeof module === 'undefined' || module, this); + +},{}],80:[function(require,module,exports){ +'use strict' + +var bnsign = require('./lib/bn-sign') + +module.exports = sign + +function sign(x) { + return bnsign(x[0]) * bnsign(x[1]) +} + +},{"./lib/bn-sign":71}],81:[function(require,module,exports){ +'use strict' + +var rationalize = require('./lib/rationalize') + +module.exports = sub + +function sub(a, b) { + return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) +} + +},{"./lib/rationalize":76}],82:[function(require,module,exports){ +'use strict' + +var bn2num = require('./lib/bn-to-num') +var ctz = require('./lib/ctz') + +module.exports = roundRat + +//Round a rational to the closest float +function roundRat(f) { + var a = f[0] + var b = f[1] + if(a.cmpn(0) === 0) { + return 0 + } + var h = a.divmod(b) + var iv = h.div + var x = bn2num(iv) + var ir = h.mod + if(ir.cmpn(0) === 0) { + return x + } + if(x) { + var s = ctz(x) + 4 + var y = bn2num(ir.shln(s).divRound(b)) + + // flip the sign of y if x is negative + if (x<0) { + y = -y; } - if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { - if (format.length === 4) { - r = (color & 3840) >> 4; - r = r >> 4 | r; - g = color & 240; - g = g >> 4 | g; - b = color & 15; - b = b << 4 | b; - } else if (format.length === 7) { - r = (color & 16711680) >> 16; - g = (color & 65280) >> 8; - b = color & 255; - } + + return x + y * Math.pow(2, -s) + } else { + var ybits = b.bitLength() - ir.bitLength() + 53 + var y = bn2num(ir.shln(ybits).divRound(b)) + if(ybits < 1023) { + return y * Math.pow(2, -ybits) } - return rgb(r, g, b); + y *= Math.pow(2, -1023) + return y * Math.pow(2, 1023-ybits) } - function d3_rgb_hsl(r, g, b) { - var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; - if (d) { - s = l < .5 ? d / (max + min) : d / (2 - max - min); - if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; - h *= 60; - } else { - h = NaN; - s = l > 0 && l < 1 ? 0 : h; +} + +},{"./lib/bn-to-num":72,"./lib/ctz":73}],83:[function(require,module,exports){ +'use strict' + +module.exports = boxIntersectWrapper + +var pool = require('typedarray-pool') +var sweep = require('./lib/sweep') +var boxIntersectIter = require('./lib/intersect') + +function boxEmpty(d, box) { + for(var j=0; j 3 && respond(); - }; - function respond() { - var status = request.status, result; - if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { - try { - result = response.call(xhr, request); - } catch (e) { - dispatch.error.call(xhr, e); - return; - } - dispatch.load.call(xhr, result); - } else { - dispatch.error.call(xhr, request); - } + return false +} + +//Unpack boxes into a flat typed array, remove empty boxes +function convertBoxes(boxes, d, data, ids) { + var ptr = 0 + var count = 0 + for(var i=0, n=boxes.length; i>>1 + if(d <= 0) { + return } - d3.dsv = function(delimiter, mimeType) { - var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); - function dsv(url, row, callback) { - if (arguments.length < 3) callback = row, row = null; - var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); - xhr.row = function(_) { - return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; - }; - return xhr; - } - function response(request) { - return dsv.parse(request.responseText); - } - function typedResponse(f) { - return function(request) { - return dsv.parse(request.responseText, f); - }; - } - dsv.parse = function(text, f) { - var o; - return dsv.parseRows(text, function(row, i) { - if (o) return o(row, i - 1); - var a = new Function("d", "return {" + row.map(function(name, i) { - return JSON.stringify(name) + ": d[" + i + "]"; - }).join(",") + "}"); - o = f ? function(row, i) { - return f(a(row), i); - } : a; - }); - }; - dsv.parseRows = function(text, f) { - var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; - function token() { - if (I >= N) return EOF; - if (eol) return eol = false, EOL; - var j = I; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; - } - } - I = i + 2; - var c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; - } - return text.slice(j + 1, i).replace(/""/g, '"'); - } - while (I < N) { - var c = text.charCodeAt(I++), k = 1; - if (c === 10) eol = true; else if (c === 13) { - eol = true; - if (text.charCodeAt(I) === 10) ++I, ++k; - } else if (c !== delimiterCode) continue; - return text.slice(j, I - k); - } - return text.slice(j); - } - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); + + var retval + + //Convert red boxes + var redList = pool.mallocDouble(2*d*n) + var redIds = pool.mallocInt32(n) + n = convertBoxes(red, d, redList, redIds) + + if(n > 0) { + if(d === 1 && full) { + //Special case: 1d complete + sweep.init(n) + retval = sweep.sweepComplete( + d, visit, + 0, n, redList, redIds, + 0, n, redList, redIds) + } else { + + //Convert blue boxes + var blueList = pool.mallocDouble(2*d*m) + var blueIds = pool.mallocInt32(m) + m = convertBoxes(blue, d, blueList, blueIds) + + if(m > 0) { + sweep.init(n+m) + + if(d === 1) { + //Special case: 1d bipartite + retval = sweep.sweepBipartite( + d, visit, + 0, n, redList, redIds, + 0, m, blueList, blueIds) + } else { + //General case: d>1 + retval = boxIntersectIter( + d, visit, full, + n, redList, redIds, + m, blueList, blueIds) } - if (f && (a = f(a, n++)) == null) continue; - rows.push(a); + + pool.free(blueList) + pool.free(blueIds) } - return rows; - }; - dsv.format = function(rows) { - if (Array.isArray(rows[0])) return dsv.formatRows(rows); - var fieldSet = new d3_Set(), fields = []; - rows.forEach(function(row) { - for (var field in row) { - if (!fieldSet.has(field)) { - fields.push(fieldSet.add(field)); - } - } - }); - return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { - return fields.map(function(field) { - return formatValue(row[field]); - }).join(delimiter); - })).join("\n"); - }; - dsv.formatRows = function(rows) { - return rows.map(formatRow).join("\n"); - }; - function formatRow(row) { - return row.map(formatValue).join(delimiter); - } - function formatValue(text) { - return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; - } - return dsv; - }; - d3.csv = d3.dsv(",", "text/csv"); - d3.tsv = d3.dsv(" ", "text/tab-separated-values"); - var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { - setTimeout(callback, 17); - }; - d3.timer = function() { - d3_timer.apply(this, arguments); - }; - function d3_timer(callback, delay, then) { - var n = arguments.length; - if (n < 2) delay = 0; - if (n < 3) then = Date.now(); - var time = then + delay, timer = { - c: callback, - t: time, - n: null - }; - if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; - d3_timer_queueTail = timer; - if (!d3_timer_interval) { - d3_timer_timeout = clearTimeout(d3_timer_timeout); - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); } - return timer; + + pool.free(redList) + pool.free(redIds) } - function d3_timer_step() { - var now = d3_timer_mark(), delay = d3_timer_sweep() - now; - if (delay > 24) { - if (isFinite(delay)) { - clearTimeout(d3_timer_timeout); - d3_timer_timeout = setTimeout(d3_timer_step, delay); + + return retval +} + + +var RESULT + +function appendItem(i,j) { + RESULT.push([i,j]) +} + +function intersectFullArray(x) { + RESULT = [] + boxIntersect(x, x, appendItem, true) + return RESULT +} + +function intersectBipartiteArray(x, y) { + RESULT = [] + boxIntersect(x, y, appendItem, false) + return RESULT +} + +//User-friendly wrapper, handle full input and no-visitor cases +function boxIntersectWrapper(arg0, arg1, arg2) { + var result + switch(arguments.length) { + case 1: + return intersectFullArray(arg0) + case 2: + if(typeof arg1 === 'function') { + return boxIntersect(arg0, arg0, arg1, true) + } else { + return intersectBipartiteArray(arg0, arg1) } - d3_timer_interval = 0; - } else { - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); - } + case 3: + return boxIntersect(arg0, arg1, arg2, false) + default: + throw new Error('box-intersect: Invalid arguments') } - d3.timer.flush = function() { - d3_timer_mark(); - d3_timer_sweep(); - }; - function d3_timer_mark() { - var now = Date.now(), timer = d3_timer_queueHead; - while (timer) { - if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; - timer = timer.n; - } - return now; - } - function d3_timer_sweep() { - var t0, t1 = d3_timer_queueHead, time = Infinity; - while (t1) { - if (t1.c) { - if (t1.t < time) time = t1.t; - t1 = (t0 = t1).n; - } else { - t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; - } - } - d3_timer_queueTail = t0; - return time; +} +},{"./lib/intersect":85,"./lib/sweep":89,"typedarray-pool":278}],84:[function(require,module,exports){ +'use strict' + +var DIMENSION = 'd' +var AXIS = 'ax' +var VISIT = 'vv' +var FLIP = 'fp' + +var ELEM_SIZE = 'es' + +var RED_START = 'rs' +var RED_END = 're' +var RED_BOXES = 'rb' +var RED_INDEX = 'ri' +var RED_PTR = 'rp' + +var BLUE_START = 'bs' +var BLUE_END = 'be' +var BLUE_BOXES = 'bb' +var BLUE_INDEX = 'bi' +var BLUE_PTR = 'bp' + +var RETVAL = 'rv' + +var INNER_LABEL = 'Q' + +var ARGS = [ + DIMENSION, + AXIS, + VISIT, + RED_START, + RED_END, + RED_BOXES, + RED_INDEX, + BLUE_START, + BLUE_END, + BLUE_BOXES, + BLUE_INDEX +] + +function generateBruteForce(redMajor, flip, full) { + var funcName = 'bruteForce' + + (redMajor ? 'Red' : 'Blue') + + (flip ? 'Flip' : '') + + (full ? 'Full' : '') + + var code = ['function ', funcName, '(', ARGS.join(), '){', + 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] + + var redLoop = + 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + + 'i<' + RED_END +';' + + '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + + 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + + 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + + 'xi=' + RED_INDEX + '[i];' + + var blueLoop = + 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + + 'j<' + BLUE_END + ';' + + '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + + 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + + (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + + 'yi=' + BLUE_INDEX + '[j];' + + if(redMajor) { + code.push(redLoop, INNER_LABEL, ':', blueLoop) + } else { + code.push(blueLoop, INNER_LABEL, ':', redLoop) } - function d3_format_precision(x, p) { - return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + + if(full) { + code.push('if(y1 8 ? function(d) { - return d / k; - } : function(d) { - return d * k; - }, - symbol: d - }; + + code.push('for(var k='+AXIS+'+1;k<'+DIMENSION+';++k){'+ + 'var r0='+RED_BOXES+'[k+'+RED_PTR+'],'+ + 'r1='+RED_BOXES+'[k+'+DIMENSION+'+'+RED_PTR+'],'+ + 'b0='+BLUE_BOXES+'[k+'+BLUE_PTR+'],'+ + 'b1='+BLUE_BOXES+'[k+'+DIMENSION+'+'+BLUE_PTR+'];'+ + 'if(r1 0 && g > 0) { - if (length + g + 1 > width) g = Math.max(1, width - length); - t.push(value.substring(i -= g, i + g)); - if ((length += g + 1) > width) break; - g = locale_grouping[j = (j + 1) % locale_grouping.length]; - } - return t.reverse().join(locale_thousands); - } : d3_identity; - return function(specifier) { - var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; - if (precision) precision = +precision.substring(1); - if (zfill || fill === "0" && align === "=") { - zfill = fill = "0"; - align = "="; - } - switch (type) { - case "n": - comma = true; - type = "g"; - break; - case "%": - scale = 100; - suffix = "%"; - type = "f"; - break; + code.push(');if(' + RETVAL + '!==void 0)return ' + RETVAL + ';}}}') - case "p": - scale = 100; - suffix = "%"; - type = "r"; - break; + return { + name: funcName, + code: code.join('') + } +} - case "b": - case "o": - case "x": - case "X": - if (symbol === "#") prefix = "0" + type.toLowerCase(); +function bruteForcePlanner(full) { + var funcName = 'bruteForce' + (full ? 'Full' : 'Partial') + var prefix = [] + var fargs = ARGS.slice() + if(!full) { + fargs.splice(3, 0, FLIP) + } - case "c": - exponent = false; + var code = ['function ' + funcName + '(' + fargs.join() + '){'] - case "d": - integer = true; - precision = 0; - break; + function invoke(redMajor, flip) { + var res = generateBruteForce(redMajor, flip, full) + prefix.push(res.code) + code.push('return ' + res.name + '(' + ARGS.join() + ');') + } - case "s": - scale = -1; - type = "r"; - break; - } - if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; - if (type == "r" && !precision) type = "g"; - if (precision != null) { - if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); - } - type = d3_format_types.get(type) || d3_format_typeDefault; - var zcomma = zfill && comma; - return function(value) { - var fullSuffix = suffix; - if (integer && value % 1) return ""; - var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; - if (scale < 0) { - var unit = d3.formatPrefix(value, precision); - value = unit.scale(value); - fullSuffix = unit.symbol + suffix; - } else { - value *= scale; - } - value = type(value, precision); - var i = value.lastIndexOf("."), before, after; - if (i < 0) { - var j = exponent ? value.lastIndexOf("e") : -1; - if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); - } else { - before = value.substring(0, i); - after = locale_decimal + value.substring(i + 1); - } - if (!zfill && comma) before = formatGroup(before, Infinity); - var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; - if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); - negative += prefix; - value = before + after; - return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; - }; - }; + code.push('if(' + RED_END + '-' + RED_START + '>' + + BLUE_END + '-' + BLUE_START + '){') + + if(full) { + invoke(true, false) + code.push('}else{') + invoke(false, false) + } else { + code.push('if(' + FLIP + '){') + invoke(true, true) + code.push('}else{') + invoke(true, false) + code.push('}}else{if(' + FLIP + '){') + invoke(false, true) + code.push('}else{') + invoke(false, false) + code.push('}') } - var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; - var d3_format_types = d3.map({ - b: function(x) { - return x.toString(2); - }, - c: function(x) { - return String.fromCharCode(x); - }, - o: function(x) { - return x.toString(8); - }, - x: function(x) { - return x.toString(16); - }, - X: function(x) { - return x.toString(16).toUpperCase(); - }, - g: function(x, p) { - return x.toPrecision(p); - }, - e: function(x, p) { - return x.toExponential(p); - }, - f: function(x, p) { - return x.toFixed(p); - }, - r: function(x, p) { - return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); - } - }); - function d3_format_typeDefault(x) { - return x + ""; + code.push('}}return ' + funcName) + + var codeStr = prefix.join('') + code.join('') + var proc = new Function(codeStr) + return proc() +} + + +exports.partial = bruteForcePlanner(false) +exports.full = bruteForcePlanner(true) +},{}],85:[function(require,module,exports){ +'use strict' + +module.exports = boxIntersectIter + +var pool = require('typedarray-pool') +var bits = require('bit-twiddle') +var bruteForce = require('./brute') +var bruteForcePartial = bruteForce.partial +var bruteForceFull = bruteForce.full +var sweep = require('./sweep') +var findMedian = require('./median') +var genPartition = require('./partition') + +//Twiddle parameters +var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search +var SCAN_CUTOFF = (1<<22) //Cut off for two way scan +var SCAN_COMPLETE_CUTOFF = (1<<22) + +//Partition functions +var partitionInteriorContainsInterval = genPartition( + '!(lo>=p0)&&!(p1>=hi)', + ['p0', 'p1']) + +var partitionStartEqual = genPartition( + 'lo===p0', + ['p0']) + +var partitionStartLessThan = genPartition( + 'lo 1 ? Date.UTC.apply(this, arguments) : arguments[0]); + var maxDoubles = bits.nextPow2(DFRAME_SIZE*levels) + if(BOX_DSTACK < maxDoubles) { + pool.free(BOX_DSTACK) + BOX_DSTACK = pool.mallocDouble(maxDoubles) } - d3_date_utc.prototype = { - getDate: function() { - return this._.getUTCDate(); - }, - getDay: function() { - return this._.getUTCDay(); - }, - getFullYear: function() { - return this._.getUTCFullYear(); - }, - getHours: function() { - return this._.getUTCHours(); - }, - getMilliseconds: function() { - return this._.getUTCMilliseconds(); - }, - getMinutes: function() { - return this._.getUTCMinutes(); - }, - getMonth: function() { - return this._.getUTCMonth(); - }, - getSeconds: function() { - return this._.getUTCSeconds(); - }, - getTime: function() { - return this._.getTime(); - }, - getTimezoneOffset: function() { - return 0; - }, - valueOf: function() { - return this._.valueOf(); - }, - setDate: function() { - d3_time_prototype.setUTCDate.apply(this._, arguments); - }, - setDay: function() { - d3_time_prototype.setUTCDay.apply(this._, arguments); - }, - setFullYear: function() { - d3_time_prototype.setUTCFullYear.apply(this._, arguments); - }, - setHours: function() { - d3_time_prototype.setUTCHours.apply(this._, arguments); - }, - setMilliseconds: function() { - d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); - }, - setMinutes: function() { - d3_time_prototype.setUTCMinutes.apply(this._, arguments); - }, - setMonth: function() { - d3_time_prototype.setUTCMonth.apply(this._, arguments); - }, - setSeconds: function() { - d3_time_prototype.setUTCSeconds.apply(this._, arguments); - }, - setTime: function() { - d3_time_prototype.setTime.apply(this._, arguments); - } - }; - var d3_time_prototype = Date.prototype; - function d3_time_interval(local, step, number) { - function round(date) { - var d0 = local(date), d1 = offset(d0, 1); - return date - d0 < d1 - date ? d0 : d1; - } - function ceil(date) { - step(date = local(new d3_date(date - 1)), 1); - return date; +} + +//Append item to queue +function iterPush(ptr, + axis, + redStart, redEnd, + blueStart, blueEnd, + state, + lo, hi) { + + var iptr = IFRAME_SIZE * ptr + BOX_ISTACK[iptr] = axis + BOX_ISTACK[iptr+1] = redStart + BOX_ISTACK[iptr+2] = redEnd + BOX_ISTACK[iptr+3] = blueStart + BOX_ISTACK[iptr+4] = blueEnd + BOX_ISTACK[iptr+5] = state + + var dptr = DFRAME_SIZE * ptr + BOX_DSTACK[dptr] = lo + BOX_DSTACK[dptr+1] = hi +} + +//Special case: Intersect single point with list of intervals +function onePointPartial( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueOffset, blue, blueId) { + + var elemSize = 2 * d + var bluePtr = blueOffset * elemSize + var blueX = blue[bluePtr + axis] + +red_loop: + for(var i=redStart, redPtr=redStart*elemSize; i 1) { - while (time < t1) { - if (!(number(time) % dt)) times.push(new Date(+time)); - step(time, 1); - } - } else { - while (time < t1) times.push(new Date(+time)), step(time, 1); + var redId = redIndex[i] + for(var j=axis+1; j 0) { + top -= 1 + + var iptr = top * IFRAME_SIZE + var axis = BOX_ISTACK[iptr] + var redStart = BOX_ISTACK[iptr+1] + var redEnd = BOX_ISTACK[iptr+2] + var blueStart = BOX_ISTACK[iptr+3] + var blueEnd = BOX_ISTACK[iptr+4] + var state = BOX_ISTACK[iptr+5] + + var dptr = top * DFRAME_SIZE + var lo = BOX_DSTACK[dptr] + var hi = BOX_DSTACK[dptr+1] + + //Unpack state info + var flip = (state & 1) + var full = !!(state & 16) + + //Unpack indices + var red = xBoxes + var redIndex = xIndex + var blue = yBoxes + var blueIndex = yIndex + if(flip) { + red = yBoxes + redIndex = yIndex + blue = xBoxes + blueIndex = xIndex + } + + if(state & 2) { + redEnd = partitionStartLessThan( + d, axis, + redStart, redEnd, red, redIndex, + hi) + if(redStart >= redEnd) { + continue } - format.parse = function(string) { - var d = { - y: 1900, - m: 0, - d: 1, - H: 0, - M: 0, - S: 0, - L: 0, - Z: null - }, i = d3_time_parse(d, template, string, 0); - if (i != string.length) return null; - if ("p" in d) d.H = d.H % 12 + d.p * 12; - var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); - if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { - if (!("w" in d)) d.w = "W" in d ? 1 : 0; - date.setFullYear(d.y, 0, 1); - date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); - } else date.setFullYear(d.y, d.m, d.d); - date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); - return localZ ? date._ : date; - }; - format.toString = function() { - return template; - }; - return format; } - function d3_time_parse(date, template, string, j) { - var c, p, t, i = 0, n = template.length, m = string.length; - while (i < n) { - if (j >= m) return -1; - c = template.charCodeAt(i++); - if (c === 37) { - t = template.charAt(i++); - p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; - if (!p || (j = p(date, string, j)) < 0) return -1; - } else if (c != string.charCodeAt(j++)) { - return -1; - } + if(state & 4) { + redStart = partitionEndLessThanEqual( + d, axis, + redStart, redEnd, red, redIndex, + lo) + if(redStart >= redEnd) { + continue } - return j; } - d3_time_format.utc = function(template) { - var local = d3_time_format(template); - function format(date) { - try { - d3_date = d3_date_utc; - var utc = new d3_date(); - utc._ = date; - return local(utc); - } finally { - d3_date = Date; + + var redCount = redEnd - redStart + var blueCount = blueEnd - blueStart + + if(full) { + if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { + retval = sweep.scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval } + continue } - format.parse = function(string) { - try { - d3_date = d3_date_utc; - var date = local.parse(string); - return date && date._; - } finally { - d3_date = Date; + } else { + if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { + //If input small, then use brute force + retval = bruteForcePartial( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval } - }; - format.toString = local.toString; - return format; - }; - d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; - var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); - locale_periods.forEach(function(p, i) { - d3_time_periodLookup.set(p.toLowerCase(), i); - }); - var d3_time_formats = { - a: function(d) { - return locale_shortDays[d.getDay()]; - }, - A: function(d) { - return locale_days[d.getDay()]; - }, - b: function(d) { - return locale_shortMonths[d.getMonth()]; - }, - B: function(d) { - return locale_months[d.getMonth()]; - }, - c: d3_time_format(locale_dateTime), - d: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - e: function(d, p) { - return d3_time_formatPad(d.getDate(), p, 2); - }, - H: function(d, p) { - return d3_time_formatPad(d.getHours(), p, 2); - }, - I: function(d, p) { - return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); - }, - j: function(d, p) { - return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); - }, - L: function(d, p) { - return d3_time_formatPad(d.getMilliseconds(), p, 3); - }, - m: function(d, p) { - return d3_time_formatPad(d.getMonth() + 1, p, 2); - }, - M: function(d, p) { - return d3_time_formatPad(d.getMinutes(), p, 2); - }, - p: function(d) { - return locale_periods[+(d.getHours() >= 12)]; - }, - S: function(d, p) { - return d3_time_formatPad(d.getSeconds(), p, 2); - }, - U: function(d, p) { - return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); - }, - w: function(d) { - return d.getDay(); - }, - W: function(d, p) { - return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); - }, - x: d3_time_format(locale_date), - X: d3_time_format(locale_time), - y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 100, p, 2); - }, - Y: function(d, p) { - return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); - }, - Z: d3_time_zone, - "%": function() { - return "%"; + continue + } else if(d * redCount * blueCount < SCAN_CUTOFF) { + //If input medium sized, then use sweep and prune + retval = sweep.scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + continue } - }; - var d3_time_parsers = { - a: d3_time_parseWeekdayAbbrev, - A: d3_time_parseWeekday, - b: d3_time_parseMonthAbbrev, - B: d3_time_parseMonth, - c: d3_time_parseLocaleFull, - d: d3_time_parseDay, - e: d3_time_parseDay, - H: d3_time_parseHour24, - I: d3_time_parseHour24, - j: d3_time_parseDayOfYear, - L: d3_time_parseMilliseconds, - m: d3_time_parseMonthNumber, - M: d3_time_parseMinutes, - p: d3_time_parseAmPm, - S: d3_time_parseSeconds, - U: d3_time_parseWeekNumberSunday, - w: d3_time_parseWeekdayNumber, - W: d3_time_parseWeekNumberMonday, - x: d3_time_parseLocaleDate, - X: d3_time_parseLocaleTime, - y: d3_time_parseYear, - Y: d3_time_parseFullYear, - Z: d3_time_parseZone, - "%": d3_time_parseLiteralPercent - }; - function d3_time_parseWeekdayAbbrev(date, string, i) { - d3_time_dayAbbrevRe.lastIndex = 0; - var n = d3_time_dayAbbrevRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseWeekday(date, string, i) { - d3_time_dayRe.lastIndex = 0; - var n = d3_time_dayRe.exec(string.slice(i)); - return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonthAbbrev(date, string, i) { - d3_time_monthAbbrevRe.lastIndex = 0; - var n = d3_time_monthAbbrevRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseMonth(date, string, i) { - d3_time_monthRe.lastIndex = 0; - var n = d3_time_monthRe.exec(string.slice(i)); - return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; - } - function d3_time_parseLocaleFull(date, string, i) { - return d3_time_parse(date, d3_time_formats.c.toString(), string, i); - } - function d3_time_parseLocaleDate(date, string, i) { - return d3_time_parse(date, d3_time_formats.x.toString(), string, i); - } - function d3_time_parseLocaleTime(date, string, i) { - return d3_time_parse(date, d3_time_formats.X.toString(), string, i); } - function d3_time_parseAmPm(date, string, i) { - var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); - return n == null ? -1 : (date.p = n, i); + + //First, find all red intervals whose interior contains (lo,hi) + var red0 = partitionInteriorContainsInterval( + d, axis, + redStart, redEnd, red, redIndex, + lo, hi) + + //Lower dimensional case + if(redStart < red0) { + + if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { + //Special case for small inputs: use brute force + retval = bruteForceFull( + d, axis+1, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } else if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blueStart, blueEnd, blue, blueIndex, + redStart, red0, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + redStart, red0, red, redIndex, + blueStart, blueEnd, blue, blueIndex) + } + if(retval !== void 0) { + return retval + } + } else { + iterPush(top++, + axis+1, + redStart, red0, + blueStart, blueEnd, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blueStart, blueEnd, + redStart, red0, + flip^1, + -Infinity, Infinity) + } } - return d3_time_format; - } - var d3_time_formatPads = { - "-": "", - _: " ", - "0": "0" - }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; - function d3_time_formatPad(value, fill, width) { - var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; - return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); - } - function d3_time_formatRe(names) { - return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); - } - function d3_time_formatLookup(names) { - var map = new d3_Map(), i = -1, n = names.length; - while (++i < n) map.set(names[i].toLowerCase(), i); - return map; - } - function d3_time_parseWeekdayNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 1)); - return n ? (date.w = +n[0], i + n[0].length) : -1; - } - function d3_time_parseWeekNumberSunday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.U = +n[0], i + n[0].length) : -1; - } - function d3_time_parseWeekNumberMonday(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i)); - return n ? (date.W = +n[0], i + n[0].length) : -1; - } - function d3_time_parseFullYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 4)); - return n ? (date.y = +n[0], i + n[0].length) : -1; - } - function d3_time_parseYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; - } - function d3_time_parseZone(date, string, i) { - return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, - i + 5) : -1; - } - function d3_time_expandYear(d) { - return d + (d > 68 ? 1900 : 2e3); - } - function d3_time_parseMonthNumber(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.m = n[0] - 1, i + n[0].length) : -1; - } - function d3_time_parseDay(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.d = +n[0], i + n[0].length) : -1; - } - function d3_time_parseDayOfYear(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.j = +n[0], i + n[0].length) : -1; - } - function d3_time_parseHour24(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.H = +n[0], i + n[0].length) : -1; - } - function d3_time_parseMinutes(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.M = +n[0], i + n[0].length) : -1; - } - function d3_time_parseSeconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 2)); - return n ? (date.S = +n[0], i + n[0].length) : -1; - } - function d3_time_parseMilliseconds(date, string, i) { - d3_time_numberRe.lastIndex = 0; - var n = d3_time_numberRe.exec(string.slice(i, i + 3)); - return n ? (date.L = +n[0], i + n[0].length) : -1; - } - function d3_time_zone(d) { - var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; - return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); - } - function d3_time_parseLiteralPercent(date, string, i) { - d3_time_percentRe.lastIndex = 0; - var n = d3_time_percentRe.exec(string.slice(i, i + 1)); - return n ? i + n[0].length : -1; - } - function d3_time_formatMulti(formats) { - var n = formats.length, i = -1; - while (++i < n) formats[i][0] = this(formats[i][0]); - return function(date) { - var i = 0, f = formats[i]; - while (!f[1](date)) f = formats[++i]; - return f[0](date); - }; - } - d3.locale = function(locale) { - return { - numberFormat: d3_locale_numberFormat(locale), - timeFormat: d3_locale_timeFormat(locale) - }; - }; - var d3_locale_enUS = d3.locale({ - decimal: ".", - thousands: ",", - grouping: [ 3 ], - currency: [ "$", "" ], - dateTime: "%a %b %e %X %Y", - date: "%m/%d/%Y", - time: "%H:%M:%S", - periods: [ "AM", "PM" ], - days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], - shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], - months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], - shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] - }); - d3.format = d3_locale_enUS.numberFormat; - d3.geo = {}; - function d3_adder() {} - d3_adder.prototype = { - s: 0, - t: 0, - add: function(y) { - d3_adderSum(y, this.t, d3_adderTemp); - d3_adderSum(d3_adderTemp.s, this.s, this); - if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; - }, - reset: function() { - this.s = this.t = 0; - }, - valueOf: function() { - return this.s; - } - }; - var d3_adderTemp = new d3_adder(); - function d3_adderSum(a, b, o) { - var x = o.s = a + b, bv = x - a, av = x - bv; - o.t = a - av + (b - bv); - } - d3.geo.stream = function(object, listener) { - if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { - d3_geo_streamObjectType[object.type](object, listener); - } else { - d3_geo_streamGeometry(object, listener); - } - }; - function d3_geo_streamGeometry(geometry, listener) { - if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { - d3_geo_streamGeometryType[geometry.type](geometry, listener); - } - } - var d3_geo_streamObjectType = { - Feature: function(feature, listener) { - d3_geo_streamGeometry(feature.geometry, listener); - }, - FeatureCollection: function(object, listener) { - var features = object.features, i = -1, n = features.length; - while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); - } - }; - var d3_geo_streamGeometryType = { - Sphere: function(object, listener) { - listener.sphere(); - }, - Point: function(object, listener) { - object = object.coordinates; - listener.point(object[0], object[1], object[2]); - }, - MultiPoint: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); - }, - LineString: function(object, listener) { - d3_geo_streamLine(object.coordinates, listener, 0); - }, - MultiLineString: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); - }, - Polygon: function(object, listener) { - d3_geo_streamPolygon(object.coordinates, listener); - }, - MultiPolygon: function(object, listener) { - var coordinates = object.coordinates, i = -1, n = coordinates.length; - while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); - }, - GeometryCollection: function(object, listener) { - var geometries = object.geometries, i = -1, n = geometries.length; - while (++i < n) d3_geo_streamGeometry(geometries[i], listener); - } - }; - function d3_geo_streamLine(coordinates, listener, closed) { - var i = -1, n = coordinates.length - closed, coordinate; - listener.lineStart(); - while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); - listener.lineEnd(); - } - function d3_geo_streamPolygon(coordinates, listener) { - var i = -1, n = coordinates.length; - listener.polygonStart(); - while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); - listener.polygonEnd(); - } - d3.geo.area = function(object) { - d3_geo_areaSum = 0; - d3.geo.stream(object, d3_geo_area); - return d3_geo_areaSum; - }; - var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); - var d3_geo_area = { - sphere: function() { - d3_geo_areaSum += 4 * π; - }, - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_areaRingSum.reset(); - d3_geo_area.lineStart = d3_geo_areaRingStart; - }, - polygonEnd: function() { - var area = 2 * d3_geo_areaRingSum; - d3_geo_areaSum += area < 0 ? 4 * π + area : area; - d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; - } - }; - function d3_geo_areaRingStart() { - var λ00, φ00, λ0, cosφ0, sinφ0; - d3_geo_area.point = function(λ, φ) { - d3_geo_area.point = nextPoint; - λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), - sinφ0 = Math.sin(φ); - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - φ = φ * d3_radians / 2 + π / 4; - var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); - d3_geo_areaRingSum.add(Math.atan2(v, u)); - λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; - } - d3_geo_area.lineEnd = function() { - nextPoint(λ00, φ00); - }; - } - function d3_geo_cartesian(spherical) { - var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); - return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; - } - function d3_geo_cartesianDot(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; - } - function d3_geo_cartesianCross(a, b) { - return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; - } - function d3_geo_cartesianAdd(a, b) { - a[0] += b[0]; - a[1] += b[1]; - a[2] += b[2]; - } - function d3_geo_cartesianScale(vector, k) { - return [ vector[0] * k, vector[1] * k, vector[2] * k ]; - } - function d3_geo_cartesianNormalize(d) { - var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); - d[0] /= l; - d[1] /= l; - d[2] /= l; - } - function d3_geo_spherical(cartesian) { - return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; - } - function d3_geo_sphericalEqual(a, b) { - return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; - } - d3.geo.bounds = function() { - var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; - var bound = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - bound.point = ringPoint; - bound.lineStart = ringStart; - bound.lineEnd = ringEnd; - dλSum = 0; - d3_geo_area.polygonStart(); - }, - polygonEnd: function() { - d3_geo_area.polygonEnd(); - bound.point = point; - bound.lineStart = lineStart; - bound.lineEnd = lineEnd; - if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; - range[0] = λ0, range[1] = λ1; + + //Divide and conquer phase + if(red0 < redEnd) { + + //Cut blue into 3 parts: + // + // Points < mid point + // Points = mid point + // Points > mid point + // + var blue0 = findMedian( + d, axis, + blueStart, blueEnd, blue, blueIndex) + var mid = blue[elemSize * blue0 + axis] + var blue1 = partitionStartEqual( + d, axis, + blue0, blueEnd, blue, blueIndex, + mid) + + //Right case + if(blue1 < blueEnd) { + iterPush(top++, + axis, + red0, redEnd, + blue1, blueEnd, + (flip|4) + (full ? 16 : 0), + mid, hi) } - }; - function point(λ, φ) { - ranges.push(range = [ λ0 = λ, λ1 = λ ]); - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; - } - function linePoint(λ, φ) { - var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); - if (p0) { - var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); - d3_geo_cartesianNormalize(inflection); - inflection = d3_geo_spherical(inflection); - var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; - if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = inflection[1] * d3_degrees; - if (φi > φ1) φ1 = φi; - } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { - var φi = -inflection[1] * d3_degrees; - if (φi < φ0) φ0 = φi; + + //Left case + if(blueStart < blue0) { + iterPush(top++, + axis, + red0, redEnd, + blueStart, blue0, + (flip|2) + (full ? 16 : 0), + lo, mid) + } + + //Center case (the hard part) + if(blue0 + 1 === blue1) { + //Optimization: Range with exactly 1 point, use a brute force scan + if(full) { + retval = onePointFull( + d, axis, visit, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) } else { - if (φ < φ0) φ0 = φ; - if (φ > φ1) φ1 = φ; + retval = onePointPartial( + d, axis, visit, flip, + red0, redEnd, red, redIndex, + blue0, blue, blueIndex[blue0]) } - if (antimeridian) { - if (λ < λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; - } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + if(retval !== void 0) { + return retval + } + } else if(blue0 < blue1) { + var red1 + if(full) { + //If full intersection, need to handle special case + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + if(red0 < red1) { + var redX = partitionStartEqual( + d, axis, + red0, red1, red, redIndex, + mid) + if(axis === d-2) { + //Degenerate sweep intersection: + // [red0, redX] with [blue0, blue1] + if(red0 < redX) { + retval = sweep.sweepComplete( + d, visit, + red0, redX, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } + + //Normal sweep intersection: + // [redX, red1] with [blue0, blue1] + if(redX < red1) { + retval = sweep.sweepBipartite( + d, visit, + redX, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + if(retval !== void 0) { + return retval + } + } + } else { + if(red0 < redX) { + iterPush(top++, + axis+1, + red0, redX, + blue0, blue1, + 16, + -Infinity, Infinity) + } + if(redX < red1) { + iterPush(top++, + axis+1, + redX, red1, + blue0, blue1, + 0, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + redX, red1, + 1, + -Infinity, Infinity) + } + } } } else { - if (λ1 >= λ0) { - if (λ < λ0) λ0 = λ; - if (λ > λ1) λ1 = λ; + if(flip) { + red1 = partitionContainsPointProper( + d, axis, + red0, redEnd, red, redIndex, + mid) } else { - if (λ > λ_) { - if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + red1 = partitionContainsPoint( + d, axis, + red0, redEnd, red, redIndex, + mid) + } + if(red0 < red1) { + if(axis === d-2) { + if(flip) { + retval = sweep.sweepBipartite( + d, visit, + blue0, blue1, blue, blueIndex, + red0, red1, red, redIndex) + } else { + retval = sweep.sweepBipartite( + d, visit, + red0, red1, red, redIndex, + blue0, blue1, blue, blueIndex) + } } else { - if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + iterPush(top++, + axis+1, + red0, red1, + blue0, blue1, + flip, + -Infinity, Infinity) + iterPush(top++, + axis+1, + blue0, blue1, + red0, red1, + flip^1, + -Infinity, Infinity) } } } - } else { - point(λ, φ); } - p0 = p, λ_ = λ; - } - function lineStart() { - bound.point = linePoint; } - function lineEnd() { - range[0] = λ0, range[1] = λ1; - bound.point = point; - p0 = null; + } +} +},{"./brute":84,"./median":86,"./partition":87,"./sweep":89,"bit-twiddle":50,"typedarray-pool":278}],86:[function(require,module,exports){ +'use strict' + +module.exports = findMedian + +var genPartition = require('./partition') + +var partitionStartLessThan = genPartition('lostart && boxes[ptr+axis] > x; + --j, ptr-=elemSize) { + //Swap + var aPtr = ptr + var bPtr = ptr+elemSize + for(var k=0; k 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; - } else λ__ = λ, φ__ = φ; - d3_geo_area.point(λ, φ); - linePoint(λ, φ); + } +} + +//Find median using quick select algorithm +// takes O(n) time with high probability +function findMedian(d, axis, start, end, boxes, ids) { + if(end <= start+1) { + return start + } + + var lo = start + var hi = end + var mid = ((end + start) >>> 1) + var elemSize = 2*d + var pivot = mid + var value = boxes[elemSize*mid+axis] + + while(lo < hi) { + if(hi - lo < PARTITION_THRESHOLD) { + insertionSort(d, axis, lo, hi, boxes, ids) + value = boxes[elemSize*mid+axis] + break } - function ringStart() { - d3_geo_area.lineStart(); - } - function ringEnd() { - ringPoint(λ__, φ__); - d3_geo_area.lineEnd(); - if (abs(dλSum) > ε) λ0 = -(λ1 = 180); - range[0] = λ0, range[1] = λ1; - p0 = null; - } - function angle(λ0, λ1) { - return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + + //Select pivot using median-of-3 + var count = hi - lo + var pivot0 = (Math.random()*count+lo)|0 + var value0 = boxes[elemSize*pivot0 + axis] + var pivot1 = (Math.random()*count+lo)|0 + var value1 = boxes[elemSize*pivot1 + axis] + var pivot2 = (Math.random()*count+lo)|0 + var value2 = boxes[elemSize*pivot2 + axis] + if(value0 <= value1) { + if(value2 >= value1) { + pivot = pivot1 + value = value1 + } else if(value0 >= value2) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } + } else { + if(value1 >= value2) { + pivot = pivot1 + value = value1 + } else if(value2 >= value0) { + pivot = pivot0 + value = value0 + } else { + pivot = pivot2 + value = value2 + } } - function compareRanges(a, b) { - return a[0] - b[0]; + + //Swap pivot to end of array + var aPtr = elemSize * (hi-1) + var bPtr = elemSize * pivot + for(var i=0; i angle(a[0], a[1])) a[1] = b[1]; - if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; - } else { - merged.push(a = b); - } - } - var best = -Infinity, dλ; - for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { - b = merged[i]; - if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; - } + var y = ids[hi-1] + ids[hi-1] = ids[pivot] + ids[pivot] = y + + //Swap pivot to last pivot + if(mid < pivot) { + hi = pivot-1 + while(lo < hi && + boxes[elemSize*(hi-1)+axis] === value) { + hi -= 1 } - ranges = range = null; - return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; - }; - }(); - d3.geo.centroid = function(object) { - d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; - d3.geo.stream(object, d3_geo_centroid); - var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; - if (m < ε2) { - x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; - if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; - m = x * x + y * y + z * z; - if (m < ε2) return [ NaN, NaN ]; - } - return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; - }; - var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; - var d3_geo_centroid = { - sphere: d3_noop, - point: d3_geo_centroidPoint, - lineStart: d3_geo_centroidLineStart, - lineEnd: d3_geo_centroidLineEnd, - polygonStart: function() { - d3_geo_centroid.lineStart = d3_geo_centroidRingStart; - }, - polygonEnd: function() { - d3_geo_centroid.lineStart = d3_geo_centroidLineStart; + hi += 1 + } else if(pivot < mid) { + lo = pivot + 1 + while(lo < hi && + boxes[elemSize*lo+axis] === value) { + lo += 1 + } + } else { + break } - }; - function d3_geo_centroidPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } - function d3_geo_centroidPointXYZ(x, y, z) { - ++d3_geo_centroidW0; - d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; - d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; - d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; + + //Make sure pivot is at start + return partitionStartLessThan( + d, axis, + start, mid, boxes, ids, + boxes[elemSize*mid+axis]) +} +},{"./partition":87}],87:[function(require,module,exports){ +'use strict' + +module.exports = genPartition + +var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m' + +function genPartition(predicate, args) { + var fargs ='abcdef'.split('').concat(args) + var reads = [] + if(predicate.indexOf('lo') >= 0) { + reads.push('lo=e[k+n]') } - function d3_geo_centroidLineStart() { - var x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroid.point = nextPoint; - d3_geo_centroidPointXYZ(x0, y0, z0); - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); - } + if(predicate.indexOf('hi') >= 0) { + reads.push('hi=e[k+o]') } - function d3_geo_centroidLineEnd() { - d3_geo_centroid.point = d3_geo_centroidPoint; + fargs.push( + code.replace('_', reads.join()) + .replace('$', predicate)) + return Function.apply(void 0, fargs) +} +},{}],88:[function(require,module,exports){ +'use strict'; + +//This code is extracted from ndarray-sort +//It is inlined here as a temporary workaround + +module.exports = wrapper; + +var INSERT_SORT_CUTOFF = 32 + +function wrapper(data, n0) { + if (n0 <= 4*INSERT_SORT_CUTOFF) { + insertionSort(0, n0 - 1, data); + } else { + quickSort(0, n0 - 1, data); } - function d3_geo_centroidRingStart() { - var λ00, φ00, x0, y0, z0; - d3_geo_centroid.point = function(λ, φ) { - λ00 = λ, φ00 = φ; - d3_geo_centroid.point = nextPoint; - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians); - x0 = cosφ * Math.cos(λ); - y0 = cosφ * Math.sin(λ); - z0 = Math.sin(φ); - d3_geo_centroidPointXYZ(x0, y0, z0); - }; - d3_geo_centroid.lineEnd = function() { - nextPoint(λ00, φ00); - d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; - d3_geo_centroid.point = d3_geo_centroidPoint; - }; - function nextPoint(λ, φ) { - λ *= d3_radians; - var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); - d3_geo_centroidX2 += v * cx; - d3_geo_centroidY2 += v * cy; - d3_geo_centroidZ2 += v * cz; - d3_geo_centroidW1 += w; - d3_geo_centroidX1 += w * (x0 + (x0 = x)); - d3_geo_centroidY1 += w * (y0 + (y0 = y)); - d3_geo_centroidZ1 += w * (z0 + (z0 = z)); - d3_geo_centroidPointXYZ(x0, y0, z0); +} + +function insertionSort(left, right, data) { + var ptr = 2*(left+1) + for(var i=left+1; i<=right; ++i) { + var a = data[ptr++] + var b = data[ptr++] + var j = i + var jptr = ptr-2 + while(j-- > left) { + var x = data[jptr-2] + var y = data[jptr-1] + if(x < a) { + break + } else if(x === a && y < b) { + break + } + data[jptr] = x + data[jptr+1] = y + jptr -= 2 } + data[jptr] = a + data[jptr+1] = b } - function d3_geo_compose(a, b) { - function compose(x, y) { - return x = a(x, y), b(x[0], x[1]); - } - if (a.invert && b.invert) compose.invert = function(x, y) { - return x = b.invert(x, y), x && a.invert(x[0], x[1]); - }; - return compose; +} + +function swap(i, j, data) { + i *= 2 + j *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = x + data[j+1] = y +} + +function move(i, j, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[i+1] = data[j+1] +} + +function rotate(i, j, k, data) { + i *= 2 + j *= 2 + k *= 2 + var x = data[i] + var y = data[i+1] + data[i] = data[j] + data[i+1] = data[j+1] + data[j] = data[k] + data[j+1] = data[k+1] + data[k] = x + data[k+1] = y +} + +function shufflePivot(i, j, px, py, data) { + i *= 2 + j *= 2 + data[i] = data[j] + data[j] = px + data[i+1] = data[j+1] + data[j+1] = py +} + +function compare(i, j, data) { + i *= 2 + j *= 2 + var x = data[i], + y = data[j] + if(x < y) { + return false + } else if(x === y) { + return data[i+1] > data[j+1] } - function d3_true() { - return true; + return true +} + +function comparePivot(i, y, b, data) { + i *= 2 + var x = data[i] + if(x < y) { + return true + } else if(x === y) { + return data[i+1] < b } - function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { - var subject = [], clip = []; - segments.forEach(function(segment) { - if ((n = segment.length - 1) <= 0) return; - var n, p0 = segment[0], p1 = segment[n]; - if (d3_geo_sphericalEqual(p0, p1)) { - listener.lineStart(); - for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); - listener.lineEnd(); - return; + return false +} + +function quickSort(left, right, data) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, + tmp = 0 + if(compare(el1, el2, data)) { + tmp = el1 + el1 = el2 + el2 = tmp + } + if(compare(el4, el5, data)) { + tmp = el4 + el4 = el5 + el5 = tmp + } + if(compare(el1, el3, data)) { + tmp = el1 + el1 = el3 + el3 = tmp + } + if(compare(el2, el3, data)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el1, el4, data)) { + tmp = el1 + el1 = el4 + el4 = tmp + } + if(compare(el3, el4, data)) { + tmp = el3 + el3 = el4 + el4 = tmp + } + if(compare(el2, el5, data)) { + tmp = el2 + el2 = el5 + el5 = tmp + } + if(compare(el2, el3, data)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el4, el5, data)) { + tmp = el4 + el4 = el5 + el5 = tmp + } + + var pivot1X = data[2*el2] + var pivot1Y = data[2*el2+1] + var pivot2X = data[2*el4] + var pivot2Y = data[2*el4+1] + + var ptr0 = 2 * el1; + var ptr2 = 2 * el3; + var ptr4 = 2 * el5; + var ptr5 = 2 * index1; + var ptr6 = 2 * index3; + var ptr7 = 2 * index5; + for (var i1 = 0; i1 < 2; ++i1) { + var x = data[ptr0+i1]; + var y = data[ptr2+i1]; + var z = data[ptr4+i1]; + data[ptr5+i1] = x; + data[ptr6+i1] = y; + data[ptr7+i1] = z; + } + + move(index2, left, data) + move(index4, right, data) + for (var k = less; k <= great; ++k) { + if (comparePivot(k, pivot1X, pivot1Y, data)) { + if (k !== less) { + swap(k, less, data) } - var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); - a.o = b; - subject.push(a); - clip.push(b); - a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); - b = new d3_geo_clipPolygonIntersection(p1, null, a, true); - a.o = b; - subject.push(a); - clip.push(b); - }); - clip.sort(compare); - d3_geo_clipPolygonLinkCircular(subject); - d3_geo_clipPolygonLinkCircular(clip); - if (!subject.length) return; - for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { - clip[i].e = entry = !entry; - } - var start = subject[0], points, point; - while (1) { - var current = start, isSubject = true; - while (current.v) if ((current = current.n) === start) return; - points = current.z; - listener.lineStart(); - do { - current.v = current.o.v = true; - if (current.e) { - if (isSubject) { - for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); - } else { - interpolate(current.x, current.n.x, 1, listener); - } - current = current.n; - } else { - if (isSubject) { - points = current.p.z; - for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); + ++less; + } else { + if (!comparePivot(k, pivot2X, pivot2Y, data)) { + while (true) { + if (!comparePivot(great, pivot2X, pivot2Y, data)) { + if (--great < k) { + break; + } + continue; } else { - interpolate(current.x, current.p.x, -1, listener); + if (comparePivot(great, pivot1X, pivot1Y, data)) { + rotate(k, less, great, data) + ++less; + --great; + } else { + swap(k, great, data) + --great; + } + break; } - current = current.p; } - current = current.o; - points = current.z; - isSubject = !isSubject; - } while (!current.v); - listener.lineEnd(); + } } } - function d3_geo_clipPolygonLinkCircular(array) { - if (!(n = array.length)) return; - var n, i = 0, a = array[0], b; - while (++i < n) { - a.n = b = array[i]; - b.p = a; - a = b; - } - a.n = b = array[0]; - b.p = a; + shufflePivot(left, less-1, pivot1X, pivot1Y, data) + shufflePivot(right, great+1, pivot2X, pivot2Y, data) + if (less - 2 - left <= INSERT_SORT_CUTOFF) { + insertionSort(left, less - 2, data); + } else { + quickSort(left, less - 2, data); } - function d3_geo_clipPolygonIntersection(point, points, other, entry) { - this.x = point; - this.z = points; - this.o = other; - this.e = entry; - this.v = false; - this.n = this.p = null; + if (right - (great + 2) <= INSERT_SORT_CUTOFF) { + insertionSort(great + 2, right, data); + } else { + quickSort(great + 2, right, data); } - function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { - return function(rotate, listener) { - var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - clip.point = pointRing; - clip.lineStart = ringStart; - clip.lineEnd = ringEnd; - segments = []; - polygon = []; - }, - polygonEnd: function() { - clip.point = point; - clip.lineStart = lineStart; - clip.lineEnd = lineEnd; - segments = d3.merge(segments); - var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); - if (segments.length) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); - } else if (clipStartInside) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (polygonStarted) listener.polygonEnd(), polygonStarted = false; - segments = polygon = null; - }, - sphere: function() { - listener.polygonStart(); - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - listener.polygonEnd(); - } - }; - function point(λ, φ) { - var point = rotate(λ, φ); - if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); - } - function pointLine(λ, φ) { - var point = rotate(λ, φ); - line.point(point[0], point[1]); - } - function lineStart() { - clip.point = pointLine; - line.lineStart(); - } - function lineEnd() { - clip.point = point; - line.lineEnd(); - } - var segments; - var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; - function pointRing(λ, φ) { - ring.push([ λ, φ ]); - var point = rotate(λ, φ); - ringListener.point(point[0], point[1]); - } - function ringStart() { - ringListener.lineStart(); - ring = []; - } - function ringEnd() { - pointRing(ring[0][0], ring[0][1]); - ringListener.lineEnd(); - var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; - ring.pop(); - polygon.push(ring); - ring = null; - if (!n) return; - if (clean & 1) { - segment = ringSegments[0]; - var n = segment.length - 1, i = -1, point; - if (n > 0) { - if (!polygonStarted) listener.polygonStart(), polygonStarted = true; - listener.lineStart(); - while (++i < n) listener.point((point = segment[i])[0], point[1]); - listener.lineEnd(); - } - return; - } - if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); - segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); - } - return clip; - }; + if (great - less <= INSERT_SORT_CUTOFF) { + insertionSort(less, great, data); + } else { + quickSort(less, great, data); } - function d3_geo_clipSegmentLength1(segment) { - return segment.length > 1; +} +},{}],89:[function(require,module,exports){ +'use strict' + +module.exports = { + init: sqInit, + sweepBipartite: sweepBipartite, + sweepComplete: sweepComplete, + scanBipartite: scanBipartite, + scanComplete: scanComplete +} + +var pool = require('typedarray-pool') +var bits = require('bit-twiddle') +var isort = require('./sort') + +//Flag for blue +var BLUE_FLAG = (1<<28) + +//1D sweep event queue stuff (use pool to save space) +var INIT_CAPACITY = 1024 +var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) +var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) +var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) + +//Reserves memory for the 1D sweep data structures +function sqInit(count) { + var rcount = bits.nextPow2(count) + if(RED_SWEEP_QUEUE.length < rcount) { + pool.free(RED_SWEEP_QUEUE) + RED_SWEEP_QUEUE = pool.mallocInt32(rcount) } - function d3_geo_clipBufferListener() { - var lines = [], line; - return { - lineStart: function() { - lines.push(line = []); - }, - point: function(λ, φ) { - line.push([ λ, φ ]); - }, - lineEnd: d3_noop, - buffer: function() { - var buffer = lines; - lines = []; - line = null; - return buffer; - }, - rejoin: function() { - if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); - } - }; + if(RED_SWEEP_INDEX.length < rcount) { + pool.free(RED_SWEEP_INDEX) + RED_SWEEP_INDEX = pool.mallocInt32(rcount) } - function d3_geo_clipSort(a, b) { - return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); + if(BLUE_SWEEP_QUEUE.length < rcount) { + pool.free(BLUE_SWEEP_QUEUE) + BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) } - var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); - function d3_geo_clipAntimeridianLine(listener) { - var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; - return { - lineStart: function() { - listener.lineStart(); - clean = 1; - }, - point: function(λ1, φ1) { - var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); - if (abs(dλ - π) < ε) { - listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - listener.point(λ1, φ0); - clean = 0; - } else if (sλ0 !== sλ1 && dλ >= π) { - if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; - if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; - φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); - listener.point(sλ0, φ0); - listener.lineEnd(); - listener.lineStart(); - listener.point(sλ1, φ0); - clean = 0; - } - listener.point(λ0 = λ1, φ0 = φ1); - sλ0 = sλ1; - }, - lineEnd: function() { - listener.lineEnd(); - λ0 = φ0 = NaN; - }, - clean: function() { - return 2 - clean; - } - }; + if(BLUE_SWEEP_INDEX.length < rcount) { + pool.free(BLUE_SWEEP_INDEX) + BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) } - function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { - var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); - return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + if(COMMON_SWEEP_QUEUE.length < rcount) { + pool.free(COMMON_SWEEP_QUEUE) + COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) } - function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { - var φ; - if (from == null) { - φ = direction * halfπ; - listener.point(-π, φ); - listener.point(0, φ); - listener.point(π, φ); - listener.point(π, 0); - listener.point(π, -φ); - listener.point(0, -φ); - listener.point(-π, -φ); - listener.point(-π, 0); - listener.point(-π, φ); - } else if (abs(from[0] - to[0]) > ε) { - var s = from[0] < to[0] ? π : -π; - φ = direction * s / 2; - listener.point(-s, φ); - listener.point(0, φ); - listener.point(s, φ); - } else { - listener.point(to[0], to[1]); - } + if(COMMON_SWEEP_INDEX.length < rcount) { + pool.free(COMMON_SWEEP_INDEX) + COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) } - function d3_geo_pointInPolygon(point, polygon) { - var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; - d3_geo_areaRingSum.reset(); - for (var i = 0, n = polygon.length; i < n; ++i) { - var ring = polygon[i], m = ring.length; - if (!m) continue; - var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; - while (true) { - if (j === m) j = 0; - point = ring[j]; - var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; - d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); - polarAngle += antimeridian ? dλ + sdλ * τ : dλ; - if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { - var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); - d3_geo_cartesianNormalize(arc); - var intersection = d3_geo_cartesianCross(meridianNormal, arc); - d3_geo_cartesianNormalize(intersection); - var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); - if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { - winding += antimeridian ^ dλ >= 0 ? 1 : -1; - } + var eventLength = 8 * rcount + if(SWEEP_EVENTS.length < eventLength) { + pool.free(SWEEP_EVENTS) + SWEEP_EVENTS = pool.mallocDouble(eventLength) + } +} + +//Remove an item from the active queue in O(1) +function sqPop(queue, index, count, item) { + var idx = index[item] + var top = queue[count-1] + queue[idx] = top + index[top] = idx +} + +//Insert an item into the active queue in O(1) +function sqPush(queue, index, count, item) { + queue[count] = item + index[item] = count +} + +//Recursion base case: use 1D sweep algorithm +function sweepBipartite( + d, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + //store events as pairs [coordinate, idx] + // + // red create: -(idx+1) + // red destroy: idx + // blue create: -(idx+BLUE_FLAG) + // blue destroy: idx+BLUE_FLAG + // + var ptr = 0 + var elemSize = 2*d + var istart = d-1 + var iend = elemSize-1 + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + for(var i=0; i= BLUE_FLAG) { + //blue destroy event + e = (e-BLUE_FLAG)|0 + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) + } else if(e >= 0) { + //red destroy event + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) + } else if(e <= -BLUE_FLAG) { + //blue create event + e = (-e-BLUE_FLAG)|0 + for(var j=0; j 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); - return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); - function visible(λ, φ) { - return Math.cos(λ) * Math.cos(φ) > cr; +} + +//Complete sweep +function sweepComplete(d, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = d-1 + var iend = elemSize-1 + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + var blueActive = 0 + var commonActive = 0 + for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { + color = 2 + i += 1 } - function clipLine(listener) { - var point0, c0, v0, v00, clean; - return { - lineStart: function() { - v00 = v0 = false; - clean = 1; - }, - point: function(λ, φ) { - var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; - if (!point0 && (v00 = v0 = v)) listener.lineStart(); - if (v !== v0) { - point2 = intersect(point0, point1); - if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { - point1[0] += ε; - point1[1] += ε; - v = visible(point1[0], point1[1]); - } - } - if (v !== v0) { - clean = 0; - if (v) { - listener.lineStart(); - point2 = intersect(point1, point0); - listener.point(point2[0], point2[1]); - } else { - point2 = intersect(point0, point1); - listener.point(point2[0], point2[1]); - listener.lineEnd(); - } - point0 = point2; - } else if (notHemisphere && point0 && smallRadius ^ v) { - var t; - if (!(c & c0) && (t = intersect(point1, point0, true))) { - clean = 0; - if (smallRadius) { - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - } else { - listener.point(t[1][0], t[1][1]); - listener.lineEnd(); - listener.lineStart(); - listener.point(t[0][0], t[0][1]); - } - } + + if(e < 0) { + //Create event + var id = -(e>>1) - 1 + + //Intersect with common + for(var j=0; j 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { - var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); - d3_geo_cartesianAdd(q1, A); - return [ q, d3_geo_spherical(q1) ]; } - } - function code(λ, φ) { - var r = smallRadius ? radius : π - radius, code = 0; - if (λ < -r) code |= 1; else if (λ > r) code |= 2; - if (φ < -r) code |= 4; else if (φ > r) code |= 8; - return code; - } - } - function d3_geom_clipLine(x0, y0, x1, y1) { - return function(line) { - var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; - r = x0 - ax; - if (!dx && r > 0) return; - r /= dx; - if (dx < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dx > 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } - r = x1 - ax; - if (!dx && r < 0) return; - r /= dx; - if (dx < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dx > 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } - r = y0 - ay; - if (!dy && r > 0) return; - r /= dy; - if (dy < 0) { - if (r < t0) return; - if (r < t1) t1 = r; - } else if (dy > 0) { - if (r > t1) return; - if (r > t0) t0 = r; + + if(color === 0) { + //Red + sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id) + } else if(color === 1) { + //Blue + sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id) + } else if(color === 2) { + //Both + sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id) } - r = y1 - ay; - if (!dy && r < 0) return; - r /= dy; - if (dy < 0) { - if (r > t1) return; - if (r > t0) t0 = r; - } else if (dy > 0) { - if (r < t0) return; - if (r < t1) t1 = r; + } else { + //Destroy event + var id = (e>>1) - 1 + if(color === 0) { + //Red + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) + } else if(color === 1) { + //Blue + sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) + } else if(color === 2) { + //Both + sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) } - if (t0 > 0) line.a = { - x: ax + t0 * dx, - y: ay + t0 * dy - }; - if (t1 < 1) line.b = { - x: ax + t1 * dx, - y: ay + t1 * dy - }; - return line; - }; + } } - var d3_geo_clipExtentMAX = 1e9; - d3.geo.clipExtent = function() { - var x0, y0, x1, y1, stream, clip, clipExtent = { - stream: function(output) { - if (stream) stream.valid = false; - stream = clip(output); - stream.valid = true; - return stream; - }, - extent: function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); - if (stream) stream.valid = false, stream = null; - return clipExtent; +} + +//Sweep and prune/scanline algorithm: +// Scan along axis, detect intersections +// Brute force all boxes along axis +function scanBipartite( + d, axis, visit, flip, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = axis + var iend = axis+d + + var redShift = 1 + var blueShift = 1 + if(flip) { + blueShift = BLUE_FLAG + } else { + redShift = BLUE_FLAG + } + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + isRed = !flip + idx -= BLUE_FLAG + } else { + isRed = !!flip + idx -= 1 } - }; - return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); - }; - function d3_geo_clipExtent(x0, y0, x1, y1) { - return function(listener) { - var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; - var clip = { - point: point, - lineStart: lineStart, - lineEnd: lineEnd, - polygonStart: function() { - listener = bufferListener; - segments = []; - polygon = []; - clean = true; - }, - polygonEnd: function() { - listener = listener_; - segments = d3.merge(segments); - var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; - if (inside || visible) { - listener.polygonStart(); - if (inside) { - listener.lineStart(); - interpolate(null, null, 1, listener); - listener.lineEnd(); - } - if (visible) { - d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); - } - listener.polygonEnd(); + if(isRed) { + sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) + } else { + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] + +red_loop: + for(var j=0; j y && d3_cross2d(a, b, p) > 0) ++wn; - } else { - if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + + for(var k=axis+2; k 0) { - do { - listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); - } while ((a = (a + direction + 4) % 4) !== a1); - } else { - listener.point(to[0], to[1]); - } - } - function pointVisible(x, y) { - return x0 <= x && x <= x1 && y0 <= y && y <= y1; - } - function point(x, y) { - if (pointVisible(x, y)) listener.point(x, y); - } - var x__, y__, v__, x_, y_, v_, first, clean; - function lineStart() { - clip.point = linePoint; - if (polygon) polygon.push(ring = []); - first = true; - v_ = false; - x_ = y_ = NaN; - } - function lineEnd() { - if (segments) { - linePoint(x__, y__); - if (v__ && v_) bufferListener.rejoin(); - segments.push(bufferListener.buffer()); - } - clip.point = point; - if (v_) listener.lineEnd(); } - function linePoint(x, y) { - x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); - y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); - var v = pointVisible(x, y); - if (polygon) ring.push([ x, y ]); - if (first) { - x__ = x, y__ = y, v__ = v; - first = false; - if (v) { - listener.lineStart(); - listener.point(x, y); + } else { + sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift) + } + } +} + +function scanComplete( + d, axis, visit, + redStart, redEnd, red, redIndex, + blueStart, blueEnd, blue, blueIndex) { + + var ptr = 0 + var elemSize = 2*d + var istart = axis + var iend = axis+d + + for(var i=redStart; iright + var n = ptr >>> 1 + isort(SWEEP_EVENTS, n) + + var redActive = 0 + for(var i=0; i= BLUE_FLAG) { + RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG + } else { + idx -= 1 + var blueId = blueIndex[idx] + var bluePtr = elemSize * idx + + var b0 = blue[bluePtr+axis+1] + var b1 = blue[bluePtr+axis+1+d] + +red_loop: + for(var j=0; j 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; + } else { + var idx = e - BLUE_FLAG + for(var j=redActive-1; j>=0; --j) { + if(RED_SWEEP_QUEUE[j] === idx) { + for(var k=j+1; k= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); - }; - albersUsa.stream = function(stream) { - var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); - return { - point: function(x, y) { - lower48Stream.point(x, y); - alaskaStream.point(x, y); - hawaiiStream.point(x, y); - }, - sphere: function() { - lower48Stream.sphere(); - alaskaStream.sphere(); - hawaiiStream.sphere(); - }, - lineStart: function() { - lower48Stream.lineStart(); - alaskaStream.lineStart(); - hawaiiStream.lineStart(); - }, - lineEnd: function() { - lower48Stream.lineEnd(); - alaskaStream.lineEnd(); - hawaiiStream.lineEnd(); - }, - polygonStart: function() { - lower48Stream.polygonStart(); - alaskaStream.polygonStart(); - hawaiiStream.polygonStart(); - }, - polygonEnd: function() { - lower48Stream.polygonEnd(); - alaskaStream.polygonEnd(); - hawaiiStream.polygonEnd(); - } - }; - }; - albersUsa.precision = function(_) { - if (!arguments.length) return lower48.precision(); - lower48.precision(_); - alaska.precision(_); - hawaii.precision(_); - return albersUsa; - }; - albersUsa.scale = function(_) { - if (!arguments.length) return lower48.scale(); - lower48.scale(_); - alaska.scale(_ * .35); - hawaii.scale(_); - return albersUsa.translate(lower48.translate()); - }; - albersUsa.translate = function(_) { - if (!arguments.length) return lower48.translate(); - var k = lower48.scale(), x = +_[0], y = +_[1]; - lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; - alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; - return albersUsa; - }; - return albersUsa.scale(1070); - }; - var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { - point: d3_noop, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: function() { - d3_geo_pathAreaPolygon = 0; - d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; - }, - polygonEnd: function() { - d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; - d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); - } - }; - function d3_geo_pathAreaRingStart() { - var x00, y00, x0, y0; - d3_geo_pathArea.point = function(x, y) { - d3_geo_pathArea.point = nextPoint; - x00 = x0 = x, y00 = y0 = y; - }; - function nextPoint(x, y) { - d3_geo_pathAreaPolygon += y0 * x - x0 * y; - x0 = x, y0 = y; - } - d3_geo_pathArea.lineEnd = function() { - nextPoint(x00, y00); - }; + module.exports.pack = toDouble + function lowUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(0, true) } - var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; - var d3_geo_pathBounds = { - point: d3_geo_pathBoundsPoint, - lineStart: d3_noop, - lineEnd: d3_noop, - polygonStart: d3_noop, - polygonEnd: d3_noop - }; - function d3_geo_pathBoundsPoint(x, y) { - if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; - if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; - if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; - if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; + module.exports.lo = lowUint + function highUint(n) { + buffer.writeDoubleLE(n, 0, true) + return buffer.readUInt32LE(4, true) } - function d3_geo_pathBuffer() { - var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; - var stream = { - point: point, - lineStart: function() { - stream.point = pointLineStart; - }, - lineEnd: lineEnd, - polygonStart: function() { - stream.lineEnd = lineEndPolygon; - }, - polygonEnd: function() { - stream.lineEnd = lineEnd; - stream.point = point; - }, - pointRadius: function(_) { - pointCircle = d3_geo_pathBufferCircle(_); - return stream; - }, - result: function() { - if (buffer.length) { - var result = buffer.join(""); - buffer = []; - return result; - } - } - }; - function point(x, y) { - buffer.push("M", x, ",", y, pointCircle); - } - function pointLineStart(x, y) { - buffer.push("M", x, ",", y); - stream.point = pointLine; - } - function pointLine(x, y) { - buffer.push("L", x, ",", y); - } - function lineEnd() { - stream.point = point; - } - function lineEndPolygon() { - buffer.push("Z"); - } - return stream; + module.exports.hi = highUint +} + +module.exports.sign = function(n) { + return module.exports.hi(n) >>> 31 +} + +module.exports.exponent = function(n) { + var b = module.exports.hi(n) + return ((b<<1) >>> 21) - 1023 +} + +module.exports.fraction = function(n) { + var lo = module.exports.lo(n) + var hi = module.exports.hi(n) + var b = hi & ((1<<20) - 1) + if(hi & 0x7ff00000) { + b += (1<<20) } - function d3_geo_pathBufferCircle(radius) { - return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; + return [lo, b] +} + +module.exports.denormalized = function(n) { + var hi = module.exports.hi(n) + return !(hi & 0x7ff00000) +} +}).call(this,require("buffer").Buffer) +},{"buffer":51}],91:[function(require,module,exports){ +"use strict" + +var doubleBits = require("double-bits") + +var SMALLEST_DENORM = Math.pow(2, -1074) +var UINT_MAX = (-1)>>>0 + +module.exports = nextafter + +function nextafter(x, y) { + if(isNaN(x) || isNaN(y)) { + return NaN } - var d3_geo_pathCentroid = { - point: d3_geo_pathCentroidPoint, - lineStart: d3_geo_pathCentroidLineStart, - lineEnd: d3_geo_pathCentroidLineEnd, - polygonStart: function() { - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; - }, - polygonEnd: function() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; - d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; - d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + if(x === y) { + return x + } + if(x === 0) { + if(y < 0) { + return -SMALLEST_DENORM + } else { + return SMALLEST_DENORM } - }; - function d3_geo_pathCentroidPoint(x, y) { - d3_geo_centroidX0 += x; - d3_geo_centroidY0 += y; - ++d3_geo_centroidZ0; } - function d3_geo_pathCentroidLineStart() { - var x0, y0; - d3_geo_pathCentroid.point = function(x, y) { - d3_geo_pathCentroid.point = nextPoint; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); - }; - function nextPoint(x, y) { - var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); - d3_geo_centroidX1 += z * (x0 + x) / 2; - d3_geo_centroidY1 += z * (y0 + y) / 2; - d3_geo_centroidZ1 += z; - d3_geo_pathCentroidPoint(x0 = x, y0 = y); + var hi = doubleBits.hi(x) + var lo = doubleBits.lo(x) + if((y > x) === (x > 0)) { + if(lo === UINT_MAX) { + hi += 1 + lo = 0 + } else { + lo += 1 + } + } else { + if(lo === 0) { + lo = UINT_MAX + hi -= 1 + } else { + lo -= 1 } } - function d3_geo_pathCentroidLineEnd() { - d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + return doubleBits.pack(lo, hi) +} +},{"double-bits":90}],92:[function(require,module,exports){ +'use strict' + +var bnadd = require('big-rat/add') + +module.exports = add + +function add(a, b) { + var n = a.length + var r = new Array(n) + for(var i=0; i 4 * δ2 && depth--) { - var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; - if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { - resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); - stream.point(x2, y2); - resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); - } - } - } - resample.precision = function(_) { - if (!arguments.length) return Math.sqrt(δ2); - maxDepth = (δ2 = _ * _) > 0 && 16; - return resample; - }; - return resample; + return r +} + +},{"big-rat":69,"big-rat/mul":78}],95:[function(require,module,exports){ +'use strict' + +var bnsub = require('big-rat/sub') + +module.exports = sub + +function sub(a, b) { + var n = a.length + var r = new Array(n) + for(var i=0; i 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { + return false } - d3_geo_transform.prototype = { - point: function(x, y) { - this.stream.point(x, y); - }, - sphere: function() { - this.stream.sphere(); - }, - lineStart: function() { - this.stream.lineStart(); - }, - lineEnd: function() { - this.stream.lineEnd(); - }, - polygonStart: function() { - this.stream.polygonStart(); - }, - polygonEnd: function() { - this.stream.polygonEnd(); - } - }; - function d3_geo_transformPoint(stream, point) { - return { - point: point, - sphere: function() { - stream.sphere(); - }, - lineStart: function() { - stream.lineStart(); - }, - lineEnd: function() { - stream.lineEnd(); - }, - polygonStart: function() { - stream.polygonStart(); - }, - polygonEnd: function() { - stream.polygonEnd(); - } - }; + + var x1 = orient(b0, a0, a1) + var y1 = orient(b1, a0, a1) + if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { + return false } - d3.geo.projection = d3_geo_projection; - d3.geo.projectionMutator = d3_geo_projectionMutator; - function d3_geo_projection(project) { - return d3_geo_projectionMutator(function() { - return project; - })(); + + //Check for degenerate collinear case + if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { + return checkCollinear(a0, a1, b0, b1) } - function d3_geo_projectionMutator(projectAt) { - var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { - x = project(x, y); - return [ x[0] * k + δx, δy - x[1] * k ]; - }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; - function projection(point) { - point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); - return [ point[0] * k + δx, δy - point[1] * k ]; - } - function invert(point) { - point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); - return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; - } - projection.stream = function(output) { - if (stream) stream.valid = false; - stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); - stream.valid = true; - return stream; - }; - projection.clipAngle = function(_) { - if (!arguments.length) return clipAngle; - preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); - return invalidate(); - }; - projection.clipExtent = function(_) { - if (!arguments.length) return clipExtent; - clipExtent = _; - postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; - return invalidate(); - }; - projection.scale = function(_) { - if (!arguments.length) return k; - k = +_; - return reset(); - }; - projection.translate = function(_) { - if (!arguments.length) return [ x, y ]; - x = +_[0]; - y = +_[1]; - return reset(); - }; - projection.center = function(_) { - if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; - λ = _[0] % 360 * d3_radians; - φ = _[1] % 360 * d3_radians; - return reset(); - }; - projection.rotate = function(_) { - if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; - δλ = _[0] % 360 * d3_radians; - δφ = _[1] % 360 * d3_radians; - δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; - return reset(); - }; - d3.rebind(projection, projectResample, "precision"); - function reset() { - projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); - var center = project(λ, φ); - δx = x - center[0] * k; - δy = y + center[1] * k; - return invalidate(); - } - function invalidate() { - if (stream) stream.valid = false, stream = null; - return projection; - } - return function() { - project = projectAt.apply(this, arguments); - projection.invert = project.invert && invert; - return reset(); - }; + + return true +} +},{"robust-orientation":259}],97:[function(require,module,exports){ +"use strict"; "use restrict"; + +module.exports = UnionFind; + +function UnionFind(count) { + this.roots = new Array(count); + this.ranks = new Array(count); + + for(var i=0; i 2 ? rotate[2] * d3_radians : 0); - function forward(coordinates) { - coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - } - forward.invert = function(coordinates) { - coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); - return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; - }; - return forward; - }; - function d3_geo_identityRotation(λ, φ) { - return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + while(roots[x0] !== x) { + var y = roots[x0] + roots[x0] = x + x0 = y } - d3_geo_identityRotation.invert = d3_geo_equirectangular; - function d3_geo_rotation(δλ, δφ, δγ) { - return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + return x; +} + +proto.link = function(x, y) { + var xr = this.find(x) + , yr = this.find(y); + if(xr === yr) { + return; } - function d3_geo_forwardRotationλ(δλ) { - return function(λ, φ) { - return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; - }; + var ranks = this.ranks + , roots = this.roots + , xd = ranks[xr] + , yd = ranks[yr]; + if(xd < yd) { + roots[xr] = yr; + } else if(yd < xd) { + roots[yr] = xr; + } else { + roots[yr] = xr; + ++ranks[xr]; } - function d3_geo_rotationλ(δλ) { - var rotation = d3_geo_forwardRotationλ(δλ); - rotation.invert = d3_geo_forwardRotationλ(-δλ); - return rotation; +} +},{}],98:[function(require,module,exports){ +(function (Buffer){ +var clone = (function() { +'use strict'; + +/** + * Clones (copies) an Object using deep copying. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). +*/ +function clone(parent, circular, depth, prototype) { + var filter; + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + filter = circular.filter; + circular = circular.circular } - function d3_geo_rotationφγ(δφ, δγ) { - var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); - function rotation(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; - return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; + + var useBuffer = typeof Buffer != 'undefined'; + + if (typeof circular == 'undefined') + circular = true; + + if (typeof depth == 'undefined') + depth = Infinity; + + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth == 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; } - rotation.invert = function(λ, φ) { - var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; - return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; - }; - return rotation; - } - d3.geo.circle = function() { - var origin = [ 0, 0 ], angle, precision = 6, interpolate; - function circle() { - var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; - interpolate(null, null, 1, { - point: function(x, y) { - ring.push(x = rotate(x, y)); - x[0] *= d3_degrees, x[1] *= d3_degrees; - } - }); - return { - type: "Polygon", - coordinates: [ ring ] - }; + + if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + child = new Buffer(parent.length); + parent.copy(child); + return child; + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } } - circle.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return circle; - }; - circle.angle = function(x) { - if (!arguments.length) return angle; - interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); - return circle; - }; - circle.precision = function(_) { - if (!arguments.length) return precision; - interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); - return circle; - }; - return circle.angle(90); - }; - function d3_geo_circleInterpolate(radius, precision) { - var cr = Math.cos(radius), sr = Math.sin(radius); - return function(from, to, direction, listener) { - var step = direction * precision; - if (from != null) { - from = d3_geo_circleAngle(cr, from); - to = d3_geo_circleAngle(cr, to); - if (direction > 0 ? from < to : from > to) from += direction * τ; - } else { - from = radius + direction * τ; - to = radius - .5 * step; + + if (circular) { + var index = allParents.indexOf(parent); + + if (index != -1) { + return allChildren[index]; } - for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { - listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + allParents.push(parent); + allChildren.push(child); + } + + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); } - }; - } - function d3_geo_circleAngle(cr, point) { - var a = d3_geo_cartesian(point); - a[0] -= cr; - d3_geo_cartesianNormalize(a); - var angle = d3_acos(-a[1]); - return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + return child; } - d3.geo.distance = function(a, b) { - var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; - return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); - }; - d3.geo.graticule = function() { - var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; - function graticule() { - return { - type: "MultiLineString", - coordinates: lines() - }; + + return _clone(parent, depth); +} + +/** + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ +clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); +}; + +// private utility functions + +function __objToStr(o) { + return Object.prototype.toString.call(o); +}; +clone.__objToStr = __objToStr; + +function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; +}; +clone.__isDate = __isDate; + +function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; +}; +clone.__isArray = __isArray; + +function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; +}; +clone.__isRegExp = __isRegExp; + +function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; +}; +clone.__getRegExpFlags = __getRegExpFlags; + +return clone; +})(); + +if (typeof module === 'object' && module.exports) { + module.exports = clone; +} + +}).call(this,require("buffer").Buffer) +},{"buffer":51}],99:[function(require,module,exports){ +module.exports={"jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}],"hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}],"hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}],"cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}],"spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}],"summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}],"autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}],"winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}],"bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}],"copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}],"greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}],"yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}],"greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}],"yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}],"bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}],"rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}],"picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}],"rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}],"portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}],"blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}],"earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}],"electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}]}; + +},{}],100:[function(require,module,exports){ +/* + * Ben Postlethwaite + * January 2013 + * License MIT + */ +'use strict'; + +var at = require('arraytools'); +var clone = require('clone'); +var colorScale = require('./colorScales'); + +module.exports = function (spec) { + + /* + * Default Options + */ + var indicies, rgba, fromrgba, torgba, + nsteps, cmap, colormap, format, + nshades, colors, alpha, index, i, + r = [], + g = [], + b = [], + a = []; + + if ( !at.isPlainObject(spec) ) spec = {}; + + nshades = spec.nshades || 72; + format = spec.format || 'hex'; + + colormap = spec.colormap; + if (!colormap) colormap = 'jet'; + + if (typeof colormap === 'string') { + colormap = colormap.toLowerCase(); + + if (!colorScale[colormap]) { + throw Error(colormap + ' not a supported colorscale'); + } + + cmap = clone(colorScale[colormap]); + + } else if (Array.isArray(colormap)) { + cmap = clone(colormap); + + } else { + throw Error('unsupported colormap option', colormap); } - function lines() { - return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { - return abs(x % DX) > ε; - }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { - return abs(y % DY) > ε; - }).map(y)); + + if (cmap.length > nshades) { + throw new Error( + colormap+' map requires nshades to be at least size '+cmap.length + ); } - graticule.lines = function() { - return lines().map(function(coordinates) { - return { - type: "LineString", - coordinates: coordinates - }; - }); - }; - graticule.outline = function() { - return { - type: "Polygon", - coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] - }; - }; - graticule.extent = function(_) { - if (!arguments.length) return graticule.minorExtent(); - return graticule.majorExtent(_).minorExtent(_); - }; - graticule.majorExtent = function(_) { - if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; - X0 = +_[0][0], X1 = +_[1][0]; - Y0 = +_[0][1], Y1 = +_[1][1]; - if (X0 > X1) _ = X0, X0 = X1, X1 = _; - if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; - return graticule.precision(precision); - }; - graticule.minorExtent = function(_) { - if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; - x0 = +_[0][0], x1 = +_[1][0]; - y0 = +_[0][1], y1 = +_[1][1]; - if (x0 > x1) _ = x0, x0 = x1, x1 = _; - if (y0 > y1) _ = y0, y0 = y1, y1 = _; - return graticule.precision(precision); - }; - graticule.step = function(_) { - if (!arguments.length) return graticule.minorStep(); - return graticule.majorStep(_).minorStep(_); - }; - graticule.majorStep = function(_) { - if (!arguments.length) return [ DX, DY ]; - DX = +_[0], DY = +_[1]; - return graticule; - }; - graticule.minorStep = function(_) { - if (!arguments.length) return [ dx, dy ]; - dx = +_[0], dy = +_[1]; - return graticule; - }; - graticule.precision = function(_) { - if (!arguments.length) return precision; - precision = +_; - x = d3_geo_graticuleX(y0, y1, 90); - y = d3_geo_graticuleY(x0, x1, precision); - X = d3_geo_graticuleX(Y0, Y1, 90); - Y = d3_geo_graticuleY(X0, X1, precision); - return graticule; - }; - return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); - }; - function d3_geo_graticuleX(y0, y1, dy) { - var y = d3.range(y0, y1 - ε, dy).concat(y1); - return function(x) { - return y.map(function(y) { - return [ x, y ]; - }); - }; + + if (!Array.isArray(spec.alpha)) { + + if (typeof spec.alpha === 'number') { + alpha = [spec.alpha, spec.alpha]; + + } else { + alpha = [1, 1]; + } + + } else if (spec.alpha.length !== 2) { + alpha = [1, 1]; + + } else { + alpha = clone(spec.alpha); + } + + /* + * map index points from 0->1 to 0 -> n-1 + */ + indicies = cmap.map(function(c) { + return Math.round(c.index * nshades); + }); + + /* + * Add alpha channel to the map + */ + if (alpha[0] < 0) alpha[0] = 0; + if (alpha[1] < 0) alpha[0] = 0; + if (alpha[0] > 1) alpha[0] = 1; + if (alpha[1] > 1) alpha[0] = 1; + + for (i = 0; i < indicies.length; ++i) { + index = cmap[i].index; + rgba = cmap[i].rgb; + + // if user supplies their own map use it + if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue; + rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index; + } + + /* + * map increasing linear values between indicies to + * linear steps in colorvalues + */ + for (i = 0; i < indicies.length-1; ++i) { + nsteps = indicies[i+1] - indicies[i]; + fromrgba = cmap[i].rgb; + torgba = cmap[i+1].rgb; + r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) ); + g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) ); + b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) ); + a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) ); + } + + r = r.map( Math.round ); + g = g.map( Math.round ); + b = b.map( Math.round ); + + colors = at.zip(r, g, b, a); + + if (format === 'hex') colors = colors.map( rgb2hex ); + if (format === 'rgbaString') colors = colors.map( rgbaStr ); + + return colors; +}; + + +function rgb2hex (rgba) { + var dig, hex = '#'; + for (var i = 0; i < 3; ++i) { + dig = rgba[i]; + dig = dig.toString(16); + hex += ('00' + dig).substr( dig.length ); + } + return hex; +} + +function rgbaStr (rgba) { + return 'rgba(' + rgba.join(',') + ')'; +} + +},{"./colorScales":99,"arraytools":49,"clone":98}],101:[function(require,module,exports){ +module.exports = compareCells + +var min = Math.min + +function compareInt(a, b) { + return a - b +} + +function compareCells(a, b) { + var n = a.length + , t = a.length - b.length + if(t) { + return t } - function d3_geo_graticuleY(x0, x1, dx) { - var x = d3.range(x0, x1 - ε, dx).concat(x1); - return function(y) { - return x.map(function(x) { - return [ x, y ]; - }); - }; + switch(n) { + case 0: + return 0 + case 1: + return a[0] - b[0] + case 2: + return (a[0]+a[1]-b[0]-b[1]) || + min(a[0],a[1]) - min(b[0],b[1]) + case 3: + var l1 = a[0]+a[1] + , m1 = b[0]+b[1] + t = l1+a[2] - (m1+b[2]) + if(t) { + return t + } + var l0 = min(a[0], a[1]) + , m0 = min(b[0], b[1]) + return min(l0, a[2]) - min(m0, b[2]) || + min(l0+a[2], l1) - min(m0+b[2], m1) + case 4: + var aw=a[0], ax=a[1], ay=a[2], az=a[3] + , bw=b[0], bx=b[1], by=b[2], bz=b[3] + return (aw+ax+ay+az)-(bw+bx+by+bz) || + min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) || + min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) - + min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) || + min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) - + min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz) + default: + var as = a.slice().sort(compareInt) + var bs = b.slice().sort(compareInt) + for(var i=0; i points[hi][0]) { + hi = i } } - function d3_geo_azimuthal(scale, angle) { - function azimuthal(λ, φ) { - var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); - return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + if(lo < hi) { + return [[lo], [hi]] + } else if(lo > hi) { + return [[hi], [lo]] + } else { + return [[lo]] + } +} +},{}],104:[function(require,module,exports){ +'use strict' + +module.exports = convexHull2D + +var monotoneHull = require('monotone-convex-hull-2d') + +function convexHull2D(points) { + var hull = monotoneHull(points) + var h = hull.length + if(h <= 2) { + return [] + } + var edges = new Array(h) + var a = hull[h-1] + for(var i=0; i 0) { - if (φ < -halfπ + ε) φ = -halfπ + ε; + return npoints +} + +function invPermute(cells, front) { + var nc = cells.length + var nf = front.length + for(var i=0; i halfπ - ε) φ = halfπ - ε; + x = x - nf + for(var k=0; k= front[k]) { + x += 1 + } + } + c[j] = x } - var ρ = F / Math.pow(t(φ), n); - return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } - forward.invert = function(x, y) { - var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); - return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; - }; - return forward; } - (d3.geo.conicConformal = function() { - return d3_geo_conic(d3_geo_conicConformal); - }).raw = d3_geo_conicConformal; - function d3_geo_conicEquidistant(φ0, φ1) { - var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; - if (abs(n) < ε) return d3_geo_equirectangular; - function forward(λ, φ) { - var ρ = G - φ; - return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; + return cells +} + +function convexHullnD(points, d) { + try { + return ich(points, true) + } catch(e) { + //If point set is degenerate, try to find a basis and rerun it + var ah = aff(points) + if(ah.length <= d) { + //No basis, no try + return [] } - forward.invert = function(x, y) { - var ρ0_y = G - y; - return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; - }; - return forward; + var npoints = permute(points, ah) + var nhull = ich(npoints, true) + return invPermute(nhull, ah) } - (d3.geo.conicEquidistant = function() { - return d3_geo_conic(d3_geo_conicEquidistant); - }).raw = d3_geo_conicEquidistant; - var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { - return 1 / cosλcosφ; - }, Math.atan); - (d3.geo.gnomonic = function() { - return d3_geo_projection(d3_geo_gnomonic); - }).raw = d3_geo_gnomonic; - function d3_geo_mercator(λ, φ) { - return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; +} +},{"affine-hull":106,"incremental-convex-hull":235}],106:[function(require,module,exports){ +'use strict' + +module.exports = affineHull + +var orient = require('robust-orientation') + +function linearlyIndependent(points, d) { + var nhull = new Array(d+1) + for(var i=0; i 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), - [ _[0], _[1], _[2] - 90 ]); - }; - return rotate([ 0, 0, 90 ]); - }).raw = d3_geo_transverseMercator; - d3.geom = {}; - function d3_geom_pointX(d) { - return d[0]; - } - function d3_geom_pointY(d) { - return d[1]; - } - d3.geom.hull = function(vertices) { - var x = d3_geom_pointX, y = d3_geom_pointY; - if (arguments.length) return hull(vertices); - function hull(data) { - if (data.length < 3) return []; - var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; - for (i = 0; i < n; i++) { - points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); - } - points.sort(d3_geom_hullOrder); - for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); - var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); - var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; - for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); - for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); - return polygon; - } - hull.x = function(_) { - return arguments.length ? (x = _, hull) : x; - }; - hull.y = function(_) { - return arguments.length ? (y = _, hull) : y; - }; - return hull; - }; - function d3_geom_hullUpper(points) { - var n = points.length, hull = [ 0, 1 ], hs = 2; - for (var i = 2; i < n; i++) { - while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; - hull[hs++] = i; - } - return hull.slice(0, hs); - } - function d3_geom_hullOrder(a, b) { - return a[0] - b[0] || a[1] - b[1]; - } - d3.geom.polygon = function(coordinates) { - d3_subclass(coordinates, d3_geom_polygonPrototype); - return coordinates; - }; - var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; - d3_geom_polygonPrototype.area = function() { - var i = -1, n = this.length, a, b = this[n - 1], area = 0; - while (++i < n) { - a = b; - b = this[i]; - area += a[1] * b[0] - a[0] * b[1]; - } - return area * .5; - }; - d3_geom_polygonPrototype.centroid = function(k) { - var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; - if (!arguments.length) k = -1 / (6 * this.area()); - while (++i < n) { - a = b; - b = this[i]; - c = a[0] * b[1] - b[0] * a[1]; - x += (a[0] + b[0]) * c; - y += (a[1] + b[1]) * c; - } - return [ x * k, y * k ]; - }; - d3_geom_polygonPrototype.clip = function(subject) { - var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; - while (++i < n) { - input = subject.slice(); - subject.length = 0; - b = this[i]; - c = input[(m = input.length - closed) - 1]; - j = -1; - while (++j < m) { - d = input[j]; - if (d3_geom_polygonInside(d, a, b)) { - if (!d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - subject.push(d); - } else if (d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - c = d; - } - if (closed) subject.push(subject[0]); - a = b; - } - return subject; - }; - function d3_geom_polygonInside(p, a, b) { - return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); - } - function d3_geom_polygonIntersect(c, d, a, b) { - var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); - return [ x1 + ua * x21, y1 + ua * y21 ]; - } - function d3_geom_polygonClosed(coordinates) { - var a = coordinates[0], b = coordinates[coordinates.length - 1]; - return !(a[0] - b[0] || a[1] - b[1]); - } - var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; - function d3_geom_voronoiBeach() { - d3_geom_voronoiRedBlackNode(this); - this.edge = this.site = this.circle = null; - } - function d3_geom_voronoiCreateBeach(site) { - var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); - beach.site = site; - return beach; - } - function d3_geom_voronoiDetachBeach(beach) { - d3_geom_voronoiDetachCircle(beach); - d3_geom_voronoiBeaches.remove(beach); - d3_geom_voronoiBeachPool.push(beach); - d3_geom_voronoiRedBlackNode(beach); + return false +} + +function affineHull(points) { + var n = points.length + if(n === 0) { + return [] } - function d3_geom_voronoiRemoveBeach(beach) { - var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { - x: x, - y: y - }, previous = beach.P, next = beach.N, disappearing = [ beach ]; - d3_geom_voronoiDetachBeach(beach); - var lArc = previous; - while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { - previous = lArc.P; - disappearing.unshift(lArc); - d3_geom_voronoiDetachBeach(lArc); - lArc = previous; - } - disappearing.unshift(lArc); - d3_geom_voronoiDetachCircle(lArc); - var rArc = next; - while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { - next = rArc.N; - disappearing.push(rArc); - d3_geom_voronoiDetachBeach(rArc); - rArc = next; - } - disappearing.push(rArc); - d3_geom_voronoiDetachCircle(rArc); - var nArcs = disappearing.length, iArc; - for (iArc = 1; iArc < nArcs; ++iArc) { - rArc = disappearing[iArc]; - lArc = disappearing[iArc - 1]; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); - } - lArc = disappearing[0]; - rArc = disappearing[nArcs - 1]; - rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); + if(n === 1) { + return [0] } - function d3_geom_voronoiAddBeach(site) { - var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; - while (node) { - dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; - if (dxl > ε) node = node.L; else { - dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); - if (dxr > ε) { - if (!node.R) { - lArc = node; - break; - } - node = node.R; - } else { - if (dxl > -ε) { - lArc = node.P; - rArc = node; - } else if (dxr > -ε) { - lArc = node; - rArc = node.N; - } else { - lArc = rArc = node; - } - break; - } - } - } - var newArc = d3_geom_voronoiCreateBeach(site); - d3_geom_voronoiBeaches.insert(lArc, newArc); - if (!lArc && !rArc) return; - if (lArc === rArc) { - d3_geom_voronoiDetachCircle(lArc); - rArc = d3_geom_voronoiCreateBeach(lArc.site); - d3_geom_voronoiBeaches.insert(newArc, rArc); - newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - return; + var d = points[0].length + var frame = [ points[0] ] + var index = [ 0 ] + for(var i=1; i ε || abs(y3 - y2) > ε) { - halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { - x: x0, - y: abs(x2 - x0) < ε ? y2 : y1 - } : abs(y3 - y1) < ε && x1 - x3 > ε ? { - x: abs(y2 - y1) < ε ? x2 : x1, - y: y1 - } : abs(x3 - x1) < ε && y3 - y0 > ε ? { - x: x1, - y: abs(x2 - x1) < ε ? y2 : y0 - } : abs(y3 - y0) < ε && x3 - x0 > ε ? { - x: abs(y2 - y0) < ε ? x2 : x0, - y: y0 - } : null), cell.site, null)); - ++nHalfEdges; - } - } + + if(n === 2 && + points[0][0] === points[1][0] && + points[0][1] === points[1][1]) { + return [0] } + + return result } - function d3_geom_voronoiHalfEdgeOrder(a, b) { - return b.angle - a.angle; - } - function d3_geom_voronoiCircle() { - d3_geom_voronoiRedBlackNode(this); - this.x = this.y = this.arc = this.site = this.cy = null; + + //Sort point indices along x-axis + var sorted = new Array(n) + for(var i=0; i= -ε2) return; - var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; - var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); - circle.arc = arc; - circle.site = cSite; - circle.x = x + bx; - circle.y = cy + Math.sqrt(x * x + y * y); - circle.cy = cy; - arc.circle = circle; - var before = null, node = d3_geom_voronoiCircles._; - while (node) { - if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { - if (node.L) node = node.L; else { - before = node.P; - break; - } - } else { - if (node.R) node = node.R; else { - before = node; - break; - } - } + sorted.sort(function(a,b) { + var d = points[a][0]-points[b][0] + if(d) { + return d } - d3_geom_voronoiCircles.insert(before, circle); - if (!before) d3_geom_voronoiFirstCircle = circle; - } - function d3_geom_voronoiDetachCircle(arc) { - var circle = arc.circle; - if (circle) { - if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; - d3_geom_voronoiCircles.remove(circle); - d3_geom_voronoiCirclePool.push(circle); - d3_geom_voronoiRedBlackNode(circle); - arc.circle = null; + return points[a][1] - points[b][1] + }) + + //Construct upper and lower hulls + var lower = [sorted[0], sorted[1]] + var upper = [sorted[0], sorted[1]] + + for(var i=2; i 1 && orient( + points[lower[m-2]], + points[lower[m-1]], + p) <= 0) { + m -= 1 + lower.pop() } - } - function d3_geom_voronoiClipEdges(extent) { - var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; - while (i--) { - e = edges[i]; - if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { - e.a = e.b = null; - edges.splice(i, 1); - } + lower.push(idx) + + //Insert into upper list + m = upper.length + while(m > 1 && orient( + points[upper[m-2]], + points[upper[m-1]], + p) >= 0) { + m -= 1 + upper.pop() } + upper.push(idx) } - function d3_geom_voronoiConnectEdge(edge, extent) { - var vb = edge.b; - if (vb) return true; - var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; - if (ry === ly) { - if (fx < x0 || fx >= x1) return; - if (lx > rx) { - if (!va) va = { - x: fx, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: fx, - y: y1 - }; - } else { - if (!va) va = { - x: fx, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: fx, - y: y0 - }; - } - } else { - fm = (lx - rx) / (ry - ly); - fb = fy - fm * fx; - if (fm < -1 || fm > 1) { - if (lx > rx) { - if (!va) va = { - x: (y0 - fb) / fm, - y: y0 - }; else if (va.y >= y1) return; - vb = { - x: (y1 - fb) / fm, - y: y1 - }; - } else { - if (!va) va = { - x: (y1 - fb) / fm, - y: y1 - }; else if (va.y < y0) return; - vb = { - x: (y0 - fb) / fm, - y: y0 - }; - } - } else { - if (ly < ry) { - if (!va) va = { - x: x0, - y: fm * x0 + fb - }; else if (va.x >= x1) return; - vb = { - x: x1, - y: fm * x1 + fb - }; - } else { - if (!va) va = { - x: x1, - y: fm * x1 + fb - }; else if (va.x < x0) return; - vb = { - x: x0, - y: fm * x0 + fb - }; - } - } - } - edge.a = va; - edge.b = vb; - return true; + + //Merge lists together + var result = new Array(upper.length + lower.length - 2) + var ptr = 0 + for(var i=0, nl=lower.length; i0; --j) { + result[ptr++] = upper[j] } - function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, rSite); - d3_geom_voronoiEdges.push(edge); - if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); - if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); - d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); - d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); - return edge; - } - function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, null); - edge.a = va; - edge.b = vb; - d3_geom_voronoiEdges.push(edge); - return edge; - } - function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { - if (!edge.a && !edge.b) { - edge.a = vertex; - edge.l = lSite; - edge.r = rSite; - } else if (edge.l === rSite) { - edge.b = vertex; - } else { - edge.a = vertex; - } - } - function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { - var va = edge.a, vb = edge.b; - this.edge = edge; - this.site = lSite; - this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); - } - d3_geom_voronoiHalfEdge.prototype = { - start: function() { - return this.edge.l === this.site ? this.edge.a : this.edge.b; - }, - end: function() { - return this.edge.l === this.site ? this.edge.b : this.edge.a; - } - }; - function d3_geom_voronoiRedBlackTree() { - this._ = null; - } - function d3_geom_voronoiRedBlackNode(node) { - node.U = node.C = node.L = node.R = node.P = node.N = null; - } - d3_geom_voronoiRedBlackTree.prototype = { - insert: function(after, node) { - var parent, grandpa, uncle; - if (after) { - node.P = after; - node.N = after.N; - if (after.N) after.N.P = node; - after.N = node; - if (after.R) { - after = after.R; - while (after.L) after = after.L; - after.L = node; - } else { - after.R = node; - } - parent = after; - } else if (this._) { - after = d3_geom_voronoiRedBlackFirst(this._); - node.P = null; - node.N = after; - after.P = after.L = node; - parent = after; - } else { - node.P = node.N = null; - this._ = node; - parent = null; - } - node.L = node.R = null; - node.U = parent; - node.C = true; - after = node; - while (parent && parent.C) { - grandpa = parent.U; - if (parent === grandpa.L) { - uncle = grandpa.R; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.R) { - d3_geom_voronoiRedBlackRotateLeft(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateRight(this, grandpa); - } - } else { - uncle = grandpa.L; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.L) { - d3_geom_voronoiRedBlackRotateRight(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, grandpa); - } - } - parent = after.U; - } - this._.C = false; - }, - remove: function(node) { - if (node.N) node.N.P = node.P; - if (node.P) node.P.N = node.N; - node.N = node.P = null; - var parent = node.U, sibling, left = node.L, right = node.R, next, red; - if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); - if (parent) { - if (parent.L === node) parent.L = next; else parent.R = next; - } else { - this._ = next; - } - if (left && right) { - red = next.C; - next.C = node.C; - next.L = left; - left.U = next; - if (next !== right) { - parent = next.U; - next.U = node.U; - node = next.R; - parent.L = node; - next.R = right; - right.U = next; - } else { - next.U = parent; - parent = next; - node = next.R; - } - } else { - red = node.C; - node = next; - } - if (node) node.U = parent; - if (red) return; - if (node && node.C) { - node.C = false; - return; - } - do { - if (node === this._) break; - if (node === parent.L) { - sibling = parent.R; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - sibling = parent.R; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.R || !sibling.R.C) { - sibling.L.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateRight(this, sibling); - sibling = parent.R; - } - sibling.C = parent.C; - parent.C = sibling.R.C = false; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - node = this._; - break; - } - } else { - sibling = parent.L; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateRight(this, parent); - sibling = parent.L; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.L || !sibling.L.C) { - sibling.R.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, sibling); - sibling = parent.L; - } - sibling.C = parent.C; - parent.C = sibling.L.C = false; - d3_geom_voronoiRedBlackRotateRight(this, parent); - node = this._; - break; - } - } - sibling.C = true; - node = parent; - parent = parent.U; - } while (!node.C); - if (node) node.C = false; - } - }; - function d3_geom_voronoiRedBlackRotateLeft(tree, node) { - var p = node, q = node.R, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; - } else { - tree._ = q; - } - q.U = parent; - p.U = q; - p.R = q.L; - if (p.R) p.R.U = p; - q.L = p; - } - function d3_geom_voronoiRedBlackRotateRight(tree, node) { - var p = node, q = node.L, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; else parent.R = q; - } else { - tree._ = q; - } - q.U = parent; - p.U = q; - p.L = q.R; - if (p.L) p.L.U = p; - q.R = p; - } - function d3_geom_voronoiRedBlackFirst(node) { - while (node.L) node = node.L; - return node; - } - function d3_geom_voronoi(sites, bbox) { - var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; - d3_geom_voronoiEdges = []; - d3_geom_voronoiCells = new Array(sites.length); - d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); - d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); - while (true) { - circle = d3_geom_voronoiFirstCircle; - if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { - if (site.x !== x0 || site.y !== y0) { - d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); - d3_geom_voronoiAddBeach(site); - x0 = site.x, y0 = site.y; - } - site = sites.pop(); - } else if (circle) { - d3_geom_voronoiRemoveBeach(circle.arc); - } else { - break; - } - } - if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); - var diagram = { - cells: d3_geom_voronoiCells, - edges: d3_geom_voronoiEdges - }; - d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; - return diagram; - } - function d3_geom_voronoiVertexOrder(a, b) { - return b.y - a.y || b.x - a.x; - } - d3.geom.voronoi = function(points) { - var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; - if (points) return voronoi(points); - function voronoi(data) { - var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; - d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { - var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { - var s = e.start(); - return [ s.x, s.y ]; - }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; - polygon.point = data[i]; - }); - return polygons; - } - function sites(data) { - return data.map(function(d, i) { - return { - x: Math.round(fx(d, i) / ε) * ε, - y: Math.round(fy(d, i) / ε) * ε, - i: i - }; - }); - } - voronoi.links = function(data) { - return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { - return edge.l && edge.r; - }).map(function(edge) { - return { - source: data[edge.l.i], - target: data[edge.r.i] - }; - }); - }; - voronoi.triangles = function(data) { - var triangles = []; - d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { - var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; - while (++j < m) { - e0 = e1; - s0 = s1; - e1 = edges[j].edge; - s1 = e1.l === site ? e1.r : e1.l; - if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { - triangles.push([ data[i], data[s0.i], data[s1.i] ]); - } - } - }); - return triangles; - }; - voronoi.x = function(_) { - return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; - }; - voronoi.y = function(_) { - return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; - }; - voronoi.clipExtent = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; - clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; - return voronoi; - }; - voronoi.size = function(_) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; - return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); - }; - return voronoi; - }; - var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; - function d3_geom_voronoiTriangleArea(a, b, c) { - return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); - } - d3.geom.delaunay = function(vertices) { - return d3.geom.voronoi().triangles(vertices); - }; - d3.geom.quadtree = function(points, x1, y1, x2, y2) { - var x = d3_geom_pointX, y = d3_geom_pointY, compat; - if (compat = arguments.length) { - x = d3_geom_quadtreeCompatX; - y = d3_geom_quadtreeCompatY; - if (compat === 3) { - y2 = y1; - x2 = x1; - y1 = x1 = 0; - } - return quadtree(points); - } - function quadtree(data) { - var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; - if (x1 != null) { - x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; - } else { - x2_ = y2_ = -(x1_ = y1_ = Infinity); - xs = [], ys = []; - n = data.length; - if (compat) for (i = 0; i < n; ++i) { - d = data[i]; - if (d.x < x1_) x1_ = d.x; - if (d.y < y1_) y1_ = d.y; - if (d.x > x2_) x2_ = d.x; - if (d.y > y2_) y2_ = d.y; - xs.push(d.x); - ys.push(d.y); - } else for (i = 0; i < n; ++i) { - var x_ = +fx(d = data[i], i), y_ = +fy(d, i); - if (x_ < x1_) x1_ = x_; - if (y_ < y1_) y1_ = y_; - if (x_ > x2_) x2_ = x_; - if (y_ > y2_) y2_ = y_; - xs.push(x_); - ys.push(y_); - } - } - var dx = x2_ - x1_, dy = y2_ - y1_; - if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; - function insert(n, d, x, y, x1, y1, x2, y2) { - if (isNaN(x) || isNaN(y)) return; - if (n.leaf) { - var nx = n.x, ny = n.y; - if (nx != null) { - if (abs(nx - x) + abs(ny - y) < .01) { - insertChild(n, d, x, y, x1, y1, x2, y2); - } else { - var nPoint = n.point; - n.x = n.y = n.point = null; - insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); - insertChild(n, d, x, y, x1, y1, x2, y2); - } - } else { - n.x = x, n.y = y, n.point = d; - } - } else { - insertChild(n, d, x, y, x1, y1, x2, y2); - } - } - function insertChild(n, d, x, y, x1, y1, x2, y2) { - var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; - n.leaf = false; - n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); - if (right) x1 = xm; else x2 = xm; - if (below) y1 = ym; else y2 = ym; - insert(n, d, x, y, x1, y1, x2, y2); - } - var root = d3_geom_quadtreeNode(); - root.add = function(d) { - insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); - }; - root.visit = function(f) { - d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); - }; - root.find = function(point) { - return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); - }; - i = -1; - if (x1 == null) { - while (++i < n) { - insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); - } - --i; - } else data.forEach(root.add); - xs = ys = data = d = null; - return root; - } - quadtree.x = function(_) { - return arguments.length ? (x = _, quadtree) : x; - }; - quadtree.y = function(_) { - return arguments.length ? (y = _, quadtree) : y; - }; - quadtree.extent = function(_) { - if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], - y2 = +_[1][1]; - return quadtree; - }; - quadtree.size = function(_) { - if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; - if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; - return quadtree; - }; - return quadtree; - }; - function d3_geom_quadtreeCompatX(d) { - return d.x; - } - function d3_geom_quadtreeCompatY(d) { - return d.y; - } - function d3_geom_quadtreeNode() { - return { - leaf: true, - nodes: [], - point: null, - x: null, - y: null - }; - } - function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { - if (!f(node, x1, y1, x2, y2)) { - var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; - if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); - if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); - if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); - if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); - } - } - function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { - var minDistance2 = Infinity, closestPoint; - (function find(node, x1, y1, x2, y2) { - if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; - if (point = node.point) { - var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; - if (distance2 < minDistance2) { - var distance = Math.sqrt(minDistance2 = distance2); - x0 = x - distance, y0 = y - distance; - x3 = x + distance, y3 = y + distance; - closestPoint = point; - } - } - var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; - for (var i = below << 1 | right, j = i + 4; i < j; ++i) { - if (node = children[i & 3]) switch (i & 3) { - case 0: - find(node, x1, y1, xm, ym); - break; - - case 1: - find(node, xm, y1, x2, ym); - break; - - case 2: - find(node, x1, ym, xm, y2); - break; - case 3: - find(node, xm, ym, x2, y2); - break; - } - } - })(root, x0, y0, x3, y3); - return closestPoint; - } - d3.interpolateRgb = d3_interpolateRgb; - function d3_interpolateRgb(a, b) { - a = d3.rgb(a); - b = d3.rgb(b); - var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; - return function(t) { - return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); - }; - } - d3.interpolateObject = d3_interpolateObject; - function d3_interpolateObject(a, b) { - var i = {}, c = {}, k; - for (k in a) { - if (k in b) { - i[k] = d3_interpolate(a[k], b[k]); - } else { - c[k] = a[k]; - } - } - for (k in b) { - if (!(k in a)) { - c[k] = b[k]; - } - } - return function(t) { - for (k in i) c[k] = i[k](t); - return c; - }; - } - d3.interpolateNumber = d3_interpolateNumber; - function d3_interpolateNumber(a, b) { - a = +a, b = +b; - return function(t) { - return a * (1 - t) + b * t; - }; - } - d3.interpolateString = d3_interpolateString; - function d3_interpolateString(a, b) { - var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; - a = a + "", b = b + ""; - while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { - if ((bs = bm.index) > bi) { - bs = b.slice(bi, bs); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - if ((am = am[0]) === (bm = bm[0])) { - if (s[i]) s[i] += bm; else s[++i] = bm; - } else { - s[++i] = null; - q.push({ - i: i, - x: d3_interpolateNumber(am, bm) - }); - } - bi = d3_interpolate_numberB.lastIndex; - } - if (bi < b.length) { - bs = b.slice(bi); - if (s[i]) s[i] += bs; else s[++i] = bs; - } - return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { - return b(t) + ""; - }) : function() { - return b; - } : (b = q.length, function(t) { - for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }); - } - var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); - d3.interpolate = d3_interpolate; - function d3_interpolate(a, b) { - var i = d3.interpolators.length, f; - while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; - return f; - } - d3.interpolators = [ function(a, b) { - var t = typeof b; - return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); - } ]; - d3.interpolateArray = d3_interpolateArray; - function d3_interpolateArray(a, b) { - var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; - for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); - for (;i < na; ++i) c[i] = a[i]; - for (;i < nb; ++i) c[i] = b[i]; - return function(t) { - for (i = 0; i < n0; ++i) c[i] = x[i](t); - return c; - }; - } - var d3_ease_default = function() { - return d3_identity; - }; - var d3_ease = d3.map({ - linear: d3_ease_default, - poly: d3_ease_poly, - quad: function() { - return d3_ease_quad; - }, - cubic: function() { - return d3_ease_cubic; - }, - sin: function() { - return d3_ease_sin; - }, - exp: function() { - return d3_ease_exp; - }, - circle: function() { - return d3_ease_circle; - }, - elastic: d3_ease_elastic, - back: d3_ease_back, - bounce: function() { - return d3_ease_bounce; - } - }); - var d3_ease_mode = d3.map({ - "in": d3_identity, - out: d3_ease_reverse, - "in-out": d3_ease_reflect, - "out-in": function(f) { - return d3_ease_reflect(d3_ease_reverse(f)); - } - }); - d3.ease = function(name) { - var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; - t = d3_ease.get(t) || d3_ease_default; - m = d3_ease_mode.get(m) || d3_identity; - return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); - }; - function d3_ease_clamp(f) { - return function(t) { - return t <= 0 ? 0 : t >= 1 ? 1 : f(t); - }; - } - function d3_ease_reverse(f) { - return function(t) { - return 1 - f(1 - t); - }; - } - function d3_ease_reflect(f) { - return function(t) { - return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); - }; - } - function d3_ease_quad(t) { - return t * t; - } - function d3_ease_cubic(t) { - return t * t * t; - } - function d3_ease_cubicInOut(t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - var t2 = t * t, t3 = t2 * t; - return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); - } - function d3_ease_poly(e) { - return function(t) { - return Math.pow(t, e); - }; - } - function d3_ease_sin(t) { - return 1 - Math.cos(t * halfπ); - } - function d3_ease_exp(t) { - return Math.pow(2, 10 * (t - 1)); - } - function d3_ease_circle(t) { - return 1 - Math.sqrt(1 - t * t); - } - function d3_ease_elastic(a, p) { - var s; - if (arguments.length < 2) p = .45; - if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; - return function(t) { - return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); - }; - } - function d3_ease_back(s) { - if (!s) s = 1.70158; - return function(t) { - return t * t * ((s + 1) * t - s); - }; - } - function d3_ease_bounce(t) { - return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; - } - d3.interpolateHcl = d3_interpolateHcl; - function d3_interpolateHcl(a, b) { - a = d3.hcl(a); - b = d3.hcl(b); - var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; - if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; - if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; - }; - } - d3.interpolateHsl = d3_interpolateHsl; - function d3_interpolateHsl(a, b) { - a = d3.hsl(a); - b = d3.hsl(b); - var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; - if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; - if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; - return function(t) { - return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; - }; - } - d3.interpolateLab = d3_interpolateLab; - function d3_interpolateLab(a, b) { - a = d3.lab(a); - b = d3.lab(b); - var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; - return function(t) { - return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; - }; - } - d3.interpolateRound = d3_interpolateRound; - function d3_interpolateRound(a, b) { - b -= a; - return function(t) { - return Math.round(a + b * t); - }; - } - d3.transform = function(string) { - var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); - return (d3.transform = function(string) { - if (string != null) { - g.setAttribute("transform", string); - var t = g.transform.baseVal.consolidate(); - } - return new d3_transform(t ? t.matrix : d3_transformIdentity); - })(string); - }; - function d3_transform(m) { - var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; - if (r0[0] * r1[1] < r1[0] * r0[1]) { - r0[0] *= -1; - r0[1] *= -1; - kx *= -1; - kz *= -1; - } - this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; - this.translate = [ m.e, m.f ]; - this.scale = [ kx, ky ]; - this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; - } - d3_transform.prototype.toString = function() { - return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; - }; - function d3_transformDot(a, b) { - return a[0] * b[0] + a[1] * b[1]; - } - function d3_transformNormalize(a) { - var k = Math.sqrt(d3_transformDot(a, a)); - if (k) { - a[0] /= k; - a[1] /= k; - } - return k; - } - function d3_transformCombine(a, b, k) { - a[0] += k * b[0]; - a[1] += k * b[1]; - return a; - } - var d3_transformIdentity = { - a: 1, - b: 0, - c: 0, - d: 1, - e: 0, - f: 0 - }; - d3.interpolateTransform = d3_interpolateTransform; - function d3_interpolateTransformPop(s) { - return s.length ? s.pop() + "," : ""; - } - function d3_interpolateTranslate(ta, tb, s, q) { - if (ta[0] !== tb[0] || ta[1] !== tb[1]) { - var i = s.push("translate(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ta[0], tb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ta[1], tb[1]) - }); - } else if (tb[0] || tb[1]) { - s.push("translate(" + tb + ")"); - } - } - function d3_interpolateRotate(ra, rb, s, q) { - if (ra !== rb) { - if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, - x: d3_interpolateNumber(ra, rb) - }); - } else if (rb) { - s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); - } - } - function d3_interpolateSkew(wa, wb, s, q) { - if (wa !== wb) { - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, - x: d3_interpolateNumber(wa, wb) - }); - } else if (wb) { - s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); - } - } - function d3_interpolateScale(ka, kb, s, q) { - if (ka[0] !== kb[0] || ka[1] !== kb[1]) { - var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ka[0], kb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ka[1], kb[1]) - }); - } else if (kb[0] !== 1 || kb[1] !== 1) { - s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); - } - } - function d3_interpolateTransform(a, b) { - var s = [], q = []; - a = d3.transform(a), b = d3.transform(b); - d3_interpolateTranslate(a.translate, b.translate, s, q); - d3_interpolateRotate(a.rotate, b.rotate, s, q); - d3_interpolateSkew(a.skew, b.skew, s, q); - d3_interpolateScale(a.scale, b.scale, s, q); - a = b = null; - return function(t) { - var i = -1, n = q.length, o; - while (++i < n) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }; - } - function d3_uninterpolateNumber(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return (x - a) / b; - }; - } - function d3_uninterpolateClamp(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return Math.max(0, Math.min(1, (x - a) / b)); - }; - } - d3.layout = {}; - d3.layout.bundle = function() { - return function(links) { - var paths = [], i = -1, n = links.length; - while (++i < n) paths.push(d3_layout_bundlePath(links[i])); - return paths; - }; - }; - function d3_layout_bundlePath(link) { - var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; - while (start !== lca) { - start = start.parent; - points.push(start); - } - var k = points.length; - while (end !== lca) { - points.splice(k, 0, end); - end = end.parent; - } - return points; - } - function d3_layout_bundleAncestors(node) { - var ancestors = [], parent = node.parent; - while (parent != null) { - ancestors.push(node); - node = parent; - parent = parent.parent; - } - ancestors.push(node); - return ancestors; - } - function d3_layout_bundleLeastCommonAncestor(a, b) { - if (a === b) return a; - var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; - while (aNode === bNode) { - sharedNode = aNode; - aNode = aNodes.pop(); - bNode = bNodes.pop(); - } - return sharedNode; - } - d3.layout.chord = function() { - var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; - function relayout() { - var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; - chords = []; - groups = []; - k = 0, i = -1; - while (++i < n) { - x = 0, j = -1; - while (++j < n) { - x += matrix[i][j]; - } - groupSums.push(x); - subgroupIndex.push(d3.range(n)); - k += x; - } - if (sortGroups) { - groupIndex.sort(function(a, b) { - return sortGroups(groupSums[a], groupSums[b]); - }); - } - if (sortSubgroups) { - subgroupIndex.forEach(function(d, i) { - d.sort(function(a, b) { - return sortSubgroups(matrix[i][a], matrix[i][b]); - }); - }); - } - k = (τ - padding * n) / k; - x = 0, i = -1; - while (++i < n) { - x0 = x, j = -1; - while (++j < n) { - var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; - subgroups[di + "-" + dj] = { - index: di, - subindex: dj, - startAngle: a0, - endAngle: a1, - value: v - }; - } - groups[di] = { - index: di, - startAngle: x0, - endAngle: x, - value: groupSums[di] - }; - x += padding; - } - i = -1; - while (++i < n) { - j = i - 1; - while (++j < n) { - var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; - if (source.value || target.value) { - chords.push(source.value < target.value ? { - source: target, - target: source - } : { - source: source, - target: target - }); - } - } - } - if (sortChords) resort(); - } - function resort() { - chords.sort(function(a, b) { - return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); - }); - } - chord.matrix = function(x) { - if (!arguments.length) return matrix; - n = (matrix = x) && matrix.length; - chords = groups = null; - return chord; - }; - chord.padding = function(x) { - if (!arguments.length) return padding; - padding = x; - chords = groups = null; - return chord; - }; - chord.sortGroups = function(x) { - if (!arguments.length) return sortGroups; - sortGroups = x; - chords = groups = null; - return chord; - }; - chord.sortSubgroups = function(x) { - if (!arguments.length) return sortSubgroups; - sortSubgroups = x; - chords = null; - return chord; - }; - chord.sortChords = function(x) { - if (!arguments.length) return sortChords; - sortChords = x; - if (chords) resort(); - return chord; - }; - chord.chords = function() { - if (!chords) relayout(); - return chords; - }; - chord.groups = function() { - if (!groups) relayout(); - return groups; - }; - return chord; - }; - d3.layout.force = function() { - var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; - function repulse(node) { - return function(quad, x1, _, x2) { - if (quad.point !== node) { - var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; - if (dw * dw / theta2 < dn) { - if (dn < chargeDistance2) { - var k = quad.charge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - return true; - } - if (quad.point && dn && dn < chargeDistance2) { - var k = quad.pointCharge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - } - return !quad.charge; - }; - } - force.tick = function() { - if ((alpha *= .99) < .005) { - timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); - return true; - } - var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; - for (i = 0; i < m; ++i) { - o = links[i]; - s = o.source; - t = o.target; - x = t.x - s.x; - y = t.y - s.y; - if (l = x * x + y * y) { - l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; - x *= l; - y *= l; - t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); - t.y -= y * k; - s.x += x * (k = 1 - k); - s.y += y * k; - } - } - if (k = alpha * gravity) { - x = size[0] / 2; - y = size[1] / 2; - i = -1; - if (k) while (++i < n) { - o = nodes[i]; - o.x += (x - o.x) * k; - o.y += (y - o.y) * k; - } - } - if (charge) { - d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); - i = -1; - while (++i < n) { - if (!(o = nodes[i]).fixed) { - q.visit(repulse(o)); - } - } - } - i = -1; - while (++i < n) { - o = nodes[i]; - if (o.fixed) { - o.x = o.px; - o.y = o.py; - } else { - o.x -= (o.px - (o.px = o.x)) * friction; - o.y -= (o.py - (o.py = o.y)) * friction; - } - } - event.tick({ - type: "tick", - alpha: alpha - }); - }; - force.nodes = function(x) { - if (!arguments.length) return nodes; - nodes = x; - return force; - }; - force.links = function(x) { - if (!arguments.length) return links; - links = x; - return force; - }; - force.size = function(x) { - if (!arguments.length) return size; - size = x; - return force; - }; - force.linkDistance = function(x) { - if (!arguments.length) return linkDistance; - linkDistance = typeof x === "function" ? x : +x; - return force; - }; - force.distance = force.linkDistance; - force.linkStrength = function(x) { - if (!arguments.length) return linkStrength; - linkStrength = typeof x === "function" ? x : +x; - return force; - }; - force.friction = function(x) { - if (!arguments.length) return friction; - friction = +x; - return force; - }; - force.charge = function(x) { - if (!arguments.length) return charge; - charge = typeof x === "function" ? x : +x; - return force; - }; - force.chargeDistance = function(x) { - if (!arguments.length) return Math.sqrt(chargeDistance2); - chargeDistance2 = x * x; - return force; - }; - force.gravity = function(x) { - if (!arguments.length) return gravity; - gravity = +x; - return force; - }; - force.theta = function(x) { - if (!arguments.length) return Math.sqrt(theta2); - theta2 = x * x; - return force; - }; - force.alpha = function(x) { - if (!arguments.length) return alpha; - x = +x; - if (alpha) { - if (x > 0) { - alpha = x; - } else { - timer.c = null, timer.t = NaN, timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); - } - } else if (x > 0) { - event.start({ - type: "start", - alpha: alpha = x - }); - timer = d3_timer(force.tick); - } - return force; - }; - force.start = function() { - var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; - for (i = 0; i < n; ++i) { - (o = nodes[i]).index = i; - o.weight = 0; - } - for (i = 0; i < m; ++i) { - o = links[i]; - if (typeof o.source == "number") o.source = nodes[o.source]; - if (typeof o.target == "number") o.target = nodes[o.target]; - ++o.source.weight; - ++o.target.weight; - } - for (i = 0; i < n; ++i) { - o = nodes[i]; - if (isNaN(o.x)) o.x = position("x", w); - if (isNaN(o.y)) o.y = position("y", h); - if (isNaN(o.px)) o.px = o.x; - if (isNaN(o.py)) o.py = o.y; - } - distances = []; - if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; - strengths = []; - if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; - charges = []; - if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; - function position(dimension, size) { - if (!neighbors) { - neighbors = new Array(n); - for (j = 0; j < n; ++j) { - neighbors[j] = []; - } - for (j = 0; j < m; ++j) { - var o = links[j]; - neighbors[o.source.index].push(o.target); - neighbors[o.target.index].push(o.source); - } - } - var candidates = neighbors[i], j = -1, l = candidates.length, x; - while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; - return Math.random() * size; - } - return force.resume(); - }; - force.resume = function() { - return force.alpha(.1); - }; - force.stop = function() { - return force.alpha(0); - }; - force.drag = function() { - if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); - if (!arguments.length) return drag; - this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); - }; - function dragmove(d) { - d.px = d3.event.x, d.py = d3.event.y; - force.resume(); - } - return d3.rebind(force, event, "on"); - }; - function d3_layout_forceDragstart(d) { - d.fixed |= 2; - } - function d3_layout_forceDragend(d) { - d.fixed &= ~6; - } - function d3_layout_forceMouseover(d) { - d.fixed |= 4; - d.px = d.x, d.py = d.y; - } - function d3_layout_forceMouseout(d) { - d.fixed &= ~4; - } - function d3_layout_forceAccumulate(quad, alpha, charges) { - var cx = 0, cy = 0; - quad.charge = 0; - if (!quad.leaf) { - var nodes = quad.nodes, n = nodes.length, i = -1, c; - while (++i < n) { - c = nodes[i]; - if (c == null) continue; - d3_layout_forceAccumulate(c, alpha, charges); - quad.charge += c.charge; - cx += c.charge * c.cx; - cy += c.charge * c.cy; - } - } - if (quad.point) { - if (!quad.leaf) { - quad.point.x += Math.random() - .5; - quad.point.y += Math.random() - .5; - } - var k = alpha * charges[quad.point.index]; - quad.charge += quad.pointCharge = k; - cx += k * quad.point.x; - cy += k * quad.point.y; - } - quad.cx = cx / quad.charge; - quad.cy = cy / quad.charge; - } - var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; - d3.layout.hierarchy = function() { - var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; - function hierarchy(root) { - var stack = [ root ], nodes = [], node; - root.depth = 0; - while ((node = stack.pop()) != null) { - nodes.push(node); - if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { - var n, childs, child; - while (--n >= 0) { - stack.push(child = childs[n]); - child.parent = node; - child.depth = node.depth + 1; - } - if (value) node.value = 0; - node.children = childs; - } else { - if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; - delete node.children; - } - } - d3_layout_hierarchyVisitAfter(root, function(node) { - var childs, parent; - if (sort && (childs = node.children)) childs.sort(sort); - if (value && (parent = node.parent)) parent.value += node.value; - }); - return nodes; - } - hierarchy.sort = function(x) { - if (!arguments.length) return sort; - sort = x; - return hierarchy; - }; - hierarchy.children = function(x) { - if (!arguments.length) return children; - children = x; - return hierarchy; - }; - hierarchy.value = function(x) { - if (!arguments.length) return value; - value = x; - return hierarchy; - }; - hierarchy.revalue = function(root) { - if (value) { - d3_layout_hierarchyVisitBefore(root, function(node) { - if (node.children) node.value = 0; - }); - d3_layout_hierarchyVisitAfter(root, function(node) { - var parent; - if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; - if (parent = node.parent) parent.value += node.value; - }); - } - return root; - }; - return hierarchy; - }; - function d3_layout_hierarchyRebind(object, hierarchy) { - d3.rebind(object, hierarchy, "sort", "children", "value"); - object.nodes = object; - object.links = d3_layout_hierarchyLinks; - return object; - } - function d3_layout_hierarchyVisitBefore(node, callback) { - var nodes = [ node ]; - while ((node = nodes.pop()) != null) { - callback(node); - if ((children = node.children) && (n = children.length)) { - var n, children; - while (--n >= 0) nodes.push(children[n]); - } - } - } - function d3_layout_hierarchyVisitAfter(node, callback) { - var nodes = [ node ], nodes2 = []; - while ((node = nodes.pop()) != null) { - nodes2.push(node); - if ((children = node.children) && (n = children.length)) { - var i = -1, n, children; - while (++i < n) nodes.push(children[i]); - } - } - while ((node = nodes2.pop()) != null) { - callback(node); - } - } - function d3_layout_hierarchyChildren(d) { - return d.children; - } - function d3_layout_hierarchyValue(d) { - return d.value; - } - function d3_layout_hierarchySort(a, b) { - return b.value - a.value; - } - function d3_layout_hierarchyLinks(nodes) { - return d3.merge(nodes.map(function(parent) { - return (parent.children || []).map(function(child) { - return { - source: parent, - target: child - }; - }); - })); - } - d3.layout.partition = function() { - var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; - function position(node, x, dx, dy) { - var children = node.children; - node.x = x; - node.y = node.depth * dy; - node.dx = dx; - node.dy = dy; - if (children && (n = children.length)) { - var i = -1, n, c, d; - dx = node.value ? dx / node.value : 0; - while (++i < n) { - position(c = children[i], x, d = c.value * dx, dy); - x += d; - } - } - } - function depth(node) { - var children = node.children, d = 0; - if (children && (n = children.length)) { - var i = -1, n; - while (++i < n) d = Math.max(d, depth(children[i])); - } - return 1 + d; - } - function partition(d, i) { - var nodes = hierarchy.call(this, d, i); - position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); - return nodes; - } - partition.size = function(x) { - if (!arguments.length) return size; - size = x; - return partition; - }; - return d3_layout_hierarchyRebind(partition, hierarchy); - }; - d3.layout.pie = function() { - var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; - function pie(data) { - var n = data.length, values = data.map(function(d, i) { - return +value.call(pie, d, i); - }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; - if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { - return values[j] - values[i]; - } : function(i, j) { - return sort(data[i], data[j]); - }); - index.forEach(function(i) { - arcs[i] = { - data: data[i], - value: v = values[i], - startAngle: a, - endAngle: a += v * k + pa, - padAngle: p - }; - }); - return arcs; - } - pie.value = function(_) { - if (!arguments.length) return value; - value = _; - return pie; - }; - pie.sort = function(_) { - if (!arguments.length) return sort; - sort = _; - return pie; - }; - pie.startAngle = function(_) { - if (!arguments.length) return startAngle; - startAngle = _; - return pie; - }; - pie.endAngle = function(_) { - if (!arguments.length) return endAngle; - endAngle = _; - return pie; - }; - pie.padAngle = function(_) { - if (!arguments.length) return padAngle; - padAngle = _; - return pie; - }; - return pie; - }; - var d3_layout_pieSortByValue = {}; - d3.layout.stack = function() { - var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; - function stack(data, index) { - if (!(n = data.length)) return data; - var series = data.map(function(d, i) { - return values.call(stack, d, i); - }); - var points = series.map(function(d) { - return d.map(function(v, i) { - return [ x.call(stack, v, i), y.call(stack, v, i) ]; - }); - }); - var orders = order.call(stack, points, index); - series = d3.permute(series, orders); - points = d3.permute(points, orders); - var offsets = offset.call(stack, points, index); - var m = series[0].length, n, i, j, o; - for (j = 0; j < m; ++j) { - out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); - for (i = 1; i < n; ++i) { - out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); - } - } - return data; - } - stack.values = function(x) { - if (!arguments.length) return values; - values = x; - return stack; - }; - stack.order = function(x) { - if (!arguments.length) return order; - order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; - return stack; - }; - stack.offset = function(x) { - if (!arguments.length) return offset; - offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; - return stack; - }; - stack.x = function(z) { - if (!arguments.length) return x; - x = z; - return stack; - }; - stack.y = function(z) { - if (!arguments.length) return y; - y = z; - return stack; - }; - stack.out = function(z) { - if (!arguments.length) return out; - out = z; - return stack; - }; - return stack; - }; - function d3_layout_stackX(d) { - return d.x; - } - function d3_layout_stackY(d) { - return d.y; - } - function d3_layout_stackOut(d, y0, y) { - d.y0 = y0; - d.y = y; - } - var d3_layout_stackOrders = d3.map({ - "inside-out": function(data) { - var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { - return max[a] - max[b]; - }), top = 0, bottom = 0, tops = [], bottoms = []; - for (i = 0; i < n; ++i) { - j = index[i]; - if (top < bottom) { - top += sums[j]; - tops.push(j); - } else { - bottom += sums[j]; - bottoms.push(j); - } - } - return bottoms.reverse().concat(tops); - }, - reverse: function(data) { - return d3.range(data.length).reverse(); - }, - "default": d3_layout_stackOrderDefault - }); - var d3_layout_stackOffsets = d3.map({ - silhouette: function(data) { - var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o > max) max = o; - sums.push(o); - } - for (j = 0; j < m; ++j) { - y0[j] = (max - sums[j]) / 2; - } - return y0; - }, - wiggle: function(data) { - var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; - y0[0] = o = o0 = 0; - for (j = 1; j < m; ++j) { - for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; - for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { - for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { - s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; - } - s2 += s3 * data[i][j][1]; - } - y0[j] = o -= s1 ? s2 / s1 * dx : 0; - if (o < o0) o0 = o; - } - for (j = 0; j < m; ++j) y0[j] -= o0; - return y0; - }, - expand: function(data) { - var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; - } - for (j = 0; j < m; ++j) y0[j] = 0; - return y0; - }, - zero: d3_layout_stackOffsetZero - }); - function d3_layout_stackOrderDefault(data) { - return d3.range(data.length); - } - function d3_layout_stackOffsetZero(data) { - var j = -1, m = data[0].length, y0 = []; - while (++j < m) y0[j] = 0; - return y0; - } - function d3_layout_stackMaxIndex(array) { - var i = 1, j = 0, v = array[0][1], k, n = array.length; - for (;i < n; ++i) { - if ((k = array[i][1]) > v) { - j = i; - v = k; - } - } - return j; - } - function d3_layout_stackReduceSum(d) { - return d.reduce(d3_layout_stackSum, 0); - } - function d3_layout_stackSum(p, d) { - return p + d[1]; - } - d3.layout.histogram = function() { - var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; - function histogram(data, i) { - var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; - while (++i < m) { - bin = bins[i] = []; - bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); - bin.y = 0; - } - if (m > 0) { - i = -1; - while (++i < n) { - x = values[i]; - if (x >= range[0] && x <= range[1]) { - bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; - bin.y += k; - bin.push(data[i]); - } - } - } - return bins; - } - histogram.value = function(x) { - if (!arguments.length) return valuer; - valuer = x; - return histogram; - }; - histogram.range = function(x) { - if (!arguments.length) return ranger; - ranger = d3_functor(x); - return histogram; - }; - histogram.bins = function(x) { - if (!arguments.length) return binner; - binner = typeof x === "number" ? function(range) { - return d3_layout_histogramBinFixed(range, x); - } : d3_functor(x); - return histogram; - }; - histogram.frequency = function(x) { - if (!arguments.length) return frequency; - frequency = !!x; - return histogram; - }; - return histogram; - }; - function d3_layout_histogramBinSturges(range, values) { - return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); - } - function d3_layout_histogramBinFixed(range, n) { - var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; - while (++x <= n) f[x] = m * x + b; - return f; - } - function d3_layout_histogramRange(values) { - return [ d3.min(values), d3.max(values) ]; - } - d3.layout.pack = function() { - var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; - function pack(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { - return radius; - }; - root.x = root.y = 0; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r = +r(d.value); - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - if (padding) { - var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r += dr; - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - d3_layout_hierarchyVisitAfter(root, function(d) { - d.r -= dr; - }); - } - d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); - return nodes; - } - pack.size = function(_) { - if (!arguments.length) return size; - size = _; - return pack; - }; - pack.radius = function(_) { - if (!arguments.length) return radius; - radius = _ == null || typeof _ === "function" ? _ : +_; - return pack; - }; - pack.padding = function(_) { - if (!arguments.length) return padding; - padding = +_; - return pack; - }; - return d3_layout_hierarchyRebind(pack, hierarchy); - }; - function d3_layout_packSort(a, b) { - return a.value - b.value; - } - function d3_layout_packInsert(a, b) { - var c = a._pack_next; - a._pack_next = b; - b._pack_prev = a; - b._pack_next = c; - c._pack_prev = b; - } - function d3_layout_packSplice(a, b) { - a._pack_next = b; - b._pack_prev = a; - } - function d3_layout_packIntersects(a, b) { - var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; - return .999 * dr * dr > dx * dx + dy * dy; - } - function d3_layout_packSiblings(node) { - if (!(nodes = node.children) || !(n = nodes.length)) return; - var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; - function bound(node) { - xMin = Math.min(node.x - node.r, xMin); - xMax = Math.max(node.x + node.r, xMax); - yMin = Math.min(node.y - node.r, yMin); - yMax = Math.max(node.y + node.r, yMax); - } - nodes.forEach(d3_layout_packLink); - a = nodes[0]; - a.x = -a.r; - a.y = 0; - bound(a); - if (n > 1) { - b = nodes[1]; - b.x = b.r; - b.y = 0; - bound(b); - if (n > 2) { - c = nodes[2]; - d3_layout_packPlace(a, b, c); - bound(c); - d3_layout_packInsert(a, c); - a._pack_prev = c; - d3_layout_packInsert(c, b); - b = a._pack_next; - for (i = 3; i < n; i++) { - d3_layout_packPlace(a, b, c = nodes[i]); - var isect = 0, s1 = 1, s2 = 1; - for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { - if (d3_layout_packIntersects(j, c)) { - isect = 1; - break; - } - } - if (isect == 1) { - for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { - if (d3_layout_packIntersects(k, c)) { - break; - } - } - } - if (isect) { - if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); - i--; - } else { - d3_layout_packInsert(a, c); - b = c; - bound(c); - } - } - } - } - var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; - for (i = 0; i < n; i++) { - c = nodes[i]; - c.x -= cx; - c.y -= cy; - cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); - } - node.r = cr; - nodes.forEach(d3_layout_packUnlink); - } - function d3_layout_packLink(node) { - node._pack_next = node._pack_prev = node; - } - function d3_layout_packUnlink(node) { - delete node._pack_next; - delete node._pack_prev; - } - function d3_layout_packTransform(node, x, y, k) { - var children = node.children; - node.x = x += k * node.x; - node.y = y += k * node.y; - node.r *= k; - if (children) { - var i = -1, n = children.length; - while (++i < n) d3_layout_packTransform(children[i], x, y, k); - } - } - function d3_layout_packPlace(a, b, c) { - var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; - if (db && (dx || dy)) { - var da = b.r + c.r, dc = dx * dx + dy * dy; - da *= da; - db *= db; - var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); - c.x = a.x + x * dx + y * dy; - c.y = a.y + x * dy - y * dx; - } else { - c.x = a.x + db; - c.y = a.y; - } - } - d3.layout.tree = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; - function tree(d, i) { - var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); - d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; - d3_layout_hierarchyVisitBefore(root1, secondWalk); - if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { - var left = root0, right = root0, bottom = root0; - d3_layout_hierarchyVisitBefore(root0, function(node) { - if (node.x < left.x) left = node; - if (node.x > right.x) right = node; - if (node.depth > bottom.depth) bottom = node; - }); - var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); - d3_layout_hierarchyVisitBefore(root0, function(node) { - node.x = (node.x + tx) * kx; - node.y = node.depth * ky; - }); - } - return nodes; - } - function wrapTree(root0) { - var root1 = { - A: null, - children: [ root0 ] - }, queue = [ root1 ], node1; - while ((node1 = queue.pop()) != null) { - for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { - queue.push((children[i] = child = { - _: children[i], - parent: node1, - children: (child = children[i].children) && child.slice() || [], - A: null, - a: null, - z: 0, - m: 0, - c: 0, - s: 0, - t: null, - i: i - }).a = child); - } - } - return root1.children[0]; - } - function firstWalk(v) { - var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; - if (children.length) { - d3_layout_treeShift(v); - var midpoint = (children[0].z + children[children.length - 1].z) / 2; - if (w) { - v.z = w.z + separation(v._, w._); - v.m = v.z - midpoint; - } else { - v.z = midpoint; - } - } else if (w) { - v.z = w.z + separation(v._, w._); - } - v.parent.A = apportion(v, w, v.parent.A || siblings[0]); - } - function secondWalk(v) { - v._.x = v.z + v.parent.m; - v.m += v.parent.m; - } - function apportion(v, w, ancestor) { - if (w) { - var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; - while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { - vom = d3_layout_treeLeft(vom); - vop = d3_layout_treeRight(vop); - vop.a = v; - shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); - if (shift > 0) { - d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); - sip += shift; - sop += shift; - } - sim += vim.m; - sip += vip.m; - som += vom.m; - sop += vop.m; - } - if (vim && !d3_layout_treeRight(vop)) { - vop.t = vim; - vop.m += sim - sop; - } - if (vip && !d3_layout_treeLeft(vom)) { - vom.t = vip; - vom.m += sip - som; - ancestor = v; - } - } - return ancestor; - } - function sizeNode(node) { - node.x *= size[0]; - node.y = node.depth * size[1]; - } - tree.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return tree; - }; - tree.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null ? sizeNode : null; - return tree; - }; - tree.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) == null ? null : sizeNode; - return tree; - }; - return d3_layout_hierarchyRebind(tree, hierarchy); - }; - function d3_layout_treeSeparation(a, b) { - return a.parent == b.parent ? 1 : 2; - } - function d3_layout_treeLeft(v) { - var children = v.children; - return children.length ? children[0] : v.t; - } - function d3_layout_treeRight(v) { - var children = v.children, n; - return (n = children.length) ? children[n - 1] : v.t; - } - function d3_layout_treeMove(wm, wp, shift) { - var change = shift / (wp.i - wm.i); - wp.c -= change; - wp.s += shift; - wm.c += change; - wp.z += shift; - wp.m += shift; - } - function d3_layout_treeShift(v) { - var shift = 0, change = 0, children = v.children, i = children.length, w; - while (--i >= 0) { - w = children[i]; - w.z += shift; - w.m += shift; - shift += w.s + (change += w.c); - } - } - function d3_layout_treeAncestor(vim, v, ancestor) { - return vim.a.parent === v.parent ? vim.a : ancestor; - } - d3.layout.cluster = function() { - var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; - function cluster(d, i) { - var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; - d3_layout_hierarchyVisitAfter(root, function(node) { - var children = node.children; - if (children && children.length) { - node.x = d3_layout_clusterX(children); - node.y = d3_layout_clusterY(children); - } else { - node.x = previousNode ? x += separation(node, previousNode) : 0; - node.y = 0; - previousNode = node; - } - }); - var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; - d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { - node.x = (node.x - root.x) * size[0]; - node.y = (root.y - node.y) * size[1]; - } : function(node) { - node.x = (node.x - x0) / (x1 - x0) * size[0]; - node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; - }); - return nodes; - } - cluster.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return cluster; - }; - cluster.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null; - return cluster; - }; - cluster.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) != null; - return cluster; - }; - return d3_layout_hierarchyRebind(cluster, hierarchy); - }; - function d3_layout_clusterY(children) { - return 1 + d3.max(children, function(child) { - return child.y; - }); - } - function d3_layout_clusterX(children) { - return children.reduce(function(x, child) { - return x + child.x; - }, 0) / children.length; - } - function d3_layout_clusterLeft(node) { - var children = node.children; - return children && children.length ? d3_layout_clusterLeft(children[0]) : node; - } - function d3_layout_clusterRight(node) { - var children = node.children, n; - return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; - } - d3.layout.treemap = function() { - var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); - function scale(children, k) { - var i = -1, n = children.length, child, area; - while (++i < n) { - area = (child = children[i]).value * (k < 0 ? 0 : k); - child.area = isNaN(area) || area <= 0 ? 0 : area; - } - } - function squarify(node) { - var children = node.children; - if (children && children.length) { - var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; - scale(remaining, rect.dx * rect.dy / node.value); - row.area = 0; - while ((n = remaining.length) > 0) { - row.push(child = remaining[n - 1]); - row.area += child.area; - if (mode !== "squarify" || (score = worst(row, u)) <= best) { - remaining.pop(); - best = score; - } else { - row.area -= row.pop().area; - position(row, u, rect, false); - u = Math.min(rect.dx, rect.dy); - row.length = row.area = 0; - best = Infinity; - } - } - if (row.length) { - position(row, u, rect, true); - row.length = row.area = 0; - } - children.forEach(squarify); - } - } - function stickify(node) { - var children = node.children; - if (children && children.length) { - var rect = pad(node), remaining = children.slice(), child, row = []; - scale(remaining, rect.dx * rect.dy / node.value); - row.area = 0; - while (child = remaining.pop()) { - row.push(child); - row.area += child.area; - if (child.z != null) { - position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); - row.length = row.area = 0; - } - } - children.forEach(stickify); - } - } - function worst(row, u) { - var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; - while (++i < n) { - if (!(r = row[i].area)) continue; - if (r < rmin) rmin = r; - if (r > rmax) rmax = r; - } - s *= s; - u *= u; - return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; - } - function position(row, u, rect, flush) { - var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; - if (u == rect.dx) { - if (flush || v > rect.dy) v = rect.dy; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dy = v; - x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); - } - o.z = true; - o.dx += rect.x + rect.dx - x; - rect.y += v; - rect.dy -= v; - } else { - if (flush || v > rect.dx) v = rect.dx; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dx = v; - y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); - } - o.z = false; - o.dy += rect.y + rect.dy - y; - rect.x += v; - rect.dx -= v; - } - } - function treemap(d) { - var nodes = stickies || hierarchy(d), root = nodes[0]; - root.x = root.y = 0; - if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; - if (stickies) hierarchy.revalue(root); - scale([ root ], root.dx * root.dy / root.value); - (stickies ? stickify : squarify)(root); - if (sticky) stickies = nodes; - return nodes; - } - treemap.size = function(x) { - if (!arguments.length) return size; - size = x; - return treemap; - }; - treemap.padding = function(x) { - if (!arguments.length) return padding; - function padFunction(node) { - var p = x.call(treemap, node, node.depth); - return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); - } - function padConstant(node) { - return d3_layout_treemapPad(node, x); - } - var type; - pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], - padConstant) : padConstant; - return treemap; - }; - treemap.round = function(x) { - if (!arguments.length) return round != Number; - round = x ? Math.round : Number; - return treemap; - }; - treemap.sticky = function(x) { - if (!arguments.length) return sticky; - sticky = x; - stickies = null; - return treemap; - }; - treemap.ratio = function(x) { - if (!arguments.length) return ratio; - ratio = x; - return treemap; - }; - treemap.mode = function(x) { - if (!arguments.length) return mode; - mode = x + ""; - return treemap; - }; - return d3_layout_hierarchyRebind(treemap, hierarchy); - }; - function d3_layout_treemapPadNull(node) { - return { - x: node.x, - y: node.y, - dx: node.dx, - dy: node.dy - }; - } - function d3_layout_treemapPad(node, padding) { - var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; - if (dx < 0) { - x += dx / 2; - dx = 0; - } - if (dy < 0) { - y += dy / 2; - dy = 0; - } - return { - x: x, - y: y, - dx: dx, - dy: dy - }; - } - d3.random = { - normal: function(µ, σ) { - var n = arguments.length; - if (n < 2) σ = 1; - if (n < 1) µ = 0; - return function() { - var x, y, r; - do { - x = Math.random() * 2 - 1; - y = Math.random() * 2 - 1; - r = x * x + y * y; - } while (!r || r > 1); - return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); - }; - }, - logNormal: function() { - var random = d3.random.normal.apply(d3, arguments); - return function() { - return Math.exp(random()); - }; - }, - bates: function(m) { - var random = d3.random.irwinHall(m); - return function() { - return random() / m; - }; - }, - irwinHall: function(m) { - return function() { - for (var s = 0, j = 0; j < m; j++) s += Math.random(); - return s; - }; - } - }; - d3.scale = {}; - function d3_scaleExtent(domain) { - var start = domain[0], stop = domain[domain.length - 1]; - return start < stop ? [ start, stop ] : [ stop, start ]; - } - function d3_scaleRange(scale) { - return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); - } - function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { - var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); - return function(x) { - return i(u(x)); - }; - } - function d3_scale_nice(domain, nice) { - var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; - if (x1 < x0) { - dx = i0, i0 = i1, i1 = dx; - dx = x0, x0 = x1, x1 = dx; - } - domain[i0] = nice.floor(x0); - domain[i1] = nice.ceil(x1); - return domain; - } - function d3_scale_niceStep(step) { - return step ? { - floor: function(x) { - return Math.floor(x / step) * step; - }, - ceil: function(x) { - return Math.ceil(x / step) * step; - } - } : d3_scale_niceIdentity; - } - var d3_scale_niceIdentity = { - floor: d3_identity, - ceil: d3_identity - }; - function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { - var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; - if (domain[k] < domain[0]) { - domain = domain.slice().reverse(); - range = range.slice().reverse(); - } - while (++j <= k) { - u.push(uninterpolate(domain[j - 1], domain[j])); - i.push(interpolate(range[j - 1], range[j])); - } - return function(x) { - var j = d3.bisect(domain, x, 1, k) - 1; - return i[j](u[j](x)); - }; - } - d3.scale.linear = function() { - return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); - }; - function d3_scale_linear(domain, range, interpolate, clamp) { - var output, input; - function rescale() { - var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; - output = linear(domain, range, uninterpolate, interpolate); - input = linear(range, domain, uninterpolate, d3_interpolate); - return scale; - } - function scale(x) { - return output(x); - } - scale.invert = function(y) { - return input(y); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = x.map(Number); - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.rangeRound = function(x) { - return scale.range(x).interpolate(d3_interpolateRound); - }; - scale.clamp = function(x) { - if (!arguments.length) return clamp; - clamp = x; - return rescale(); - }; - scale.interpolate = function(x) { - if (!arguments.length) return interpolate; - interpolate = x; - return rescale(); - }; - scale.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - scale.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - scale.nice = function(m) { - d3_scale_linearNice(domain, m); - return rescale(); - }; - scale.copy = function() { - return d3_scale_linear(domain, range, interpolate, clamp); - }; - return rescale(); - } - function d3_scale_linearRebind(scale, linear) { - return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); - } - function d3_scale_linearNice(domain, m) { - d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); - return domain; - } - function d3_scale_linearTickRange(domain, m) { - if (m == null) m = 10; - var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; - if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; - extent[0] = Math.ceil(extent[0] / step) * step; - extent[1] = Math.floor(extent[1] / step) * step + step * .5; - extent[2] = step; - return extent; - } - function d3_scale_linearTicks(domain, m) { - return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); - } - function d3_scale_linearTickFormat(domain, m, format) { - var range = d3_scale_linearTickRange(domain, m); - if (format) { - var match = d3_format_re.exec(format); - match.shift(); - if (match[8] === "s") { - var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); - if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); - match[8] = "f"; - format = d3.format(match.join("")); - return function(d) { - return format(prefix.scale(d)) + prefix.symbol; - }; - } - if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); - format = match.join(""); - } else { - format = ",." + d3_scale_linearPrecision(range[2]) + "f"; - } - return d3.format(format); - } - var d3_scale_linearFormatSignificant = { - s: 1, - g: 1, - p: 1, - r: 1, - e: 1 - }; - function d3_scale_linearPrecision(value) { - return -Math.floor(Math.log(value) / Math.LN10 + .01); - } - function d3_scale_linearFormatPrecision(type, range) { - var p = d3_scale_linearPrecision(range[2]); - return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; - } - d3.scale.log = function() { - return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); - }; - function d3_scale_log(linear, base, positive, domain) { - function log(x) { - return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); - } - function pow(x) { - return positive ? Math.pow(base, x) : -Math.pow(base, -x); - } - function scale(x) { - return linear(log(x)); - } - scale.invert = function(x) { - return pow(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - positive = x[0] >= 0; - linear.domain((domain = x.map(Number)).map(log)); - return scale; - }; - scale.base = function(_) { - if (!arguments.length) return base; - base = +_; - linear.domain(domain.map(log)); - return scale; - }; - scale.nice = function() { - var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); - linear.domain(niced); - domain = niced.map(pow); - return scale; - }; - scale.ticks = function() { - var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; - if (isFinite(j - i)) { - if (positive) { - for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); - ticks.push(pow(i)); - } else { - ticks.push(pow(i)); - for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); - } - for (i = 0; ticks[i] < u; i++) {} - for (j = ticks.length; ticks[j - 1] > v; j--) {} - ticks = ticks.slice(i, j); - } - return ticks; - }; - scale.tickFormat = function(n, format) { - if (!arguments.length) return d3_scale_logFormat; - if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); - var k = Math.max(1, base * n / scale.ticks().length); - return function(d) { - var i = d / pow(Math.round(log(d))); - if (i * base < base - .5) i *= base; - return i <= k ? format(d) : ""; - }; - }; - scale.copy = function() { - return d3_scale_log(linear.copy(), base, positive, domain); - }; - return d3_scale_linearRebind(scale, linear); - } - var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { - floor: function(x) { - return -Math.ceil(-x); - }, - ceil: function(x) { - return -Math.floor(-x); - } - }; - d3.scale.pow = function() { - return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); - }; - function d3_scale_pow(linear, exponent, domain) { - var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); - function scale(x) { - return linear(powp(x)); - } - scale.invert = function(x) { - return powb(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return domain; - linear.domain((domain = x.map(Number)).map(powp)); - return scale; - }; - scale.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - scale.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - scale.nice = function(m) { - return scale.domain(d3_scale_linearNice(domain, m)); - }; - scale.exponent = function(x) { - if (!arguments.length) return exponent; - powp = d3_scale_powPow(exponent = x); - powb = d3_scale_powPow(1 / exponent); - linear.domain(domain.map(powp)); - return scale; - }; - scale.copy = function() { - return d3_scale_pow(linear.copy(), exponent, domain); - }; - return d3_scale_linearRebind(scale, linear); - } - function d3_scale_powPow(e) { - return function(x) { - return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); - }; - } - d3.scale.sqrt = function() { - return d3.scale.pow().exponent(.5); - }; - d3.scale.ordinal = function() { - return d3_scale_ordinal([], { - t: "range", - a: [ [] ] - }); - }; - function d3_scale_ordinal(domain, ranger) { - var index, range, rangeBand; - function scale(x) { - return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; - } - function steps(start, step) { - return d3.range(domain.length).map(function(i) { - return start + step * i; - }); - } - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = []; - index = new d3_Map(); - var i = -1, n = x.length, xi; - while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); - return scale[ranger.t].apply(scale, ranger.a); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - rangeBand = 0; - ranger = { - t: "range", - a: arguments - }; - return scale; - }; - scale.rangePoints = function(x, padding) { - if (arguments.length < 2) padding = 0; - var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, - 0) : (stop - start) / (domain.length - 1 + padding); - range = steps(start + step * padding / 2, step); - rangeBand = 0; - ranger = { - t: "rangePoints", - a: arguments + //Return result + return result +} +},{"robust-orientation":259}],108:[function(require,module,exports){ +module.exports = { + AFG: "afghan", + ALA: "\\b\\wland", + ALB: "albania", + DZA: "algeria", + ASM: "^(?=.*americ).*samoa", + AND: "andorra", + AGO: "angola", + AIA: "anguill?a", + ATA: "antarctica", + ATG: "antigua", + ARG: "argentin", + ARM: "armenia", + ABW: "^(?!.*bonaire).*\\baruba", + AUS: "australia", + AUT: "^(?!.*hungary).*austria|\\baustri.*\\bemp", + AZE: "azerbaijan", + BHS: "bahamas", + BHR: "bahrain", + BGD: "bangladesh|^(?=.*east).*paki?stan", + BRB: "barbados", + BLR: "belarus|byelo", + BEL: "^(?!.*luxem).*belgium", + BLZ: "belize|^(?=.*british).*honduras", + BEN: "benin|dahome", + BMU: "bermuda", + BTN: "bhutan", + BOL: "bolivia", + BES: "^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands", + BIH: "herzegovina|bosnia", + BWA: "botswana|bechuana", + BVT: "bouvet", + BRA: "brazil", + IOT: "british.?indian.?ocean", + BRN: "brunei", + BGR: "bulgaria", + BFA: "burkina|\\bfaso|upper.?volta", + BDI: "burundi", + KHM: "cambodia|kampuchea|khmer", + CMR: "cameroon", + CAN: "canada", + CPV: "verde", + CYM: "cayman", + CAF: "\\bcentral.african.republic", + TCD: "\\bchad", + CHL: "\\bchile", + CHN: "^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china", + CXR: "christmas", + CCK: "\\bcocos|keeling", + COL: "colombia", + COM: "comoro", + COD: "\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc", + COG: "^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo", + COK: "\\bcook", + CRI: "costa.?rica", + CIV: "ivoire|ivory", + HRV: "croatia", + CUB: "\\bcuba", + CUW: "^(?!.*bonaire).*\\bcura(c|ç)ao", + CYP: "cyprus", + CZE: "^(?=.*rep).*czech|czechia|bohemia", + CSK: "czechoslovakia", + DNK: "denmark", + DJI: "djibouti", + DMA: "dominica(?!n)", + DOM: "dominican.rep", + ECU: "ecuador", + EGY: "egypt", + SLV: "el.?salvador", + GNQ: "guine.*eq|eq.*guine|^(?=.*span).*guinea", + ERI: "eritrea", + EST: "estonia", + ETH: "ethiopia|abyssinia", + FLK: "falkland|malvinas", + FRO: "faroe|faeroe", + FJI: "fiji", + FIN: "finland", + FRA: "^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul", + GUF: "^(?=.*french).*guiana", + PYF: "french.?polynesia|tahiti", + ATF: "french.?southern", + GAB: "gabon", + GMB: "gambia", + GEO: "^(?!.*south).*georgia", + DDR: "german.?democratic.?republic|democratic.?republic.*germany|east.germany", + DEU: "^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german", + GHA: "ghana|gold.?coast", + GIB: "gibraltar", + GRC: "greece|hellenic|hellas", + GRL: "greenland", + GRD: "grenada", + GLP: "guadeloupe", + GUM: "\\bguam", + GTM: "guatemala", + GGY: "guernsey", + GIN: "^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea", + GNB: "bissau|^(?=.*portu).*guinea", + GUY: "guyana|british.?guiana", + HTI: "haiti", + HMD: "heard.*mcdonald", + VAT: "holy.?see|vatican|papal.?st", + HND: "^(?!.*brit).*honduras", + HKG: "hong.?kong", + HUN: "^(?!.*austr).*hungary", + ISL: "iceland", + IND: "india(?!.*ocea)", + IDN: "indonesia", + IRN: "\\biran|persia", + IRQ: "\\biraq|mesopotamia", + IRL: "ireland", + IMN: "^(?=.*isle).*\\bman", + ISR: "israel", + ITA: "italy", + JAM: "jamaica", + JPN: "japan", + JEY: "jersey", + JOR: "jordan", + KAZ: "kazak", + KEN: "kenya|british.?east.?africa|east.?africa.?prot", + KIR: "kiribati", + PRK: "^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk", + KOR: "^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea", + KWT: "kuwait", + KGZ: "kyrgyz|kirghiz", + LAO: "\\blaos?\\b", + LVA: "latvia", + LBN: "lebanon", + LSO: "lesotho|basuto", + LBR: "liberia", + LBY: "libya", + LIE: "liechtenstein", + LTU: "lithuania", + LUX: "^(?!.*belg).*luxem", + MAC: "maca(o|u)", + MKD: "macedonia|fyrom", + MDG: "madagascar|malagasy", + MWI: "malawi|nyasa", + MYS: "malaysia", + MDV: "maldive", + MLI: "\\bmali\\b", + MLT: "\\bmalta", + MHL: "marshall", + MTQ: "martinique", + MRT: "mauritania", + MUS: "mauritius", + MYT: "\\bmayotte", + MEX: "\\bmexic", + FSM: "micronesia", + MDA: "moldov|b(a|e)ssarabia", + MCO: "monaco", + MNG: "mongolia", + MNE: "^(?!.*serbia).*montenegro", + MSR: "montserrat", + MAR: "morocco|\\bmaroc", + MOZ: "mozambique", + MMR: "myanmar|burma", + NAM: "namibia", + NRU: "nauru", + NPL: "nepal", + NLD: "^(?!.*\\bant)(?!.*\\bcarib).*netherlands", + ANT: "^(?=.*\\bant).*(nether|dutch)", + NCL: "new.?caledonia", + NZL: "new.?zealand", + NIC: "nicaragua", + NER: "\\bniger(?!ia)", + NGA: "nigeria", + NIU: "niue", + NFK: "norfolk", + MNP: "mariana", + NOR: "norway", + OMN: "\\boman|trucial", + PAK: "^(?!.*east).*paki?stan", + PLW: "palau", + PSE: "palestin|\\bgaza|west.?bank", + PAN: "panama", + PNG: "papua|new.?guinea", + PRY: "paraguay", + PER: "peru", + PHL: "philippines", + PCN: "pitcairn", + POL: "poland", + PRT: "portugal", + PRI: "puerto.?rico", + QAT: "qatar", + REU: "r(e|é)union", + ROU: "r(o|u|ou)mania", + RUS: "\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics", + RWA: "rwanda", + BLM: "barth(e|é)lemy", + SHN: "helena", + KNA: "kitts|\\bnevis", + LCA: "\\blucia", + MAF: "^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)", + SPM: "miquelon", + VCT: "vincent", + WSM: "^(?!.*amer).*samoa", + SMR: "san.?marino", + STP: "\\bs(a|ã)o.?tom(e|é)", + SAU: "\\bsa\\w*.?arabia", + SEN: "senegal", + SRB: "^(?!.*monte).*serbia", + SYC: "seychell", + SLE: "sierra", + SGP: "singapore", + SXM: "^(?!.*martin)(?!.*saba).*maarten", + SVK: "^(?!.*cze).*slovak", + SVN: "slovenia", + SLB: "solomon", + SOM: "somali", + ZAF: "\\bs\\w*.?africa", + SGS: "south.?georgia|sandwich", + SSD: "\\bs\\w*.?sudan", + ESP: "spain", + LKA: "sri.?lanka|ceylon", + SDN: "^(?!.*\\bs(?!u)).*sudan", + SUR: "surinam|dutch.?guiana", + SJM: "svalbard", + SWZ: "swaziland", + SWE: "sweden", + CHE: "switz|swiss", + SYR: "syria", + TWN: "taiwan|taipei|formosa", + TJK: "tajik", + TZA: "tanzania", + THA: "thailand|\\bsiam", + TLS: "^(?=.*leste).*timor|^(?=.*east).*timor", + TGO: "togo", + TKL: "tokelau", + TON: "tonga", + TTO: "trinidad|tobago", + TUN: "tunisia", + TUR: "turkey", + TKM: "turkmen", + TCA: "turks", + TUV: "tuvalu", + UGA: "uganda", + UKR: "ukrain", + ARE: "emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em", + GBR: "united.?kingdom|britain|^u\\.?k\\.?$", + USA: "united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)", + UMI: "minor.?outlying.?is", + URY: "uruguay", + UZB: "uzbek", + VUT: "vanuatu|new.?hebrides", + VEN: "venezuela", + VNM: "^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam", + VGB: "^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin", + VIR: "^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin", + WLF: "futuna|wallis", + ESH: "western.sahara", + YEM: "^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen", + YMD: "^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen", + YUG: "yugoslavia", + ZMB: "zambia|northern.?rhodesia", + EAZ: "zanzibar", + ZWE: "zimbabwe|^(?!.*northern).*rhodesia" +}; + +},{}],109:[function(require,module,exports){ +"use strict" + +var createThunk = require("./lib/thunk.js") + +function Procedure() { + this.argTypes = [] + this.shimArgs = [] + this.arrayArgs = [] + this.arrayBlockIndices = [] + this.scalarArgs = [] + this.offsetArgs = [] + this.offsetArgIndex = [] + this.indexArgs = [] + this.shapeArgs = [] + this.funcName = "" + this.pre = null + this.body = null + this.post = null + this.debug = false +} + +function compileCwise(user_args) { + //Create procedure + var proc = new Procedure() + + //Parse blocks + proc.pre = user_args.pre + proc.body = user_args.body + proc.post = user_args.post + + //Parse arguments + var proc_args = user_args.args.slice(0) + proc.argTypes = proc_args + for(var i=0; i0) { + throw new Error("cwise: pre() block may not reference array args") + } + if(i < proc.post.args.length && proc.post.args[i].count>0) { + throw new Error("cwise: post() block may not reference array args") + } + } else if(arg_type === "scalar") { + proc.scalarArgs.push(i) + proc.shimArgs.push("scalar" + i) + } else if(arg_type === "index") { + proc.indexArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { + throw new Error("cwise: pre() block may not reference array index") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array index") + } + if(i < proc.post.args.length && proc.post.args[i].count > 0) { + throw new Error("cwise: post() block may not reference array index") + } + } else if(arg_type === "shape") { + proc.shapeArgs.push(i) + if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { + throw new Error("cwise: pre() block may not write to array shape") + } + if(i < proc.body.args.length && proc.body.args[i].lvalue) { + throw new Error("cwise: body() block may not write to array shape") + } + if(i < proc.post.args.length && proc.post.args[i].lvalue) { + throw new Error("cwise: post() block may not write to array shape") + } + } else if(typeof arg_type === "object" && arg_type.offset) { + proc.argTypes[i] = "offset" + proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) + proc.offsetArgIndex.push(i) + } else { + throw new Error("cwise: Unknown argument type " + proc_args[i]) + } + } + + //Make sure at least one array argument was specified + if(proc.arrayArgs.length <= 0) { + throw new Error("cwise: No array arguments specified") + } + + //Make sure arguments are correct + if(proc.pre.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in pre() block") + } + if(proc.body.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in body() block") + } + if(proc.post.args.length > proc_args.length) { + throw new Error("cwise: Too many arguments in post() block") + } + + //Check debug flag + proc.debug = !!user_args.printCode || !!user_args.debug + + //Retrieve name + proc.funcName = user_args.funcName || "cwise" + + //Read in block size + proc.blockSize = user_args.blockSize || 64 + + return createThunk(proc) +} + +module.exports = compileCwise + +},{"./lib/thunk.js":111}],110:[function(require,module,exports){ +"use strict" + +var uniq = require("uniq") + +// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) +// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. +function innerFill(order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , has_index = proc.indexArgs.length>0 + , code = [] + , vars = [] + , idx=0, pidx=0, i, j + for(i=0; i=0; --i) { // Start at largest stride and work your way inwards + idx = order[i] + code.push(["for(i",i,"=0;i",i," 0) { + code.push(["index[",pidx,"]-=s",pidx].join("")) + } + code.push(["++index[",idx,"]"].join("")) + } + code.push("}") + } + return code.join("\n") +} + +// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. +// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. +// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. +function outerFill(matched, order, proc, body) { + var dimension = order.length + , nargs = proc.arrayArgs.length + , blockSize = proc.blockSize + , has_index = proc.indexArgs.length > 0 + , code = [] + for(var i=0; i0;){"].join("")) // Iterate back to front + code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). + code.push(["s",order[i],"=j",i].join("")) + code.push(["j",i,"=0"].join("")) + code.push(["}else{s",order[i],"=",blockSize].join("")) + code.push(["j",i,"-=",blockSize,"}"].join("")) + if(has_index) { + code.push(["index[",order[i],"]=j",i].join("")) + } + } + for(var i=0; i 0) { + allEqual = allEqual && summary[i] === summary[i-1] + } + } + if(allEqual) { + return summary[0] + } + return summary.join("") +} + +//Generates a cwise operator +function generateCWiseOp(proc, typesig) { + + //Compute dimension + // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. + var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 + var orders = new Array(proc.arrayArgs.length) + var dtypes = new Array(proc.arrayArgs.length) + for(var i=0; i 0) { + vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) + } + if(proc.indexArgs.length > 0) { + // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. + var zeros = new Array(dimension) + for(var i=0; i 3) { + code.push(processBlock(proc.pre, proc, dtypes)) + } + + //Process body + var body = processBlock(proc.body, proc, dtypes) + var matched = countMatches(loopOrders) + if(matched < dimension) { + code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. + } else { + code.push(innerFill(loopOrders[0], proc, body)) + } + + //Inline epilog + if(proc.post.body.length > 3) { + code.push(processBlock(proc.post, proc, dtypes)) + } + + if(proc.debug) { + console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") + } + + var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") + var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) + return f() +} +module.exports = generateCWiseOp + +},{"uniq":279}],111:[function(require,module,exports){ +"use strict" + +// The function below is called when constructing a cwise function object, and does the following: +// A function object is constructed which accepts as argument a compilation function and returns another function. +// It is this other function that is eventually returned by createThunk, and this function is the one that actually +// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. +// The compilation passed to the first function object is used for compiling new functions. +// Once this function object is created, it is called with compile as argument, where the first argument of compile +// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). +// So createThunk roughly works like this: +// function createThunk(proc) { +// var thunk = function(compileBound) { +// var CACHED = {} +// return function(arrays and scalars) { +// if (dtype and order of arrays in CACHED) { +// var func = CACHED[dtype and order of arrays] +// } else { +// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) +// } +// return func(arrays and scalars) +// } +// } +// return thunk(compile.bind1(proc)) +// } + +var compile = require("./compile.js") + +function createThunk(proc) { + var code = ["'use strict'", "var CACHED={}"] + var vars = [] + var thunkName = proc.funcName + "_cwise_thunk" + + //Build thunk + code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) + var typesig = [] + var string_typesig = [] + var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). + Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] + var shapeLengthConditions = [], shapeConditions = [] + // Process array arguments + for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) + shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) + shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") + } + } + // Check for shape equality + if (proc.arrayArgs.length > 1) { + code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") + code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") + code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") + code.push("}") + } + // Process scalar arguments + for(var i=0; i b ? 1 : a >= b ? 0 : NaN; + } + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; }; - d3.scale.category20b = function() { - return d3.scale.ordinal().range(d3_category20b); + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; }; - d3.scale.category20c = function() { - return d3.scale.ordinal().range(d3_category20c); + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; }; - var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); - var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); - var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); - var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); - d3.scale.quantile = function() { - return d3_scale_quantile([], []); + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n) if ((b = array[i]) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; }; - function d3_scale_quantile(domain, range) { - var thresholds; - function rescale() { - var k = 0, q = range.length; - thresholds = []; - while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); - return scale; + function d3_number(x) { + return x === null ? NaN : +x; + } + function d3_numeric(x) { + return !isNaN(x); + } + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = +array[i])) s += a; + } else { + while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; } - function scale(x) { - if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + return s; + }; + d3.mean = function(array, f) { + var s = 0, n = array.length, a, i = -1, j = n; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; } - scale.domain = function(x) { - if (!arguments.length) return domain; - domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.quantiles = function() { - return thresholds; - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; - }; - scale.copy = function() { - return d3_scale_quantile(domain, range); - }; - return rescale(); - } - d3.scale.quantize = function() { - return d3_scale_quantize(0, 1, [ 0, 1 ]); + if (j) return s / j; }; - function d3_scale_quantize(x0, x1, range) { - var kx, i; - function scale(x) { - return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + var numbers = [], n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); } - function rescale() { - kx = range.length / (x1 - x0); - i = range.length - 1; - return scale; + if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); + }; + d3.variance = function(array, f) { + var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) { + if (d3_numeric(a = d3_number(array[i]))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } else { + while (++i < n) { + if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } } - scale.domain = function(x) { - if (!arguments.length) return [ x0, x1 ]; - x0 = +x[0]; - x1 = +x[x.length - 1]; - return rescale(); - }; - scale.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - y = y < 0 ? NaN : y / kx + x0; - return [ y, y + 1 / kx ]; - }; - scale.copy = function() { - return d3_scale_quantize(x0, x1, range); + if (j > 1) return s / (j - 1); + }; + d3.deviation = function() { + var v = d3.variance.apply(this, arguments); + return v ? Math.sqrt(v) : v; + }; + function d3_bisector(compare) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; + } + return lo; + } }; - return rescale(); } - d3.scale.threshold = function() { - return d3_scale_threshold([ .5 ], [ 0, 1 ]); + var d3_bisect = d3_bisector(d3_ascending); + d3.bisectLeft = d3_bisect.left; + d3.bisect = d3.bisectRight = d3_bisect.right; + d3.bisector = function(f) { + return d3_bisector(f.length === 1 ? function(d, x) { + return d3_ascending(f(d), x); + } : f); }; - function d3_scale_threshold(domain, range) { - function scale(x) { - if (x <= x) return range[d3.bisect(domain, x)]; + d3.shuffle = function(array, i0, i1) { + if ((m = arguments.length) < 3) { + i1 = array.length; + if (m < 2) i0 = 0; } - scale.domain = function(_) { - if (!arguments.length) return domain; - domain = _; - return scale; - }; - scale.range = function(_) { - if (!arguments.length) return range; - range = _; - return scale; - }; - scale.invertExtent = function(y) { - y = range.indexOf(y); - return [ domain[y - 1], domain[y] ]; - }; - scale.copy = function() { - return d3_scale_threshold(domain, range); - }; - return scale; - } - d3.scale.identity = function() { - return d3_scale_identity([ 0, 1 ]); + var m = i1 - i0, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; + } + return array; }; - function d3_scale_identity(domain) { - function identity(x) { - return +x; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.transpose = function(matrix) { + if (!(n = matrix.length)) return []; + for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { + for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { + row[j] = matrix[j][i]; + } } - identity.invert = identity; - identity.domain = identity.range = function(x) { - if (!arguments.length) return domain; - domain = x.map(identity); - return identity; - }; - identity.ticks = function(m) { - return d3_scale_linearTicks(domain, m); - }; - identity.tickFormat = function(m, format) { - return d3_scale_linearTickFormat(domain, m, format); - }; - identity.copy = function() { - return d3_scale_identity(domain); - }; - return identity; - } - d3.svg = {}; - function d3_zero() { - return 0; + return transpose; + }; + function d3_transposeLength(d) { + return d.length; } - d3.svg.arc = function() { - var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; - function arc() { - var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; - if (r1 < r0) rc = r1, r1 = r0, r0 = rc; - if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; - var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; - if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { - rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); - if (!cw) p1 *= -1; - if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); - if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); - } - if (r1) { - x0 = r1 * Math.cos(a0 + p1); - y0 = r1 * Math.sin(a0 + p1); - x1 = r1 * Math.cos(a1 - p1); - y1 = r1 * Math.sin(a1 - p1); - var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; - if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { - var h1 = (a0 + a1) / 2; - x0 = r1 * Math.cos(h1); - y0 = r1 * Math.sin(h1); - x1 = y1 = null; - } - } else { - x0 = y0 = 0; - } - if (r0) { - x2 = r0 * Math.cos(a1 - p0); - y2 = r0 * Math.sin(a1 - p0); - x3 = r0 * Math.cos(a0 + p0); - y3 = r0 * Math.sin(a0 + p0); - var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; - if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { - var h0 = (a0 + a1) / 2; - x2 = r0 * Math.cos(h0); - y2 = r0 * Math.sin(h0); - x3 = y3 = null; - } - } else { - x2 = y2 = 0; + d3.zip = function() { + return d3.transpose(arguments); + }; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; } - if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { - cr = r0 < r1 ^ cw ? 0 : 1; - var rc1 = rc, rc0 = rc; - if (da < π) { - var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); - rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); - rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); - } - if (x1 != null) { - var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); - if (rc === rc1) { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); - } else { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); - } - } else { - path.push("M", x0, ",", y0); - } - if (x3 != null) { - var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); - if (rc === rc0) { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); - } else { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); - } - } else { - path.push("L", x2, ",", y2); - } - } else { - path.push("M", x0, ",", y0); - if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); - path.push("L", x2, ",", y2); - if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + } + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; } - path.push("Z"); - return path.join(""); } - function circleSegment(r1, cw) { - return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); + } + } + d3.map = function(object, f) { + var map = new d3_Map(); + if (object instanceof d3_Map) { + object.forEach(function(key, value) { + map.set(key, value); + }); + } else if (Array.isArray(object)) { + var i = -1, n = object.length, o; + if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); + } else { + for (var key in object) map.set(key, object[key]); } - arc.innerRadius = function(v) { - if (!arguments.length) return innerRadius; - innerRadius = d3_functor(v); - return arc; - }; - arc.outerRadius = function(v) { - if (!arguments.length) return outerRadius; - outerRadius = d3_functor(v); - return arc; - }; - arc.cornerRadius = function(v) { - if (!arguments.length) return cornerRadius; - cornerRadius = d3_functor(v); - return arc; - }; - arc.padRadius = function(v) { - if (!arguments.length) return padRadius; - padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); - return arc; - }; - arc.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return arc; - }; - arc.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return arc; - }; - arc.padAngle = function(v) { - if (!arguments.length) return padAngle; - padAngle = d3_functor(v); - return arc; - }; - arc.centroid = function() { - var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; - return [ Math.cos(a) * r, Math.sin(a) * r ]; - }; - return arc; + return map; }; - var d3_svg_arcAuto = "auto"; - function d3_svg_arcInnerRadius(d) { - return d.innerRadius; + function d3_Map() { + this._ = Object.create(null); } - function d3_svg_arcOuterRadius(d) { - return d.outerRadius; + var d3_map_proto = "__proto__", d3_map_zero = "\x00"; + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this._[d3_map_escape(key)]; + }, + set: function(key, value) { + return this._[d3_map_escape(key)] = value; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + for (var key in this._) values.push(this._[key]); + return values; + }, + entries: function() { + var entries = []; + for (var key in this._) entries.push({ + key: d3_map_unescape(key), + value: this._[key] + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); + } + }); + function d3_map_escape(key) { + return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; } - function d3_svg_arcStartAngle(d) { - return d.startAngle; + function d3_map_unescape(key) { + return (key += "")[0] === d3_map_zero ? key.slice(1) : key; } - function d3_svg_arcEndAngle(d) { - return d.endAngle; + function d3_map_has(key) { + return d3_map_escape(key) in this._; } - function d3_svg_arcPadAngle(d) { - return d && d.padAngle; + function d3_map_remove(key) { + return (key = d3_map_escape(key)) in this._ && delete this._[key]; } - function d3_svg_arcSweep(x0, y0, x1, y1) { - return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + function d3_map_keys() { + var keys = []; + for (var key in this._) keys.push(d3_map_unescape(key)); + return keys; } - function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { - var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; - if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; - return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; + function d3_map_size() { + var size = 0; + for (var key in this._) ++size; + return size; } - function d3_svg_line(projection) { - var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; - function line(data) { - var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); - function segment() { - segments.push("M", interpolate(projection(points), tension)); - } + function d3_map_empty() { + for (var key in this._) return false; + return true; + } + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; while (++i < n) { - if (defined.call(this, d = data[i], i)) { - points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); - } else if (points.length) { - segment(); - points = []; + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); } } - if (points.length) segment(); - return segments.length ? segments.join("") : null; + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; } - line.x = function(_) { - if (!arguments.length) return x; - x = _; - return line; + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); }; - line.y = function(_) { - if (!arguments.length) return y; - y = _; - return line; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); }; - line.defined = function(_) { - if (!arguments.length) return defined; - defined = _; - return line; + nest.key = function(d) { + keys.push(d); + return nest; }; - line.interpolate = function(_) { - if (!arguments.length) return interpolateKey; - if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; - return line; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; }; - line.tension = function(_) { - if (!arguments.length) return tension; - tension = _; - return line; + nest.sortValues = function(order) { + sortValues = order; + return nest; }; - return line; - } - d3.svg.line = function() { - return d3_svg_line(d3_identity); + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; }; - var d3_svg_lineInterpolators = d3.map({ - linear: d3_svg_lineLinear, - "linear-closed": d3_svg_lineLinearClosed, - step: d3_svg_lineStep, - "step-before": d3_svg_lineStepBefore, - "step-after": d3_svg_lineStepAfter, - basis: d3_svg_lineBasis, - "basis-open": d3_svg_lineBasisOpen, - "basis-closed": d3_svg_lineBasisClosed, - bundle: d3_svg_lineBundle, - cardinal: d3_svg_lineCardinal, - "cardinal-open": d3_svg_lineCardinalOpen, - "cardinal-closed": d3_svg_lineCardinalClosed, - monotone: d3_svg_lineMonotone - }); - d3_svg_lineInterpolators.forEach(function(key, value) { - value.key = key; - value.closed = /-closed$/.test(key); + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() { + this._ = Object.create(null); + } + d3_class(d3_Set, { + has: d3_map_has, + add: function(key) { + this._[d3_map_escape(key += "")] = true; + return key; + }, + remove: d3_map_remove, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key)); + } }); - function d3_svg_lineLinear(points) { - return points.length > 1 ? points.join("L") : points + "Z"; + d3.behavior = {}; + function d3_identity(d) { + return d; } - function d3_svg_lineLinearClosed(points) { - return points.join("L") + "Z"; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; } - function d3_svg_lineStep(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); - if (n > 1) path.push("H", p[0]); - return path.join(""); + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.slice(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } } - function d3_svg_lineStepBefore(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); - return path.join(""); + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.slice(i + 1); + type = type.slice(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; } - function d3_svg_lineStepAfter(points) { - var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; - while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); - return path.join(""); + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); } - function d3_svg_lineCardinalOpen(points, tension) { - return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; } - function d3_svg_lineCardinalClosed(points, tension) { - return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), - points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; } - function d3_svg_lineCardinal(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; } - function d3_svg_lineHermite(points, tangents) { - if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { - return d3_svg_lineLinear(points); - } - var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; - if (quad) { - path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; - p0 = points[1]; - pi = 2; - } - if (tangents.length > 1) { - t = tangents[1]; - p = points[pi]; - pi++; - path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - for (var i = 2; i < tangents.length; i++, pi++) { - p = points[pi]; - t = tangents[i]; - path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatches = function(n, s) { + var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; + d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + return d3_selectMatches(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = Sizzle; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3.select(d3_document.documentElement); + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } } } - if (quad) { - var lp = points[pi]; - path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; - } - return path; + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; } - function d3_svg_lineCardinalTangents(points, tension) { - var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; - while (++i < n) { - p0 = p1; - p1 = p2; - p2 = points[i]; - tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } } - return tangents; + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; } - function d3_svg_lineBasis(points) { - if (points.length < 3) return d3_svg_lineLinear(points); - var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; - points.push(points[n - 1]); - while (++i <= n) { - pi = points[i]; - px.shift(); - px.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px, py); + var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: d3_nsXhtml, + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; + } + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; } - points.pop(); - path.push("L", pi); - return path.join(""); - } - function d3_svg_lineBasisOpen(points) { - if (points.length < 4) return d3_svg_lineLinear(points); - var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; - while (++i < 3) { - pi = points[i]; - px.push(pi[0]); - py.push(pi[1]); + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); } - path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); - --i; - while (++i < n) { - pi = points[i]; - px.shift(); - px.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px, py); + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); } - return path.join(""); - } - function d3_svg_lineBasisClosed(points) { - var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; - while (++i < 4) { - pi = points[i % n]; - px.push(pi[0]); - py.push(pi[1]); + function attrConstant() { + this.setAttribute(name, value); } - path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; - --i; - while (++i < m) { - pi = points[i % n]; - px.shift(); - px.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px, py); + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); } - return path.join(""); - } - function d3_svg_lineBundle(points, tension) { - var n = points.length - 1; - if (n) { - var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; - while (++i <= n) { - p = points[i]; - t = i / n; - p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); - p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); - } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); } - return d3_svg_lineBasis(points); - } - function d3_svg_lineDot4(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; - } - var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; - function d3_svg_lineBasisBezier(path, x, y) { - path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); - } - function d3_svg_lineSlope(p0, p1) { - return (p1[1] - p0[1]) / (p1[0] - p0[0]); - } - function d3_svg_lineFiniteDifferences(points) { - var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); - while (++i < j) { - m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); } - m[i] = d; - return m; + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } - function d3_svg_lineMonotoneTangents(points) { - var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; - while (++i < j) { - d = d3_svg_lineSlope(points[i], points[i + 1]); - if (abs(d) < ε) { - m[i] = m[i + 1] = 0; - } else { - a = m[i] / d; - b = m[i + 1] / d; - s = a * a + b * b; - if (s > 9) { - s = d * 3 / Math.sqrt(s); - m[i] = s * a; - m[i + 1] = s * b; + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); + } + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; } + return true; } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; } - i = -1; - while (++i <= j) { - s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); - tangents.push([ s || 0, m[i] * s || 0 ]); - } - return tangents; + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } - function d3_svg_lineMonotone(points) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + function d3_selection_classes(name) { + return (name + "").trim().split(/^|\s+/); } - d3.svg.line.radial = function() { - var line = d3_svg_line(d3_svg_lineRadial); - line.radius = line.x, delete line.x; - line.angle = line.y, delete line.y; - return line; - }; - function d3_svg_lineRadial(points) { - var point, i = -1, n = points.length, r, a; - while (++i < n) { - point = points[i]; - r = point[0]; - a = point[1] - halfπ; - point[0] = r * Math.cos(a); - point[1] = r * Math.sin(a); + function d3_selection_classed(name, value) { + name = d3_selection_classes(name).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); } - return points; + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; } - function d3_svg_area(projection) { - var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; - function area(data) { - var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { - return x; - } : d3_functor(x1), fy1 = y0 === y1 ? function() { - return y; - } : d3_functor(y1), x, y; - function segment() { - segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); - } - while (++i < n) { - if (defined.call(this, d = data[i], i)) { - points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); - points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); - } else if (points0.length) { - segment(); - points0 = []; - points1 = []; - } + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); } - if (points0.length) segment(); - return segments.length ? segments.join("") : null; - } - area.x = function(_) { - if (!arguments.length) return x1; - x0 = x1 = _; - return area; - }; - area.x0 = function(_) { - if (!arguments.length) return x0; - x0 = _; - return area; - }; - area.x1 = function(_) { - if (!arguments.length) return x1; - x1 = _; - return area; - }; - area.y = function(_) { - if (!arguments.length) return y1; - y0 = y1 = _; - return area; - }; - area.y0 = function(_) { - if (!arguments.length) return y0; - y0 = _; - return area; - }; - area.y1 = function(_) { - if (!arguments.length) return y1; - y1 = _; - return area; - }; - area.defined = function(_) { - if (!arguments.length) return defined; - defined = _; - return area; - }; - area.interpolate = function(_) { - if (!arguments.length) return interpolateKey; - if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; - interpolateReverse = interpolate.reverse || interpolate; - L = interpolate.closed ? "M" : "L"; - return area; }; - area.tension = function(_) { - if (!arguments.length) return tension; - tension = _; - return area; - }; - return area; } - d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; - d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; - d3.svg.area = function() { - return d3_svg_area(d3_identity); - }; - d3.svg.area.radial = function() { - var area = d3_svg_area(d3_svg_lineRadial); - area.radius = area.x, delete area.x; - area.innerRadius = area.x0, delete area.x0; - area.outerRadius = area.x1, delete area.x1; - area.angle = area.y, delete area.y; - area.startAngle = area.y0, delete area.y0; - area.endAngle = area.y1, delete area.y1; - return area; - }; - d3.svg.chord = function() { - var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; - function chord(d, i) { - var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); - return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) { + var node = this.node(); + return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); + } + priority = ""; } - function subgroup(self, f, d, i) { - var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; - return { - r: r, - a0: a0, - a1: a1, - p0: [ r * Math.cos(a0), r * Math.sin(a0) ], - p1: [ r * Math.cos(a1), r * Math.sin(a1) ] - }; + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); } - function equals(a, b) { - return a.a0 == b.a0 && a.a1 == b.a1; + function styleConstant() { + this.style.setProperty(name, value, priority); } - function arc(r, p, a) { - return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); } - function curve(r0, p0, r1, p1) { - return "Q 0,0 " + p1; + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; + } + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); + return this; } - chord.radius = function(v) { - if (!arguments.length) return radius; - radius = d3_functor(v); - return chord; - }; - chord.source = function(v) { - if (!arguments.length) return source; - source = d3_functor(v); - return chord; - }; - chord.target = function(v) { - if (!arguments.length) return target; - target = d3_functor(v); - return chord; - }; - chord.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return chord; - }; - chord.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return chord; - }; - return chord; + return this.each(d3_selection_property(name, value)); }; - function d3_svg_chordRadius(d) { - return d.radius; - } - d3.svg.diagonal = function() { - var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; - function diagonal(d, i) { - var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { - x: p0.x, - y: m - }, { - x: p3.x, - y: m - }, p3 ]; - p = p.map(projection); - return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; } - diagonal.source = function(x) { - if (!arguments.length) return source; - source = d3_functor(x); - return diagonal; - }; - diagonal.target = function(x) { - if (!arguments.length) return target; - target = d3_functor(x); - return diagonal; - }; - diagonal.projection = function(x) { - if (!arguments.length) return projection; - projection = x; - return diagonal; - }; - return diagonal; + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; + } + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; }; - function d3_svg_diagonalProjection(d) { - return [ d.x, d.y ]; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + function create() { + var document = this.ownerDocument, namespace = this.namespaceURI; + return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); + } + function createNS() { + return this.ownerDocument.createElementNS(name.space, name.local); + } + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; } - d3.svg.diagonal.radial = function() { - var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; - diagonal.projection = function(x) { - return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; - }; - return diagonal; + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); }; - function d3_svg_diagonalRadialProjection(projection) { - return function() { - var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; - return [ r * Math.cos(a), r * Math.sin(a) ]; - }; + d3_selectionPrototype.remove = function() { + return this.each(d3_selectionRemove); + }; + function d3_selectionRemove() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); } - d3.svg.symbol = function() { - var type = d3_svg_symbolType, size = d3_svg_symbolSize; - function symbol(d, i) { - return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } + } + return value; } - symbol.type = function(x) { - if (!arguments.length) return type; - type = d3_functor(x); - return symbol; + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; + for (i = -1; ++i < n; ) { + if (node = group[i]) { + if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues[i] = keyValue; + } + } + for (i = -1; ++i < m; ) { + if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } else if (node !== true) { + updateNodes[i] = node; + node.__data__ = nodeData; + } + nodeByKeyValue.set(keyValue, true); + } + for (i = -1; ++i < n; ) { + if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { + exitNodes[i] = group[i]; + } + } + } else { + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } + } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); + } + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } + } else { + while (++i < n) { + bind(group = this[i], value); + } + } + update.enter = function() { + return enter; }; - symbol.size = function(x) { - if (!arguments.length) return size; - size = d3_functor(x); - return symbol; + update.exit = function() { + return exit; }; - return symbol; + return update; }; - function d3_svg_symbolSize() { - return 64; - } - function d3_svg_symbolType() { - return "circle"; - } - function d3_svg_symbolCircle(size) { - var r = Math.sqrt(size / π); - return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; - } - var d3_svg_symbols = d3.map({ - circle: d3_svg_symbolCircle, - cross: function(size) { - var r = Math.sqrt(size / 5) / 2; - return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; - }, - diamond: function(size) { - var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; - return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; - }, - square: function(size) { - var r = Math.sqrt(size) / 2; - return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; - }, - "triangle-down": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; - }, - "triangle-up": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; - } - }); - d3.svg.symbolTypes = d3_svg_symbols.keys(); - var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); - d3_selectionPrototype.transition = function(name) { - var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { - time: Date.now(), - ease: d3_ease_cubicInOut, - delay: 0, - duration: 250 + function d3_selection_dataNode(data) { + return { + __data__: data }; - for (var j = -1, m = this.length; ++j < m; ) { + } + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); + }; + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); - subgroup.push(node); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { + subgroup.push(node); + } } } - return d3_transition(subgroups, ns, id); - }; - d3_selectionPrototype.interrupt = function(name) { - return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); + return d3_selection(subgroups); }; - var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); - function d3_selection_interruptNS(ns) { + function d3_selection_filter(selector) { return function() { - var lock, activeId, active; - if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { - active.timer.c = null; - active.timer.t = NaN; - if (--lock.count) delete lock[activeId]; else delete this[ns]; - lock.active += .5; - active.event && active.event.interrupt.call(this, this.__data__, active.index); - } + return d3_selectMatches(this, selector); }; } - function d3_transition(groups, ns, id) { - d3_subclass(groups, d3_transitionPrototype); - groups.namespace = ns; - groups.id = id; - return groups; - } - var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; - d3_transitionPrototype.call = d3_selectionPrototype.call; - d3_transitionPrototype.empty = d3_selectionPrototype.empty; - d3_transitionPrototype.node = d3_selectionPrototype.node; - d3_transitionPrototype.size = d3_selectionPrototype.size; - d3.transition = function(selection, name) { - return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); - }; - d3.transition.prototype = d3_transitionPrototype; - d3_transitionPrototype.select = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; - selector = d3_selection_selector(selector); + d3_selectionPrototype.order = function() { for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { - if ("__data__" in node) subnode.__data__ = node.__data__; - d3_transitionNode(subnode, i, ns, id, node[ns][id]); - subgroup.push(subnode); - } else { - subgroup.push(null); + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; } } } - return d3_transition(subgroups, ns, id); + return this; }; - d3_transitionPrototype.selectAll = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - transition = node[ns][id]; - subnodes = selector.call(node, node.__data__, i, j); - subgroups.push(subgroup = []); - for (var k = -1, o = subnodes.length; ++k < o; ) { - if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); - subgroup.push(subnode); - } - } + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3_ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; + } + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); } } - return d3_transition(subgroups, ns, id); + return groups; + } + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; }; - d3_transitionPrototype.filter = function(filter) { - var subgroups = [], subgroup, group, node; - if (typeof filter !== "function") filter = d3_selection_filter(filter); + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { - subgroup.push(node); - } + var node = group[i]; + if (node) return node; } } - return d3_transition(subgroups, this.namespace, this.id); + return null; }; - d3_transitionPrototype.tween = function(name, tween) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) return this.node()[ns][id].tween.get(name); - return d3_selection_each(this, tween == null ? function(node) { - node[ns][id].tween.remove(name); - } : function(node) { - node[ns][id].tween.set(name, tween); + d3_selectionPrototype.size = function() { + var n = 0; + d3_selection_each(this, function() { + ++n; }); + return n; }; - function d3_transition_tween(groups, name, value, tween) { - var id = groups.id, ns = groups.namespace; - return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { - node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); - } : (value = tween(value), function(node) { - node[ns][id].tween.set(name, value); - })); + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; } - d3_transitionPrototype.attr = function(nameNS, value) { - if (arguments.length < 2) { - for (value in nameNS) this.attr(value, nameNS[value]); - return this; - } - var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); - function attrNull() { - this.removeAttribute(name); - } - function attrNullNS() { - this.removeAttributeNS(name.space, name.local); - } - function attrTween(b) { - return b == null ? attrNull : (b += "", function() { - var a = this.getAttribute(name), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttribute(name, i(t)); - }); - }); - } - function attrTweenNS(b) { - return b == null ? attrNullNS : (b += "", function() { - var a = this.getAttributeNS(name.space, name.local), i; - return a !== b && (i = interpolate(a, b), function(t) { - this.setAttributeNS(name.space, name.local, i(t)); - }); - }); + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } } - return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + return d3_selection(subgroups); }; - d3_transitionPrototype.attrTween = function(nameNS, tween) { - var name = d3.ns.qualify(nameNS); - function attrTween(d, i) { - var f = tween.call(this, d, i, this.getAttribute(name)); - return f && function(t) { - this.setAttribute(name, f(t)); - }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; + } + d3.select = function(node) { + var group; + if (typeof node === "string") { + group = [ d3_select(node, d3_document) ]; + group.parentNode = d3_document.documentElement; + } else { + group = [ node ]; + group.parentNode = d3_documentElement(node); } - function attrTweenNS(d, i) { - var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); - return f && function(t) { - this.setAttributeNS(name.space, name.local, f(t)); - }; + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group; + if (typeof nodes === "string") { + group = d3_array(d3_selectAll(nodes, d3_document)); + group.parentNode = d3_document.documentElement; + } else { + group = d3_array(nodes); + group.parentNode = null; } - return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + return d3_selection([ group ]); }; - d3_transitionPrototype.style = function(name, value, priority) { + d3_selectionPrototype.on = function(type, listener, capture) { var n = arguments.length; if (n < 3) { - if (typeof name !== "string") { - if (n < 2) value = ""; - for (priority in name) this.style(priority, name[priority], value); + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); return this; } - priority = ""; + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; } - function styleNull() { - this.style.removeProperty(name); + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.slice(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } } - function styleString(b) { - return b == null ? styleNull : (b += "", function() { - var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; - return a !== b && (i = d3_interpolate(a, b), function(t) { - this.style.setProperty(name, i(t), priority); - }); - }); + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; } - return d3_transition_tween(this, "style." + name, value, styleString); - }; - d3_transitionPrototype.styleTween = function(name, tween, priority) { - if (arguments.length < 3) priority = ""; - function styleTween(d, i) { - var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); - return f && function(t) { - this.style.setProperty(name, f(t), priority); - }; + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } } - return this.tween("style." + name, styleTween); - }; - d3_transitionPrototype.text = function(value) { - return d3_transition_tween(this, "text", value, d3_transition_text); - }; - function d3_transition_text(b) { - if (b == null) b = ""; - return function() { - this.textContent = b; - }; + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; } - d3_transitionPrototype.remove = function() { - var ns = this.namespace; - return this.each("end.transition", function() { - var p; - if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); - }); - }; - d3_transitionPrototype.ease = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].ease; - if (typeof value !== "function") value = d3.ease.apply(d3, arguments); - return d3_selection_each(this, function(node) { - node[ns][id].ease = value; + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + if (d3_document) { + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); }); - }; - d3_transitionPrototype.delay = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].delay; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node[ns][id].delay = +value.call(node, node.__data__, i, j); - } : (value = +value, function(node) { - node[ns][id].delay = value; - })); - }; - d3_transitionPrototype.duration = function(value) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].duration; - return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { - node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); - } : (value = Math.max(1, value), function(node) { - node[ns][id].duration = value; - })); - }; - d3_transitionPrototype.each = function(type, listener) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) { - var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + } + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; try { - d3_transitionInheritId = id; - d3_selection_each(this, function(node, i, j) { - d3_transitionInherit = node[ns][id]; - type.call(node, node.__data__, i, j); - }); + listener.apply(this, argumentz); } finally { - d3_transitionInherit = inherit; - d3_transitionInheritId = inheritId; + d3.event = o; } - } else { - d3_selection_each(this, function(node) { - var transition = node[ns][id]; - (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); - }); - } - return this; - }; - d3_transitionPrototype.transition = function() { - var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if (node = group[i]) { - transition = node[ns][id0]; - d3_transitionNode(node, i, ns, id1, { - time: transition.time, - ease: transition.ease, - delay: transition.delay + transition.duration, - duration: transition.duration - }); - } - subgroup.push(node); + }; + } + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); } - } - return d3_transition(subgroups, ns, id1); - }; - function d3_transitionNamespace(name) { - return name == null ? "__transition__" : "__transition_" + name + "__"; + }; } - function d3_transitionNode(node, i, ns, id, inherit) { - var lock = node[ns] || (node[ns] = { - active: 0, - count: 0 - }), transition = lock[id], time, timer, duration, ease, tweens; - function schedule(elapsed) { - var delay = transition.delay; - timer.t = delay + time; - if (delay <= elapsed) return start(elapsed - delay); - timer.c = start; + var d3_event_dragSelect, d3_event_dragId = 0; + function d3_event_dragSuppress(node) { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect == null) { + d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); } - function start(elapsed) { - var activeId = lock.active, active = lock[activeId]; - if (active) { - active.timer.c = null; - active.timer.t = NaN; - --lock.count; - delete lock[activeId]; - active.event && active.event.interrupt.call(node, node.__data__, active.index); + if (d3_event_dragSelect) { + var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + var off = function() { + w.on(click, null); + }; + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); } - for (var cancelId in lock) { - if (+cancelId < id) { - var cancel = lock[cancelId]; - cancel.timer.c = null; - cancel.timer.t = NaN; - --lock.count; - delete lock[cancelId]; + }; + } + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0) { + var window = d3_window(container); + if (window.scrollX || window.scrollY) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); } } - timer.c = tick; - d3_timer(function() { - if (timer.c && tick(elapsed || 1)) { - timer.c = null; - timer.t = NaN; - } - return 1; - }, 0, time); - lock.active = id; - transition.event && transition.event.start.call(node, node.__data__, i); - tweens = []; - transition.tween.forEach(function(key, value) { - if (value = value.call(node, node.__data__, i)) { - tweens.push(value); - } - }); - ease = transition.ease; - duration = transition.duration; + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; } - function tick(elapsed) { - var t = elapsed / duration, e = ease(t), n = tweens.length; - while (n > 0) { - tweens[--n].call(node, e); - } - if (t >= 1) { - transition.event && transition.event.end.call(node, node.__data__, i); - if (--lock.count) delete lock[id]; else delete node[ns]; - return 1; + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + } + d3.touch = function(container, touches, identifier) { + if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; + if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { + if ((touch = touches[i]).identifier === identifier) { + return d3_mousePoint(container, touch); } } - if (!transition) { - time = inherit.time; - timer = d3_timer(schedule, 0, time); - transition = lock[id] = { - tween: new d3_Map(), - time: time, - timer: timer, - delay: inherit.delay, - duration: inherit.duration, - ease: inherit.ease, - index: i - }; - inherit = null; - ++lock.count; + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); } - } - d3.svg.axis = function() { - var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; - function axis(g) { - g.each(function() { - var g = d3.select(this); - var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); - var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; - var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), - d3.transition(path)); - tickEnter.append("line"); - tickEnter.append("text"); - var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; - if (orient === "bottom" || orient === "top") { - tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; - text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); + function dragstart(id, position, subject, move, end) { + return function() { + var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); + if (origin) { + dragOffset = origin.apply(that, arguments); + dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; } else { - tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; - text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); - pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); + dragOffset = [ 0, 0 ]; } - lineEnter.attr(y2, sign * innerTickSize); - textEnter.attr(y1, sign * tickSpacing); - lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); - textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); - if (scale1.rangeBand) { - var x = scale1, dx = x.rangeBand() / 2; - scale0 = scale1 = function(d) { - return x(d) + dx; - }; - } else if (scale0.rangeBand) { - scale0 = scale1; - } else { - tickExit.call(tickTransform, scale1, scale0); + dispatch({ + type: "dragstart" + }); + function moved() { + var position1 = position(parent, dragId), dx, dy; + if (!position1) return; + dx = position1[0] - position0[0]; + dy = position1[1] - position0[1]; + dragged |= dx | dy; + position0 = position1; + dispatch({ + type: "drag", + x: position1[0] + dragOffset[0], + y: position1[1] + dragOffset[1], + dx: dx, + dy: dy + }); } - tickEnter.call(tickTransform, scale0, scale1); - tickUpdate.call(tickTransform, scale1, scale1); - }); + function ended() { + if (!position(parent, dragId)) return; + dragSubject.on(move + dragName, null).on(end + dragName, null); + dragRestore(dragged); + dispatch({ + type: "dragend" + }); + } + }; } - axis.scale = function(x) { - if (!arguments.length) return scale; - scale = x; - return axis; - }; - axis.orient = function(x) { - if (!arguments.length) return orient; - orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; - return axis; - }; - axis.ticks = function() { - if (!arguments.length) return tickArguments_; - tickArguments_ = d3_array(arguments); - return axis; - }; - axis.tickValues = function(x) { - if (!arguments.length) return tickValues; - tickValues = x; - return axis; - }; - axis.tickFormat = function(x) { - if (!arguments.length) return tickFormat_; - tickFormat_ = x; - return axis; - }; - axis.tickSize = function(x) { - var n = arguments.length; - if (!n) return innerTickSize; - innerTickSize = +x; - outerTickSize = +arguments[n - 1]; - return axis; - }; - axis.innerTickSize = function(x) { - if (!arguments.length) return innerTickSize; - innerTickSize = +x; - return axis; - }; - axis.outerTickSize = function(x) { - if (!arguments.length) return outerTickSize; - outerTickSize = +x; - return axis; - }; - axis.tickPadding = function(x) { - if (!arguments.length) return tickPadding; - tickPadding = +x; - return axis; - }; - axis.tickSubdivide = function() { - return arguments.length && axis; + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; }; - return axis; + return d3.rebind(drag, event, "on"); }; - var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { - top: 1, - right: 1, - bottom: 1, - left: 1 + function d3_behavior_dragTouchId() { + return d3.event.changedTouches[0].identifier; + } + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; }; - function d3_svg_axisX(selection, x0, x1) { - selection.attr("transform", function(d) { - var v0 = x0(d); - return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; - }); + var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; } - function d3_svg_axisY(selection, y0, y1) { - selection.attr("transform", function(d) { - var v0 = y0(d); - return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; - }); + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); } - d3.svg.brush = function() { - var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; - function brush(g) { - g.each(function() { - var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); - var background = g.selectAll(".background").data([ 0 ]); - background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); - g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); - var resize = g.selectAll(".resize").data(resizes, d3_identity); - resize.exit().remove(); - resize.enter().append("g").attr("class", function(d) { - return "resize " + d; - }).style("cursor", function(d) { - return d3_svg_brushCursor[d]; - }).append("rect").attr("x", function(d) { - return /[ew]$/.test(d) ? -3 : null; - }).attr("y", function(d) { - return /^[ns]/.test(d) ? -3 : null; - }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); - resize.style("display", brush.empty() ? "none" : null); - var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; - if (x) { - range = d3_scaleRange(x); - backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); - redrawX(gUpdate); - } - if (y) { - range = d3_scaleRange(y); - backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); - redrawY(gUpdate); - } - redraw(gUpdate); - }); + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? π : Math.acos(x); + } + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; + } + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < ε2) { + S = Math.log(w1 / w0) / ρ; + i = function(t) { + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; + }; + } else { + var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); + S = (r1 - r0) / ρ; + i = function(t) { + var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; + }; } - brush.event = function(g) { + i.duration = S * 1e3; + return i; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + if (!d3_behavior_zoomWheel) { + d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); + } + function zoom(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom.event = function(g) { g.each(function() { - var event_ = event.of(this, arguments), extent1 = { - x: xExtent, - y: yExtent, - i: xExtentDomain, - j: yExtentDomain - }, extent0 = this.__chart__ || extent1; - this.__chart__ = extent1; + var dispatch = event.of(this, arguments), view1 = view; if (d3_transitionInheritId) { - d3.select(this).transition().each("start.brush", function() { - xExtentDomain = extent0.i; - yExtentDomain = extent0.j; - xExtent = extent0.x; - yExtent = extent0.y; - event_({ - type: "brushstart" - }); - }).tween("brush:brush", function() { - var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); - xExtentDomain = yExtentDomain = null; + d3.select(this).transition().each("start.zoom", function() { + view = this.__chart__ || { + x: 0, + y: 0, + k: 1 + }; + zoomstarted(dispatch); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); return function(t) { - xExtent = extent1.x = xi(t); - yExtent = extent1.y = yi(t); - event_({ - type: "brush", - mode: "resize" - }); + var l = i(t), k = dx / l[2]; + this.__chart__ = view = { + x: cx - l[0] * k, + y: cy - l[1] * k, + k: k + }; + zoomed(dispatch); }; - }).each("end.brush", function() { - xExtentDomain = extent1.i; - yExtentDomain = extent1.j; - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); + }).each("interrupt.zoom", function() { + zoomended(dispatch); + }).each("end.zoom", function() { + zoomended(dispatch); }); } else { - event_({ - type: "brushstart" - }); - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); + this.__chart__ = view; + zoomstarted(dispatch); + zoomed(dispatch); + zoomended(dispatch); } }); }; - function redraw(g) { - g.selectAll(".resize").attr("transform", function(d) { - return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; - }); + zoom.translate = function(_) { + if (!arguments.length) return [ view.x, view.y ]; + view = { + x: +_[0], + y: +_[1], + k: view.k + }; + rescale(); + return zoom; + }; + zoom.scale = function(_) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: null + }; + scaleTo(+_); + rescale(); + return zoom; + }; + zoom.scaleExtent = function(_) { + if (!arguments.length) return scaleExtent; + scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; + return zoom; + }; + zoom.center = function(_) { + if (!arguments.length) return center; + center = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.size = function(_) { + if (!arguments.length) return size; + size = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.duration = function(_) { + if (!arguments.length) return duration; + duration = +_; + return zoom; + }; + zoom.x = function(z) { + if (!arguments.length) return x1; + x1 = z; + x0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + zoom.y = function(z) { + if (!arguments.length) return y1; + y1 = z; + y0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + function location(p) { + return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; } - function redrawX(g) { - g.select(".extent").attr("x", xExtent[0]); - g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + function point(l) { + return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; } - function redrawY(g) { - g.select(".extent").attr("y", yExtent[0]); - g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); } - function brushstart() { - var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; - var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); - if (d3.event.changedTouches) { - w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); - } else { - w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); - } - g.interrupt().selectAll("*").interrupt(); - if (dragging) { - origin[0] = xExtent[0] - origin[0]; - origin[1] = yExtent[0] - origin[1]; - } else if (resizing) { - var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); - offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; - origin[0] = xExtent[ex]; - origin[1] = yExtent[ey]; - } else if (d3.event.altKey) center = origin.slice(); - g.style("pointer-events", "none").selectAll(".resize").style("display", null); - d3.select("body").style("cursor", eventTarget.style("cursor")); - event_({ - type: "brushstart" + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function zoomTo(that, p, l, k) { + that.__chart__ = { + x: view.x, + y: view.y, + k: view.k + }; + scaleTo(Math.pow(2, k)); + translateTo(center0 = p, l); + that = d3.select(that); + if (duration > 0) that = that.transition().duration(duration); + that.call(zoom.event); + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(dispatch) { + if (!zooming++) dispatch({ + type: "zoomstart" }); - brushmove(); - function keydown() { - if (d3.event.keyCode == 32) { - if (!dragging) { - center = null; - origin[0] -= xExtent[1]; - origin[1] -= yExtent[1]; - dragging = 2; - } - d3_eventPreventDefault(); - } + } + function zoomed(dispatch) { + rescale(); + dispatch({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(dispatch) { + if (!--zooming) dispatch({ + type: "zoomend" + }), center0 = null; + } + function mousedowned() { + var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); + d3_selection_interrupt.call(that); + zoomstarted(dispatch); + function moved() { + dragged = 1; + translateTo(d3.mouse(that), location0); + zoomed(dispatch); } - function keyup() { - if (d3.event.keyCode == 32 && dragging == 2) { - origin[0] += xExtent[1]; - origin[1] += yExtent[1]; - dragging = 0; - d3_eventPreventDefault(); - } + function ended() { + subject.on(mousemove, null).on(mouseup, null); + dragRestore(dragged); + zoomended(dispatch); } - function brushmove() { - var point = d3.mouse(target), moved = false; - if (offset) { - point[0] += offset[0]; - point[1] += offset[1]; - } - if (!dragging) { - if (d3.event.altKey) { - if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; - origin[0] = xExtent[+(point[0] < center[0])]; - origin[1] = yExtent[+(point[1] < center[1])]; - } else center = null; - } - if (resizingX && move1(point, x, 0)) { - redrawX(g); - moved = true; - } - if (resizingY && move1(point, y, 1)) { - redrawY(g); - moved = true; + } + function touchstarted() { + var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); + started(); + zoomstarted(dispatch); + subject.on(mousedown, null).on(touchstart, started); + function relocate() { + var touches = d3.touches(that); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var target = d3.event.target; + d3.select(target).on(touchmove, moved).on(touchend, ended); + targets.push(target); + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; } - if (moved) { - redraw(g); - event_({ - type: "brush", - mode: dragging ? "move" : "resize" - }); + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0]; + zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); + d3_eventPreventDefault(); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; } } - function move1(point, scale, i) { - var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; - if (dragging) { - r0 -= position; - r1 -= size + position; - } - min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; - if (dragging) { - max = (min += position) + size; - } else { - if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); - if (position < min) { - max = min; - min = position; - } else { - max = position; + function moved() { + var touches = d3.touches(that), p0, l0, p1, l1; + d3_selection_interrupt.call(that); + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; } } - if (extent[0] != min || extent[1] != max) { - if (i) yExtentDomain = null; else xExtentDomain = null; - extent[0] = min; - extent[1] = max; - return true; + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); } + touchtime = null; + translateTo(p0, l0); + zoomed(dispatch); } - function brushend() { - brushmove(); - g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); - d3.select("body").style("cursor", null); - w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); - dragRestore(); - event_({ - type: "brushend" - }); - } - } - brush.x = function(z) { - if (!arguments.length) return x; - x = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.y = function(z) { - if (!arguments.length) return y; - y = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.clamp = function(z) { - if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; - if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; - return brush; - }; - brush.extent = function(z) { - var x0, x1, y0, y1, t; - if (!arguments.length) { - if (x) { - if (xExtentDomain) { - x0 = xExtentDomain[0], x1 = xExtentDomain[1]; - } else { - x0 = xExtent[0], x1 = xExtent[1]; - if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; } - } - if (y) { - if (yExtentDomain) { - y0 = yExtentDomain[0], y1 = yExtentDomain[1]; - } else { - y0 = yExtent[0], y1 = yExtent[1]; - if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; + for (var identifier in locations0) { + return void relocate(); } } - return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; - } - if (x) { - x0 = z[0], x1 = z[1]; - if (y) x0 = x0[0], x1 = x1[0]; - xExtentDomain = [ x0, x1 ]; - if (x.invert) x0 = x(x0), x1 = x(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; - } - if (y) { - y0 = z[0], y1 = z[1]; - if (x) y0 = y0[1], y1 = y1[1]; - yExtentDomain = [ y0, y1 ]; - if (y.invert) y0 = y(y0), y1 = y(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; - } - return brush; - }; - brush.clear = function() { - if (!brush.empty()) { - xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; - xExtentDomain = yExtentDomain = null; + d3.selectAll(targets).on(zoomName, null); + subject.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(dispatch); } - return brush; - }; - brush.empty = function() { - return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; - }; - return d3.rebind(brush, event, "on"); + } + function mousewheeled() { + var dispatch = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), + translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(dispatch); + }, 50); + d3_eventPreventDefault(); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(center0, translate0); + zoomed(dispatch); + } + function dblclicked() { + var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; + zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + } + return d3.rebind(zoom, event, "on"); }; - var d3_svg_brushCursor = { - n: "ns-resize", - e: "ew-resize", - s: "ns-resize", - w: "ew-resize", - nw: "nwse-resize", - ne: "nesw-resize", - se: "nwse-resize", - sw: "nesw-resize" + var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; + d3.color = d3_color; + function d3_color() {} + d3_color.prototype.toString = function() { + return this.rgb() + ""; }; - var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; - var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; - var d3_time_formatUtc = d3_time_format.utc; - var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); - d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; - function d3_time_formatIsoNative(date) { - return date.toISOString(); + d3.hsl = d3_hsl; + function d3_hsl(h, s, l) { + return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); } - d3_time_formatIsoNative.parse = function(string) { - var date = new Date(string); - return isNaN(date) ? null : date; + var d3_hslPrototype = d3_hsl.prototype = new d3_color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, this.l / k); }; - d3_time_formatIsoNative.toString = d3_time_formatIso.toString; - d3_time.second = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 1e3) * 1e3); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 1e3); - }, function(date) { - return date.getSeconds(); - }); - d3_time.seconds = d3_time.second.range; - d3_time.seconds.utc = d3_time.second.utc.range; - d3_time.minute = d3_time_interval(function(date) { - return new d3_date(Math.floor(date / 6e4) * 6e4); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 6e4); - }, function(date) { - return date.getMinutes(); - }); - d3_time.minutes = d3_time.minute.range; - d3_time.minutes.utc = d3_time.minute.utc.range; - d3_time.hour = d3_time_interval(function(date) { - var timezone = date.getTimezoneOffset() / 60; - return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); - }, function(date, offset) { - date.setTime(date.getTime() + Math.floor(offset) * 36e5); - }, function(date) { - return date.getHours(); - }); - d3_time.hours = d3_time.hour.range; - d3_time.hours.utc = d3_time.hour.utc.range; - d3_time.month = d3_time_interval(function(date) { - date = d3_time.day(date); - date.setDate(1); - return date; - }, function(date, offset) { - date.setMonth(date.getMonth() + offset); - }, function(date) { - return date.getMonth(); - }); - d3_time.months = d3_time.month.range; - d3_time.months.utc = d3_time.month.utc.range; - function d3_time_scale(linear, methods, format) { - function scale(x) { - return linear(x); + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; } - scale.invert = function(x) { - return d3_time_scaleDate(linear.invert(x)); - }; - scale.domain = function(x) { - if (!arguments.length) return linear.domain().map(d3_time_scaleDate); - linear.domain(x); - return scale; - }; - function tickMethod(extent, count) { - var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); - return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { - return d / 31536e6; - }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + function vv(h) { + return Math.round(v(h) * 255); } - scale.nice = function(interval, skip) { - var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); - if (method) interval = method[0], skip = method[1]; - function skipped(date) { - return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; - } - return scale.domain(d3_scale_nice(domain, skip > 1 ? { - floor: function(date) { - while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); - return date; - }, - ceil: function(date) { - while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); - return date; - } - } : interval)); - }; - scale.ticks = function(interval, skip) { - var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { - range: interval - }, skip ]; - if (method) interval = method[0], skip = method[1]; - return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); - }; - scale.tickFormat = function() { - return format; - }; - scale.copy = function() { - return d3_time_scale(linear.copy(), methods, format); - }; - return d3_scale_linearRebind(scale, linear); + return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } - function d3_time_scaleDate(t) { - return new Date(t); + d3.hcl = d3_hcl; + function d3_hcl(h, c, l) { + return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); } - var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; - var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; - var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { - return d.getMilliseconds(); - } ], [ ":%S", function(d) { - return d.getSeconds(); - } ], [ "%I:%M", function(d) { - return d.getMinutes(); - } ], [ "%I %p", function(d) { - return d.getHours(); - } ], [ "%a %d", function(d) { - return d.getDay() && d.getDate() != 1; - } ], [ "%b %d", function(d) { - return d.getDate() != 1; - } ], [ "%B", function(d) { - return d.getMonth(); - } ], [ "%Y", d3_true ] ]); - var d3_time_scaleMilliseconds = { - range: function(start, stop, step) { - return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); - }, - floor: d3_identity, - ceil: d3_identity + var d3_hclPrototype = d3_hcl.prototype = new d3_color(); + d3_hclPrototype.brighter = function(k) { + return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); }; - d3_time_scaleLocalMethods.year = d3_time.year; - d3_time.scale = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + d3_hclPrototype.darker = function(k) { + return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); }; - var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { - return [ m[0].utc, m[1] ]; - }); - var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { - return d.getUTCMilliseconds(); - } ], [ ":%S", function(d) { - return d.getUTCSeconds(); - } ], [ "%I:%M", function(d) { - return d.getUTCMinutes(); - } ], [ "%I %p", function(d) { - return d.getUTCHours(); - } ], [ "%a %d", function(d) { - return d.getUTCDay() && d.getUTCDate() != 1; - } ], [ "%b %d", function(d) { - return d.getUTCDate() != 1; - } ], [ "%B", function(d) { - return d.getUTCMonth(); - } ], [ "%Y", d3_true ] ]); - d3_time_scaleUtcMethods.year = d3_time.year.utc; - d3_time.scale.utc = function() { - return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + d3_hclPrototype.rgb = function() { + return d3_hcl_lab(this.h, this.c, this.l).rgb(); + }; + function d3_hcl_lab(h, c, l) { + if (isNaN(h)) h = 0; + if (isNaN(c)) c = 0; + return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + } + d3.lab = d3_lab; + function d3_lab(l, a, b) { + return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + } + var d3_lab_K = 18; + var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; + var d3_labPrototype = d3_lab.prototype = new d3_color(); + d3_labPrototype.brighter = function(k) { + return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.darker = function(k) { + return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.rgb = function() { + return d3_lab_rgb(this.l, this.a, this.b); + }; + function d3_lab_rgb(l, a, b) { + var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; + x = d3_lab_xyz(x) * d3_lab_X; + y = d3_lab_xyz(y) * d3_lab_Y; + z = d3_lab_xyz(z) * d3_lab_Z; + return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + } + function d3_lab_hcl(l, a, b) { + return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + } + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + } + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + } + function d3_xyz_rgb(r) { + return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + } + d3.rgb = d3_rgb; + function d3_rgb(r, g, b) { + return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + } + function d3_rgbNumber(value) { + return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return new d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return new d3_rgb(k * this.r, k * this.g, k * this.b); }; - d3.text = d3_xhrType(function(request) { - return request.responseText; - }); - d3.json = function(url, callback) { - return d3_xhr(url, "application/json", d3_json, callback); + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); }; - function d3_json(request) { - return JSON.parse(request.responseText); - } - d3.html = function(url, callback) { - return d3_xhr(url, "text/html", d3_html, callback); + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); }; - function d3_html(request) { - var range = d3_document.createRange(); - range.selectNode(d3_document.body); - return range.createContextualFragment(request.responseText); - } - d3.xml = d3_xhrType(function(request) { - return request.responseXML; - }); - if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; -}(); -},{}],83:[function(require,module,exports){ -arguments[4][76][0].apply(exports,arguments) -},{"dup":76,"robust-orientation":1040,"simplicial-complex":86}],84:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],85:[function(require,module,exports){ -arguments[4][78][0].apply(exports,arguments) -},{"dup":78}],86:[function(require,module,exports){ -arguments[4][79][0].apply(exports,arguments) -},{"bit-twiddle":84,"dup":79,"union-find":85}],87:[function(require,module,exports){ -"use strict" - -function unique_pred(list, compare) { - var ptr = 1 - , len = list.length - , a=list[0], b=list[0] - for(var i=1; i> 4; + r = r >> 4 | r; + g = color & 240; + g = g >> 4 | g; + b = color & 15; + b = b << 4 | b; + } else if (format.length === 7) { + r = (color & 16711680) >> 16; + g = (color & 65280) >> 8; + b = color & 255; + } } + return rgb(r, g, b); } - return 0 -} - -function triangulate1D(n, points, includePointAtInfinity) { - if(n === 1) { - if(includePointAtInfinity) { - return [ [-1, 0] ] + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; } else { - return [] + h = NaN; + s = l > 0 && l < 1 ? 0 : h; } + return new d3_hsl(h, s, l); } - var lifted = points.map(function(p, i) { - return [ p[0], i ] - }) - lifted.sort(function(a,b) { - return a[0] - b[0] - }) - var cells = new Array(n - 1) - for(var i=1; i= 2) { - return false - } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; } - cell[j] = v + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); } - return true - }) - } else { - hull = hull.filter(function(cell) { - for(var i=0; i<=d; ++i) { - var v = dindex[cell[i]] - if(v < 0) { - return false - } - cell[i] = v + } + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; } - return true - }) + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); } - - if(d & 1) { - for(var i=0; i= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.slice(j + 1, i).replace(/""/g, '"'); + } + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.slice(j, I - k); } + return text.slice(j); } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); + } + if (f && (a = f(a, n++)) == null) continue; + rows.push(a); + } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); } - - function lib$es6$promise$asap$$setScheduler(scheduleFn) { - lib$es6$promise$asap$$customSchedulerFn = scheduleFn; - } - - function lib$es6$promise$asap$$setAsap(asapFn) { - lib$es6$promise$asap$$asap = asapFn; + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; } - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function() { - process.nextTick(lib$es6$promise$asap$$flush); - }; + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function() { + d3_timer.apply(this, arguments); + }; + function d3_timer(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; + return timer; + } + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); + } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(), timer = d3_timer_queueHead; + while (timer) { + if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; + timer = timer.n; } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.c) { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } else { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + } } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; + d3_timer_queueTail = t0; + return time; + } + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value = +value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + function d3_locale_numberFormat(locale) { + var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { + var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; + while (i > 0 && g > 0) { + if (length + g + 1 > width) g = Math.max(1, width - length); + t.push(value.substring(i -= g, i + g)); + if ((length += g + 1) > width) break; + g = locale_grouping[j = (j + 1) % locale_grouping.length]; } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); + return t.reverse().join(locale_thousands); + } : d3_identity; + return function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; } - } + switch (type) { + case "n": + comma = true; + type = "g"; + break; - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - function lib$es6$promise$then$$then(onFulfillment, onRejection) { - var parent = this; + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; - var child = new this.constructor(lib$es6$promise$$internal$$noop); + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; - if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { - lib$es6$promise$$internal$$makePromise(child); - } + case "b": + case "o": + case "x": + case "X": + if (symbol === "#") prefix = "0" + type.toLowerCase(); - var state = parent._state; + case "c": + exponent = false; - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$asap(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } + case "d": + integer = true; + precision = 0; + break; - return child; + case "s": + scale = -1; + type = "r"; + break; + } + if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; + if (type == "r" && !precision) type = "g"; + if (precision != null) { + if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); + } + type = d3_format_types.get(type) || d3_format_typeDefault; + var zcomma = zfill && comma; + return function(value) { + var fullSuffix = suffix; + if (integer && value % 1) return ""; + var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; + if (scale < 0) { + var unit = d3.formatPrefix(value, precision); + value = unit.scale(value); + fullSuffix = unit.symbol + suffix; + } else { + value *= scale; + } + value = type(value, precision); + var i = value.lastIndexOf("."), before, after; + if (i < 0) { + var j = exponent ? value.lastIndexOf("e") : -1; + if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); + } else { + before = value.substring(0, i); + after = locale_decimal + value.substring(i + 1); + } + if (!zfill && comma) before = formatGroup(before, Infinity); + var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; + if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); + negative += prefix; + value = before + after; + return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; + }; + }; + } + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); + } + }); + function d3_format_typeDefault(x) { + return x + ""; + } + var d3_time = d3.time = {}, d3_date = Date; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); + } + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); } - var lib$es6$promise$then$$default = lib$es6$promise$then$$then; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; + }; + var d3_time_prototype = Date.prototype; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); + function ceil(date) { + step(date = local(new d3_date(date - 1)), 1); + return date; } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); + function offset(date, k) { + step(date = new d3_date(+date), k); + return date; } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; + function range(t0, t1, dt) { + var time = ceil(t0), times = []; + if (dt > 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); } + return times; } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + function range_utc(t0, t1, dt) { try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; } } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$asap(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; + } + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; + } + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + function d3_locale_timeFormat(locale) { + var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.slice(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); + string.push(template.slice(j, i)); + return string.join(""); } + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { + if (!("w" in d)) d.w = "W" in d ? 1 : 0; + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { - if (maybeThenable.constructor === promise.constructor && - then === lib$es6$promise$then$$default && - constructor.resolve === lib$es6$promise$promise$resolve$$default) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; } } + return j; } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + d3_time_format.utc = function(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; } + }; + format.toString = local.toString; + return format; + }; + d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; + var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); + locale_periods.forEach(function(p, i) { + d3_time_periodLookup.set(p.toLowerCase(), i); + }); + var d3_time_formats = { + a: function(d) { + return locale_shortDays[d.getDay()]; + }, + A: function(d) { + return locale_days[d.getDay()]; + }, + b: function(d) { + return locale_shortMonths[d.getMonth()]; + }, + B: function(d) { + return locale_months[d.getMonth()]; + }, + c: d3_time_format(locale_dateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return locale_periods[+(d.getHours() >= 12)]; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(locale_date), + X: d3_time_format(locale_time), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; } - - promise._subscribers.length = 0; + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.slice(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.slice(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); } - - var lib$es6$promise$$internal$$id = 0; - function lib$es6$promise$$internal$$nextId() { - return lib$es6$promise$$internal$$id++; + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); } - - function lib$es6$promise$$internal$$makePromise(promise) { - promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); } - - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!lib$es6$promise$utils$$isArray(entries)) { - return new Constructor(function(resolve, reject) { - reject(new TypeError('You must pass an array to race.')); - }); - } else { - return new Constructor(function(resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); - } - }); - } + return d3_time_format; + } + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); + } + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + } + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; + } + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; + } + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; + } + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + } + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, + i + 5) : -1; + } + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); + } + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + } + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; + } + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; + } + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; + } + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.slice(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; + } + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + } + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.slice(i, i + 1)); + return n ? i + n[0].length : -1; + } + function d3_time_formatMulti(formats) { + var n = formats.length, i = -1; + while (++i < n) formats[i][0] = this(formats[i][0]); + return function(date) { + var i = 0, f = formats[i]; + while (!f[1](date)) f = formats[++i]; + return f[0](date); + }; + } + d3.locale = function(locale) { + return { + numberFormat: d3_locale_numberFormat(locale), + timeFormat: d3_locale_timeFormat(locale) + }; + }; + var d3_locale_enUS = d3.locale({ + decimal: ".", + thousands: ",", + grouping: [ 3 ], + currency: [ "$", "" ], + dateTime: "%a %b %e %X %Y", + date: "%m/%d/%Y", + time: "%H:%M:%S", + periods: [ "AM", "PM" ], + days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], + shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], + months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], + shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] + }); + d3.format = d3_locale_enUS.numberFormat; + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); + } + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + var d3_geo_streamObjectType = { + Feature: function(feature, listener) { + d3_geo_streamGeometry(feature.geometry, listener); + }, + FeatureCollection: function(object, listener) { + var features = object.features, i = -1, n = features.length; + while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); - this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); - } + }; + var d3_geo_streamGeometryType = { + Sphere: function(object, listener) { + listener.sphere(); + }, + Point: function(object, listener) { + object = object.coordinates; + listener.point(object[0], object[1], object[2]); + }, + MultiPoint: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); + }, + LineString: function(object, listener) { + d3_geo_streamLine(object.coordinates, listener, 0); + }, + MultiLineString: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); + }, + Polygon: function(object, listener) { + d3_geo_streamPolygon(object.coordinates, listener); + }, + MultiPolygon: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); + }, + GeometryCollection: function(object, listener) { + var geometries = object.geometries, i = -1, n = geometries.length; + while (++i < n) d3_geo_streamGeometry(geometries[i], listener); } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; - lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; - lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure + }; + function d3_geo_streamLine(coordinates, listener, closed) { + var i = -1, n = coordinates.length - closed, coordinate; + listener.lineStart(); + while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); + listener.lineEnd(); + } + function d3_geo_streamPolygon(coordinates, listener) { + var i = -1, n = coordinates.length; + listener.polygonStart(); + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); + listener.polygonEnd(); + } + d3.geo.area = function(object) { + d3_geo_areaSum = 0; + d3.geo.stream(object, d3_geo_area); + return d3_geo_areaSum; + }; + var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); + var d3_geo_area = { + sphere: function() { + d3_geo_areaSum += 4 * π; + }, + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_areaRingSum.reset(); + d3_geo_area.lineStart = d3_geo_areaRingStart; + }, + polygonEnd: function() { + var area = 2 * d3_geo_areaRingSum; + d3_geo_areaSum += area < 0 ? 4 * π + area : area; + d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + } + }; + function d3_geo_areaRingStart() { + var λ00, φ00, λ0, cosφ0, sinφ0; + d3_geo_area.point = function(λ, φ) { + d3_geo_area.point = nextPoint; + λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), + sinφ0 = Math.sin(φ); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + φ = φ * d3_radians / 2 + π / 4; + var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; + } + function d3_geo_cartesian(spherical) { + var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); + return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + } + function d3_geo_cartesianDot(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + function linePoint(λ, φ) { + var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); + if (p0) { + var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); + d3_geo_cartesianNormalize(inflection); + inflection = d3_geo_spherical(inflection); + var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; } else { - // success + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); + if (antimeridian) { + if (λ < λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: lib$es6$promise$then$$default, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { - lib$es6$promise$$internal$$makePromise(this.promise); - } - - if (lib$es6$promise$utils$$isArray(input)) { - this._input = input; - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); } else { - this.length = this.length || 0; - this._enumerate(); - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(this.promise, this._result); + if (λ1 >= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } } } } else { - lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); + point(λ, φ); } + p0 = p, λ_ = λ; } - - function lib$es6$promise$enumerator$$validationError() { - return new Error('Array Methods must be provided an Array'); + function lineStart() { + bound.point = linePoint; } - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var length = this.length; - var input = this._input; - - for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - this._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var c = this._instanceConstructor; - var resolve = c.resolve; - - if (resolve === lib$es6$promise$promise$resolve$$default) { - var then = lib$es6$promise$$internal$$getThen(entry); - - if (then === lib$es6$promise$then$$default && - entry._state !== lib$es6$promise$$internal$$PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === lib$es6$promise$promise$$default) { - var promise = new c(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); - } - } else { - this._willSettleAt(resolve(entry), i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var promise = this.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - this._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - this._result[i] = value; - } - } - - if (this._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, this._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); } - - lib$es6$promise$polyfill$$default(); -}).call(this); - - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":70}],90:[function(require,module,exports){ -/** - * inspired by is-number - * but significantly simplified and sped up by ignoring number and string constructors - * ie these return false: - * new Number(1) - * new String('1') - */ - -'use strict'; - -/** - * Is this string all whitespace? - * This solution kind of makes my brain hurt, but it's significantly faster - * than !str.trim() or any other solution I could find. - * - * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character - * and verified with: - * - * for(var i = 0; i < 65536; i++) { - * var s = String.fromCharCode(i); - * if(+s===0 && !s.trim()) console.log(i, s); - * } - * - * which counts a couple of these as *not* whitespace, but finds nothing else - * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears - * that there are no whitespace characters above this, and code points above - * this do not map onto white space characters. - */ -function allBlankCharCodes(str){ - var l = str.length, - a; - for(var i = 0; i < l; i++) { - a = str.charCodeAt(i); - if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) && - (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) && - (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) && - (a !== 8288) && (a !== 12288) && (a !== 65279)) { - return false; - } + function ringStart() { + d3_geo_area.lineStart(); } - return true; -} - -module.exports = function(n) { - var type = typeof n; - if(type === 'string') { - var original = n; - n = +n; - // whitespace strings cast to zero - filter them out - if(n===0 && allBlankCharCodes(original)) return false; + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; } - else if(type !== 'number') return false; - - return n - n < 1; -}; - -},{}],91:[function(require,module,exports){ -'use strict' - -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var pool = require('typedarray-pool') -var shaders = require('./lib/shaders') - -module.exports = createError2D - -var WEIGHTS = [ - // x-error bar - [1, 0, 0, 1, 0, 0], - [1, 0, 0, -1, 0, 0], - [-1, 0, 0, -1, 0, 0], - - [-1, 0, 0, -1, 0, 0], - [-1, 0, 0, 1, 0, 0], - [1, 0, 0, 1, 0, 0], - - // x-error right cap - [1, 0, -1, 0, 0, 1], - [1, 0, -1, 0, 0, -1], - [1, 0, 1, 0, 0, -1], - - [1, 0, 1, 0, 0, -1], - [1, 0, 1, 0, 0, 1], - [1, 0, -1, 0, 0, 1], - - // x-error left cap - [-1, 0, -1, 0, 0, 1], - [-1, 0, -1, 0, 0, -1], - [-1, 0, 1, 0, 0, -1], - - [-1, 0, 1, 0, 0, -1], - [-1, 0, 1, 0, 0, 1], - [-1, 0, -1, 0, 0, 1], - - // y-error bar - [0, 1, 1, 0, 0, 0], - [0, 1, -1, 0, 0, 0], - [0, -1, -1, 0, 0, 0], - - [0, -1, -1, 0, 0, 0], - [0, 1, 1, 0, 0, 0], - [0, -1, 1, 0, 0, 0], - - // y-error top cap - [0, 1, 0, -1, 1, 0], - [0, 1, 0, -1, -1, 0], - [0, 1, 0, 1, -1, 0], - - [0, 1, 0, 1, 1, 0], - [0, 1, 0, -1, 1, 0], - [0, 1, 0, 1, -1, 0], - - // y-error bottom cap - [0, -1, 0, -1, 1, 0], - [0, -1, 0, -1, -1, 0], - [0, -1, 0, 1, -1, 0], - - [0, -1, 0, 1, 1, 0], - [0, -1, 0, -1, 1, 0], - [0, -1, 0, 1, -1, 0] -] - -function GLError2D (plot, shader, buffer) { - this.plot = plot - - this.shader = shader - this.buffer = buffer - - this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - - this.numPoints = 0 - - this.color = [0, 0, 0, 1] -} - -var proto = GLError2D.prototype - -proto.draw = (function () { - var MATRIX = [ - 1, 0, 0, - 0, 1, 0, - 0, 0, 1 - ] - - var PIXEL_SCALE = [1, 1] - - return function () { - var plot = this.plot - var shader = this.shader - var buffer = this.buffer - var bounds = this.bounds - var numPoints = this.numPoints - - if (!numPoints) { - return + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; } - - var gl = plot.gl - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] - - PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX - PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY - - buffer.bind() - shader.bind() - - shader.uniforms.viewTransform = MATRIX - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.color = this.color - - shader.attributes.position.pointer( - gl.FLOAT, - false, - 16, - 0) - - shader.attributes.pixelOffset.pointer( - gl.FLOAT, - false, - 16, - 8) - - gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length) + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; + } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } -})() - -proto.drawPick = function (offset) { return offset } -proto.pick = function (x, y) { - return null -} - -proto.update = function (options) { - options = options || {} - - var i, x, y - - var positions = options.positions || [] - var errors = options.errors || [] - - var lineWidth = 1 - if ('lineWidth' in options) { - lineWidth = +options.lineWidth + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; } - - var capSize = 5 - if ('capSize' in options) { - capSize = +options.capSize + function d3_geo_centroidLineStart() { + var x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroid.point = nextPoint; + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } } - - this.color = (options.color || [0, 0, 0, 1]).slice() - - var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - - var numPoints = this.numPoints = positions.length >> 1 - for (i = 0; i < numPoints; ++i) { - x = positions[i * 2] - y = positions[i * 2 + 1] - - bounds[0] = Math.min(x, bounds[0]) - bounds[1] = Math.min(y, bounds[1]) - bounds[2] = Math.max(x, bounds[2]) - bounds[3] = Math.max(y, bounds[3]) + function d3_geo_centroidLineEnd() { + d3_geo_centroid.point = d3_geo_centroidPoint; } - if (bounds[2] === bounds[0]) { - bounds[2] += 1 + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } } - if (bounds[3] === bounds[1]) { - bounds[3] += 1 + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; } - var sx = 1.0 / (bounds[2] - bounds[0]) - var sy = 1.0 / (bounds[3] - bounds[1]) - var tx = bounds[0] - var ty = bounds[1] - - var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4) - var ptr = 0 - for (i = 0; i < numPoints; ++i) { - x = positions[2 * i] - y = positions[2 * i + 1] - var ex0 = errors[4 * i] - var ex1 = errors[4 * i + 1] - var ey0 = errors[4 * i + 2] - var ey1 = errors[4 * i + 3] - - for (var j = 0; j < WEIGHTS.length; ++j) { - var w = WEIGHTS[j] - - var dx = w[0] - var dy = w[1] - - if (dx < 0) { - dx *= ex0 - } else if (dx > 0) { - dx *= ex1 - } - - if (dy < 0) { - dy *= ey0 - } else if (dy > 0) { - dy *= ey1 + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; } - - bufferData[ptr++] = sx * ((x - tx) + dx) - bufferData[ptr++] = sy * ((y - ty) + dy) - bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4] - bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5] + var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); + a.o = b; + subject.push(a); + clip.push(b); + a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); + b = new d3_geo_clipPolygonIntersection(p1, null, a, true); + a.o = b; + subject.push(a); + clip.push(b); + }); + clip.sort(compare); + d3_geo_clipPolygonLinkCircular(subject); + d3_geo_clipPolygonLinkCircular(clip); + if (!subject.length) return; + for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { + clip[i].e = entry = !entry; + } + var start = subject[0], points, point; + while (1) { + var current = start, isSubject = true; + while (current.v) if ((current = current.n) === start) return; + points = current.z; + listener.lineStart(); + do { + current.v = current.o.v = true; + if (current.e) { + if (isSubject) { + for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.n.x, 1, listener); + } + current = current.n; + } else { + if (isSubject) { + points = current.p.z; + for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); + } + current = current.p; + } + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); } } - this.buffer.update(bufferData) - pool.free(bufferData) -} - -proto.dispose = function () { - this.plot.removeObject(this) - this.shader.dispose() - this.buffer.dispose() -} - -function createError2D (plot, options) { - var shader = createShader(plot.gl, shaders.vertex, shaders.fragment) - var buffer = createBuffer(plot.gl) - - var errorbars = new GLError2D(plot, shader, buffer) - - errorbars.update(options) - - plot.addObject(errorbars) - - return errorbars -} - -},{"./lib/shaders":92,"gl-buffer":93,"gl-shader":94,"typedarray-pool":122}],92:[function(require,module,exports){ - - -module.exports = { - vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n", - fragment: "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" -} - -},{}],93:[function(require,module,exports){ -"use strict" - -var pool = require("typedarray-pool") -var ops = require("ndarray-ops") -var ndarray = require("ndarray") - -var SUPPORTED_TYPES = [ - "uint8", - "uint8_clamped", - "uint16", - "uint32", - "int8", - "int16", - "int32", - "float32" ] - -function GLBuffer(gl, type, handle, length, usage) { - this.gl = gl - this.type = type - this.handle = handle - this.length = length - this.usage = usage -} - -var proto = GLBuffer.prototype - -proto.bind = function() { - this.gl.bindBuffer(this.type, this.handle) -} - -proto.unbind = function() { - this.gl.bindBuffer(this.type, null) -} - -proto.dispose = function() { - this.gl.deleteBuffer(this.handle) -} - -function updateTypeArray(gl, type, len, usage, data, offset) { - var dataLen = data.length * data.BYTES_PER_ELEMENT - if(offset < 0) { - gl.bufferData(type, data, usage) - return dataLen + function d3_geo_clipPolygonLinkCircular(array) { + if (!(n = array.length)) return; + var n, i = 0, a = array[0], b; + while (++i < n) { + a.n = b = array[i]; + b.p = a; + a = b; + } + a.n = b = array[0]; + b.p = a; } - if(dataLen + offset > len) { - throw new Error("gl-buffer: If resizing buffer, must not specify offset") + function d3_geo_clipPolygonIntersection(point, points, other, entry) { + this.x = point; + this.z = points; + this.o = other; + this.e = entry; + this.v = false; + this.n = this.p = null; } - gl.bufferSubData(type, offset, data) - return len -} - -function makeScratchTypeArray(array, dtype) { - var res = pool.malloc(array.length, dtype) - var n = array.length - for(var i=0; i 0) { + if (!polygonStarted) listener.polygonStart(), polygonStarted = true; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); + } + return; + } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + } + return clip; + }; } - return res -} - -function isPacked(shape, stride) { - var n = 1 - for(var i=stride.length-1; i>=0; --i) { - if(stride[i] !== n) { - return false - } - n *= shape[i] + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; + } + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; } - return true -} - -proto.update = function(array, offset) { - if(typeof offset !== "number") { - offset = -1 + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } - this.bind() - if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray - var dtype = array.dtype - if(SUPPORTED_TYPES.indexOf(dtype) < 0) { - dtype = "float32" - } - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - var ext = gl.getExtension('OES_element_index_uint') - if(ext && dtype !== "uint16") { - dtype = "uint32" - } else { - dtype = "uint16" - } - } - if(dtype === array.dtype && isPacked(array.shape, array.stride)) { - if(array.offset === 0 && array.data.length === array.shape[0]) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); + if (abs(dλ - π) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= π) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; } + }; + } + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + } + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfπ; + listener.point(-π, φ); + listener.point(0, φ); + listener.point(π, φ); + listener.point(π, 0); + listener.point(π, -φ); + listener.point(0, -φ); + listener.point(-π, -φ); + listener.point(-π, 0); + listener.point(-π, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? π : -π; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); } else { - var tmp = pool.malloc(array.size, dtype) - var ndt = ndarray(tmp, array.shape) - ops.assign(ndt, array) - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) + listener.point(to[0], to[1]); + } + } + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); + polarAngle += antimeridian ? dλ + sdλ * τ : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; } - pool.free(tmp) } - } else if(Array.isArray(array)) { //Vanilla array - var t - if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { - t = makeScratchTypeArray(array, "uint16") - } else { - t = makeScratchTypeArray(array, "float32") + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + } + function d3_geo_clipCircle(radius) { + var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; } - if(offset < 0) { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) - } else { - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; } - pool.free(t) - } else if(typeof array === "object" && typeof array.length === "number") { //Typed array - this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) - } else if(typeof array === "number" || array === undefined) { //Number/default - if(offset >= 0) { - throw new Error("gl-buffer: Cannot specify offset when resizing buffer") + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } } - array = array | 0 - if(array <= 0) { - array = 1 + function code(λ, φ) { + var r = smallRadius ? radius : π - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; } - this.gl.bufferData(this.type, array|0, this.usage) - this.length = array - } else { //Error, case should not happen - throw new Error("gl-buffer: Invalid data type") - } -} - -function createBuffer(gl, data, type, usage) { - type = type || gl.ARRAY_BUFFER - usage = usage || gl.DYNAMIC_DRAW - if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { - throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") - } - if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { - throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") - } - var handle = gl.createBuffer() - var result = new GLBuffer(gl, type, handle, 0, usage) - result.update(data) - return result -} - -module.exports = createBuffer - -},{"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":122}],94:[function(require,module,exports){ -'use strict' - -var createUniformWrapper = require('./lib/create-uniforms') -var createAttributeWrapper = require('./lib/create-attributes') -var makeReflect = require('./lib/reflect') -var shaderCache = require('./lib/shader-cache') -var runtime = require('./lib/runtime-reflect') -var GLError = require("./lib/GLError") - -//Shader object -function Shader(gl) { - this.gl = gl - - //Default initialize these to null - this._vref = - this._fref = - this._relink = - this.vertShader = - this.fragShader = - this.program = - this.attributes = - this.uniforms = - this.types = null -} - -var proto = Shader.prototype - -proto.bind = function() { - if(!this.program) { - this._relink() - } - this.gl.useProgram(this.program) -} - -proto.dispose = function() { - if(this._fref) { - this._fref.dispose() - } - if(this._vref) { - this._vref.dispose() - } - this.attributes = - this.types = - this.vertShader = - this.fragShader = - this.program = - this._relink = - this._fref = - this._vref = null -} - -function compareAttributes(a, b) { - if(a.name < b.name) { - return -1 - } - return 1 -} - -//Update export hook for glslify-live -proto.update = function( - vertSource - , fragSource - , uniforms - , attributes) { - - //If only one object passed, assume glslify style output - if(!fragSource || arguments.length === 1) { - var obj = vertSource - vertSource = obj.vertex - fragSource = obj.fragment - uniforms = obj.uniforms - attributes = obj.attributes - } - - var wrapper = this - var gl = wrapper.gl - - //Compile vertex and fragment shaders - var pvref = wrapper._vref - wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource) - if(pvref) { - pvref.dispose() - } - wrapper.vertShader = wrapper._vref.shader - var pfref = this._fref - wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource) - if(pfref) { - pfref.dispose() } - wrapper.fragShader = wrapper._fref.shader - - //If uniforms/attributes is not specified, use RT reflection - if(!uniforms || !attributes) { - - //Create initial test program - var testProgram = gl.createProgram() - gl.attachShader(testProgram, wrapper.fragShader) - gl.attachShader(testProgram, wrapper.vertShader) - gl.linkProgram(testProgram) - if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) { - var errLog = gl.getProgramInfoLog(testProgram) - throw new GLError(errLog, 'Error linking program:' + errLog) - } - - //Load data from runtime - uniforms = uniforms || runtime.uniforms(gl, testProgram) - attributes = attributes || runtime.attributes(gl, testProgram) - - //Release test program - gl.deleteProgram(testProgram) + function d3_geom_clipLine(x0, y0, x1, y1) { + return function(line) { + var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; + r = x0 - ax; + if (!dx && r > 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; } - - //Sort attributes lexicographically - // overrides undefined WebGL behavior for attribute locations - attributes = attributes.slice() - attributes.sort(compareAttributes) - - //Convert attribute types, read out locations - var attributeUnpacked = [] - var attributeNames = [] - var attributeLocations = [] - for(var i=0; i= 0) { - var size = attr.type.charAt(attr.type.length-1)|0 - var locVector = new Array(size) - for(var j=0; j y && d3_cross2d(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; + } + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); } else { - attributeLocations.push(-1) + listener.point(to[0], to[1]); } } - attributeUnpacked.push({ - name: attr.name, - type: attr.type, - locations: locVector - }) - } else { - attributeUnpacked.push({ - name: attr.name, - type: attr.type, - locations: [ attributeLocations.length ] - }) - attributeNames.push(attr.name) - if(typeof attr.location === 'number') { - attributeLocations.push(attr.location|0) - } else { - attributeLocations.push(-1) + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; } - } - } - - //For all unspecified attributes, assign them lexicographically min attribute - var curLocation = 0 - for(var i=0; i= 0) { - curLocation += 1 + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); } - attributeLocations[i] = curLocation + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); + } + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } + } else { + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } + } + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; } - } - - //Rebuild program and recompute all uniform locations - var uniformLocations = new Array(uniforms.length) - function relink() { - wrapper.program = shaderCache.program( - gl - , wrapper._vref - , wrapper._fref - , attributeNames - , attributeLocations) - - for(var i=0; i= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); + } + }; + }; + albersUsa.precision = function(_) { + if (!arguments.length) return lower48.precision(); + lower48.precision(_); + alaska.precision(_); + hawaii.precision(_); + return albersUsa; + }; + albersUsa.scale = function(_) { + if (!arguments.length) return lower48.scale(); + lower48.scale(_); + alaska.scale(_ * .35); + hawaii.scale(_); + return albersUsa.translate(lower48.translate()); + }; + albersUsa.translate = function(_) { + if (!arguments.length) return lower48.translate(); + var k = lower48.scale(), x = +_[0], y = +_[1]; + lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; + alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + return albersUsa; + }; + return albersUsa.scale(1070); + }; + var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_pathAreaPolygon = 0; + d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; + }, + polygonEnd: function() { + d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; + d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); } - , enumerable: true - }) - - parts.pointer = function(type, normalized, stride, offset) { - type = type || gl.FLOAT - normalized = !!normalized - stride = stride || (dimension * dimension) - offset = offset || 0 - for(var i=0; i d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; + } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; } } - return x + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); } - , get: function() { - return parts + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; } - , enumerable: true - }) -} - -//Create shims for attributes -function createAttributeWrapper( - gl - , wrapper - , attributes - , locations) { - - var obj = {} - for(var i=0, n=attributes.length; i= 0) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addVectorAttribute( - gl - , wrapper - , locs[0] - , locations - , d - , obj - , name) - } else if(type.indexOf('mat') >= 0) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) - } - addMatrixAttribute( - gl - , wrapper - , locs - , locations - , d - , obj - , name) - } else { - throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type) - } - break + function pointLine(x, y) { + buffer.push("L", x, ",", y); } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + buffer.push("Z"); + } + return stream; } - return obj -} - -},{"./GLError":95}],97:[function(require,module,exports){ -'use strict' - -var coallesceUniforms = require('./reflect') -var GLError = require("./GLError") - -module.exports = createUniformWrapper - -//Binds a function and returns a value -function identity(x) { - var c = new Function('y', 'return function(){return y}') - return c(x) -} - -function makeVector(length, fill) { - var result = new Array(length) - for(var i=0; i 4) { - throw new GLError('', 'Invalid data type') - } - switch(type.charAt(0)) { - case 'b': - case 'i': - return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' - case 'v': - return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' - default: - throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type) - } - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) - } - return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' - } else { - throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) - } - break + var d3_geo_pathCentroid = { + point: d3_geo_pathCentroidPoint, + lineStart: d3_geo_pathCentroidLineStart, + lineEnd: d3_geo_pathCentroidLineEnd, + polygonStart: function() { + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; + }, + polygonEnd: function() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; + d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; } + }; + function d3_geo_pathCentroidPoint(x, y) { + d3_geo_centroidX0 += x; + d3_geo_centroidY0 += y; + ++d3_geo_centroidZ0; } - - function enumerateIndices(prefix, type) { - if(typeof type !== 'object') { - return [ [prefix, type] ] - } - var indices = [] - for(var id in type) { - var prop = type[id] - var tprefix = prefix - if(parseInt(id) + '' === id) { - tprefix += '[' + id + ']' - } else { - tprefix += '.' + id - } - if(typeof prop === 'object') { - indices.push.apply(indices, enumerateIndices(tprefix, prop)) - } else { - indices.push([tprefix, prop]) - } + function d3_geo_pathCentroidLineStart() { + var x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); } - return indices } - - function makeSetter(type) { - var code = [ 'return function updateProperty(obj){' ] - var indices = enumerateIndices('', type) - for(var i=0; i 4) { - throw new GLError('', 'Invalid data type') - } - if(type.charAt(0) === 'b') { - return makeVector(d, false) - } - return makeVector(d, 0) - } else if(type.indexOf('mat') === 0 && type.length === 4) { - var d = type.charCodeAt(type.length-1) - 48 - if(d < 2 || d > 4) { - throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) - } - return makeVector(d*d, 0) - } else { - throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) - } - break + function d3_geo_pathCentroidRingStart() { + var x00, y00, x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + z = y0 * x - x0 * y; + d3_geo_centroidX2 += z * (x0 + x); + d3_geo_centroidY2 += z * (y0 + y); + d3_geo_centroidZ2 += z * 3; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); } + d3_geo_pathCentroid.lineEnd = function() { + nextPoint(x00, y00); + }; } - - function storeProperty(obj, prop, type) { - if(typeof type === 'object') { - var child = processObject(type) - Object.defineProperty(obj, prop, { - get: identity(child), - set: makeSetter(type), - enumerable: true, - configurable: false - }) - } else { - if(locations[type]) { - Object.defineProperty(obj, prop, { - get: makeGetter(type), - set: makeSetter(type), - enumerable: true, - configurable: false - }) - } else { - obj[prop] = defaultValue(uniforms[type].type) - } + function d3_geo_pathContext(context) { + var pointRadius = 4.5; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointRadius = _; + return stream; + }, + result: d3_noop + }; + function point(x, y) { + context.moveTo(x + pointRadius, y); + context.arc(x, y, pointRadius, 0, τ); } - } - - function processObject(obj) { - var result - if(Array.isArray(obj)) { - result = new Array(obj.length) - for(var i=0; i 1) { - if(!(x[0] in o)) { - o[x[0]] = [] - } - o = o[x[0]] - for(var k=1; k 1) { - for(var j=0; j 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); } - } else { - result.push({ - name: info.name, - type: type - }) } } + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; + }; + return resample; } - return result -} - -function runtimeAttributes(gl, program) { - var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES) - var result = [] - for(var i=0; i 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); } - - return { - long: longForm.trim(), - short: shortForm.trim() + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); }; -} - - -},{"add-line-numbers":102,"gl-constants/lookup":106,"glsl-shader-name":107,"sprintf-js":116}],102:[function(require,module,exports){ -var padLeft = require('pad-left') - -module.exports = addLineNumbers -function addLineNumbers (string, start, delim) { - start = typeof start === 'number' ? start : 1 - delim = delim || ': ' - - var lines = string.split(/\r?\n/) - var totalDigits = String(lines.length + start - 1).length - return lines.map(function (line, i) { - var c = i + start - var digits = String(c).length - var prefix = padLeft(c, totalDigits - digits) - return prefix + delim + line - }).join('\n') -} - -},{"pad-left":103}],103:[function(require,module,exports){ -/*! - * pad-left - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ - -'use strict'; - -var repeat = require('repeat-string'); - -module.exports = function padLeft(str, num, ch) { - ch = typeof ch !== 'undefined' ? (ch + '') : ' '; - return repeat(ch, num) + str; -}; -},{"repeat-string":104}],104:[function(require,module,exports){ -/*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - -'use strict'; - -/** - * Results cache - */ - -var res = ''; -var cache; - -/** - * Expose `repeat` - */ - -module.exports = repeat; - -/** - * Repeat the given `string` the specified `number` - * of times. - * - * **Example:** - * - * ```js - * var repeat = require('repeat-string'); - * repeat('A', 5); - * //=> AAAAA - * ``` - * - * @param {String} `string` The string to repeat - * @param {Number} `number` The number of times to repeat the string - * @return {String} Repeated string - * @api public - */ - -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('repeat-string expects a string.'); } - - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; - - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); } - - while (max > res.length && num > 0) { - if (num & 1) { - res += str; + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; + } + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; } - - num >>= 1; - if (!num) break; - str += str; + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; } - - return res.substr(0, max); -} - - -},{}],105:[function(require,module,exports){ -module.exports = { - 0: 'NONE', - 1: 'ONE', - 2: 'LINE_LOOP', - 3: 'LINE_STRIP', - 4: 'TRIANGLES', - 5: 'TRIANGLE_STRIP', - 6: 'TRIANGLE_FAN', - 256: 'DEPTH_BUFFER_BIT', - 512: 'NEVER', - 513: 'LESS', - 514: 'EQUAL', - 515: 'LEQUAL', - 516: 'GREATER', - 517: 'NOTEQUAL', - 518: 'GEQUAL', - 519: 'ALWAYS', - 768: 'SRC_COLOR', - 769: 'ONE_MINUS_SRC_COLOR', - 770: 'SRC_ALPHA', - 771: 'ONE_MINUS_SRC_ALPHA', - 772: 'DST_ALPHA', - 773: 'ONE_MINUS_DST_ALPHA', - 774: 'DST_COLOR', - 775: 'ONE_MINUS_DST_COLOR', - 776: 'SRC_ALPHA_SATURATE', - 1024: 'STENCIL_BUFFER_BIT', - 1028: 'FRONT', - 1029: 'BACK', - 1032: 'FRONT_AND_BACK', - 1280: 'INVALID_ENUM', - 1281: 'INVALID_VALUE', - 1282: 'INVALID_OPERATION', - 1285: 'OUT_OF_MEMORY', - 1286: 'INVALID_FRAMEBUFFER_OPERATION', - 2304: 'CW', - 2305: 'CCW', - 2849: 'LINE_WIDTH', - 2884: 'CULL_FACE', - 2885: 'CULL_FACE_MODE', - 2886: 'FRONT_FACE', - 2928: 'DEPTH_RANGE', - 2929: 'DEPTH_TEST', - 2930: 'DEPTH_WRITEMASK', - 2931: 'DEPTH_CLEAR_VALUE', - 2932: 'DEPTH_FUNC', - 2960: 'STENCIL_TEST', - 2961: 'STENCIL_CLEAR_VALUE', - 2962: 'STENCIL_FUNC', - 2963: 'STENCIL_VALUE_MASK', - 2964: 'STENCIL_FAIL', - 2965: 'STENCIL_PASS_DEPTH_FAIL', - 2966: 'STENCIL_PASS_DEPTH_PASS', - 2967: 'STENCIL_REF', - 2968: 'STENCIL_WRITEMASK', - 2978: 'VIEWPORT', - 3024: 'DITHER', - 3042: 'BLEND', - 3088: 'SCISSOR_BOX', - 3089: 'SCISSOR_TEST', - 3106: 'COLOR_CLEAR_VALUE', - 3107: 'COLOR_WRITEMASK', - 3317: 'UNPACK_ALIGNMENT', - 3333: 'PACK_ALIGNMENT', - 3379: 'MAX_TEXTURE_SIZE', - 3386: 'MAX_VIEWPORT_DIMS', - 3408: 'SUBPIXEL_BITS', - 3410: 'RED_BITS', - 3411: 'GREEN_BITS', - 3412: 'BLUE_BITS', - 3413: 'ALPHA_BITS', - 3414: 'DEPTH_BITS', - 3415: 'STENCIL_BITS', - 3553: 'TEXTURE_2D', - 4352: 'DONT_CARE', - 4353: 'FASTEST', - 4354: 'NICEST', - 5120: 'BYTE', - 5121: 'UNSIGNED_BYTE', - 5122: 'SHORT', - 5123: 'UNSIGNED_SHORT', - 5124: 'INT', - 5125: 'UNSIGNED_INT', - 5126: 'FLOAT', - 5386: 'INVERT', - 5890: 'TEXTURE', - 6401: 'STENCIL_INDEX', - 6402: 'DEPTH_COMPONENT', - 6406: 'ALPHA', - 6407: 'RGB', - 6408: 'RGBA', - 6409: 'LUMINANCE', - 6410: 'LUMINANCE_ALPHA', - 7680: 'KEEP', - 7681: 'REPLACE', - 7682: 'INCR', - 7683: 'DECR', - 7936: 'VENDOR', - 7937: 'RENDERER', - 7938: 'VERSION', - 9728: 'NEAREST', - 9729: 'LINEAR', - 9984: 'NEAREST_MIPMAP_NEAREST', - 9985: 'LINEAR_MIPMAP_NEAREST', - 9986: 'NEAREST_MIPMAP_LINEAR', - 9987: 'LINEAR_MIPMAP_LINEAR', - 10240: 'TEXTURE_MAG_FILTER', - 10241: 'TEXTURE_MIN_FILTER', - 10242: 'TEXTURE_WRAP_S', - 10243: 'TEXTURE_WRAP_T', - 10497: 'REPEAT', - 10752: 'POLYGON_OFFSET_UNITS', - 16384: 'COLOR_BUFFER_BIT', - 32769: 'CONSTANT_COLOR', - 32770: 'ONE_MINUS_CONSTANT_COLOR', - 32771: 'CONSTANT_ALPHA', - 32772: 'ONE_MINUS_CONSTANT_ALPHA', - 32773: 'BLEND_COLOR', - 32774: 'FUNC_ADD', - 32777: 'BLEND_EQUATION_RGB', - 32778: 'FUNC_SUBTRACT', - 32779: 'FUNC_REVERSE_SUBTRACT', - 32819: 'UNSIGNED_SHORT_4_4_4_4', - 32820: 'UNSIGNED_SHORT_5_5_5_1', - 32823: 'POLYGON_OFFSET_FILL', - 32824: 'POLYGON_OFFSET_FACTOR', - 32854: 'RGBA4', - 32855: 'RGB5_A1', - 32873: 'TEXTURE_BINDING_2D', - 32926: 'SAMPLE_ALPHA_TO_COVERAGE', - 32928: 'SAMPLE_COVERAGE', - 32936: 'SAMPLE_BUFFERS', - 32937: 'SAMPLES', - 32938: 'SAMPLE_COVERAGE_VALUE', - 32939: 'SAMPLE_COVERAGE_INVERT', - 32968: 'BLEND_DST_RGB', - 32969: 'BLEND_SRC_RGB', - 32970: 'BLEND_DST_ALPHA', - 32971: 'BLEND_SRC_ALPHA', - 33071: 'CLAMP_TO_EDGE', - 33170: 'GENERATE_MIPMAP_HINT', - 33189: 'DEPTH_COMPONENT16', - 33306: 'DEPTH_STENCIL_ATTACHMENT', - 33635: 'UNSIGNED_SHORT_5_6_5', - 33648: 'MIRRORED_REPEAT', - 33901: 'ALIASED_POINT_SIZE_RANGE', - 33902: 'ALIASED_LINE_WIDTH_RANGE', - 33984: 'TEXTURE0', - 33985: 'TEXTURE1', - 33986: 'TEXTURE2', - 33987: 'TEXTURE3', - 33988: 'TEXTURE4', - 33989: 'TEXTURE5', - 33990: 'TEXTURE6', - 33991: 'TEXTURE7', - 33992: 'TEXTURE8', - 33993: 'TEXTURE9', - 33994: 'TEXTURE10', - 33995: 'TEXTURE11', - 33996: 'TEXTURE12', - 33997: 'TEXTURE13', - 33998: 'TEXTURE14', - 33999: 'TEXTURE15', - 34000: 'TEXTURE16', - 34001: 'TEXTURE17', - 34002: 'TEXTURE18', - 34003: 'TEXTURE19', - 34004: 'TEXTURE20', - 34005: 'TEXTURE21', - 34006: 'TEXTURE22', - 34007: 'TEXTURE23', - 34008: 'TEXTURE24', - 34009: 'TEXTURE25', - 34010: 'TEXTURE26', - 34011: 'TEXTURE27', - 34012: 'TEXTURE28', - 34013: 'TEXTURE29', - 34014: 'TEXTURE30', - 34015: 'TEXTURE31', - 34016: 'ACTIVE_TEXTURE', - 34024: 'MAX_RENDERBUFFER_SIZE', - 34041: 'DEPTH_STENCIL', - 34055: 'INCR_WRAP', - 34056: 'DECR_WRAP', - 34067: 'TEXTURE_CUBE_MAP', - 34068: 'TEXTURE_BINDING_CUBE_MAP', - 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', - 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', - 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', - 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', - 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', - 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', - 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', - 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', - 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', - 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', - 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', - 34342: 'CURRENT_VERTEX_ATTRIB', - 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', - 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', - 34467: 'COMPRESSED_TEXTURE_FORMATS', - 34660: 'BUFFER_SIZE', - 34661: 'BUFFER_USAGE', - 34816: 'STENCIL_BACK_FUNC', - 34817: 'STENCIL_BACK_FAIL', - 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', - 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', - 34877: 'BLEND_EQUATION_ALPHA', - 34921: 'MAX_VERTEX_ATTRIBS', - 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', - 34930: 'MAX_TEXTURE_IMAGE_UNITS', - 34962: 'ARRAY_BUFFER', - 34963: 'ELEMENT_ARRAY_BUFFER', - 34964: 'ARRAY_BUFFER_BINDING', - 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', - 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', - 35040: 'STREAM_DRAW', - 35044: 'STATIC_DRAW', - 35048: 'DYNAMIC_DRAW', - 35632: 'FRAGMENT_SHADER', - 35633: 'VERTEX_SHADER', - 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', - 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', - 35663: 'SHADER_TYPE', - 35664: 'FLOAT_VEC2', - 35665: 'FLOAT_VEC3', - 35666: 'FLOAT_VEC4', - 35667: 'INT_VEC2', - 35668: 'INT_VEC3', - 35669: 'INT_VEC4', - 35670: 'BOOL', - 35671: 'BOOL_VEC2', - 35672: 'BOOL_VEC3', - 35673: 'BOOL_VEC4', - 35674: 'FLOAT_MAT2', - 35675: 'FLOAT_MAT3', - 35676: 'FLOAT_MAT4', - 35678: 'SAMPLER_2D', - 35680: 'SAMPLER_CUBE', - 35712: 'DELETE_STATUS', - 35713: 'COMPILE_STATUS', - 35714: 'LINK_STATUS', - 35715: 'VALIDATE_STATUS', - 35716: 'INFO_LOG_LENGTH', - 35717: 'ATTACHED_SHADERS', - 35718: 'ACTIVE_UNIFORMS', - 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', - 35720: 'SHADER_SOURCE_LENGTH', - 35721: 'ACTIVE_ATTRIBUTES', - 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', - 35724: 'SHADING_LANGUAGE_VERSION', - 35725: 'CURRENT_PROGRAM', - 36003: 'STENCIL_BACK_REF', - 36004: 'STENCIL_BACK_VALUE_MASK', - 36005: 'STENCIL_BACK_WRITEMASK', - 36006: 'FRAMEBUFFER_BINDING', - 36007: 'RENDERBUFFER_BINDING', - 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', - 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', - 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', - 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', - 36053: 'FRAMEBUFFER_COMPLETE', - 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', - 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', - 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', - 36061: 'FRAMEBUFFER_UNSUPPORTED', - 36064: 'COLOR_ATTACHMENT0', - 36096: 'DEPTH_ATTACHMENT', - 36128: 'STENCIL_ATTACHMENT', - 36160: 'FRAMEBUFFER', - 36161: 'RENDERBUFFER', - 36162: 'RENDERBUFFER_WIDTH', - 36163: 'RENDERBUFFER_HEIGHT', - 36164: 'RENDERBUFFER_INTERNAL_FORMAT', - 36168: 'STENCIL_INDEX8', - 36176: 'RENDERBUFFER_RED_SIZE', - 36177: 'RENDERBUFFER_GREEN_SIZE', - 36178: 'RENDERBUFFER_BLUE_SIZE', - 36179: 'RENDERBUFFER_ALPHA_SIZE', - 36180: 'RENDERBUFFER_DEPTH_SIZE', - 36181: 'RENDERBUFFER_STENCIL_SIZE', - 36194: 'RGB565', - 36336: 'LOW_FLOAT', - 36337: 'MEDIUM_FLOAT', - 36338: 'HIGH_FLOAT', - 36339: 'LOW_INT', - 36340: 'MEDIUM_INT', - 36341: 'HIGH_INT', - 36346: 'SHADER_COMPILER', - 36347: 'MAX_VERTEX_UNIFORM_VECTORS', - 36348: 'MAX_VARYING_VECTORS', - 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', - 37440: 'UNPACK_FLIP_Y_WEBGL', - 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', - 37442: 'CONTEXT_LOST_WEBGL', - 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', - 37444: 'BROWSER_DEFAULT_WEBGL' -} - -},{}],106:[function(require,module,exports){ -var gl10 = require('./1.0/numbers') - -module.exports = function lookupConstant (number) { - return gl10[number] -} - -},{"./1.0/numbers":105}],107:[function(require,module,exports){ -var tokenize = require('glsl-tokenizer') -var atob = require('atob-lite') - -module.exports = getName - -function getName(src) { - var tokens = Array.isArray(src) - ? src - : tokenize(src) - - for (var i = 0; i < tokens.length; i++) { - var token = tokens[i] - if (token.type !== 'preprocessor') continue - var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) - if (!match) continue - if (!match[2]) continue - - var b64 = match[1] - var name = match[2] - - return (b64 ? atob(name) : name).trim() + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; } -} - -},{"atob-lite":108,"glsl-tokenizer":115}],108:[function(require,module,exports){ -module.exports = function _atob(str) { - return atob(str) -} - -},{}],109:[function(require,module,exports){ -module.exports = tokenize - -var literals100 = require('./lib/literals') - , operators = require('./lib/operators') - , builtins100 = require('./lib/builtins') - , literals300es = require('./lib/literals-300es') - , builtins300es = require('./lib/builtins-300es') - -var NORMAL = 999 // <-- never emitted - , TOKEN = 9999 // <-- never emitted - , BLOCK_COMMENT = 0 - , LINE_COMMENT = 1 - , PREPROCESSOR = 2 - , OPERATOR = 3 - , INTEGER = 4 - , FLOAT = 5 - , IDENT = 6 - , BUILTIN = 7 - , KEYWORD = 8 - , WHITESPACE = 9 - , EOF = 10 - , HEX = 11 - -var map = [ - 'block-comment' - , 'line-comment' - , 'preprocessor' - , 'operator' - , 'integer' - , 'float' - , 'ident' - , 'builtin' - , 'keyword' - , 'whitespace' - , 'eof' - , 'integer' -] - -function tokenize(opt) { - var i = 0 - , total = 0 - , mode = NORMAL - , c - , last - , content = [] - , tokens = [] - , token_idx = 0 - , token_offs = 0 - , line = 1 - , col = 0 - , start = 0 - , isnum = false - , isoperator = false - , input = '' - , len - - opt = opt || {} - var allBuiltins = builtins100 - var allLiterals = literals100 - if (opt.version === '300 es') { - allBuiltins = builtins300es - allLiterals = literals300es + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; + }; } - - return function(data) { - tokens = [] - if (data !== null) return write(data.replace ? data.replace(/\r\n/g, '\n') : data) - return end() + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; } - - function token(data) { - if (data.length) { - tokens.push({ - type: map[mode] - , data: data - , position: start - , line: line - , column: col - }) + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; } - - function write(chunk) { - i = 0 - input += chunk - len = input.length - - var last - - while(c = input[i], i < len) { - last = i - - switch(mode) { - case BLOCK_COMMENT: i = block_comment(); break - case LINE_COMMENT: i = line_comment(); break - case PREPROCESSOR: i = preprocessor(); break - case OPERATOR: i = operator(); break - case INTEGER: i = integer(); break - case HEX: i = hex(); break - case FLOAT: i = decimal(); break - case TOKEN: i = readtoken(); break - case WHITESPACE: i = whitespace(); break - case NORMAL: i = normal(); break + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] + }; + } + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); + }; + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * τ; + } else { + from = radius + direction * τ; + to = radius - .5 * step; } - - if(last !== i) { - switch(input[last]) { - case '\n': col = 0; ++line; break - default: ++col; break - } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); } - } - - total += i - input = input.slice(i) - return tokens + }; } - - function end(chunk) { - if(content.length) { - token(content.join('')) - } - - mode = EOF - token('(eof)') - return tokens + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); } - - function normal() { - content = content.length ? [] : content - - if(last === '/' && c === '*') { - start = total + i - 1 - mode = BLOCK_COMMENT - last = c - return i + 1 - } - - if(last === '/' && c === '/') { - start = total + i - 1 - mode = LINE_COMMENT - last = c - return i + 1 - } - - if(c === '#') { - mode = PREPROCESSOR - start = total + i - return i + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; } - - if(/\s/.test(c)) { - mode = WHITESPACE - start = total + i - return i + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); } - - isnum = /\d/.test(c) - isoperator = /[^\w_]/.test(c) - - start = total + i - mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN - return i + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; + }); + }; + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + }; + }; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); + }; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); + }; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); + }; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); + }; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; + }; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; + }; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; + }; + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; + }); + }; } - - function whitespace() { - if(/[^\s]/g.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } - content.push(c) - last = c - return i + 1 + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; + }); + }; } - - function preprocessor() { - if((c === '\r' || c === '\n') && last !== '\\') { - token(content.join('')) - mode = NORMAL - return i - } - content.push(c) - last = c - return i + 1 + function d3_source(d) { + return d.source; } - - function line_comment() { - return preprocessor() + function d3_target(d) { + return d.target; } - - function block_comment() { - if(c === '/' && last === '*') { - content.push(c) - token(content.join('')) - mode = NORMAL - return i + 1 + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; } - - content.push(c) - last = c - return i + 1 + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; } - - function operator() { - if(last === '.' && /\d/.test(c)) { - mode = FLOAT - return i - } - - if(last === '/' && c === '*') { - mode = BLOCK_COMMENT - return i - } - - if(last === '/' && c === '/') { - mode = LINE_COMMENT - return i - } - - if(c === '.' && content.length) { - while(determine_operator(content)); - - mode = FLOAT - return i - } - - if(c === ';' || c === ')' || c === '(') { - if(content.length) while(determine_operator(content)); - token(c) - mode = NORMAL - return i + 1 + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; } - - var is_composite_operator = content.length === 2 && c !== '=' - if(/[\w_\d\s]/.test(c) || is_composite_operator) { - while(determine_operator(content)); - mode = NORMAL - return i + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; } - - content.push(c) - last = c - return i + 1 + azimuthal.invert = function(x, y) { + var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; + }; + return azimuthal; } - - function determine_operator(buf) { - var j = 0 - , idx - , res - - do { - idx = operators.indexOf(buf.slice(0, buf.length + j).join('')) - res = operators[idx] - - if(idx === -1) { - if(j-- + buf.length > 0) continue - res = buf.slice(0, 1).join('') + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(ρ) { + return 2 * Math.asin(ρ / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(π / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + if (F > 0) { + if (φ < -halfπ + ε) φ = -halfπ + ε; + } else { + if (φ > halfπ - ε) φ = halfπ - ε; } - - token(res) - - start += res.length - content = content.slice(res.length) - return content.length - } while(1) - } - - function hex() { - if(/[^a-fA-F0-9]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i + var ρ = F / Math.pow(t(φ), n); + return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } - - content.push(c) - last = c - return i + 1 + forward.invert = function(x, y) { + var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); + return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; + }; + return forward; } - - function integer() { - if(c === '.') { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } - - if(/[eE]/.test(c)) { - content.push(c) - mode = FLOAT - last = c - return i + 1 - } - - if(c === 'x' && content.length === 1 && content[0] === '0') { - mode = HEX - content.push(c) - last = c - return i + 1 - } - - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var ρ = G - φ; + return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; } - - content.push(c) - last = c - return i + 1 + forward.invert = function(x, y) { + var ρ0_y = G - y; + return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; + }; + return forward; } - - function decimal() { - if(c === 'f') { - content.push(c) - last = c - i += 1 - } - - if(/[eE]/.test(c)) { - content.push(c) - last = c - return i + 1 - } - - if (c === '-' && /[eE]/.test(last)) { - content.push(c) - last = c - return i + 1 - } - - if(/[^\d]/.test(c)) { - token(content.join('')) - mode = NORMAL - return i - } - - content.push(c) - last = c - return i + 1 + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; } - - function readtoken() { - if(/[^\d\w_]/.test(c)) { - var contentstr = content.join('') - if(allLiterals.indexOf(contentstr) > -1) { - mode = KEYWORD - } else if(allBuiltins.indexOf(contentstr) > -1) { - mode = BUILTIN - } else { - mode = IDENT + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; + }; + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = π * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; } - token(content.join('')) - mode = NORMAL - return i - } - content.push(c) - last = c - return i + 1 + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(ρ) { + return 2 * Math.atan(ρ); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; } -} - -},{"./lib/builtins":111,"./lib/builtins-300es":110,"./lib/literals":113,"./lib/literals-300es":112,"./lib/operators":114}],110:[function(require,module,exports){ -// 300es builtins/reserved words that were previously valid in v100 -var v100 = require('./builtins') - -// The texture2D|Cube functions have been removed -// And the gl_ features are updated -v100 = v100.slice().filter(function (b) { - return !/^(gl\_|texture)/.test(b) -}) - -module.exports = v100.concat([ - // the updated gl_ constants - 'gl_VertexID' - , 'gl_InstanceID' - , 'gl_Position' - , 'gl_PointSize' - , 'gl_FragCoord' - , 'gl_FrontFacing' - , 'gl_FragDepth' - , 'gl_PointCoord' - , 'gl_MaxVertexAttribs' - , 'gl_MaxVertexUniformVectors' - , 'gl_MaxVertexOutputVectors' - , 'gl_MaxFragmentInputVectors' - , 'gl_MaxVertexTextureImageUnits' - , 'gl_MaxCombinedTextureImageUnits' - , 'gl_MaxTextureImageUnits' - , 'gl_MaxFragmentUniformVectors' - , 'gl_MaxDrawBuffers' - , 'gl_MinProgramTexelOffset' - , 'gl_MaxProgramTexelOffset' - , 'gl_DepthRangeParameters' - , 'gl_DepthRange' - - // other builtins - , 'trunc' - , 'round' - , 'roundEven' - , 'isnan' - , 'isinf' - , 'floatBitsToInt' - , 'floatBitsToUint' - , 'intBitsToFloat' - , 'uintBitsToFloat' - , 'packSnorm2x16' - , 'unpackSnorm2x16' - , 'packUnorm2x16' - , 'unpackUnorm2x16' - , 'packHalf2x16' - , 'unpackHalf2x16' - , 'outerProduct' - , 'transpose' - , 'determinant' - , 'inverse' - , 'texture' - , 'textureSize' - , 'textureProj' - , 'textureLod' - , 'textureOffset' - , 'texelFetch' - , 'texelFetchOffset' - , 'textureProjOffset' - , 'textureLodOffset' - , 'textureProjLod' - , 'textureProjLodOffset' - , 'textureGrad' - , 'textureGradOffset' - , 'textureProjGrad' - , 'textureProjGradOffset' -]) - -},{"./builtins":111}],111:[function(require,module,exports){ -module.exports = [ - // Keep this list sorted - 'abs' - , 'acos' - , 'all' - , 'any' - , 'asin' - , 'atan' - , 'ceil' - , 'clamp' - , 'cos' - , 'cross' - , 'dFdx' - , 'dFdy' - , 'degrees' - , 'distance' - , 'dot' - , 'equal' - , 'exp' - , 'exp2' - , 'faceforward' - , 'floor' - , 'fract' - , 'gl_BackColor' - , 'gl_BackLightModelProduct' - , 'gl_BackLightProduct' - , 'gl_BackMaterial' - , 'gl_BackSecondaryColor' - , 'gl_ClipPlane' - , 'gl_ClipVertex' - , 'gl_Color' - , 'gl_DepthRange' - , 'gl_DepthRangeParameters' - , 'gl_EyePlaneQ' - , 'gl_EyePlaneR' - , 'gl_EyePlaneS' - , 'gl_EyePlaneT' - , 'gl_Fog' - , 'gl_FogCoord' - , 'gl_FogFragCoord' - , 'gl_FogParameters' - , 'gl_FragColor' - , 'gl_FragCoord' - , 'gl_FragData' - , 'gl_FragDepth' - , 'gl_FragDepthEXT' - , 'gl_FrontColor' - , 'gl_FrontFacing' - , 'gl_FrontLightModelProduct' - , 'gl_FrontLightProduct' - , 'gl_FrontMaterial' - , 'gl_FrontSecondaryColor' - , 'gl_LightModel' - , 'gl_LightModelParameters' - , 'gl_LightModelProducts' - , 'gl_LightProducts' - , 'gl_LightSource' - , 'gl_LightSourceParameters' - , 'gl_MaterialParameters' - , 'gl_MaxClipPlanes' - , 'gl_MaxCombinedTextureImageUnits' - , 'gl_MaxDrawBuffers' - , 'gl_MaxFragmentUniformComponents' - , 'gl_MaxLights' - , 'gl_MaxTextureCoords' - , 'gl_MaxTextureImageUnits' - , 'gl_MaxTextureUnits' - , 'gl_MaxVaryingFloats' - , 'gl_MaxVertexAttribs' - , 'gl_MaxVertexTextureImageUnits' - , 'gl_MaxVertexUniformComponents' - , 'gl_ModelViewMatrix' - , 'gl_ModelViewMatrixInverse' - , 'gl_ModelViewMatrixInverseTranspose' - , 'gl_ModelViewMatrixTranspose' - , 'gl_ModelViewProjectionMatrix' - , 'gl_ModelViewProjectionMatrixInverse' - , 'gl_ModelViewProjectionMatrixInverseTranspose' - , 'gl_ModelViewProjectionMatrixTranspose' - , 'gl_MultiTexCoord0' - , 'gl_MultiTexCoord1' - , 'gl_MultiTexCoord2' - , 'gl_MultiTexCoord3' - , 'gl_MultiTexCoord4' - , 'gl_MultiTexCoord5' - , 'gl_MultiTexCoord6' - , 'gl_MultiTexCoord7' - , 'gl_Normal' - , 'gl_NormalMatrix' - , 'gl_NormalScale' - , 'gl_ObjectPlaneQ' - , 'gl_ObjectPlaneR' - , 'gl_ObjectPlaneS' - , 'gl_ObjectPlaneT' - , 'gl_Point' - , 'gl_PointCoord' - , 'gl_PointParameters' - , 'gl_PointSize' - , 'gl_Position' - , 'gl_ProjectionMatrix' - , 'gl_ProjectionMatrixInverse' - , 'gl_ProjectionMatrixInverseTranspose' - , 'gl_ProjectionMatrixTranspose' - , 'gl_SecondaryColor' - , 'gl_TexCoord' - , 'gl_TextureEnvColor' - , 'gl_TextureMatrix' - , 'gl_TextureMatrixInverse' - , 'gl_TextureMatrixInverseTranspose' - , 'gl_TextureMatrixTranspose' - , 'gl_Vertex' - , 'greaterThan' - , 'greaterThanEqual' - , 'inversesqrt' - , 'length' - , 'lessThan' - , 'lessThanEqual' - , 'log' - , 'log2' - , 'matrixCompMult' - , 'max' - , 'min' - , 'mix' - , 'mod' - , 'normalize' - , 'not' - , 'notEqual' - , 'pow' - , 'radians' - , 'reflect' - , 'refract' - , 'sign' - , 'sin' - , 'smoothstep' - , 'sqrt' - , 'step' - , 'tan' - , 'texture2D' - , 'texture2DLod' - , 'texture2DProj' - , 'texture2DProjLod' - , 'textureCube' - , 'textureCubeLod' - , 'texture2DLodEXT' - , 'texture2DProjLodEXT' - , 'textureCubeLodEXT' - , 'texture2DGradEXT' - , 'texture2DProjGradEXT' - , 'textureCubeGradEXT' -] - -},{}],112:[function(require,module,exports){ -var v100 = require('./literals') - -module.exports = v100.slice().concat([ - 'layout' - , 'centroid' - , 'smooth' - , 'case' - , 'mat2x2' - , 'mat2x3' - , 'mat2x4' - , 'mat3x2' - , 'mat3x3' - , 'mat3x4' - , 'mat4x2' - , 'mat4x3' - , 'mat4x4' - , 'uint' - , 'uvec2' - , 'uvec3' - , 'uvec4' - , 'samplerCubeShadow' - , 'sampler2DArray' - , 'sampler2DArrayShadow' - , 'isampler2D' - , 'isampler3D' - , 'isamplerCube' - , 'isampler2DArray' - , 'usampler2D' - , 'usampler3D' - , 'usamplerCube' - , 'usampler2DArray' - , 'coherent' - , 'restrict' - , 'readonly' - , 'writeonly' - , 'resource' - , 'atomic_uint' - , 'noperspective' - , 'patch' - , 'sample' - , 'subroutine' - , 'common' - , 'partition' - , 'active' - , 'filter' - , 'image1D' - , 'image2D' - , 'image3D' - , 'imageCube' - , 'iimage1D' - , 'iimage2D' - , 'iimage3D' - , 'iimageCube' - , 'uimage1D' - , 'uimage2D' - , 'uimage3D' - , 'uimageCube' - , 'image1DArray' - , 'image2DArray' - , 'iimage1DArray' - , 'iimage2DArray' - , 'uimage1DArray' - , 'uimage2DArray' - , 'image1DShadow' - , 'image2DShadow' - , 'image1DArrayShadow' - , 'image2DArrayShadow' - , 'imageBuffer' - , 'iimageBuffer' - , 'uimageBuffer' - , 'sampler1DArray' - , 'sampler1DArrayShadow' - , 'isampler1D' - , 'isampler1DArray' - , 'usampler1D' - , 'usampler1DArray' - , 'isampler2DRect' - , 'usampler2DRect' - , 'samplerBuffer' - , 'isamplerBuffer' - , 'usamplerBuffer' - , 'sampler2DMS' - , 'isampler2DMS' - , 'usampler2DMS' - , 'sampler2DMSArray' - , 'isampler2DMSArray' - , 'usampler2DMSArray' -]) - -},{"./literals":113}],113:[function(require,module,exports){ -module.exports = [ - // current - 'precision' - , 'highp' - , 'mediump' - , 'lowp' - , 'attribute' - , 'const' - , 'uniform' - , 'varying' - , 'break' - , 'continue' - , 'do' - , 'for' - , 'while' - , 'if' - , 'else' - , 'in' - , 'out' - , 'inout' - , 'float' - , 'int' - , 'void' - , 'bool' - , 'true' - , 'false' - , 'discard' - , 'return' - , 'mat2' - , 'mat3' - , 'mat4' - , 'vec2' - , 'vec3' - , 'vec4' - , 'ivec2' - , 'ivec3' - , 'ivec4' - , 'bvec2' - , 'bvec3' - , 'bvec4' - , 'sampler1D' - , 'sampler2D' - , 'sampler3D' - , 'samplerCube' - , 'sampler1DShadow' - , 'sampler2DShadow' - , 'struct' - - // future - , 'asm' - , 'class' - , 'union' - , 'enum' - , 'typedef' - , 'template' - , 'this' - , 'packed' - , 'goto' - , 'switch' - , 'default' - , 'inline' - , 'noinline' - , 'volatile' - , 'public' - , 'static' - , 'extern' - , 'external' - , 'interface' - , 'long' - , 'short' - , 'double' - , 'half' - , 'fixed' - , 'unsigned' - , 'input' - , 'output' - , 'hvec2' - , 'hvec3' - , 'hvec4' - , 'dvec2' - , 'dvec3' - , 'dvec4' - , 'fvec2' - , 'fvec3' - , 'fvec4' - , 'sampler2DRect' - , 'sampler3DRect' - , 'sampler2DRectShadow' - , 'sizeof' - , 'cast' - , 'namespace' - , 'using' -] - -},{}],114:[function(require,module,exports){ -module.exports = [ - '<<=' - , '>>=' - , '++' - , '--' - , '<<' - , '>>' - , '<=' - , '>=' - , '==' - , '!=' - , '&&' - , '||' - , '+=' - , '-=' - , '*=' - , '/=' - , '%=' - , '&=' - , '^^' - , '^=' - , '|=' - , '(' - , ')' - , '[' - , ']' - , '.' - , '!' - , '~' - , '*' - , '/' - , '%' - , '+' - , '-' - , '<' - , '>' - , '&' - , '^' - , '|' - , '?' - , ':' - , '=' - , ',' - , ';' - , '{' - , '}' -] - -},{}],115:[function(require,module,exports){ -var tokenize = require('./index') - -module.exports = tokenizeString - -function tokenizeString(str, opt) { - var generator = tokenize(opt) - var tokens = [] - - tokens = tokens.concat(generator(str)) - tokens = tokens.concat(generator(null)) - - return tokens -} - -},{"./index":109}],116:[function(require,module,exports){ -(function(window) { - var re = { - not_string: /[^s]/, - number: /[diefg]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[\+\-]/ + d3_geo_transverseMercator.invert = function(x, y) { + return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; + }; + (d3.geo.transverseMercator = function() { + var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; + projection.center = function(_) { + return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); + }; + projection.rotate = function(_) { + return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), + [ _[0], _[1], _[2] - 90 ]); + }; + return rotate([ 0, 0, 90 ]); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; + for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); + return polygon; } - - function sprintf() { - var key = arguments[0], cache = sprintf.cache - if (!(cache[key] && cache.hasOwnProperty(key))) { - cache[key] = sprintf.parse(key) + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [ 0, 1 ], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; + } + return hull.slice(0, hs); + } + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; + } + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; + }; + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; + }; + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; + }; + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); } - return sprintf.format.call(null, cache[key], arguments) + c = d; + } + if (closed) subject.push(subject[0]); + a = b; } - - sprintf.format = function(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]) - if (node_type === "string") { - output[output.length] = parse_tree[i] - } - else if (node_type === "array") { - match = parse_tree[i] // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor] - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) - } - arg = arg[match[2][k]] - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } - - if (get_type(arg) == "function") { - arg = arg() - } - - if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { - throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) - } - - if (re.number.test(match[8])) { - is_positive = arg >= 0 - } - - switch (match[8]) { - case "b": - arg = arg.toString(2) - break - case "c": - arg = String.fromCharCode(arg) - break - case "d": - case "i": - arg = parseInt(arg, 10) - break - case "j": - arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) - break - case "e": - arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() - break - case "f": - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) - break - case "g": - arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) - break - case "o": - arg = arg.toString(8) - break - case "s": - arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) - break - case "u": - arg = arg >>> 0 - break - case "x": - arg = arg.toString(16) - break - case "X": - arg = arg.toString(16).toUpperCase() - break - } - if (re.json.test(match[8])) { - output[output.length] = arg - } - else { - if (re.number.test(match[8]) && (!is_positive || match[3])) { - sign = is_positive ? "+" : "-" - arg = arg.toString().replace(re.sign, "") - } - else { - sign = "" - } - pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " - pad_length = match[6] - (sign + arg).length - pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" - output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) - } - } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + } + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; + } + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); + } + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; + } + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; + } + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); + } + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; } - return output.join("") + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; + } + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; + } + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; + } + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; + } + } + } + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } + } + } + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; + } + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; + } + } + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } + } + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; + } + } else { + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } + } + } + edge.a = va; + edge.b = vb; + return true; + } + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; + } + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; + } + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; } - - sprintf.cache = {} - - sprintf.parse = function(fmt) { - var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = match[0] + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; + } + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree[parse_tree.length] = "%" + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); + } + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list[field_list.length] = field_match[1] - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - } - } - else { - throw new SyntaxError("[sprintf] failed to parse named argument key") - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") - } - parse_tree[parse_tree.length] = match + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + } + parent = after.U; + } + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; + } + } else { + red = node.C; + node = next; + } + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; } - else { - throw new SyntaxError("[sprintf] unexpected placeholder") + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; } - _fmt = _fmt.substring(match[0].length) + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; + } } - return parse_tree + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; } - - var vsprintf = function(fmt, argv, _argv) { - _argv = (argv || []).slice(0) - _argv.splice(0, 0, fmt) - return sprintf.apply(null, _argv) + }; + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; } - - /** - * helpers - */ - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; + } + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; } - - function str_repeat(input, multiplier) { - return Array(multiplier + 1).join(input) + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; + } + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; + } + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); + } else { + break; + } } - - /** - * export to either browser or node.js - */ - if (typeof exports !== "undefined") { - exports.sprintf = sprintf - exports.vsprintf = vsprintf + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; + } + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; + } + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; + } + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); + }; + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } + } + }); + return triangles; + }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); + } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); + }; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; + } + return quadtree(points); + } + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } + } + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; + } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = xm; else x2 = xm; + if (below) y1 = ym; else y2 = ym; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); + }; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); + }; + root.find = function(point) { + return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); + } + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; + } + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); } - else { - window.sprintf = sprintf - window.vsprintf = vsprintf - - if (typeof define === "function" && define.amd) { - define(function() { - return { - sprintf: sprintf, - vsprintf: vsprintf - } - }) + } + function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { + var minDistance2 = Infinity, closestPoint; + (function find(node, x1, y1, x2, y2) { + if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; + if (point = node.point) { + var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; + if (distance2 < minDistance2) { + var distance = Math.sqrt(minDistance2 = distance2); + x0 = x - distance, y0 = y - distance; + x3 = x + distance, y3 = y + distance; + closestPoint = point; } - } -})(typeof window === "undefined" ? this : window); - -},{}],117:[function(require,module,exports){ -var hiddenStore = require('./hidden-store.js'); + } + var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; + for (var i = below << 1 | right, j = i + 4; i < j; ++i) { + if (node = children[i & 3]) switch (i & 3) { + case 0: + find(node, x1, y1, xm, ym); + break; -module.exports = createStore; + case 1: + find(node, xm, y1, x2, ym); + break; -function createStore() { - var key = {}; + case 2: + find(node, x1, ym, xm, y2); + break; - return function (obj) { - if ((typeof obj !== 'object' || obj === null) && - typeof obj !== 'function' - ) { - throw new Error('Weakmap-shim: Key must be object') + case 3: + find(node, xm, ym, x2, y2); + break; } - - var store = obj.valueOf(key); - return store && store.identity === key ? - store : hiddenStore(obj, key); + } + })(root, x0, y0, x3, y3); + return closestPoint; + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; -} - -},{"./hidden-store.js":118}],118:[function(require,module,exports){ -module.exports = hiddenStore; - -function hiddenStore(obj, key) { - var store = { identity: key }; - var valueOf = obj.valueOf; - - Object.defineProperty(obj, "valueOf", { - value: function (value) { - return value !== key ? - valueOf.apply(this, arguments) : store; - }, - writable: true - }); - - return store; -} - -},{}],119:[function(require,module,exports){ -// Original - @Gozola. -// https://gist.github.com/Gozala/1269991 -// This is a reimplemented version (with a few bug fixes). - -var createStore = require('./create-store.js'); - -module.exports = weakMap; - -function weakMap() { - var privates = createStore(); - - return { - 'get': function (key, fallback) { - var store = privates(key) - return store.hasOwnProperty('value') ? - store.value : fallback - }, - 'set': function (key, value) { - privates(key).value = value; - }, - 'has': function(key) { - return 'value' in privates(key); - }, - 'delete': function (key) { - return delete privates(key).value; - } - } -} - -},{"./create-store.js":117}],120:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],121:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],122:[function(require,module,exports){ -(function (global,Buffer){ -'use strict' - -var bits = require('bit-twiddle') -var dup = require('dup') - -//Legacy pool support -if(!global.__TYPEDARRAY_POOL) { - global.__TYPEDARRAY_POOL = { - UINT8 : dup([32, 0]) - , UINT16 : dup([32, 0]) - , UINT32 : dup([32, 0]) - , INT8 : dup([32, 0]) - , INT16 : dup([32, 0]) - , INT32 : dup([32, 0]) - , FLOAT : dup([32, 0]) - , DOUBLE : dup([32, 0]) - , DATA : dup([32, 0]) - , UINT8C : dup([32, 0]) - , BUFFER : dup([32, 0]) } -} - -var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined' -var POOL = global.__TYPEDARRAY_POOL - -//Upgrade pool -if(!POOL.UINT8C) { - POOL.UINT8C = dup([32, 0]) -} -if(!POOL.BUFFER) { - POOL.BUFFER = dup([32, 0]) -} - -//New technique: Only allocate from ArrayBufferView and Buffer -var DATA = POOL.DATA - , BUFFER = POOL.BUFFER - -exports.free = function free(array) { - if(Buffer.isBuffer(array)) { - BUFFER[bits.log2(array.length)].push(array) - } else { - if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') { - array = array.buffer + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } } - if(!array) { - return + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } } - var n = array.length || array.byteLength - var log_n = bits.log2(n)|0 - DATA[log_n].push(array) + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; } -} - -function freeArrayBuffer(buffer) { - if(!buffer) { - return + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + a = +a, b = +b; + return function(t) { + return a * (1 - t) + b * t; + }; } - var n = buffer.length || buffer.byteLength - var log_n = bits.log2(n) - DATA[log_n].push(buffer) -} - -function freeTypedArray(array) { - freeArrayBuffer(array.buffer) -} - -exports.freeUint8 = -exports.freeUint16 = -exports.freeUint32 = -exports.freeInt8 = -exports.freeInt16 = -exports.freeInt32 = -exports.freeFloat32 = -exports.freeFloat = -exports.freeFloat64 = -exports.freeDouble = -exports.freeUint8Clamped = -exports.freeDataView = freeTypedArray - -exports.freeArrayBuffer = freeArrayBuffer - -exports.freeBuffer = function freeBuffer(array) { - BUFFER[bits.log2(array.length)].push(array) -} - -exports.malloc = function malloc(n, dtype) { - if(dtype === undefined || dtype === 'arraybuffer') { - return mallocArrayBuffer(n) - } else { - switch(dtype) { - case 'uint8': - return mallocUint8(n) - case 'uint16': - return mallocUint16(n) - case 'uint32': - return mallocUint32(n) - case 'int8': - return mallocInt8(n) - case 'int16': - return mallocInt16(n) - case 'int32': - return mallocInt32(n) - case 'float': - case 'float32': - return mallocFloat(n) - case 'double': - case 'float64': - return mallocDouble(n) - case 'uint8_clamped': - return mallocUint8Clamped(n) - case 'buffer': - return mallocBuffer(n) - case 'data': - case 'dataview': - return mallocDataView(n) - - default: - return null + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; else s[++i] = bm; + } else { + s[++i] = null; + q.push({ + i: i, + x: d3_interpolateNumber(am, bm) + }); + } + bi = d3_interpolate_numberB.lastIndex; } + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; else s[++i] = bs; + } + return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { + return b(t) + ""; + }) : function() { + return b; + } : (b = q.length, function(t) { + for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }); } - return null -} - -function mallocArrayBuffer(n) { - var n = bits.nextPow2(n) - var log_n = bits.log2(n) - var d = DATA[log_n] - if(d.length > 0) { - return d.pop() - } - return new ArrayBuffer(n) -} -exports.mallocArrayBuffer = mallocArrayBuffer - -function mallocUint8(n) { - return new Uint8Array(mallocArrayBuffer(n), 0, n) -} -exports.mallocUint8 = mallocUint8 - -function mallocUint16(n) { - return new Uint16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocUint16 = mallocUint16 - -function mallocUint32(n) { - return new Uint32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocUint32 = mallocUint32 - -function mallocInt8(n) { - return new Int8Array(mallocArrayBuffer(n), 0, n) -} -exports.mallocInt8 = mallocInt8 - -function mallocInt16(n) { - return new Int16Array(mallocArrayBuffer(2*n), 0, n) -} -exports.mallocInt16 = mallocInt16 - -function mallocInt32(n) { - return new Int32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocInt32 = mallocInt32 - -function mallocFloat(n) { - return new Float32Array(mallocArrayBuffer(4*n), 0, n) -} -exports.mallocFloat32 = exports.mallocFloat = mallocFloat - -function mallocDouble(n) { - return new Float64Array(mallocArrayBuffer(8*n), 0, n) -} -exports.mallocFloat64 = exports.mallocDouble = mallocDouble - -function mallocUint8Clamped(n) { - if(hasUint8C) { - return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n) - } else { - return mallocUint8(n) + var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; } -} -exports.mallocUint8Clamped = mallocUint8Clamped - -function mallocDataView(n) { - return new DataView(mallocArrayBuffer(n), 0, n) -} -exports.mallocDataView = mallocDataView - -function mallocBuffer(n) { - n = bits.nextPow2(n) - var log_n = bits.log2(n) - var cache = BUFFER[log_n] - if(cache.length > 0) { - return cache.pop() + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; } - return new Buffer(n) -} -exports.mallocBuffer = mallocBuffer - -exports.clearCache = function clearCache() { - for(var i=0; i<32; ++i) { - POOL.UINT8[i].length = 0 - POOL.UINT16[i].length = 0 - POOL.UINT32[i].length = 0 - POOL.INT8[i].length = 0 - POOL.INT16[i].length = 0 - POOL.INT32[i].length = 0 - POOL.FLOAT[i].length = 0 - POOL.DOUBLE[i].length = 0 - POOL.UINT8C[i].length = 0 - DATA[i].length = 0 - BUFFER[i].length = 0 + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; } -} -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"bit-twiddle":120,"buffer":65,"dup":121}],123:[function(require,module,exports){ -'use strict' - -module.exports = createErrorBars - -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders/index') - -var IDENTITY = [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] - -function ErrorBars(gl, buffer, vao, shader) { - this.gl = gl - this.shader = shader - this.buffer = buffer - this.vao = vao - this.pixelRatio = 1 - this.bounds = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]] - this.clipBounds = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]] - this.lineWidth = [1,1,1] - this.capSize = [10,10,10] - this.lineCount = [0,0,0] - this.lineOffset = [0,0,0] - this.opacity = 1 -} - -var proto = ErrorBars.prototype - -proto.isOpaque = function() { - return this.opacity >= 1 -} - -proto.isTransparent = function() { - return this.opacity < 1 -} - -proto.drawTransparent = proto.draw = function(cameraParams) { - var gl = this.gl - var uniforms = this.shader.uniforms - - this.shader.bind() - var view = uniforms.view = cameraParams.view || IDENTITY - var projection = uniforms.projection = cameraParams.projection || IDENTITY - uniforms.model = cameraParams.model || IDENTITY - uniforms.clipBounds = this.clipBounds - uniforms.opacity = this.opacity - - - var cx = view[12] - var cy = view[13] - var cz = view[14] - var cw = view[15] - var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight - - - this.vao.bind() - for(var i=0; i<3; ++i) { - gl.lineWidth(this.lineWidth[i]) - uniforms.capSize = this.capSize[i] * pixelScaleF - gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i]) + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; } - this.vao.unbind() -} - -function updateBounds(bounds, point) { - for(var i=0; i<3; ++i) { - bounds[0][i] = Math.min(bounds[0][i], point[i]) - bounds[1][i] = Math.max(bounds[1][i], point[i]) + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; } -} - -var FACE_TABLE = (function(){ - var table = new Array(3) - for(var d=0; d<3; ++d) { - var row = [] - for(var j=1; j<=2; ++j) { - for(var s=-1; s<=1; s+=2) { - var u = (j+d) % 3 - var y = [0,0,0] - y[u] = s - row.push(y) - } - } - table[d] = row + function d3_ease_quad(t) { + return t * t; } - return table -})() - - -function emitFace(verts, x, c, d) { - var offsets = FACE_TABLE[d] - for(var i=0; i= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); } - if('capSize' in options) { - this.capSize = options.capSize - if(!Array.isArray(this.capSize)) { - this.capSize = [this.capSize, this.capSize, this.capSize] - } + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; } - if('opacity' in options) { - this.opacity = options.opacity + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); } - - var color = options.color || [[0,0,0],[0,0,0],[0,0,0]] - var position = options.position - var error = options.error - if(!Array.isArray(color[0])) { - color = [color,color,color] + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); } - - if(position && error) { - - var verts = [] - var n = position.length - var vertexCount = 0 - this.bounds = [[ Infinity, Infinity, Infinity], - [-Infinity,-Infinity,-Infinity]] - this.lineCount = [0,0,0] - - //Build geometry for lines - for(var j=0; j<3; ++j) { - this.lineOffset[j] = vertexCount - -i_loop: - for(var i=0; i 0) { - var x = p.slice() - x[j] += e[1][j] - verts.push(p[0], p[1], p[2], - c[0], c[1], c[2], c[3], - 0, 0, 0, - x[0], x[1], x[2], - c[0], c[1], c[2], c[3], - 0, 0, 0) - updateBounds(this.bounds, x) - vertexCount += 2 + emitFace(verts, x, c, j) - } + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); + } + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; + } + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; + } + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; + } + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; + } + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; + } + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; + }; + } + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); + }; + } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); } - this.lineCount[j] = vertexCount - this.lineOffset[j] + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); + }; + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; } - this.buffer.update(verts) + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; } -} - -proto.dispose = function() { - this.shader.dispose() - this.buffer.dispose() - this.vao.dispose() -} - -function createErrorBars(options) { - var gl = options.gl - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 0, - stride: 40 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 4, - offset: 12, - stride: 40 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 28, - stride: 40 - } - ]) - - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.color.location = 1 - shader.attributes.offset.location = 2 - - var result = new ErrorBars(gl, buffer, vao, shader) - result.update(options) - return result -} - -},{"./shaders/index":158,"gl-buffer":124,"gl-vao":157}],124:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":127}],125:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],126:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],127:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":125,"buffer":65,"dup":122}],128:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":129,"./lib/create-attributes":130,"./lib/create-uniforms":131,"./lib/reflect":132,"./lib/runtime-reflect":133,"./lib/shader-cache":134,"dup":94}],129:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],130:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":129,"dup":96}],131:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":129,"./reflect":132,"dup":97}],132:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],133:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],134:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":129,"dup":100,"gl-format-compiler-error":135,"weakmap-shim":153}],135:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":136,"dup":101,"gl-constants/lookup":140,"glsl-shader-name":141,"sprintf-js":150}],136:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":137}],137:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":138}],138:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],139:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],140:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":139,"dup":106}],141:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":142,"dup":107,"glsl-tokenizer":149}],142:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],143:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":145,"./lib/builtins-300es":144,"./lib/literals":147,"./lib/literals-300es":146,"./lib/operators":148,"dup":109}],144:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":145,"dup":110}],145:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],146:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":147,"dup":112}],147:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],148:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],149:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":143,"dup":115}],150:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],151:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":152,"dup":117}],152:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],153:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":151,"dup":119}],154:[function(require,module,exports){ -"use strict" - -function doBind(gl, elements, attributes) { - if(elements) { - elements.bind() - } else { - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null) + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; + }; + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; } - var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0 - if(attributes) { - if(attributes.length > nattribs) { - throw new Error("gl-vao: Too many vertex attributes") + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; } - for(var i=0; i 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); } - } else { - gl.bindBuffer(gl.ARRAY_BUFFER, null) - for(var i=0; i 0) { + alpha = x; + } else { + timer.c = null, timer.t = NaN, timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + } + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + timer = d3_timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, l = candidates.length, x; + while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); + }; + force.resume = function() { + return force.alpha(.1); + }; + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); } - - gl.depthMask(false) - gl.disable(gl.DEPTH_TEST) - } - - var shader = this.lineShader - shader.bind() - - var uniforms = shader.uniforms - uniforms.matrix = MATRIX - uniforms.color = color - uniforms.width = width * pixelRatio - uniforms.screenShape = SCREEN_SHAPE - uniforms.dashPattern = this.dashPattern.bind() - uniforms.dashLength = this.dashLength * pixelRatio - - var attributes = shader.attributes - attributes.a.pointer(gl.FLOAT, false, 16, 0) - attributes.d.pointer(gl.FLOAT, false, 16, 8) - - gl.drawArrays(gl.TRIANGLES, 0, count) - - //Draw mitres - if(width > 2 && !this.usingDashes) { - var mshader = this.mitreShader - mshader.bind() - - var muniforms = mshader.uniforms - muniforms.matrix = MATRIX - muniforms.color = color - muniforms.screenShape = SCREEN_SHAPE - muniforms.radius = width * pixelRatio - - mshader.attributes.p.pointer(gl.FLOAT, false, 48, 0) - gl.drawArrays(gl.POINTS, 0, (count/3)|0) + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; } -} -})() - -proto.drawPick = (function() { - var MATRIX = [1, 0, 0, - 0, 1, 0, - 0, 0, 1] - var SCREEN_SHAPE = [0,0] - var PICK_OFFSET = [0,0,0,0] - return function(pickOffset) { - var plot = this.plot - var shader = this.pickShader - var buffer = this.lineBuffer - var pickBuffer= this.pickBuffer - var width = this.width - var numPoints = this.numPoints - var bounds = this.bounds - var count = this.vertCount - - var gl = plot.gl - var viewBox = plot.viewBox - var dataBox = plot.dataBox - var pixelRatio = plot.pickPixelRatio - - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] - - this.pickOffset = pickOffset - - if(!count) { - return pickOffset + numPoints - } - - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 - - SCREEN_SHAPE[0] = screenX - SCREEN_SHAPE[1] = screenY - - PICK_OFFSET[0] = pickOffset & 0xff - PICK_OFFSET[1] = (pickOffset>>>8) & 0xff - PICK_OFFSET[2] = (pickOffset>>>16) & 0xff - PICK_OFFSET[3] = pickOffset>>>24 - - shader.bind() - - var uniforms = shader.uniforms - uniforms.matrix = MATRIX - uniforms.width = width * pixelRatio - uniforms.pickOffset = PICK_OFFSET - uniforms.screenShape = SCREEN_SHAPE - - var attributes = shader.attributes - - buffer.bind() - attributes.a.pointer(gl.FLOAT, false, 16, 0) - attributes.d.pointer(gl.FLOAT, false, 16, 8) - - pickBuffer.bind() - attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0) - attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4) - - gl.drawArrays(gl.TRIANGLES, 0, count) - - return pickOffset + numPoints + function d3_layout_forceDragend(d) { + d.fixed &= ~6; } -})() - -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.numPoints - if(value < pickOffset || value >= pickOffset + pointCount) { - return null + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; } - var pointId = value - pickOffset - var points = this.data - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; } -} - -function deepCopy(arr) { - return arr.map(function(x) { - return x.slice() - }) -} - -proto.update = function(options) { - options = options || {} - - var gl = this.plot.gl - - var connectGaps = !!options.connectGaps - - this.color = (options.color || [0,0,1,1]).slice() - this.width = +(options.width || 1) - - this.fill = (options.fill || [false,false,false,false]).slice() - this.fillColor = deepCopy(options.fillColor || [[0,0,0,1], - [0,0,0,1], - [0,0,0,1], - [0,0,0,1]]) - - var dashes = options.dashes || [1] - var dashLength = 0 - for(var i=0; i= 0) { + stack.push(child = childs[n]); + child.parent = node; + child.depth = node.depth + 1; + } + if (value) node.value = 0; + node.children = childs; + } else { + if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; + delete node.children; + } + } + d3_layout_hierarchyVisitAfter(root, function(node) { + var childs, parent; + if (sort && (childs = node.children)) childs.sort(sort); + if (value && (parent = node.parent)) parent.value += node.value; + }); + return nodes; } - fillColor ^= 255 + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + if (value) { + d3_layout_hierarchyVisitBefore(root, function(node) { + if (node.children) node.value = 0; + }); + d3_layout_hierarchyVisitAfter(root, function(node) { + var parent; + if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; + if (parent = node.parent) parent.value += node.value; + }); + } + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; } - this.dashPattern.dispose() - this.usingDashes = dashes.length > 1 - - this.dashPattern = createTexture(gl, - ndarray(dashData, [dashLength, 1, 4], [1, 0, 0])) - this.dashPattern.minFilter = gl.NEAREST - this.dashPattern.magFilter = gl.NEAREST - this.dashLength = dashLength - pool.free(dashData) - - var data = options.positions - this.data = data - - var bounds = this.bounds - bounds[0] = bounds[1] = Infinity - bounds[2] = bounds[3] = -Infinity - - var numPoints = this.numPoints = data.length>>>1 - if(numPoints === 0) { - return + function d3_layout_hierarchyVisitBefore(node, callback) { + var nodes = [ node ]; + while ((node = nodes.pop()) != null) { + callback(node); + if ((children = node.children) && (n = children.length)) { + var n, children; + while (--n >= 0) nodes.push(children[n]); + } + } } - - for(var i=0; i 1) { - var id = --ptr - var ax = data[2*ptr] - var ay = data[2*ptr+1] - - var next = id-1 - var bx = data[2*next] - var by = data[2*next+1] - - if (isNaN(ax) || isNaN(ay) || isNaN(bx) || isNaN(by)) { - continue + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; + } + } + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); + } + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; + function pie(data) { + var n = data.length, values = data.map(function(d, i) { + return +value.call(pie, d, i); + }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + index.forEach(function(i) { + arcs[i] = { + data: data[i], + value: v = values[i], + startAngle: a, + endAngle: a += v * k + pa, + padAngle: p + }; + }); + return arcs; + } + pie.value = function(_) { + if (!arguments.length) return value; + value = _; + return pie; + }; + pie.sort = function(_) { + if (!arguments.length) return sort; + sort = _; + return pie; + }; + pie.startAngle = function(_) { + if (!arguments.length) return startAngle; + startAngle = _; + return pie; + }; + pie.endAngle = function(_) { + if (!arguments.length) return endAngle; + endAngle = _; + return pie; + }; + pie.padAngle = function(_) { + if (!arguments.length) return padAngle; + padAngle = _; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + if (!(n = data.length)) return data; + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var m = series[0].length, n, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } + } + return data; } - - count += 1 - - ax = (ax - bounds[0]) / (bounds[2] - bounds[0]) - ay = (ay - bounds[1]) / (bounds[3] - bounds[1]) - - bx = (bx - bounds[0]) / (bounds[2] - bounds[0]) - by = (by - bounds[1]) / (bounds[3] - bounds[1]) - - var dx = bx - ax - var dy = by - ay - - var akey0 = id | (1<<24) - var akey1 = (id-1) - var bkey0 = id - var bkey1 = (id-1) | (1<<24) - - lineData[--lineDataPtr] = -dy - lineData[--lineDataPtr] = -dx - lineData[--lineDataPtr] = ay - lineData[--lineDataPtr] = ax - pickData[--pickDataPtr] = akey0 - pickData[--pickDataPtr] = akey1 - - lineData[--lineDataPtr] = dy - lineData[--lineDataPtr] = dx - lineData[--lineDataPtr] = by - lineData[--lineDataPtr] = bx - pickData[--pickDataPtr] = bkey0 - pickData[--pickDataPtr] = bkey1 - - lineData[--lineDataPtr] = -dy - lineData[--lineDataPtr] = -dx - lineData[--lineDataPtr] = by - lineData[--lineDataPtr] = bx - pickData[--pickDataPtr] = bkey0 - pickData[--pickDataPtr] = bkey1 - - lineData[--lineDataPtr] = dy - lineData[--lineDataPtr] = dx - lineData[--lineDataPtr] = by - lineData[--lineDataPtr] = bx - pickData[--pickDataPtr] = bkey0 - pickData[--pickDataPtr] = bkey1 - - lineData[--lineDataPtr] = -dy - lineData[--lineDataPtr] = -dx - lineData[--lineDataPtr] = ay - lineData[--lineDataPtr] = ax - pickData[--pickDataPtr] = akey0 - pickData[--pickDataPtr] = akey1 - - lineData[--lineDataPtr] = dy - lineData[--lineDataPtr] = dx - lineData[--lineDataPtr] = ay - lineData[--lineDataPtr] = ax - pickData[--pickDataPtr] = akey0 - pickData[--pickDataPtr] = akey1 + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; } - - this.vertCount = 6 * count - this.lineBuffer.update(lineData.subarray(lineDataPtr)) - this.pickBuffer.update(pickData.subarray(pickDataPtr)) - - pool.free(lineData) - pool.free(pickData) -} - -proto.dispose = function() { - this.plot.removeObject(this) - this.lineBuffer.dispose() - this.pickBuffer.dispose() - this.lineShader.dispose() - this.mitreShader.dispose() - this.fillShader.dispose() - this.pickShader.dispose() - this.dashPattern.dispose() -} - -function createLinePlot(plot, options) { - var gl = plot.gl - var lineBuffer = createBuffer(gl) - var pickBuffer = createBuffer(gl) - var dashPattern = createTexture(gl, [1,1]) - var lineShader = createShader(gl, SHADERS.lineVertex, SHADERS.lineFragment) - var mitreShader = createShader(gl, SHADERS.mitreVertex, SHADERS.mitreFragment) - var fillShader = createShader(gl, SHADERS.fillVertex, SHADERS.fillFragment) - var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) - var linePlot = new GLLine2D( - plot, - dashPattern, - lineBuffer, - pickBuffer, - lineShader, - mitreShader, - fillShader, - pickShader) - plot.addObject(linePlot) - linePlot.update(options) - return linePlot -} - -},{"./lib/shaders":159,"gl-buffer":161,"gl-shader":162,"gl-texture2d":188,"ndarray":1031,"typedarray-pool":191}],161:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":191}],162:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":163,"./lib/create-attributes":164,"./lib/create-uniforms":165,"./lib/reflect":166,"./lib/runtime-reflect":167,"./lib/shader-cache":168,"dup":94}],163:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],164:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":163,"dup":96}],165:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":163,"./reflect":166,"dup":97}],166:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],167:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],168:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":163,"dup":100,"gl-format-compiler-error":169,"weakmap-shim":187}],169:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":170,"dup":101,"gl-constants/lookup":174,"glsl-shader-name":175,"sprintf-js":184}],170:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":171}],171:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":172}],172:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],173:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],174:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":173,"dup":106}],175:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":176,"dup":107,"glsl-tokenizer":183}],176:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],177:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":179,"./lib/builtins-300es":178,"./lib/literals":181,"./lib/literals-300es":180,"./lib/operators":182,"dup":109}],178:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":179,"dup":110}],179:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],180:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":181,"dup":112}],181:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],182:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],183:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":177,"dup":115}],184:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],185:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":186,"dup":117}],186:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],187:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":185,"dup":119}],188:[function(require,module,exports){ -'use strict' - -var ndarray = require('ndarray') -var ops = require('ndarray-ops') -var pool = require('typedarray-pool') - -module.exports = createTexture2D - -var linearTypes = null -var filterTypes = null -var wrapTypes = null - -function lazyInitLinearTypes(gl) { - linearTypes = [ - gl.LINEAR, - gl.NEAREST_MIPMAP_LINEAR, - gl.LINEAR_MIPMAP_NEAREST, - gl.LINEAR_MIPMAP_NEAREST - ] - filterTypes = [ - gl.NEAREST, - gl.LINEAR, - gl.NEAREST_MIPMAP_NEAREST, - gl.NEAREST_MIPMAP_LINEAR, - gl.LINEAR_MIPMAP_NEAREST, - gl.LINEAR_MIPMAP_LINEAR - ] - wrapTypes = [ - gl.REPEAT, - gl.CLAMP_TO_EDGE, - gl.MIRRORED_REPEAT - ] -} - -var convertFloatToUint8 = function(out, inp) { - ops.muls(out, inp, 255.0) -} - -function reshapeTexture(tex, w, h) { - var gl = tex.gl - var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(w < 0 || w > maxSize || h < 0 || h > maxSize) { - throw new Error('gl-texture2d: Invalid texture size') + function d3_layout_stackY(d) { + return d.y; } - tex._shape = [w, h] - tex.bind() - gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) - tex._mipLevels = [0] - return tex -} - -function Texture2D(gl, handle, width, height, format, type) { - this.gl = gl - this.handle = handle - this.format = format - this.type = type - this._shape = [width, height] - this._mipLevels = [0] - this._magFilter = gl.NEAREST - this._minFilter = gl.NEAREST - this._wrapS = gl.CLAMP_TO_EDGE - this._wrapT = gl.CLAMP_TO_EDGE - this._anisoSamples = 1 - - var parent = this - var wrapVector = [this._wrapS, this._wrapT] - Object.defineProperties(wrapVector, [ - { - get: function() { - return parent._wrapS - }, - set: function(v) { - return parent.wrapS = v + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } } + return bottoms.reverse().concat(tops); }, - { - get: function() { - return parent._wrapT - }, - set: function(v) { - return parent.wrapT = v + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); } - } - ]) - this._wrapVector = wrapVector - - var shapeVector = [this._shape[0], this._shape[1]] - Object.defineProperties(shapeVector, [ - { - get: function() { - return parent._shape[0] - }, - set: function(v) { - return parent.width = v + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; } + return y0; }, - { - get: function() { - return parent._shape[1] - }, - set: function(v) { - return parent.height = v + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; + } + s2 += s3 * data[i][j][1]; + } + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; } - } - ]) - this._shapeVector = shapeVector -} - -var proto = Texture2D.prototype - -Object.defineProperties(proto, { - minFilter: { - get: function() { - return this._minFilter + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; }, - set: function(v) { - this.bind() - var gl = this.gl - if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { - if(!gl.getExtension('OES_texture_float_linear')) { - v = gl.NEAREST + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + } + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); + } + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; + } + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; + } + } + return j; + } + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); + } + function d3_layout_stackSum(p, d) { + return p + d[1]; + } + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); + } } } - if(filterTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown filter mode ' + v) + return bins; + } + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); + } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; + }; + root.x = root.y = 0; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + d3_layout_hierarchyVisitAfter(root, function(d) { + d.r -= dr; + }); } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v) - return this._minFilter = v + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; } - }, - magFilter: { - get: function() { - return this._magFilter - }, - set: function(v) { - this.bind() - var gl = this.gl - if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { - if(!gl.getExtension('OES_texture_float_linear')) { - v = gl.NEAREST + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; + }; + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; + }; + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); + }; + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } + } + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; + } + } + } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } } } - if(filterTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown filter mode ' + v) - } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) - return this._magFilter = v } - }, - mipSamples: { - get: function() { - return this._anisoSamples - }, - set: function(i) { - var psamples = this._anisoSamples - this._anisoSamples = Math.max(i, 1)|0 - if(psamples !== this._anisoSamples) { - var ext = gl.getExtension('EXT_texture_filter_anisotropic') - if(ext) { - this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) - } - } - return this._anisoSamples + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } - }, - wrapS: { - get: function() { - return this._wrapS - }, - set: function(v) { - this.bind() - if(wrapTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown wrap mode ' + v) - } - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v) - return this._wrapS = v + node.r = cr; + nodes.forEach(d3_layout_packUnlink); + } + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; + } + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); } - }, - wrapT: { - get: function() { - return this._wrapT - }, - set: function(v) { - this.bind() - if(wrapTypes.indexOf(v) < 0) { - throw new Error('gl-texture2d: Unknown wrap mode ' + v) - } - this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v) - return this._wrapT = v + } + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; } - }, - wrap: { - get: function() { - return this._wrapVector - }, - set: function(v) { - if(!Array.isArray(v)) { - v = [v,v] - } - if(v.length !== 2) { - throw new Error('gl-texture2d: Must specify wrap mode for rows and columns') + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); + d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; + d3_layout_hierarchyVisitBefore(root1, secondWalk); + if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { + var left = root0, right = root0, bottom = root0; + d3_layout_hierarchyVisitBefore(root0, function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); + d3_layout_hierarchyVisitBefore(root0, function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); } - for(var i=0; i<2; ++i) { - if(wrapTypes.indexOf(v[i]) < 0) { - throw new Error('gl-texture2d: Unknown wrap mode ' + v) + return nodes; + } + function wrapTree(root0) { + var root1 = { + A: null, + children: [ root0 ] + }, queue = [ root1 ], node1; + while ((node1 = queue.pop()) != null) { + for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { + queue.push((children[i] = child = { + _: children[i], + parent: node1, + children: (child = children[i].children) && child.slice() || [], + A: null, + a: null, + z: 0, + m: 0, + c: 0, + s: 0, + t: null, + i: i + }).a = child); } } - this._wrapS = v[0] - this._wrapT = v[1] - - var gl = this.gl - this.bind() - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT) - - return v + return root1.children[0]; } - }, - shape: { - get: function() { - return this._shapeVector - }, - set: function(x) { - if(!Array.isArray(x)) { - x = [x|0,x|0] - } else { - if(x.length !== 2) { - throw new Error('gl-texture2d: Invalid texture shape') + function firstWalk(v) { + var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; + if (children.length) { + d3_layout_treeShift(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; } + } else if (w) { + v.z = w.z + separation(v._, w._); } - reshapeTexture(this, x[0]|0, x[1]|0) - return [x[0]|0, x[1]|0] + v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } - }, - width: { - get: function() { - return this._shape[0] - }, - set: function(w) { - w = w|0 - reshapeTexture(this, w, this._shape[1]) - return w + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; } - }, - height: { - get: function() { - return this._shape[1] - }, - set: function(h) { - h = h|0 - reshapeTexture(this, this._shape[0], h) - return h + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !d3_layout_treeRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; } - } -}) - -proto.bind = function(unit) { - var gl = this.gl - if(unit !== undefined) { - gl.activeTexture(gl.TEXTURE0 + (unit|0)) - } - gl.bindTexture(gl.TEXTURE_2D, this.handle) - if(unit !== undefined) { - return (unit|0) - } - return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0 -} - -proto.dispose = function() { - this.gl.deleteTexture(this.handle) -} - -proto.generateMipmap = function() { - this.bind() - this.gl.generateMipmap(this.gl.TEXTURE_2D) - - //Update mip levels - var l = Math.min(this._shape[0], this._shape[1]) - for(var i=0; l>0; ++i, l>>>=1) { - if(this._mipLevels.indexOf(i) < 0) { - this._mipLevels.push(i) + function sizeNode(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null ? sizeNode : null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) == null ? null : sizeNode; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); + }; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; } -} - -proto.setPixels = function(data, x_off, y_off, mip_level) { - var gl = this.gl - this.bind() - if(Array.isArray(x_off)) { - mip_level = y_off - y_off = x_off[1]|0 - x_off = x_off[0]|0 - } else { - x_off = x_off || 0 - y_off = y_off || 0 + function d3_layout_treeLeft(v) { + var children = v.children; + return children.length ? children[0] : v.t; } - mip_level = mip_level || 0 - if(data instanceof HTMLCanvasElement || - data instanceof ImageData || - data instanceof HTMLImageElement || - data instanceof HTMLVideoElement) { - var needsMip = this._mipLevels.indexOf(mip_level) < 0 - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data) - this._mipLevels.push(mip_level) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data) - } - } else if(data.shape && data.stride && data.data) { - if(data.shape.length < 2 || - x_off + data.shape[1] > this._shape[1]>>>mip_level || - y_off + data.shape[0] > this._shape[0]>>>mip_level || - x_off < 0 || - y_off < 0) { - throw new Error('gl-texture2d: Texture dimensions are out of bounds') - } - texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data) - } else { - throw new Error('gl-texture2d: Unsupported data type') + function d3_layout_treeRight(v) { + var children = v.children, n; + return (n = children.length) ? children[n - 1] : v.t; } -} - - -function isPacked(shape, stride) { - if(shape.length === 3) { - return (stride[2] === 1) && - (stride[1] === shape[0]*shape[2]) && - (stride[0] === shape[2]) + function d3_layout_treeMove(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; } - return (stride[0] === 1) && - (stride[1] === shape[0]) -} - -function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) { - var dtype = array.dtype - var shape = array.shape.slice() - if(shape.length < 2 || shape.length > 3) { - throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') + function d3_layout_treeShift(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); + } } - var type = 0, format = 0 - var packed = isPacked(shape, array.stride.slice()) - if(dtype === 'float32') { - type = gl.FLOAT - } else if(dtype === 'float64') { - type = gl.FLOAT - packed = false - dtype = 'float32' - } else if(dtype === 'uint8') { - type = gl.UNSIGNED_BYTE - } else { - type = gl.UNSIGNED_BYTE - packed = false - dtype = 'uint8' + function d3_layout_treeAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; } - var channels = 1 - if(shape.length === 2) { - format = gl.LUMINANCE - shape = [shape[0], shape[1], 1] - array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) - } else if(shape.length === 3) { - if(shape[2] === 1) { - format = gl.ALPHA - } else if(shape[2] === 2) { - format = gl.LUMINANCE_ALPHA - } else if(shape[2] === 3) { - format = gl.RGB - } else if(shape[2] === 4) { - format = gl.RGBA - } else { - throw new Error('gl-texture2d: Invalid shape for pixel coords') + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_hierarchyVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; } - channels = shape[2] - } else { - throw new Error('gl-texture2d: Invalid shape for texture') + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); } - //For 1-channel textures allow conversion between formats - if((format === gl.LUMINANCE || format === gl.ALPHA) && - (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { - format = cformat + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; } - if(format !== cformat) { - throw new Error('gl-texture2d: Incompatible texture format for setPixels') + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; } - var size = array.size - var needsMip = mipLevels.indexOf(mip_level) < 0 - if(needsMip) { - mipLevels.push(mip_level) + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; } - if(type === ctype && packed) { - //Array data types are compatible, can directly copy into texture - if(array.offset === 0 && array.data.length === size) { - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } + } + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } + } + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); + } + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); + } + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; } - } else { - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + } + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); + } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; } } - } else { - //Need to do type conversion to pack data into buffer - var pack_buffer - if(ctype === gl.FLOAT) { - pack_buffer = pool.mallocFloat32(size) - } else { - pack_buffer = pool.mallocUint8(size) - } - var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) - if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { - convertFloatToUint8(pack_view, array) - } else { - ops.assign(pack_view, array) + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = root.y = 0; + if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; } - if(needsMip) { - gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) - } else { - gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; + }; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; + }; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; + }; + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; + }; + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; + }; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; + }; + return d3_layout_hierarchyRebind(treemap, hierarchy); + }; + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy + }; + } + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; } - if(ctype === gl.FLOAT) { - pool.freeFloat32(pack_buffer) - } else { - pool.freeUint8(pack_buffer) + if (dy < 0) { + y += dy / 2; + dy = 0; } + return { + x: x, + y: y, + dx: dx, + dy: dy + }; } -} - -function initTexture(gl) { - var tex = gl.createTexture() - gl.bindTexture(gl.TEXTURE_2D, tex) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) - return tex -} - -function createTextureShape(gl, width, height, format, type) { - var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { - throw new Error('gl-texture2d: Invalid texture shape') - } - if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { - throw new Error('gl-texture2d: Floating point textures not supported on this platform') + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; + }, + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; + }, + bates: function(m) { + var random = d3.random.irwinHall(m); + return function() { + return random() / m; + }; + }, + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; + } + }; + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; } - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) - return new Texture2D(gl, tex, width, height, format, type) -} - -function createTextureDOM(gl, element, format, type) { - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element) - return new Texture2D(gl, tex, element.width|0, element.height|0, format, type) -} - -//Creates a texture from an ndarray -function createTextureArray(gl, array) { - var dtype = array.dtype - var shape = array.shape.slice() - var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) - if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { - throw new Error('gl-texture2d: Invalid texture size') + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } - var packed = isPacked(shape, array.stride.slice()) - var type = 0 - if(dtype === 'float32') { - type = gl.FLOAT - } else if(dtype === 'float64') { - type = gl.FLOAT - packed = false - dtype = 'float32' - } else if(dtype === 'uint8') { - type = gl.UNSIGNED_BYTE - } else { - type = gl.UNSIGNED_BYTE - packed = false - dtype = 'uint8' + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; } - var format = 0 - if(shape.length === 2) { - format = gl.LUMINANCE - shape = [shape[0], shape[1], 1] - array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) - } else if(shape.length === 3) { - if(shape[2] === 1) { - format = gl.ALPHA - } else if(shape[2] === 2) { - format = gl.LUMINANCE_ALPHA - } else if(shape[2] === 3) { - format = gl.RGB - } else if(shape[2] === 4) { - format = gl.RGBA - } else { - throw new Error('gl-texture2d: Invalid shape for pixel coords') + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; } - } else { - throw new Error('gl-texture2d: Invalid shape for texture') + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; } - if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { - type = gl.UNSIGNED_BYTE - packed = false + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; + }, + ceil: function(x) { + return Math.ceil(x / step) * step; + } + } : d3_scale_niceIdentity; } - var buffer, buf_store - var size = array.size - if(!packed) { - var stride = [shape[2], shape[2]*shape[0], 1] - buf_store = pool.malloc(size, dtype) - var buf_array = ndarray(buf_store, shape, stride, 0) - if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { - convertFloatToUint8(buf_array, array) - } else { - ops.assign(buf_array, array) + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); } - buffer = buf_store.subarray(0, size) - } else if (array.offset === 0 && array.data.length === size) { - buffer = array.data - } else { - buffer = array.data.subarray(array.offset, array.offset + size) - } - var tex = initTexture(gl) - gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) - if(!packed) { - pool.free(buf_store) - } - return new Texture2D(gl, tex, shape[0], shape[1], format, type) -} - -function createTexture2D(gl) { - if(arguments.length <= 1) { - throw new Error('gl-texture2d: Missing arguments for texture2d constructor') - } - if(!linearTypes) { - lazyInitLinearTypes(gl) - } - if(typeof arguments[1] === 'number') { - return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) - } - if(Array.isArray(arguments[1])) { - return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; } - if(typeof arguments[1] === 'object') { - var obj = arguments[1] - if(obj instanceof HTMLCanvasElement || - obj instanceof HTMLImageElement || - obj instanceof HTMLVideoElement || - obj instanceof ImageData) { - return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) - } else if(obj.shape && obj.data && obj.stride) { - return createTextureArray(gl, obj) + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; } + function scale(x) { + return output(x); + } + scale.invert = function(y) { + return input(y); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); + }; + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); + }; + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); + }; + return rescale(); } - throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') -} - -},{"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":191}],189:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],190:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],191:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":189,"buffer":65,"dup":122}],192:[function(require,module,exports){ - -var createShader = require('gl-shader') - -var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n" -var forwardFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n" -var pickFrag = "precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}" - -var ATTRIBUTES = [ - {name: 'position', type: 'vec3'}, - {name: 'nextPosition', type: 'vec3'}, - {name: 'arcLength', type: 'float'}, - {name: 'lineWidth', type: 'float'}, - {name: 'color', type: 'vec4'} -] - -exports.createShader = function(gl) { - return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES) -} - -exports.createPickShader = function(gl) { - return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES) -} - -},{"gl-shader":199}],193:[function(require,module,exports){ -'use strict' - -module.exports = createLinePlot - -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createTexture = require('gl-texture2d') -var unpackFloat = require('glsl-read-float') -var bsearch = require('binary-search-bounds') -var ndarray = require('ndarray') -var shaders = require('./lib/shaders') - -var createShader = shaders.createShader -var createPickShader = shaders.createPickShader - -var identity = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1] - -function distance (a, b) { - var s = 0.0 - for (var i = 0; i < 3; ++i) { - var d = a[i] - b[i] - s += d * d + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } - return Math.sqrt(s) -} - -function filterClipBounds (bounds) { - var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]] - for (var i = 0; i < 3; ++i) { - result[0][i] = Math.max(bounds[0][i], result[0][i]) - result[1][i] = Math.min(bounds[1][i], result[1][i]) + function d3_scale_linearNice(domain, m) { + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + return domain; } - return result -} - -function PickResult (tau, position, index, dataCoordinate) { - this.arcLength = tau - this.position = position - this.index = index - this.dataCoordinate = dataCoordinate -} - -function LinePlot (gl, shader, pickShader, buffer, vao, texture) { - this.gl = gl - this.shader = shader - this.pickShader = pickShader - this.buffer = buffer - this.vao = vao - this.clipBounds = [ - [ -Infinity, -Infinity, -Infinity ], - [ Infinity, Infinity, Infinity ]] - this.points = [] - this.arcLength = [] - this.vertexCount = 0 - this.bounds = [[0, 0, 0], [0, 0, 0]] - this.pickId = 0 - this.lineWidth = 1 - this.texture = texture - this.dashScale = 1 - this.opacity = 1 - this.dirty = true - this.pixelRatio = 1 -} - -var proto = LinePlot.prototype - -proto.isTransparent = function () { - return this.opacity < 1 -} - -proto.isOpaque = function () { - return this.opacity >= 1 -} - -proto.pickSlots = 1 - -proto.setPickBase = function (id) { - this.pickId = id -} - -proto.drawTransparent = proto.draw = function (camera) { - var gl = this.gl - var shader = this.shader - var vao = this.vao - shader.bind() - shader.uniforms = { - model: camera.model || identity, - view: camera.view || identity, - projection: camera.projection || identity, - clipBounds: filterClipBounds(this.clipBounds), - dashTexture: this.texture.bind(), - dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], - opacity: this.opacity, - screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], - pixelRatio: this.pixelRatio + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; } - vao.bind() - vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) -} - -proto.drawPick = function (camera) { - var gl = this.gl - var shader = this.pickShader - var vao = this.vao - shader.bind() - shader.uniforms = { - model: camera.model || identity, - view: camera.view || identity, - projection: camera.projection || identity, - pickId: this.pickId, - clipBounds: filterClipBounds(this.clipBounds), - screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], - pixelRatio: this.pixelRatio + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } - vao.bind() - vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) -} - -proto.update = function (options) { - var i, j - - this.dirty = true - - var connectGaps = !!options.connectGaps - - if ('dashScale' in options) { - this.dashScale = options.dashScale + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + if (format) { + var match = d3_format_re.exec(format); + match.shift(); + if (match[8] === "s") { + var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); + if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); + match[8] = "f"; + format = d3.format(match.join("")); + return function(d) { + return format(prefix.scale(d)) + prefix.symbol; + }; + } + if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); + format = match.join(""); + } else { + format = ",." + d3_scale_linearPrecision(range[2]) + "f"; + } + return d3.format(format); } - if ('opacity' in options) { - this.opacity = +options.opacity + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); } - - var positions = options.position || options.positions - if (!positions) { - return + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; } - - // Default color - var colors = options.color || options.colors || [0, 0, 0, 1] - - var lineWidth = options.lineWidth || 1 - - // Recalculate buffer data - var buffer = [] - var arcLengthArray = [] - var pointArray = [] - var arcLength = 0.0 - var vertexCount = 0 - var bounds = [ - [ Infinity, Infinity, Infinity ], - [ -Infinity, -Infinity, -Infinity ]] - var hadGap = false - - fill_loop: - for (i = 1; i < positions.length; ++i) { - var a = positions[i - 1] - var b = positions[i] - - arcLengthArray.push(arcLength) - pointArray.push(a.slice()) - - for (j = 0; j < 3; ++j) { - if (isNaN(a[j]) || isNaN(b[j]) || - !isFinite(a[j]) || !isFinite(b[j])) { - - if (!connectGaps && buffer.length > 0) { - for (var k = 0; k < 24; ++k) { - buffer.push(buffer[buffer.length - 12]) - } - vertexCount += 2 - hadGap = true + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); + } + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); } - - continue fill_loop + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); } - bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]) - bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]) + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(1, base * n / scale.ticks().length); + return function(d) { + var i = d / pow(Math.round(log(d))); + if (i * base < base - .5) i *= base; + return i <= k ? format(d) : ""; + }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); } - - var acolor, bcolor - if (Array.isArray(colors[0])) { - acolor = colors[i - 1] - bcolor = colors[i] - } else { - acolor = bcolor = colors + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); } - if (acolor.length === 3) { - acolor = [acolor[0], acolor[1], acolor[2], 1] + scale.invert = function(x) { + return powb(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; + } + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); + }; + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } - if (bcolor.length === 3) { - bcolor = [bcolor[0], bcolor[1], bcolor[2], 1] + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; + }); } - - var w0 - if (Array.isArray(lineWidth)) { - w0 = lineWidth[i - 1] - } else { - w0 = lineWidth + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments + }; + return scale; + }; + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, + 0) : (stop - start) / (domain.length - 1 + padding); + range = steps(start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; + }; + scale.rangeRoundPoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), + 0) : (stop - start) / (domain.length - 1 + padding) | 0; + range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); + rangeBand = 0; + ranger = { + t: "rangeRoundPoints", + a: arguments + }; + return scale; + }; + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; + }; + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); + range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; + }; + scale.rangeBand = function() { + return rangeBand; + }; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); + }; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); + }; + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); + }; + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; } - - var t0 = arcLength - arcLength += distance(a, b) - - if (hadGap) { - for (j = 0; j < 2; ++j) { - buffer.push( - a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3]) - } - vertexCount += 2 - hadGap = false + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; } - - buffer.push( - a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3], - a[0], a[1], a[2], b[0], b[1], b[2], t0, -w0, acolor[0], acolor[1], acolor[2], acolor[3], - b[0], b[1], b[2], a[0], a[1], a[2], arcLength, -w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3], - b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3]) - - vertexCount += 4 + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); } - this.buffer.update(buffer) - - arcLengthArray.push(arcLength) - pointArray.push(positions[positions.length - 1].slice()) - - this.bounds = bounds - - this.vertexCount = vertexCount - - this.points = pointArray - this.arcLength = arcLengthArray - - if ('dashes' in options) { - var dashArray = options.dashes - - // Calculate prefix sum - var prefixSum = dashArray.slice() - prefixSum.unshift(0) - for (i = 1; i < prefixSum.length; ++i) { - prefixSum[i] = prefixSum[i - 1] + prefixSum[i] + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; } - - var dashTexture = ndarray(new Array(256 * 4), [256, 1, 4]) - for (i = 0; i < 256; ++i) { - for (j = 0; j < 4; ++j) { - dashTexture.set(i, 0, j, 0) + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; + } + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; + }; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); + }; + return rescale(); + } + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); + }; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; + }; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; + } + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; + } + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; + }; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; + } + d3.svg = {}; + function d3_zero() { + return 0; + } + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; + function arc() { + var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; + if (r1 < r0) rc = r1, r1 = r0, r0 = rc; + if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; + var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; + if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { + rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); + if (!cw) p1 *= -1; + if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); + if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); } - if (bsearch.le(prefixSum, prefixSum[prefixSum.length - 1] * i / 255.0) & 1) { - dashTexture.set(i, 0, 0, 0) + if (r1) { + x0 = r1 * Math.cos(a0 + p1); + y0 = r1 * Math.sin(a0 + p1); + x1 = r1 * Math.cos(a1 - p1); + y1 = r1 * Math.sin(a1 - p1); + var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; + if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { + var h1 = (a0 + a1) / 2; + x0 = r1 * Math.cos(h1); + y0 = r1 * Math.sin(h1); + x1 = y1 = null; + } } else { - dashTexture.set(i, 0, 0, 255) + x0 = y0 = 0; + } + if (r0) { + x2 = r0 * Math.cos(a1 - p0); + y2 = r0 * Math.sin(a1 - p0); + x3 = r0 * Math.cos(a0 + p0); + y3 = r0 * Math.sin(a0 + p0); + var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; + if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { + var h0 = (a0 + a1) / 2; + x2 = r0 * Math.cos(h0); + y2 = r0 * Math.sin(h0); + x3 = y3 = null; + } + } else { + x2 = y2 = 0; + } + if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { + cr = r0 < r1 ^ cw ? 0 : 1; + var rc1 = rc, rc0 = rc; + if (da < π) { + var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); + rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); + } + if (x1 != null) { + var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); + if (rc === rc1) { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); + } else { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + } else { + path.push("M", x0, ",", y0); + } + if (x3 != null) { + var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); + if (rc === rc0) { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } else { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } + } else { + path.push("L", x2, ",", y2); + } + } else { + path.push("M", x0, ",", y0); + if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); + path.push("L", x2, ",", y2); + if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); } + path.push("Z"); + return path.join(""); } - - this.texture.setPixels(dashTexture) - } -} - -proto.dispose = function () { - this.shader.dispose() - this.vao.dispose() - this.buffer.dispose() -} - -proto.pick = function (selection) { - if (!selection) { - return null - } - if (selection.id !== this.pickId) { - return null + function circleSegment(r1, cw) { + return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; + } + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; + }; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; + }; + arc.cornerRadius = function(v) { + if (!arguments.length) return cornerRadius; + cornerRadius = d3_functor(v); + return arc; + }; + arc.padRadius = function(v) { + if (!arguments.length) return padRadius; + padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); + return arc; + }; + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; + }; + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; + }; + arc.padAngle = function(v) { + if (!arguments.length) return padAngle; + padAngle = d3_functor(v); + return arc; + }; + arc.centroid = function() { + var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; + return [ Math.cos(a) * r, Math.sin(a) * r ]; + }; + return arc; + }; + var d3_svg_arcAuto = "auto"; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; } - var tau = unpackFloat( - selection.value[0], - selection.value[1], - selection.value[2], - 0) - var index = bsearch.le(this.arcLength, tau) - if (index < 0) { - return null + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; } - if (index === this.arcLength.length - 1) { - return new PickResult( - this.arcLength[this.arcLength.length - 1], - this.points[this.points.length - 1].slice(), - index) + function d3_svg_arcStartAngle(d) { + return d.startAngle; } - var a = this.points[index] - var b = this.points[Math.min(index + 1, this.points.length - 1)] - var t = (tau - this.arcLength[index]) / (this.arcLength[index + 1] - this.arcLength[index]) - var ti = 1.0 - t - var x = [0, 0, 0] - for (var i = 0; i < 3; ++i) { - x[i] = ti * a[i] + t * b[i] + function d3_svg_arcEndAngle(d) { + return d.endAngle; } - var dataIndex = Math.min((t < 0.5) ? index : (index + 1), this.points.length - 1) - return new PickResult( - tau, - x, - dataIndex, - this.points[dataIndex]) -} - -function createLinePlot (options) { - var gl = options.gl || (options.scene && options.scene.gl) - - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.nextPosition.location = 1 - shader.attributes.arcLength.location = 2 - shader.attributes.lineWidth.location = 3 - shader.attributes.color.location = 4 - - var pickShader = createPickShader(gl) - pickShader.attributes.position.location = 0 - pickShader.attributes.nextPosition.location = 1 - pickShader.attributes.arcLength.location = 2 - pickShader.attributes.lineWidth.location = 3 - pickShader.attributes.color.location = 4 - - var buffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - 'buffer': buffer, - 'size': 3, - 'offset': 0, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 3, - 'offset': 12, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 1, - 'offset': 24, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 1, - 'offset': 28, - 'stride': 48 - }, - { - 'buffer': buffer, - 'size': 4, - 'offset': 32, - 'stride': 48 - } - ]) - - // Create texture for dash pattern - var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) - for (var i = 0; i < 256 * 4; ++i) { - defaultTexture.data[i] = 255 + function d3_svg_arcPadAngle(d) { + return d && d.padAngle; } - var texture = createTexture(gl, defaultTexture) - texture.wrap = gl.REPEAT - - var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) - linePlot.update(options) - return linePlot -} - -},{"./lib/shaders":192,"binary-search-bounds":194,"gl-buffer":195,"gl-texture2d":228,"gl-vao":232,"glsl-read-float":233,"ndarray":1031}],194:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],195:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":198}],196:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],197:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],198:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":196,"buffer":65,"dup":122}],199:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":200,"./lib/create-attributes":201,"./lib/create-uniforms":202,"./lib/reflect":203,"./lib/runtime-reflect":204,"./lib/shader-cache":205,"dup":94}],200:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],201:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":200,"dup":96}],202:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":200,"./reflect":203,"dup":97}],203:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],204:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],205:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":200,"dup":100,"gl-format-compiler-error":206,"weakmap-shim":224}],206:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":207,"dup":101,"gl-constants/lookup":211,"glsl-shader-name":212,"sprintf-js":221}],207:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":208}],208:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":209}],209:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],210:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],211:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":210,"dup":106}],212:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":213,"dup":107,"glsl-tokenizer":220}],213:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],214:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":216,"./lib/builtins-300es":215,"./lib/literals":218,"./lib/literals-300es":217,"./lib/operators":219,"dup":109}],215:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":216,"dup":110}],216:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],217:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":218,"dup":112}],218:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],219:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],220:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":214,"dup":115}],221:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],222:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":223,"dup":117}],223:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],224:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":222,"dup":119}],225:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],226:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],227:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":225,"buffer":65,"dup":122}],228:[function(require,module,exports){ -arguments[4][188][0].apply(exports,arguments) -},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":227}],229:[function(require,module,exports){ -arguments[4][154][0].apply(exports,arguments) -},{"dup":154}],230:[function(require,module,exports){ -arguments[4][155][0].apply(exports,arguments) -},{"./do-bind.js":229,"dup":155}],231:[function(require,module,exports){ -arguments[4][156][0].apply(exports,arguments) -},{"./do-bind.js":229,"dup":156}],232:[function(require,module,exports){ -arguments[4][157][0].apply(exports,arguments) -},{"./lib/vao-emulated.js":230,"./lib/vao-native.js":231,"dup":157}],233:[function(require,module,exports){ -module.exports = decodeFloat - -var UINT8_VIEW = new Uint8Array(4) -var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) - -function decodeFloat(x, y, z, w) { - UINT8_VIEW[0] = w - UINT8_VIEW[1] = z - UINT8_VIEW[2] = y - UINT8_VIEW[3] = x - return FLOAT_VIEW[0] -} - -},{}],234:[function(require,module,exports){ -module.exports = clone; - -/** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param {mat4} a matrix to clone - * @returns {mat4} a new 4x4 matrix - */ -function clone(a) { - var out = new Float32Array(16); - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -}; -},{}],235:[function(require,module,exports){ -module.exports = create; - -/** - * Creates a new identity mat4 - * - * @returns {mat4} a new 4x4 matrix - */ -function create() { - var out = new Float32Array(16); - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -}; -},{}],236:[function(require,module,exports){ -module.exports = determinant; - -/** - * Calculates the determinant of a mat4 - * - * @param {mat4} a the source matrix - * @returns {Number} determinant of a - */ -function determinant(a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32; - - // Calculate the determinant - return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; -}; -},{}],237:[function(require,module,exports){ -module.exports = fromQuat; - -/** - * Creates a matrix from a quaternion rotation. - * - * @param {mat4} out mat4 receiving operation result - * @param {quat4} q Rotation quaternion - * @returns {mat4} out - */ -function fromQuat(out, q) { - var x = q[0], y = q[1], z = q[2], w = q[3], - x2 = x + x, - y2 = y + y, - z2 = z + z, - - xx = x * x2, - yx = y * x2, - yy = y * y2, - zx = z * x2, - zy = z * y2, - zz = z * z2, - wx = w * x2, - wy = w * y2, - wz = w * z2; - - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; - - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; - - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; - - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - - return out; -}; -},{}],238:[function(require,module,exports){ -module.exports = fromRotationTranslation; - -/** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat4} q Rotation quaternion - * @param {vec3} v Translation vector - * @returns {mat4} out - */ -function fromRotationTranslation(out, q, v) { - // Quaternion math - var x = q[0], y = q[1], z = q[2], w = q[3], - x2 = x + x, - y2 = y + y, - z2 = z + z, - - xx = x * x2, - xy = x * y2, - xz = x * z2, - yy = y * y2, - yz = y * z2, - zz = z * z2, - wx = w * x2, - wy = w * y2, - wz = w * z2; - - out[0] = 1 - (yy + zz); - out[1] = xy + wz; - out[2] = xz - wy; - out[3] = 0; - out[4] = xy - wz; - out[5] = 1 - (xx + zz); - out[6] = yz + wx; - out[7] = 0; - out[8] = xz + wy; - out[9] = yz - wx; - out[10] = 1 - (xx + yy); - out[11] = 0; - out[12] = v[0]; - out[13] = v[1]; - out[14] = v[2]; - out[15] = 1; - - return out; -}; -},{}],239:[function(require,module,exports){ -module.exports = identity; - -/** - * Set a mat4 to the identity matrix - * - * @param {mat4} out the receiving matrix - * @returns {mat4} out - */ -function identity(out) { - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -}; -},{}],240:[function(require,module,exports){ -module.exports = invert; - -/** - * Inverts a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - - b00 = a00 * a11 - a01 * a10, - b01 = a00 * a12 - a02 * a10, - b02 = a00 * a13 - a03 * a10, - b03 = a01 * a12 - a02 * a11, - b04 = a01 * a13 - a03 * a11, - b05 = a02 * a13 - a03 * a12, - b06 = a20 * a31 - a21 * a30, - b07 = a20 * a32 - a22 * a30, - b08 = a20 * a33 - a23 * a30, - b09 = a21 * a32 - a22 * a31, - b10 = a21 * a33 - a23 * a31, - b11 = a22 * a33 - a23 * a32, - - // Calculate the determinant - det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - - if (!det) { - return null; + function d3_svg_arcSweep(x0, y0, x1, y1) { + return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + } + function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { + var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; + if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; + return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; + } + } + if (points.length) segment(); + return segments.length ? segments.join("") : null; } - det = 1.0 / det; - - out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - - return out; -}; -},{}],241:[function(require,module,exports){ -var identity = require('./identity'); - -module.exports = lookAt; - -/** - * Generates a look-at matrix with the given eye position, focal point, and up axis - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {vec3} eye Position of the viewer - * @param {vec3} center Point the viewer is looking at - * @param {vec3} up vec3 pointing up - * @returns {mat4} out - */ -function lookAt(out, eye, center, up) { - var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, - eyex = eye[0], - eyey = eye[1], - eyez = eye[2], - upx = up[0], - upy = up[1], - upz = up[2], - centerx = center[0], - centery = center[1], - centerz = center[2]; - - if (Math.abs(eyex - centerx) < 0.000001 && - Math.abs(eyey - centery) < 0.000001 && - Math.abs(eyez - centerz) < 0.000001) { - return identity(out); + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.length > 1 ? points.join("L") : points + "Z"; + } + function d3_svg_lineLinearClosed(points) { + return points.join("L") + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); } - - z0 = eyex - centerx; - z1 = eyey - centery; - z2 = eyez - centerz; - - len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); - z0 *= len; - z1 *= len; - z2 *= len; - - x0 = upy * z2 - upz * z1; - x1 = upz * z0 - upx * z2; - x2 = upx * z1 - upy * z0; - len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); - if (!len) { - x0 = 0; - x1 = 0; - x2 = 0; - } else { - len = 1 / len; - x0 *= len; - x1 *= len; - x2 *= len; + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; } - - y0 = z1 * x2 - z2 * x1; - y1 = z2 * x0 - z0 * x2; - y2 = z0 * x1 - z1 * x0; - - len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); - if (!len) { - y0 = 0; - y1 = 0; - y2 = 0; - } else { - len = 1 / len; - y0 *= len; - y1 *= len; - y2 *= len; + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } } - - out[0] = x0; - out[1] = y0; - out[2] = z0; - out[3] = 0; - out[4] = x1; - out[5] = y1; - out[6] = z1; - out[7] = 0; - out[8] = x2; - out[9] = y2; - out[10] = z2; - out[11] = 0; - out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); - out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); - out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); - out[15] = 1; - - return out; -}; -},{"./identity":239}],242:[function(require,module,exports){ -module.exports = multiply; - -/** - * Multiplies two mat4's - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ -function multiply(out, a, b) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], - a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], - a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], - a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - - // Cache only the current line of the second matrix - var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; - out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; - out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; - out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - return out; -}; -},{}],243:[function(require,module,exports){ -module.exports = perspective; - -/** - * Generates a perspective projection matrix with the given bounds - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {number} fovy Vertical field of view in radians - * @param {number} aspect Aspect ratio. typically viewport width/height - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ -function perspective(out, fovy, aspect, near, far) { - var f = 1.0 / Math.tan(fovy / 2), - nf = 1 / (near - far); - out[0] = f / aspect; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = f; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = (far + near) * nf; - out[11] = -1; - out[12] = 0; - out[13] = 0; - out[14] = (2 * far * near) * nf; - out[15] = 0; - return out; -}; -},{}],244:[function(require,module,exports){ -module.exports = rotate; - -/** - * Rotates a mat4 by the given angle - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ -function rotate(out, a, rad, axis) { - var x = axis[0], y = axis[1], z = axis[2], - len = Math.sqrt(x * x + y * y + z * z), - s, c, t, - a00, a01, a02, a03, - a10, a11, a12, a13, - a20, a21, a22, a23, - b00, b01, b02, - b10, b11, b12, - b20, b21, b22; - - if (Math.abs(len) < 0.000001) { return null; } - - len = 1 / len; - x *= len; - y *= len; - z *= len; - - s = Math.sin(rad); - c = Math.cos(rad); - t = 1 - c; - - a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; - a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; - a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; - - // Construct the elements of the rotation matrix - b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; - b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; - b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; - - // Perform rotation-specific matrix multiplication - out[0] = a00 * b00 + a10 * b01 + a20 * b02; - out[1] = a01 * b00 + a11 * b01 + a21 * b02; - out[2] = a02 * b00 + a12 * b01 + a22 * b02; - out[3] = a03 * b00 + a13 * b01 + a23 * b02; - out[4] = a00 * b10 + a10 * b11 + a20 * b12; - out[5] = a01 * b10 + a11 * b11 + a21 * b12; - out[6] = a02 * b10 + a12 * b11 + a22 * b12; - out[7] = a03 * b10 + a13 * b11 + a23 * b12; - out[8] = a00 * b20 + a10 * b21 + a20 * b22; - out[9] = a01 * b20 + a11 * b21 + a21 * b22; - out[10] = a02 * b20 + a12 * b21 + a22 * b22; - out[11] = a03 * b20 + a13 * b21 + a23 * b22; - - if (a !== out) { // If the source and destination differ, copy the unchanged last row - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); + } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); + } + } + return d3_svg_lineBasis(points); + } + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); + } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; + } else { + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; + } + } + } + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); + } + return tangents; + } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] - halfπ; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); } - return out; -}; -},{}],245:[function(require,module,exports){ -module.exports = rotateX; - -/** - * Rotates a matrix by the given angle around the X axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateX(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a10 = a[4], - a11 = a[5], - a12 = a[6], - a13 = a[7], - a20 = a[8], - a21 = a[9], - a22 = a[10], - a23 = a[11]; - - if (a !== out) { // If the source and destination differ, copy the unchanged rows - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + return points; + } + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; + } + } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; } - - // Perform axis-specific matrix multiplication - out[4] = a10 * c + a20 * s; - out[5] = a11 * c + a21 * s; - out[6] = a12 * c + a22 * s; - out[7] = a13 * c + a23 * s; - out[8] = a20 * c - a10 * s; - out[9] = a21 * c - a11 * s; - out[10] = a22 * c - a12 * s; - out[11] = a23 * c - a13 * s; - return out; -}; -},{}],246:[function(require,module,exports){ -module.exports = rotateY; - -/** - * Rotates a matrix by the given angle around the Y axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateY(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a[0], - a01 = a[1], - a02 = a[2], - a03 = a[3], - a20 = a[8], - a21 = a[9], - a22 = a[10], - a23 = a[11]; - - if (a !== out) { // If the source and destination differ, copy the unchanged rows - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; + } + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; } - - // Perform axis-specific matrix multiplication - out[0] = a00 * c - a20 * s; - out[1] = a01 * c - a21 * s; - out[2] = a02 * c - a22 * s; - out[3] = a03 * c - a23 * s; - out[8] = a00 * s + a20 * c; - out[9] = a01 * s + a21 * c; - out[10] = a02 * s + a22 * c; - out[11] = a03 * s + a23 * c; - return out; -}; -},{}],247:[function(require,module,exports){ -module.exports = rotateZ; - -/** - * Rotates a matrix by the given angle around the Z axis - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to rotate - * @param {Number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ -function rotateZ(out, a, rad) { - var s = Math.sin(rad), - c = Math.cos(rad), - a00 = a[0], - a01 = a[1], - a02 = a[2], - a03 = a[3], - a10 = a[4], - a11 = a[5], - a12 = a[6], - a13 = a[7]; - - if (a !== out) { // If the source and destination differ, copy the unchanged last row - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; } - - // Perform axis-specific matrix multiplication - out[0] = a00 * c + a10 * s; - out[1] = a01 * c + a11 * s; - out[2] = a02 * c + a12 * s; - out[3] = a03 * c + a13 * s; - out[4] = a10 * c - a00 * s; - out[5] = a11 * c - a01 * s; - out[6] = a12 * c - a02 * s; - out[7] = a13 * c - a03 * s; - return out; -}; -},{}],248:[function(require,module,exports){ -module.exports = scale; - -/** - * Scales the mat4 by the dimensions in the given vec3 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {vec3} v the vec3 to scale the matrix by - * @returns {mat4} out - **/ -function scale(out, a, v) { - var x = v[0], y = v[1], z = v[2]; - - out[0] = a[0] * x; - out[1] = a[1] * x; - out[2] = a[2] * x; - out[3] = a[3] * x; - out[4] = a[4] * y; - out[5] = a[5] * y; - out[6] = a[6] * y; - out[7] = a[7] * y; - out[8] = a[8] * z; - out[9] = a[9] * z; - out[10] = a[10] * z; - out[11] = a[11] * z; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -}; -},{}],249:[function(require,module,exports){ -module.exports = translate; - -/** - * Translate a mat4 by the given vector - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to translate - * @param {vec3} v vector to translate by - * @returns {mat4} out - */ -function translate(out, a, v) { - var x = v[0], y = v[1], z = v[2], - a00, a01, a02, a03, - a10, a11, a12, a13, - a20, a21, a22, a23; - - if (a === out) { - out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; - out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; - out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; - out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; - } else { - a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; - a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; - a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; - - out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; - out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; - out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; - - out[12] = a00 * x + a10 * y + a20 * z + a[12]; - out[13] = a01 * x + a11 * y + a21 * z + a[13]; - out[14] = a02 * x + a12 * y + a22 * z + a[14]; - out[15] = a03 * x + a13 * y + a23 * z + a[15]; + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; } - - return out; -}; -},{}],250:[function(require,module,exports){ -module.exports = transpose; - -/** - * Transpose the values of a mat4 - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the source matrix - * @returns {mat4} out - */ -function transpose(out, a) { - // If we are transposing ourselves we can skip a few steps but have to cache some values - if (out === a) { - var a01 = a[1], a02 = a[2], a03 = a[3], - a12 = a[6], a13 = a[7], - a23 = a[11]; - - out[1] = a[4]; - out[2] = a[8]; - out[3] = a[12]; - out[4] = a01; - out[6] = a[9]; - out[7] = a[13]; - out[8] = a02; - out[9] = a12; - out[11] = a[14]; - out[12] = a03; - out[13] = a13; - out[14] = a23; - } else { - out[0] = a[0]; - out[1] = a[4]; - out[2] = a[8]; - out[3] = a[12]; - out[4] = a[1]; - out[5] = a[5]; - out[6] = a[9]; - out[7] = a[13]; - out[8] = a[2]; - out[9] = a[6]; - out[10] = a[10]; - out[11] = a[14]; - out[12] = a[3]; - out[13] = a[7]; - out[14] = a[11]; - out[15] = a[15]; + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; } - - return out; -}; -},{}],251:[function(require,module,exports){ -'use strict' - -var barycentric = require('barycentric') -var closestPointToTriangle = require('polytope-closest-point/lib/closest_point_2d.js') - -module.exports = closestPointToPickLocation - -function xformMatrix(m, v) { - var out = [0,0,0,0] - for(var i=0; i<4; ++i) { - for(var j=0; j<4; ++j) { - out[j] += m[4*i + j] * v[i] + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; + } + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; + } + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; + } + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; + } + function d3_svg_symbolType() { + return "circle"; + } + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; + }, + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + d3_selectionPrototype.transition = function(name) { + var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); + subgroup.push(node); + } } + return d3_transition(subgroups, ns, id); + }; + d3_selectionPrototype.interrupt = function(name) { + return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); + }; + var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); + function d3_selection_interruptNS(ns) { + return function() { + var lock, activeId, active; + if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { + active.timer.c = null; + active.timer.t = NaN; + if (--lock.count) delete lock[activeId]; else delete this[ns]; + lock.active += .5; + active.event && active.event.interrupt.call(this, this.__data__, active.index); + } + }; } - return out -} - -function projectVertex(v, model, view, projection, resolution) { - var p = xformMatrix(projection, - xformMatrix(view, - xformMatrix(model, [v[0], v[1], v[2], 1]))) - for(var i=0; i<3; ++i) { - p[i] /= p[3] + function d3_transition(groups, ns, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.namespace = ns; + groups.id = id; + return groups; } - return [ 0.5 * resolution[0] * (1.0+p[0]), 0.5 * resolution[1] * (1.0-p[1]) ] -} - -function barycentricCoord(simplex, point) { - if(simplex.length === 2) { - var d0 = 0.0 - var d1 = 0.0 - for(var i=0; i<2; ++i) { - d0 += Math.pow(point[i] - simplex[0][i], 2) - d1 += Math.pow(point[i] - simplex[1][i], 2) + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection, name) { + return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, ns, id, node[ns][id]); + subgroup.push(subnode); + } else { + subgroup.push(null); + } + } } - d0 = Math.sqrt(d0) - d1 = Math.sqrt(d1) - if(d0+d1 < 1e-6) { - return [1,0] + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node[ns][id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); + subgroup.push(subnode); + } + } + } } - return [d1/(d0+d1),d0/(d1+d0)] - } else if(simplex.length === 3) { - var closestPoint = [0,0] - closestPointToTriangle(simplex[0], simplex[1], simplex[2], point, closestPoint) - return barycentric(simplex, closestPoint) - } - return [] -} - -function interpolate(simplex, weights) { - var result = [0,0,0] - for(var i=0; i 1.0001) { - return null + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); } - s += weights[i] - } - if(Math.abs(s - 1.0) > 0.001) { - return null + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); + }; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; + } + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; } - return [closestIndex, interpolate(simplex, weights), weights] -} -},{"barycentric":254,"polytope-closest-point/lib/closest_point_2d.js":298}],252:[function(require,module,exports){ - - -var triVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}" -var triFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}" -var edgeVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}" -var edgeFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" -var pointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}" -var pointFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" -var pickVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}" -var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}" -var pickPointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}" -var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}" -var contourFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n" - -exports.meshShader = { - vertex: triVertSrc, - fragment: triFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'normal', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'} - ] -} -exports.wireShader = { - vertex: edgeVertSrc, - fragment: edgeFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'} - ] -} -exports.pointShader = { - vertex: pointVertSrc, - fragment: pointFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'color', type: 'vec4'}, - {name: 'uv', type: 'vec2'}, - {name: 'pointSize', type: 'float'} - ] -} -exports.pickShader = { - vertex: pickVertSrc, - fragment: pickFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'id', type: 'vec4'} - ] -} -exports.pointPickShader = { - vertex: pickPointVertSrc, - fragment: pickFragSrc, - attributes: [ - {name: 'position', type: 'vec3'}, - {name: 'pointSize', type: 'float'}, - {name: 'id', type: 'vec4'} - ] -} -exports.contourShader = { - vertex: contourVertSrc, - fragment: contourFragSrc, - attributes: [ - {name: 'position', type: 'vec3'} - ] -} - -},{}],253:[function(require,module,exports){ -'use strict' - -var DEFAULT_VERTEX_NORMALS_EPSILON = 1e-6; // may be too large if triangles are very small -var DEFAULT_FACE_NORMALS_EPSILON = 1e-6; - -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createTexture = require('gl-texture2d') -var normals = require('normals') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var ndarray = require('ndarray') -var colormap = require('colormap') -var getContour = require('simplicial-complex-contour') -var pool = require('typedarray-pool') -var shaders = require('./lib/shaders') -var closestPoint = require('./lib/closest-point') - -var meshShader = shaders.meshShader -var wireShader = shaders.wireShader -var pointShader = shaders.pointShader -var pickShader = shaders.pickShader -var pointPickShader = shaders.pointPickShader -var contourShader = shaders.contourShader - -var identityMatrix = [ - 1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1] - -function SimplicialMesh(gl - , texture - , triShader - , lineShader - , pointShader - , pickShader - , pointPickShader - , contourShader - , trianglePositions - , triangleIds - , triangleColors - , triangleUVs - , triangleNormals - , triangleVAO - , edgePositions - , edgeIds - , edgeColors - , edgeUVs - , edgeVAO - , pointPositions - , pointIds - , pointColors - , pointUVs - , pointSizes - , pointVAO - , contourPositions - , contourVAO) { - - this.gl = gl - this.cells = [] - this.positions = [] - this.intensity = [] - this.texture = texture - this.dirty = true - - this.triShader = triShader - this.lineShader = lineShader - this.pointShader = pointShader - this.pickShader = pickShader - this.pointPickShader = pointPickShader - this.contourShader = contourShader - - this.trianglePositions = trianglePositions - this.triangleColors = triangleColors - this.triangleNormals = triangleNormals - this.triangleUVs = triangleUVs - this.triangleIds = triangleIds - this.triangleVAO = triangleVAO - this.triangleCount = 0 - - this.lineWidth = 1 - this.edgePositions = edgePositions - this.edgeColors = edgeColors - this.edgeUVs = edgeUVs - this.edgeIds = edgeIds - this.edgeVAO = edgeVAO - this.edgeCount = 0 - - this.pointPositions = pointPositions - this.pointColors = pointColors - this.pointUVs = pointUVs - this.pointSizes = pointSizes - this.pointIds = pointIds - this.pointVAO = pointVAO - this.pointCount = 0 - - this.contourLineWidth = 1 - this.contourPositions = contourPositions - this.contourVAO = contourVAO - this.contourCount = 0 - this.contourColor = [0,0,0] - this.contourEnable = true - - this.pickId = 1 - this.bounds = [ - [ Infinity, Infinity, Infinity], - [-Infinity,-Infinity,-Infinity] ] - this.clipBounds = [ - [-Infinity,-Infinity,-Infinity], - [ Infinity, Infinity, Infinity] ] - - this.lightPosition = [1e5, 1e5, 0] - this.ambientLight = 0.8 - this.diffuseLight = 0.8 - this.specularLight = 2.0 - this.roughness = 0.5 - this.fresnel = 1.5 - - this.opacity = 1.0 - - this._model = identityMatrix - this._view = identityMatrix - this._projection = identityMatrix - this._resolution = [1,1] -} - -var proto = SimplicialMesh.prototype - -proto.isOpaque = function() { - return this.opacity >= 1 -} - -proto.isTransparent = function() { - return this.opacity < 1 -} - -proto.pickSlots = 1 - -proto.setPickBase = function(id) { - this.pickId = id -} - -function genColormap(param) { - var colors = colormap({ - colormap: param - , nshades: 256 - , format: 'rgba' - }) - - var result = new Uint8Array(256*4) - for(var i=0; i<256; ++i) { - var c = colors[i] - for(var j=0; j<3; ++j) { - result[4*i+j] = c[j] + d3_transitionPrototype.remove = function() { + var ns = this.namespace; + return this.each("end.transition", function() { + var p; + if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node[ns][id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].delay; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node[ns][id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].duration; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node[ns][id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + try { + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node[ns][id]; + type.call(node, node.__data__, i, j); + }); + } finally { + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } + } else { + d3_selection_each(this, function(node) { + var transition = node[ns][id]; + (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); + }); } - result[4*i+3] = c[3]*255 - } - - return ndarray(result, [256,256,4], [4,0,1]) -} - -function unpackIntensity(cells, numVerts, cellIntensity) { - var result = new Array(numVerts) - for(var i=0; i 0) { + tweens[--n].call(node, e); } - } else { - for(var i=0; i= 1) { + transition.event && transition.event.end.call(node, node.__data__, i); + if (--lock.count) delete lock[id]; else delete node[ns]; + return 1; } } + if (!transition) { + time = inherit.time; + timer = d3_timer(schedule, 0, time); + transition = lock[id] = { + tween: new d3_Map(), + time: time, + timer: timer, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + } } - - if(vertexIntensity) { - this.intensity = vertexIntensity - } else if(cellIntensity) { - this.intensity = unpackIntensity(cells, positions.length, cellIntensity) - } else { - this.intensity = takeZComponent(positions) + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; + if (orient === "bottom" || orient === "top") { + tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; + text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); + } else { + tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; + text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); + pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); + } + lineEnter.attr(y2, sign * innerTickSize); + textEnter.attr(y1, sign * tickSpacing); + lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); + textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1, scale0); + } + tickEnter.call(tickTransform, scale0, scale1); + tickUpdate.call(tickTransform, scale1, scale1); + }); + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; + }; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; + }; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = d3_array(arguments); + return axis; + }; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; + }; + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; + }; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; + }; + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 + }; + function d3_svg_axisX(selection, x0, x1) { + selection.attr("transform", function(d) { + var v0 = x0(d); + return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; + }); } - - //Point size - var pointSizes = params.pointSizes - var meshPointSize = params.pointSize || 1.0 - - //Update bounds - this.bounds = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]] - for(var i=0; irect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); } - } - - //Pack cells into buffers - var triangleCount = 0 - var edgeCount = 0 - var pointCount = 0 - -fill_loop: - for(var i=0; i 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); + }; + scale.tickFormat = function() { + return format; + }; + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); + }; + return d3_scale_linearRebind(scale, linear); } - for(var i=0; i<3; ++i) { - var s = invCameraMatrix[12+i] - for(var j=0; j<3; ++j) { - s += invCameraMatrix[4*j+i] * this.lightPosition[j] - } - uniforms.lightPosition[i] = s / w + function d3_time_scaleDate(t) { + return new Date(t); } - - if(this.triangleCount > 0) { - var shader = this.triShader - shader.bind() - shader.uniforms = uniforms - - this.triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) - this.triangleVAO.unbind() + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { + return d.getMilliseconds(); + } ], [ ":%S", function(d) { + return d.getSeconds(); + } ], [ "%I:%M", function(d) { + return d.getMinutes(); + } ], [ "%I %p", function(d) { + return d.getHours(); + } ], [ "%a %d", function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ "%b %d", function(d) { + return d.getDate() != 1; + } ], [ "%B", function(d) { + return d.getMonth(); + } ], [ "%Y", d3_true ] ]); + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); + }, + floor: d3_identity, + ceil: d3_identity + }; + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { + return d.getUTCMilliseconds(); + } ], [ ":%S", function(d) { + return d.getUTCSeconds(); + } ], [ "%I:%M", function(d) { + return d.getUTCMinutes(); + } ], [ "%I %p", function(d) { + return d.getUTCHours(); + } ], [ "%a %d", function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ "%b %d", function(d) { + return d.getUTCDate() != 1; + } ], [ "%B", function(d) { + return d.getUTCMonth(); + } ], [ "%Y", d3_true ] ]); + d3_time_scaleUtcMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); } - - if(this.edgeCount > 0 && this.lineWidth > 0) { - var shader = this.lineShader - shader.bind() - shader.uniforms = uniforms - - this.edgeVAO.bind() - gl.lineWidth(this.lineWidth) - gl.drawArrays(gl.LINES, 0, this.edgeCount*2) - this.edgeVAO.unbind() + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); } + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; +}(); +},{}],114:[function(require,module,exports){ +"use strict" - if(this.pointCount > 0) { - var shader = this.pointShader - shader.bind() - shader.uniforms = uniforms - - this.pointVAO.bind() - gl.drawArrays(gl.POINTS, 0, this.pointCount) - this.pointVAO.unbind() - } +var ch = require("incremental-convex-hull") +var uniq = require("uniq") - if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) { - var shader = this.contourShader - shader.bind() - shader.uniforms = uniforms +module.exports = triangulate - this.contourVAO.bind() - gl.drawArrays(gl.LINES, 0, this.contourCount) - this.contourVAO.unbind() - } +function LiftedPoint(p, i) { + this.point = p + this.index = i } -proto.drawPick = function(params) { - params = params || {} - - var gl = this.gl - - var model = params.model || identityMatrix - var view = params.view || identityMatrix - var projection = params.projection || identityMatrix - - var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]] - for(var i=0; i<3; ++i) { - clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]) - clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]) - } - - //Save camera parameters - this._model = [].slice.call(model) - this._view = [].slice.call(view) - this._projection = [].slice.call(projection) - this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight] - - var uniforms = { - model: model, - view: view, - projection: projection, - clipBounds: clipBounds, - pickId: this.pickId / 255.0, - } - - var shader = this.pickShader - shader.bind() - shader.uniforms = uniforms - - if(this.triangleCount > 0) { - this.triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) - this.triangleVAO.unbind() - } - - if(this.edgeCount > 0) { - this.edgeVAO.bind() - gl.lineWidth(this.lineWidth) - gl.drawArrays(gl.LINES, 0, this.edgeCount*2) - this.edgeVAO.unbind() - } - - if(this.pointCount > 0) { - var shader = this.pointPickShader - shader.bind() - shader.uniforms = uniforms - - this.pointVAO.bind() - gl.drawArrays(gl.POINTS, 0, this.pointCount) - this.pointVAO.unbind() +function compareLifted(a, b) { + var ap = a.point + var bp = b.point + var d = ap.length + for(var i=0; i= 2) { + return false + } + } + cell[j] = v + } + return true + }) + } else { + hull = hull.filter(function(cell) { + for(var i=0; i<=d; ++i) { + var v = dindex[cell[i]] + if(v < 0) { + return false + } + cell[i] = v + } + return true + }) + } -function reduce(x) { - var r = 0 - for(var i=0; i 0) { + return dupe_number(count|0, value) + } + break + case "object": + if(typeof (count.length) === "number") { + return dupe_array(count, value, 0) + } + break } - return y + return [] } -},{"robust-linear-solve":255}],255:[function(require,module,exports){ -arguments[4][51][0].apply(exports,arguments) -},{"dup":51,"robust-determinant":261}],256:[function(require,module,exports){ -arguments[4][52][0].apply(exports,arguments) -},{"dup":52}],257:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"dup":53}],258:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"dup":54,"two-product":260,"two-sum":257}],259:[function(require,module,exports){ -arguments[4][55][0].apply(exports,arguments) -},{"dup":55}],260:[function(require,module,exports){ -arguments[4][56][0].apply(exports,arguments) -},{"dup":56}],261:[function(require,module,exports){ -arguments[4][57][0].apply(exports,arguments) -},{"dup":57,"robust-compress":256,"robust-scale":258,"robust-sum":259,"two-product":260}],262:[function(require,module,exports){ -module.exports={ - "jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}], - - "hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}], - - "hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}], - "cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}], - - "spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}], +module.exports = dupe +},{}],116:[function(require,module,exports){ +(function (process,global){ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.1.2 + */ - "summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}], +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } - "autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}], + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } - "winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}], + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } - "bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}], + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } - "copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}], + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; - "greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}], + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } - "yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}], + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } - "greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}], + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } - "yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}], + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - "bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}], + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; - "rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}], + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; + } - "picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}], + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } - "rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}], + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); - "portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}], + return function() { + node.data = (iterations = ++iterations % 2); + }; + } - "blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}], + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } - "earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}], + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } - "electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; - "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}], + callback(arg); - "viridis": [{"index":0,"rgb":[68,1,84]},{"index":0.13,"rgb":[71,44,122]},{"index":0.25,"rgb":[59,81,139]},{"index":0.38,"rgb":[44,113,142]},{"index":0.5,"rgb":[33,144,141]},{"index":0.63,"rgb":[39,173,129]},{"index":0.75,"rgb":[92,200,99]},{"index":0.88,"rgb":[170,220,50]},{"index":1,"rgb":[253,231,37]}], + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } - "inferno": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[31,12,72]},{"index":0.25,"rgb":[85,15,109]},{"index":0.38,"rgb":[136,34,106]},{"index":0.5,"rgb":[186,54,85]},{"index":0.63,"rgb":[227,89,51]},{"index":0.75,"rgb":[249,140,10]},{"index":0.88,"rgb":[249,201,50]},{"index":1,"rgb":[252,255,164]}], + lib$es6$promise$asap$$len = 0; + } - "magma": [{"index":0,"rgb":[0,0,4]},{"index":0.13,"rgb":[28,16,68]},{"index":0.25,"rgb":[79,18,123]},{"index":0.38,"rgb":[129,37,129]},{"index":0.5,"rgb":[181,54,122]},{"index":0.63,"rgb":[229,80,100]},{"index":0.75,"rgb":[251,135,97]},{"index":0.88,"rgb":[254,194,135]},{"index":1,"rgb":[252,253,191]}], + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } - "plasma": [{"index":0,"rgb":[13,8,135]},{"index":0.13,"rgb":[75,3,161]},{"index":0.25,"rgb":[125,3,168]},{"index":0.38,"rgb":[168,34,150]},{"index":0.5,"rgb":[203,70,121]},{"index":0.63,"rgb":[229,107,93]},{"index":0.75,"rgb":[248,148,65]},{"index":0.88,"rgb":[253,195,40]},{"index":1,"rgb":[240,249,33]}], + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + function lib$es6$promise$then$$then(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; - "warm": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[172,0,187]},{"index":0.25,"rgb":[219,0,170]},{"index":0.38,"rgb":[255,0,130]},{"index":0.5,"rgb":[255,63,74]},{"index":0.63,"rgb":[255,123,0]},{"index":0.75,"rgb":[234,176,0]},{"index":0.88,"rgb":[190,228,0]},{"index":1,"rgb":[147,255,0]}], + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } - "cool": [{"index":0,"rgb":[125,0,179]},{"index":0.13,"rgb":[116,0,218]},{"index":0.25,"rgb":[98,74,237]},{"index":0.38,"rgb":[68,146,231]},{"index":0.5,"rgb":[0,204,197]},{"index":0.63,"rgb":[0,247,146]},{"index":0.75,"rgb":[0,255,88]},{"index":0.88,"rgb":[40,255,8]},{"index":1,"rgb":[147,255,0]}], + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; - "rainbow-soft": [{"index":0,"rgb":[125,0,179]},{"index":0.1,"rgb":[199,0,180]},{"index":0.2,"rgb":[255,0,121]},{"index":0.3,"rgb":[255,108,0]},{"index":0.4,"rgb":[222,194,0]},{"index":0.5,"rgb":[150,255,0]},{"index":0.6,"rgb":[0,255,55]},{"index":0.7,"rgb":[0,246,150]},{"index":0.8,"rgb":[50,167,222]},{"index":0.9,"rgb":[103,51,235]},{"index":1,"rgb":[124,0,186]}], + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } - "bathymetry": [{"index":0,"rgb":[40,26,44]},{"index":0.13,"rgb":[59,49,90]},{"index":0.25,"rgb":[64,76,139]},{"index":0.38,"rgb":[63,110,151]},{"index":0.5,"rgb":[72,142,158]},{"index":0.63,"rgb":[85,174,163]},{"index":0.75,"rgb":[120,206,163]},{"index":0.88,"rgb":[187,230,172]},{"index":1,"rgb":[253,254,204]}], + return child; + } + var lib$es6$promise$then$$default = lib$es6$promise$then$$then; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; - "cdom": [{"index":0,"rgb":[47,15,62]},{"index":0.13,"rgb":[87,23,86]},{"index":0.25,"rgb":[130,28,99]},{"index":0.38,"rgb":[171,41,96]},{"index":0.5,"rgb":[206,67,86]},{"index":0.63,"rgb":[230,106,84]},{"index":0.75,"rgb":[242,149,103]},{"index":0.88,"rgb":[249,193,135]},{"index":1,"rgb":[254,237,176]}], + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } - "chlorophyll": [{"index":0,"rgb":[18,36,20]},{"index":0.13,"rgb":[25,63,41]},{"index":0.25,"rgb":[24,91,59]},{"index":0.38,"rgb":[13,119,72]},{"index":0.5,"rgb":[18,148,80]},{"index":0.63,"rgb":[80,173,89]},{"index":0.75,"rgb":[132,196,122]},{"index":0.88,"rgb":[175,221,162]},{"index":1,"rgb":[215,249,208]}], + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - "density": [{"index":0,"rgb":[54,14,36]},{"index":0.13,"rgb":[89,23,80]},{"index":0.25,"rgb":[110,45,132]},{"index":0.38,"rgb":[120,77,178]},{"index":0.5,"rgb":[120,113,213]},{"index":0.63,"rgb":[115,151,228]},{"index":0.75,"rgb":[134,185,227]},{"index":0.88,"rgb":[177,214,227]},{"index":1,"rgb":[230,241,241]}], + function lib$es6$promise$$internal$$noop() {} - "freesurface-blue": [{"index":0,"rgb":[30,4,110]},{"index":0.13,"rgb":[47,14,176]},{"index":0.25,"rgb":[41,45,236]},{"index":0.38,"rgb":[25,99,212]},{"index":0.5,"rgb":[68,131,200]},{"index":0.63,"rgb":[114,156,197]},{"index":0.75,"rgb":[157,181,203]},{"index":0.88,"rgb":[200,208,216]},{"index":1,"rgb":[241,237,236]}], + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; - "freesurface-red": [{"index":0,"rgb":[60,9,18]},{"index":0.13,"rgb":[100,17,27]},{"index":0.25,"rgb":[142,20,29]},{"index":0.38,"rgb":[177,43,27]},{"index":0.5,"rgb":[192,87,63]},{"index":0.63,"rgb":[205,125,105]},{"index":0.75,"rgb":[216,162,148]},{"index":0.88,"rgb":[227,199,193]},{"index":1,"rgb":[241,237,236]}], + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - "oxygen": [{"index":0,"rgb":[64,5,5]},{"index":0.13,"rgb":[106,6,15]},{"index":0.25,"rgb":[144,26,7]},{"index":0.38,"rgb":[168,64,3]},{"index":0.5,"rgb":[188,100,4]},{"index":0.63,"rgb":[206,136,11]},{"index":0.75,"rgb":[220,174,25]},{"index":0.88,"rgb":[231,215,44]},{"index":1,"rgb":[248,254,105]}], + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } - "par": [{"index":0,"rgb":[51,20,24]},{"index":0.13,"rgb":[90,32,35]},{"index":0.25,"rgb":[129,44,34]},{"index":0.38,"rgb":[159,68,25]},{"index":0.5,"rgb":[182,99,19]},{"index":0.63,"rgb":[199,134,22]},{"index":0.75,"rgb":[212,171,35]},{"index":0.88,"rgb":[221,210,54]},{"index":1,"rgb":[225,253,75]}], + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } - "phase": [{"index":0,"rgb":[145,105,18]},{"index":0.13,"rgb":[184,71,38]},{"index":0.25,"rgb":[186,58,115]},{"index":0.38,"rgb":[160,71,185]},{"index":0.5,"rgb":[110,97,218]},{"index":0.63,"rgb":[50,123,164]},{"index":0.75,"rgb":[31,131,110]},{"index":0.88,"rgb":[77,129,34]},{"index":1,"rgb":[145,105,18]}], + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } - "salinity": [{"index":0,"rgb":[42,24,108]},{"index":0.13,"rgb":[33,50,162]},{"index":0.25,"rgb":[15,90,145]},{"index":0.38,"rgb":[40,118,137]},{"index":0.5,"rgb":[59,146,135]},{"index":0.63,"rgb":[79,175,126]},{"index":0.75,"rgb":[120,203,104]},{"index":0.88,"rgb":[193,221,100]},{"index":1,"rgb":[253,239,154]}], + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } - "temperature": [{"index":0,"rgb":[4,35,51]},{"index":0.13,"rgb":[23,51,122]},{"index":0.25,"rgb":[85,59,157]},{"index":0.38,"rgb":[129,79,143]},{"index":0.5,"rgb":[175,95,130]},{"index":0.63,"rgb":[222,112,101]},{"index":0.75,"rgb":[249,146,66]},{"index":0.88,"rgb":[249,196,65]},{"index":1,"rgb":[232,250,91]}], + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; - "turbidity": [{"index":0,"rgb":[34,31,27]},{"index":0.13,"rgb":[65,50,41]},{"index":0.25,"rgb":[98,69,52]},{"index":0.38,"rgb":[131,89,57]},{"index":0.5,"rgb":[161,112,59]},{"index":0.63,"rgb":[185,140,66]},{"index":0.75,"rgb":[202,174,88]},{"index":0.88,"rgb":[216,209,126]},{"index":1,"rgb":[233,246,171]}], + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); - "velocity-blue": [{"index":0,"rgb":[17,32,64]},{"index":0.13,"rgb":[35,52,116]},{"index":0.25,"rgb":[29,81,156]},{"index":0.38,"rgb":[31,113,162]},{"index":0.5,"rgb":[50,144,169]},{"index":0.63,"rgb":[87,173,176]},{"index":0.75,"rgb":[149,196,189]},{"index":0.88,"rgb":[203,221,211]},{"index":1,"rgb":[254,251,230]}], + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } - "velocity-green": [{"index":0,"rgb":[23,35,19]},{"index":0.13,"rgb":[24,64,38]},{"index":0.25,"rgb":[11,95,45]},{"index":0.38,"rgb":[39,123,35]},{"index":0.5,"rgb":[95,146,12]},{"index":0.63,"rgb":[152,165,18]},{"index":0.75,"rgb":[201,186,69]},{"index":0.88,"rgb":[233,216,137]},{"index":1,"rgb":[255,253,205]}], + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } - "cubehelix": [{"index":0,"rgb":[0,0,0]},{"index":0.07,"rgb":[22,5,59]},{"index":0.13,"rgb":[60,4,105]},{"index":0.2,"rgb":[109,1,135]},{"index":0.27,"rgb":[161,0,147]},{"index":0.33,"rgb":[210,2,142]},{"index":0.4,"rgb":[251,11,123]},{"index":0.47,"rgb":[255,29,97]},{"index":0.53,"rgb":[255,54,69]},{"index":0.6,"rgb":[255,85,46]},{"index":0.67,"rgb":[255,120,34]},{"index":0.73,"rgb":[255,157,37]},{"index":0.8,"rgb":[241,191,57]},{"index":0.87,"rgb":[224,220,93]},{"index":0.93,"rgb":[218,241,142]},{"index":1,"rgb":[227,253,198]}] -}; + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === lib$es6$promise$then$$default && + constructor.resolve === lib$es6$promise$promise$resolve$$default) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } -},{}],263:[function(require,module,exports){ -/* - * Ben Postlethwaite - * January 2013 - * License MIT - */ -'use strict'; + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } -var at = require('arraytools'); -var clone = require('clone'); -var colorScale = require('./colorScales'); + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } -module.exports = createColormap; + lib$es6$promise$$internal$$publish(promise); + } -function createColormap (spec) { - /* - * Default Options - */ - var indicies, rgba, fromrgba, torgba, - nsteps, cmap, colormap, format, - nshades, colors, alpha, index, i, - r = [], - g = [], - b = [], - a = []; + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - if ( !at.isPlainObject(spec) ) spec = {}; + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; - nshades = spec.nshades || 72; - format = spec.format || 'hex'; + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } - colormap = spec.colormap; - if (!colormap) colormap = 'jet'; + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; - if (typeof colormap === 'string') { - colormap = colormap.toLowerCase(); + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } - if (!colorScale[colormap]) { - throw Error(colormap + ' not a supported colorscale'); - } + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; - cmap = clone(colorScale[colormap]); + parent._onerror = null; - } else if (Array.isArray(colormap)) { - cmap = clone(colormap); + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - } else { - throw Error('unsupported colormap option', colormap); + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } } - if (cmap.length > nshades) { - throw new Error( - colormap+' map requires nshades to be at least size '+cmap.length - ); - } + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; - if (!Array.isArray(spec.alpha)) { + if (subscribers.length === 0) { return; } - if (typeof spec.alpha === 'number') { - alpha = [spec.alpha, spec.alpha]; + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); } else { - alpha = [1, 1]; + callback(detail); } + } - } else if (spec.alpha.length !== 2) { - alpha = [1, 1]; - - } else { - alpha = clone(spec.alpha); + promise._subscribers.length = 0; } - /* - * map index points from 0->1 to 0 -> n-1 - */ - indicies = cmap.map(function(c) { - return Math.round(c.index * nshades); - }); - - /* - * Add alpha channel to the map - */ - if (alpha[0] < 0) alpha[0] = 0; - if (alpha[1] < 0) alpha[0] = 0; - if (alpha[0] > 1) alpha[0] = 1; - if (alpha[1] > 1) alpha[0] = 1; - - for (i = 0; i < indicies.length; ++i) { - index = cmap[i].index; - rgba = cmap[i].rgb; - - // if user supplies their own map use it - if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue; - rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index; + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; } - /* - * map increasing linear values between indicies to - * linear steps in colorvalues - */ - for (i = 0; i < indicies.length-1; ++i) { - nsteps = indicies[i+1] - indicies[i]; - fromrgba = cmap[i].rgb; - torgba = cmap[i+1].rgb; - r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) ); - g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) ); - b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) ); - a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) ); + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } } - r = r.map( Math.round ); - g = g.map( Math.round ); - b = b.map( Math.round ); + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; - colors = at.zip(r, g, b, a); + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); - if (format === 'hex') colors = colors.map( rgb2hex ); - if (format === 'rgbaString') colors = colors.map( rgbaStr ); + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } - return colors; -}; + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } -function rgb2hex (rgba) { - var dig, hex = '#'; - for (var i = 0; i < 3; ++i) { - dig = rgba[i]; - dig = dig.toString(16); - hex += ('00' + dig).substr( dig.length ); + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } } - return hex; -} -function rgbaStr (rgba) { - return 'rgba(' + rgba.join(',') + ')'; -} + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } -},{"./colorScales":262,"arraytools":64,"clone":264}],264:[function(require,module,exports){ -(function (Buffer){ -var clone = (function() { -'use strict'; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; -/** - * Clones (copies) an Object using deep copying. - * - * This function supports circular references by default, but if you are certain - * there are no circular references in your object, you can save some CPU time - * by calling clone(obj, false). - * - * Caution: if `circular` is false and `parent` contains circular references, - * your program may enter an infinite loop and crash. - * - * @param `parent` - the object to be cloned - * @param `circular` - set to true if the object to be cloned may contain - * circular references. (optional - true by default) - * @param `depth` - set to a number if the object is only to be cloned to - * a particular depth. (optional - defaults to Infinity) - * @param `prototype` - sets the prototype to be used when cloning an object. - * (optional - defaults to parent prototype). -*/ -function clone(parent, circular, depth, prototype) { - var filter; - if (typeof circular === 'object') { - depth = circular.depth; - prototype = circular.prototype; - filter = circular.filter; - circular = circular.circular - } - // maintain two arrays for circular references, where corresponding parents - // and children have the same index - var allParents = []; - var allChildren = []; + var promise = new Constructor(lib$es6$promise$$internal$$noop); - var useBuffer = typeof Buffer != 'undefined'; + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } - if (typeof circular == 'undefined') - circular = true; + var length = entries.length; - if (typeof depth == 'undefined') - depth = Infinity; + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } - // recurse this function so we don't reset allParents and allChildren - function _clone(parent, depth) { - // cloning null always returns null - if (parent === null) - return null; + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } - if (depth == 0) - return parent; + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } - var child; - var proto; - if (typeof parent != 'object') { - return parent; + return promise; } - - if (clone.__isArray(parent)) { - child = []; - } else if (clone.__isRegExp(parent)) { - child = new RegExp(parent.source, __getRegExpFlags(parent)); - if (parent.lastIndex) child.lastIndex = parent.lastIndex; - } else if (clone.__isDate(parent)) { - child = new Date(parent.getTime()); - } else if (useBuffer && Buffer.isBuffer(parent)) { - child = new Buffer(parent.length); - parent.copy(child); - return child; - } else { - if (typeof prototype == 'undefined') { - proto = Object.getPrototypeOf(parent); - child = Object.create(proto); - } - else { - child = Object.create(prototype); - proto = prototype; - } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - if (circular) { - var index = allParents.indexOf(parent); + var lib$es6$promise$promise$$counter = 0; - if (index != -1) { - return allChildren[index]; - } - allParents.push(parent); - allChildren.push(child); + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); - } - - if (attrs && attrs.set == null) { - continue; - } - child[i] = _clone(parent[i], depth - 1); + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } - return child; - } + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. - return _clone(parent, depth); -} + Terminology + ----------- -/** - * Simple flat clone using prototype, accepts only objects, usefull for property - * override on FLAT configuration object (no nested props). - * - * USE WITH CAUTION! This may not behave as you wish if you do not know how this - * works. - */ -clone.clonePrototype = function clonePrototype(parent) { - if (parent === null) - return null; + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. - var c = function () {}; - c.prototype = parent; - return new c(); -}; + A promise can be in one of three states: pending, fulfilled, or rejected. -// private utility functions + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. -function __objToStr(o) { - return Object.prototype.toString.call(o); -}; -clone.__objToStr = __objToStr; + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. -function __isDate(o) { - return typeof o === 'object' && __objToStr(o) === '[object Date]'; -}; -clone.__isDate = __isDate; -function __isArray(o) { - return typeof o === 'object' && __objToStr(o) === '[object Array]'; -}; -clone.__isArray = __isArray; + Basic Usage: + ------------ -function __isRegExp(o) { - return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; -}; -clone.__isRegExp = __isRegExp; + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); -function __getRegExpFlags(re) { - var flags = ''; - if (re.global) flags += 'g'; - if (re.ignoreCase) flags += 'i'; - if (re.multiline) flags += 'm'; - return flags; -}; -clone.__getRegExpFlags = __getRegExpFlags; + // on failure + reject(reason); + }); -return clone; -})(); + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` -if (typeof module === 'object' && module.exports) { - module.exports = clone; -} + Advanced Usage: + --------------- -}).call(this,require("buffer").Buffer) -},{"buffer":65}],265:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":306}],266:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":267,"./lib/create-attributes":268,"./lib/create-uniforms":269,"./lib/reflect":270,"./lib/runtime-reflect":271,"./lib/shader-cache":272,"dup":94}],267:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],268:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":267,"dup":96}],269:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":267,"./reflect":270,"dup":97}],270:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],271:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],272:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":267,"dup":100,"gl-format-compiler-error":273,"weakmap-shim":291}],273:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":274,"dup":101,"gl-constants/lookup":278,"glsl-shader-name":279,"sprintf-js":288}],274:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":275}],275:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":276}],276:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],277:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],278:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":277,"dup":106}],279:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":280,"dup":107,"glsl-tokenizer":287}],280:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],281:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":283,"./lib/builtins-300es":282,"./lib/literals":285,"./lib/literals-300es":284,"./lib/operators":286,"dup":109}],282:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":283,"dup":110}],283:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],284:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":285,"dup":112}],285:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],286:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],287:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":281,"dup":115}],288:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],289:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":290,"dup":117}],290:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],291:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":289,"dup":119}],292:[function(require,module,exports){ -arguments[4][188][0].apply(exports,arguments) -},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":306}],293:[function(require,module,exports){ -arguments[4][154][0].apply(exports,arguments) -},{"dup":154}],294:[function(require,module,exports){ -arguments[4][155][0].apply(exports,arguments) -},{"./do-bind.js":293,"dup":155}],295:[function(require,module,exports){ -arguments[4][156][0].apply(exports,arguments) -},{"./do-bind.js":293,"dup":156}],296:[function(require,module,exports){ -arguments[4][157][0].apply(exports,arguments) -},{"./lib/vao-emulated.js":294,"./lib/vao-native.js":295,"dup":157}],297:[function(require,module,exports){ -var DEFAULT_NORMALS_EPSILON = 1e-6; -var DEFAULT_FACE_EPSILON = 1e-6; + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. -//Estimate the vertex normals of a mesh -exports.vertexNormals = function(faces, positions, specifiedEpsilon) { + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); - var N = positions.length; - var normals = new Array(N); - var epsilon = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon; + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); - //Initialize normal array - for(var i=0; i postsJSON + values[1] // => commentsJSON - //Compute infineteismal arcs - var d01 = new Array(3); - var m01 = 0.0; - var d21 = new Array(3); - var m21 = 0.0; - for(var k=0; k<3; ++k) { - d01[k] = v0[k] - v1[k]; - m01 += d01[k] * d01[k]; - d21[k] = v2[k] - v1[k]; - m21 += d21[k] * d21[k]; - } + return values; + }); + ``` - //Accumulate values in normal - if(m01 * m21 > epsilon) { - var norm = normals[c]; - var w = 1.0 / Math.sqrt(m01 * m21); - for(var k=0; k<3; ++k) { - var u = (k+1)%3; - var v = (k+2)%3; - norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); - } - } - } - } + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; - //Scale all normals to unit length - for(var i=0; i epsilon) { - var w = 1.0 / Math.sqrt(m); - for(var k=0; k<3; ++k) { - norm[k] *= w; - } - } else { - for(var k=0; k<3; ++k) { - norm[k] = 0.0; + if (lib$es6$promise$$internal$$noop !== resolver) { + typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); + this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); } } - } - //Return the resulting set of patches - return normals; -} + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; -//Compute face normals of a mesh -exports.faceNormals = function(faces, positions, specifiedEpsilon) { + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, - var N = faces.length; - var normals = new Array(N); - var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon; + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. - for(var i=0; i epsilon) { - l = 1.0 / Math.sqrt(l); - } else { - l = 0.0; - } - for(var j=0; j<3; ++j) { - n[j] *= l; - } - normals[i] = n; - } - return normals; -} + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + Synchronous Example + ```javascript + var result; -},{}],298:[function(require,module,exports){ -//Optimized version for triangle closest point -// Based on Eberly's WildMagick codes -// http://www.geometrictools.com/LibMathematics/Distance/Distance.html -"use strict"; + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` -var diff = new Float64Array(4); -var edge0 = new Float64Array(4); -var edge1 = new Float64Array(4); + Errback Example -function closestPoint2d(V0, V1, V2, point, result) { - //Reallocate buffers if necessary - if(diff.length < point.length) { - diff = new Float64Array(point.length); - edge0 = new Float64Array(point.length); - edge1 = new Float64Array(point.length); - } - //Compute edges - for(var i=0; i= a00) { - s = 1.0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } else { - s = 0; - if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else if (-b1 >= a11) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } - } - } else { // region 3 - s = 0; - if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else if (-b1 >= a11) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; + ```js + findResult(function(result, err){ + if (err) { + // failure } else { - t = -b1/a11; - sqrDistance = b1*t + c; + // success } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure } - } else if (t < 0) { // region 5 - t = 0; - if (b0 >= 0) { - s = 0; - sqrDistance = c; - } else if (-b0 >= a00) { - s = 1; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } - } else { // region 0 - // minimum at interior point - var invDet = 1.0 / det; - s *= invDet; - t *= invDet; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - var tmp0, tmp1, numer, denom; - - if (s < 0) { // region 2 - tmp0 = a01 + b0; - tmp1 = a11 + b1; - if (tmp1 > tmp0) { - numer = tmp1 - tmp0; - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - s = 1; - t = 0; - sqrDistance = a00 + 2.0*b0 + c; - } else { - s = numer/denom; - t = 1 - s; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - s = 0; - if (tmp1 <= 0) { - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else if (b1 >= 0) { - t = 0; - sqrDistance = c; - } else { - t = -b1/a11; - sqrDistance = b1*t + c; - } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + } - } else if (t < 0) { // region 6 - tmp0 = a01 + b1; - tmp1 = a00 + b0; - if (tmp1 > tmp0) { - numer = tmp1 - tmp0; - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - t = 1; - s = 0; - sqrDistance = a11 + 2.0*b1 + c; - } else { - t = numer/denom; - s = 1 - t; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; - } - } else { - t = 0; - if (tmp1 <= 0) { - s = 1; - sqrDistance = a00 + 2.0*b0 + c; - } else if (b0 >= 0) { - s = 0; - sqrDistance = c; - } else { - s = -b0/a00; - sqrDistance = b0*s + c; - } + + function failure(reason) { + } - } else { // region 1 - numer = a11 + b1 - a01 - b0; - if (numer <= 0) { - s = 0; - t = 1; - sqrDistance = a11 + 2.0*b1 + c; - } else { - denom = a00 - 2.0*a01 + a11; - if (numer >= denom) { - s = 1; - t = 0; - sqrDistance = a00 + 2.0*b0 + c; + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure } else { - s = numer/denom; - t = 1 - s; - sqrDistance = s*(a00*s + a01*t + 2.0*b0) + - t*(a01*s + a11*t + 2.0*b1) + c; + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success } - } - } - } - var u = 1.0 - s - t; - for(var i=0; i>1,v=E[2*m+1];', - 'if(v===b){return m}', - 'if(b 0) { - code.push(',') - } - code.push('[') - for(var j=0; j 0) { - code.push(',') - } - code.push('B(C,E,c[', f[0], '],c[', f[1], '])') + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } } - code.push(']') - } - code.push(');') - } - for(var i=d+1; i>1; --i) { - if(i < d+1) { - code.push('else ') - } - code.push('if(l===', i, '){') + var P = local.Promise; - //Generate mask - var maskStr = [] - for(var j=0; j + * but significantly simplified and sped up by ignoring number and string constructors + * ie these return false: + * new Number(1) + * new String('1') + */ -var chull = require('convex-hull') +'use strict'; -function constructVertex(d, a, b) { - var x = new Array(d) - for(var i=0; i 13) && (a !== 32) && (a !== 133) && (a !== 160) && + (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) && + (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) && + (a !== 8288) && (a !== 12288) && (a !== 65279)) { + return false; + } } - } - return x + return true; } -function constructCell(dimension, mask) { - if(mask === 0 || mask === (1<<(dimension+1))-1) { - return [] - } - var points = [] - var index = [] - for(var i=0; i<=dimension; ++i) { - if(mask & (1< 1) { - var scratch_shape = [] - for(var i=1; i 1) { - - //Copy data into scratch - code.push("dptr=0;sptr=ptr") - for(var i=order.length-1; i>=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"left){", - "dptr=0", - "sptr=cptr-s0") - for(var i=1; ib){break __l}"].join("")) - for(var i=order.length-1; i>=1; --i) { - code.push( - "sptr+=e"+i, - "dptr+=f"+i, - "}") - } - - //Copy data back - code.push("dptr=cptr;sptr=cptr-s0") - for(var i=order.length-1; i>=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j,"left)&&("+dataRead("cptr-s0")+">scratch)){", - dataWrite("cptr", dataRead("cptr-s0")), - "cptr-=s0", - "}", - dataWrite("cptr", "scratch")) - } - - //Close outer loop body - code.push("}") - if(order.length > 1 && allocator) { - code.push("free(scratch)") - } - code.push("} return " + funcName) - - //Compile and link function - if(allocator) { - var result = new Function("malloc", "free", code.join("\n")) - return result(allocator[0], allocator[1]) - } else { - var result = new Function(code.join("\n")) - return result() - } +proto.dispose = function() { + this.gl.deleteBuffer(this.handle) } -function createQuickSort(order, dtype, insertionSort) { - var code = [ "'use strict'" ] - var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("") - var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length)) - var allocator = getMallocFree(dtype) - var labelCounter=0 - - code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) - - var vars = [ - "sixth=((right-left+1)/6)|0", - "index1=left+sixth", - "index5=right-sixth", - "index3=(left+right)>>1", - "index2=index3-sixth", - "index4=index3+sixth", - "el1=index1", - "el2=index2", - "el3=index3", - "el4=index4", - "el5=index5", - "less=left+1", - "great=right-1", - "pivots_are_equal=true", - "tmp", - "tmp0", - "x", - "y", - "z", - "k", - "ptr0", - "ptr1", - "ptr2", - "comp_pivot1=0", - "comp_pivot2=0", - "comp=0" - ] - - if(order.length > 1) { - var ele_size = [] - for(var i=1; i len) { + throw new Error("gl-buffer: If resizing buffer, must not specify offset") } - - //Initialize local variables - code.push("var " + vars.join(",")) - - function toPointer(v) { - return ["(offset+",v,"*s0)"].join("") + gl.bufferSubData(type, offset, data) + return len +} + +function makeScratchTypeArray(array, dtype) { + var res = pool.malloc(array.length, dtype) + var n = array.length + for(var i=0; i=0; --i) { + if(stride[i] !== n) { + return false } - return ["data[",ptr,"]"].join("") + n *= shape[i] } - - function dataWrite(ptr, v) { - if(dtype === "generic") { - return ["data.set(", ptr, ",", v, ")"].join("") - } - return ["data[",ptr,"]=",v].join("") + return true +} + +proto.update = function(array, offset) { + if(typeof offset !== "number") { + offset = -1 } - - function cacheLoop(ptrs, usePivot, body) { - if(ptrs.length === 1) { - code.push("ptr0="+toPointer(ptrs[0])) - } else { - for(var i=0; i=0; --i) { - var j = order[i] - if(j === 0) { - continue - } - code.push(["for(i",j,"=0;i",j," 1) { - for(var i=0; i1) { - code.push("ptr_shift+=d"+j) + if(dtype === array.dtype && isPacked(array.shape, array.stride)) { + if(array.offset === 0 && array.data.length === array.shape[0]) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset) } else { - code.push("ptr0+=d"+j) + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset) } - code.push("}") - } - } - - function lexicoLoop(label, ptrs, usePivot, body) { - if(ptrs.length === 1) { - code.push("ptr0="+toPointer(ptrs[0])) } else { - for(var i=0; i 1) { - for(var i=0; i=1; --i) { - if(usePivot) { - code.push("pivot_ptr+=f"+i) - } - if(ptrs.length > 1) { - code.push("ptr_shift+=e"+i) + var tmp = pool.malloc(array.size, dtype) + var ndt = ndarray(tmp, array.shape) + ops.assign(ndt, array) + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset) } else { - code.push("ptr0+=e"+i) + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset) } - code.push("}") - } - } - - function cleanUp() { - if(order.length > 1 && allocator) { - code.push("free(pivot1)", "free(pivot2)") + pool.free(tmp) } - } - - function compareSwap(a_id, b_id) { - var a = "el"+a_id - var b = "el"+b_id - if(order.length > 1) { - var lbl = "__l" + (++labelCounter) - lexicoLoop(lbl, [a, b], false, [ - "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n", - "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n", - "if(comp<0){break ", lbl, "}" - ].join("")) + } else if(Array.isArray(array)) { //Vanilla array + var t + if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) { + t = makeScratchTypeArray(array, "uint16") } else { - code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join("")) + t = makeScratchTypeArray(array, "float32") } - } - - compareSwap(1, 2) - compareSwap(4, 5) - compareSwap(1, 3) - compareSwap(2, 3) - compareSwap(1, 4) - compareSwap(3, 4) - compareSwap(2, 5) - compareSwap(2, 3) - compareSwap(4, 5) - - if(order.length > 1) { - cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [ - "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n", - "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n", - "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n", - "x=",dataRead("ptr0"),"\n", - "y=",dataRead("ptr2"),"\n", - "z=",dataRead("ptr4"),"\n", - dataWrite("ptr5", "x"),"\n", - dataWrite("ptr6", "y"),"\n", - dataWrite("ptr7", "z") - ].join("")) - } else { - code.push([ - "pivot1=", dataRead(toPointer("el2")), "\n", - "pivot2=", dataRead(toPointer("el4")), "\n", - "pivots_are_equal=pivot1===pivot2\n", - "x=", dataRead(toPointer("el1")), "\n", - "y=", dataRead(toPointer("el3")), "\n", - "z=", dataRead(toPointer("el5")), "\n", - dataWrite(toPointer("index1"), "x"), "\n", - dataWrite(toPointer("index3"), "y"), "\n", - dataWrite(toPointer("index5"), "z") - ].join("")) - } - - - function moveElement(dst, src) { - if(order.length > 1) { - cacheLoop([dst, src], false, - dataWrite("ptr0", dataRead("ptr1")) - ) + if(offset < 0) { + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset) } else { - code.push(dataWrite(toPointer(dst), dataRead(toPointer(src)))) + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset) } - } - - moveElement("index2", "left") - moveElement("index4", "right") - - function comparePivot(result, ptr, n) { - if(order.length > 1) { - var lbl = "__l" + (++labelCounter) - lexicoLoop(lbl, [ptr], true, [ - result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n", - "if(",result,"!==0){break ", lbl, "}" - ].join("")) - } else { - code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join("")) + pool.free(t) + } else if(typeof array === "object" && typeof array.length === "number") { //Typed array + this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset) + } else if(typeof array === "number" || array === undefined) { //Number/default + if(offset >= 0) { + throw new Error("gl-buffer: Cannot specify offset when resizing buffer") } - } - - function swapElements(a, b) { - if(order.length > 1) { - cacheLoop([a,b],false,[ - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", "tmp") - ].join("")) - } else { - code.push([ - "ptr0=",toPointer(a),"\n", - "ptr1=",toPointer(b),"\n", - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", "tmp") - ].join("")) + array = array | 0 + if(array <= 0) { + array = 1 } + this.gl.bufferData(this.type, array|0, this.usage) + this.length = array + } else { //Error, case should not happen + throw new Error("gl-buffer: Invalid data type") } - - function tripleSwap(k, less, great) { - if(order.length > 1) { - cacheLoop([k,less,great], false, [ - "tmp=",dataRead("ptr0"),"\n", - dataWrite("ptr0", dataRead("ptr1")),"\n", - dataWrite("ptr1", dataRead("ptr2")),"\n", - dataWrite("ptr2", "tmp") - ].join("")) - code.push("++"+less, "--"+great) - } else { - code.push([ - "ptr0=",toPointer(k),"\n", - "ptr1=",toPointer(less),"\n", - "ptr2=",toPointer(great),"\n", - "++",less,"\n", - "--",great,"\n", - "tmp=", dataRead("ptr0"), "\n", - dataWrite("ptr0", dataRead("ptr1")), "\n", - dataWrite("ptr1", dataRead("ptr2")), "\n", - dataWrite("ptr2", "tmp") - ].join("")) - } +} + +function createBuffer(gl, data, type, usage) { + type = type || gl.ARRAY_BUFFER + usage = usage || gl.DYNAMIC_DRAW + if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) { + throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER") } - - function swapAndDecrement(k, great) { - swapElements(k, great) - code.push("--"+great) + if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) { + throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW") } - - code.push("if(pivots_are_equal){") - //Pivots are equal case - code.push("for(k=less;k<=great;++k){") - comparePivot("comp", "k", 1) - code.push("if(comp===0){continue}") - code.push("if(comp<0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - code.push("while(true){") - comparePivot("comp", "great", 1) - code.push("if(comp>0){") - code.push("great--") - code.push("}else if(comp<0){") - tripleSwap("k", "less", "great") - code.push("break") - code.push("}else{") - swapAndDecrement("k", "great") - code.push("break") - code.push("}") - code.push("}") - code.push("}") - code.push("}") - code.push("}else{") - //Pivots not equal case - code.push("for(k=less;k<=great;++k){") - comparePivot("comp_pivot1", "k", 1) - code.push("if(comp_pivot1<0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - comparePivot("comp_pivot2", "k", 2) - code.push("if(comp_pivot2>0){") - code.push("while(true){") - comparePivot("comp", "great", 2) - code.push("if(comp>0){") - code.push("if(--great1) { - cacheLoop([mem_dest, pivot_dest], true, [ - dataWrite("ptr0", dataRead("ptr1")), "\n", - dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join("")) - ].join("")) - } else { - code.push( - dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))), - dataWrite(toPointer(pivot_dest), "pivot"+pivot)) + var handle = gl.createBuffer() + var result = new GLBuffer(gl, type, handle, 0, usage) + result.update(data) + return result +} + +module.exports = createBuffer + +},{"ndarray":253,"ndarray-ops":252,"typedarray-pool":278}],119:[function(require,module,exports){ +'use strict' + +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var pool = require('typedarray-pool') +var shaders = require('./lib/shaders') + +module.exports = createError2D + +var WEIGHTS = [ + // x-error bar + [1, 0, 0, 1, 0, 0], + [1, 0, 0, -1, 0, 0], + [-1, 0, 0, -1, 0, 0], + + [-1, 0, 0, -1, 0, 0], + [-1, 0, 0, 1, 0, 0], + [1, 0, 0, 1, 0, 0], + + // x-error right cap + [1, 0, -1, 0, 0, 1], + [1, 0, -1, 0, 0, -1], + [1, 0, 1, 0, 0, -1], + + [1, 0, 1, 0, 0, -1], + [1, 0, 1, 0, 0, 1], + [1, 0, -1, 0, 0, 1], + + // x-error left cap + [-1, 0, -1, 0, 0, 1], + [-1, 0, -1, 0, 0, -1], + [-1, 0, 1, 0, 0, -1], + + [-1, 0, 1, 0, 0, -1], + [-1, 0, 1, 0, 0, 1], + [-1, 0, -1, 0, 0, 1], + + // y-error bar + [0, 1, 1, 0, 0, 0], + [0, 1, -1, 0, 0, 0], + [0, -1, -1, 0, 0, 0], + + [0, -1, -1, 0, 0, 0], + [0, 1, 1, 0, 0, 0], + [0, -1, 1, 0, 0, 0], + + // y-error top cap + [0, 1, 0, -1, 1, 0], + [0, 1, 0, -1, -1, 0], + [0, 1, 0, 1, -1, 0], + + [0, 1, 0, 1, 1, 0], + [0, 1, 0, -1, 1, 0], + [0, 1, 0, 1, -1, 0], + + // y-error bottom cap + [0, -1, 0, -1, 1, 0], + [0, -1, 0, -1, -1, 0], + [0, -1, 0, 1, -1, 0], + + [0, -1, 0, 1, 1, 0], + [0, -1, 0, -1, 1, 0], + [0, -1, 0, 1, -1, 0] +] + +function GLError2D (plot, shader, buffer) { + this.plot = plot + + this.shader = shader + this.buffer = buffer + + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + + this.numPoints = 0 + + this.color = [0, 0, 0, 1] +} + +var proto = GLError2D.prototype + +proto.draw = (function () { + var MATRIX = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + + var PIXEL_SCALE = [1, 1] + + return function () { + var plot = this.plot + var shader = this.shader + var buffer = this.buffer + var bounds = this.bounds + var numPoints = this.numPoints + + if (!numPoints) { + return } - } - - storePivot("left", "(less-1)", 1) - storePivot("right", "(great+1)", 2) - //Recursive sort call - function doSort(left, right) { - code.push([ - "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n", - "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", - "}else{\n", - funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", - "}" - ].join("")) + var gl = plot.gl + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + + MATRIX[0] = 2.0 * boundX / dataX + MATRIX[4] = 2.0 * boundY / dataY + MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 + MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + + var screenX = viewBox[2] - viewBox[0] + var screenY = viewBox[3] - viewBox[1] + + PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX + PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY + + buffer.bind() + shader.bind() + + shader.uniforms.viewTransform = MATRIX + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.color = this.color + + shader.attributes.position.pointer( + gl.FLOAT, + false, + 16, + 0) + + shader.attributes.pixelOffset.pointer( + gl.FLOAT, + false, + 16, + 8) + + gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length) } - doSort("left", "(less-2)") - doSort("(great+2)", "right") - - //If pivots are equal, then early out - code.push("if(pivots_are_equal){") - cleanUp() - code.push("return") - code.push("}") - - function walkPointer(ptr, pivot, body) { - if(order.length > 1) { - code.push(["__l",++labelCounter,":while(true){"].join("")) - cacheLoop([ptr], true, [ - "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}" - ].join("")) - code.push(body, "}") - } else { - code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join("")) - } +})() + +proto.drawPick = function (offset) { return offset } +proto.pick = function (x, y) { + return null +} + +proto.update = function (options) { + options = options || {} + + var i, x, y + + var positions = options.positions || [] + var errors = options.errors || [] + + var lineWidth = 1 + if ('lineWidth' in options) { + lineWidth = +options.lineWidth } - - //Check bounds - code.push("if(lessindex5){") - - walkPointer("less", 1, "++less") - walkPointer("great", 2, "--great") - - code.push("for(k=less;k<=great;++k){") - comparePivot("comp_pivot1", "k", 1) - code.push("if(comp_pivot1===0){") - code.push("if(k!==less){") - swapElements("k", "less") - code.push("}") - code.push("++less") - code.push("}else{") - comparePivot("comp_pivot2", "k", 2) - code.push("if(comp_pivot2===0){") - code.push("while(true){") - comparePivot("comp", "great", 2) - code.push("if(comp===0){") - code.push("if(--great 1 && allocator) { - var compiled = new Function("insertionSort", "malloc", "free", code.join("\n")) - return compiled(insertionSort, allocator[0], allocator[1]) + + var capSize = 5 + if ('capSize' in options) { + capSize = +options.capSize } - var compiled = new Function("insertionSort", code.join("\n")) - return compiled(insertionSort) -} -function compileSort(order, dtype) { - var code = ["'use strict'"] - var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("") - var funcArgs = [ "array" ] - - code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) - - //Unpack local variables from array - var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"] - for(var i=0; i> 1 + for (i = 0; i < numPoints; ++i) { + x = positions[i * 2] + y = positions[i * 2 + 1] + + bounds[0] = Math.min(x, bounds[0]) + bounds[1] = Math.min(y, bounds[1]) + bounds[2] = Math.max(x, bounds[2]) + bounds[3] = Math.max(y, bounds[3]) } - - var scratch_stride = new Array(order.length) - var nprod = [] - for(var i=0; i 0) { - vars.push(["d",j,"=s",j,"-d",p,"*n",p].join("")) - } else { - vars.push(["d",j,"=s",j].join("")) + if (bounds[3] === bounds[1]) { + bounds[3] += 1 + } + var sx = 1.0 / (bounds[2] - bounds[0]) + var sy = 1.0 / (bounds[3] - bounds[1]) + var tx = bounds[0] + var ty = bounds[1] + + var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4) + var ptr = 0 + for (i = 0; i < numPoints; ++i) { + x = positions[2 * i] + y = positions[2 * i + 1] + var ex0 = errors[4 * i] + var ex1 = errors[4 * i + 1] + var ey0 = errors[4 * i + 2] + var ey1 = errors[4 * i + 3] + + for (var j = 0; j < WEIGHTS.length; ++j) { + var w = WEIGHTS[j] + + var dx = w[0] + var dy = w[1] + + if (dx < 0) { + dx *= ex0 + } else if (dx > 0) { + dx *= ex1 } - p = j - } - var k = order.length-1-i - if(k !== 0) { - if(q > 0) { - vars.push(["e",k,"=s",k,"-e",q,"*n",q, - ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join("")) - } else { - vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join("")) + + if (dy < 0) { + dy *= ey0 + } else if (dy > 0) { + dy *= ey1 } - q = k + + bufferData[ptr++] = sx * ((x - tx) + dx) + bufferData[ptr++] = sy * ((y - ty) + dy) + bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4] + bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5] } } - - //Declare local variables - code.push("var " + vars.join(",")) - - //Create arguments for subroutine - var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length)) - - //Call main sorting routine - code.push([ - "if(n0<=",INSERTION_SORT_THRESHOLD,"){", - "insertionSort(", sortArgs.join(","), ")}else{", - "quickSort(", sortArgs.join(","), - ")}" - ].join("")) - - //Return - code.push("}return " + funcName) - - //Link everything together - var result = new Function("insertionSort", "quickSort", code.join("\n")) - var insertionSort = createInsertionSort(order, dtype) - var quickSort = createQuickSort(order, dtype, insertionSort) - return result(insertionSort, quickSort) + this.buffer.update(bufferData) + pool.free(bufferData) } -module.exports = compileSort -},{"typedarray-pool":306}],303:[function(require,module,exports){ -"use strict" - -var compile = require("./lib/compile_sort.js") -var CACHE = {} - -function sort(array) { - var order = array.order - var dtype = array.dtype - var typeSig = [order, dtype ] - var typeName = typeSig.join(":") - var compiled = CACHE[typeName] - if(!compiled) { - CACHE[typeName] = compiled = compile(order, dtype) - } - compiled(array) - return array +proto.dispose = function () { + this.plot.removeObject(this) + this.shader.dispose() + this.buffer.dispose() } -module.exports = sort -},{"./lib/compile_sort.js":302}],304:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],305:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],306:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":304,"buffer":65,"dup":122}],307:[function(require,module,exports){ -'use strict' +function createError2D (plot, options) { + var shader = createShader(plot.gl, shaders.vertex, shaders.fragment) + var buffer = createBuffer(plot.gl) -module.exports = createBoxes + var errorbars = new GLError2D(plot, shader, buffer) -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') + errorbars.update(options) -var shaders = require('./shaders') + plot.addObject(errorbars) -function Boxes(plot, vbo, shader) { - this.plot = plot - this.vbo = vbo - this.shader = shader + return errorbars } -var proto = Boxes.prototype +},{"./lib/shaders":120,"gl-buffer":118,"gl-shader":197,"typedarray-pool":278}],120:[function(require,module,exports){ -proto.bind = function() { - var shader = this.shader - this.vbo.bind() - this.shader.bind() - shader.attributes.coord.pointer() - shader.uniforms.screenBox = this.plot.screenBox + +module.exports = { + vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n", + fragment: "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" } -proto.drawBox = (function() { - var lo = [0,0] - var hi = [0,0] - return function(loX, loY, hiX, hiY, color) { - var plot = this.plot - var shader = this.shader - var gl = plot.gl +},{}],121:[function(require,module,exports){ +'use strict' - lo[0] = loX - lo[1] = loY - hi[0] = hiX - hi[1] = hiY +module.exports = createErrorBars - shader.uniforms.lo = lo - shader.uniforms.hi = hi - shader.uniforms.color = color +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders/index') - gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) - } -}()) +var IDENTITY = [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] -proto.dispose = function() { - this.vbo.dispose() - this.shader.dispose() +function ErrorBars(gl, buffer, vao, shader) { + this.gl = gl + this.shader = shader + this.buffer = buffer + this.vao = vao + this.pixelRatio = 1 + this.bounds = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]] + this.clipBounds = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]] + this.lineWidth = [1,1,1] + this.capSize = [10,10,10] + this.lineCount = [0,0,0] + this.lineOffset = [0,0,0] + this.opacity = 1 } -function createBoxes(plot) { - var gl = plot.gl - var vbo = createBuffer(gl, [ - 0,0, - 0,1, - 1,0, - 1,1]) - var shader = createShader(gl, shaders.boxVert, shaders.lineFrag) - return new Boxes(plot, vbo, shader) +var proto = ErrorBars.prototype + +proto.isOpaque = function() { + return this.opacity >= 1 } -},{"./shaders":310,"gl-buffer":313,"gl-shader":328}],308:[function(require,module,exports){ -'use strict' +proto.isTransparent = function() { + return this.opacity < 1 +} -module.exports = createGrid +proto.drawTransparent = proto.draw = function(cameraParams) { + var gl = this.gl + var uniforms = this.shader.uniforms -var createBuffer = require('gl-buffer') -var createShader = require('gl-shader') -var bsearch = require('binary-search-bounds') -var shaders = require('./shaders') + this.shader.bind() + var view = uniforms.view = cameraParams.view || IDENTITY + var projection = uniforms.projection = cameraParams.projection || IDENTITY + uniforms.model = cameraParams.model || IDENTITY + uniforms.clipBounds = this.clipBounds + uniforms.opacity = this.opacity -function Grid(plot, vbo, shader, tickShader) { - this.plot = plot - this.vbo = vbo - this.shader = shader - this.tickShader = tickShader - this.ticks = [[], []] + + var cx = view[12] + var cy = view[13] + var cz = view[14] + var cw = view[15] + var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight + + + this.vao.bind() + for(var i=0; i<3; ++i) { + gl.lineWidth(this.lineWidth[i]) + uniforms.capSize = this.capSize[i] * pixelScaleF + gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i]) + } + this.vao.unbind() } -function compareTickNum(a, b) { - return a - b +function updateBounds(bounds, point) { + for(var i=0; i<3; ++i) { + bounds[0][i] = Math.min(bounds[0][i], point[i]) + bounds[1][i] = Math.max(bounds[1][i], point[i]) + } } -var proto = Grid.prototype +var FACE_TABLE = (function(){ + var table = new Array(3) + for(var d=0; d<3; ++d) { + var row = [] + for(var j=1; j<=2; ++j) { + for(var s=-1; s<=1; s+=2) { + var u = (j+d) % 3 + var y = [0,0,0] + y[u] = s + row.push(y) + } + } + table[d] = row + } + return table +})() -proto.draw = (function() { - var DATA_SHIFT = [0,0] - var DATA_SCALE = [0,0] - var DATA_AXIS = [0,0] +function emitFace(verts, x, c, d) { + var offsets = FACE_TABLE[d] + for(var i=0; i 0) { + var x = p.slice() + x[j] += e[1][j] + verts.push(p[0], p[1], p[2], + c[0], c[1], c[2], c[3], + 0, 0, 0, + x[0], x[1], x[2], + c[0], c[1], c[2], c[3], + 0, 0, 0) + updateBounds(this.bounds, x) + vertexCount += 2 + emitFace(verts, x, c, j) + } } - offset += size + this.lineCount[j] = vertexCount - this.lineOffset[j] } + this.buffer.update(verts) } -})() +} -proto.drawTickMarks = (function() { - var DATA_SHIFT = [0,0] - var DATA_SCALE = [0,0] - var X_AXIS = [1,0] - var Y_AXIS = [0,1] - var SCR_OFFSET = [0,0] - var TICK_SCALE = [0,0] +proto.dispose = function() { + this.shader.dispose() + this.buffer.dispose() + this.vao.dispose() +} - return function() { - var plot = this.plot - var vbo = this.vbo - var shader = this.tickShader - var ticks = this.ticks - var gl = plot.gl - var bounds = plot._tickBounds - var dataBox = plot.dataBox - var viewBox = plot.viewBox - var pixelRatio = plot.pixelRatio - var screenBox = plot.screenBox +function createErrorBars(options) { + var gl = options.gl + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 0, + stride: 40 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 4, + offset: 12, + stride: 40 + }, + { + buffer: buffer, + type: gl.FLOAT, + size: 3, + offset: 28, + stride: 40 + } + ]) - var screenWidth = screenBox[2] - screenBox[0] - var screenHeight = screenBox[3] - screenBox[1] - var viewWidth = viewBox[2] - viewBox[0] - var viewHeight = viewBox[3] - viewBox[1] + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.color.location = 1 + shader.attributes.offset.location = 2 - for(var i=0; i<2; ++i) { - var lo = bounds[i] - var hi = bounds[i+2] - var boundScale = hi - lo - var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) - var dataWidth = (dataBox[i+2] - dataBox[i]) - DATA_SCALE[i] = 2.0 * boundScale / dataWidth - DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth - } + var result = new ErrorBars(gl, buffer, vao, shader) + result.update(options) + return result +} - DATA_SCALE[0] *= viewWidth / screenWidth - DATA_SHIFT[0] *= viewWidth / screenWidth +},{"./shaders/index":122,"gl-buffer":118,"gl-vao":226}],122:[function(require,module,exports){ +'use strict' - DATA_SCALE[1] *= viewHeight / screenHeight - DATA_SHIFT[1] *= viewHeight / screenHeight - shader.bind() - vbo.bind() +var createShader = require('gl-shader') - shader.attributes.dataCoord.pointer() +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}" - var uniforms = shader.uniforms - uniforms.dataShift = DATA_SHIFT - uniforms.dataScale = DATA_SCALE +module.exports = function(gl) { + return createShader(gl, vertSrc, fragSrc, null, [ + {name: 'position', type: 'vec3'}, + {name: 'offset', type: 'vec3'}, + {name: 'color', type: 'vec4'} + ]) +} - var tickMarkLength = plot.tickMarkLength - var tickMarkWidth = plot.tickMarkWidth - var tickMarkColor = plot.tickMarkColor +},{"gl-shader":197}],123:[function(require,module,exports){ +'use strict' - var xTicksOffset = 0 - var yTicksOffset = ticks[0].length * 6 +var createTexture = require('gl-texture2d') - var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xEnd = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) - var xOffset = xTicksOffset + 6 * xStart - var xCount = 6 * Math.max(0, xEnd - xStart) +module.exports = createFBO - var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yEnd = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) - var yOffset = yTicksOffset + 6 * yStart - var yCount = 6 * Math.max(0, yEnd - yStart) +var colorAttachmentArrays = null +var FRAMEBUFFER_UNSUPPORTED +var FRAMEBUFFER_INCOMPLETE_ATTACHMENT +var FRAMEBUFFER_INCOMPLETE_DIMENSIONS +var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT - SCR_OFFSET[0] = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0 - SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 - TICK_SCALE[0] = tickMarkLength[1] * pixelRatio / screenWidth - TICK_SCALE[1] = tickMarkWidth[1] * pixelRatio / screenHeight +function saveFBOState(gl) { + var fbo = gl.getParameter(gl.FRAMEBUFFER_BINDING) + var rbo = gl.getParameter(gl.RENDERBUFFER_BINDING) + var tex = gl.getParameter(gl.TEXTURE_BINDING_2D) + return [fbo, rbo, tex] +} - if(yCount) { - uniforms.color = tickMarkColor[1] - uniforms.tickScale = TICK_SCALE - uniforms.dataAxis = Y_AXIS - uniforms.screenOffset = SCR_OFFSET - gl.drawArrays(gl.TRIANGLES, yOffset, yCount) +function restoreFBOState(gl, data) { + gl.bindFramebuffer(gl.FRAMEBUFFER, data[0]) + gl.bindRenderbuffer(gl.RENDERBUFFER, data[1]) + gl.bindTexture(gl.TEXTURE_2D, data[2]) +} + +function lazyInitColorAttachments(gl, ext) { + var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL) + colorAttachmentArrays = new Array(maxColorAttachments + 1) + for(var i=0; i<=maxColorAttachments; ++i) { + var x = new Array(maxColorAttachments) + for(var j=0; j 1) { + ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]) } -})() -proto.update = (function() { - var OFFSET_X = [1, 1, -1, -1, 1, -1] - var OFFSET_Y = [1, -1, 1, 1, -1, -1] + //Allocate depth/stencil buffers + var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture') + if(WEBGL_depth_texture) { + if(useStencil) { + fbo.depth = initTexture(gl, width, height, + WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, + gl.DEPTH_STENCIL, + gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo.depth = initTexture(gl, width, height, + gl.UNSIGNED_SHORT, + gl.DEPTH_COMPONENT, + gl.DEPTH_ATTACHMENT) + } + } else { + if(useDepth && useStencil) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT) + } else if(useDepth) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT) + } else if(useStencil) { + fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT) + } + } - return function(options) { - var ticks = options.ticks - var bounds = options.bounds - var data = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length)) + //Check frame buffer state + var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) + if(status !== gl.FRAMEBUFFER_COMPLETE) { - var zeroLineEnable = this.plot.zeroLineEnable + //Release all partially allocated resources + fbo._destroyed = true - var ptr = 0 - var gridTicks = [[], []] - for(var dim=0; dim<2; ++dim) { - var localTicks = gridTicks[dim] - var axisTicks = ticks[dim] - var lo = bounds[dim] - var hi = bounds[dim+2] - for(var i=0; i maxFBOSize || + h < 0 || h > maxFBOSize) { + throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions') + } -},{"./shaders":310,"gl-buffer":313,"gl-shader":328}],310:[function(require,module,exports){ -'use strict' + //Update shape + fbo._shape[0] = w + fbo._shape[1] = h + //Save framebuffer state + var state = saveFBOState(gl) + //Resize framebuffer attachments + for(var i=0; i maxFBOSize || height < 0 || height > maxFBOSize) { + throw new Error('gl-fbo: Parameters are too large for FBO') + } - var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1] + //Handle each option type + options = options || {} - SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0 - if(tickEnable[axis]) { - SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis] - if(start < end && tickOffset[end] > tickOffset[start]) { - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = textColor[axis] - shader.uniforms.angle = textAngle[axis] - gl.drawArrays( - gl.TRIANGLES, - tickOffset[start], - tickOffset[end] - tickOffset[start]) - } + //Figure out number of color buffers to use + var numColors = 1 + if('color' in options) { + numColors = Math.max(options.color|0, 0) + if(numColors < 0) { + throw new Error('gl-fbo: Must specify a nonnegative number of colors') } - if(labelEnable[axis] && labelCount) { - SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis] - shader.uniforms.dataAxis = ZERO_2 - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = labelColor[axis] - shader.uniforms.angle = labelAngle[axis] - gl.drawArrays( - gl.TRIANGLES, - labelOffset, - labelCount) + if(numColors > 1) { + //Check if multiple render targets supported + if(!WEBGL_draw_buffers) { + throw new Error('gl-fbo: Multiple draw buffer extension not supported') + } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) { + throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers') + } } + } - SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0 - if(tickEnable[axis+2]) { - SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2] - if(start < end && tickOffset[end] > tickOffset[start]) { - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = textColor[axis+2] - shader.uniforms.angle = textAngle[axis+2] - gl.drawArrays( - gl.TRIANGLES, - tickOffset[start], - tickOffset[end] - tickOffset[start]) - } + //Determine whether to use floating point textures + var colorType = gl.UNSIGNED_BYTE + var OES_texture_float = gl.getExtension('OES_texture_float') + if(options.float && numColors > 0) { + if(!OES_texture_float) { + throw new Error('gl-fbo: Context does not support floating point textures') } - if(labelEnable[axis+2] && labelCount) { - SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2] - shader.uniforms.dataAxis = ZERO_2 - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.color = labelColor[axis+2] - shader.uniforms.angle = labelAngle[axis+2] - gl.drawArrays( - gl.TRIANGLES, - labelOffset, - labelCount) + colorType = gl.FLOAT + } else if(options.preferFloat && numColors > 0) { + if(OES_texture_float) { + colorType = gl.FLOAT } + } + //Check if we should use depth buffer + var useDepth = true + if('depth' in options) { + useDepth = !!options.depth } -})() -proto.drawTitle = (function() { - var DATA_AXIS = [0,0] - var SCREEN_OFFSET = [0,0] + //Check if we should use a stencil buffer + var useStencil = false + if('stencil' in options) { + useStencil = !!options.stencil + } - return function() { - var plot = this.plot - var shader = this.shader - var gl = plot.gl - var screenBox = plot.screenBox - var titleCenter = plot.titleCenter - var titleAngle = plot.titleAngle - var titleColor = plot.titleColor - var titleCenter = plot.titleCenter - var pixelRatio = plot.pixelRatio + return new Framebuffer( + gl, + width, + height, + colorType, + numColors, + useDepth, + useStencil, + WEBGL_draw_buffers) +} - if(!this.titleCount) { - return - } +},{"gl-texture2d":222}],124:[function(require,module,exports){ - for(var i=0; i<2; ++i) { - SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) / - (screenBox[2+i] - screenBox[i]) - 1 - } - shader.bind() - shader.uniforms.dataAxis = DATA_AXIS - shader.uniforms.screenOffset = SCREEN_OFFSET - shader.uniforms.angle = titleAngle - shader.uniforms.color = titleColor +exports.lineVertex = "precision mediump float;\n#define GLSLIFY 1\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n vec2 dir = (matrix * vec3(d, 0)).xy;\n vec3 base = matrix * vec3(a, 1);\n vec2 n = 0.5 * width *\n normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n vec2 tangent = normalize(screenShape.xy * dir);\n if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n direction = -tangent;\n } else {\n direction = tangent;\n }\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n" +exports.lineFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n" +exports.mitreVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 p;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n vec3 pp = matrix * vec3(p, 1);\n gl_Position = vec4(pp.xy, 0, pp.z);\n gl_PointSize = radius;\n}\n" +exports.mitreFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n discard;\n }\n gl_FragColor = vec4(color.rgb, color.a);\n}\n" +exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n return mat2(m[1][1],-m[0][1],\n -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n float b01 = a22 * a11 - a12 * a21;\n float b11 = -a22 * a10 + a12 * a20;\n float b21 = a21 * a10 - a11 * a20;\n\n float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n float\n a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n b00 = a00 * a11 - a01 * a10,\n b01 = a00 * a12 - a02 * a10,\n b02 = a00 * a13 - a03 * a10,\n b03 = a01 * a12 - a02 * a11,\n b04 = a01 * a13 - a03 * a11,\n b05 = a02 * a13 - a03 * a12,\n b06 = a20 * a31 - a21 * a30,\n b07 = a20 * a32 - a22 * a30,\n b08 = a20 * a33 - a23 * a30,\n b09 = a21 * a32 - a22 * a31,\n b10 = a21 * a33 - a23 * a31,\n b11 = a22 * a33 - a23 * a32,\n\n det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n return mat4(\n a11 * b11 - a12 * b10 + a13 * b09,\n a02 * b10 - a01 * b11 - a03 * b09,\n a31 * b05 - a32 * b04 + a33 * b03,\n a22 * b04 - a21 * b05 - a23 * b03,\n a12 * b08 - a10 * b11 - a13 * b07,\n a00 * b11 - a02 * b08 + a03 * b07,\n a32 * b02 - a30 * b05 - a33 * b01,\n a20 * b05 - a22 * b02 + a23 * b01,\n a10 * b10 - a11 * b08 + a13 * b06,\n a01 * b08 - a00 * b10 - a03 * b06,\n a30 * b04 - a31 * b02 + a33 * b00,\n a21 * b02 - a20 * b04 - a23 * b00,\n a11 * b07 - a10 * b09 - a12 * b06,\n a00 * b09 - a01 * b07 + a02 * b06,\n a31 * b01 - a30 * b03 - a32 * b00,\n a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 n = width *\n normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n gl_Position = vec4(base.xy/base.z + n, 0, 1);\n pickA = pick0;\n pickB = pick1;\n}\n" +exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n vec4 fragId = vec4(pickA.xyz, 0.0);\n if(pickB.w > pickA.w) {\n fragId.xyz = pickB.xyz;\n }\n\n fragId += pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n gl_FragColor = fragId / 255.0;\n}\n" +exports.fillVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n vec3 base = matrix * vec3(a, 1);\n vec2 p = base.xy / base.z;\n if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n if(dot(p, projectAxis) < projectValue) {\n p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n }\n }\n gl_Position = vec4(p, depth, 1);\n}\n" +exports.fillFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n" - gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount) - } -})() +},{}],125:[function(require,module,exports){ +'use strict' -proto.bind = (function() { - var DATA_SHIFT = [0,0] - var DATA_SCALE = [0,0] - var TEXT_SCALE = [0,0] +module.exports = createLinePlot - return function() { - var plot = this.plot - var shader = this.shader - var bounds = plot._tickBounds - var dataBox = plot.dataBox - var screenBox = plot.screenBox - var viewBox = plot.viewBox +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var createTexture = require('gl-texture2d') +var ndarray = require('ndarray') +var pool = require('typedarray-pool') - shader.bind() +var SHADERS = require('./lib/shaders') - //Set up coordinate scaling uniforms - for(var i=0; i<2; ++i) { +function GLLine2D( + plot, + dashPattern, + lineBuffer, + pickBuffer, + lineShader, + mitreShader, + fillShader, + pickShader) { - var lo = bounds[i] - var hi = bounds[i+2] - var boundScale = hi - lo - var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) - var dataWidth = (dataBox[i+2] - dataBox[i]) + this.plot = plot + this.dashPattern = dashPattern + this.lineBuffer = lineBuffer + this.pickBuffer = pickBuffer + this.lineShader = lineShader + this.mitreShader = mitreShader + this.fillShader = fillShader + this.pickShader = pickShader + this.usingDashes = false - var viewLo = viewBox[i] - var viewHi = viewBox[i+2] - var viewScale = viewHi - viewLo - var screenLo = screenBox[i] - var screenHi = screenBox[i+2] - var screenScale = screenHi - screenLo + this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - DATA_SCALE[i] = 2.0 * boundScale / dataWidth * viewScale / screenScale - DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth * viewScale / screenScale - } + this.width = 1 + this.color = [0,0,1,1] - TEXT_SCALE[1] = 2.0 * plot.pixelRatio / (screenBox[3] - screenBox[1]) - TEXT_SCALE[0] = TEXT_SCALE[1] * (screenBox[3] - screenBox[1]) / (screenBox[2] - screenBox[0]) + //Fill to axes + this.fill = [false, false, false, false] + this.fillColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - shader.uniforms.dataScale = DATA_SCALE - shader.uniforms.dataShift = DATA_SHIFT - shader.uniforms.textScale = TEXT_SCALE + this.data = null + this.numPoints = 0 + this.vertCount = 0 - //Set attributes - this.vbo.bind() - shader.attributes.textCoordinate.pointer() - } -})() + this.pickOffset = 0 -proto.update = function(options) { - var vertices = [] - var axesTicks = options.ticks - var bounds = options.bounds + this.lodBuffer = [] +} - for(var dimension=0; dimension<2; ++dimension) { - var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity] +var proto = GLLine2D.prototype - //Copy vertices over to buffer - var ticks = axesTicks[dimension] - for(var i=0; i>>1,x=a[m]"] - if(earlyOut) { - if(predicate.indexOf("c") < 0) { - code.push(";if(x===y){return m}else if(x<=y){") - } else { - code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){") + if(fill[1]) { + fillUniforms.color = fillColor[1] + fillUniforms.projectAxis = NY_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) } - } else { - code.push(";if(", predicate, "){i=m;") - } - if(reversed) { - code.push("l=m+1}else{h=m-1}") - } else { - code.push("h=m-1}else{l=m+1}") - } - code.push("}") - if(earlyOut) { - code.push("return -1};") - } else { - code.push("return i};") + + if(fill[2]) { + fillUniforms.color = fillColor[2] + fillUniforms.projectAxis = PX_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) + } + + if(fill[3]) { + fillUniforms.color = fillColor[3] + fillUniforms.projectAxis = PY_AXIS + fillUniforms.projectValue = 1 + gl.drawArrays(gl.TRIANGLES, 0, count) + } + + gl.depthMask(false) + gl.disable(gl.DEPTH_TEST) } - return code.join("") -} -function compileBoundsSearch(predicate, reversed, suffix, earlyOut) { - var result = new Function([ - compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut), - compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut), -"function dispatchBsearch", suffix, "(a,y,c,l,h){\ -if(typeof(c)==='function'){\ -return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\ -}else{\ -return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\ -}}\ -return dispatchBsearch", suffix].join("")) - return result() -} + var shader = this.lineShader + shader.bind() -module.exports = { - ge: compileBoundsSearch(">=", false, "GE"), - gt: compileBoundsSearch(">", false, "GT"), - lt: compileBoundsSearch("<", true, "LT"), - le: compileBoundsSearch("<=", true, "LE"), - eq: compileBoundsSearch("-", true, "EQ", true) -} + var uniforms = shader.uniforms + uniforms.matrix = MATRIX + uniforms.color = color + uniforms.width = width * pixelRatio + uniforms.screenShape = SCREEN_SHAPE + uniforms.dashPattern = this.dashPattern.bind() + uniforms.dashLength = this.dashLength * pixelRatio -},{}],313:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":316}],314:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],315:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],316:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":314,"buffer":65,"dup":122}],317:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],318:[function(require,module,exports){ -module.exports = require("cwise-compiler") -},{"cwise-compiler":319}],319:[function(require,module,exports){ -"use strict" - -var createThunk = require("./lib/thunk.js") - -function Procedure() { - this.argTypes = [] - this.shimArgs = [] - this.arrayArgs = [] - this.arrayBlockIndices = [] - this.scalarArgs = [] - this.offsetArgs = [] - this.offsetArgIndex = [] - this.indexArgs = [] - this.shapeArgs = [] - this.funcName = "" - this.pre = null - this.body = null - this.post = null - this.debug = false -} - -function compileCwise(user_args) { - //Create procedure - var proc = new Procedure() - - //Parse blocks - proc.pre = user_args.pre - proc.body = user_args.body - proc.post = user_args.post - - //Parse arguments - var proc_args = user_args.args.slice(0) - proc.argTypes = proc_args - for(var i=0; i0) { - throw new Error("cwise: pre() block may not reference array args") - } - if(i < proc.post.args.length && proc.post.args[i].count>0) { - throw new Error("cwise: post() block may not reference array args") - } - } else if(arg_type === "scalar") { - proc.scalarArgs.push(i) - proc.shimArgs.push("scalar" + i) - } else if(arg_type === "index") { - proc.indexArgs.push(i) - if(i < proc.pre.args.length && proc.pre.args[i].count > 0) { - throw new Error("cwise: pre() block may not reference array index") - } - if(i < proc.body.args.length && proc.body.args[i].lvalue) { - throw new Error("cwise: body() block may not write to array index") - } - if(i < proc.post.args.length && proc.post.args[i].count > 0) { - throw new Error("cwise: post() block may not reference array index") - } - } else if(arg_type === "shape") { - proc.shapeArgs.push(i) - if(i < proc.pre.args.length && proc.pre.args[i].lvalue) { - throw new Error("cwise: pre() block may not write to array shape") - } - if(i < proc.body.args.length && proc.body.args[i].lvalue) { - throw new Error("cwise: body() block may not write to array shape") - } - if(i < proc.post.args.length && proc.post.args[i].lvalue) { - throw new Error("cwise: post() block may not write to array shape") - } - } else if(typeof arg_type === "object" && arg_type.offset) { - proc.argTypes[i] = "offset" - proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset }) - proc.offsetArgIndex.push(i) - } else { - throw new Error("cwise: Unknown argument type " + proc_args[i]) - } - } - - //Make sure at least one array argument was specified - if(proc.arrayArgs.length <= 0) { - throw new Error("cwise: No array arguments specified") - } - - //Make sure arguments are correct - if(proc.pre.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in pre() block") - } - if(proc.body.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in body() block") - } - if(proc.post.args.length > proc_args.length) { - throw new Error("cwise: Too many arguments in post() block") - } - - //Check debug flag - proc.debug = !!user_args.printCode || !!user_args.debug - - //Retrieve name - proc.funcName = user_args.funcName || "cwise" - - //Read in block size - proc.blockSize = user_args.blockSize || 64 - - return createThunk(proc) -} - -module.exports = compileCwise + var attributes = shader.attributes + attributes.a.pointer(gl.FLOAT, false, 16, 0) + attributes.d.pointer(gl.FLOAT, false, 16, 8) -},{"./lib/thunk.js":321}],320:[function(require,module,exports){ -"use strict" - -var uniq = require("uniq") - -// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index) -// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments. -function innerFill(order, proc, body) { - var dimension = order.length - , nargs = proc.arrayArgs.length - , has_index = proc.indexArgs.length>0 - , code = [] - , vars = [] - , idx=0, pidx=0, i, j - for(i=0; i=0; --i) { // Start at largest stride and work your way inwards - idx = order[i] - code.push(["for(i",i,"=0;i",i," 0) { - code.push(["index[",pidx,"]-=s",pidx].join("")) - } - code.push(["++index[",idx,"]"].join("")) - } - code.push("}") - } - return code.join("\n") -} - -// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block. -// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary. -// I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used. -function outerFill(matched, order, proc, body) { - var dimension = order.length - , nargs = proc.arrayArgs.length - , blockSize = proc.blockSize - , has_index = proc.indexArgs.length > 0 - , code = [] - for(var i=0; i0;){"].join("")) // Iterate back to front - code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j). - code.push(["s",order[i],"=j",i].join("")) - code.push(["j",i,"=0"].join("")) - code.push(["}else{s",order[i],"=",blockSize].join("")) - code.push(["j",i,"-=",blockSize,"}"].join("")) - if(has_index) { - code.push(["index[",order[i],"]=j",i].join("")) - } - } - for(var i=0; i 0) { - allEqual = allEqual && summary[i] === summary[i-1] - } - } - if(allEqual) { - return summary[0] - } - return summary.join("") -} - -//Generates a cwise operator -function generateCWiseOp(proc, typesig) { - - //Compute dimension - // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg. - var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0 - var orders = new Array(proc.arrayArgs.length) - var dtypes = new Array(proc.arrayArgs.length) - for(var i=0; i 0) { - vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example) - } - if(proc.indexArgs.length > 0) { - // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes. - var zeros = new Array(dimension) - for(var i=0; i 3) { - code.push(processBlock(proc.pre, proc, dtypes)) - } - - //Process body - var body = processBlock(proc.body, proc, dtypes) - var matched = countMatches(loopOrders) - if(matched < dimension) { - code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example. - } else { - code.push(innerFill(loopOrders[0], proc, body)) - } - - //Inline epilog - if(proc.post.body.length > 3) { - code.push(processBlock(proc.post, proc, dtypes)) - } - - if(proc.debug) { - console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------") - } - - var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("") - var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join("")) - return f() -} -module.exports = generateCWiseOp + gl.drawArrays(gl.TRIANGLES, 0, count) + + //Draw mitres + if(width > 2 && !this.usingDashes) { + var mshader = this.mitreShader + mshader.bind() -},{"uniq":322}],321:[function(require,module,exports){ -"use strict" - -// The function below is called when constructing a cwise function object, and does the following: -// A function object is constructed which accepts as argument a compilation function and returns another function. -// It is this other function that is eventually returned by createThunk, and this function is the one that actually -// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed. -// The compilation passed to the first function object is used for compiling new functions. -// Once this function object is created, it is called with compile as argument, where the first argument of compile -// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise). -// So createThunk roughly works like this: -// function createThunk(proc) { -// var thunk = function(compileBound) { -// var CACHED = {} -// return function(arrays and scalars) { -// if (dtype and order of arrays in CACHED) { -// var func = CACHED[dtype and order of arrays] -// } else { -// var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays) -// } -// return func(arrays and scalars) -// } -// } -// return thunk(compile.bind1(proc)) -// } - -var compile = require("./compile.js") - -function createThunk(proc) { - var code = ["'use strict'", "var CACHED={}"] - var vars = [] - var thunkName = proc.funcName + "_cwise_thunk" - - //Build thunk - code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join("")) - var typesig = [] - var string_typesig = [] - var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS). - Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")] - var shapeLengthConditions = [], shapeConditions = [] - // Process array arguments - for(var i=0; i0) { // Gather conditions to check for shape equality (ignoring block indices) - shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i]))) - shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]") - } - } - // Check for shape equality - if (proc.arrayArgs.length > 1) { - code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')") - code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {") - code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')") - code.push("}") - } - // Process scalar arguments - for(var i=0; i>>8) & 0xff + PICK_OFFSET[2] = (pickOffset>>>16) & 0xff + PICK_OFFSET[3] = pickOffset>>>24 + + shader.bind() + + var uniforms = shader.uniforms + uniforms.matrix = MATRIX + uniforms.width = width * pixelRatio + uniforms.pickOffset = PICK_OFFSET + uniforms.screenShape = SCREEN_SHAPE + + var attributes = shader.attributes + + buffer.bind() + attributes.a.pointer(gl.FLOAT, false, 16, 0) + attributes.d.pointer(gl.FLOAT, false, 16, 8) + + pickBuffer.bind() + attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0) + attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4) + + gl.drawArrays(gl.TRIANGLES, 0, count) + + return pickOffset + numPoints + } +})() + +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.numPoints + if(value < pickOffset || value >= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var points = this.data + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] + } } -function restoreFBOState(gl, data) { - gl.bindFramebuffer(gl.FRAMEBUFFER, data[0]) - gl.bindRenderbuffer(gl.RENDERBUFFER, data[1]) - gl.bindTexture(gl.TEXTURE_2D, data[2]) +function deepCopy(arr) { + return arr.map(function(x) { + return x.slice() + }) } -function lazyInitColorAttachments(gl, ext) { - var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL) - colorAttachmentArrays = new Array(maxColorAttachments + 1) - for(var i=0; i<=maxColorAttachments; ++i) { - var x = new Array(maxColorAttachments) - for(var j=0; j 1 + + this.dashPattern = createTexture(gl, + ndarray(dashData, [dashLength, 1, 4], [1, 0, 0])) + this.dashPattern.minFilter = gl.NEAREST + this.dashPattern.magFilter = gl.NEAREST + this.dashLength = dashLength + pool.free(dashData) + + var data = options.positions + this.data = data + + var bounds = this.bounds + bounds[0] = bounds[1] = Infinity + bounds[2] = bounds[3] = -Infinity + + var numPoints = this.numPoints = data.length>>>1 + if(numPoints === 0) { + return + } + + for(var i=0; i 1) { + var id = --ptr + var ax = data[2*ptr] + var ay = data[2*ptr+1] + + var next = id-1 + var bx = data[2*next] + var by = data[2*next+1] + + if (isNaN(ax) || isNaN(ay) || isNaN(bx) || isNaN(by)) { + continue + } + + count += 1 + + ax = (ax - bounds[0]) / (bounds[2] - bounds[0]) + ay = (ay - bounds[1]) / (bounds[3] - bounds[1]) + + bx = (bx - bounds[0]) / (bounds[2] - bounds[0]) + by = (by - bounds[1]) / (bounds[3] - bounds[1]) + + var dx = bx - ax + var dy = by - ay + + var akey0 = id | (1<<24) + var akey1 = (id-1) + var bkey0 = id + var bkey1 = (id-1) | (1<<24) + + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 + + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 + + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 + + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = by + lineData[--lineDataPtr] = bx + pickData[--pickDataPtr] = bkey0 + pickData[--pickDataPtr] = bkey1 + + lineData[--lineDataPtr] = -dy + lineData[--lineDataPtr] = -dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 + + lineData[--lineDataPtr] = dy + lineData[--lineDataPtr] = dx + lineData[--lineDataPtr] = ay + lineData[--lineDataPtr] = ax + pickData[--pickDataPtr] = akey0 + pickData[--pickDataPtr] = akey1 } + + this.vertCount = 6 * count + this.lineBuffer.update(lineData.subarray(lineDataPtr)) + this.pickBuffer.update(pickData.subarray(pickDataPtr)) + + pool.free(lineData) + pool.free(pickData) } -//Throw an appropriate error -function throwFBOError(status) { - switch(status){ - case FRAMEBUFFER_UNSUPPORTED: - throw new Error('gl-fbo: Framebuffer unsupported') - case FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - throw new Error('gl-fbo: Framebuffer incomplete attachment') - case FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - throw new Error('gl-fbo: Framebuffer incomplete dimensions') - case FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - throw new Error('gl-fbo: Framebuffer incomplete missing attachment') - default: - throw new Error('gl-fbo: Framebuffer failed for unspecified reason') +proto.dispose = function() { + this.plot.removeObject(this) + this.lineBuffer.dispose() + this.pickBuffer.dispose() + this.lineShader.dispose() + this.mitreShader.dispose() + this.fillShader.dispose() + this.pickShader.dispose() + this.dashPattern.dispose() +} + +function createLinePlot(plot, options) { + var gl = plot.gl + var lineBuffer = createBuffer(gl) + var pickBuffer = createBuffer(gl) + var dashPattern = createTexture(gl, [1,1]) + var lineShader = createShader(gl, SHADERS.lineVertex, SHADERS.lineFragment) + var mitreShader = createShader(gl, SHADERS.mitreVertex, SHADERS.mitreFragment) + var fillShader = createShader(gl, SHADERS.fillVertex, SHADERS.fillFragment) + var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) + var linePlot = new GLLine2D( + plot, + dashPattern, + lineBuffer, + pickBuffer, + lineShader, + mitreShader, + fillShader, + pickShader) + plot.addObject(linePlot) + linePlot.update(options) + return linePlot +} + +},{"./lib/shaders":124,"gl-buffer":118,"gl-shader":197,"gl-texture2d":222,"ndarray":253,"typedarray-pool":278}],126:[function(require,module,exports){ + +var createShader = require('gl-shader') + +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n" +var forwardFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n" +var pickFrag = "precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}" + +var ATTRIBUTES = [ + {name: 'position', type: 'vec3'}, + {name: 'nextPosition', type: 'vec3'}, + {name: 'arcLength', type: 'float'}, + {name: 'lineWidth', type: 'float'}, + {name: 'color', type: 'vec4'} +] + +exports.createShader = function(gl) { + return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES) +} + +exports.createPickShader = function(gl) { + return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES) +} + +},{"gl-shader":197}],127:[function(require,module,exports){ +'use strict' + +module.exports = createLinePlot + +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createTexture = require('gl-texture2d') +var unpackFloat = require('glsl-read-float') +var bsearch = require('binary-search-bounds') +var ndarray = require('ndarray') +var shaders = require('./lib/shaders') + +var createShader = shaders.createShader +var createPickShader = shaders.createPickShader + +var identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1] + +function distance (a, b) { + var s = 0.0 + for (var i = 0; i < 3; ++i) { + var d = a[i] - b[i] + s += d * d + } + return Math.sqrt(s) +} + +function filterClipBounds (bounds) { + var result = [[-1e6, -1e6, -1e6], [1e6, 1e6, 1e6]] + for (var i = 0; i < 3; ++i) { + result[0][i] = Math.max(bounds[0][i], result[0][i]) + result[1][i] = Math.min(bounds[1][i], result[1][i]) } + return result +} + +function PickResult (tau, position, index, dataCoordinate) { + this.arcLength = tau + this.position = position + this.index = index + this.dataCoordinate = dataCoordinate +} + +function LinePlot (gl, shader, pickShader, buffer, vao, texture) { + this.gl = gl + this.shader = shader + this.pickShader = pickShader + this.buffer = buffer + this.vao = vao + this.clipBounds = [ + [ -Infinity, -Infinity, -Infinity ], + [ Infinity, Infinity, Infinity ]] + this.points = [] + this.arcLength = [] + this.vertexCount = 0 + this.bounds = [[0, 0, 0], [0, 0, 0]] + this.pickId = 0 + this.lineWidth = 1 + this.texture = texture + this.dashScale = 1 + this.opacity = 1 + this.dirty = true + this.pixelRatio = 1 +} + +var proto = LinePlot.prototype + +proto.isTransparent = function () { + return this.opacity < 1 +} + +proto.isOpaque = function () { + return this.opacity >= 1 +} + +proto.pickSlots = 1 + +proto.setPickBase = function (id) { + this.pickId = id } -//Initialize a texture object -function initTexture(gl, width, height, type, format, attachment) { - if(!type) { - return null +proto.drawTransparent = proto.draw = function (camera) { + var gl = this.gl + var shader = this.shader + var vao = this.vao + shader.bind() + shader.uniforms = { + model: camera.model || identity, + view: camera.view || identity, + projection: camera.projection || identity, + clipBounds: filterClipBounds(this.clipBounds), + dashTexture: this.texture.bind(), + dashScale: this.dashScale / this.arcLength[this.arcLength.length - 1], + opacity: this.opacity, + screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], + pixelRatio: this.pixelRatio } - var result = createTexture(gl, width, height, format, type) - result.magFilter = gl.NEAREST - result.minFilter = gl.NEAREST - result.mipSamples = 1 - result.bind() - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, result.handle, 0) - return result + vao.bind() + vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) } -//Initialize a render buffer object -function initRenderBuffer(gl, width, height, component, attachment) { - var result = gl.createRenderbuffer() - gl.bindRenderbuffer(gl.RENDERBUFFER, result) - gl.renderbufferStorage(gl.RENDERBUFFER, component, width, height) - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, result) - return result +proto.drawPick = function (camera) { + var gl = this.gl + var shader = this.pickShader + var vao = this.vao + shader.bind() + shader.uniforms = { + model: camera.model || identity, + view: camera.view || identity, + projection: camera.projection || identity, + pickId: this.pickId, + clipBounds: filterClipBounds(this.clipBounds), + screenShape: [gl.drawingBufferWidth, gl.drawingBufferHeight], + pixelRatio: this.pixelRatio + } + vao.bind() + vao.draw(gl.TRIANGLE_STRIP, this.vertexCount) } -//Rebuild the frame buffer -function rebuildFBO(fbo) { - - //Save FBO state - var state = saveFBOState(fbo.gl) +proto.update = function (options) { + var i, j - var gl = fbo.gl - var handle = fbo.handle = gl.createFramebuffer() - var width = fbo._shape[0] - var height = fbo._shape[1] - var numColors = fbo.color.length - var ext = fbo._ext - var useStencil = fbo._useStencil - var useDepth = fbo._useDepth - var colorType = fbo._colorType + this.dirty = true - //Bind the fbo - gl.bindFramebuffer(gl.FRAMEBUFFER, handle) + var connectGaps = !!options.connectGaps - //Allocate color buffers - for(var i=0; i 1) { - ext.drawBuffersWEBGL(colorAttachmentArrays[numColors]) + if ('opacity' in options) { + this.opacity = +options.opacity } - //Allocate depth/stencil buffers - var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture') - if(WEBGL_depth_texture) { - if(useStencil) { - fbo.depth = initTexture(gl, width, height, - WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL, - gl.DEPTH_STENCIL, - gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo.depth = initTexture(gl, width, height, - gl.UNSIGNED_SHORT, - gl.DEPTH_COMPONENT, - gl.DEPTH_ATTACHMENT) - } - } else { - if(useDepth && useStencil) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT) - } else if(useDepth) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT) - } else if(useStencil) { - fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT) - } + var positions = options.position || options.positions + if (!positions) { + return } - //Check frame buffer state - var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER) - if(status !== gl.FRAMEBUFFER_COMPLETE) { + // Default color + var colors = options.color || options.colors || [0, 0, 0, 1] - //Release all partially allocated resources - fbo._destroyed = true + var lineWidth = options.lineWidth || 1 - //Release all resources - gl.bindFramebuffer(gl.FRAMEBUFFER, null) - gl.deleteFramebuffer(fbo.handle) - fbo.handle = null - if(fbo.depth) { - fbo.depth.dispose() - fbo.depth = null + // Recalculate buffer data + var buffer = [] + var arcLengthArray = [] + var pointArray = [] + var arcLength = 0.0 + var vertexCount = 0 + var bounds = [ + [ Infinity, Infinity, Infinity ], + [ -Infinity, -Infinity, -Infinity ]] + var hadGap = false + + fill_loop: + for (i = 1; i < positions.length; ++i) { + var a = positions[i - 1] + var b = positions[i] + + arcLengthArray.push(arcLength) + pointArray.push(a.slice()) + + for (j = 0; j < 3; ++j) { + if (isNaN(a[j]) || isNaN(b[j]) || + !isFinite(a[j]) || !isFinite(b[j])) { + + if (!connectGaps && buffer.length > 0) { + for (var k = 0; k < 24; ++k) { + buffer.push(buffer[buffer.length - 12]) + } + vertexCount += 2 + hadGap = true + } + + continue fill_loop + } + bounds[0][j] = Math.min(bounds[0][j], a[j], b[j]) + bounds[1][j] = Math.max(bounds[1][j], a[j], b[j]) } - if(fbo._depth_rb) { - gl.deleteRenderbuffer(fbo._depth_rb) - fbo._depth_rb = null + + var acolor, bcolor + if (Array.isArray(colors[0])) { + acolor = colors[i - 1] + bcolor = colors[i] + } else { + acolor = bcolor = colors } - for(var i=0; i maxFBOSize || - h < 0 || h > maxFBOSize) { - throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions') + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.nextPosition.location = 1 + shader.attributes.arcLength.location = 2 + shader.attributes.lineWidth.location = 3 + shader.attributes.color.location = 4 + + var pickShader = createPickShader(gl) + pickShader.attributes.position.location = 0 + pickShader.attributes.nextPosition.location = 1 + pickShader.attributes.arcLength.location = 2 + pickShader.attributes.lineWidth.location = 3 + pickShader.attributes.color.location = 4 + + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { + 'buffer': buffer, + 'size': 3, + 'offset': 0, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 3, + 'offset': 12, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 1, + 'offset': 24, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 1, + 'offset': 28, + 'stride': 48 + }, + { + 'buffer': buffer, + 'size': 4, + 'offset': 32, + 'stride': 48 + } + ]) + + // Create texture for dash pattern + var defaultTexture = ndarray(new Array(256 * 4), [256, 1, 4]) + for (var i = 0; i < 256 * 4; ++i) { + defaultTexture.data[i] = 255 } + var texture = createTexture(gl, defaultTexture) + texture.wrap = gl.REPEAT - //Update shape - fbo._shape[0] = w - fbo._shape[1] = h + var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture) + linePlot.update(options) + return linePlot +} - //Save framebuffer state - var state = saveFBOState(gl) +},{"./lib/shaders":126,"binary-search-bounds":128,"gl-buffer":118,"gl-texture2d":222,"gl-vao":226,"glsl-read-float":129,"ndarray":253}],128:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],129:[function(require,module,exports){ +module.exports = decodeFloat + +var UINT8_VIEW = new Uint8Array(4) +var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer) + +function decodeFloat(x, y, z, w) { + UINT8_VIEW[0] = w + UINT8_VIEW[1] = z + UINT8_VIEW[2] = y + UINT8_VIEW[3] = x + return FLOAT_VIEW[0] +} + +},{}],130:[function(require,module,exports){ +module.exports = invert + +/** + * Inverts a mat3 + * + * @alias mat3.invert + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2] + var a10 = a[3], a11 = a[4], a12 = a[5] + var a20 = a[6], a21 = a[7], a22 = a[8] + + var b01 = a22 * a11 - a12 * a21 + var b11 = -a22 * a10 + a12 * a20 + var b21 = a21 * a10 - a11 * a20 + + // Calculate the determinant + var det = a00 * b01 + a01 * b11 + a02 * b21 + + if (!det) return null + det = 1.0 / det + + out[0] = b01 * det + out[1] = (-a22 * a01 + a02 * a21) * det + out[2] = (a12 * a01 - a02 * a11) * det + out[3] = b11 * det + out[4] = (a22 * a00 - a02 * a20) * det + out[5] = (-a12 * a00 + a02 * a10) * det + out[6] = b21 * det + out[7] = (-a21 * a00 + a01 * a20) * det + out[8] = (a11 * a00 - a01 * a10) * det + + return out +} + +},{}],131:[function(require,module,exports){ +module.exports = clone; + +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {mat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ +function clone(a) { + var out = new Float32Array(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; +},{}],132:[function(require,module,exports){ +module.exports = create; + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ +function create() { + var out = new Float32Array(16); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; +},{}],133:[function(require,module,exports){ +module.exports = determinant; + +/** + * Calculates the determinant of a mat4 + * + * @param {mat4} a the source matrix + * @returns {Number} determinant of a + */ +function determinant(a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - //Resize framebuffer attachments - for(var i=0; i maxFBOSize || height < 0 || height > maxFBOSize) { - throw new Error('gl-fbo: Parameters are too large for FBO') - } +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], - //Handle each option type - options = options || {} + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, - //Figure out number of color buffers to use - var numColors = 1 - if('color' in options) { - numColors = Math.max(options.color|0, 0) - if(numColors < 0) { - throw new Error('gl-fbo: Must specify a nonnegative number of colors') - } - if(numColors > 1) { - //Check if multiple render targets supported - if(!WEBGL_draw_buffers) { - throw new Error('gl-fbo: Multiple draw buffer extension not supported') - } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) { - throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers') - } - } - } + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - //Determine whether to use floating point textures - var colorType = gl.UNSIGNED_BYTE - var OES_texture_float = gl.getExtension('OES_texture_float') - if(options.float && numColors > 0) { - if(!OES_texture_float) { - throw new Error('gl-fbo: Context does not support floating point textures') - } - colorType = gl.FLOAT - } else if(options.preferFloat && numColors > 0) { - if(OES_texture_float) { - colorType = gl.FLOAT + if (!det) { + return null; } - } - - //Check if we should use depth buffer - var useDepth = true - if('depth' in options) { - useDepth = !!options.depth - } + det = 1.0 / det; - //Check if we should use a stencil buffer - var useStencil = false - if('stencil' in options) { - useStencil = !!options.stencil - } + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return new Framebuffer( - gl, - width, - height, - colorType, - numColors, - useDepth, - useStencil, - WEBGL_draw_buffers) -} + return out; +}; +},{}],138:[function(require,module,exports){ +var identity = require('./identity'); -},{"gl-texture2d":324}],324:[function(require,module,exports){ -arguments[4][188][0].apply(exports,arguments) -},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":326}],325:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],326:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":317,"buffer":65,"dup":122}],327:[function(require,module,exports){ -'use strict' +module.exports = lookAt; -module.exports = createSelectBuffer +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {vec3} eye Position of the viewer + * @param {vec3} center Point the viewer is looking at + * @param {vec3} up vec3 pointing up + * @returns {mat4} out + */ +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, + eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2], + centerx = center[0], + centery = center[1], + centerz = center[2]; -var createFBO = require('gl-fbo') -var pool = require('typedarray-pool') -var ndarray = require('ndarray') + if (Math.abs(eyex - centerx) < 0.000001 && + Math.abs(eyey - centery) < 0.000001 && + Math.abs(eyez - centerz) < 0.000001) { + return identity(out); + } -var nextPow2 = require('bit-twiddle').nextPow2 + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; -var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_4_arg0_||255>_inline_4_arg1_||255>_inline_4_arg2_||255>_inline_4_arg3_){var _inline_4_l=_inline_4_arg4_-_inline_4_arg6_[0],_inline_4_a=_inline_4_arg5_-_inline_4_arg6_[1],_inline_4_f=_inline_4_l*_inline_4_l+_inline_4_a*_inline_4_a;_inline_4_f this.buffer.length) { - pool.free(this.buffer) - var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) - for(var i=0; i 8192) { - throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") - } - var height = 3 * size - if(canvas.height < height) { - canvas.height = height +function barycentricCoord(simplex, point) { + if(simplex.length === 2) { + var d0 = 0.0 + var d1 = 0.0 + for(var i=0; i<2; ++i) { + d0 += Math.pow(point[i] - simplex[0][i], 2) + d1 += Math.pow(point[i] - simplex[1][i], 2) + } + d0 = Math.sqrt(d0) + d1 = Math.sqrt(d1) + if(d0+d1 < 1e-6) { + return [1,0] + } + return [d1/(d0+d1),d0/(d1+d0)] + } else if(simplex.length === 3) { + var closestPoint = [0,0] + closestPointToTriangle(simplex[0], simplex[1], simplex[2], point, closestPoint) + return barycentric(simplex, closestPoint) } - - context.fillStyle = "#000" - context.fillRect(0, 0, canvas.width, canvas.height) - - context.fillStyle = "#fff" - context.fillText(str, size, 2*size) - - //Cut pixels from image - var pixelData = context.getImageData(0, 0, width, height) - var pixels = ndarray(pixelData.data, [height, width, 4]) - - return pixels.pick(-1,-1,0).transpose(1,0) + return [] } -function getContour(pixels, doSimplify) { - var contour = surfaceNets(pixels, 128) - if(doSimplify) { - return simplify(contour.cells, contour.positions, 0.25) - } - return { - edges: contour.cells, - positions: contour.positions +function interpolate(simplex, weights) { + var result = [0,0,0] + for(var i=0; i 1.0001) { + return null } + s += weights[i] } - return { - edges: [], - positions: [] + if(Math.abs(s - 1.0) > 0.001) { + return null } + return [closestIndex, interpolate(simplex, weights), weights] } +},{"barycentric":151,"polytope-closest-point/lib/closest_point_2d.js":153}],149:[function(require,module,exports){ -function vectorizeText(str, canvas, context, options) { - var size = options.size || 64 - var family = options.font || "normal" - - context.font = size + "px " + family - context.textAlign = "start" - context.textBaseline = "alphabetic" - context.direction = "ltr" - var pixels = getPixels(canvas, context, str, size) +var triVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}" +var triFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}" +var edgeVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}" +var edgeFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" +var pointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}" +var pointFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}" +var pickVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}" +var pickFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}" +var pickPointVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}" +var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}" +var contourFragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n" - return processPixels(pixels, options, size) +exports.meshShader = { + vertex: triVertSrc, + fragment: triFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'normal', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'} + ] } - -},{"cdt2d":356,"clean-pslg":367,"ndarray":1031,"planar-graph-to-polyline":424,"simplify-planar-graph":428,"surface-nets":450}],356:[function(require,module,exports){ -'use strict' - -var monotoneTriangulate = require('./lib/monotone') -var makeIndex = require('./lib/triangulation') -var delaunayFlip = require('./lib/delaunay') -var filterTriangulation = require('./lib/filter') - -module.exports = cdt2d - -function canonicalizeEdge(e) { - return [Math.min(e[0], e[1]), Math.max(e[0], e[1])] +exports.wireShader = { + vertex: edgeVertSrc, + fragment: edgeFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'} + ] } - -function compareEdge(a, b) { - return a[0]-b[0] || a[1]-b[1] +exports.pointShader = { + vertex: pointVertSrc, + fragment: pointFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'color', type: 'vec4'}, + {name: 'uv', type: 'vec2'}, + {name: 'pointSize', type: 'float'} + ] } - -function canonicalizeEdges(edges) { - return edges.map(canonicalizeEdge).sort(compareEdge) +exports.pickShader = { + vertex: pickVertSrc, + fragment: pickFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'id', type: 'vec4'} + ] } - -function getDefault(options, property, dflt) { - if(property in options) { - return options[property] - } - return dflt +exports.pointPickShader = { + vertex: pickPointVertSrc, + fragment: pickFragSrc, + attributes: [ + {name: 'position', type: 'vec3'}, + {name: 'pointSize', type: 'float'}, + {name: 'id', type: 'vec4'} + ] } - -function cdt2d(points, edges, options) { - - if(!Array.isArray(edges)) { - options = edges || {} - edges = [] - } else { - options = options || {} - edges = edges || [] - } - - //Parse out options - var delaunay = !!getDefault(options, 'delaunay', true) - var interior = !!getDefault(options, 'interior', true) - var exterior = !!getDefault(options, 'exterior', true) - var infinity = !!getDefault(options, 'infinity', false) - - //Handle trivial case - if((!interior && !exterior) || points.length === 0) { - return [] - } - - //Construct initial triangulation - var cells = monotoneTriangulate(points, edges) - - //If delaunay refinement needed, then improve quality by edge flipping - if(delaunay || interior !== exterior || infinity) { - - //Index all of the cells to support fast neighborhood queries - var triangulation = makeIndex(points.length, canonicalizeEdges(edges)) - for(var i=0; i 0) { - var b = stack.pop() - var a = stack.pop() + this.pointPositions = pointPositions + this.pointColors = pointColors + this.pointUVs = pointUVs + this.pointSizes = pointSizes + this.pointIds = pointIds + this.pointVAO = pointVAO + this.pointCount = 0 - //Find opposite pairs - var x = -1, y = -1 - var star = stars[a] - for(var i=1; i= 0) { - continue - } + this.lightPosition = [1e5, 1e5, 0] + this.ambientLight = 0.8 + this.diffuseLight = 0.8 + this.specularLight = 2.0 + this.roughness = 0.5 + this.fresnel = 1.5 - //Flip the edge - triangulation.flip(a, b) + this.opacity = 1.0 - //Test flipping neighboring edges - testFlip(points, triangulation, stack, x, a, y) - testFlip(points, triangulation, stack, a, y, x) - testFlip(points, triangulation, stack, y, b, x) - testFlip(points, triangulation, stack, b, x, y) - } + this._model = identityMatrix + this._view = identityMatrix + this._projection = identityMatrix + this._resolution = [1,1] } -},{"binary-search-bounds":312,"robust-in-sphere":361}],358:[function(require,module,exports){ -'use strict' - -var bsearch = require('binary-search-bounds') +var proto = SimplicialMesh.prototype -module.exports = classifyFaces +proto.isOpaque = function() { + return this.opacity >= 1 +} -function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) { - this.cells = cells - this.neighbor = neighbor - this.flags = flags - this.constraint = constraint - this.active = active - this.next = next - this.boundary = boundary +proto.isTransparent = function() { + return this.opacity < 1 } -var proto = FaceIndex.prototype +proto.pickSlots = 1 -function compareCell(a, b) { - return a[0] - b[0] || - a[1] - b[1] || - a[2] - b[2] +proto.setPickBase = function(id) { + this.pickId = id } -proto.locate = (function() { - var key = [0,0,0] - return function(a, b, c) { - var x = a, y = b, z = c - if(b < c) { - if(b < a) { - x = b - y = c - z = a - } - } else if(c < a) { - x = c - y = a - z = b - } - if(x < 0) { - return -1 - } - key[0] = x - key[1] = y - key[2] = z - return bsearch.eq(this.cells, key, compareCell) - } -})() +function genColormap(param) { + var colors = colormap({ + colormap: param + , nshades: 256 + , format: 'rgba' + }) -function indexCells(triangulation, infinity) { - //First get cells and canonicalize - var cells = triangulation.cells() - var nc = cells.length - for(var i=0; i 0 || next.length > 0) { - while(active.length > 0) { - var t = active.pop() - if(flags[t] === -side) { - continue + var level = getContour(this.cells, this.intensity, selection.intensity) + var cells = level.cells + var vertexIds = level.vertexIds + var vertexWeights = level.vertexWeights + var numCells = cells.length + var result = pool.mallocFloat32(2 * 3 * numCells) + var ptr = 0 + for(var i=0; i= 0 && flags[f] === 0) { - if(constraint[3*t+j]) { - next.push(f) - } else { - active.push(f) - flags[f] = side - } - } + var a = vertexIds[v][0] + var b = vertexIds[v][1] + var w = vertexWeights[v] + var wi = 1.0 - w + var pa = this.positions[a] + var pb = this.positions[b] + for(var k=0; k<3; ++k) { + result[ptr++] = w * pa[k] + wi * pb[k] } } + } + this.contourCount = (ptr / 3)|0 + this.contourPositions.update(result.subarray(0, ptr)) + pool.free(result) +} - //Swap arrays and loop - var tmp = next - next = active - active = tmp - next.length = 0 - side = -side +proto.update = function(params) { + params = params || {} + var gl = this.gl + + this.dirty = true + + if('contourEnable' in params) { + this.contourEnable = params.contourEnable + } + if('contourColor' in params) { + this.contourColor = params.contourColor + } + if('lineWidth' in params) { + this.lineWidth = params.lineWidth + } + if('lightPosition' in params) { + this.lightPosition = params.lightPosition + } + if('opacity' in params) { + this.opacity = params.opacity + } + if('ambient' in params) { + this.ambientLight = params.ambient + } + if('diffuse' in params) { + this.diffuseLight = params.diffuse + } + if('specular' in params) { + this.specularLight = params.specular + } + if('roughness' in params) { + this.roughness = params.roughness + } + if('fresnel' in params) { + this.fresnel = params.fresnel } - var result = filterCells(cells, flags, target) - if(infinity) { - return result.concat(index.boundary) + if(params.texture) { + this.texture.dispose() + this.texture = createTexture(gl, params.texture) + } else if (params.colormap) { + this.texture.shape = [256,256] + this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR + this.texture.magFilter = gl.LINEAR + this.texture.setPixels(genColormap(params.colormap)) + this.texture.generateMipmap() } - return result -} -},{"binary-search-bounds":312}],359:[function(require,module,exports){ -'use strict' + var cells = params.cells + var positions = params.positions -var bsearch = require('binary-search-bounds') -var orient = require('robust-orientation')[3] + if(!positions || !cells) { + return + } -var EVENT_POINT = 0 -var EVENT_END = 1 -var EVENT_START = 2 + var tPos = [] + var tCol = [] + var tNor = [] + var tUVs = [] + var tIds = [] -module.exports = monotoneTriangulate + var ePos = [] + var eCol = [] + var eUVs = [] + var eIds = [] -//A partial convex hull fragment, made of two unimonotone polygons -function PartialHull(a, b, idx, lowerIds, upperIds) { - this.a = a - this.b = b - this.idx = idx - this.lowerIds = lowerIds - this.upperIds = upperIds -} + var pPos = [] + var pCol = [] + var pUVs = [] + var pSiz = [] + var pIds = [] -//An event in the sweep line procedure -function Event(a, b, type, idx) { - this.a = a - this.b = b - this.type = type - this.idx = idx -} + //Save geometry data for picking calculations + this.cells = cells + this.positions = positions -//This is used to compare events for the sweep line procedure -// Points are: -// 1. sorted lexicographically -// 2. sorted by type (point < end < start) -// 3. segments sorted by winding order -// 4. sorted by index -function compareEvent(a, b) { - var d = - (a.a[0] - b.a[0]) || - (a.a[1] - b.a[1]) || - (a.type - b.type) - if(d) { return d } - if(a.type !== EVENT_POINT) { - d = orient(a.a, a.b, b.b) - if(d) { return d } + //Compute normals + var vertexNormals = params.vertexNormals + var cellNormals = params.cellNormals + var vertexNormalsEpsilon = params.vertexNormalsEpsilon === void(0) ? DEFAULT_VERTEX_NORMALS_EPSILON : params.vertexNormalsEpsilon + var faceNormalsEpsilon = params.faceNormalsEpsilon === void(0) ? DEFAULT_FACE_NORMALS_EPSILON : params.faceNormalsEpsilon + if(params.useFacetNormals && !cellNormals) { + cellNormals = normals.faceNormals(cells, positions, faceNormalsEpsilon) + } + if(!cellNormals && !vertexNormals) { + vertexNormals = normals.vertexNormals(cells, positions, vertexNormalsEpsilon) } - return a.idx - b.idx -} - -function testPoint(hull, p) { - return orient(hull.a, hull.b, p) -} -function addPoint(cells, hulls, points, p, idx) { - var lo = bsearch.lt(hulls, p, testPoint) - var hi = bsearch.gt(hulls, p, testPoint) - for(var i=lo; i 1 && orient( - points[lowerIds[m-2]], - points[lowerIds[m-1]], - p) > 0) { - cells.push( - [lowerIds[m-1], - lowerIds[m-2], - idx]) - m -= 1 - } - lowerIds.length = m - lowerIds.push(idx) + //UVs + var vertexUVs = params.vertexUVs + var vertexIntensity = params.vertexIntensity + var cellUVs = params.cellUVs + var cellIntensity = params.cellIntensity - //Insert p into upper hull - var upperIds = hull.upperIds - var m = upperIds.length - while(m > 1 && orient( - points[upperIds[m-2]], - points[upperIds[m-1]], - p) < 0) { - cells.push( - [upperIds[m-2], - upperIds[m-1], - idx]) - m -= 1 + var intensityLo = Infinity + var intensityHi = -Infinity + if(!vertexUVs && !cellUVs) { + if(vertexIntensity) { + for(var i=0; i b[0]) { - events.push( - new Event(b, a, EVENT_START, i), - new Event(a, b, EVENT_END, i)) - } - } + var c + if(vertexColors) { + c = vertexColors[v] + } else if(cellColors) { + c = cellColors[i] + } else { + c = meshColor + } + if(c.length === 3) { + eCol.push(c[0], c[1], c[2], 1) + } else { + eCol.push(c[0], c[1], c[2], c[3]) + } - //Sort events - events.sort(compareEvent) + var uv + if(vertexUVs) { + uv = vertexUVs[v] + } else if(vertexIntensity) { + uv = [ + (vertexIntensity[v] - intensityLo) / + (intensityHi - intensityLo), 0] + } else if(cellUVs) { + uv = cellUVs[i] + } else if(cellIntensity) { + uv = [ + (cellIntensity[i] - intensityLo) / + (intensityHi - intensityLo), 0] + } else { + uv = [ + (p[2] - intensityLo) / + (intensityHi - intensityLo), 0] + } + eUVs.push(uv[0], uv[1]) - //Initialize hull - var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52) - var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ] + eIds.push(i) + } + edgeCount += 1 + break - //Process events in order - var cells = [] - for(var i=0, numEvents=events.length; i= 0 - } -})() + this.pointCount = pointCount + this.edgeCount = edgeCount + this.triangleCount = triangleCount -proto.removeTriangle = function(i, j, k) { - var stars = this.stars - removePair(stars[i], j, k) - removePair(stars[j], k, i) - removePair(stars[k], i, j) -} + this.pointPositions.update(pPos) + this.pointColors.update(pCol) + this.pointUVs.update(pUVs) + this.pointSizes.update(pSiz) + this.pointIds.update(new Uint32Array(pIds)) -proto.addTriangle = function(i, j, k) { - var stars = this.stars - stars[i].push(j, k) - stars[j].push(k, i) - stars[k].push(i, j) -} + this.edgePositions.update(ePos) + this.edgeColors.update(eCol) + this.edgeUVs.update(eUVs) + this.edgeIds.update(new Uint32Array(eIds)) -proto.opposite = function(j, i) { - var list = this.stars[i] - for(var k=1, n=list.length; k>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } -} + this.texture.bind(0) -function makeProduct(a, b) { - if(a.charAt(0) === "m") { - if(b.charAt(0) === "w") { - var toks = a.split("[") - return ["w", b.substr(1), "m", toks[0].substr(1)].join("") - } else { - return ["prod(", a, ",", b, ")"].join("") - } - } else { - return makeProduct(b, a) - } -} + var invCameraMatrix = new Array(16) + multiply(invCameraMatrix, uniforms.view, uniforms.model) + multiply(invCameraMatrix, uniforms.projection, invCameraMatrix) + invert(invCameraMatrix, invCameraMatrix) -function sign(s) { - if(s & 1 !== 0) { - return "-" + for(var i=0; i<3; ++i) { + uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15] } - return "" -} -function determinant(m) { - if(m.length === 2) { - return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")] - } else { - var expr = [] - for(var i=0; i 0) { + var shader = this.triShader + shader.bind() + shader.uniforms = uniforms + + this.triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) + this.triangleVAO.unbind() } - return generateSum(terms) -} -function orientation(n) { - var pos = [] - var neg = [] - var m = matrix(n) - for(var i=0; i 0 && this.lineWidth > 0) { + var shader = this.lineShader + shader.bind() + shader.uniforms = uniforms + + this.edgeVAO.bind() + gl.lineWidth(this.lineWidth) + gl.drawArrays(gl.LINES, 0, this.edgeCount*2) + this.edgeVAO.unbind() } - var posExpr = generateSum(pos) - var negExpr = generateSum(neg) - var funcName = "exactInSphere" + n - var funcArgs = [] - for(var i=0; i 0) { + var shader = this.pointShader + shader.bind() + shader.uniforms = uniforms + + this.pointVAO.bind() + gl.drawArrays(gl.POINTS, 0, this.pointCount) + this.pointVAO.unbind() } - var code = ["function ", funcName, "(", funcArgs.join(), "){"] - for(var i=0; i 0 && this.contourLineWidth > 0) { + var shader = this.contourShader + shader.bind() + shader.uniforms = uniforms + + this.contourVAO.bind() + gl.drawArrays(gl.LINES, 0, this.contourCount) + this.contourVAO.unbind() } - code.push("var p=", posExpr, ",n=", negExpr, ",d=diff(p,n);return d[d.length-1];}return ", funcName) - var proc = new Function("sum", "diff", "prod", "scale", code.join("")) - return proc(robustSum, robustDiff, twoProduct, robustScale) } -function inSphere0() { return 0 } -function inSphere1() { return 0 } -function inSphere2() { return 0 } +proto.drawPick = function(params) { + params = params || {} -var CACHED = [ - inSphere0, - inSphere1, - inSphere2 -] + var gl = this.gl -function slowInSphere(args) { - var proc = CACHED[args.length] - if(!proc) { - proc = CACHED[args.length] = orientation(args.length) - } - return proc.apply(undefined, args) -} + var model = params.model || identityMatrix + var view = params.view || identityMatrix + var projection = params.projection || identityMatrix -function generateInSphereTest() { - while(CACHED.length <= NUM_EXPAND) { - CACHED.push(orientation(CACHED.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=NUM_EXPAND; ++i) { - args.push("a" + i) - procArgs.push("o" + i) + var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]] + for(var i=0; i<3; ++i) { + clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i]) + clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i]) } - var code = [ - "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=NUM_EXPAND; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") + + //Save camera parameters + this._model = [].slice.call(model) + this._view = [].slice.call(view) + this._projection = [].slice.call(projection) + this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight] + + var uniforms = { + model: model, + view: view, + projection: projection, + clipBounds: clipBounds, + pickId: this.pickId / 255.0, } - code.push("}var s=new Array(arguments.length);for(var i=0;i 0) { + this.triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3) + this.triangleVAO.unbind() } -} -generateInSphereTest() -},{"robust-scale":363,"robust-subtract":364,"robust-sum":365,"two-product":366}],362:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"dup":53}],363:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"dup":54,"two-product":366,"two-sum":362}],364:[function(require,module,exports){ -"use strict" + if(this.edgeCount > 0) { + this.edgeVAO.bind() + gl.lineWidth(this.lineWidth) + gl.drawArrays(gl.LINES, 0, this.edgeCount*2) + this.edgeVAO.unbind() + } -module.exports = robustSubtract + if(this.pointCount > 0) { + var shader = this.pointPickShader + shader.bind() + shader.uniforms = uniforms -//Easy case: Add two scalars -function scalarScalar(a, b) { - var x = a + b - var bv = x - a - var av = x - bv - var br = b - bv - var ar = a - av - var y = ar + br - if(y) { - return [y, x] + this.pointVAO.bind() + gl.drawArrays(gl.POINTS, 0, this.pointCount) + this.pointVAO.unbind() } - return [x] } -function robustSubtract(e, f) { - var ne = e.length|0 - var nf = f.length|0 - if(ne === 1 && nf === 1) { - return scalarScalar(e[0], -f[0]) - } - var n = ne + nf - var g = new Array(n) - var count = 0 - var eptr = 0 - var fptr = 0 - var abs = Math.abs - var ei = e[eptr] - var ea = abs(ei) - var fi = -f[fptr] - var fa = abs(fi) - var a, b - if(ea < fa) { - b = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - b = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - if((eptr < ne && ea < fa) || (fptr >= nf)) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - var x = a + b - var bv = x - a - var y = b - bv - var q0 = y - var q1 = x - var _x, _bv, _av, _br, _ar - while(eptr < ne && fptr < nf) { - if(ea < fa) { - a = ei - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - ea = abs(ei) - } - } else { - a = fi - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - fa = abs(fi) - } - } - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x + +proto.pick = function(pickData) { + if(!pickData) { + return null } - while(eptr < ne) { - a = ei - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - eptr += 1 - if(eptr < ne) { - ei = e[eptr] - } + if(pickData.id !== this.pickId) { + return null } - while(fptr < nf) { - a = fi - b = q0 - x = a + b - bv = x - a - y = b - bv - if(y) { - g[count++] = y - } - _x = q1 + x - _bv = _x - q1 - _av = _x - _bv - _br = x - _bv - _ar = q1 - _av - q0 = _ar + _br - q1 = _x - fptr += 1 - if(fptr < nf) { - fi = -f[fptr] - } + + var cellId = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2] + var cell = this.cells[cellId] + var positions = this.positions + + var simplex = new Array(cell.length) + for(var i=0; i 0) { - return [nextafter(f, -Infinity), f] - } else { - return [f, f] - } + this.triangleVAO.dispose() + this.trianglePositions.dispose() + this.triangleColors.dispose() + this.triangleUVs.dispose() + this.triangleNormals.dispose() + this.triangleIds.dispose() + + this.edgeVAO.dispose() + this.edgePositions.dispose() + this.edgeColors.dispose() + this.edgeUVs.dispose() + this.edgeIds.dispose() + + this.pointVAO.dispose() + this.pointPositions.dispose() + this.pointColors.dispose() + this.pointUVs.dispose() + this.pointSizes.dispose() + this.pointIds.dispose() + + this.contourVAO.dispose() + this.contourPositions.dispose() + this.contourShader.dispose() } -//Convert a list of edges in a pslg to bounding boxes -function boundEdges(points, edges) { - var bounds = new Array(edges.length) - for(var i=0; i= floatPoints.length) { - return ratPoints[idx-floatPoints.length] - } - var p = floatPoints[idx] - return [ rat(p[0]), rat(p[1]) ] + var b = new Array(d+1) + for(var i=0; i=0; --i) { - var junction = junctions[i] - var e = junction[0] + var x = solve(A, b) + var w = reduce(x[d+1]) + + if(w === 0) { + w = 1.0 + } + var y = new Array(d+1) + for(var i=0; i<=d; ++i) { + y[i] = reduce(x[i]) / w + } + return y +} +},{"robust-linear-solve":256}],152:[function(require,module,exports){ +var DEFAULT_NORMALS_EPSILON = 1e-6; +var DEFAULT_FACE_EPSILON = 1e-6; - var edge = edges[e] - var s = edge[0] - var t = edge[1] +//Estimate the vertex normals of a mesh +exports.vertexNormals = function(faces, positions, specifiedEpsilon) { - //Check if edge is not lexicographically sorted - var a = floatPoints[s] - var b = floatPoints[t] - if(((a[0] - b[0]) || (a[1] - b[1])) < 0) { - var tmp = s - s = t - t = tmp - } + var N = positions.length; + var normals = new Array(N); + var epsilon = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon; - //Split leading edge - edge[0] = s - var last = edge[1] = junction[1] + //Initialize normal array + for(var i=0; i 0 && junctions[i-1][0] === e) { - var junction = junctions[--i] - var next = junction[1] - if(useColor) { - edges.push([last, next, color]) - } else { - edges.push([last, next]) + //Shift indices back + p = c; + c = n; + n = f[(j+1) % f.length]; + + var v0 = positions[p]; + var v1 = positions[c]; + var v2 = positions[n]; + + //Compute infineteismal arcs + var d01 = new Array(3); + var m01 = 0.0; + var d21 = new Array(3); + var m21 = 0.0; + for(var k=0; k<3; ++k) { + d01[k] = v0[k] - v1[k]; + m01 += d01[k] * d01[k]; + d21[k] = v2[k] - v1[k]; + m21 += d21[k] * d21[k]; + } + + //Accumulate values in normal + if(m01 * m21 > epsilon) { + var norm = normals[c]; + var w = 1.0 / Math.sqrt(m01 * m21); + for(var k=0; k<3; ++k) { + var u = (k+1)%3; + var v = (k+2)%3; + norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]); + } } - last = next } + } - //Add final edge - if(useColor) { - edges.push([last, t, color]) + //Scale all normals to unit length + for(var i=0; i epsilon) { + var w = 1.0 / Math.sqrt(m); + for(var k=0; k<3; ++k) { + norm[k] *= w; + } } else { - edges.push([last, t]) + for(var k=0; k<3; ++k) { + norm[k] = 0.0; + } } } - //Return constructed rational points - return ratPoints + //Return the resulting set of patches + return normals; } -//Merge overlapping points -function dedupPoints(floatPoints, ratPoints, floatBounds) { - var numPoints = floatPoints.length + ratPoints.length - var uf = new UnionFind(numPoints) - - //Compute rational bounds - var bounds = floatBounds - for(var i=0; i b[2]) { - return 1 - } - return 0 -} -//Remove duplicate edge labels -function dedupEdges(edges, labels, useColor) { - if(edges.length === 0) { - return - } - if(labels) { - for(var i=0; i epsilon) { + l = 1.0 / Math.sqrt(l); + } else { + l = 0.0; } - } - if(useColor) { - edges.sort(compareLex3) - } else { - edges.sort(compareLex2) - } - var ptr = 1 - for(var i=1; i 0 || tjunctions.length > 0) +function closestPoint2d(V0, V1, V2, point, result) { + //Reallocate buffers if necessary + if(diff.length < point.length) { + diff = new Float64Array(point.length); + edge0 = new Float64Array(point.length); + edge1 = new Float64Array(point.length); } - - // More iterations necessary - return true -} - -//Main loop, runs PSLG clean up until completion -function cleanPSLG(points, edges, colors) { - var modified = false - - //If using colors, augment edges with color data - var prevEdges - if(colors) { - prevEdges = edges - var augEdges = new Array(edges.length) - for(var i=0; i= a00) { + s = 1.0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } else { + s = 0; + if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else if (-b1 >= a11) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else { // region 3 + s = 0; + if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else if (-b1 >= a11) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else if (t < 0) { // region 5 + t = 0; + if (b0 >= 0) { + s = 0; + sqrDistance = c; + } else if (-b0 >= a00) { + s = 1; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } else { // region 0 + // minimum at interior point + var invDet = 1.0 / det; + s *= invDet; + t *= invDet; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + var tmp0, tmp1, numer, denom; + + if (s < 0) { // region 2 + tmp0 = a01 + b0; + tmp1 = a11 + b1; + if (tmp1 > tmp0) { + numer = tmp1 - tmp0; + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + s = 1; + t = 0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = numer/denom; + t = 1 - s; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + s = 0; + if (tmp1 <= 0) { + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else if (b1 >= 0) { + t = 0; + sqrDistance = c; + } else { + t = -b1/a11; + sqrDistance = b1*t + c; + } + } + } else if (t < 0) { // region 6 + tmp0 = a01 + b1; + tmp1 = a00 + b0; + if (tmp1 > tmp0) { + numer = tmp1 - tmp0; + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + t = 1; + s = 0; + sqrDistance = a11 + 2.0*b1 + c; + } else { + t = numer/denom; + s = 1 - t; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } else { + t = 0; + if (tmp1 <= 0) { + s = 1; + sqrDistance = a00 + 2.0*b0 + c; + } else if (b0 >= 0) { + s = 0; + sqrDistance = c; + } else { + s = -b0/a00; + sqrDistance = b0*s + c; + } + } + } else { // region 1 + numer = a11 + b1 - a01 - b0; + if (numer <= 0) { + s = 0; + t = 1; + sqrDistance = a11 + 2.0*b1 + c; + } else { + denom = a00 - 2.0*a01 + a11; + if (numer >= denom) { + s = 1; + t = 0; + sqrDistance = a00 + 2.0*b0 + c; + } else { + s = numer/denom; + t = 1 - s; + sqrDistance = s*(a00*s + a01*t + 2.0*b0) + + t*(a01*s + a11*t + 2.0*b1) + c; + } + } } - edges = augEdges } - - //Run snap rounding until convergence - while(snapRound(points, edges, !!colors)) { - modified = true + var u = 1.0 - s - t; + for(var i=0; i 0) { - a = a.shln(shift) - } else if(shift < 0) { - b = b.shln(-shift) + edges[ptr++] = edges[i] + edges[ptr++] = edges[i+1] } - return rationalize(a, b) -} -},{"./div":371,"./is-rat":373,"./lib/is-bn":377,"./lib/num-to-bn":378,"./lib/rationalize":379,"./lib/str-to-bn":380}],373:[function(require,module,exports){ -'use strict' - -var isBN = require('./lib/is-bn') - -module.exports = isRat - -function isRat(x) { - return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1]) + return ndarray(edges, [(ptr/2)|0, 2]) } -},{"./lib/is-bn":377}],374:[function(require,module,exports){ -'use strict' - -var bn = require('bn.js') - -module.exports = sign - -function sign(x) { - return x.cmp(new bn(0)) +function getCrossingWeights(edges, values, signs, level) { + var edata = edges.data + var numEdges = edges.shape[0] + var weights = pool.mallocDouble(numEdges) + var ptr = 0 + for(var i=0; i 20) { - return 52 +function unpackEdges(edges) { + var ne = edges.shape[0]|0 + var edata = edges.data + var result = new Array(ne) + for(var i=0; i>1,v=E[2*m+1];', + 'if(v===b){return m}', + 'if(b 0) { + code.push(',') + } + code.push('[') + for(var j=0; j 0) { + code.push(',') + } + code.push('B(C,E,c[', f[0], '],c[', f[1], '])') + } + code.push(']') + } + code.push(');') + } -function str2BN(x) { - return new BN(x) -} + for(var i=d+1; i>1; --i) { + if(i < d+1) { + code.push('else ') + } + code.push('if(l===', i, '){') -},{"bn.js":383}],381:[function(require,module,exports){ -'use strict' + //Generate mask + var maskStr = [] + for(var j=0; j= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') - start++; - - if (base === 16) - this._parseHex(number, start); - else - this._parseBase(number, base, start); - - if (number[0] === '-') - this.sign = true; - - this.strip(); - - if (endian !== 'le') - return; - - this._initArray(this.toArray(), base, endian); -}; - -BN.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.sign = true; - number = -number; + for(var i=0; i 1) { + var scratch_shape = [] + for(var i=1; i 1) { + + //Copy data into scratch + code.push("dptr=0;sptr=ptr") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"left){", + "dptr=0", + "sptr=cptr-s0") + for(var i=1; ib){break __l}"].join("")) + for(var i=order.length-1; i>=1; --i) { + code.push( + "sptr+=e"+i, + "dptr+=f"+i, + "}") + } + + //Copy data back + code.push("dptr=cptr;sptr=cptr-s0") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j,"= 0; i -= 3) { - var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + //Copy scratch into cptr + code.push("dptr=cptr;sptr=0") + for(var i=order.length-1; i>=0; --i) { + var j = order[i] + if(j === 0) { + continue } + code.push(["for(i",j,"=0;i",j,">> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; + code.push(dataWrite("dptr", "scratch[sptr++]")) + for(var i=0; ileft)&&("+dataRead("cptr-s0")+">scratch)){", + dataWrite("cptr", dataRead("cptr-s0")), + "cptr-=s0", + "}", + dataWrite("cptr", "scratch")) } - return this.strip(); -}; - -function parseHex(str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) - r |= c - 49 + 0xa; - - // 'A' - 'F' - else if (c >= 17 && c <= 22) - r |= c - 17 + 0xa; - - // '0' - '9' - else - r |= c & 0xf; + + //Close outer loop body + code.push("}") + if(order.length > 1 && allocator) { + code.push("free(scratch)") + } + code.push("} return " + funcName) + + //Compile and link function + if(allocator) { + var result = new Function("malloc", "free", code.join("\n")) + return result(allocator[0], allocator[1]) + } else { + var result = new Function(code.join("\n")) + return result() } - return r; } -BN.prototype._parseHex = function _parseHex(number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - // Scan 24-bit chunks and add them to the number - var off = 0; - for (var i = number.length - 6, j = 0; i >= start; i -= 6) { - var w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; +function createQuickSort(order, dtype, insertionSort) { + var code = [ "'use strict'" ] + var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("") + var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length)) + var allocator = getMallocFree(dtype) + var labelCounter=0 + + code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) + + var vars = [ + "sixth=((right-left+1)/6)|0", + "index1=left+sixth", + "index5=right-sixth", + "index3=(left+right)>>1", + "index2=index3-sixth", + "index4=index3+sixth", + "el1=index1", + "el2=index2", + "el3=index3", + "el4=index4", + "el5=index5", + "less=left+1", + "great=right-1", + "pivots_are_equal=true", + "tmp", + "tmp0", + "x", + "y", + "z", + "k", + "ptr0", + "ptr1", + "ptr2", + "comp_pivot1=0", + "comp_pivot2=0", + "comp=0" + ] + + if(order.length > 1) { + var ele_size = [] + for(var i=1; i=0; --i) { + var j = order[i] + if(j === 0) { + continue + } + code.push(["for(i",j,"=0;i",j," 1) { + for(var i=0; i1) { + code.push("ptr_shift+=d"+j) + } else { + code.push("ptr0+=d"+j) + } + code.push("}") + } + } + + function lexicoLoop(label, ptrs, usePivot, body) { + if(ptrs.length === 1) { + code.push("ptr0="+toPointer(ptrs[0])) + } else { + for(var i=0; i 1) { + for(var i=0; i=1; --i) { + if(usePivot) { + code.push("pivot_ptr+=f"+i) + } + if(ptrs.length > 1) { + code.push("ptr_shift+=e"+i) + } else { + code.push("ptr0+=e"+i) + } + code.push("}") } } - if (i + 6 !== start) { - var w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; + + function cleanUp() { + if(order.length > 1 && allocator) { + code.push("free(pivot1)", "free(pivot2)") + } } - this.strip(); -}; - -function parseBase(str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) - r += c - 49 + 0xa; - - // 'A' - else if (c >= 17) - r += c - 17 + 0xa; - - // '0' - '9' - else - r += c; + + function compareSwap(a_id, b_id) { + var a = "el"+a_id + var b = "el"+b_id + if(order.length > 1) { + var lbl = "__l" + (++labelCounter) + lexicoLoop(lbl, [a, b], false, [ + "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n", + "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n", + "if(comp<0){break ", lbl, "}" + ].join("")) + } else { + code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join("")) + } } - return r; -} - -BN.prototype._parseBase = function _parseBase(number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) - limbLen++; - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) - this.words[0] += word; - else - this._iaddn(word); + + compareSwap(1, 2) + compareSwap(4, 5) + compareSwap(1, 3) + compareSwap(2, 3) + compareSwap(1, 4) + compareSwap(3, 4) + compareSwap(2, 5) + compareSwap(2, 3) + compareSwap(4, 5) + + if(order.length > 1) { + cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [ + "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n", + "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n", + "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n", + "x=",dataRead("ptr0"),"\n", + "y=",dataRead("ptr2"),"\n", + "z=",dataRead("ptr4"),"\n", + dataWrite("ptr5", "x"),"\n", + dataWrite("ptr6", "y"),"\n", + dataWrite("ptr7", "z") + ].join("")) + } else { + code.push([ + "pivot1=", dataRead(toPointer("el2")), "\n", + "pivot2=", dataRead(toPointer("el4")), "\n", + "pivots_are_equal=pivot1===pivot2\n", + "x=", dataRead(toPointer("el1")), "\n", + "y=", dataRead(toPointer("el3")), "\n", + "z=", dataRead(toPointer("el5")), "\n", + dataWrite(toPointer("index1"), "x"), "\n", + dataWrite(toPointer("index3"), "y"), "\n", + dataWrite(toPointer("index5"), "z") + ].join("")) } + - if (mod !== 0) { - var pow = 1; - var word = parseBase(number, i, number.length, base); - - for (var i = 0; i < mod; i++) - pow *= base; - this.imuln(pow); - if (this.words[0] + word < 0x4000000) - this.words[0] += word; - else - this._iaddn(word); + function moveElement(dst, src) { + if(order.length > 1) { + cacheLoop([dst, src], false, + dataWrite("ptr0", dataRead("ptr1")) + ) + } else { + code.push(dataWrite(toPointer(dst), dataRead(toPointer(src)))) + } } -}; - -BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - dest.words[i] = this.words[i]; - dest.length = this.length; - dest.sign = this.sign; - dest.red = this.red; -}; - -BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; -}; - -// Remove leading `0` from `this` -BN.prototype.strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) - this.length--; - return this._normSign(); -}; - -BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) - this.sign = false; - return this; -}; - -BN.prototype.inspect = function inspect() { - return (this.red ? ''; -}; - -/* - -var zeros = []; -var groupSizes = []; -var groupBases = []; - -var s = ''; -var i = -1; -while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; -} -groupSizes[0] = 0; -groupSizes[1] = 0; -groupBases[0] = 0; -groupBases[1] = 0; -var base = 2 - 1; -while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; + + moveElement("index2", "left") + moveElement("index4", "right") + + function comparePivot(result, ptr, n) { + if(order.length > 1) { + var lbl = "__l" + (++labelCounter) + lexicoLoop(lbl, [ptr], true, [ + result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n", + "if(",result,"!==0){break ", lbl, "}" + ].join("")) + } else { + code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join("")) + } } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; -} - -*/ - -var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' -]; - -var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 -]; - -var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 -]; - -BN.prototype.toString = function toString(base, padding) { - base = base || 10; - if (base === 16 || base === 'hex') { - var out = ''; - var off = 0; - var padding = padding | 0 || 1; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) - out = zeros[6 - word.length] + word + out; - else - out = word + out; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } + + function swapElements(a, b) { + if(order.length > 1) { + cacheLoop([a,b],false,[ + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", "tmp") + ].join("")) + } else { + code.push([ + "ptr0=",toPointer(a),"\n", + "ptr1=",toPointer(b),"\n", + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", "tmp") + ].join("")) } - if (carry !== 0) - out = carry.toString(16) + out; - while (out.length % padding !== 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - var out = ''; - var c = this.clone(); - c.sign = false; - while (c.cmpn(0) !== 0) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (c.cmpn(0) !== 0) - out = zeros[groupSize - r.length] + r + out; - else - out = r + out; + } + + function tripleSwap(k, less, great) { + if(order.length > 1) { + cacheLoop([k,less,great], false, [ + "tmp=",dataRead("ptr0"),"\n", + dataWrite("ptr0", dataRead("ptr1")),"\n", + dataWrite("ptr1", dataRead("ptr2")),"\n", + dataWrite("ptr2", "tmp") + ].join("")) + code.push("++"+less, "--"+great) + } else { + code.push([ + "ptr0=",toPointer(k),"\n", + "ptr1=",toPointer(less),"\n", + "ptr2=",toPointer(great),"\n", + "++",less,"\n", + "--",great,"\n", + "tmp=", dataRead("ptr0"), "\n", + dataWrite("ptr0", dataRead("ptr1")), "\n", + dataWrite("ptr1", dataRead("ptr2")), "\n", + dataWrite("ptr2", "tmp") + ].join("")) } - if (this.cmpn(0) === 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else { - assert(false, 'Base should be between 2 and 36'); } -}; - -BN.prototype.toJSON = function toJSON() { - return this.toString(16); -}; - -BN.prototype.toArray = function toArray(endian) { - this.strip(); - var res = new Array(this.byteLength()); - res[0] = 0; - - var q = this.clone(); - if (endian !== 'le') { - // Assume big-endian - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); - - res[res.length - i - 1] = b; + + function swapAndDecrement(k, great) { + swapElements(k, great) + code.push("--"+great) + } + + code.push("if(pivots_are_equal){") + //Pivots are equal case + code.push("for(k=less;k<=great;++k){") + comparePivot("comp", "k", 1) + code.push("if(comp===0){continue}") + code.push("if(comp<0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + code.push("while(true){") + comparePivot("comp", "great", 1) + code.push("if(comp>0){") + code.push("great--") + code.push("}else if(comp<0){") + tripleSwap("k", "less", "great") + code.push("break") + code.push("}else{") + swapAndDecrement("k", "great") + code.push("break") + code.push("}") + code.push("}") + code.push("}") + code.push("}") + code.push("}else{") + //Pivots not equal case + code.push("for(k=less;k<=great;++k){") + comparePivot("comp_pivot1", "k", 1) + code.push("if(comp_pivot1<0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + comparePivot("comp_pivot2", "k", 2) + code.push("if(comp_pivot2>0){") + code.push("while(true){") + comparePivot("comp", "great", 2) + code.push("if(comp>0){") + code.push("if(--great1) { + cacheLoop([mem_dest, pivot_dest], true, [ + dataWrite("ptr0", dataRead("ptr1")), "\n", + dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join("")) + ].join("")) + } else { + code.push( + dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))), + dataWrite(toPointer(pivot_dest), "pivot"+pivot)) } - } else { - // Assume little-endian - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); + } + + storePivot("left", "(less-1)", 1) + storePivot("right", "(great+1)", 2) - res[i] = b; + //Recursive sort call + function doSort(left, right) { + code.push([ + "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n", + "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", + "}else{\n", + funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n", + "}" + ].join("")) + } + doSort("left", "(less-2)") + doSort("(great+2)", "right") + + //If pivots are equal, then early out + code.push("if(pivots_are_equal){") + cleanUp() + code.push("return") + code.push("}") + + function walkPointer(ptr, pivot, body) { + if(order.length > 1) { + code.push(["__l",++labelCounter,":while(true){"].join("")) + cacheLoop([ptr], true, [ + "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}" + ].join("")) + code.push(body, "}") + } else { + code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join("")) } } + + //Check bounds + code.push("if(lessindex5){") + + walkPointer("less", 1, "++less") + walkPointer("great", 2, "--great") + + code.push("for(k=less;k<=great;++k){") + comparePivot("comp_pivot1", "k", 1) + code.push("if(comp_pivot1===0){") + code.push("if(k!==less){") + swapElements("k", "less") + code.push("}") + code.push("++less") + code.push("}else{") + comparePivot("comp_pivot2", "k", 2) + code.push("if(comp_pivot2===0){") + code.push("while(true){") + comparePivot("comp", "great", 2) + code.push("if(comp===0){") + code.push("if(--great 1 && allocator) { + var compiled = new Function("insertionSort", "malloc", "free", code.join("\n")) + return compiled(insertionSort, allocator[0], allocator[1]) + } + var compiled = new Function("insertionSort", code.join("\n")) + return compiled(insertionSort) +} - return res; -}; - -if (Math.clz32) { - BN.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); - }; -} else { - BN.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; +function compileSort(order, dtype) { + var code = ["'use strict'"] + var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("") + var funcArgs = [ "array" ] + + code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join("")) + + //Unpack local variables from array + var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"] + for(var i=0; i= 0x40) { - r += 7; - t >>>= 7; + if(nprod.length === 0) { + scratch_stride[k] = "1" + } else { + scratch_stride[k] = nprod.join("*") } - if (t >= 0x8) { - r += 4; - t >>>= 4; + nprod.push("n"+k) + } + + var p = -1, q = -1 + for(var i=0; i 0) { + vars.push(["d",j,"=s",j,"-d",p,"*n",p].join("")) + } else { + vars.push(["d",j,"=s",j].join("")) + } + p = j } - if (t >= 0x02) { - r += 2; - t >>>= 2; + var k = order.length-1-i + if(k !== 0) { + if(q > 0) { + vars.push(["e",k,"=s",k,"-e",q,"*n",q, + ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join("")) + } else { + vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join("")) + } + q = k } - return r + t; - }; -} - -BN.prototype._zeroBits = function _zeroBits(w) { - // Short-cut - if (w === 0) - return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; } - if ((t & 0x1) === 0) - r++; - return r; -}; + + //Declare local variables + code.push("var " + vars.join(",")) + + //Create arguments for subroutine + var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length)) + + //Call main sorting routine + code.push([ + "if(n0<=",INSERTION_SORT_THRESHOLD,"){", + "insertionSort(", sortArgs.join(","), ")}else{", + "quickSort(", sortArgs.join(","), + ")}" + ].join("")) + + //Return + code.push("}return " + funcName) + + //Link everything together + var result = new Function("insertionSort", "quickSort", code.join("\n")) + var insertionSort = createInsertionSort(order, dtype) + var quickSort = createQuickSort(order, dtype, insertionSort) + return result(insertionSort, quickSort) +} -// Return number of used bits in a BN -BN.prototype.bitLength = function bitLength() { - var hi = 0; - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; -}; +module.exports = compileSort +},{"typedarray-pool":278}],158:[function(require,module,exports){ +"use strict" -// Number of trailing zero bits -BN.prototype.zeroBits = function zeroBits() { - if (this.cmpn(0) === 0) - return 0; +var compile = require("./lib/compile_sort.js") +var CACHE = {} - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) - break; +function sort(array) { + var order = array.order + var dtype = array.dtype + var typeSig = [order, dtype ] + var typeName = typeSig.join(":") + var compiled = CACHE[typeName] + if(!compiled) { + CACHE[typeName] = compiled = compile(order, dtype) } - return r; -}; - -BN.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); -}; - -// Return negative clone of `this` -BN.prototype.neg = function neg() { - if (this.cmpn(0) === 0) - return this.clone(); - - var r = this.clone(); - r.sign = !this.sign; - return r; -}; - - -// Or `num` with `this` in-place -BN.prototype.ior = function ior(num) { - this.sign = this.sign || num.sign; - - while (this.length < num.length) - this.words[this.length++] = 0; - - for (var i = 0; i < num.length; i++) - this.words[i] = this.words[i] | num.words[i]; - - return this.strip(); -}; - - -// Or `num` with `this` -BN.prototype.or = function or(num) { - if (this.length > num.length) - return this.clone().ior(num); - else - return num.clone().ior(this); -}; + compiled(array) + return array +} +module.exports = sort +},{"./lib/compile_sort.js":157}],159:[function(require,module,exports){ +'use strict' -// And `num` with `this` in-place -BN.prototype.iand = function iand(num) { - this.sign = this.sign && num.sign; +module.exports = createBoxes - // b = min-length(num, this) - var b; - if (this.length > num.length) - b = num; - else - b = this; +var createBuffer = require('gl-buffer') +var createShader = require('gl-shader') - for (var i = 0; i < b.length; i++) - this.words[i] = this.words[i] & num.words[i]; +var shaders = require('./shaders') - this.length = b.length; +function Boxes(plot, vbo, shader) { + this.plot = plot + this.vbo = vbo + this.shader = shader +} - return this.strip(); -}; +var proto = Boxes.prototype +proto.bind = function() { + var shader = this.shader + this.vbo.bind() + this.shader.bind() + shader.attributes.coord.pointer() + shader.uniforms.screenBox = this.plot.screenBox +} -// And `num` with `this` -BN.prototype.and = function and(num) { - if (this.length > num.length) - return this.clone().iand(num); - else - return num.clone().iand(this); -}; +proto.drawBox = (function() { + var lo = [0,0] + var hi = [0,0] + return function(loX, loY, hiX, hiY, color) { + var plot = this.plot + var shader = this.shader + var gl = plot.gl + lo[0] = loX + lo[1] = loY + hi[0] = hiX + hi[1] = hiY -// Xor `num` with `this` in-place -BN.prototype.ixor = function ixor(num) { - this.sign = this.sign || num.sign; + shader.uniforms.lo = lo + shader.uniforms.hi = hi + shader.uniforms.color = color - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) } +}()) - for (var i = 0; i < b.length; i++) - this.words[i] = a.words[i] ^ b.words[i]; - - if (this !== a) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - - this.length = a.length; - - return this.strip(); -}; - - -// Xor `num` with `this` -BN.prototype.xor = function xor(num) { - if (this.length > num.length) - return this.clone().ixor(num); - else - return num.clone().ixor(this); -}; - - -// Set `bit` of `this` -BN.prototype.setn = function setn(bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - while (this.length <= off) - this.words[this.length++] = 0; - - if (val) - this.words[off] = this.words[off] | (1 << wbit); - else - this.words[off] = this.words[off] & ~(1 << wbit); - - return this.strip(); -}; +proto.dispose = function() { + this.vbo.dispose() + this.shader.dispose() +} +function createBoxes(plot) { + var gl = plot.gl + var vbo = createBuffer(gl, [ + 0,0, + 0,1, + 1,0, + 1,1]) + var shader = createShader(gl, shaders.boxVert, shaders.lineFrag) + return new Boxes(plot, vbo, shader) +} -// Add `num` to `this` in-place -BN.prototype.iadd = function iadd(num) { - // negative + positive - if (this.sign && !num.sign) { - this.sign = false; - var r = this.isub(num); - this.sign = !this.sign; - return this._normSign(); +},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],160:[function(require,module,exports){ +'use strict' - // positive + negative - } else if (!this.sign && num.sign) { - num.sign = false; - var r = this.isub(num); - num.sign = true; - return r._normSign(); - } +module.exports = createGrid - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } +var createBuffer = require('gl-buffer') +var createShader = require('gl-shader') +var bsearch = require('binary-search-bounds') +var shaders = require('./shaders') - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] + b.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } +function Grid(plot, vbo, shader, tickShader) { + this.plot = plot + this.vbo = vbo + this.shader = shader + this.tickShader = tickShader + this.ticks = [[], []] +} - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) - this.words[i] = a.words[i]; - } +function compareTickNum(a, b) { + return a - b +} - return this; -}; +var proto = Grid.prototype -// Add `num` to `this` -BN.prototype.add = function add(num) { - if (num.sign && !this.sign) { - num.sign = false; - var res = this.sub(num); - num.sign = true; - return res; - } else if (!num.sign && this.sign) { - this.sign = false; - var res = num.sub(this); - this.sign = true; - return res; - } +proto.draw = (function() { - if (this.length > num.length) - return this.clone().iadd(num); - else - return num.clone().iadd(this); -}; + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var DATA_AXIS = [0,0] -// Subtract `num` from `this` in-place -BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.sign) { - num.sign = false; - var r = this.iadd(num); - num.sign = true; - return r._normSign(); + return function() { + var plot = this.plot + var vbo = this.vbo + var shader = this.shader + var ticks = this.ticks + var gl = plot.gl + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var viewPixels = plot.viewBox + var lineWidth = plot.gridLineWidth + var gridColor = plot.gridLineColor + var gridEnable = plot.gridLineEnable + var pixelRatio = plot.pixelRatio - // -this - num = -(this + num) - } else if (this.sign) { - this.sign = false; - this.iadd(num); - this.sign = true; - return this._normSign(); - } + for(var i=0; i<2; ++i) { + var lo = bounds[i] + var hi = bounds[i+2] + var boundScale = hi - lo + var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) + var dataWidth = dataBox[i+2] - dataBox[i] + DATA_SCALE[i] = 2.0 * boundScale / dataWidth + DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth + } - // At this point both numbers are positive - var cmp = this.cmp(num); + shader.bind() + vbo.bind() + shader.attributes.dataCoord.pointer() + shader.uniforms.dataShift = DATA_SHIFT + shader.uniforms.dataScale = DATA_SCALE - // Optimization - zeroify - if (cmp === 0) { - this.sign = false; - this.length = 1; - this.words[0] = 0; - return this; - } + var offset = 0 + for(var i=0; i<2; ++i) { + DATA_AXIS[0] = DATA_AXIS[1] = 0 + DATA_AXIS[i] = 1 + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.lineWidth = lineWidth[i] / (viewPixels[i+2] - viewPixels[i]) * pixelRatio + shader.uniforms.color = gridColor[i] - // a > b - var a; - var b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + var size = ticks[i].length * 6 + if(gridEnable[i] && size) { + gl.drawArrays(gl.TRIANGLES, offset, size) + } + offset += size + } } +})() - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] - b.words[i] + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } +proto.drawTickMarks = (function() { + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var X_AXIS = [1,0] + var Y_AXIS = [0,1] + var SCR_OFFSET = [0,0] + var TICK_SCALE = [0,0] - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - this.length = Math.max(this.length, i); + return function() { + var plot = this.plot + var vbo = this.vbo + var shader = this.tickShader + var ticks = this.ticks + var gl = plot.gl + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var viewBox = plot.viewBox + var pixelRatio = plot.pixelRatio + var screenBox = plot.screenBox - if (a !== this) - this.sign = true; + var screenWidth = screenBox[2] - screenBox[0] + var screenHeight = screenBox[3] - screenBox[1] + var viewWidth = viewBox[2] - viewBox[0] + var viewHeight = viewBox[3] - viewBox[1] - return this.strip(); -}; + for(var i=0; i<2; ++i) { + var lo = bounds[i] + var hi = bounds[i+2] + var boundScale = hi - lo + var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) + var dataWidth = (dataBox[i+2] - dataBox[i]) + DATA_SCALE[i] = 2.0 * boundScale / dataWidth + DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth + } -// Subtract `num` from `this` -BN.prototype.sub = function sub(num) { - return this.clone().isub(num); -}; + DATA_SCALE[0] *= viewWidth / screenWidth + DATA_SHIFT[0] *= viewWidth / screenWidth -/* -// NOTE: This could be potentionally used to generate loop-less multiplications -function _genCombMulTo(alen, blen) { - var len = alen + blen - 1; - var src = [ - 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + - 'mask = 0x3ffffff, shift = 0x4000000;', - 'out.length = ' + len + ';' - ]; - for (var k = 0; k < len; k++) { - var minJ = Math.max(0, k - alen + 1); - var maxJ = Math.min(k, blen - 1); + DATA_SCALE[1] *= viewHeight / screenHeight + DATA_SHIFT[1] *= viewHeight / screenHeight - for (var j = minJ; j <= maxJ; j++) { - var i = k - j; - var mul = 'a[' + i + '] * b[' + j + ']'; + shader.bind() + vbo.bind() - if (j === minJ) { - src.push('w = ' + mul + ' + c;'); - src.push('c = (w / shift) | 0;'); - } else { - src.push('w += ' + mul + ';'); - src.push('c += (w / shift) | 0;'); - } - src.push('w &= mask;'); - } - src.push('o[' + k + '] = w;'); - } - src.push('if (c !== 0) {', - ' o[' + k + '] = c;', - ' out.length++;', - '}', - 'return out;'); + shader.attributes.dataCoord.pointer() - return src.join('\n'); -} -*/ + var uniforms = shader.uniforms + uniforms.dataShift = DATA_SHIFT + uniforms.dataScale = DATA_SCALE -BN.prototype._smallMulTo = function _smallMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; + var tickMarkLength = plot.tickMarkLength + var tickMarkWidth = plot.tickMarkWidth + var tickMarkColor = plot.tickMarkColor - var carry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; + var xTicksOffset = 0 + var yTicksOffset = ticks[0].length * 6 - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - } - out.words[k] = rword; - carry = ncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } + var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xEnd = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length) + var xOffset = xTicksOffset + 6 * xStart + var xCount = 6 * Math.max(0, xEnd - xStart) - return out.strip(); -}; + var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yEnd = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length) + var yOffset = yTicksOffset + 6 * yStart + var yCount = 6 * Math.max(0, yEnd - yStart) -BN.prototype._bigMulTo = function _bigMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; + SCR_OFFSET[0] = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0 + SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkLength[1] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkWidth[1] * pixelRatio / screenHeight - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; + if(yCount) { + uniforms.color = tickMarkColor[1] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = Y_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, yOffset, yCount) + } - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[0] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[0] * pixelRatio / screenHeight - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; + if(xCount) { + uniforms.color = tickMarkColor[0] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - return out.strip(); -}; + SCR_OFFSET[0] = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0 + SCR_OFFSET[1] = (viewBox[3] + viewBox[1]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkLength[3] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkWidth[3] * pixelRatio / screenHeight -BN.prototype.mulTo = function mulTo(num, out) { - var res; - if (this.length + num.length < 63) - res = this._smallMulTo(num, out); - else - res = this._bigMulTo(num, out); - return res; -}; + if(yCount) { + uniforms.color = tickMarkColor[3] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = Y_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, yOffset, yCount) + } -// Multiply `this` by `num` -BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); -}; + SCR_OFFSET[0] = (viewBox[2] + viewBox[0]) / screenWidth - 1.0 + SCR_OFFSET[1] = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0 + TICK_SCALE[0] = tickMarkWidth[2] * pixelRatio / screenWidth + TICK_SCALE[1] = tickMarkLength[2] * pixelRatio / screenHeight -// In-place Multiplication -BN.prototype.imul = function imul(num) { - if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { - this.words[0] = 0; - this.length = 1; - return this; + if(xCount) { + uniforms.color = tickMarkColor[2] + uniforms.tickScale = TICK_SCALE + uniforms.dataAxis = X_AXIS + uniforms.screenOffset = SCR_OFFSET + gl.drawArrays(gl.TRIANGLES, xOffset, xCount) + } } +})() - var tlen = this.length; - var nlen = num.length; +proto.update = (function() { + var OFFSET_X = [1, 1, -1, -1, 1, -1] + var OFFSET_Y = [1, -1, 1, 1, -1, -1] - this.sign = num.sign !== this.sign; - this.length = this.length + num.length; - this.words[this.length - 1] = 0; + return function(options) { + var ticks = options.ticks + var bounds = options.bounds + var data = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length)) - for (var k = this.length - 2; k >= 0; k--) { - // Sum all words with the same `i + j = k` and accumulate `carry`, - // note that carry could be >= 0x3ffffff - var carry = 0; - var rword = 0; - var maxJ = Math.min(k, nlen - 1); - for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i]; - var b = num.words[j]; - var r = a * b; + var zeroLineEnable = this.plot.zeroLineEnable - var lo = r & 0x3ffffff; - carry += (r / 0x4000000) | 0; - lo += rword; - rword = lo & 0x3ffffff; - carry += lo >>> 26; + var ptr = 0 + var gridTicks = [[], []] + for(var dim=0; dim<2; ++dim) { + var localTicks = gridTicks[dim] + var axisTicks = ticks[dim] + var lo = bounds[dim] + var hi = bounds[dim+2] + for(var i=0; i>> 26; + this.ticks = gridTicks + this.vbo.update(data) } +})() - return this.strip(); -}; +proto.dispose = function() { + this.vbo.dispose() + this.shader.dispose() + this.tickShader.dispose() +} -BN.prototype.imuln = function imuln(num) { - assert(typeof num === 'number'); +function createGrid(plot) { + var gl = plot.gl + var vbo = createBuffer(gl) + var shader = createShader(gl, shaders.gridVert, shaders.gridFrag) + var tickShader = createShader(gl, shaders.tickVert, shaders.gridFrag) + var grid = new Grid(plot, vbo, shader, tickShader) + return grid +} - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i] * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } +},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197}],161:[function(require,module,exports){ +'use strict' - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } +module.exports = createLines - return this; -}; +var createBuffer = require('gl-buffer') +var createShader = require('gl-shader') -BN.prototype.muln = function muln(num) { - return this.clone().imuln(num); -}; +var shaders = require('./shaders') -// `this` * `this` -BN.prototype.sqr = function sqr() { - return this.mul(this); -}; +function Lines(plot, vbo, shader) { + this.plot = plot + this.vbo = vbo + this.shader = shader +} -// `this` * `this` in-place -BN.prototype.isqr = function isqr() { - return this.mul(this); -}; +var proto = Lines.prototype -// Shift-left in-place -BN.prototype.ishln = function ishln(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); +proto.bind = function() { + var shader = this.shader + this.vbo.bind() + this.shader.bind() + shader.attributes.coord.pointer() + shader.uniforms.screenBox = this.plot.screenBox +} - if (r !== 0) { - var carry = 0; - for (var i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - if (carry) { - this.words[i] = carry; - this.length++; - } - } +proto.drawLine = (function() { + var start = [0,0] + var end = [0,0] + return function(startX, startY, endX, endY, width, color) { + var plot = this.plot + var shader = this.shader + var gl = plot.gl - if (s !== 0) { - for (var i = this.length - 1; i >= 0; i--) - this.words[i + s] = this.words[i]; - for (var i = 0; i < s; i++) - this.words[i] = 0; - this.length += s; + start[0] = startX + start[1] = startY + end[0] = endX + end[1] = endY + + shader.uniforms.start = start + shader.uniforms.end = end + shader.uniforms.width = width * plot.pixelRatio + shader.uniforms.color = color + + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) } +}()) - return this.strip(); -}; +proto.dispose = function() { + this.vbo.dispose() + this.shader.dispose() +} -// Shift-right in-place -// NOTE: `hint` is a lowest bit before trailing zeroes -// NOTE: if `extended` is present - it will be filled with destroyed bits -BN.prototype.ishrn = function ishrn(bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) - h = (hint - (hint % 26)) / 26; - else - h = 0; +function createLines(plot) { + var gl = plot.gl + var vbo = createBuffer(gl, [ + -1,-1, + -1,1, + 1,-1, + 1,1]) + var shader = createShader(gl, shaders.lineVert, shaders.lineFrag) + var lines = new Lines(plot, vbo, shader) + return lines +} - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; +},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],162:[function(require,module,exports){ +'use strict' - h -= s; - h = Math.max(0, h); - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) - maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (var i = 0; i < this.length; i++) - this.words[i] = this.words[i + s]; - } else { - this.words[0] = 0; - this.length = 1; - } +var FRAGMENT = "precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n" - var carry = 0; - for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i]; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } +module.exports = { + lineVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n", + lineFrag: FRAGMENT, + textVert: "#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n", + textFrag: FRAGMENT, + gridVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n", + gridFrag: FRAGMENT, + boxVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n", + tickVert: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n" +} - // Push carried bits as a mask - if (maskedWords && carry !== 0) - maskedWords.words[maskedWords.length++] = carry; +},{}],163:[function(require,module,exports){ +'use strict' - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } +module.exports = createTextElements - this.strip(); +var createBuffer = require('gl-buffer') +var createShader = require('gl-shader') +var getText = require('text-cache') +var bsearch = require('binary-search-bounds') +var shaders = require('./shaders') - return this; -}; +function TextElements(plot, vbo, shader) { + this.plot = plot + this.vbo = vbo + this.shader = shader + this.tickOffset = [[],[]] + this.tickX = [[],[]] + this.labelOffset = [0,0] + this.labelCount = [0,0] +} -// Shift-left -BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); -}; +var proto = TextElements.prototype -// Shift-right -BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); -}; +proto.drawTicks = (function() { + var DATA_AXIS = [0,0] + var SCREEN_OFFSET = [0,0] + var ZERO_2 = [0,0] -// Test if n bit is set -BN.prototype.testn = function testn(bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; + return function(axis) { + var plot = this.plot + var shader = this.shader + var tickX = this.tickX[axis] + var tickOffset = this.tickOffset[axis] + var gl = plot.gl + var viewBox = plot.viewBox + var dataBox = plot.dataBox + var screenBox = plot.screenBox + var pixelRatio = plot.pixelRatio + var tickEnable = plot.tickEnable + var tickPad = plot.tickPad + var textColor = plot.tickColor + var textAngle = plot.tickAngle + var tickLength = plot.tickMarkLength + + var labelEnable = plot.labelEnable + var labelPad = plot.labelPad + var labelColor = plot.labelColor + var labelAngle = plot.labelAngle + var labelOffset = this.labelOffset[axis] + var labelCount = this.labelCount[axis] - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - return false; - } + var start = bsearch.lt(tickX, dataBox[axis]) + var end = bsearch.le(tickX, dataBox[axis+2]) - // Check bit and return - var w = this.words[s]; + DATA_AXIS[0] = DATA_AXIS[1] = 0 + DATA_AXIS[axis] = 1 - return !!(w & q); -}; + SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0 -// Return only lowers bits of number (in-place) -BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; + var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1] - assert(!this.sign, 'imaskn works only with positive numbers'); + SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0 + if(tickEnable[axis]) { + SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis] + if(start < end && tickOffset[end] > tickOffset[start]) { + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = textColor[axis] + shader.uniforms.angle = textAngle[axis] + gl.drawArrays( + gl.TRIANGLES, + tickOffset[start], + tickOffset[end] - tickOffset[start]) + } + } + if(labelEnable[axis] && labelCount) { + SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis] + shader.uniforms.dataAxis = ZERO_2 + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = labelColor[axis] + shader.uniforms.angle = labelAngle[axis] + gl.drawArrays( + gl.TRIANGLES, + labelOffset, + labelCount) + } - if (r !== 0) - s++; - this.length = Math.min(s, this.length); + SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0 + if(tickEnable[axis+2]) { + SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2] + if(start < end && tickOffset[end] > tickOffset[start]) { + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = textColor[axis+2] + shader.uniforms.angle = textAngle[axis+2] + gl.drawArrays( + gl.TRIANGLES, + tickOffset[start], + tickOffset[end] - tickOffset[start]) + } + } + if(labelEnable[axis+2] && labelCount) { + SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2] + shader.uniforms.dataAxis = ZERO_2 + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.color = labelColor[axis+2] + shader.uniforms.angle = labelAngle[axis+2] + gl.drawArrays( + gl.TRIANGLES, + labelOffset, + labelCount) + } - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; } +})() - return this.strip(); -}; +proto.drawTitle = (function() { + var DATA_AXIS = [0,0] + var SCREEN_OFFSET = [0,0] -// Return only lowers bits of number -BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); -}; + return function() { + var plot = this.plot + var shader = this.shader + var gl = plot.gl + var screenBox = plot.screenBox + var titleCenter = plot.titleCenter + var titleAngle = plot.titleAngle + var titleColor = plot.titleColor + var titleCenter = plot.titleCenter + var pixelRatio = plot.pixelRatio -// Add plain number `num` to `this` -BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.isubn(-num); + if(!this.titleCount) { + return + } - // Possible sign change - if (this.sign) { - if (this.length === 1 && this.words[0] < num) { - this.words[0] = num - this.words[0]; - this.sign = false; - return this; + for(var i=0; i<2; ++i) { + SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) / + (screenBox[2+i] - screenBox[i]) - 1 } - this.sign = false; - this.isubn(num); - this.sign = true; - return this; - } + shader.bind() + shader.uniforms.dataAxis = DATA_AXIS + shader.uniforms.screenOffset = SCREEN_OFFSET + shader.uniforms.angle = titleAngle + shader.uniforms.color = titleColor - // Add without checks - return this._iaddn(num); -}; + gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount) + } +})() -BN.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; +proto.bind = (function() { + var DATA_SHIFT = [0,0] + var DATA_SCALE = [0,0] + var TEXT_SCALE = [0,0] - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) - this.words[i + 1] = 1; - else - this.words[i + 1]++; - } - this.length = Math.max(this.length, i + 1); + return function() { + var plot = this.plot + var shader = this.shader + var bounds = plot._tickBounds + var dataBox = plot.dataBox + var screenBox = plot.screenBox + var viewBox = plot.viewBox - return this; -}; + shader.bind() -// Subtract plain number `num` from `this` -BN.prototype.isubn = function isubn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.iaddn(-num); + //Set up coordinate scaling uniforms + for(var i=0; i<2; ++i) { - if (this.sign) { - this.sign = false; - this.iaddn(num); - this.sign = true; - return this; - } + var lo = bounds[i] + var hi = bounds[i+2] + var boundScale = hi - lo + var dataCenter = 0.5 * (dataBox[i+2] + dataBox[i]) + var dataWidth = (dataBox[i+2] - dataBox[i]) - this.words[0] -= num; + var viewLo = viewBox[i] + var viewHi = viewBox[i+2] + var viewScale = viewHi - viewLo + var screenLo = screenBox[i] + var screenHi = screenBox[i+2] + var screenScale = screenHi - screenLo - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } + DATA_SCALE[i] = 2.0 * boundScale / dataWidth * viewScale / screenScale + DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth * viewScale / screenScale + } - return this.strip(); -}; + TEXT_SCALE[1] = 2.0 * plot.pixelRatio / (screenBox[3] - screenBox[1]) + TEXT_SCALE[0] = TEXT_SCALE[1] * (screenBox[3] - screenBox[1]) / (screenBox[2] - screenBox[0]) -BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); -}; + shader.uniforms.dataScale = DATA_SCALE + shader.uniforms.dataShift = DATA_SHIFT + shader.uniforms.textScale = TEXT_SCALE -BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); -}; + //Set attributes + this.vbo.bind() + shader.attributes.textCoordinate.pointer() + } +})() -BN.prototype.iabs = function iabs() { - this.sign = false; +proto.update = function(options) { + var vertices = [] + var axesTicks = options.ticks + var bounds = options.bounds - return this; -}; + for(var dimension=0; dimension<2; ++dimension) { + var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity] -BN.prototype.abs = function abs() { - return this.clone().iabs(); -}; + //Copy vertices over to buffer + var ticks = axesTicks[dimension] + for(var i=0; i> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - var w = this.words[i + shift] + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } + for(var j=0; j> 26; - this.words[i] = w & 0x3ffffff; + this.tickOffset[dimension] = offsets + this.tickX[dimension] = tickX } - this.sign = true; - return this.strip(); -}; + //Add labels + for(var dimension=0; dimension<2; ++dimension) { + this.labelOffset[dimension] = Math.floor(vertices.length/3) -BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; + var data = getText(options.labelFont[dimension], options.labels[dimension]).data + var scale = options.labelSize[dimension] + for(var i=0; i= 0; j--) { - var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1]; +},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197,"text-cache":273}],164:[function(require,module,exports){ +arguments[4][62][0].apply(exports,arguments) +},{"dup":62}],165:[function(require,module,exports){ +'use strict' - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); +module.exports = createGLPlot2D - a._ishlnsubmul(b, qj, j); - while (a.sign) { - qj--; - a.sign = false; - a._ishlnsubmul(b, 1, j); - if (a.cmpn(0) !== 0) - a.sign = !a.sign; - } - if (q) - q.words[j] = qj; - } - if (q) - q.strip(); - a.strip(); +var createPick = require('gl-select-static') - // Denormalize - if (mode !== 'div' && shift !== 0) - a.ishrn(shift); - return { div: q ? q : null, mod: a }; -}; +var createGrid = require('./lib/grid') +var createText = require('./lib/text') +var createLine = require('./lib/line') +var createBox = require('./lib/box') -BN.prototype.divmod = function divmod(num, mode) { - assert(num.cmpn(0) !== 0); +function GLPlot2D(gl, pickBuffer) { + this.gl = gl + this.pickBuffer = pickBuffer - if (this.sign && !num.sign) { - var res = this.neg().divmod(num, mode); - var div; - var mod; - if (mode !== 'mod') - div = res.div.neg(); - if (mode !== 'div') - mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); - return { - div: div, - mod: mod - }; - } else if (!this.sign && num.sign) { - var res = this.divmod(num.neg(), mode); - var div; - if (mode !== 'mod') - div = res.div.neg(); - return { div: div, mod: res.mod }; - } else if (this.sign && num.sign) { - return this.neg().divmod(num.neg(), mode); - } + this.screenBox = [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] + this.viewBox = [0, 0, 0, 0] + this.dataBox = [-10, -10, 10, 10] - // Both numbers are positive at this point + this.gridLineEnable = [true,true] + this.gridLineWidth = [1,1] + this.gridLineColor = [[0,0,0,1], + [0,0,0,1]] - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) - return { div: new BN(0), mod: this }; + this.pixelRatio = 1 - // Very short reduction - if (num.length === 1) { - if (mode === 'div') - return { div: this.divn(num.words[0]), mod: null }; - else if (mode === 'mod') - return { div: null, mod: new BN(this.modn(num.words[0])) }; - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } + this.tickMarkLength = [0,0,0,0] + this.tickMarkWidth = [0,0,0,0] + this.tickMarkColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - return this._wordDiv(num, mode); -}; + this.tickPad = [15,15,15,15] + this.tickAngle = [0,0,0,0] + this.tickEnable = [true,true,true,true] + this.tickColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -// Find `this` / `num` -BN.prototype.div = function div(num) { - return this.divmod(num, 'div').div; -}; + this.labelPad = [15,15,15,15] + this.labelAngle = [0,Math.PI/2,0,3.0*Math.PI/2] + this.labelEnable = [true,true,true,true] + this.labelColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] -// Find `this` % `num` -BN.prototype.mod = function mod(num) { - return this.divmod(num, 'mod').mod; -}; + this.titleCenter = [0,0] + this.titleEnable = true + this.titleAngle = 0 + this.titleColor = [0,0,0,1] -// Find Round(`this` / `num`) -BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); + this.borderColor = [0,0,0,0] + this.backgroundColor = [0,0,0,0] - // Fast case - exact division - if (dm.mod.cmpn(0) === 0) - return dm.div; + this.zeroLineEnable = [true, true] + this.zeroLineWidth = [4, 4] + this.zeroLineColor = [[0, 0, 0, 1],[0, 0, 0, 1]] - var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; + this.borderLineEnable = [true,true,true,true] + this.borderLineWidth = [2,2,2,2] + this.borderLineColor = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] - var half = num.shrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); + //Drawing parameters + this.grid = null + this.text = null + this.line = null + this.box = null + this.objects = [] + this.overlays = [] - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) - return dm.div; + this._tickBounds = [Infinity, Infinity, -Infinity, -Infinity] - // Round up - return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); -}; + this.dirty = false + this.pickDirty = false + this.pickDelay = 120 + this.pickRadius = 10 + this._pickTimeout = null + this._drawPick = this.drawPick.bind(this) -BN.prototype.modn = function modn(num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; + this._depthCounter = 0 +} + +var proto = GLPlot2D.prototype + +proto.setDirty = function() { + this.dirty = this.pickDirty = true +} - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) - acc = (p * acc + this.words[i]) % num; +proto.setOverlayDirty = function() { + this.dirty = true +} - return acc; -}; +proto.nextDepthValue = function() { + return (this._depthCounter++) / 65536.0 +} -// In-place division by number -BN.prototype.idivn = function idivn(num) { - assert(num <= 0x3ffffff); +function lerp(a, b, t) { + var s = 0.5 * (t + 1.0) + return Math.floor((1.0-s)*a + s*b)|0 +} - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = this.words[i] + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } +proto.draw = (function() { +var TICK_MARK_BOX = [0,0,0,0] +return function() { + var gl = this.gl + var screenBox = this.screenBox + var viewPixels = this.viewBox + var dataBox = this.dataBox + var pixelRatio = this.pixelRatio + var grid = this.grid + var line = this.line + var text = this.text + var objects = this.objects - return this.strip(); -}; + this._depthCounter = 0 -BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); -}; + if(this.pickDirty) { + if(this._pickTimeout) { + clearTimeout(this._pickTimeout) + } + this.pickDirty = false + this._pickTimeout = setTimeout(this._drawPick, this.pickDelay) + } -BN.prototype.egcd = function egcd(p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); + if(!this.dirty) { + return + } + this.dirty = false - var x = this; - var y = p.clone(); + gl.bindFramebuffer(gl.FRAMEBUFFER, null) - if (x.sign) - x = x.mod(p); - else - x = x.clone(); + //Turn on scissor + gl.enable(gl.SCISSOR_TEST) - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); + //Turn off depth buffer + gl.disable(gl.DEPTH_TEST) + gl.depthFunc(gl.LESS) + gl.depthMask(false) - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); + //Configure premultiplied alpha blending + gl.enable(gl.BLEND) + gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - var g = 0; + //Draw border + gl.scissor( + screenBox[0], + screenBox[1], + screenBox[2]-screenBox[0], + screenBox[3]-screenBox[1]) + var borderColor = this.borderColor + gl.clearColor( + borderColor[0]*borderColor[3], + borderColor[1]*borderColor[3], + borderColor[2]*borderColor[3], + borderColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) - while (x.isEven() && y.isEven()) { - x.ishrn(1); - y.ishrn(1); - ++g; - } + //Draw center pane + gl.scissor( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + gl.viewport( + viewPixels[0], + viewPixels[1], + viewPixels[2]-viewPixels[0], + viewPixels[3]-viewPixels[1]) + var backgroundColor = this.backgroundColor + gl.clearColor( + backgroundColor[0]*backgroundColor[3], + backgroundColor[1]*backgroundColor[3], + backgroundColor[2]*backgroundColor[3], + backgroundColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT) - var yp = y.clone(); - var xp = x.clone(); + //Draw grid + grid.draw() - while (x.cmpn(0) !== 0) { - while (x.isEven()) { - x.ishrn(1); - if (A.isEven() && B.isEven()) { - A.ishrn(1); - B.ishrn(1); - } else { - A.iadd(yp).ishrn(1); - B.isub(xp).ishrn(1); + //Draw zero lines separately + var zeroLineEnable = this.zeroLineEnable + var zeroLineColor = this.zeroLineColor + var zeroLineWidth = this.zeroLineWidth + if(zeroLineEnable[0] || zeroLineEnable[1]) { + line.bind() + for(var i=0; i<2; ++i) { + if(!zeroLineEnable[i] || + !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) { + continue } - } - while (y.isEven()) { - y.ishrn(1); - if (C.isEven() && D.isEven()) { - C.ishrn(1); - D.ishrn(1); + var zeroIntercept = screenBox[i] - + dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) + + if(i === 0) { + line.drawLine( + zeroIntercept, screenBox[1], zeroIntercept, screenBox[3], + zeroLineWidth[i], + zeroLineColor[i]) } else { - C.iadd(yp).ishrn(1); - D.isub(xp).ishrn(1); + line.drawLine( + screenBox[0], zeroIntercept, screenBox[2], zeroIntercept, + zeroLineWidth[i], + zeroLineColor[i]) } } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } } - return { - a: C, - b: D, - gcd: y.ishln(g) - }; -}; - -// This is reduced incarnation of the binary EEA -// above, designated to invert members of the -// _prime_ fields F(p) at a maximal speed -BN.prototype._invmp = function _invmp(p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); - - var a = this; - var b = p.clone(); + //Draw traces + for(var i=0; i 0 && b.cmpn(1) > 0) { - while (a.isEven()) { - a.ishrn(1); - if (x1.isEven()) - x1.ishrn(1); - else - x1.iadd(delta).ishrn(1); - } - while (b.isEven()) { - b.ishrn(1); - if (x2.isEven()) - x2.ishrn(1); - else - x2.iadd(delta).ishrn(1); - } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } + //Draw border lines + var borderLineEnable = this.borderLineEnable + var borderLineWidth = this.borderLineWidth + var borderLineColor = this.borderLineColor + if(borderLineEnable[1]) { + line.drawLine( + viewPixels[0], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio, + viewPixels[0], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio, + borderLineWidth[1], borderLineColor[1]) } - if (a.cmpn(1) === 0) - return x1; - else - return x2; -}; - -BN.prototype.gcd = function gcd(num) { - if (this.cmpn(0) === 0) - return num.clone(); - if (num.cmpn(0) === 0) - return this.clone(); - - var a = this.clone(); - var b = num.clone(); - a.sign = false; - b.sign = false; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.ishrn(1); - b.ishrn(1); + if(borderLineEnable[0]) { + line.drawLine( + viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[1], + viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[1], + borderLineWidth[0], borderLineColor[0]) + } + if(borderLineEnable[3]) { + line.drawLine( + viewPixels[2], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio, + viewPixels[2], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio, + borderLineWidth[3], borderLineColor[3]) + } + if(borderLineEnable[2]) { + line.drawLine( + viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[3], + viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[3], + borderLineWidth[2], borderLineColor[2]) } - do { - while (a.isEven()) - a.ishrn(1); - while (b.isEven()) - b.ishrn(1); + //Draw text elements + text.bind() + for(var i=0; i<2; ++i) { + text.drawTicks(i) + } + if(this.titleEnable) { + text.drawTitle() + } - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } + //Draw other overlay elements (select boxes, etc.) + var overlays = this.overlays + for(var i=0; i>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; + var pickResult = this.pickBuffer.query(scrX, scrY, this.pickRadius) + if(!pickResult) { + return null } - return this; -}; -BN.prototype.cmpn = function cmpn(num) { - var sign = num < 0; - if (sign) - num = -num; + var pickValue = pickResult.id + + (pickResult.value[0]<<8) + + (pickResult.value[1]<<16) + + (pickResult.value[2]<<24) - if (this.sign && !sign) - return -1; - else if (!this.sign && sign) - return 1; + var objects = this.objects + for(var i=0; i 1) { - res = 1; - } else { - var w = this.words[0]; - res = w === num ? 0 : w < num ? -1 : 1; +function deepClone(array) { + var result = array.slice() + for(var i=0; i `num` -// 0 - if `this` == `num` -// -1 - if `this` < `num` -BN.prototype.cmp = function cmp(num) { - if (this.sign && !num.sign) - return -1; - else if (!this.sign && num.sign) - return 1; + return result +} - var res = this.ucmp(num); - if (this.sign) - return -res; - else - return res; -}; +function compareTicks(a, b) { + return a.x - b.x +} -// Unsigned comparison -BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) - return 1; - else if (this.length < num.length) - return -1; +proto.setScreenBox = function(nbox) { + var screenBox = this.screenBox + var pixelRatio = this.pixelRatio - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i]; - var b = num.words[i]; + screenBox[0] = Math.round(nbox[0] * pixelRatio) | 0 + screenBox[1] = Math.round(nbox[1] * pixelRatio) | 0 + screenBox[2] = Math.round(nbox[2] * pixelRatio) | 0 + screenBox[3] = Math.round(nbox[3] * pixelRatio) | 0 - if (a === b) - continue; - if (a < b) - res = -1; - else if (a > b) - res = 1; - break; - } - return res; -}; + this.setDirty() +} -// -// A reduce context, could be using montgomery or something better, depending -// on the `m` itself. -// -BN.red = function red(num) { - return new Red(num); -}; +proto.setDataBox = function(nbox) { + var dataBox = this.dataBox -BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(!this.sign, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); -}; + var different = + dataBox[0] !== nbox[0] || + dataBox[1] !== nbox[1] || + dataBox[2] !== nbox[2] || + dataBox[3] !== nbox[3] -BN.prototype.fromRed = function fromRed() { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); -}; + if(different) { + dataBox[0] = nbox[0] + dataBox[1] = nbox[1] + dataBox[2] = nbox[2] + dataBox[3] = nbox[3] -BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; -}; + this.setDirty() + } +} -BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); -}; +proto.setViewBox = function(nbox) { + var pixelRatio = this.pixelRatio + var viewBox = this.viewBox -BN.prototype.redAdd = function redAdd(num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); -}; + viewBox[0] = Math.round(nbox[0] * pixelRatio)|0 + viewBox[1] = Math.round(nbox[1] * pixelRatio)|0 + viewBox[2] = Math.round(nbox[2] * pixelRatio)|0 + viewBox[3] = Math.round(nbox[3] * pixelRatio)|0 -BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); -}; + var pickPixelRatio = this.pickPixelRatio + this.pickBuffer.shape = [ + Math.round((nbox[2] - nbox[0]) * pickPixelRatio)|0, + Math.round((nbox[3] - nbox[1]) * pickPixelRatio)|0 ] -BN.prototype.redSub = function redSub(num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); -}; + this.setDirty() +} -BN.prototype.redISub = function redISub(num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); -}; +proto.update = function(options) { + options = options || {} -BN.prototype.redShl = function redShl(num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); -}; + var gl = this.gl -BN.prototype.redMul = function redMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); -}; + this.pixelRatio = options.pixelRatio || 1 -BN.prototype.redIMul = function redIMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); -}; + var pixelRatio = this.pixelRatio + this.pickPixelRatio = Math.max(pixelRatio, 1) -BN.prototype.redSqr = function redSqr() { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); -}; + this.setScreenBox(options.screenBox || + [0, 0, gl.drawingBufferWidth/pixelRatio, gl.drawingBufferHeight/pixelRatio]) -BN.prototype.redISqr = function redISqr() { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); -}; + var screenBox = this.screenBox + this.setViewBox(options.viewBox || + [0.125*(this.screenBox[2]-this.screenBox[0])/pixelRatio, + 0.125*(this.screenBox[3]-this.screenBox[1])/pixelRatio, + 0.875*(this.screenBox[2]-this.screenBox[0])/pixelRatio, + 0.875*(this.screenBox[3]-this.screenBox[1])/pixelRatio]) -// Square root over p -BN.prototype.redSqrt = function redSqrt() { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); -}; + var viewBox = this.viewBox + var aspectRatio = (viewBox[2] - viewBox[0]) / (viewBox[3] - viewBox[1]) + this.setDataBox(options.dataBox || [-10, -10/aspectRatio, 10, 10/aspectRatio]) -BN.prototype.redInvm = function redInvm() { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); -}; + this.borderColor = (options.borderColor || [0,0,0,0]).slice() + this.backgroundColor = (options.backgroundColor || [0,0,0,0]).slice() -// Return negative clone of `this` % `red modulo` -BN.prototype.redNeg = function redNeg() { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); -}; + this.gridLineEnable = (options.gridLineEnable || [true,true]).slice() + this.gridLineWidth = (options.gridLineWidth || [1,1]).slice() + this.gridLineColor = deepClone(options.gridLineColor || + [[0.5,0.5,0.5,1],[0.5,0.5,0.5,1]]) -BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); -}; + this.zeroLineEnable = (options.zeroLineEnable || [true, true]).slice() + this.zeroLineWidth = (options.zeroLineWidth || [4, 4]).slice() + this.zeroLineColor = deepClone(options.zeroLineColor || + [[0, 0, 0, 1],[0, 0, 0, 1]]) -// Prime numbers with efficient reduction -var primes = { - k256: null, - p224: null, - p192: null, - p25519: null -}; + this.tickMarkLength = (options.tickMarkLength || [0,0,0,0]).slice() + this.tickMarkWidth = (options.tickMarkWidth || [0,0,0,0]).slice() + this.tickMarkColor = deepClone(options.tickMarkColor || + [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]) -// Pseudo-Mersenne prime -function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).ishln(this.n).isub(this.p); + this.titleCenter = (options.titleCenter || [ + 0.5*(viewBox[0]+viewBox[2])/pixelRatio,(viewBox[3]+120)/pixelRatio]).slice() + this.titleEnable = !('titleEnable' in options) || !!options.titleEnable + this.titleAngle = options.titleAngle || 0 + this.titleColor = (options.titleColor || [0,0,0,1]).slice() - this.tmp = this._tmp(); -} + this.labelPad = (options.labelPad || [15,15,15,15]).slice() + this.labelAngle = (options.labelAngle || + [0,Math.PI/2,0,3.0*Math.PI/2]).slice() + this.labelEnable = (options.labelEnable || [true,true,true,true]).slice() + this.labelColor = deepClone(options.labelColor || + [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]) -MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; -}; + this.tickPad = (options.tickPad || [15,15,15,15]).slice() + this.tickAngle = (options.tickAngle || [0,0,0,0]).slice() + this.tickEnable = (options.tickEnable || [true,true,true,true]).slice() + this.tickColor = deepClone(options.tickColor || + [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]) -MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; + this.borderLineEnable = (options.borderLineEnable || + [true,true,true,true]).slice() + this.borderLineWidth = (options.borderLineWidth || [2,2,2,2]).slice() + this.borderLineColor = deepClone(options.borderLineColor || + [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]]) - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); + var ticks = options.ticks || [ [], [] ] - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); + //Compute bounds on ticks + var bounds = this._tickBounds + bounds[0] = bounds[1] = Infinity + bounds[2] = bounds[3] = -Infinity + for(var i=0; i<2; ++i) { + var axisTicks = ticks[i].slice(0) + if(axisTicks.length === 0) { + continue + } + axisTicks.sort(compareTicks) + bounds[i] = Math.min(bounds[i], axisTicks[0].x) + bounds[i+2] = Math.max(bounds[i+2], axisTicks[axisTicks.length-1].x) } - return r; -}; - -MPrime.prototype.split = function split(input, out) { - input.ishrn(this.n, 0, out); -}; + //Update grid + this.grid.update({ + bounds: bounds, + ticks: ticks + }) -MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); -}; + //Update text + this.text.update({ + bounds: bounds, + ticks: ticks, + labels: options.labels || ['x', 'y'], + labelSize: options.labelSize || [12,12], + labelFont: options.labelFont || ['sans-serif', 'sans-serif'], + title: options.title || '', + titleSize: options.titleSize || 18, + titleFont: options.titleFont || 'sans-serif' + }) -function K256() { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); + this.setDirty() } -inherits(K256, MPrime); -K256.prototype.split = function split(input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; +proto.dispose = function() { + this.box.dispose() + this.grid.dispose() + this.text.dispose() + this.line.dispose() + for(var i=this.objects.length-1; i>=0; --i) { + this.objects[i].dispose() + } + this.objects.length = 0 + for(var i=this.overlays.length-1; i>=0; --i) { + this.overlays[i].dispose() + } + this.overlays.length = 0 - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) - output.words[i] = input.words[i]; - output.length = outLen; + this.gl = null +} - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; +proto.addObject = function(object) { + if(this.objects.indexOf(object) < 0) { + this.objects.push(object) + this.setDirty() } +} - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; +proto.removeObject = function(object) { + var objects = this.objects + for(var i=0; i>> 22); - prev = next; +proto.addOverlay = function(object) { + if(this.overlays.indexOf(object) < 0) { + this.overlays.push(object) + this.setOverlayDirty() } - input.words[i - 10] = prev >>> 22; - input.length -= 9; -}; +} -K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; +proto.removeOverlay = function(object) { + var objects = this.overlays + for(var i=0; i>>= 26; +var now = require('right-now') +var createView = require('3d-view') +var mouseChange = require('mouse-change') +var mouseWheel = require('mouse-wheel') - num.words[i] = lo; - carry = hi; +function createCamera(element, options) { + element = element || document.body + options = options || {} + + var limits = [ 0.01, Infinity ] + if('distanceLimits' in options) { + limits[0] = options.distanceLimits[0] + limits[1] = options.distanceLimits[1] + } + if('zoomMin' in options) { + limits[0] = options.zoomMin + } + if('zoomMax' in options) { + limits[1] = options.zoomMax } - if (carry !== 0) - num.words[num.length++] = carry; - return num; -}; -// Exported mostly for testing purposes, use plain name instead -BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) - return primes[name]; + var view = createView({ + center: options.center || [0,0,0], + up: options.up || [0,1,0], + eye: options.eye || [0,0,10], + mode: options.mode || 'orbit', + distanceLimits: limits + }) + + var pmatrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] + var distance = 0.0 + var width = element.clientWidth + var height = element.clientHeight + + var camera = { + view: view, + element: element, + delay: options.delay || 16, + rotateSpeed: options.rotateSpeed || 1, + zoomSpeed: options.zoomSpeed || 1, + translateSpeed: options.translateSpeed || 1, + flipX: !!options.flipX, + flipY: !!options.flipY, + modes: view.modes, + tick: function() { + var t = now() + var delay = this.delay + view.idle(t-delay) + view.flush(t-(100+delay*2)) + var ctime = t - 2 * delay + view.recalcMatrix(ctime) + var allEqual = true + var matrix = view.computedMatrix + for(var i=0; i<16; ++i) { + allEqual = allEqual && (pmatrix[i] === matrix[i]) + pmatrix[i] = matrix[i] + } + var sizeChanged = + element.clientWidth === width && + element.clientHeight === height + width = element.clientWidth + height = element.clientHeight + if(allEqual) { + return !sizeChanged + } + distance = Math.exp(view.computedRadius[0]) + return true + }, + lookAt: function(center, eye, up) { + view.lookAt(view.lastT(), center, eye, up) + }, + rotate: function(pitch, yaw, roll) { + view.rotate(view.lastT(), pitch, yaw, roll) + }, + pan: function(dx, dy, dz) { + view.pan(view.lastT(), dx, dy, dz) + }, + translate: function(dx, dy, dz) { + view.translate(view.lastT(), dx, dy, dz) + } + } + + Object.defineProperties(camera, { + matrix: { + get: function() { + return view.computedMatrix + }, + set: function(mat) { + view.setMatrix(view.lastT(), mat) + return view.computedMatrix + }, + enumerable: true + }, + mode: { + get: function() { + return view.getMode() + }, + set: function(mode) { + view.setMode(mode) + return view.getMode() + }, + enumerable: true + }, + center: { + get: function() { + return view.computedCenter + }, + set: function(ncenter) { + view.lookAt(view.lastT(), ncenter) + return view.computedCenter + }, + enumerable: true + }, + eye: { + get: function() { + return view.computedEye + }, + set: function(neye) { + view.lookAt(view.lastT(), null, neye) + return view.computedEye + }, + enumerable: true + }, + up: { + get: function() { + return view.computedUp + }, + set: function(nup) { + view.lookAt(view.lastT(), null, null, nup) + return view.computedUp + }, + enumerable: true + }, + distance: { + get: function() { + return distance + }, + set: function(d) { + view.setDistance(view.lastT(), d) + return d + }, + enumerable: true + }, + distanceLimits: { + get: function() { + return view.getDistanceLimits(limits) + }, + set: function(v) { + view.setDistanceLimits(v) + return v + }, + enumerable: true + } + }) + + element.addEventListener('contextmenu', function(ev) { + ev.preventDefault() + return false + }) - var prime; - if (name === 'k256') - prime = new K256(); - else if (name === 'p224') - prime = new P224(); - else if (name === 'p192') - prime = new P192(); - else if (name === 'p25519') - prime = new P25519(); - else - throw new Error('Unknown prime ' + name); - primes[name] = prime; + var lastX = 0, lastY = 0 + mouseChange(element, function(buttons, x, y, mods) { + var scale = 1.0 / element.clientHeight + var dx = scale * (x - lastX) + var dy = scale * (y - lastY) - return prime; -}; + var flipX = camera.flipX ? 1 : -1 + var flipY = camera.flipY ? 1 : -1 -// -// Base reduction engine -// -function Red(m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - this.m = m; - this.prime = null; - } -} + var drot = Math.PI * camera.rotateSpeed -Red.prototype._verify1 = function _verify1(a) { - assert(!a.sign, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); -}; + var t = now() -Red.prototype._verify2 = function _verify2(a, b) { - assert(!a.sign && !b.sign, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); -}; + if(buttons & 1) { + if(mods.shift) { + view.rotate(t, 0, 0, -dx * drot) + } else { + view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0) + } + } else if(buttons & 2) { + view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0) + } else if(buttons & 4) { + var kzoom = camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 50.0 + view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) + } -Red.prototype.imod = function imod(a) { - if (this.prime) - return this.prime.ireduce(a)._forceRed(this); - return a.mod(this.m)._forceRed(this); -}; + lastX = x + lastY = y + }) -Red.prototype.neg = function neg(a) { - var r = a.clone(); - r.sign = !r.sign; - return r.iadd(this.m)._forceRed(this); -}; + mouseWheel(element, function(dx, dy, dz) { + var flipX = camera.flipX ? 1 : -1 + var flipY = camera.flipY ? 1 : -1 + var t = now() + if(Math.abs(dx) > Math.abs(dy)) { + view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) + } else { + var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0 + view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) + } + }, true) -Red.prototype.add = function add(a, b) { - this._verify2(a, b); + return camera +} +},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],168:[function(require,module,exports){ +// Copyright (C) 2011 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. - var res = a.add(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res._forceRed(this); -}; +/** + * @fileoverview Install a leaky WeakMap emulation on platforms that + * don't provide a built-in one. + * + *

Assumes that an ES5 platform where, if {@code WeakMap} is + * already present, then it conforms to the anticipated ES6 + * specification. To run this file on an ES5 or almost ES5 + * implementation where the {@code WeakMap} specification does not + * quite conform, run repairES5.js first. + * + *

Even though WeakMapModule is not global, the linter thinks it + * is, which is why it is in the overrides list below. + * + *

NOTE: Before using this WeakMap emulation in a non-SES + * environment, see the note below about hiddenRecord. + * + * @author Mark S. Miller + * @requires crypto, ArrayBuffer, Uint8Array, navigator, console + * @overrides WeakMap, ses, Proxy + * @overrides WeakMapModule + */ -Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); +/** + * This {@code WeakMap} emulation is observably equivalent to the + * ES-Harmony WeakMap, but with leakier garbage collection properties. + * + *

As with true WeakMaps, in this emulation, a key does not + * retain maps indexed by that key and (crucially) a map does not + * retain the keys it indexes. A map by itself also does not retain + * the values associated with that map. + * + *

However, the values associated with a key in some map are + * retained so long as that key is retained and those associations are + * not overridden. For example, when used to support membranes, all + * values exported from a given membrane will live for the lifetime + * they would have had in the absence of an interposed membrane. Even + * when the membrane is revoked, all objects that would have been + * reachable in the absence of revocation will still be reachable, as + * far as the GC can tell, even though they will no longer be relevant + * to ongoing computation. + * + *

The API implemented here is approximately the API as implemented + * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, + * rather than the offially approved proposal page. TODO(erights): + * upgrade the ecmascript WeakMap proposal page to explain this API + * change and present to EcmaScript committee for their approval. + * + *

The first difference between the emulation here and that in + * FF6.0a1 is the presence of non enumerable {@code get___, has___, + * set___, and delete___} methods on WeakMap instances to represent + * what would be the hidden internal properties of a primitive + * implementation. Whereas the FF6.0a1 WeakMap.prototype methods + * require their {@code this} to be a genuine WeakMap instance (i.e., + * an object of {@code [[Class]]} "WeakMap}), since there is nothing + * unforgeable about the pseudo-internal method names used here, + * nothing prevents these emulated prototype methods from being + * applied to non-WeakMaps with pseudo-internal methods of the same + * names. + * + *

Another difference is that our emulated {@code + * WeakMap.prototype} is not itself a WeakMap. A problem with the + * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap + * providing ambient mutability and an ambient communications + * channel. Thus, if a WeakMap is already present and has this + * problem, repairES5.js wraps it in a safe wrappper in order to + * prevent access to this channel. (See + * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). + */ - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res; -}; +/** + * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is + * absent, install an approximate emulation. + * + *

If WeakMap is present but cannot store some objects, use our approximate + * emulation as a wrapper. + * + *

If this is almost a secureable ES5 platform, then WeakMap.js + * should be run after repairES5.js. + * + *

See {@code WeakMap} for documentation of the garbage collection + * properties of this WeakMap emulation. + */ +(function WeakMapModule() { + "use strict"; -Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); + if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { + // already too broken, so give up + return; + } - var res = a.sub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res._forceRed(this); -}; + /** + * In some cases (current Firefox), we must make a choice betweeen a + * WeakMap which is capable of using all varieties of host objects as + * keys and one which is capable of safely using proxies as keys. See + * comments below about HostWeakMap and DoubleWeakMap for details. + * + * This function (which is a global, not exposed to guests) marks a + * WeakMap as permitted to do what is necessary to index all host + * objects, at the cost of making it unsafe for proxies. + * + * Do not apply this function to anything which is not a genuine + * fresh WeakMap. + */ + function weakMapPermitHostObjects(map) { + // identity of function used as a secret -- good enough and cheap + if (map.permitHostObjects___) { + map.permitHostObjects___(weakMapPermitHostObjects); + } + } + if (typeof ses !== 'undefined') { + ses.weakMapPermitHostObjects = weakMapPermitHostObjects; + } -Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); + // IE 11 has no Proxy but has a broken WeakMap such that we need to patch + // it using DoubleWeakMap; this flag tells DoubleWeakMap so. + var doubleWeakMapCheckSilentFailure = false; - var res = a.isub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res; -}; + // Check if there is already a good-enough WeakMap implementation, and if so + // exit without replacing it. + if (typeof WeakMap === 'function') { + var HostWeakMap = WeakMap; + // There is a WeakMap -- is it good enough? + if (typeof navigator !== 'undefined' && + /Firefox/.test(navigator.userAgent)) { + // We're now *assuming not*, because as of this writing (2013-05-06) + // Firefox's WeakMaps have a miscellany of objects they won't accept, and + // we don't want to make an exhaustive list, and testing for just one + // will be a problem if that one is fixed alone (as they did for Event). -Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.shln(num)); -}; + // If there is a platform that we *can* reliably test on, here's how to + // do it: + // var problematic = ... ; + // var testHostMap = new HostWeakMap(); + // try { + // testHostMap.set(problematic, 1); // Firefox 20 will throw here + // if (testHostMap.get(problematic) === 1) { + // return; + // } + // } catch (e) {} -Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); -}; + } else { + // IE 11 bug: WeakMaps silently fail to store frozen objects. + var testMap = new HostWeakMap(); + var testObject = Object.freeze({}); + testMap.set(testObject, 1); + if (testMap.get(testObject) !== 1) { + doubleWeakMapCheckSilentFailure = true; + // Fall through to installing our WeakMap. + } else { + module.exports = WeakMap; + return; + } + } + } -Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); -}; + var hop = Object.prototype.hasOwnProperty; + var gopn = Object.getOwnPropertyNames; + var defProp = Object.defineProperty; + var isExtensible = Object.isExtensible; -Red.prototype.isqr = function isqr(a) { - return this.imul(a, a); -}; + /** + * Security depends on HIDDEN_NAME being both unguessable and + * undiscoverable by untrusted code. + * + *

Given the known weaknesses of Math.random() on existing + * browsers, it does not generate unguessability we can be confident + * of. + * + *

It is the monkey patching logic in this file that is intended + * to ensure undiscoverability. The basic idea is that there are + * three fundamental means of discovering properties of an object: + * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), + * as well as some proposed ES6 extensions that appear on our + * whitelist. The first two only discover enumerable properties, and + * we only use HIDDEN_NAME to name a non-enumerable property, so the + * only remaining threat should be getOwnPropertyNames and some + * proposed ES6 extensions that appear on our whitelist. We monkey + * patch them to remove HIDDEN_NAME from the list of properties they + * returns. + * + *

TODO(erights): On a platform with built-in Proxies, proxies + * could be used to trap and thereby discover the HIDDEN_NAME, so we + * need to monkey patch Proxy.create, Proxy.createFunction, etc, in + * order to wrap the provided handler with the real handler which + * filters out all traps using HIDDEN_NAME. + * + *

TODO(erights): Revisit Mike Stay's suggestion that we use an + * encapsulated function at a not-necessarily-secret name, which + * uses the Stiegler shared-state rights amplification pattern to + * reveal the associated value only to the WeakMap in which this key + * is associated with that value. Since only the key retains the + * function, the function can also remember the key without causing + * leakage of the key, so this doesn't violate our general gc + * goals. In addition, because the name need not be a guarded + * secret, we could efficiently handle cross-frame frozen keys. + */ + var HIDDEN_NAME_PREFIX = 'weakmap:'; + var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; -Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); -}; + if (typeof crypto !== 'undefined' && + typeof crypto.getRandomValues === 'function' && + typeof ArrayBuffer === 'function' && + typeof Uint8Array === 'function') { + var ab = new ArrayBuffer(25); + var u8s = new Uint8Array(ab); + crypto.getRandomValues(u8s); + HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + + Array.prototype.map.call(u8s, function(u8) { + return (u8 % 36).toString(36); + }).join('') + '___'; + } -Red.prototype.sqrt = function sqrt(a) { - if (a.cmpn(0) === 0) - return a.clone(); + function isNotHiddenName(name) { + return !( + name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && + name.substr(name.length - 3) === '___'); + } - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); + /** + * Monkey patch getOwnPropertyNames to avoid revealing the + * HIDDEN_NAME. + * + *

The ES5.1 spec requires each name to appear only once, but as + * of this writing, this requirement is controversial for ES6, so we + * made this code robust against this case. If the resulting extra + * search turns out to be expensive, we can probably relax this once + * ES6 is adequately supported on all major browsers, iff no browser + * versions we support at that time have relaxed this constraint + * without providing built-in ES6 WeakMaps. + */ + defProp(Object, 'getOwnPropertyNames', { + value: function fakeGetOwnPropertyNames(obj) { + return gopn(obj).filter(isNotHiddenName); + } + }); - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).ishrn(2); - var r = this.pow(a, pow); - return r; + /** + * getPropertyNames is not in ES5 but it is proposed for ES6 and + * does appear in our whitelist, so we need to clean it too. + */ + if ('getPropertyNames' in Object) { + var originalGetPropertyNames = Object.getPropertyNames; + defProp(Object, 'getPropertyNames', { + value: function fakeGetPropertyNames(obj) { + return originalGetPropertyNames(obj).filter(isNotHiddenName); + } + }); } - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (q.cmpn(0) !== 0 && q.andln(1) === 0) { - s++; - q.ishrn(1); - } - assert(q.cmpn(0) !== 0); + /** + *

To treat objects as identity-keys with reasonable efficiency + * on ES5 by itself (i.e., without any object-keyed collections), we + * need to add a hidden property to such key objects when we + * can. This raises several issues: + *

    + *
  • Arranging to add this property to objects before we lose the + * chance, and + *
  • Hiding the existence of this new property from most + * JavaScript code. + *
  • Preventing certification theft, where one object is + * created falsely claiming to be the key of an association + * actually keyed by another object. + *
  • Preventing value theft, where untrusted code with + * access to a key object but not a weak map nevertheless + * obtains access to the value associated with that key in that + * weak map. + *
+ * We do so by + *
    + *
  • Making the name of the hidden property unguessable, so "[]" + * indexing, which we cannot intercept, cannot be used to access + * a property without knowing the name. + *
  • Making the hidden property non-enumerable, so we need not + * worry about for-in loops or {@code Object.keys}, + *
  • monkey patching those reflective methods that would + * prevent extensions, to add this hidden property first, + *
  • monkey patching those methods that would reveal this + * hidden property. + *
+ * Unfortunately, because of same-origin iframes, we cannot reliably + * add this hidden property before an object becomes + * non-extensible. Instead, if we encounter a non-extensible object + * without a hidden record that we can detect (whether or not it has + * a hidden record stored under a name secret to us), then we just + * use the key object itself to represent its identity in a brute + * force leaky map stored in the weak map, losing all the advantages + * of weakness for these. + */ + function getHiddenRecord(key) { + if (key !== Object(key)) { + throw new TypeError('Not an object: ' + key); + } + var hiddenRecord = key[HIDDEN_NAME]; + if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } + if (!isExtensible(key)) { + // Weak map must brute force, as explained in doc-comment above. + return void 0; + } - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); + // The hiddenRecord and the key point directly at each other, via + // the "key" and HIDDEN_NAME properties respectively. The key + // field is for quickly verifying that this hidden record is an + // own property, not a hidden record from up the prototype chain. + // + // NOTE: Because this WeakMap emulation is meant only for systems like + // SES where Object.prototype is frozen without any numeric + // properties, it is ok to use an object literal for the hiddenRecord. + // This has two advantages: + // * It is much faster in a performance critical place + // * It avoids relying on Object.create(null), which had been + // problematic on Chrome 28.0.1480.0. See + // https://code.google.com/p/google-caja/issues/detail?id=1687 + hiddenRecord = { key: key }; - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).ishrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - while (this.pow(z, lpow).cmp(nOne) !== 0) - z.redIAdd(nOne); + // When using this WeakMap emulation on platforms where + // Object.prototype might not be frozen and Object.create(null) is + // reliable, use the following two commented out lines instead. + // hiddenRecord = Object.create(null); + // hiddenRecord.key = key; - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).ishrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) - tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).ishln(m - i - 1)); + // Please contact us if you need this to work on platforms where + // Object.prototype might not be frozen and + // Object.create(null) might not be reliable. - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; + try { + defProp(key, HIDDEN_NAME, { + value: hiddenRecord, + writable: false, + enumerable: false, + configurable: false + }); + return hiddenRecord; + } catch (error) { + // Under some circumstances, isExtensible seems to misreport whether + // the HIDDEN_NAME can be defined. + // The circumstances have not been isolated, but at least affect + // Node.js v0.10.26 on TravisCI / Linux, but not the same version of + // Node.js on OS X. + return void 0; + } } - return r; -}; + /** + * Monkey patch operations that would make their argument + * non-extensible. + * + *

The monkey patched versions throw a TypeError if their + * argument is not an object, so it should only be done to functions + * that should throw a TypeError anyway if their argument is not an + * object. + */ + (function(){ + var oldFreeze = Object.freeze; + defProp(Object, 'freeze', { + value: function identifyingFreeze(obj) { + getHiddenRecord(obj); + return oldFreeze(obj); + } + }); + var oldSeal = Object.seal; + defProp(Object, 'seal', { + value: function identifyingSeal(obj) { + getHiddenRecord(obj); + return oldSeal(obj); + } + }); + var oldPreventExtensions = Object.preventExtensions; + defProp(Object, 'preventExtensions', { + value: function identifyingPreventExtensions(obj) { + getHiddenRecord(obj); + return oldPreventExtensions(obj); + } + }); + })(); -Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); - if (inv.sign) { - inv.sign = false; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); + function constFunc(func) { + func.prototype = null; + return Object.freeze(func); } -}; -Red.prototype.pow = function pow(a, num) { - var w = []; + var calledAsFunctionWarningDone = false; + function calledAsFunctionWarning() { + // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() + // but we used to permit it and do it ourselves, so warn only. + if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { + calledAsFunctionWarningDone = true; + console.warn('WeakMap should be invoked as new WeakMap(), not ' + + 'WeakMap(). This will be an error in the future.'); + } + } - if (num.cmpn(0) === 0) - return new BN(1); + var nextId = 0; - var q = num.clone(); + var OurWeakMap = function() { + if (!(this instanceof OurWeakMap)) { // approximate test for new ...() + calledAsFunctionWarning(); + } - while (q.cmpn(0) !== 0) { - w.push(q.andln(1)); - q.ishrn(1); - } + // We are currently (12/25/2012) never encountering any prematurely + // non-extensible keys. + var keys = []; // brute force for prematurely non-extensible keys. + var values = []; // brute force for corresponding values. + var id = nextId++; - // Skip leading zeroes - var res = a; - for (var i = 0; i < w.length; i++, res = this.sqr(res)) - if (w[i] !== 0) - break; + function get___(key, opt_default) { + var index; + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + return id in hiddenRecord ? hiddenRecord[id] : opt_default; + } else { + index = keys.indexOf(key); + return index >= 0 ? values[index] : opt_default; + } + } - if (++i < w.length) { - for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { - if (w[i] === 0) - continue; - res = this.mul(res, q); + function has___(key) { + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + return id in hiddenRecord; + } else { + return keys.indexOf(key) >= 0; + } } - } - return res; -}; + function set___(key, value) { + var index; + var hiddenRecord = getHiddenRecord(key); + if (hiddenRecord) { + hiddenRecord[id] = value; + } else { + index = keys.indexOf(key); + if (index >= 0) { + values[index] = value; + } else { + // Since some browsers preemptively terminate slow turns but + // then continue computing with presumably corrupted heap + // state, we here defensively get keys.length first and then + // use it to update both the values and keys arrays, keeping + // them in sync. + index = keys.length; + values[index] = value; + // If we crash here, values will be one longer than keys. + keys[index] = key; + } + } + return this; + } -Red.prototype.convertTo = function convertTo(num) { - var r = num.mod(this.m); - if (r === num) - return r.clone(); - else - return r; -}; + function delete___(key) { + var hiddenRecord = getHiddenRecord(key); + var index, lastIndex; + if (hiddenRecord) { + return id in hiddenRecord && delete hiddenRecord[id]; + } else { + index = keys.indexOf(key); + if (index < 0) { + return false; + } + // Since some browsers preemptively terminate slow turns but + // then continue computing with potentially corrupted heap + // state, we here defensively get keys.length first and then use + // it to update both the keys and the values array, keeping + // them in sync. We update the two with an order of assignments, + // such that any prefix of these assignments will preserve the + // key/value correspondence, either before or after the delete. + // Note that this needs to work correctly when index === lastIndex. + lastIndex = keys.length - 1; + keys[index] = void 0; + // If we crash here, there's a void 0 in the keys array, but + // no operation will cause a "keys.indexOf(void 0)", since + // getHiddenRecord(void 0) will always throw an error first. + values[index] = values[lastIndex]; + // If we crash here, values[index] cannot be found here, + // because keys[index] is void 0. + keys[index] = keys[lastIndex]; + // If index === lastIndex and we crash here, then keys[index] + // is still void 0, since the aliasing killed the previous key. + keys.length = lastIndex; + // If we crash here, keys will be one shorter than values. + values.length = lastIndex; + return true; + } + } -Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; -}; + return Object.create(OurWeakMap.prototype, { + get___: { value: constFunc(get___) }, + has___: { value: constFunc(has___) }, + set___: { value: constFunc(set___) }, + delete___: { value: constFunc(delete___) } + }); + }; -// -// Montgomery method engine -// + OurWeakMap.prototype = Object.create(Object.prototype, { + get: { + /** + * Return the value most recently associated with key, or + * opt_default if none. + */ + value: function get(key, opt_default) { + return this.get___(key, opt_default); + }, + writable: true, + configurable: true + }, -BN.mont = function mont(num) { - return new Mont(num); -}; + has: { + /** + * Is there a value associated with key in this WeakMap? + */ + value: function has(key) { + return this.has___(key); + }, + writable: true, + configurable: true + }, -function Mont(m) { - Red.call(this, m); + set: { + /** + * Associate value with key in this WeakMap, overwriting any + * previous association if present. + */ + value: function set(key, value) { + return this.set___(key, value); + }, + writable: true, + configurable: true + }, - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) - this.shift += 26 - (this.shift % 26); - this.r = new BN(1).ishln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); + 'delete': { + /** + * Remove any association for key in this WeakMap, returning + * whether there was one. + * + *

Note that the boolean return here does not work like the + * {@code delete} operator. The {@code delete} operator returns + * whether the deletion succeeds at bringing about a state in + * which the deleted property is absent. The {@code delete} + * operator therefore returns true if the property was already + * absent, whereas this {@code delete} method returns false if + * the association was already absent. + */ + value: function remove(key) { + return this.delete___(key); + }, + writable: true, + configurable: true + } + }); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv.sign = true; - this.minv = this.minv.mod(this.r); -} -inherits(Mont, Red); + if (typeof HostWeakMap === 'function') { + (function() { + // If we got here, then the platform has a WeakMap but we are concerned + // that it may refuse to store some key types. Therefore, make a map + // implementation which makes use of both as possible. -Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.shln(this.shift)); -}; + // In this mode we are always using double maps, so we are not proxy-safe. + // This combination does not occur in any known browser, but we had best + // be safe. + if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { + Proxy = undefined; + } -Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; -}; + function DoubleWeakMap() { + if (!(this instanceof OurWeakMap)) { // approximate test for new ...() + calledAsFunctionWarning(); + } -Mont.prototype.imul = function imul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { - a.words[0] = 0; - a.length = 1; - return a; - } + // Preferable, truly weak map. + var hmap = new HostWeakMap(); - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); + // Our hidden-property-based pseudo-weak-map. Lazily initialized in the + // 'set' implementation; thus we can avoid performing extra lookups if + // we know all entries actually stored are entered in 'hmap'. + var omap = undefined; - return res._forceRed(this); -}; + // Hidden-property maps are not compatible with proxies because proxies + // can observe the hidden name and either accidentally expose it or fail + // to allow the hidden property to be set. Therefore, we do not allow + // arbitrary WeakMaps to switch to using hidden properties, but only + // those which need the ability, and unprivileged code is not allowed + // to set the flag. + // + // (Except in doubleWeakMapCheckSilentFailure mode in which case we + // disable proxies.) + var enableSwitching = false; -Mont.prototype.mul = function mul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) - return new BN(0)._forceRed(this); + function dget(key, opt_default) { + if (omap) { + return hmap.has(key) ? hmap.get(key) + : omap.get___(key, opt_default); + } else { + return hmap.get(key, opt_default); + } + } - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); + function dhas(key) { + return hmap.has(key) || (omap ? omap.has___(key) : false); + } - return res._forceRed(this); -}; + var dset; + if (doubleWeakMapCheckSilentFailure) { + dset = function(key, value) { + hmap.set(key, value); + if (!hmap.has(key)) { + if (!omap) { omap = new OurWeakMap(); } + omap.set(key, value); + } + return this; + }; + } else { + dset = function(key, value) { + if (enableSwitching) { + try { + hmap.set(key, value); + } catch (e) { + if (!omap) { omap = new OurWeakMap(); } + omap.set___(key, value); + } + } else { + hmap.set(key, value); + } + return this; + }; + } -Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); -}; + function ddelete(key) { + var result = !!hmap['delete'](key); + if (omap) { return omap.delete___(key) || result; } + return result; + } -})(typeof module === 'undefined' || module, this); + return Object.create(OurWeakMap.prototype, { + get___: { value: constFunc(dget) }, + has___: { value: constFunc(dhas) }, + set___: { value: constFunc(dset) }, + delete___: { value: constFunc(ddelete) }, + permitHostObjects___: { value: constFunc(function(token) { + if (token === weakMapPermitHostObjects) { + enableSwitching = true; + } else { + throw new Error('bogus call to permitHostObjects___'); + } + })} + }); + } + DoubleWeakMap.prototype = OurWeakMap.prototype; + module.exports = DoubleWeakMap; -},{}],384:[function(require,module,exports){ -(function (Buffer){ -var hasTypedArrays = false -if(typeof Float64Array !== "undefined") { - var DOUBLE_VIEW = new Float64Array(1) - , UINT_VIEW = new Uint32Array(DOUBLE_VIEW.buffer) - DOUBLE_VIEW[0] = 1.0 - hasTypedArrays = true - if(UINT_VIEW[1] === 0x3ff00000) { - //Use little endian - module.exports = function doubleBitsLE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[0], UINT_VIEW[1] ] - } - function toDoubleLE(lo, hi) { - UINT_VIEW[0] = lo - UINT_VIEW[1] = hi - return DOUBLE_VIEW[0] - } - module.exports.pack = toDoubleLE - function lowUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - module.exports.lo = lowUintLE - function highUintLE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - module.exports.hi = highUintLE - } else if(UINT_VIEW[0] === 0x3ff00000) { - //Use big endian - module.exports = function doubleBitsBE(n) { - DOUBLE_VIEW[0] = n - return [ UINT_VIEW[1], UINT_VIEW[0] ] - } - function toDoubleBE(lo, hi) { - UINT_VIEW[1] = lo - UINT_VIEW[0] = hi - return DOUBLE_VIEW[0] - } - module.exports.pack = toDoubleBE - function lowUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[1] - } - module.exports.lo = lowUintBE - function highUintBE(n) { - DOUBLE_VIEW[0] = n - return UINT_VIEW[0] - } - module.exports.hi = highUintBE + // define .constructor to hide OurWeakMap ctor + Object.defineProperty(WeakMap.prototype, 'constructor', { + value: WeakMap, + enumerable: false, // as default .constructor is + configurable: true, + writable: true + }); + })(); } else { - hasTypedArrays = false - } -} -if(!hasTypedArrays) { - var buffer = new Buffer(8) - module.exports = function doubleBits(n) { - buffer.writeDoubleLE(n, 0, true) - return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ] - } - function toDouble(lo, hi) { - buffer.writeUInt32LE(lo, 0, true) - buffer.writeUInt32LE(hi, 4, true) - return buffer.readDoubleLE(0, true) - } - module.exports.pack = toDouble - function lowUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(0, true) - } - module.exports.lo = lowUint - function highUint(n) { - buffer.writeDoubleLE(n, 0, true) - return buffer.readUInt32LE(4, true) + // There is no host WeakMap, so we must use the emulation. + + // Emulated WeakMaps are incompatible with native proxies (because proxies + // can observe the hidden name), so we must disable Proxy usage (in + // ArrayLike and Domado, currently). + if (typeof Proxy !== 'undefined') { + Proxy = undefined; + } + + module.exports = OurWeakMap; } - module.exports.hi = highUint -} +})(); -module.exports.sign = function(n) { - return module.exports.hi(n) >>> 31 -} +},{}],169:[function(require,module,exports){ +'use strict' -module.exports.exponent = function(n) { - var b = module.exports.hi(n) - return ((b<<1) >>> 21) - 1023 -} +var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') -module.exports.fraction = function(n) { - var lo = module.exports.lo(n) - var hi = module.exports.hi(n) - var b = hi & ((1<<20) - 1) - if(hi & 0x7ff00000) { - b += (1<<20) +var TriangleCache = new weakMap() + +function createABigTriangle(gl) { + + var triangleVAO = TriangleCache.get(gl) + if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) { + var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) + triangleVAO = createVAO(gl, [ + { buffer: buf, + type: gl.FLOAT, + size: 2 + } + ]) + triangleVAO._triangleBuffer = buf + TriangleCache.set(gl, triangleVAO) } - return [lo, b] + triangleVAO.bind() + gl.drawArrays(gl.TRIANGLES, 0, 3) + triangleVAO.unbind() } -module.exports.denormalized = function(n) { - var hi = module.exports.hi(n) - return !(hi & 0x7ff00000) -} -}).call(this,require("buffer").Buffer) -},{"buffer":65}],385:[function(require,module,exports){ +module.exports = createABigTriangle + +},{"gl-buffer":118,"gl-vao":226,"weak-map":168}],170:[function(require,module,exports){ 'use strict' -var bnsign = require('./lib/bn-sign') +module.exports = createAxes -module.exports = sign +var createText = require('./lib/text.js') +var createLines = require('./lib/lines.js') +var createBackground = require('./lib/background.js') +var getCubeProperties = require('./lib/cube.js') +var Ticks = require('./lib/ticks.js') -function sign(x) { - return bnsign(x[0]) * bnsign(x[1]) +var identity = new Float32Array([ + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]) + +function copyVec3(a, b) { + a[0] = b[0] + a[1] = b[1] + a[2] = b[2] + return a } -},{"./lib/bn-sign":374}],386:[function(require,module,exports){ -'use strict' +function Axes(gl) { + this.gl = gl -var rationalize = require('./lib/rationalize') + this.pixelRatio = 1 -module.exports = sub + this.bounds = [ [-10, -10, -10], + [ 10, 10, 10] ] + this.ticks = [ [], [], [] ] + this.autoTicks = true + this.tickSpacing = [ 1, 1, 1 ] -function sub(a, b) { - return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1])) -} + this.tickEnable = [ true, true, true ] + this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ] + this.tickSize = [ 12, 12, 12 ] + this.tickAngle = [ 0, 0, 0 ] + this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.tickPad = [ 10, 10, 10 ] -},{"./lib/rationalize":379}],387:[function(require,module,exports){ -'use strict' + this.lastCubeProps = { + cubeEdges: [0,0,0], + axis: [0,0,0] + } -var bn2num = require('./lib/bn-to-num') -var ctz = require('./lib/ctz') + this.labels = [ 'x', 'y', 'z' ] + this.labelEnable = [ true, true, true ] + this.labelFont = 'sans-serif' + this.labelSize = [ 20, 20, 20 ] + this.labelAngle = [ 0, 0, 0 ] + this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.labelPad = [ 10, 10, 10 ] -module.exports = roundRat + this.lineEnable = [ true, true, true ] + this.lineMirror = [ false, false, false ] + this.lineWidth = [ 1, 1, 1 ] + this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] -//Round a rational to the closest float -function roundRat(f) { - var a = f[0] - var b = f[1] - if(a.cmpn(0) === 0) { - return 0 - } - var h = a.divmod(b) - var iv = h.div - var x = bn2num(iv) - var ir = h.mod - if(ir.cmpn(0) === 0) { - return x - } - if(x) { - var s = ctz(x) + 4 - var y = bn2num(ir.shln(s).divRound(b)) + this.lineTickEnable = [ true, true, true ] + this.lineTickMirror = [ false, false, false ] + this.lineTickLength = [ 0, 0, 0 ] + this.lineTickWidth = [ 1, 1, 1 ] + this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - // flip the sign of y if x is negative - if (x<0) { - y = -y; - } + this.gridEnable = [ true, true, true ] + this.gridWidth = [ 1, 1, 1 ] + this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - return x + y * Math.pow(2, -s) - } else { - var ybits = b.bitLength() - ir.bitLength() + 53 - var y = bn2num(ir.shln(ybits).divRound(b)) - if(ybits < 1023) { - return y * Math.pow(2, -ybits) - } - y *= Math.pow(2, -1023) - return y * Math.pow(2, 1023-ybits) - } -} + this.zeroEnable = [ true, true, true ] + this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] + this.zeroLineWidth = [ 2, 2, 2 ] -},{"./lib/bn-to-num":375,"./lib/ctz":376}],388:[function(require,module,exports){ -'use strict' + this.backgroundEnable = [ false, false, false ] + this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5], + [0.8, 0.8, 0.8, 0.5], + [0.8, 0.8, 0.8, 0.5] ] -module.exports = boxIntersectWrapper + this._firstInit = true + this._text = null + this._lines = null + this._background = createBackground(gl) +} -var pool = require('typedarray-pool') -var sweep = require('./lib/sweep') -var boxIntersectIter = require('./lib/intersect') +var proto = Axes.prototype -function boxEmpty(d, box) { - for(var j=0; j>>1 - if(d <= 0) { - return + if(boundsChanged && this.autoTicks) { + nextTicks = Ticks.create(this.bounds, this.tickSpacing) + ticksUpdate = true } - var retval + //Compare next ticks to previous ticks, only update if needed + if(ticksUpdate) { + for(var i=0; i<3; ++i) { + nextTicks[i].sort(function(a,b) { + return a.x-b.x + }) + } + if(Ticks.equal(nextTicks, this.ticks)) { + ticksUpdate = false + } else { + this.ticks = nextTicks + } + } - //Convert red boxes - var redList = pool.mallocDouble(2*d*n) - var redIds = pool.mallocInt32(n) - n = convertBoxes(red, d, redList, redIds) + //Parse tick properties + BOOLEAN('tickEnable') + if(STRING('tickFont')) { + ticksUpdate = true //If font changes, must rebuild vbo + } + NUMBER('tickSize') + NUMBER('tickAngle') + NUMBER('tickPad') + COLOR('tickColor') - if(n > 0) { - if(d === 1 && full) { - //Special case: 1d complete - sweep.init(n) - retval = sweep.sweepComplete( - d, visit, - 0, n, redList, redIds, - 0, n, redList, redIds) - } else { + //Axis labels + var labelUpdate = STRING('labels') + if(STRING('labelFont')) { + labelUpdate = true + } + BOOLEAN('labelEnable') + NUMBER('labelSize') + NUMBER('labelPad') + COLOR('labelColor') - //Convert blue boxes - var blueList = pool.mallocDouble(2*d*m) - var blueIds = pool.mallocInt32(m) - m = convertBoxes(blue, d, blueList, blueIds) + //Axis lines + BOOLEAN('lineEnable') + BOOLEAN('lineMirror') + NUMBER('lineWidth') + COLOR('lineColor') - if(m > 0) { - sweep.init(n+m) + //Axis line ticks + BOOLEAN('lineTickEnable') + BOOLEAN('lineTickMirror') + NUMBER('lineTickLength') + NUMBER('lineTickWidth') + COLOR('lineTickColor') - if(d === 1) { - //Special case: 1d bipartite - retval = sweep.sweepBipartite( - d, visit, - 0, n, redList, redIds, - 0, m, blueList, blueIds) - } else { - //General case: d>1 - retval = boxIntersectIter( - d, visit, full, - n, redList, redIds, - m, blueList, blueIds) - } + //Grid lines + BOOLEAN('gridEnable') + NUMBER('gridWidth') + COLOR('gridColor') - pool.free(blueList) - pool.free(blueIds) - } - } + //Zero line + BOOLEAN('zeroEnable') + COLOR('zeroLineColor') + NUMBER('zeroLineWidth') - pool.free(redList) - pool.free(redIds) + //Background + BOOLEAN('backgroundEnable') + COLOR('backgroundColor') + + //Update text if necessary + if(!this._text) { + this._text = createText( + this.gl, + this.bounds, + this.labels, + this.labelFont, + this.ticks, + this.tickFont) + } else if(this._text && (labelUpdate || ticksUpdate)) { + this._text.update( + this.bounds, + this.labels, + this.labelFont, + this.ticks, + this.tickFont) } - return retval + //Update lines if necessary + if(this._lines && ticksUpdate) { + this._lines.dispose() + this._lines = null + } + if(!this._lines) { + this._lines = createLines(this.gl, this.bounds, this.ticks) + } +} + +function OffsetInfo() { + this.primalOffset = [0,0,0] + this.primalMinor = [0,0,0] + this.mirrorOffset = [0,0,0] + this.mirrorMinor = [0,0,0] } +var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ] -var RESULT +function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) { + var primalOffset = result.primalOffset + var primalMinor = result.primalMinor + var dualOffset = result.mirrorOffset + var dualMinor = result.mirrorMinor + var e = cubeEdges[i] -function appendItem(i,j) { - RESULT.push([i,j]) + //Calculate offsets + for(var j=0; j<3; ++j) { + if(i === j) { + continue + } + var a = primalOffset, + b = dualOffset, + c = primalMinor, + d = dualMinor + if(e & (1< 0) { + c[j] = -1 + d[j] = 0 + } else { + c[j] = 0 + d[j] = +1 + } + } } -function intersectFullArray(x) { - RESULT = [] - boxIntersect(x, x, appendItem, true) - return RESULT +var CUBE_ENABLE = [0,0,0] +var DEFAULT_PARAMS = { + model: identity, + view: identity, + projection: identity } -function intersectBipartiteArray(x, y) { - RESULT = [] - boxIntersect(x, y, appendItem, false) - return RESULT +proto.isOpaque = function() { + return true } -//User-friendly wrapper, handle full input and no-visitor cases -function boxIntersectWrapper(arg0, arg1, arg2) { - var result - switch(arguments.length) { - case 1: - return intersectFullArray(arg0) - case 2: - if(typeof arg1 === 'function') { - return boxIntersect(arg0, arg0, arg1, true) - } else { - return intersectBipartiteArray(arg0, arg1) - } - case 3: - return boxIntersect(arg0, arg1, arg2, false) - default: - throw new Error('box-intersect: Invalid arguments') - } +proto.isTransparent = function() { + return false } -},{"./lib/intersect":390,"./lib/sweep":394,"typedarray-pool":397}],389:[function(require,module,exports){ -'use strict' -var DIMENSION = 'd' -var AXIS = 'ax' -var VISIT = 'vv' -var FLIP = 'fp' +proto.drawTransparent = function(params) {} -var ELEM_SIZE = 'es' -var RED_START = 'rs' -var RED_END = 're' -var RED_BOXES = 'rb' -var RED_INDEX = 'ri' -var RED_PTR = 'rp' +var PRIMAL_MINOR = [0,0,0] +var MIRROR_MINOR = [0,0,0] +var PRIMAL_OFFSET = [0,0,0] -var BLUE_START = 'bs' -var BLUE_END = 'be' -var BLUE_BOXES = 'bb' -var BLUE_INDEX = 'bi' -var BLUE_PTR = 'bp' +proto.draw = function(params) { + params = params || DEFAULT_PARAMS -var RETVAL = 'rv' + var gl = this.gl + + //Geometry for camera and axes + var model = params.model || identity + var view = params.view || identity + var projection = params.projection || identity + var bounds = this.bounds + + //Unpack axis info + var cubeParams = getCubeProperties(model, view, projection, bounds) + var cubeEdges = cubeParams.cubeEdges + var cubeAxis = cubeParams.axis + + var cx = view[12] + var cy = view[13] + var cz = view[14] + var cw = view[15] + + var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight + + for(var i=0; i<3; ++i) { + this.lastCubeProps.cubeEdges[i] = cubeEdges[i] + this.lastCubeProps.axis[i] = cubeAxis[i] + } + + //Compute axis info + var lineOffset = LINE_OFFSET + for(var i=0; i<3; ++i) { + computeLineOffset( + LINE_OFFSET[i], + i, + this.bounds, + cubeEdges, + cubeAxis) + } + + //Set up state parameters + var gl = this.gl + + //Draw background first + var cubeEnable = CUBE_ENABLE + for(var i=0; i<3; ++i) { + if(this.backgroundEnable[i]) { + cubeEnable[i] = cubeAxis[i] + } else { + cubeEnable[i] = 0 + } + } + + this._background.draw( + model, + view, + projection, + bounds, + cubeEnable, + this.backgroundColor) + + //Draw lines + this._lines.bind( + model, + view, + projection, + this) -var INNER_LABEL = 'Q' + //First draw grid lines and zero lines + for(var i=0; i<3; ++i) { + var x = [0,0,0] + if(cubeAxis[i] > 0) { + x[i] = bounds[1][i] + } else { + x[i] = bounds[0][i] + } -var ARGS = [ - DIMENSION, - AXIS, - VISIT, - RED_START, - RED_END, - RED_BOXES, - RED_INDEX, - BLUE_START, - BLUE_END, - BLUE_BOXES, - BLUE_INDEX -] + //Draw grid lines + for(var j=0; j<2; ++j) { + var u = (i + 1 + j) % 3 + var v = (i + 1 + (j^1)) % 3 + if(this.gridEnable[u]) { + this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio) + } + } -function generateBruteForce(redMajor, flip, full) { - var funcName = 'bruteForce' + - (redMajor ? 'Red' : 'Blue') + - (flip ? 'Flip' : '') + - (full ? 'Full' : '') + //Draw zero lines (need to do this AFTER all grid lines are drawn) + for(var j=0; j<2; ++j) { + var u = (i + 1 + j) % 3 + var v = (i + 1 + (j^1)) % 3 + if(this.zeroEnable[v]) { + //Check if zero line in bounds + if(bounds[0][v] <= 0 && bounds[1][v] >= 0) { + this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio) + } + } + } + } - var code = ['function ', funcName, '(', ARGS.join(), '){', - 'var ', ELEM_SIZE, '=2*', DIMENSION, ';'] + //Then draw axis lines and tick marks + for(var i=0; i<3; ++i) { - var redLoop = - 'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' + - 'i<' + RED_END +';' + - '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' + - 'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' + - 'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' + - 'xi=' + RED_INDEX + '[i];' + //Draw axis lines + if(this.lineEnable[i]) { + this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) + } + if(this.lineMirror[i]) { + this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) + } - var blueLoop = - 'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' + - 'j<' + BLUE_END + ';' + - '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' + - 'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' + - (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') + - 'yi=' + BLUE_INDEX + '[j];' + //Compute minor axes + var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor) + var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor) + var tickLength = this.lineTickLength + var op = 0 + for(var j=0; j<3; ++j) { + var scaleFactor = pixelScaleF / model[5*j] + primalMinor[j] *= tickLength[j] * scaleFactor + mirrorMinor[j] *= tickLength[j] * scaleFactor + } - if(redMajor) { - code.push(redLoop, INNER_LABEL, ':', blueLoop) - } else { - code.push(blueLoop, INNER_LABEL, ':', redLoop) + //Draw axis line ticks + if(this.lineTickEnable[i]) { + this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) + } + if(this.lineTickMirror[i]) { + this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) + } } - if(full) { - code.push('if(y1' + - BLUE_END + '-' + BLUE_START + '){') + //Add label padding + for(var j=0; j<3; ++j) { + offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j] + } + offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]) - if(full) { - invoke(true, false) - code.push('}else{') - invoke(false, false) - } else { - code.push('if(' + FLIP + '){') - invoke(true, true) - code.push('}else{') - invoke(true, false) - code.push('}}else{if(' + FLIP + '){') - invoke(false, true) - code.push('}else{') - invoke(false, false) - code.push('}') + //Draw axis + this._text.drawLabel( + i, + this.labelSize[i], + this.labelAngle[i], + offset, + this.labelColor[i]) + } } - code.push('}}return ' + funcName) +} - var codeStr = prefix.join('') + code.join('') - var proc = new Function(codeStr) - return proc() +proto.dispose = function() { + this._text.dispose() + this._lines.dispose() + this._background.dispose() + this._lines = null + this._text = null + this._background = null + this.gl = null } +function createAxes(gl, options) { + var axes = new Axes(gl) + axes.update(options) + return axes +} -exports.partial = bruteForcePlanner(false) -exports.full = bruteForcePlanner(true) -},{}],390:[function(require,module,exports){ +},{"./lib/background.js":171,"./lib/cube.js":172,"./lib/lines.js":173,"./lib/text.js":175,"./lib/ticks.js":176}],171:[function(require,module,exports){ 'use strict' -module.exports = boxIntersectIter - -var pool = require('typedarray-pool') -var bits = require('bit-twiddle') -var bruteForce = require('./brute') -var bruteForcePartial = bruteForce.partial -var bruteForceFull = bruteForce.full -var sweep = require('./sweep') -var findMedian = require('./median') -var genPartition = require('./partition') +module.exports = createBackgroundCube -//Twiddle parameters -var BRUTE_FORCE_CUTOFF = 128 //Cut off for brute force search -var SCAN_CUTOFF = (1<<22) //Cut off for two way scan -var SCAN_COMPLETE_CUTOFF = (1<<22) +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders').bg -//Partition functions -var partitionInteriorContainsInterval = genPartition( - '!(lo>=p0)&&!(p1>=hi)', - ['p0', 'p1']) +function BackgroundCube(gl, buffer, vao, shader) { + this.gl = gl + this.buffer = buffer + this.vao = vao + this.shader = shader +} -var partitionStartEqual = genPartition( - 'lo===p0', - ['p0']) +var proto = BackgroundCube.prototype -var partitionStartLessThan = genPartition( - 'lo 0) { - top -= 1 + var base = p[0] + var ax = base[0] / base[3] + var ay = base[1] / base[3] + var area = 0.0 + for(var i=1; i+1= redEnd) { - continue - } - } - if(state & 4) { - redStart = partitionEndLessThanEqual( - d, axis, - redStart, redEnd, red, redIndex, - lo) - if(redStart >= redEnd) { - continue - } - } - - var redCount = redEnd - redStart - var blueCount = blueEnd - blueStart + return area +} - if(full) { - if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) { - retval = sweep.scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } - } else { - if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) { - //If input small, then use brute force - retval = bruteForcePartial( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } else if(d * redCount * blueCount < SCAN_CUTOFF) { - //If input medium sized, then use sweep and prune - retval = sweep.scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - continue - } - } - - //First, find all red intervals whose interior contains (lo,hi) - var red0 = partitionInteriorContainsInterval( - d, axis, - redStart, redEnd, red, redIndex, - lo, hi) +var CUBE_EDGES = [1,1,1] +var CUBE_AXIS = [0,0,0] +var CUBE_RESULT = { + cubeEdges: CUBE_EDGES, + axis: CUBE_AXIS +} - //Lower dimensional case - if(redStart < red0) { +function getCubeEdges(model, view, projection, bounds) { - if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) { - //Special case for small inputs: use brute force - retval = bruteForceFull( - d, axis+1, visit, - redStart, red0, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - if(retval !== void 0) { - return retval - } - } else if(axis === d-2) { - if(flip) { - retval = sweep.sweepBipartite( - d, visit, - blueStart, blueEnd, blue, blueIndex, - redStart, red0, red, redIndex) - } else { - retval = sweep.sweepBipartite( - d, visit, - redStart, red0, red, redIndex, - blueStart, blueEnd, blue, blueIndex) - } - if(retval !== void 0) { - return retval - } - } else { - iterPush(top++, - axis+1, - redStart, red0, - blueStart, blueEnd, - flip, - -Infinity, Infinity) - iterPush(top++, - axis+1, - blueStart, blueEnd, - redStart, red0, - flip^1, - -Infinity, Infinity) + //Concatenate matrices + multiply(mvp, view, model) + multiply(mvp, projection, mvp) + + //First project cube vertices + var ptr = 0 + for(var i=0; i<2; ++i) { + x[2] = bounds[i][2] + for(var j=0; j<2; ++j) { + x[1] = bounds[j][1] + for(var k=0; k<2; ++k) { + x[0] = bounds[k][0] + transformHg(pCubeVerts[ptr], x, mvp) + ptr += 1 } } + } - //Divide and conquer phase - if(red0 < redEnd) { - - //Cut blue into 3 parts: - // - // Points < mid point - // Points = mid point - // Points > mid point - // - var blue0 = findMedian( - d, axis, - blueStart, blueEnd, blue, blueIndex) - var mid = blue[elemSize * blue0 + axis] - var blue1 = partitionStartEqual( - d, axis, - blue0, blueEnd, blue, blueIndex, - mid) - - //Right case - if(blue1 < blueEnd) { - iterPush(top++, - axis, - red0, redEnd, - blue1, blueEnd, - (flip|4) + (full ? 16 : 0), - mid, hi) - } + //Classify camera against cube faces + var closest = -1 - //Left case - if(blueStart < blue0) { - iterPush(top++, - axis, - red0, redEnd, - blueStart, blue0, - (flip|2) + (full ? 16 : 0), - lo, mid) + for(var i=0; i<8; ++i) { + var w = pCubeVerts[i][3] + for(var l=0; l<3; ++l) { + cubeVerts[i][l] = pCubeVerts[i][l] / w + } + if(w < 0) { + if(closest < 0) { + closest = i + } else if(cubeVerts[i][2] < cubeVerts[closest][2]) { + closest = i } + } + } - //Center case (the hard part) - if(blue0 + 1 === blue1) { - //Optimization: Range with exactly 1 point, use a brute force scan - if(full) { - retval = onePointFull( - d, axis, visit, - red0, redEnd, red, redIndex, - blue0, blue, blueIndex[blue0]) + if(closest < 0) { + closest = 0 + for(var d=0; d<3; ++d) { + var u = (d+2) % 3 + var v = (d+1) % 3 + var o0 = -1 + var o1 = -1 + for(var s=0; s<2; ++s) { + var f0 = (s< o0) { + closest |= 1< o0) { + closest |= 1<start && boxes[ptr+axis] > x; - --j, ptr-=elemSize) { - //Swap - var aPtr = ptr - var bPtr = ptr+elemSize - for(var k=0; k cubeVerts[i][1]) { + bottom = i } } -} -//Find median using quick select algorithm -// takes O(n) time with high probability -function findMedian(d, axis, start, end, boxes, ids) { - if(end <= start+1) { - return start + //Find left/right neighbors of bottom vertex + var left = -1 + for(var i=0; i<3; ++i) { + var idx = bottom ^ (1<>> 1) - var elemSize = 2*d - var pivot = mid - var value = boxes[elemSize*mid+axis] - - while(lo < hi) { - if(hi - lo < PARTITION_THRESHOLD) { - insertionSort(d, axis, lo, hi, boxes, ids) - value = boxes[elemSize*mid+axis] - break + var right = -1 + for(var i=0; i<3; ++i) { + var idx = bottom ^ (1<= value1) { - pivot = pivot1 - value = value1 - } else if(value0 >= value2) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } - } else { - if(value1 >= value2) { - pivot = pivot1 - value = value1 - } else if(value2 >= value0) { - pivot = pivot0 - value = value0 - } else { - pivot = pivot2 - value = value2 - } + if(right < 0) { + right = idx } - - //Swap pivot to end of array - var aPtr = elemSize * (hi-1) - var bPtr = elemSize * pivot - for(var i=0; i cubeVerts[right][0]) { + right = idx } - var y = ids[hi-1] - ids[hi-1] = ids[pivot] - ids[pivot] = y - - //Partition using pivot - pivot = partitionStartLessThan( - d, axis, - lo, hi-1, boxes, ids, - value) + } - //Swap pivot back - var aPtr = elemSize * (hi-1) - var bPtr = elemSize * pivot - for(var i=0; i= 0) { - reads.push('lo=e[k+n]') - } - if(predicate.indexOf('hi') >= 0) { - reads.push('hi=e[k+o]') - } - fargs.push( - code.replace('_', reads.join()) - .replace('$', predicate)) - return Function.apply(void 0, fargs) +var MAJOR_AXIS = [0,0,0] +var MINOR_AXIS = [0,0,0] +var SCREEN_AXIS = [0,0,0] +var OFFSET_VEC = [0,0,0] +var SHAPE = [1,1] + +function zeroVec(a) { + a[0] = a[1] = a[2] = 0 + return a } -},{}],393:[function(require,module,exports){ -'use strict'; -//This code is extracted from ndarray-sort -//It is inlined here as a temporary workaround +function copyVec(a,b) { + a[0] = b[0] + a[1] = b[1] + a[2] = b[2] + return a +} -module.exports = wrapper; +function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) { + this.gl = gl + this.vertBuffer = vertBuffer + this.vao = vao + this.shader = shader + this.tickCount = tickCount + this.tickOffset = tickOffset + this.gridCount = gridCount + this.gridOffset = gridOffset +} -var INSERT_SORT_CUTOFF = 32 +var proto = Lines.prototype -function wrapper(data, n0) { - if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data); - } else { - quickSort(0, n0 - 1, data); - } -} +proto.bind = function(model, view, projection) { + this.shader.bind() + this.shader.uniforms.model = model + this.shader.uniforms.view = view + this.shader.uniforms.projection = projection -function insertionSort(left, right, data) { - var ptr = 2*(left+1) - for(var i=left+1; i<=right; ++i) { - var a = data[ptr++] - var b = data[ptr++] - var j = i - var jptr = ptr-2 - while(j-- > left) { - var x = data[jptr-2] - var y = data[jptr-1] - if(x < a) { - break - } else if(x === a && y < b) { - break - } - data[jptr] = x - data[jptr+1] = y - jptr -= 2 - } - data[jptr] = a - data[jptr+1] = b - } -} + SHAPE[0] = this.gl.drawingBufferWidth + SHAPE[1] = this.gl.drawingBufferHeight -function swap(i, j, data) { - i *= 2 - j *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = x - data[j+1] = y + this.shader.uniforms.screenShape = SHAPE + this.vao.bind() } -function move(i, j, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[i+1] = data[j+1] -} +proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) { + var minorAxis = zeroVec(MINOR_AXIS) + this.shader.uniforms.majorAxis = MINOR_AXIS -function rotate(i, j, k, data) { - i *= 2 - j *= 2 - k *= 2 - var x = data[i] - var y = data[i+1] - data[i] = data[j] - data[i+1] = data[j+1] - data[j] = data[k] - data[j+1] = data[k+1] - data[k] = x - data[k+1] = y -} + minorAxis[j] = bounds[1][j] - bounds[0][j] + this.shader.uniforms.minorAxis = minorAxis -function shufflePivot(i, j, px, py, data) { - i *= 2 - j *= 2 - data[i] = data[j] - data[j] = px - data[i+1] = data[j+1] - data[j+1] = py -} + var noffset = copyVec(OFFSET_VEC, offset) + noffset[j] += bounds[0][j] + this.shader.uniforms.offset = noffset -function compare(i, j, data) { - i *= 2 - j *= 2 - var x = data[i], - y = data[j] - if(x < y) { - return false - } else if(x === y) { - return data[i+1] > data[j+1] - } - return true -} + this.shader.uniforms.lineWidth = lineWidth -function comparePivot(i, y, b, data) { - i *= 2 - var x = data[i] - if(x < y) { - return true - } else if(x === y) { - return data[i+1] < b - } - return false -} + this.shader.uniforms.color = color -function quickSort(left, right, data) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, - tmp = 0 - if(compare(el1, el2, data)) { - tmp = el1 - el1 = el2 - el2 = tmp - } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - if(compare(el1, el3, data)) { - tmp = el1 - el1 = el3 - el3 = tmp - } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(compare(el1, el4, data)) { - tmp = el1 - el1 = el4 - el4 = tmp - } - if(compare(el3, el4, data)) { - tmp = el3 - el3 = el4 - el4 = tmp - } - if(compare(el2, el5, data)) { - tmp = el2 - el2 = el5 - el5 = tmp - } - if(compare(el2, el3, data)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(compare(el4, el5, data)) { - tmp = el4 - el4 = el5 - el5 = tmp - } + var screenAxis = zeroVec(SCREEN_AXIS) + screenAxis[(j+2)%3] = 1 + this.shader.uniforms.screenAxis = screenAxis + this.vao.draw(this.gl.TRIANGLES, 6) - var pivot1X = data[2*el2] - var pivot1Y = data[2*el2+1] - var pivot2X = data[2*el4] - var pivot2Y = data[2*el4+1] + var screenAxis = zeroVec(SCREEN_AXIS) + screenAxis[(j+1)%3] = 1 + this.shader.uniforms.screenAxis = screenAxis + this.vao.draw(this.gl.TRIANGLES, 6) +} - var ptr0 = 2 * el1; - var ptr2 = 2 * el3; - var ptr4 = 2 * el5; - var ptr5 = 2 * index1; - var ptr6 = 2 * index3; - var ptr7 = 2 * index5; - for (var i1 = 0; i1 < 2; ++i1) { - var x = data[ptr0+i1]; - var y = data[ptr2+i1]; - var z = data[ptr4+i1]; - data[ptr5+i1] = x; - data[ptr6+i1] = y; - data[ptr7+i1] = z; +proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) { + if(!this.tickCount[j]) { + return } - move(index2, left, data) - move(index4, right, data) - for (var k = less; k <= great; ++k) { - if (comparePivot(k, pivot1X, pivot1Y, data)) { - if (k !== less) { - swap(k, less, data) - } - ++less; - } else { - if (!comparePivot(k, pivot2X, pivot2Y, data)) { - while (true) { - if (!comparePivot(great, pivot2X, pivot2Y, data)) { - if (--great < k) { - break; - } - continue; - } else { - if (comparePivot(great, pivot1X, pivot1Y, data)) { - rotate(k, less, great, data) - ++less; - --great; - } else { - swap(k, great, data) - --great; - } - break; - } - } - } - } - } - shufflePivot(left, less-1, pivot1X, pivot1Y, data) - shufflePivot(right, great+1, pivot2X, pivot2Y, data) - if (less - 2 - left <= INSERT_SORT_CUTOFF) { - insertionSort(left, less - 2, data); - } else { - quickSort(left, less - 2, data); - } - if (right - (great + 2) <= INSERT_SORT_CUTOFF) { - insertionSort(great + 2, right, data); - } else { - quickSort(great + 2, right, data); - } - if (great - less <= INSERT_SORT_CUTOFF) { - insertionSort(less, great, data); - } else { - quickSort(less, great, data); - } -} -},{}],394:[function(require,module,exports){ -'use strict' + var majorAxis = zeroVec(MAJOR_AXIS) + majorAxis[j] = 1 + this.shader.uniforms.majorAxis = majorAxis + this.shader.uniforms.offset = offset + this.shader.uniforms.minorAxis = minorAxis + this.shader.uniforms.color = color + this.shader.uniforms.lineWidth = lineWidth -module.exports = { - init: sqInit, - sweepBipartite: sweepBipartite, - sweepComplete: sweepComplete, - scanBipartite: scanBipartite, - scanComplete: scanComplete + var screenAxis = zeroVec(SCREEN_AXIS) + screenAxis[j] = 1 + this.shader.uniforms.screenAxis = screenAxis + this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j]) } -var pool = require('typedarray-pool') -var bits = require('bit-twiddle') -var isort = require('./sort') -//Flag for blue -var BLUE_FLAG = (1<<28) +proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) { + if(!this.gridCount[i]) { + return + } -//1D sweep event queue stuff (use pool to save space) -var INIT_CAPACITY = 1024 -var RED_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var RED_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var BLUE_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY) -var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY) -var SWEEP_EVENTS = pool.mallocDouble(INIT_CAPACITY * 8) + var minorAxis = zeroVec(MINOR_AXIS) + minorAxis[j] = bounds[1][j] - bounds[0][j] + this.shader.uniforms.minorAxis = minorAxis -//Reserves memory for the 1D sweep data structures -function sqInit(count) { - var rcount = bits.nextPow2(count) - if(RED_SWEEP_QUEUE.length < rcount) { - pool.free(RED_SWEEP_QUEUE) - RED_SWEEP_QUEUE = pool.mallocInt32(rcount) - } - if(RED_SWEEP_INDEX.length < rcount) { - pool.free(RED_SWEEP_INDEX) - RED_SWEEP_INDEX = pool.mallocInt32(rcount) - } - if(BLUE_SWEEP_QUEUE.length < rcount) { - pool.free(BLUE_SWEEP_QUEUE) - BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount) - } - if(BLUE_SWEEP_INDEX.length < rcount) { - pool.free(BLUE_SWEEP_INDEX) - BLUE_SWEEP_INDEX = pool.mallocInt32(rcount) - } - if(COMMON_SWEEP_QUEUE.length < rcount) { - pool.free(COMMON_SWEEP_QUEUE) - COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount) - } - if(COMMON_SWEEP_INDEX.length < rcount) { - pool.free(COMMON_SWEEP_INDEX) - COMMON_SWEEP_INDEX = pool.mallocInt32(rcount) - } - var eventLength = 8 * rcount - if(SWEEP_EVENTS.length < eventLength) { - pool.free(SWEEP_EVENTS) - SWEEP_EVENTS = pool.mallocDouble(eventLength) - } -} + var noffset = copyVec(OFFSET_VEC, offset) + noffset[j] += bounds[0][j] + this.shader.uniforms.offset = noffset -//Remove an item from the active queue in O(1) -function sqPop(queue, index, count, item) { - var idx = index[item] - var top = queue[count-1] - queue[idx] = top - index[top] = idx -} + var majorAxis = zeroVec(MAJOR_AXIS) + majorAxis[i] = 1 + this.shader.uniforms.majorAxis = majorAxis -//Insert an item into the active queue in O(1) -function sqPush(queue, index, count, item) { - queue[count] = item - index[item] = count + var screenAxis = zeroVec(SCREEN_AXIS) + screenAxis[i] = 1 + this.shader.uniforms.screenAxis = screenAxis + this.shader.uniforms.lineWidth = lineWidth + + this.shader.uniforms.color = color + this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i]) } -//Recursion base case: use 1D sweep algorithm -function sweepBipartite( - d, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { +proto.drawZero = function(j, i, bounds, offset, color, lineWidth) { + var minorAxis = zeroVec(MINOR_AXIS) + this.shader.uniforms.majorAxis = minorAxis - //store events as pairs [coordinate, idx] - // - // red create: -(idx+1) - // red destroy: idx - // blue create: -(idx+BLUE_FLAG) - // blue destroy: idx+BLUE_FLAG - // - var ptr = 0 - var elemSize = 2*d - var istart = d-1 - var iend = elemSize-1 + minorAxis[j] = bounds[1][j] - bounds[0][j] + this.shader.uniforms.minorAxis = minorAxis - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - for(var i=0; i= BLUE_FLAG) { - //blue destroy event - e = (e-BLUE_FLAG)|0 - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e) - } else if(e >= 0) { - //red destroy event - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e) - } else if(e <= -BLUE_FLAG) { - //blue create event - e = (-e-BLUE_FLAG)|0 - for(var j=0; jright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - var blueActive = 0 - var commonActive = 0 - for(var i=0; i>1) === (SWEEP_EVENTS[2*i+3]>>1)) { - color = 2 - i += 1 + //Create cube VAO + var vertBuf = createBuffer(gl, new Float32Array(vertices)) + var vao = createVAO(gl, [ + { "buffer": vertBuf, + "type": gl.FLOAT, + "size": 3, + "stride": 0, + "offset": 0 } - - if(e < 0) { - //Create event - var id = -(e>>1) - 1 + ]) + var shader = createShader(gl) + shader.attributes.position.location = 0 + return new Lines(gl, vertBuf, vao, shader, tickCount, tickOffset, gridCount, gridOffset) +} - //Intersect with common - for(var j=0; j>1) - 1 - if(color === 0) { - //Red - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id) - } else if(color === 1) { - //Blue - sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id) - } else if(color === 2) { - //Both - sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id) - } - } - } +var lineVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n" +var lineFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" +exports.line = function(gl) { + return createShader(gl, lineVert, lineFrag, null, [ + {name: 'position', type: 'vec3'} + ]) } -//Sweep and prune/scanline algorithm: -// Scan along axis, detect intersections -// Brute force all boxes along axis -function scanBipartite( - d, axis, visit, flip, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { - - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d +var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}" +var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" +exports.text = function(gl) { + return createShader(gl, textVert, textFrag, null, [ + {name: 'position', type: 'vec3'} + ]) +} - var redShift = 1 - var blueShift = 1 - if(flip) { - blueShift = BLUE_FLAG - } else { - redShift = BLUE_FLAG - } +var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}" +var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}" +exports.bg = function(gl) { + return createShader(gl, bgVert, bgFrag, null, [ + {name: 'position', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) +} - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - isRed = !flip - idx -= BLUE_FLAG - } else { - isRed = !!flip - idx -= 1 - } - if(isRed) { - sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx) - } else { - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx - - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] +module.exports = createTextSprites -red_loop: - for(var j=0; j=0; --j) { + var p = positions[c[j]] + data.push(scale*p[0], -scale*p[1], t) } - } else { - sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift) } } -} -function scanComplete( - d, axis, visit, - redStart, redEnd, red, redIndex, - blueStart, blueEnd, blue, blueIndex) { + //Generate sprites for all 3 axes, store data in texture atlases + var tickOffset = [0,0,0] + var tickCount = [0,0,0] + var labelOffset = [0,0,0] + var labelCount = [0,0,0] + for(var d=0; d<3; ++d) { - var ptr = 0 - var elemSize = 2*d - var istart = axis - var iend = axis+d + //Generate label + labelOffset[d] = (data.length/VERTEX_SIZE)|0 + addItem(0.5*(bounds[0][d]+bounds[1][d]), labels[d], labelFont) + labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d] - for(var i=redStart; iright - var n = ptr >>> 1 - isort(SWEEP_EVENTS, n) - - var redActive = 0 - for(var i=0; i= BLUE_FLAG) { - RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG - } else { - idx -= 1 - var blueId = blueIndex[idx] - var bluePtr = elemSize * idx + this.buffer.update(data) + this.tickOffset = tickOffset + this.tickCount = tickCount + this.labelOffset = labelOffset + this.labelCount = labelCount +} - var b0 = blue[bluePtr+axis+1] - var b1 = blue[bluePtr+axis+1+d] +//Draws the tick marks for an axis +var AXIS = [0,0,0] +proto.drawTicks = function(d, scale, angle, offset, color) { + if(!this.tickCount[d]) { + return + } -red_loop: - for(var j=0; j=0; --j) { - if(RED_SWEEP_QUEUE[j] === idx) { - for(var k=j+1; k>>0 + var buffer = createBuffer(gl) + var vao = createVAO(gl, [ + { "buffer": buffer, + "size": 3 + } + ]) -module.exports = nextafter + var shader = createShader(gl) + shader.attributes.position.location = 0 + + var result = new TextSprites( + gl, + shader, + buffer, + vao) + + result.update(bounds, labels, labelFont, ticks, tickFont) + + return result +} + +}).call(this,require('_process')) +},{"./shaders":174,"_process":56,"gl-buffer":118,"gl-vao":226,"vectorize-text":280}],176:[function(require,module,exports){ +'use strict' + +exports.create = defaultTicks +exports.equal = ticksEqual -function nextafter(x, y) { - if(isNaN(x) || isNaN(y)) { - return NaN +function prettyPrint(spacing, i) { + var stepStr = spacing + "" + var u = stepStr.indexOf(".") + var sigFigs = 0 + if(u >= 0) { + sigFigs = stepStr.length - u - 1 } - if(x === y) { - return x + var shift = Math.pow(10, sigFigs) + var x = Math.round(spacing * i * shift) + var xstr = x + "" + if(xstr.indexOf("e") >= 0) { + return xstr } - if(x === 0) { - if(y < 0) { - return -SMALLEST_DENORM - } else { - return SMALLEST_DENORM - } + var xi = x / shift, xf = x % shift + if(x < 0) { + xi = -Math.ceil(xi)|0 + xf = (-xf)|0 + } else { + xi = Math.floor(xi)|0 + xf = xf|0 } - var hi = doubleBits.hi(x) - var lo = doubleBits.lo(x) - if((y > x) === (x > 0)) { - if(lo === UINT_MAX) { - hi += 1 - lo = 0 - } else { - lo += 1 + var xis = "" + xi + if(x < 0) { + xis = "-" + xis + } + if(sigFigs) { + var xs = "" + xf + while(xs.length < sigFigs) { + xs = "0" + xs } + return xis + "." + xs } else { - if(lo === 0) { - lo = UINT_MAX - hi -= 1 - } else { - lo -= 1 - } + return xis } - return doubleBits.pack(lo, hi) } -},{"double-bits":400}],400:[function(require,module,exports){ -arguments[4][384][0].apply(exports,arguments) -},{"buffer":65,"dup":384}],401:[function(require,module,exports){ -'use strict' -var bnadd = require('big-rat/add') - -module.exports = add - -function add(a, b) { - var n = a.length - var r = new Array(n) - for(var i=0; i=bounds[0][d]; --t) { + ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) + } + array.push(ticks) } - return r + return array } -},{"big-rat/add":369}],402:[function(require,module,exports){ -'use strict' - -module.exports = float2rat +function ticksEqual(ticksA, ticksB) { + for(var i=0; i<3; ++i) { + if(ticksA[i].length !== ticksB[i].length) { + return false + } + for(var j=0; j 1.0) { + t = 1.0 + } + var ti = 1.0 - t var n = a.length var r = new Array(n) for(var i=0; i 0) || (a > 0 && b < 0)) { + var p = lerpW(s, b, t, a) + pos.push(p) + neg.push(p.slice()) + } + if(b < 0) { + neg.push(t.slice()) + } else if(b > 0) { + pos.push(t.slice()) + } else { + pos.push(t.slice()) + neg.push(t.slice()) + } + a = b } - return r + return { positive: pos, negative: neg } } -},{"big-rat/sub":386}],405:[function(require,module,exports){ -"use strict" - -module.exports = segmentsIntersect - -var orient = require("robust-orientation")[3] - -function checkCollinear(a0, a1, b0, b1) { - - for(var d=0; d<2; ++d) { - var x0 = a0[d] - var y0 = a1[d] - var l0 = Math.min(x0, y0) - var h0 = Math.max(x0, y0) - - var x1 = b0[d] - var y1 = b1[d] - var l1 = Math.min(x1, y1) - var h1 = Math.max(x1, y1) - - if(h1 < l0 || h0 < l1) { - return false +function positive(points, plane) { + var pos = [] + var a = planeT(points[points.length-1], plane) + for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { + pos.push(lerpW(s, b, t, a)) + } + if(b >= 0) { + pos.push(t.slice()) } + a = b } - - return true + return pos } -function segmentsIntersect(a0, a1, b0, b1) { - var x0 = orient(a0, b0, b1) - var y0 = orient(a1, b0, b1) - if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) { - return false +function negative(points, plane) { + var neg = [] + var a = planeT(points[points.length-1], plane) + for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { + neg.push(lerpW(s, b, t, a)) + } + if(b <= 0) { + neg.push(t.slice()) + } + a = b } + return neg +} +},{"robust-dot-product":179,"robust-sum":262}],179:[function(require,module,exports){ +"use strict" - var x1 = orient(b0, a0, a1) - var y1 = orient(b1, a0, a1) - if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) { - return false - } +var twoProduct = require("two-product") +var robustSum = require("robust-sum") - //Check for degenerate collinear case - if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) { - return checkCollinear(a0, a1, b0, b1) - } +module.exports = robustDotProduct - return true +function robustDotProduct(a, b) { + var r = twoProduct(a[0], b[0]) + for(var i=1; i 0) { - var v = dead.pop() - live[v] = false - var n = adj[v] - for(var i=0; i 0) { - nextCell = adj[i][b][0] - nextDir = i - break - } - } - nextVertex = nextCell[nextDir^1] + var poly = [] - for(var dir=0; dir<2; ++dir) { - var nbhd = adj[dir][b] - for(var k=0; k 0) { - nextCell = e - nextVertex = p - nextDir = dir - } + if((axis[d] < 0) === !!i) { + continue } - } - if(noCut) { - return nextVertex - } - if(nextCell) { - cut(nextCell, nextDir) - } - return nextVertex - } - function extractCycle(v, dir) { - var e0 = adj[dir][v][0] - var cycle = [v] - cut(e0, dir) - var u = e0[dir^1] - var d0 = dir - while(true) { - while(u !== v) { - cycle.push(u) - u = next(cycle[cycle.length-2], u, false) - } - if(adj[0][v].length + adj[1][v].length === 0) { - break - } - var a = cycle[cycle.length-1] - var b = v - var c = cycle[1] - var d = next(a, b, true) - if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) { - break + x[d] = bounds[i][d] + for(var j=0; j<2; ++j) { + x[u] = bounds[j^i][u] + for(var k=0; k<2; ++k) { + x[v] = bounds[k^j^i][v] + poly.push(x.slice()) + } + } + for(var j=0; j 0) { - var ni = adj[0][i].length - var ncycle = extractCycle(i,j) - if(shouldGlue(pcycle, ncycle)) { - //Glue together trivial cycles - pcycle.push.apply(pcycle, ncycle) - } else { - if(pcycle.length > 0) { - cycles.push(pcycle) + //Loop over vertices of polygon to find extremal points + for(var j=0; j 0) { - cycles.push(pcycle) - } } } - //Combine paths and loops together - return cycles + return ranges } -},{"compare-angle":410}],410:[function(require,module,exports){ -"use strict" -module.exports = compareAngle +},{"./lib/cube.js":172,"extract-frustum-planes":177,"gl-mat4/multiply":139,"gl-mat4/transpose":147,"gl-vec4/transformMat4":227,"split-polygon":178}],181:[function(require,module,exports){ +'use strict' -var orient = require("robust-orientation") -var sgn = require("signum") -var twoSum = require("two-sum") -var robustProduct = require("robust-product") -var robustSum = require("robust-sum") -function testInterior(a, b, c) { - var x0 = twoSum(a[0], -b[0]) - var y0 = twoSum(a[1], -b[1]) - var x1 = twoSum(c[0], -b[0]) - var y1 = twoSum(c[1], -b[1]) +var createShader = require('gl-shader') - var d = robustSum( - robustProduct(x0, x1), - robustProduct(y0, y1)) +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n vec3 vertexPosition = mix(coordinates[0],\n mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n vec2 delta = weight * clipOffset * screenShape;\n vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n gl_Position = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n fragColor = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}" - return d[d.length-1] >= 0 +module.exports = function(gl) { + return createShader(gl, vertSrc, fragSrc, null, [ + {name: 'position', type: 'vec3'}, + {name: 'color', type: 'vec3'}, + {name: 'weight', type: 'float'} + ]) } -function compareAngle(a, b, c, d) { - var bcd = orient(b, c, d) - if(bcd === 0) { - //Handle degenerate cases - var sabc = sgn(orient(a, b, c)) - var sabd = sgn(orient(a, b, d)) - if(sabc === sabd) { - if(sabc === 0) { - var ic = testInterior(a, b, c) - var id = testInterior(a, b, d) - if(ic === id) { - return 0 - } else if(ic) { - return 1 - } else { - return -1 - } - } - return 0 - } else if(sabd === 0) { - if(sabc > 0) { - return -1 - } else if(testInterior(a, b, d)) { - return -1 - } else { - return 1 - } - } else if(sabc === 0) { - if(sabd > 0) { - return 1 - } else if(testInterior(a, b, c)) { - return 1 - } else { - return -1 - } - } - return sgn(sabd - sabc) +},{"gl-shader":197}],182:[function(require,module,exports){ +'use strict' + +var createBuffer = require('gl-buffer') +var createVAO = require('gl-vao') +var createShader = require('./shaders/index') + +module.exports = createSpikes + +var identity = [1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1] + +function AxisSpikes(gl, buffer, vao, shader) { + this.gl = gl + this.buffer = buffer + this.vao = vao + this.shader = shader + this.pixelRatio = 1 + this.bounds = [[-1000,-1000,-1000], [1000,1000,1000]] + this.position = [0,0,0] + this.lineWidth = [2,2,2] + this.colors = [[0,0,0,1], [0,0,0,1], [0,0,0,1]] + this.enabled = [true,true,true] + this.drawSides = [true,true,true] + this.axes = null +} + +var proto = AxisSpikes.prototype + +var OUTER_FACE = [0,0,0] +var INNER_FACE = [0,0,0] + +var SHAPE = [0,0] + +proto.isTransparent = function() { + return false +} + +proto.drawTransparent = function(camera) {} + +proto.draw = function(camera) { + var gl = this.gl + var vao = this.vao + var shader = this.shader + + vao.bind() + shader.bind() + + var model = camera.model || identity + var view = camera.view || identity + var projection = camera.projection || identity + + var axis + if(this.axes) { + axis = this.axes.lastCubeProps.axis } - var abc = orient(a, b, c) - if(abc > 0) { - if(bcd > 0 && orient(a, b, d) > 0) { - return 1 - } - return -1 - } else if(abc < 0) { - if(bcd > 0 || orient(a, b, d) > 0) { - return 1 - } - return -1 - } else { - var abd = orient(a, b, d) - if(abd > 0) { - return 1 + + var outerFace = OUTER_FACE + var innerFace = INNER_FACE + for(var i=0; i<3; ++i) { + if(axis && axis[i] < 0) { + outerFace[i] = this.bounds[0][i] + innerFace[i] = this.bounds[1][i] } else { - if(testInterior(a, b, c)) { - return 1 - } else { - return -1 - } + outerFace[i] = this.bounds[1][i] + innerFace[i] = this.bounds[0][i] } } -} -},{"robust-orientation":1040,"robust-product":412,"robust-sum":421,"signum":413,"two-sum":414}],411:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"dup":54,"two-product":422,"two-sum":414}],412:[function(require,module,exports){ -"use strict" -var robustSum = require("robust-sum") -var robustScale = require("robust-scale") + SHAPE[0] = gl.drawingBufferWidth + SHAPE[1] = gl.drawingBufferHeight -module.exports = robustProduct + shader.uniforms.model = model + shader.uniforms.view = view + shader.uniforms.projection = projection + shader.uniforms.coordinates = [this.position, outerFace, innerFace] + shader.uniforms.colors = this.colors + shader.uniforms.screenShape = SHAPE -function robustProduct(a, b) { - if(a.length === 1) { - return robustScale(b, a[0]) + for(var i=0; i<3; ++i) { + shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio + if(this.enabled[i]) { + vao.draw(gl.TRIANGLES, 6, 6*i) + if(this.drawSides[i]) { + vao.draw(gl.TRIANGLES, 12, 18+12*i) + } + } } - if(b.length === 1) { - return robustScale(a, b[0]) + + vao.unbind() +} + +proto.update = function(options) { + if(!options) { + return } - if(a.length === 0 || b.length === 0) { - return [0] + if("bounds" in options) { + this.bounds = options.bounds } - var r = [0] - if(a.length < b.length) { - for(var i=0; i 0) { return 1 } - return 0.0 +proto.dispose = function() { + this.vao.dispose() + this.buffer.dispose() + this.shader.dispose() } -},{}],414:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"dup":53}],415:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],416:[function(require,module,exports){ -"use strict" -var bounds = require("binary-search-bounds") -var NOT_FOUND = 0 -var SUCCESS = 1 -var EMPTY = 2 -module.exports = createWrapper +function createSpikes(gl, options) { + //Create buffers + var data = [ ] -function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { - this.mid = mid - this.left = left - this.right = right - this.leftPoints = leftPoints - this.rightPoints = rightPoints - this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length -} + function line(x,y,z,i,l,h) { + var row = [x,y,z, 0,0,0, 1] + row[i+3] = 1 + row[i] = l + data.push.apply(data, row) + row[6] = -1 + data.push.apply(data, row) + row[i] = h + data.push.apply(data, row) + data.push.apply(data, row) + row[6] = 1 + data.push.apply(data, row) + row[i] = l + data.push.apply(data, row) + } -var proto = IntervalTreeNode.prototype + line(0,0,0, 0, 0, 1) + line(0,0,0, 1, 0, 1) + line(0,0,0, 2, 0, 1) -function copy(a, b) { - a.mid = b.mid - a.left = b.left - a.right = b.right - a.leftPoints = b.leftPoints - a.rightPoints = b.rightPoints - a.count = b.count -} + line(1,0,0, 1, -1,1) + line(1,0,0, 2, -1,1) -function rebuild(node, intervals) { - var ntree = createIntervalTree(intervals) - node.mid = ntree.mid - node.left = ntree.left - node.right = ntree.right - node.leftPoints = ntree.leftPoints - node.rightPoints = ntree.rightPoints - node.count = ntree.count -} + line(0,1,0, 0, -1,1) + line(0,1,0, 2, -1,1) -function rebuildWithInterval(node, interval) { - var intervals = node.intervals([]) - intervals.push(interval) - rebuild(node, intervals) -} + line(0,0,1, 0, -1,1) + line(0,0,1, 1, -1,1) -function rebuildWithoutInterval(node, interval) { - var intervals = node.intervals([]) - var idx = intervals.indexOf(interval) - if(idx < 0) { - return NOT_FOUND - } - intervals.splice(idx, 1) - rebuild(node, intervals) - return SUCCESS -} + var buffer = createBuffer(gl, data) + var vao = createVAO(gl, [{ + type: gl.FLOAT, + buffer: buffer, + size: 3, + offset: 0, + stride: 28 + }, { + type: gl.FLOAT, + buffer: buffer, + size: 3, + offset: 12, + stride: 28 + }, { + type: gl.FLOAT, + buffer: buffer, + size: 1, + offset: 24, + stride: 28 + }]) -proto.intervals = function(result) { - result.push.apply(result, this.leftPoints) - if(this.left) { - this.left.intervals(result) - } - if(this.right) { - this.right.intervals(result) - } - return result + //Create shader + var shader = createShader(gl) + shader.attributes.position.location = 0 + shader.attributes.color.location = 1 + shader.attributes.weight.location = 2 + + //Create spike object + var spikes = new AxisSpikes(gl, buffer, vao, shader) + + //Set parameters + spikes.update(options) + + //Return resulting object + return spikes } -proto.insert = function(interval) { - var weight = this.count - this.leftPoints.length - this.count += 1 - if(interval[1] < this.mid) { - if(this.left) { - if(4*(this.left.count+1) > 3*(weight+1)) { - rebuildWithInterval(this, interval) - } else { - this.left.insert(interval) - } - } else { - this.left = createIntervalTree([interval]) - } - } else if(interval[0] > this.mid) { - if(this.right) { - if(4*(this.right.count+1) > 3*(weight+1)) { - rebuildWithInterval(this, interval) - } else { - this.right.insert(interval) - } - } else { - this.right = createIntervalTree([interval]) - } - } else { - var l = bounds.ge(this.leftPoints, interval, compareBegin) - var r = bounds.ge(this.rightPoints, interval, compareEnd) - this.leftPoints.splice(l, 0, interval) - this.rightPoints.splice(r, 0, interval) - } +},{"./shaders/index":181,"gl-buffer":118,"gl-vao":226}],183:[function(require,module,exports){ +'use strict' + +module.exports = createScene + +var createCamera = require('3d-view-controls') +var createAxes = require('gl-axes3d') +var axesRanges = require('gl-axes3d/properties') +var createSpikes = require('gl-spikes3d') +var createSelect = require('gl-select-static') +var createFBO = require('gl-fbo') +var drawTriangle = require('a-big-triangle') +var mouseChange = require('mouse-change') +var perspective = require('gl-mat4/perspective') +var createShader = require('./lib/shader') + +function MouseSelect() { + this.mouse = [-1,-1] + this.screen = null + this.distance = Infinity + this.index = null + this.dataCoordinate = null + this.dataPosition = null + this.object = null + this.data = null } -proto.remove = function(interval) { - var weight = this.count - this.leftPoints - if(interval[1] < this.mid) { - if(!this.left) { - return NOT_FOUND - } - var rw = this.right ? this.right.count : 0 - if(4 * rw > 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) - } - var r = this.left.remove(interval) - if(r === EMPTY) { - this.left = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 - } - return r - } else if(interval[0] > this.mid) { - if(!this.right) { - return NOT_FOUND - } - var lw = this.left ? this.left.count : 0 - if(4 * lw > 3 * (weight-1)) { - return rebuildWithoutInterval(this, interval) - } - var r = this.right.remove(interval) - if(r === EMPTY) { - this.right = null - this.count -= 1 - return SUCCESS - } else if(r === SUCCESS) { - this.count -= 1 - } - return r - } else { - if(this.count === 1) { - if(this.leftPoints[0] === interval) { - return EMPTY - } else { - return NOT_FOUND - } - } - if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { - if(this.left && this.right) { - var p = this - var n = this.left - while(n.right) { - p = n - n = n.right - } - if(p === this) { - n.right = this.right - } else { - var l = this.left - var r = this.right - p.count -= n.count - p.right = n.left - n.left = l - n.right = r - } - copy(this, n) - this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length - } else if(this.left) { - copy(this, this.left) - } else { - copy(this, this.right) - } - return SUCCESS - } - for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l 0) { + var base = Math.round(Math.pow(10, y)) + return Math.ceil(x/base) * base } + return Math.ceil(x) } -function reportRightRange(arr, lo, cb) { - for(var i=arr.length-1; i>=0 && arr[i][1] >= lo; --i) { - var r = cb(arr[i]) - if(r) { return r } +function defaultBool(x) { + if(typeof x === 'boolean') { + return x } + return true } -function reportRange(arr, cb) { - for(var i=0; i this.mid) { - if(this.right) { - var r = this.right.queryPoint(x, cb) - if(r) { return r } + var stopped = false + + var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio) + + var canvas = options.canvas + if(!canvas) { + canvas = document.createElement('canvas') + if(options.container) { + var container = options.container + container.appendChild(canvas) + } else { + document.body.appendChild(canvas) } - return reportRightRange(this.rightPoints, x, cb) - } else { - return reportRange(this.leftPoints, cb) } -} -proto.queryInterval = function(lo, hi, cb) { - if(lo < this.mid && this.left) { - var r = this.left.queryInterval(lo, hi, cb) - if(r) { return r } - } - if(hi > this.mid && this.right) { - var r = this.right.queryInterval(lo, hi, cb) - if(r) { return r } + var gl = options.gl + if(!gl) { + gl = getContext(canvas, + options.glOptions || { + premultipliedAlpha: true, + antialias: true + }) } - if(hi < this.mid) { - return reportLeftRange(this.leftPoints, hi, cb) - } else if(lo > this.mid) { - return reportRightRange(this.rightPoints, lo, cb) - } else { - return reportRange(this.leftPoints, cb) + if(!gl) { + throw new Error('webgl not supported') } -} -function compareNumbers(a, b) { - return a - b -} + //Initial bounds + var bounds = options.bounds || [[-10,-10,-10], [10,10,10]] -function compareBegin(a, b) { - var d = a[0] - b[0] - if(d) { return d } - return a[1] - b[1] -} + //Create selection + var selection = new MouseSelect() -function compareEnd(a, b) { - var d = a[1] - b[1] - if(d) { return d } - return a[0] - b[0] -} + //Accumulation buffer + var accumBuffer = createFBO(gl, + [gl.drawingBufferWidth, gl.drawingBufferHeight], { + preferFloat: true + }) -function createIntervalTree(intervals) { - if(intervals.length === 0) { - return null - } - var pts = [] - for(var i=0; i>1] + //Create axes + var axesOptions = options.axes || {} + var axes = createAxes(gl, axesOptions) + axes.enable = !axesOptions.disable - var leftIntervals = [] - var rightIntervals = [] - var centerIntervals = [] - for(var i=0; i 0 && pickBufferCount[numPick-1] === 0) { + pickBufferCount.pop() + pickBuffers.pop().dispose() + } } -} -Object.defineProperty(tproto, "count", { - get: function() { - if(this.root) { - return this.root.count + scene.update = function(options) { + if(stopped) { + return } - return 0 + options = options || {} + dirty = true + pickDirty = true } -}) -Object.defineProperty(tproto, "intervals", { - get: function() { - if(this.root) { - return this.root.intervals([]) + scene.add = function(obj) { + if(stopped) { + return } - return [] + obj.axes = axes + objects.push(obj) + pickBufferIds.push(-1) + dirty = true + pickDirty = true + reallocPickIds() } -}) -function createWrapper(intervals) { - if(!intervals || intervals.length === 0) { - return new IntervalTree(null) + scene.remove = function(obj) { + if(stopped) { + return + } + var idx = objects.indexOf(obj) + if(idx < 0) { + return + } + objects.splice(idx, 1) + pickBufferIds.pop() + dirty = true + pickDirty = true + reallocPickIds() } - return new IntervalTree(createIntervalTree(intervals)) -} -},{"binary-search-bounds":415}],417:[function(require,module,exports){ -"use strict" + scene.dispose = function() { + if(stopped) { + return + } -module.exports = orderSegments + stopped = true -var orient = require("robust-orientation") + window.removeEventListener('resize', resizeListener) + canvas.removeEventListener('webglcontextlost', checkContextLoss) + scene.mouseListener.enabled = false -function horizontalOrder(a, b) { - var bl, br - if(b[0][0] < b[1][0]) { - bl = b[0] - br = b[1] - } else if(b[0][0] > b[1][0]) { - bl = b[1] - br = b[0] - } else { - var alo = Math.min(a[0][1], a[1][1]) - var ahi = Math.max(a[0][1], a[1][1]) - var blo = Math.min(b[0][1], b[1][1]) - var bhi = Math.max(b[0][1], b[1][1]) - if(ahi < blo) { - return ahi - blo + if(scene.contextLost) { + return } - if(alo > bhi) { - return alo - bhi + + //Destroy objects + axes.dispose() + spikes.dispose() + for(var i=0; i a[1][0]) { - al = a[1] - ar = a[0] - } else { - return horizontalOrder(a, b) - } - var bl, br - if(b[0][0] < b[1][0]) { - bl = b[0] - br = b[1] - } else if(b[0][0] > b[1][0]) { - bl = b[1] - br = b[0] - } else { - return -horizontalOrder(b, a) + //Clean up buffers + accumBuffer.dispose() + for(var i=0; i selection.distance) { + continue + } + for(var j=0; j 0) { - if(d2 >= 0) { - return d1 + + change = change || (selection.object !== prevObj) + if(change && scene.onselect) { + scene.onselect(selection) + } + + if((buttons & 1) && !(prevButtons & 1) && scene.onclick) { + scene.onclick(selection) + } + prevButtons = buttons + }) + + function checkContextLoss() { + if(scene.contextLost) { + return true + } + if(gl.isContextLost()) { + scene.contextLost = true + scene.mouseListener.enabled = false + scene.selection.object = null + if(scene.oncontextloss) { + scene.oncontextloss() + } } - } else if(d2) { - return d2 } - d1 = orient(br, bl, ar) - d2 = orient(br, bl, al) - if(d1 < 0) { - if(d2 <= 0) { - return d1 + + canvas.addEventListener('webglcontextlost', checkContextLoss) + + //Render the scene for mouse picking + function renderPick() { + if(checkContextLoss()) { + return } - } else if(d1 > 0) { - if(d2 >= 0) { - return d1 + + gl.colorMask(true, true, true, true) + gl.depthMask(true) + gl.disable(gl.BLEND) + gl.enable(gl.DEPTH_TEST) + + var numObjs = objects.length + var numPick = pickBuffers.length + for(var j=0; j=0; --s) { - var n = n_stack[s] - if(d_stack[s] <= 0) { - n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) - } else { - n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) + + //Recalculate bounds + pickDirty = pickDirty || boundsChanged + dirty = dirty || boundsChanged + + //Get scene + var width = gl.drawingBufferWidth + var height = gl.drawingBufferHeight + viewShape[0] = width + viewShape[1] = height + pickShape[0] = Math.max(width/scene.pixelRatio, 1)|0 + pickShape[1] = Math.max(height/scene.pixelRatio, 1)|0 + + //Compute camera parameters + perspective(projection, + scene.fovy, + width/height, + scene.zNear, + scene.zFar) + + //Compute model matrix + for(var i=0; i<16; ++i) { + model[i] = 0 } - } - //Rebalance tree using rotations - //console.log("start insert", key, d_stack) - for(var s=n_stack.length-1; s>1; --s) { - var p = n_stack[s-1] - var n = n_stack[s] - if(p._color === BLACK || n._color === BLACK) { - break + model[15] = 1 + + var maxS = 0 + for(var i=0; i<3; ++i) { + maxS = Math.max(maxS, bounds[1][i] - bounds[0][i]) } - var pp = n_stack[s-2] - if(pp.left === p) { - if(p.left === n) { - var y = pp.right - if(y && y._color === RED) { - //console.log("LLr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LLb") - pp._color = RED - pp.left = p.right - p._color = BLACK - p.right = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = p - } else { - ppp.right = p - } - } - break - } + + for(var i=0; i<3; ++i) { + if(scene.autoScale) { + model[5*i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i]) } else { - var y = pp.right - if(y && y._color === RED) { - //console.log("LRr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LRb") - p.right = n.left - pp._color = RED - pp.left = n.right - n._color = BLACK - n.left = p - n.right = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = n - } else { - ppp.right = n - } - } - break - } + model[5*i] = 1 / maxS } - } else { - if(p.right === n) { - var y = pp.left - if(y && y._color === RED) { - //console.log("RRr", y.key) - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RRb") - pp._color = RED - pp.right = p.left - p._color = BLACK - p.left = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = p - } else { - ppp.left = p - } - } - break - } + if(scene.autoCenter) { + model[12+i] = -model[5*i] * 0.5 * (bounds[0][i] + bounds[1][i]) + } + } + + //Apply axes/clip bounds + for(var i=0; i= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = n - } else { - ppp.left = n - } - } - break - } + spikes.position = selection.dataPosition } + spikes.bounds = bounds } - } - //Return new tree - n_stack[0]._color = BLACK - return new RedBlackTree(cmp, n_stack[0]) -} + //If state changed, then redraw pick buffers + if(pickDirty) { + pickDirty = false + renderPick() + } -//Visit all nodes inorder -function doVisitFull(visit, node) { - if(node.left) { - var v = doVisitFull(visit, node.left) - if(v) { return v } - } - var v = visit(node.key, node.value) - if(v) { return v } - if(node.right) { - return doVisitFull(visit, node.right) - } -} + if(!dirty) { + return + } -//Visit half nodes in order -function doVisitHalf(lo, compare, visit, node) { - var l = compare(lo, node.key) - if(l <= 0) { - if(node.left) { - var v = doVisitHalf(lo, compare, visit, node.left) - if(v) { return v } + //Recalculate pixel data + scene.axesPixels = axesRanges(scene.axes, cameraParams, width, height) + + //Call render callback + if(scene.onrender) { + scene.onrender() } - var v = visit(node.key, node.value) - if(v) { return v } - } - if(node.right) { - return doVisitHalf(lo, compare, visit, node.right) - } -} -//Visit all nodes within a range -function doVisit(lo, hi, compare, visit, node) { - var l = compare(lo, node.key) - var h = compare(hi, node.key) - var v - if(l <= 0) { - if(node.left) { - v = doVisit(lo, hi, compare, visit, node.left) - if(v) { return v } + //Read value + gl.bindFramebuffer(gl.FRAMEBUFFER, null) + gl.viewport(0, 0, width, height) + + //General strategy: 3 steps + // 1. render non-transparent objects + // 2. accumulate transparent objects into separate fbo + // 3. composite final scene + + //Clear FBO + var clearColor = scene.clearColor + gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]) + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) + gl.depthMask(true) + gl.colorMask(true, true, true, true) + gl.enable(gl.DEPTH_TEST) + gl.depthFunc(gl.LEQUAL) + gl.disable(gl.BLEND) + gl.disable(gl.CULL_FACE) //most visualization surfaces are 2 sided + + //Render opaque pass + var hasTransparent = false + if(axes.enable) { + hasTransparent = hasTransparent || axes.isTransparent() + axes.draw(cameraParams) } - if(h > 0) { - v = visit(node.key, node.value) - if(v) { return v } + spikes.axes = axes + if(selection.object) { + spikes.draw(cameraParams) + } + + gl.disable(gl.CULL_FACE) //most visualization surfaces are 2 sided + + for(var i=0; i 0 && node.right) { - return doVisit(lo, hi, compare, visit, node.right) - } -} + if(hasTransparent) { + //Render transparent pass + accumBuffer.shape = viewShape + accumBuffer.bind() + gl.clear(gl.DEPTH_BUFFER_BIT) + gl.colorMask(false, false, false, false) + gl.depthMask(true) + gl.depthFunc(gl.LESS) -proto.forEach = function rbTreeForEach(visit, lo, hi) { - if(!this.root) { - return - } - switch(arguments.length) { - case 1: - return doVisitFull(visit, this.root) - break + //Render forward facing objects + if(axes.enable && axes.isTransparent()) { + axes.drawTransparent(cameraParams) + } + for(var i=0; i= 0) { - return + if(axes.isTransparent()) { + axes.drawTransparent(cameraParams) } - return doVisit(lo, hi, this._compare, visit, this.root) - break - } -} -//First item in list -Object.defineProperty(proto, "begin", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.left - } - return new RedBlackTreeIterator(this, stack) - } -}) + for(var i=0; i= n.right._count) { - break - } - n = n.right - } else { - break - } - } - return new RedBlackTreeIterator(this, []) -} + //Draw composite pass + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) + gl.disable(gl.DEPTH_TEST) + accumShader.bind() + accumBuffer.color[0].bind(0) + accumShader.uniforms.accumBuffer = 0 + drawTriangle(gl) -proto.ge = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d <= 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right + //Turn off blending + gl.disable(gl.BLEND) } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} -proto.gt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d < 0) { - last_ptr = stack.length - } - if(d < 0) { - n = n.left - } else { - n = n.right + //Clear dirty flags + dirty = false + for(var i=0; i 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} -proto.le = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d >= 0) { - last_ptr = stack.length - } - if(d < 0) { - n = n.left - } else { - n = n.right + //Draw the whole scene + function render() { + if(stopped || scene.contextLost) { + return } + requestAnimationFrame(render) + redraw() } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} + render() -//Finds the item with key if it exists -proto.find = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d === 0) { - return new RedBlackTreeIterator(this, stack) - } - if(d <= 0) { - n = n.left - } else { - n = n.right + //Force redraw of whole scene + scene.redraw = function() { + if(stopped) { + return } + dirty = true + redraw() } - return new RedBlackTreeIterator(this, []) -} -//Removes item with key from tree -proto.remove = function(key) { - var iter = this.find(key) - if(iter) { - return iter.remove() - } - return this + return scene } -//Returns the item at `key` -proto.get = function(key) { - var cmp = this._compare - var n = this.root - while(n) { - var d = cmp(key, n.key) - if(d === 0) { - return n.value - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - return -} +},{"./lib/shader":166,"3d-view-controls":167,"a-big-triangle":169,"gl-axes3d":170,"gl-axes3d/properties":180,"gl-fbo":123,"gl-mat4/perspective":140,"gl-select-static":196,"gl-spikes3d":182,"mouse-change":241}],184:[function(require,module,exports){ +'use strict' -//Iterator for red black tree -function RedBlackTreeIterator(tree, stack) { - this.tree = tree - this._stack = stack + + +module.exports = { + vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", + fragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n", + pickVertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", + pickFragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n" } -var iproto = RedBlackTreeIterator.prototype +},{}],185:[function(require,module,exports){ +'use strict' -//Test if iterator is valid -Object.defineProperty(iproto, "valid", { - get: function() { - return this._stack.length > 0 - } -}) +module.exports = createFancyScatter2D -//Node of the iterator -Object.defineProperty(iproto, "node", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1] - } - return null - }, - enumerable: true -}) +var createShader = require('gl-shader') +var createBuffer = require('gl-buffer') +var textCache = require('text-cache') +var pool = require('typedarray-pool') +var vectorizeText = require('vectorize-text') +var shaders = require('./lib/shaders') -//Makes a copy of an iterator -iproto.clone = function() { - return new RedBlackTreeIterator(this.tree, this._stack.slice()) -} +var BOUNDARIES = {} -//Swaps two nodes -function swapNode(n, v) { - n.key = v.key - n.value = v.value - n.left = v.left - n.right = v.right - n._color = v._color - n._count = v._count -} +function getBoundary(glyph) { + if(glyph in BOUNDARIES) { + return BOUNDARIES[glyph] + } -//Fix up a double black node in a tree -function fixDoubleBlack(stack) { - var n, p, s, z - for(var i=stack.length-1; i>=0; --i) { - n = stack[i] - if(i === 0) { - n._color = BLACK - return - } - //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) - p = stack[i-1] - if(p.left === n) { - //console.log("left child") - s = p.right - if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.right = cloneNode(s) - z = s.right = cloneNode(s.right) - p.right = s.left - s.left = p - s.right = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - return - } else if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red") - s = p.right = cloneNode(s) - z = s.left = cloneNode(s.left) - p.right = z.left - s.left = z.right - z.left = p - z.right = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = z - } else { - pp.right = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent", p.right.value) - p._color = BLACK - p.right = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent", p.right.value) - p.right = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.right = s.left - s.left = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } else { - //console.log("right child") - s = p.left - if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red", p.value, p._color) - s = p.left = cloneNode(s) - z = s.left = cloneNode(s.left) - p.left = s.right - s.right = p - s.left = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - return - } else if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.left = cloneNode(s) - z = s.right = cloneNode(s.right) - p.left = z.right - s.right = z.left - z.right = p - z.left = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = z - } else { - pp.left = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent") - p._color = BLACK - p.left = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent") - p.left = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.left = s.right - s.right = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 + var polys = vectorizeText(glyph, { + polygons: true, + font: 'sans-serif', + textAlign: 'left', + textBaseline: 'alphabetic' + }) + + var coords = [] + var normals = [] + + polys.forEach(function(loops) { + loops.forEach(function(loop) { + for(var i=0; i=0; --i) { - var n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + + proto.draw = function() { + var plot = this.plot + var shader = this.shader + var numVertices = this.numVertices + + if(!numVertices) { + return } + + var gl = plot.gl + + calcScales.call(this) + + shader.bind() + + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.viewTransform = MATRIX + + this.positionBuffer.bind() + shader.attributes.position.pointer() + + this.offsetBuffer.bind() + shader.attributes.offset.pointer() + + this.colorBuffer.bind() + shader.attributes.color.pointer(gl.UNSIGNED_BYTE, true) + + gl.drawArrays(gl.TRIANGLES, 0, numVertices) } - //Get node - n = cstack[cstack.length-1] - //console.log("start remove: ", n.value) + var PICK_OFFSET = [0,0,0,0] - //If not leaf, then swap with previous node - if(n.left && n.right) { - //console.log("moving to leaf") + proto.drawPick = function(offset) { + var plot = this.plot + var shader = this.pickShader + var numVertices = this.numVertices - //First walk to previous leaf - var split = cstack.length - n = n.left - while(n.right) { - cstack.push(n) - n = n.right + var gl = plot.gl + + this.pickOffset = offset + + if(!numVertices) { + return offset } - //Copy path to leaf - var v = cstack[split-1] - cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) - cstack[split-1].key = n.key - cstack[split-1].value = n.value - //Fix up stack - for(var i=cstack.length-2; i>=split; --i) { - n = cstack[i] - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + for(var i=0; i<4; ++i) { + PICK_OFFSET[i] = ((offset>>(i*8)) & 0xff) } - cstack[split-1].left = cstack[split] + + calcScales.call(this) + + shader.bind() + + shader.uniforms.pixelScale = PIXEL_SCALE + shader.uniforms.viewTransform = MATRIX + shader.uniforms.pickOffset = PICK_OFFSET + + this.positionBuffer.bind() + shader.attributes.position.pointer() + + this.offsetBuffer.bind() + shader.attributes.offset.pointer() + + this.idBuffer.bind() + shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false) + + gl.drawArrays(gl.TRIANGLES, 0, numVertices) + + return offset + this.numPoints } - //console.log("stack=", cstack.map(function(v) { return v.value })) +})() - //Remove leaf node - n = cstack[cstack.length-1] - if(n._color === RED) { - //Easy case: removing red leaf - //console.log("RED leaf") - var p = cstack[cstack.length-2] - if(p.left === n) { - p.left = null - } else if(p.right === n) { - p.right = null - } - cstack.pop() - for(var i=0; i= pickOffset + pointCount) { + return null + } + var pointId = value - pickOffset + var points = this.points + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] } - return new RedBlackTree(this.tree._compare, cstack[0]) } -//Returns key -Object.defineProperty(iproto, "key", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].key - } - return - }, - enumerable: true -}) +proto.update = function(options) { + options = options || {} -//Returns value -Object.defineProperty(iproto, "value", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].value - } - return - }, - enumerable: true -}) + var positions = options.positions || [] + var colors = options.colors || [] + var glyphs = options.glyphs || [] + var sizes = options.sizes || [] + var borderWidths = options.borderWidths || [] + var borderColors = options.borderColors || [] + this.points = positions -//Returns the position of this iterator in the sorted list -Object.defineProperty(iproto, "index", { - get: function() { - var idx = 0 - var stack = this._stack - if(stack.length === 0) { - var r = this.tree.root - if(r) { - return r._count - } - return 0 - } else if(stack[stack.length-1].left) { - idx = stack[stack.length-1].left._count - } - for(var s=stack.length-2; s>=0; --s) { - if(stack[s+1] === stack[s].right) { - ++idx - if(stack[s].left) { - idx += stack[s].left._count - } - } + var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] + var numVertices = 0 + for(var i=0; i> 1 + for(var j=0; j<2; ++j) { + bounds[j] = Math.min(bounds[j], positions[2*i+j]) + bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j]) } - return idx - }, - enumerable: true -}) + } -//Advances iterator to next element in list -iproto.next = function() { - var stack = this._stack - if(stack.length === 0) { - return + if(bounds[0] === bounds[2]) { + bounds[2] += 1 } - var n = stack[stack.length-1] - if(n.right) { - n = n.right - while(n) { - stack.push(n) - n = n.left - } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].right === n) { - n = stack[stack.length-1] - stack.pop() - } + if(bounds[3] === bounds[1]) { + bounds[3] += 1 } -} -//Checks if iterator is at end of tree -Object.defineProperty(iproto, "hasNext", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].right) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].left === stack[s]) { - return true - } + var sx = 1/(bounds[2] - bounds[0]) + var sy = 1/(bounds[3] - bounds[1]) + var tx = bounds[0] + var ty = bounds[1] + + var v_position = pool.mallocFloat32(2 * numVertices) + var v_offset = pool.mallocFloat32(2 * numVertices) + var v_color = pool.mallocUint8(4 * numVertices) + var v_ids = pool.mallocUint32(numVertices) + var ptr = 0 + + for(var i=0; i=0; --i) { - n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + var w = borderWidths[i] + r = borderColors[4*i] * 255.0 + g = borderColors[4*i+1] * 255.0 + b = borderColors[4*i+2] * 255.0 + a = borderColors[4*i+3] * 255.0 + + for(var j=0; j 0 && stack[stack.length-1].left === n) { - n = stack[stack.length-1] - stack.pop() - } + quickSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) } } -//Checks if iterator is at start of tree -Object.defineProperty(iproto, "hasPrev", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].left) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].right === stack[s]) { - return true +function insertionSort(left, right, data_levels, data_points, data_ids, data_weights) { + for(var i=left+1; i<=right; ++i) { + var a_level = data_levels[i] + var a_x = data_points[2*i] + var a_y = data_points[2*i+1] + var a_id = data_ids[i] + var a_weight = data_weights[i] + + var j = i + while(j > left) { + var b_level = data_levels[j-1] + var b_x = data_points[2*(j-1)] + if(((b_level - a_level) || (a_x - b_x)) >= 0) { + break } + data_levels[j] = b_level + data_points[2*j] = b_x + data_points[2*j+1] = data_points[2*j-1] + data_ids[j] = data_ids[j-1] + data_weights[j] = data_weights[j-1] + j -= 1 } - return false - } -}) -//Default comparison function -function defaultCompare(a, b) { - if(a < b) { - return -1 - } - if(a > b) { - return 1 + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } - return 0 } -//Build a tree -function createRBTree(compare) { - return new RedBlackTree(compare || defaultCompare, null) +function swap(i, j, data_levels, data_points, data_ids, data_weights) { + var a_level = data_levels[i] + var a_x = data_points[2*i] + var a_y = data_points[2*i+1] + var a_id = data_ids[i] + var a_weight = data_weights[i] + + data_levels[i] = data_levels[j] + data_points[2*i] = data_points[2*j] + data_points[2*i+1] = data_points[2*j+1] + data_ids[i] = data_ids[j] + data_weights[i] = data_weights[j] + + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } -},{}],419:[function(require,module,exports){ -"use strict" -module.exports = createSlabDecomposition +function move(i, j, data_levels, data_points, data_ids, data_weights) { + data_levels[i] = data_levels[j] + data_points[2*i] = data_points[2*j] + data_points[2*i+1] = data_points[2*j+1] + data_ids[i] = data_ids[j] + data_weights[i] = data_weights[j] +} -var bounds = require("binary-search-bounds") -var createRBTree = require("functional-red-black-tree") -var orient = require("robust-orientation") -var orderSegments = require("./lib/order-segments") +function rotate(i, j, k, data_levels, data_points, data_ids, data_weights) { + var a_level = data_levels[i] + var a_x = data_points[2*i] + var a_y = data_points[2*i+1] + var a_id = data_ids[i] + var a_weight = data_weights[i] -function SlabDecomposition(slabs, coordinates, horizontal) { - this.slabs = slabs - this.coordinates = coordinates - this.horizontal = horizontal + data_levels[i] = data_levels[j] + data_points[2*i] = data_points[2*j] + data_points[2*i+1] = data_points[2*j+1] + data_ids[i] = data_ids[j] + data_weights[i] = data_weights[j] + + data_levels[j] = data_levels[k] + data_points[2*j] = data_points[2*k] + data_points[2*j+1] = data_points[2*k+1] + data_ids[j] = data_ids[k] + data_weights[j] = data_weights[k] + + data_levels[k] = a_level + data_points[2*k] = a_x + data_points[2*k+1] = a_y + data_ids[k] = a_id + data_weights[k] = a_weight } -var proto = SlabDecomposition.prototype +function shufflePivot( + i, j, + a_level, a_x, a_y, a_id, a_weight, + data_levels, data_points, data_ids, data_weights) { -function compareHorizontal(e, y) { - return e.y - y + data_levels[i] = data_levels[j] + data_points[2*i] = data_points[2*j] + data_points[2*i+1] = data_points[2*j+1] + data_ids[i] = data_ids[j] + data_weights[i] = data_weights[j] + + data_levels[j] = a_level + data_points[2*j] = a_x + data_points[2*j+1] = a_y + data_ids[j] = a_id + data_weights[j] = a_weight } -function searchBucket(root, p) { - var lastNode = null - while(root) { - var seg = root.key - var l, r - if(seg[0][0] < seg[1][0]) { - l = seg[0] - r = seg[1] - } else { - l = seg[1] - r = seg[0] - } - var o = orient(l, r, p) - if(o < 0) { - root = root.left - } else if(o > 0) { - if(p[0] !== seg[1][0]) { - lastNode = root - root = root.right - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } - } else { - if(p[0] !== seg[1][0]) { - return root - } else { - var val = searchBucket(root.right, p) - if(val) { - return val - } - root = root.left - } - } - } - return lastNode +function compare(i, j, data_levels, data_points, data_ids) { + return ((data_levels[i] - data_levels[j]) || + (data_points[2*j] - data_points[2*i]) || + (data_ids[i] - data_ids[j])) < 0 } -proto.castUp = function(p) { - var bucket = bounds.le(this.coordinates, p[0]) - if(bucket < 0) { - return -1 +function comparePivot(i, level, x, y, id, data_levels, data_points, data_ids) { + return ((level - data_levels[i]) || + (data_points[2*i] - x) || + (id - data_ids[i])) < 0 +} + +function quickSort(left, right, data_levels, data_points, data_ids, data_weights) { + var sixth = (right - left + 1) / 6 | 0, + index1 = left + sixth, + index5 = right - sixth, + index3 = left + right >> 1, + index2 = index3 - sixth, + index4 = index3 + sixth, + el1 = index1, + el2 = index2, + el3 = index3, + el4 = index4, + el5 = index5, + less = left + 1, + great = right - 1, + tmp = 0 + if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el2 + el2 = tmp } - var root = this.slabs[bucket] - var hitNode = searchBucket(this.slabs[bucket], p) - var lastHit = -1 - if(hitNode) { - lastHit = hitNode.value + if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el4 + el4 = el5 + el5 = tmp } - //Edge case: need to handle horizontal segments (sucks) - if(this.coordinates[bucket] === p[0]) { - var lastSegment = null - if(hitNode) { - lastSegment = hitNode.key - } - if(bucket > 0) { - var otherHitNode = searchBucket(this.slabs[bucket-1], p) - if(otherHitNode) { - if(lastSegment) { - if(orderSegments(otherHitNode.key, lastSegment) > 0) { - lastSegment = otherHitNode.key - lastHit = otherHitNode.value - } - } else { - lastHit = otherHitNode.value - lastSegment = otherHitNode.key - } - } - } - var horiz = this.horizontal[bucket] - if(horiz.length > 0) { - var hbucket = bounds.ge(horiz, p[1], compareHorizontal) - if(hbucket < horiz.length) { - var e = horiz[hbucket] - if(p[1] === e.y) { - if(e.closed) { - return e.index - } else { - while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { - hbucket = hbucket+1 - e = horiz[hbucket] - if(e.closed) { - return e.index - } - } - if(e.y === p[1] && !e.start) { - hbucket = hbucket+1 - if(hbucket >= horiz.length) { - return lastHit - } - e = horiz[hbucket] - } - } - } - //Check if e is above/below last segment - if(e.start) { - if(lastSegment) { - var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) - if(lastSegment[0][0] > lastSegment[1][0]) { - o = -o - } - if(o > 0) { - lastHit = e.index - } - } else { - lastHit = e.index - } - } else if(e.y !== p[1]) { - lastHit = e.index - } - } - } + if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el3 + el3 = tmp + } + if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) { + tmp = el1 + el1 = el4 + el4 = tmp + } + if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) { + tmp = el3 + el3 = el4 + el4 = tmp + } + if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el5 + el5 = tmp + } + if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { + tmp = el2 + el2 = el3 + el3 = tmp + } + if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { + tmp = el4 + el4 = el5 + el5 = tmp } - return lastHit -} -function IntervalSegment(y, index, start, closed) { - this.y = y - this.index = index - this.start = start - this.closed = closed -} + var pivot1_level = data_levels[el2] + var pivot1_x = data_points[2*el2] + var pivot1_y = data_points[2*el2+1] + var pivot1_id = data_ids[el2] + var pivot1_weight = data_weights[el2] -function Event(x, segment, create, index) { - this.x = x - this.segment = segment - this.create = create - this.index = index -} + var pivot2_level = data_levels[el4] + var pivot2_x = data_points[2*el4] + var pivot2_y = data_points[2*el4+1] + var pivot2_id = data_ids[el4] + var pivot2_weight = data_weights[el4] + var ptr0 = el1 + var ptr2 = el3 + var ptr4 = el5 + var ptr5 = index1 + var ptr6 = index3 + var ptr7 = index5 -function createSlabDecomposition(segments) { - var numSegments = segments.length - var numEvents = 2 * numSegments - var events = new Array(numEvents) - for(var i=0; i 0 && coordinates[bucket] === p[0]) { - root = slabs[bucket-1] - } else { - return 1 - } - } - var lastOrientation = 1 - while(root) { - var s = root.key - var o = orient(p, s[0], s[1]) - if(s[0][0] < s[1][0]) { - if(o < 0) { - root = root.left - } else if(o > 0) { - lastOrientation = -1 - root = root.right - } else { - return 0 - } +function partition(points, ids, start, end, lox, loy, hix, hiy) { + var mid = start + for(var i=start; i 0) { - root = root.left - } else if(o < 0) { - lastOrientation = 1 - root = root.right - } else { - return 0 - } + points[2*i] = points[2*mid] + points[2*i+1] = points[2*mid+1] + ids[i] = ids[mid] + points[2*mid] = x + points[2*mid+1] = y + ids[mid] = s + mid += 1 } } - return lastOrientation } + return mid } -function classifyEmpty(p) { - return 1 +function SnapInterval(pixelSize, offset, count) { + this.pixelSize = pixelSize + this.offset = offset + this.count = count } -function createClassifyVertical(testVertical) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 - } - return 1 +function snapPoints(points, ids, weights, bounds) { + var n = points.length >>> 1 + if(n < 1) { + return [] } -} -function createClassifyPointDegen(testVertical, testNormal) { - return function classify(p) { - if(testVertical(p[0], p[1])) { - return 0 - } - return testNormal(p) + var lox = Infinity, loy = Infinity + var hix = -Infinity, hiy = -Infinity + for(var i=0; i= Math.max(0.9 * count, 32)) { + var mid = (end + start)>>>1 + snapRec(nx, ny, diam_2, offset, mid, level+1) + offset = mid + } + snapRec(nx, ny, diam_2, offset, nextOffset, level+1) + offset = nextOffset } } } + snapRec(lox, loy, diam, 0, n, 0) + sortLevels(levels, points, ids, weights, n) - //Degenerate case: All loops are empty - if(segments.length === 0) { - if(vsegments.length === 0) { - return classifyEmpty - } else { - return createClassifyVertical(buildVerticalIndex(vsegments)) + var lod = [] + var lastLevel = 0 + var prevOffset = n + for(var ptr=n-1; ptr>=0; --ptr) { + points[2*ptr] = (points[2*ptr] - lox) * scaleX + points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY + + var level = levels[ptr] + if(level === lastLevel) { + continue } - } - //Build slab decomposition - var slabs = makeSlabs(segments) - var testSlab = buildSlabSearch(slabs.slabs, slabs.coordinates) + lod.push(new SnapInterval( + diam * Math.pow(0.5, level), + ptr+1, + prevOffset - (ptr+1) + )) + prevOffset = ptr+1 - if(vsegments.length === 0) { - return testSlab - } else { - return createClassifyPointDegen( - buildVerticalIndex(vsegments), - testSlab) + lastLevel = level } -} -},{"binary-search-bounds":415,"interval-tree-1d":416,"robust-orientation":1040,"slab-decomposition":419}],421:[function(require,module,exports){ -arguments[4][55][0].apply(exports,arguments) -},{"dup":55}],422:[function(require,module,exports){ -arguments[4][56][0].apply(exports,arguments) -},{"dup":56}],423:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],424:[function(require,module,exports){ -'use strict' - -module.exports = planarGraphToPolyline -var e2a = require('edges-to-adjacency-list') -var planarDual = require('planar-dual') -var preprocessPolygon = require('point-in-big-polygon') -var twoProduct = require('two-product') -var robustSum = require('robust-sum') -var uniq = require('uniq') -var trimLeaves = require('./lib/trim-leaves') + lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset)) + pool.free(levels) -function makeArray(length, fill) { - var result = new Array(length) - for(var i=0; i 0 +proto.dispose = function() { + this.shader.dispose() + this.pickShader.dispose() + this.offsetBuffer.dispose() + this.pickBuffer.dispose() + if(this.xCoords) { + pool.free(this.xCoords) } + this.plot.removeObject(this) +} - //Extract all clockwise faces - faces = faces.filter(ccw) +proto.update = function(options) { + options = options || {} - //Detect which loops are contained in one another to handle parent-of relation - var numFaces = faces.length - var parent = new Array(numFaces) - var containment = new Array(numFaces) - for(var i=0; i>>1) + packed.set(data) + var packedW = pool.mallocFloat32(data.length) + this.points = data + this.scales = snapPoints(packed, packedId, packedW, this.bounds) + this.offsetBuffer.update(packed) + this.pickBuffer.update(packedId) + this.weightBuffer.update(packedW) + var xCoords = pool.mallocFloat32(data.length>>>1) + for(var i=0,j=0; i 0) { - var top = toVisit.pop() - var nbhd = fadj[top] - uniq(nbhd, function(a,b) { - return a-b - }) - var nnbhr = nbhd.length - var p = parity[top] - var polyline - if(p === 0) { - var c = faces[top] - polyline = [c] - } - for(var i=0; i= 0) { - continue - } - parity[f] = p^1 - toVisit.push(f) - if(p === 0) { - var c = faces[f] - if(!sharedBoundary(c)) { - c.reverse() - polyline.push(c) - } - } - } - if(p === 0) { - result.push(polyline) - } + this.pointCount = data.length >>> 1 + this.pickOffset = 0 +} + +proto.drawPick = (function() { + var MATRIX = [1,0,0, + 0,1,0, + 0,0,1] + var PICK_VEC4 = [0,0,0,0] +return function(pickOffset) { + var plot = this.plot + var shader = this.pickShader + var scales = this.scales + var offsetBuffer = this.offsetBuffer + var pickBuffer = this.pickBuffer + var bounds = this.bounds + var size = this.size + var borderSize = this.borderSize + var gl = plot.gl + var pixelRatio = plot.pickPixelRatio + var viewBox = plot.viewBox + var dataBox = plot.dataBox + + if(this.pointCount === 0) { + return pickOffset } - return result -} -},{"./lib/trim-leaves":407,"edges-to-adjacency-list":408,"planar-dual":409,"point-in-big-polygon":420,"robust-sum":421,"two-product":422,"uniq":423}],425:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],426:[function(require,module,exports){ -"use strict"; "use restrict"; + var boundX = bounds[2] - bounds[0] + var boundY = bounds[3] - bounds[1] + var dataX = dataBox[2] - dataBox[0] + var dataY = dataBox[3] - dataBox[1] + var screenX = (viewBox[2] - viewBox[0]) * pixelRatio / plot.pixelRatio + var screenY = (viewBox[3] - viewBox[1]) * pixelRatio / plot.pixelRatio -module.exports = UnionFind; + var pixelSize = Math.min(dataX / screenX, dataY / screenY) + var targetScale = pixelSize -function UnionFind(count) { - this.roots = new Array(count); - this.ranks = new Array(count); - - for(var i=0; i>8) & 0xff) + PICK_VEC4[2] = ((pickOffset>>16) & 0xff) + PICK_VEC4[3] = ((pickOffset>>24) & 0xff) -UnionFind.prototype.find = function(x) { - var roots = this.roots; - while(roots[x] !== x) { - var y = roots[x]; - roots[x] = roots[y]; - x = y; - } - return x; -} + shader.bind() + shader.uniforms.matrix = MATRIX + shader.uniforms.color = this.color + shader.uniforms.borderColor = this.borderColor + shader.uniforms.pointSize = pixelRatio * (size + borderSize) + shader.uniforms.pickOffset = PICK_VEC4 -UnionFind.prototype.link = function(x, y) { - var xr = this.find(x) - , yr = this.find(y); - if(xr === yr) { - return; - } - var ranks = this.ranks - , roots = this.roots - , xd = ranks[xr] - , yd = ranks[yr]; - if(xd < yd) { - roots[xr] = yr; - } else if(yd < xd) { - roots[yr] = xr; + if(this.borderSize === 0) { + shader.uniforms.centerFraction = 2.0; } else { - roots[yr] = xr; - ++ranks[xr]; + shader.uniforms.centerFraction = size / (size + borderSize + 1.25) } -} + offsetBuffer.bind() + shader.attributes.position.pointer() + pickBuffer.bind() + shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE) -},{}],427:[function(require,module,exports){ -arguments[4][79][0].apply(exports,arguments) -},{"bit-twiddle":425,"dup":79,"union-find":426}],428:[function(require,module,exports){ -"use strict" + var xCoords = this.xCoords + var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX + var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX -module.exports = simplifyPolygon + for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { + var lod = scales[scaleNum] + if(lod.pixelSize < pixelSize && scaleNum > 1) { + continue + } -var orient = require("robust-orientation") -var sc = require("simplicial-complex") + var intervalStart = lod.offset + var intervalEnd = lod.count + intervalStart -function errorWeight(base, a, b) { - var area = Math.abs(orient(base, a, b)) - var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2)) - return area / perim + var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) + var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + + if(endOffset > startOffset) { + gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + } + } + + return pickOffset + this.pointCount } +})() -function simplifyPolygon(cells, positions, minArea) { +proto.draw = (function() { + var MATRIX = [1, 0, 0, + 0, 1, 0, + 0, 0, 1] - var n = positions.length - var nc = cells.length - var inv = new Array(n) - var outv = new Array(n) - var weights = new Array(n) - var dead = new Array(n) - - //Initialize tables - for(var i=0; i> 1 - } - return (i >> 1) - 1 - } + var xCoords = this.xCoords + var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX + var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX - //Bubble element i down the heap - function heapDown(i) { - var w = heapWeight(i) - while(true) { - var tw = w - var left = 2*i + 1 - var right = 2*(i + 1) - var next = i - if(left < heapCount) { - var lw = heapWeight(left) - if(lw < tw) { - next = left - tw = lw - } - } - if(right < heapCount) { - var rw = heapWeight(right) - if(rw < tw) { - next = right - } + var firstLevel = true + + for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { + var lod = scales[scaleNum] + if(lod.pixelSize < pixelSize && scaleNum > 1) { + continue } - if(next === i) { - return i + + var intervalStart = lod.offset + var intervalEnd = lod.count + intervalStart + + var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) + var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + + if(endOffset > startOffset) { + gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) } - heapSwap(i, next) - i = next - } - } - //Bubbles element i up the heap - function heapUp(i) { - var w = heapWeight(i) - while(i > 0) { - var parent = heapParent(i) - if(parent >= 0) { - var pw = heapWeight(parent) - if(w < pw) { - heapSwap(i, parent) - i = parent - continue - } + if(firstLevel) { + firstLevel = false + shader.uniforms.useWeight = 0 } - return i } } +})() - //Pop minimum element - function heapPop() { - if(heapCount > 0) { - var head = heap[0] - heapSwap(0, heapCount-1) - heapCount -= 1 - heapDown(0) - return head - } - return -1 +proto.pick = function(x, y, value) { + var pickOffset = this.pickOffset + var pointCount = this.pointCount + if(value < pickOffset || value >= pickOffset + pointCount) { + return null } - - //Update heap item i - function heapUpdate(i, w) { - var a = heap[i] - if(weights[a] === w) { - return i - } - weights[a] = -Infinity - heapUp(i) - heapPop() - weights[a] = w - heapCount += 1 - return heapUp(heapCount-1) + var pointId = value - pickOffset + var points = this.points + return { + object: this, + pointId: pointId, + dataCoord: [ points[2*pointId], points[2*pointId+1] ] } +} - //Kills a vertex (assume vertex already removed from heap) - function kill(i) { - if(dead[i]) { - return - } - //Kill vertex - dead[i] = true - //Fixup topology - var s = inv[i] - var t = outv[i] - if(inv[t] >= 0) { - inv[t] = s - } - if(outv[s] >= 0) { - outv[s] = t - } +function createScatter2D(plot, options) { + var gl = plot.gl + var buffer = createBuffer(gl) + var pickBuffer = createBuffer(gl) + var weightBuffer = createBuffer(gl) + var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment) + var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) - //Update weights on s and t - if(index[s] >= 0) { - heapUpdate(index[s], computeWeight(s)) - } - if(index[t] >= 0) { - heapUpdate(index[t], computeWeight(t)) - } - } + var result = new Scatter2D( + plot, buffer, pickBuffer, weightBuffer, shader, pickShader) + result.update(options) - //Initialize weights and heap - var heap = [] - var index = new Array(n) - for(var i=0; i>1; i>=0; --i) { - heapDown(i) - } - - //Kill vertices - while(true) { - var hmin = heapPop() - if((hmin < 0) || (weights[hmin] > minArea)) { - break - } - kill(hmin) - } + //Register with plot + plot.addObject(result) - //Build collapsed vertex table - var npositions = [] - for(var i=0; i= 0 && tout >= 0 && tin !== tout) { - var cin = index[tin] - var cout = index[tout] - if(cin !== cout) { - ncells.push([ cin, cout ]) - } - } - }) +module.exports = getGlyph - //Normalize result - sc.unique(sc.normalize(ncells)) +var GLYPH_CACHE = {} - //Return final list of cells - return { - positions: npositions, - edges: ncells +function getGlyph(symbol, font) { + var fontCache = GLYPH_CACHE[font] + if(!fontCache) { + fontCache = GLYPH_CACHE[font] = {} + } + if(symbol in fontCache) { + return fontCache[symbol] } -} -},{"robust-orientation":1040,"simplicial-complex":427}],429:[function(require,module,exports){ -"use strict" -var pool = require("typedarray-pool") + //Get line and triangle meshes for glyph + var lineSymbol = vectorizeText(symbol, { + textAlign: "center", + textBaseline: "middle", + lineHeight: 1.0, + font: font + }) + var triSymbol = vectorizeText(symbol, { + triangles: true, + textAlign: "center", + textBaseline: "middle", + lineHeight: 1.0, + font: font + }) -module.exports = createSurfaceExtractor + //Calculate bounding box + var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]] + for(var i=0; i 0) { - stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) - } - vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + for(var i=0; i<3; ++i) { + if(this.axesProject[i] && this.projectOpacity[i] < 1) { + return true } } - //Create index variables - for(var i=0; i=0; --i) { - sizeVariable.push(shape(order[i])) + return false +} + +proto.isOpaque = function() { + if(this.opacity >= 1) { + return true } - //Previous phases and vertex_ids - vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", - PHASES + "=mallocUint32(" + POOL_SIZE + ")", - VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", - POINTER + "=0") - //Create cube variables for phases - vars.push(pcube(0) + "=0") - for(var j=1; j<(1<= 1) { + return true } - var jperm = permBitmask(dimension, j, order) - vars.push(pdelta(jperm) + "=(-" + cubeDelta.join("-") + ")|0", - qcube(jperm) + "=(" + signFlag + cubeDelta.join("-") + ")|0", - pcube(jperm) + "=0") } - vars.push(vert(0) + "=0", TEMPORARY + "=0") + return false +} - function forLoopBegin(i, start) { - code.push("for(", index(order[i]), "=", start, ";", - index(order[i]), "<", shape(order[i]), ";", - "++", index(order[i]), "){") - } +var VIEW_SHAPE = [0,0] +var U_VEC = [0,0,0] +var V_VEC = [0,0,0] +var MU_VEC = [0,0,0,1] +var MV_VEC = [0,0,0,1] +var SCRATCH_MATRIX = IDENTITY.slice() +var SCRATCH_VEC = [0,0,0] +var CLIP_BOUNDS = [[0,0,0], [0,0,0]] - function forLoopEnd(i) { - for(var j=0; j=0; --i) { - forLoopBegin(i, 0) - } - var phaseFuncArgs = [] - for(var i=0; i0; k=(k-1)&subset) { - faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") - } - faceArgs.push(vert(0)) - for(var k=0; k Math.abs(mdv[1])) { + var tmp = mdu + mdu = mdv + mdv = tmp + tmp = du + du = dv + dv = tmp + var t = u + u = v + v = t } - fillEmptySlice(i) - code.push("if(", shape(order[i]), ">0){", - index(order[i]), "=1;") - createLoop(i-1, mask|(1< 0) { + dv[v] = -1 } - forLoopBegin(i, 2) - createLoop(i-1, mask) - if(i === dimension-1) { - code.push("if(", index(order[dimension-1]), "&1){", - POINTER, "=0;}") - flip() + var su = 0.0 + var sv = 0.0 + for(var j=0; j<4; ++j) { + su += Math.pow(model[4*u+j], 2) + sv += Math.pow(model[4*v+j], 2) } - forLoopEnd(i) - code.push("}") - } - - createLoop(dimension-1, 0) - - //Release scratch memory - code.push("freeUint32(", VERTEX_IDS, ");freeUint32(", PHASES, ");") + du[u] /= Math.sqrt(su) + dv[v] /= Math.sqrt(sv) + uniforms.axes[0] = du + uniforms.axes[1] = dv - //Compile and link procedure - var procedureCode = [ - "'use strict';", - "function ", funcName, "(", args.join(), "){", - "var ", vars.join(), ";", - code.join(""), - "}", - "return ", funcName ].join("") + //Update fragment clip bounds + uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8) + uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8) - var proc = new Function( - "vertex", - "face", - "phase", - "mallocUint32", - "freeUint32", - procedureCode) - return proc( - vertexFunc, - faceFunc, - phaseFunc, - pool.mallocUint32, - pool.freeUint32) -} + //Draw interior + points.vao.draw(gl.TRIANGLES, points.vertexCount) -function createSurfaceExtractor(args) { - function error(msg) { - throw new Error("ndarray-extract-contour: " + msg) - } - if(typeof args !== "object") { - error("Must specify arguments") - } - var order = args.order - if(!Array.isArray(order)) { - error("Must specify order") - } - var arrays = args.arrayArguments||1 - if(arrays < 1) { - error("Must have at least one array argument") - } - var scalars = args.scalarArguments||0 - if(scalars < 0) { - error("Scalar arg count must be > 0") - } - if(typeof args.vertex !== "function") { - error("Must specify vertex creation function") - } - if(typeof args.cell !== "function") { - error("Must specify cell creation function") - } - if(typeof args.phase !== "function") { - error("Must specify phase function") - } - var getters = args.getters || [] - var typesig = new Array(arrays) - for(var i=0; i= 0) { - typesig[i] = true - } else { - typesig[i] = false + //Draw edges + if(points.lineWidth > 0) { + gl.lineWidth(points.lineWidth) + points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) } } - return compileSurfaceProcedure( - args.vertex, - args.cell, - args.phase, - scalars, - order, - typesig) } -},{"typedarray-pool":432}],430:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],431:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],432:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":430,"buffer":65,"dup":122}],433:[function(require,module,exports){ -// transliterated from the python snippet here: -// http://en.wikipedia.org/wiki/Lanczos_approximation -var g = 7; -var p = [ - 0.99999999999980993, - 676.5203681218851, - -1259.1392167224028, - 771.32342877765313, - -176.61502916214059, - 12.507343278686905, - -0.13857109526572012, - 9.9843695780195716e-6, - 1.5056327351493116e-7 -]; -var g_ln = 607/128; -var p_ln = [ - 0.99999999999999709182, - 57.156235665862923517, - -59.597960355475491248, - 14.136097974741747174, - -0.49191381609762019978, - 0.33994649984811888699e-4, - 0.46523628927048575665e-4, - -0.98374475304879564677e-4, - 0.15808870322491248884e-3, - -0.21026444172410488319e-3, - 0.21743961811521264320e-3, - -0.16431810653676389022e-3, - 0.84418223983852743293e-4, - -0.26190838401581408670e-4, - 0.36899182659531622704e-5 -]; +var NEG_INFINITY3 = [-1e8, -1e8, -1e8] +var POS_INFINITY3 = [1e8, 1e8, 1e8] +var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] -// Spouge approximation (suitable for large arguments) -function lngamma(z) { +function drawFull(shader, pshader, points, camera, transparent, forceDraw) { + var gl = points.gl - if(z < 0) return Number('0/0'); - var x = p_ln[0]; - for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); - var t = z + g_ln + 0.5; - return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); -} + points.vao.bind() -module.exports = function gamma (z) { - if (z < 0.5) { - return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); - } - else if(z > 100) return Math.exp(lngamma(z)); - else { - z -= 1; - var x = p[0]; - for (var i = 1; i < g + 2; i++) { - x += p[i] / (z + i); - } - var t = z + g + 0.5; + if(transparent === (points.opacity < 1) || forceDraw) { + shader.bind() + var uniforms = shader.uniforms - return Math.sqrt(2 * Math.PI) - * Math.pow(t, z + 0.5) - * Math.exp(-t) - * x - ; - } -}; + uniforms.model = camera.model || IDENTITY + uniforms.view = camera.view || IDENTITY + uniforms.projection = camera.projection || IDENTITY -module.exports.log = lngamma; + VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth + VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight + uniforms.screenSize = VIEW_SHAPE -},{}],434:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],435:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],436:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":434,"buffer":65,"dup":122}],437:[function(require,module,exports){ -"use strict" + uniforms.highlightId = points.highlightId + uniforms.highlightScale = points.highlightScale -module.exports = permutationSign + uniforms.fragClipBounds = CLIP_GROUP + uniforms.clipBounds = points.axes.bounds -var BRUTE_FORCE_CUTOFF = 32 + uniforms.opacity = points.opacity + uniforms.pickGroup = points.pickId / 255.0 -var pool = require("typedarray-pool") + uniforms.pixelRatio = points.pixelRatio -function permutationSign(p) { - var n = p.length - if(n < BRUTE_FORCE_CUTOFF) { - //Use quadratic algorithm for small n - var sgn = 1 - for(var i=0; i 0) { + gl.lineWidth(points.lineWidth) + points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) } - pool.freeUint8(visited) - return sgn } + + drawProject(pshader, points, camera, transparent, forceDraw) + + points.vao.unbind() } -},{"typedarray-pool":436}],438:[function(require,module,exports){ -"use strict" -var pool = require("typedarray-pool") -var inverse = require("invert-permutation") +proto.draw = function(camera) { + var shader = this.useOrtho ? this.orthoShader : this.shader + drawFull(shader, this.projectShader, this, camera, false, false) +} -function rank(permutation) { - var n = permutation.length - switch(n) { - case 0: - case 1: - return 0 - case 2: - return permutation[1] - default: - break - } - var p = pool.mallocUint32(n) - var pinv = pool.mallocUint32(n) - var r = 0, s, t, i - inverse(permutation, pinv) - for(i=0; i0; --i) { - t = pinv[i] - s = p[i] - p[i] = p[t] - p[t] = s - pinv[i] = pinv[s] - pinv[s] = t - r = (r + s) * i - } - pool.freeUint32(pinv) - pool.freeUint32(p) - return r +proto.drawTransparent = function(camera) { + var shader = this.useOrtho ? this.orthoShader : this.shader + drawFull(shader, this.projectShader, this, camera, true, false) } -function unrank(n, r, p) { - switch(n) { - case 0: - if(p) { return p } - return [] - case 1: - if(p) { - p[0] = 0 - return p - } else { - return [0] - } - case 2: - if(p) { - if(r) { - p[0] = 0 - p[1] = 1 - } else { - p[0] = 1 - p[1] = 0 - } - return p - } else { - return r ? [0,1] : [1,0] - } - default: - break +proto.drawPick = function(camera) { + var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader + drawFull(shader, this.pickProjectShader, this, camera, false, true) +} + +proto.pick = function(selected) { + if(!selected) { + return null } - p = p || new Array(n) - var s, t, i, nf=1 - p[0] = 0 - for(i=1; i0; --i) { - s = (r / nf)|0 - r = (r - s * nf)|0 - nf = (nf / i)|0 - t = p[i]|0 - p[i] = p[s]|0 - p[s] = t|0 + var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) + if(x >= this.pointCount || x < 0) { + return null } - return p -} - -exports.rank = rank -exports.unrank = unrank -},{"invert-permutation":439,"typedarray-pool":442}],439:[function(require,module,exports){ -"use strict" - -function invertPermutation(pi, result) { - result = result || new Array(pi.length) - for(var i=0; i>8) &0xff + var a2 = (pointId>>16)&0xff + this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0] + } +} -module.exports = triangulateCube +proto.update = function(options) { -var perm = require("permutation-rank") -var sgn = require("permutation-parity") -var gamma = require("gamma") + options = options || {} -function triangulateCube(dimension) { - if(dimension < 0) { - return [ ] + if('perspective' in options) { + this.useOrtho = !options.perspective } - if(dimension === 0) { - return [ [0] ] + if('orthographic' in options) { + this.useOrtho = !!options.orthographic } - var dfactorial = Math.round(gamma(dimension+1))|0 - var result = [] - for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", - "args": [{ - "name": "_inline_1_arg0_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg1_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg2_", - "lvalue": false, - "rvalue": true, - "count": 1 - }, { - "name": "_inline_1_arg3_", - "lvalue": false, - "rvalue": true, - "count": 2 - }, { - "name": "_inline_1_arg4_", - "lvalue": false, - "rvalue": true, - "count": 1 - }], - "thisVars": [], - "localVars": ["_inline_1_da", "_inline_1_db"] - }, - funcName: 'zeroCrossings' -}) + if('projectOpacity' in options) { + if(Array.isArray(options.projectOpacity)) { + this.projectOpacity = options.projectOpacity.slice() + } else { + var s = +options.projectOpacity + this.projectOpacity = [s,s,s] + } + } + if('opacity' in options) { + this.opacity = options.opacity + } + + //Set dirty flag + this.dirty = true + + //Create new buffers + var points = options.position + if(!points) { + return + } + + //Text font + var font = options.font || 'normal' + var alignment = options.alignment || [0,0] + + //Bounds + var lowerBound = [ Infinity, Infinity, Infinity] + var upperBound = [-Infinity,-Infinity,-Infinity] + + //Unpack options + var glyphs = options.glyph + var colors = options.color + var sizes = options.size + var angles = options.angle + var lineColors = options.lineColor + + //Picking geometry + var pickCounter = 0 -},{"cwise-compiler":445}],445:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":447,"dup":319}],446:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":448}],447:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":446,"dup":321}],448:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],449:[function(require,module,exports){ -"use strict" + //First do pass to compute buffer sizes + var triVertexCount = 0 + var lineVertexCount = 0 -module.exports = findZeroCrossings + //Count number of points and buffer size + var numPoints = points.length -var core = require("./lib/zc-core") +count_loop: + for(var i=0; i c)|0 },") - if(dtype === "generic") { - code.push("getters:[0],") - } + var textOffset = [0,alignment[1]] - //Generate vertex function - var cubeArgs = [] - var extraArgs = [] - for(var i=0; i>>7){") - } - for(var i=0; i<1<<(1< 128) { - if((i%128)===0) { - if(extraFuncs.length > 0) { - currentFunc.push("}}") - } - var efName = "vExtra" + extraFuncs.length - code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") - currentFunc = [ - "function ", efName, "(m,", extraArgs.join(), "){switch(m){" - ] - extraFuncs.push(currentFunc) - } + var triOffset = 0 + var lineOffset = triVertexCount + var color = [0,0,0,1] + var lineColor = [0,0,0,1] + + var isColorArray = Array.isArray(colors) && Array.isArray(colors[0]) + var isLineColorArray = Array.isArray(lineColors) && Array.isArray(lineColors[0]) + +fill_loop: + for(var i=0; i j) { - continue + var glyphMesh = glyphData[0] + var glyphLines = glyphData[1] + var glyphBounds = glyphData[2] + + + //Get color + if(Array.isArray(colors)) { + var c + if(isColorArray) { + c = colors[i] + } else { + c = colors + } + if(c.length === 3) { + for(var j=0; j<3; ++j) { + color[j] = c[j] } - if(!(i&(1< 0) { - cStr = "+" + crossingCount[k] + "*c" + c = lineColors + } + if(c.length === 3) { + for(var j=0; j<3; ++j) { + lineColor[j] = c[j] + } + lineColor[j] = 1 + } else if(c.length === 4) { + for(var j=0; j<4; ++j) { + lineColor[j] = c[j] } - var weight = 0.5 * (crossings[k].length / totalCrossings) - var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) - vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") - } + } else { + lineColor[0] = lineColor[1] = lineColor[2] = 0 + lineColor[3] = 1 } - currentFunc.push("a.push([", vertexStr.join(), "]);", - "break;") - } - code.push("}},") - if(extraFuncs.length > 0) { - currentFunc.push("}}") - } - //Create face function - var faceArgs = [] - for(var i=0; i<(1<<(dimension-1)); ++i) { - faceArgs.push("v" + i) - } - faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c") - code.push("cell:function cellFunc(", faceArgs.join(), "){") + var size = 0.5 + if(Array.isArray(sizes)) { + size = +sizes[i] + } else if(sizes) { + size = +sizes + } else if(this.useOrtho) { + size = 12 + } - var facets = triangulateCube(dimension-1) - code.push("if(p0){b.push(", - facets.map(function(f) { - return "[" + f.map(function(v) { - return "v" + v - }) + "]" - }).join(), ")}else{b.push(", - facets.map(function(f) { - var e = f.slice() - e.reverse() - return "[" + e.map(function(v) { - return "v" + v - }) + "]" - }).join(), - ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";") + var angle = 0 + if(Array.isArray(angles)) { + angle = +angles[i] + } else if(angles) { + angle = +angles + } - for(var i=0; i 0) { + textOffset[0] = -alignment[0] * (1+glyphBounds[0][0]) + } -var CACHE = {} + //Write out inner marker + var cells = glyphMesh.cells + var verts = glyphMesh.positions -function surfaceNets(array,level) { - if(array.dimension <= 0) { - return { positions: [], cells: [] } - } else if(array.dimension === 1) { - return mesh1D(array, level) - } - var typesig = array.order.join() + "-" + array.dtype - var proc = CACHE[typesig] - var level = (+level) || 0.0 - if(!proc) { - proc = CACHE[typesig] = buildSurfaceNets(array.order, array.dtype) + for(var j=0; j0) { - shapeX += 0.02 - } - } +proto.dispose = function() { + //Shaders + this.shader.dispose() + this.orthoShader.dispose() + this.pickPerspectiveShader.dispose() + this.pickOrthoShader.dispose() - var data = new Float32Array(bufferSize) - var ptr = 0 - var xOffset = -0.5 * shapeX - for(var i=0; i 0) { + + //Draw border + var w = lineWidth * pixelRatio + boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor) + boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor) + boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor) + boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor) + } } -var proto = GLPlot2D.prototype +proto.update = function(options) { + options = options || {} -proto.setDirty = function() { - this.dirty = this.pickDirty = true + this.innerFill = !!options.innerFill + this.outerFill = !!options.outerFill + this.innerColor = (options.innerColor || [0,0,0,0.5]).slice() + this.outerColor = (options.outerColor || [0,0,0,0.5]).slice() + this.borderColor = (options.borderColor || [0,0,0,1]).slice() + this.borderWidth = options.borderWidth || 0 + this.selectBox = (options.selectBox || this.selectBox).slice() } -proto.setOverlayDirty = function() { - this.dirty = true +proto.dispose = function() { + this.boxBuffer.dispose() + this.boxShader.dispose() + this.plot.removeOverlay(this) } -proto.nextDepthValue = function() { - return (this._depthCounter++) / 65536.0 +function createSelectBox(plot, options) { + var gl = plot.gl + var buffer = createBuffer(gl, [ + 0, 0, + 0, 1, + 1, 0, + 1, 1 ]) + var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment) + var selectBox = new SelectBox(plot, buffer, shader) + selectBox.update(options) + plot.addOverlay(selectBox) + return selectBox } -function lerp(a, b, t) { - var s = 0.5 * (t + 1.0) - return Math.floor((1.0-s)*a + s*b)|0 +},{"./lib/shaders":194,"gl-buffer":118,"gl-shader":197}],196:[function(require,module,exports){ +'use strict' + +module.exports = createSelectBuffer + +var createFBO = require('gl-fbo') +var pool = require('typedarray-pool') +var ndarray = require('ndarray') + +var nextPow2 = require('bit-twiddle').nextPow2 + +var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_34_arg0_||255>_inline_34_arg1_||255>_inline_34_arg2_||255>_inline_34_arg3_){var _inline_34_l=_inline_34_arg4_-_inline_34_arg6_[0],_inline_34_a=_inline_34_arg5_-_inline_34_arg6_[1],_inline_34_f=_inline_34_l*_inline_34_l+_inline_34_a*_inline_34_a;_inline_34_f this.buffer.length) { + pool.free(this.buffer) + var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) + for(var i=0; i= 0)) { - continue - } + var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius) + var dx = closest[0] + var dy = closest[1] + if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) { + return null + } - var zeroIntercept = screenBox[i] - - dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i]) + var c0 = region.get(dx, dy, 0) + var c1 = region.get(dx, dy, 1) + var c2 = region.get(dx, dy, 2) + var c3 = region.get(dx, dy, 3) - if(i === 0) { - line.drawLine( - zeroIntercept, screenBox[1], zeroIntercept, screenBox[3], - zeroLineWidth[i], - zeroLineColor[i]) - } else { - line.drawLine( - screenBox[0], zeroIntercept, screenBox[2], zeroIntercept, - zeroLineWidth[i], - zeroLineColor[i]) - } - } - } + return new SelectResult( + (dx + x0)|0, + (dy + y0)|0, + c0, + [c1, c2, c3], + Math.sqrt(closest[2])) +} - //Draw traces - for(var i=0; i= 0) { + var size = attr.type.charAt(attr.type.length-1)|0 + var locVector = new Array(size) + for(var j=0; j= 0) { + curLocation += 1 + } + attributeLocations[i] = curLocation + } } - return result -} - -function compareTicks(a, b) { - return a.x - b.x -} -proto.setScreenBox = function(nbox) { - var screenBox = this.screenBox - var pixelRatio = this.pixelRatio + //Rebuild program and recompute all uniform locations + var uniformLocations = new Array(uniforms.length) + function relink() { + wrapper.program = shaderCache.program( + gl + , wrapper._vref + , wrapper._fref + , attributeNames + , attributeLocations) - screenBox[0] = Math.round(nbox[0] * pixelRatio) | 0 - screenBox[1] = Math.round(nbox[1] * pixelRatio) | 0 - screenBox[2] = Math.round(nbox[2] * pixelRatio) | 0 - screenBox[3] = Math.round(nbox[3] * pixelRatio) | 0 + for(var i=0; i=0; --i) { - this.objects[i].dispose() - } - this.objects.length = 0 - for(var i=this.overlays.length-1; i>=0; --i) { - this.overlays[i].dispose() - } - this.overlays.length = 0 - - this.gl = null -} +function addMatrixAttribute( + gl + , wrapper + , index + , locations + , dimension + , obj + , name) { -proto.addObject = function(object) { - if(this.objects.indexOf(object) < 0) { - this.objects.push(object) - this.setDirty() + var parts = new Array(dimension) + var attrs = new Array(dimension) + for(var i=0; i= 0) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addVectorAttribute( + gl + , wrapper + , locs[0] + , locations + , d + , obj + , name) + } else if(type.indexOf('mat') >= 0) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type) + } + addMatrixAttribute( + gl + , wrapper + , locs + , locations + , d + , obj + , name) + } else { + throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type) + } + break + } + } + return obj } -},{"gl-shader":590}],454:[function(require,module,exports){ +},{"./GLError":198}],200:[function(require,module,exports){ 'use strict' -module.exports = createCamera +var coallesceUniforms = require('./reflect') +var GLError = require("./GLError") -var now = require('right-now') -var createView = require('3d-view') -var mouseChange = require('mouse-change') -var mouseWheel = require('mouse-wheel') +module.exports = createUniformWrapper -function createCamera(element, options) { - element = element || document.body - options = options || {} +//Binds a function and returns a value +function identity(x) { + var c = new Function('y', 'return function(){return y}') + return c(x) +} - var limits = [ 0.01, Infinity ] - if('distanceLimits' in options) { - limits[0] = options.distanceLimits[0] - limits[1] = options.distanceLimits[1] - } - if('zoomMin' in options) { - limits[0] = options.zoomMin - } - if('zoomMax' in options) { - limits[1] = options.zoomMax +function makeVector(length, fill) { + var result = new Array(length) + for(var i=0; i 4) { + throw new GLError('', 'Invalid data type') + } + switch(type.charAt(0)) { + case 'b': + case 'i': + return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')' + case 'v': + return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')' + default: + throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type) + } + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + } + return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')' + } else { + throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) + } + break } } - Object.defineProperties(camera, { - matrix: { - get: function() { - return view.computedMatrix - }, - set: function(mat) { - view.setMatrix(view.lastT(), mat) - return view.computedMatrix - }, - enumerable: true - }, - mode: { - get: function() { - return view.getMode() - }, - set: function(mode) { - view.setMode(mode) - return view.getMode() - }, - enumerable: true - }, - center: { - get: function() { - return view.computedCenter - }, - set: function(ncenter) { - view.lookAt(view.lastT(), ncenter) - return view.computedCenter - }, - enumerable: true - }, - eye: { - get: function() { - return view.computedEye - }, - set: function(neye) { - view.lookAt(view.lastT(), null, neye) - return view.computedEye - }, - enumerable: true - }, - up: { - get: function() { - return view.computedUp - }, - set: function(nup) { - view.lookAt(view.lastT(), null, null, nup) - return view.computedUp - }, - enumerable: true - }, - distance: { - get: function() { - return distance - }, - set: function(d) { - view.setDistance(view.lastT(), d) - return d - }, - enumerable: true - }, - distanceLimits: { - get: function() { - return view.getDistanceLimits(limits) - }, - set: function(v) { - view.setDistanceLimits(v) - return v - }, - enumerable: true + function enumerateIndices(prefix, type) { + if(typeof type !== 'object') { + return [ [prefix, type] ] } - }) - - element.addEventListener('contextmenu', function(ev) { - ev.preventDefault() - return false - }) - - var lastX = 0, lastY = 0 - mouseChange(element, function(buttons, x, y, mods) { - var scale = 1.0 / element.clientHeight - var dx = scale * (x - lastX) - var dy = scale * (y - lastY) - - var flipX = camera.flipX ? 1 : -1 - var flipY = camera.flipY ? 1 : -1 - - var drot = Math.PI * camera.rotateSpeed - - var t = now() - - if(buttons & 1) { - if(mods.shift) { - view.rotate(t, 0, 0, -dx * drot) + var indices = [] + for(var id in type) { + var prop = type[id] + var tprefix = prefix + if(parseInt(id) + '' === id) { + tprefix += '[' + id + ']' } else { - view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0) + tprefix += '.' + id + } + if(typeof prop === 'object') { + indices.push.apply(indices, enumerateIndices(tprefix, prop)) + } else { + indices.push([tprefix, prop]) } - } else if(buttons & 2) { - view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0) - } else if(buttons & 4) { - var kzoom = camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 50.0 - view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) } + return indices + } - lastX = x - lastY = y - }) - - mouseWheel(element, function(dx, dy, dz) { - var flipX = camera.flipX ? 1 : -1 - var flipY = camera.flipY ? 1 : -1 - var t = now() - if(Math.abs(dx) > Math.abs(dy)) { - view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth) - } else { - var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0 - view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1)) + function makeSetter(type) { + var code = [ 'return function updateProperty(obj){' ] + var indices = enumerateIndices('', type) + for(var i=0; i 4) { + throw new GLError('', 'Invalid data type') + } + if(type.charAt(0) === 'b') { + return makeVector(d, false) + } + return makeVector(d, 0) + } else if(type.indexOf('mat') === 0 && type.length === 4) { + var d = type.charCodeAt(type.length-1) - 48 + if(d < 2 || d > 4) { + throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type) + } + return makeVector(d*d, 0) + } else { + throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type) + } + break } - }, true) - - return camera -} -},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],455:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":458}],456:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],457:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],458:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":456,"buffer":65,"dup":122}],459:[function(require,module,exports){ -arguments[4][154][0].apply(exports,arguments) -},{"dup":154}],460:[function(require,module,exports){ -arguments[4][155][0].apply(exports,arguments) -},{"./do-bind.js":459,"dup":155}],461:[function(require,module,exports){ -arguments[4][156][0].apply(exports,arguments) -},{"./do-bind.js":459,"dup":156}],462:[function(require,module,exports){ -arguments[4][157][0].apply(exports,arguments) -},{"./lib/vao-emulated.js":460,"./lib/vao-native.js":461,"dup":157}],463:[function(require,module,exports){ -// Copyright (C) 2011 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Install a leaky WeakMap emulation on platforms that - * don't provide a built-in one. - * - *

Assumes that an ES5 platform where, if {@code WeakMap} is - * already present, then it conforms to the anticipated ES6 - * specification. To run this file on an ES5 or almost ES5 - * implementation where the {@code WeakMap} specification does not - * quite conform, run repairES5.js first. - * - *

Even though WeakMapModule is not global, the linter thinks it - * is, which is why it is in the overrides list below. - * - *

NOTE: Before using this WeakMap emulation in a non-SES - * environment, see the note below about hiddenRecord. - * - * @author Mark S. Miller - * @requires crypto, ArrayBuffer, Uint8Array, navigator, console - * @overrides WeakMap, ses, Proxy - * @overrides WeakMapModule - */ - -/** - * This {@code WeakMap} emulation is observably equivalent to the - * ES-Harmony WeakMap, but with leakier garbage collection properties. - * - *

As with true WeakMaps, in this emulation, a key does not - * retain maps indexed by that key and (crucially) a map does not - * retain the keys it indexes. A map by itself also does not retain - * the values associated with that map. - * - *

However, the values associated with a key in some map are - * retained so long as that key is retained and those associations are - * not overridden. For example, when used to support membranes, all - * values exported from a given membrane will live for the lifetime - * they would have had in the absence of an interposed membrane. Even - * when the membrane is revoked, all objects that would have been - * reachable in the absence of revocation will still be reachable, as - * far as the GC can tell, even though they will no longer be relevant - * to ongoing computation. - * - *

The API implemented here is approximately the API as implemented - * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman, - * rather than the offially approved proposal page. TODO(erights): - * upgrade the ecmascript WeakMap proposal page to explain this API - * change and present to EcmaScript committee for their approval. - * - *

The first difference between the emulation here and that in - * FF6.0a1 is the presence of non enumerable {@code get___, has___, - * set___, and delete___} methods on WeakMap instances to represent - * what would be the hidden internal properties of a primitive - * implementation. Whereas the FF6.0a1 WeakMap.prototype methods - * require their {@code this} to be a genuine WeakMap instance (i.e., - * an object of {@code [[Class]]} "WeakMap}), since there is nothing - * unforgeable about the pseudo-internal method names used here, - * nothing prevents these emulated prototype methods from being - * applied to non-WeakMaps with pseudo-internal methods of the same - * names. - * - *

Another difference is that our emulated {@code - * WeakMap.prototype} is not itself a WeakMap. A problem with the - * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap - * providing ambient mutability and an ambient communications - * channel. Thus, if a WeakMap is already present and has this - * problem, repairES5.js wraps it in a safe wrappper in order to - * prevent access to this channel. (See - * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js). - */ - -/** - * If this is a full secureable ES5 platform and the ES-Harmony {@code WeakMap} is - * absent, install an approximate emulation. - * - *

If WeakMap is present but cannot store some objects, use our approximate - * emulation as a wrapper. - * - *

If this is almost a secureable ES5 platform, then WeakMap.js - * should be run after repairES5.js. - * - *

See {@code WeakMap} for documentation of the garbage collection - * properties of this WeakMap emulation. - */ -(function WeakMapModule() { - "use strict"; - - if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { - // already too broken, so give up - return; } - /** - * In some cases (current Firefox), we must make a choice betweeen a - * WeakMap which is capable of using all varieties of host objects as - * keys and one which is capable of safely using proxies as keys. See - * comments below about HostWeakMap and DoubleWeakMap for details. - * - * This function (which is a global, not exposed to guests) marks a - * WeakMap as permitted to do what is necessary to index all host - * objects, at the cost of making it unsafe for proxies. - * - * Do not apply this function to anything which is not a genuine - * fresh WeakMap. - */ - function weakMapPermitHostObjects(map) { - // identity of function used as a secret -- good enough and cheap - if (map.permitHostObjects___) { - map.permitHostObjects___(weakMapPermitHostObjects); + function storeProperty(obj, prop, type) { + if(typeof type === 'object') { + var child = processObject(type) + Object.defineProperty(obj, prop, { + get: identity(child), + set: makeSetter(type), + enumerable: true, + configurable: false + }) + } else { + if(locations[type]) { + Object.defineProperty(obj, prop, { + get: makeGetter(type), + set: makeSetter(type), + enumerable: true, + configurable: false + }) + } else { + obj[prop] = defaultValue(uniforms[type].type) + } } } - if (typeof ses !== 'undefined') { - ses.weakMapPermitHostObjects = weakMapPermitHostObjects; + + function processObject(obj) { + var result + if(Array.isArray(obj)) { + result = new Array(obj.length) + for(var i=0; i 1) { + if(!(x[0] in o)) { + o[x[0]] = [] + } + o = o[x[0]] + for(var k=1; kunguessable and - * undiscoverable by untrusted code. - * - *

Given the known weaknesses of Math.random() on existing - * browsers, it does not generate unguessability we can be confident - * of. - * - *

It is the monkey patching logic in this file that is intended - * to ensure undiscoverability. The basic idea is that there are - * three fundamental means of discovering properties of an object: - * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), - * as well as some proposed ES6 extensions that appear on our - * whitelist. The first two only discover enumerable properties, and - * we only use HIDDEN_NAME to name a non-enumerable property, so the - * only remaining threat should be getOwnPropertyNames and some - * proposed ES6 extensions that appear on our whitelist. We monkey - * patch them to remove HIDDEN_NAME from the list of properties they - * returns. - * - *

TODO(erights): On a platform with built-in Proxies, proxies - * could be used to trap and thereby discover the HIDDEN_NAME, so we - * need to monkey patch Proxy.create, Proxy.createFunction, etc, in - * order to wrap the provided handler with the real handler which - * filters out all traps using HIDDEN_NAME. - * - *

TODO(erights): Revisit Mike Stay's suggestion that we use an - * encapsulated function at a not-necessarily-secret name, which - * uses the Stiegler shared-state rights amplification pattern to - * reveal the associated value only to the WeakMap in which this key - * is associated with that value. Since only the key retains the - * function, the function can also remember the key without causing - * leakage of the key, so this doesn't violate our general gc - * goals. In addition, because the name need not be a guarded - * secret, we could efficiently handle cross-frame frozen keys. - */ - var HIDDEN_NAME_PREFIX = 'weakmap:'; - var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; +exports.uniforms = runtimeUniforms +exports.attributes = runtimeAttributes - if (typeof crypto !== 'undefined' && - typeof crypto.getRandomValues === 'function' && - typeof ArrayBuffer === 'function' && - typeof Uint8Array === 'function') { - var ab = new ArrayBuffer(25); - var u8s = new Uint8Array(ab); - crypto.getRandomValues(u8s); - HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + - Array.prototype.map.call(u8s, function(u8) { - return (u8 % 36).toString(36); - }).join('') + '___'; - } +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + 'SAMPLER_2D': 'sampler2D', + 'SAMPLER_CUBE':'samplerCube' +} - function isNotHiddenName(name) { - return !( - name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && - name.substr(name.length - 3) === '___'); - } +var GL_TABLE = null - /** - * Monkey patch getOwnPropertyNames to avoid revealing the - * HIDDEN_NAME. - * - *

The ES5.1 spec requires each name to appear only once, but as - * of this writing, this requirement is controversial for ES6, so we - * made this code robust against this case. If the resulting extra - * search turns out to be expensive, we can probably relax this once - * ES6 is adequately supported on all major browsers, iff no browser - * versions we support at that time have relaxed this constraint - * without providing built-in ES6 WeakMaps. - */ - defProp(Object, 'getOwnPropertyNames', { - value: function fakeGetOwnPropertyNames(obj) { - return gopn(obj).filter(isNotHiddenName); +function getType(gl, type) { + if(!GL_TABLE) { + var typeNames = Object.keys(GL_TO_GLSL_TYPES) + GL_TABLE = {} + for(var i=0; i 1) { + for(var j=0; jTo treat objects as identity-keys with reasonable efficiency - * on ES5 by itself (i.e., without any object-keyed collections), we - * need to add a hidden property to such key objects when we - * can. This raises several issues: - *

    - *
  • Arranging to add this property to objects before we lose the - * chance, and - *
  • Hiding the existence of this new property from most - * JavaScript code. - *
  • Preventing certification theft, where one object is - * created falsely claiming to be the key of an association - * actually keyed by another object. - *
  • Preventing value theft, where untrusted code with - * access to a key object but not a weak map nevertheless - * obtains access to the value associated with that key in that - * weak map. - *
- * We do so by - *
    - *
  • Making the name of the hidden property unguessable, so "[]" - * indexing, which we cannot intercept, cannot be used to access - * a property without knowing the name. - *
  • Making the hidden property non-enumerable, so we need not - * worry about for-in loops or {@code Object.keys}, - *
  • monkey patching those reflective methods that would - * prevent extensions, to add this hidden property first, - *
  • monkey patching those methods that would reveal this - * hidden property. - *
- * Unfortunately, because of same-origin iframes, we cannot reliably - * add this hidden property before an object becomes - * non-extensible. Instead, if we encounter a non-extensible object - * without a hidden record that we can detect (whether or not it has - * a hidden record stored under a name secret to us), then we just - * use the key object itself to represent its identity in a brute - * force leaky map stored in the weak map, losing all the advantages - * of weakness for these. - */ - function getHiddenRecord(key) { - if (key !== Object(key)) { - throw new TypeError('Not an object: ' + key); +function runtimeAttributes(gl, program) { + var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES) + var result = [] + for(var i=0; i

See {@code WeakMap} for documentation of the garbage collection - * properties of this WeakMap emulation. - */ -(function WeakMapModule() { - "use strict"; +function compileShader(gl, type, src) { + var shader = gl.createShader(type) + gl.shaderSource(shader, src) + gl.compileShader(shader) + if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + var errLog = gl.getShaderInfoLog(shader) + try { + var fmt = formatCompilerError(errLog, src, type); + } catch (e){ + console.warn('Failed to format compiler error: ' + e); + throw new GLError(errLog, 'Error compiling shader:\n' + errLog) + } + throw new GLError(errLog, fmt.short, fmt.long) + } + return shader +} - if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) { - // already too broken, so give up - return; +proto.getShaderReference = function(type, src) { + var gl = this.gl + var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0] + var shader = shaders[src] + if(!shader || !gl.isShader(shader.shader)) { + var shaderObj = compileShader(gl, type, src) + shader = shaders[src] = new ShaderReference( + SHADER_COUNTER++, + src, + type, + shaderObj, + [], + 1, + this) + } else { + shader.count += 1 } + return shader +} - /** - * In some cases (current Firefox), we must make a choice betweeen a - * WeakMap which is capable of using all varieties of host objects as - * keys and one which is capable of safely using proxies as keys. See - * comments below about HostWeakMap and DoubleWeakMap for details. - * - * This function (which is a global, not exposed to guests) marks a - * WeakMap as permitted to do what is necessary to index all host - * objects, at the cost of making it unsafe for proxies. - * - * Do not apply this function to anything which is not a genuine - * fresh WeakMap. - */ - function weakMapPermitHostObjects(map) { - // identity of function used as a secret -- good enough and cheap - if (map.permitHostObjects___) { - map.permitHostObjects___(weakMapPermitHostObjects); - } +function linkProgram(gl, vshader, fshader, attribs, locations) { + var program = gl.createProgram() + gl.attachShader(program, vshader) + gl.attachShader(program, fshader) + for(var i=0; iunguessable and - * undiscoverable by untrusted code. - * - *

Given the known weaknesses of Math.random() on existing - * browsers, it does not generate unguessability we can be confident - * of. - * - *

It is the monkey patching logic in this file that is intended - * to ensure undiscoverability. The basic idea is that there are - * three fundamental means of discovering properties of an object: - * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(), - * as well as some proposed ES6 extensions that appear on our - * whitelist. The first two only discover enumerable properties, and - * we only use HIDDEN_NAME to name a non-enumerable property, so the - * only remaining threat should be getOwnPropertyNames and some - * proposed ES6 extensions that appear on our whitelist. We monkey - * patch them to remove HIDDEN_NAME from the list of properties they - * returns. - * - *

TODO(erights): On a platform with built-in Proxies, proxies - * could be used to trap and thereby discover the HIDDEN_NAME, so we - * need to monkey patch Proxy.create, Proxy.createFunction, etc, in - * order to wrap the provided handler with the real handler which - * filters out all traps using HIDDEN_NAME. - * - *

TODO(erights): Revisit Mike Stay's suggestion that we use an - * encapsulated function at a not-necessarily-secret name, which - * uses the Stiegler shared-state rights amplification pattern to - * reveal the associated value only to the WeakMap in which this key - * is associated with that value. Since only the key retains the - * function, the function can also remember the key without causing - * leakage of the key, so this doesn't violate our general gc - * goals. In addition, because the name need not be a guarded - * secret, we could efficiently handle cross-frame frozen keys. - */ - var HIDDEN_NAME_PREFIX = 'weakmap:'; - var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___'; +var sprintf = require('sprintf-js').sprintf; +var glConstants = require('gl-constants/lookup'); +var shaderName = require('glsl-shader-name'); +var addLineNumbers = require('add-line-numbers'); - if (typeof crypto !== 'undefined' && - typeof crypto.getRandomValues === 'function' && - typeof ArrayBuffer === 'function' && - typeof Uint8Array === 'function') { - var ab = new ArrayBuffer(25); - var u8s = new Uint8Array(ab); - crypto.getRandomValues(u8s); - HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' + - Array.prototype.map.call(u8s, function(u8) { - return (u8 % 36).toString(36); - }).join('') + '___'; - } +module.exports = formatCompilerError; - function isNotHiddenName(name) { - return !( - name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX && - name.substr(name.length - 3) === '___'); - } +function formatCompilerError(errLog, src, type) { + "use strict"; - /** - * Monkey patch getOwnPropertyNames to avoid revealing the - * HIDDEN_NAME. - * - *

The ES5.1 spec requires each name to appear only once, but as - * of this writing, this requirement is controversial for ES6, so we - * made this code robust against this case. If the resulting extra - * search turns out to be expensive, we can probably relax this once - * ES6 is adequately supported on all major browsers, iff no browser - * versions we support at that time have relaxed this constraint - * without providing built-in ES6 WeakMaps. - */ - defProp(Object, 'getOwnPropertyNames', { - value: function fakeGetOwnPropertyNames(obj) { - return gopn(obj).filter(isNotHiddenName); + var name = shaderName(src) || 'of unknown name (see npm glsl-shader-name)'; + + var typeName = 'unknown type'; + if (type !== undefined) { + typeName = type === glConstants.FRAGMENT_SHADER ? 'fragment' : 'vertex' + } + + var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name); + var shortForm = sprintf("%s%s", longForm, errLog); + + var errorStrings = errLog.split('\n'); + var errors = {}; + + for (var i = 0; i < errorStrings.length; i++) { + var errorString = errorStrings[i]; + if (errorString === '') continue; + var lineNo = parseInt(errorString.split(':')[2]); + if (isNaN(lineNo)) { + throw new Error(sprintf('Could not parse error: %s', errorString)); + } + errors[lineNo] = errorString; } - }); - /** - * getPropertyNames is not in ES5 but it is proposed for ES6 and - * does appear in our whitelist, so we need to clean it too. - */ - if ('getPropertyNames' in Object) { - var originalGetPropertyNames = Object.getPropertyNames; - defProp(Object, 'getPropertyNames', { - value: function fakeGetPropertyNames(obj) { - return originalGetPropertyNames(obj).filter(isNotHiddenName); - } - }); - } + var lines = addLineNumbers(src).split('\n'); - /** - *

To treat objects as identity-keys with reasonable efficiency - * on ES5 by itself (i.e., without any object-keyed collections), we - * need to add a hidden property to such key objects when we - * can. This raises several issues: - *

    - *
  • Arranging to add this property to objects before we lose the - * chance, and - *
  • Hiding the existence of this new property from most - * JavaScript code. - *
  • Preventing certification theft, where one object is - * created falsely claiming to be the key of an association - * actually keyed by another object. - *
  • Preventing value theft, where untrusted code with - * access to a key object but not a weak map nevertheless - * obtains access to the value associated with that key in that - * weak map. - *
- * We do so by - *
    - *
  • Making the name of the hidden property unguessable, so "[]" - * indexing, which we cannot intercept, cannot be used to access - * a property without knowing the name. - *
  • Making the hidden property non-enumerable, so we need not - * worry about for-in loops or {@code Object.keys}, - *
  • monkey patching those reflective methods that would - * prevent extensions, to add this hidden property first, - *
  • monkey patching those methods that would reveal this - * hidden property. - *
- * Unfortunately, because of same-origin iframes, we cannot reliably - * add this hidden property before an object becomes - * non-extensible. Instead, if we encounter a non-extensible object - * without a hidden record that we can detect (whether or not it has - * a hidden record stored under a name secret to us), then we just - * use the key object itself to represent its identity in a brute - * force leaky map stored in the weak map, losing all the advantages - * of weakness for these. - */ - function getHiddenRecord(key) { - if (key !== Object(key)) { - throw new TypeError('Not an object: ' + key); - } - var hiddenRecord = key[HIDDEN_NAME]; - if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; } - if (!isExtensible(key)) { - // Weak map must brute force, as explained in doc-comment above. - return void 0; + for (var i = 0; i < lines.length; i++) { + if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue; + var line = lines[i]; + longForm += line + '\n'; + if (errors[i+1]) { + var e = errors[i+1]; + e = e.substr(e.split(':', 3).join(':').length + 1).trim(); + longForm += sprintf('^^^ %s\n\n', e); + } } - // The hiddenRecord and the key point directly at each other, via - // the "key" and HIDDEN_NAME properties respectively. The key - // field is for quickly verifying that this hidden record is an - // own property, not a hidden record from up the prototype chain. - // - // NOTE: Because this WeakMap emulation is meant only for systems like - // SES where Object.prototype is frozen without any numeric - // properties, it is ok to use an object literal for the hiddenRecord. - // This has two advantages: - // * It is much faster in a performance critical place - // * It avoids relying on Object.create(null), which had been - // problematic on Chrome 28.0.1480.0. See - // https://code.google.com/p/google-caja/issues/detail?id=1687 - hiddenRecord = { key: key }; + return { + long: longForm.trim(), + short: shortForm.trim() + }; +} - // When using this WeakMap emulation on platforms where - // Object.prototype might not be frozen and Object.create(null) is - // reliable, use the following two commented out lines instead. - // hiddenRecord = Object.create(null); - // hiddenRecord.key = key; - // Please contact us if you need this to work on platforms where - // Object.prototype might not be frozen and - // Object.create(null) might not be reliable. +},{"add-line-numbers":205,"gl-constants/lookup":208,"glsl-shader-name":209,"sprintf-js":211}],205:[function(require,module,exports){ +var padLeft = require('pad-left') - try { - defProp(key, HIDDEN_NAME, { - value: hiddenRecord, - writable: false, - enumerable: false, - configurable: false - }); - return hiddenRecord; - } catch (error) { - // Under some circumstances, isExtensible seems to misreport whether - // the HIDDEN_NAME can be defined. - // The circumstances have not been isolated, but at least affect - // Node.js v0.10.26 on TravisCI / Linux, but not the same version of - // Node.js on OS X. - return void 0; - } - } +module.exports = addLineNumbers +function addLineNumbers (string, start, delim) { + start = typeof start === 'number' ? start : 1 + delim = delim || ': ' - /** - * Monkey patch operations that would make their argument - * non-extensible. - * - *

The monkey patched versions throw a TypeError if their - * argument is not an object, so it should only be done to functions - * that should throw a TypeError anyway if their argument is not an - * object. - */ - (function(){ - var oldFreeze = Object.freeze; - defProp(Object, 'freeze', { - value: function identifyingFreeze(obj) { - getHiddenRecord(obj); - return oldFreeze(obj); - } - }); - var oldSeal = Object.seal; - defProp(Object, 'seal', { - value: function identifyingSeal(obj) { - getHiddenRecord(obj); - return oldSeal(obj); - } - }); - var oldPreventExtensions = Object.preventExtensions; - defProp(Object, 'preventExtensions', { - value: function identifyingPreventExtensions(obj) { - getHiddenRecord(obj); - return oldPreventExtensions(obj); - } - }); - })(); + var lines = string.split(/\r?\n/) + var totalDigits = String(lines.length + start - 1).length + return lines.map(function (line, i) { + var c = i + start + var digits = String(c).length + var prefix = padLeft(c, totalDigits - digits) + return prefix + delim + line + }).join('\n') +} - function constFunc(func) { - func.prototype = null; - return Object.freeze(func); - } +},{"pad-left":206}],206:[function(require,module,exports){ +/*! + * pad-left + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT license. + */ - var calledAsFunctionWarningDone = false; - function calledAsFunctionWarning() { - // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap() - // but we used to permit it and do it ourselves, so warn only. - if (!calledAsFunctionWarningDone && typeof console !== 'undefined') { - calledAsFunctionWarningDone = true; - console.warn('WeakMap should be invoked as new WeakMap(), not ' + - 'WeakMap(). This will be an error in the future.'); - } - } +'use strict'; - var nextId = 0; +var repeat = require('repeat-string'); + +module.exports = function padLeft(str, num, ch) { + ch = typeof ch !== 'undefined' ? (ch + '') : ' '; + return repeat(ch, num) + str; +}; +},{"repeat-string":254}],207:[function(require,module,exports){ +module.exports = { + 0: 'NONE', + 1: 'ONE', + 2: 'LINE_LOOP', + 3: 'LINE_STRIP', + 4: 'TRIANGLES', + 5: 'TRIANGLE_STRIP', + 6: 'TRIANGLE_FAN', + 256: 'DEPTH_BUFFER_BIT', + 512: 'NEVER', + 513: 'LESS', + 514: 'EQUAL', + 515: 'LEQUAL', + 516: 'GREATER', + 517: 'NOTEQUAL', + 518: 'GEQUAL', + 519: 'ALWAYS', + 768: 'SRC_COLOR', + 769: 'ONE_MINUS_SRC_COLOR', + 770: 'SRC_ALPHA', + 771: 'ONE_MINUS_SRC_ALPHA', + 772: 'DST_ALPHA', + 773: 'ONE_MINUS_DST_ALPHA', + 774: 'DST_COLOR', + 775: 'ONE_MINUS_DST_COLOR', + 776: 'SRC_ALPHA_SATURATE', + 1024: 'STENCIL_BUFFER_BIT', + 1028: 'FRONT', + 1029: 'BACK', + 1032: 'FRONT_AND_BACK', + 1280: 'INVALID_ENUM', + 1281: 'INVALID_VALUE', + 1282: 'INVALID_OPERATION', + 1285: 'OUT_OF_MEMORY', + 1286: 'INVALID_FRAMEBUFFER_OPERATION', + 2304: 'CW', + 2305: 'CCW', + 2849: 'LINE_WIDTH', + 2884: 'CULL_FACE', + 2885: 'CULL_FACE_MODE', + 2886: 'FRONT_FACE', + 2928: 'DEPTH_RANGE', + 2929: 'DEPTH_TEST', + 2930: 'DEPTH_WRITEMASK', + 2931: 'DEPTH_CLEAR_VALUE', + 2932: 'DEPTH_FUNC', + 2960: 'STENCIL_TEST', + 2961: 'STENCIL_CLEAR_VALUE', + 2962: 'STENCIL_FUNC', + 2963: 'STENCIL_VALUE_MASK', + 2964: 'STENCIL_FAIL', + 2965: 'STENCIL_PASS_DEPTH_FAIL', + 2966: 'STENCIL_PASS_DEPTH_PASS', + 2967: 'STENCIL_REF', + 2968: 'STENCIL_WRITEMASK', + 2978: 'VIEWPORT', + 3024: 'DITHER', + 3042: 'BLEND', + 3088: 'SCISSOR_BOX', + 3089: 'SCISSOR_TEST', + 3106: 'COLOR_CLEAR_VALUE', + 3107: 'COLOR_WRITEMASK', + 3317: 'UNPACK_ALIGNMENT', + 3333: 'PACK_ALIGNMENT', + 3379: 'MAX_TEXTURE_SIZE', + 3386: 'MAX_VIEWPORT_DIMS', + 3408: 'SUBPIXEL_BITS', + 3410: 'RED_BITS', + 3411: 'GREEN_BITS', + 3412: 'BLUE_BITS', + 3413: 'ALPHA_BITS', + 3414: 'DEPTH_BITS', + 3415: 'STENCIL_BITS', + 3553: 'TEXTURE_2D', + 4352: 'DONT_CARE', + 4353: 'FASTEST', + 4354: 'NICEST', + 5120: 'BYTE', + 5121: 'UNSIGNED_BYTE', + 5122: 'SHORT', + 5123: 'UNSIGNED_SHORT', + 5124: 'INT', + 5125: 'UNSIGNED_INT', + 5126: 'FLOAT', + 5386: 'INVERT', + 5890: 'TEXTURE', + 6401: 'STENCIL_INDEX', + 6402: 'DEPTH_COMPONENT', + 6406: 'ALPHA', + 6407: 'RGB', + 6408: 'RGBA', + 6409: 'LUMINANCE', + 6410: 'LUMINANCE_ALPHA', + 7680: 'KEEP', + 7681: 'REPLACE', + 7682: 'INCR', + 7683: 'DECR', + 7936: 'VENDOR', + 7937: 'RENDERER', + 7938: 'VERSION', + 9728: 'NEAREST', + 9729: 'LINEAR', + 9984: 'NEAREST_MIPMAP_NEAREST', + 9985: 'LINEAR_MIPMAP_NEAREST', + 9986: 'NEAREST_MIPMAP_LINEAR', + 9987: 'LINEAR_MIPMAP_LINEAR', + 10240: 'TEXTURE_MAG_FILTER', + 10241: 'TEXTURE_MIN_FILTER', + 10242: 'TEXTURE_WRAP_S', + 10243: 'TEXTURE_WRAP_T', + 10497: 'REPEAT', + 10752: 'POLYGON_OFFSET_UNITS', + 16384: 'COLOR_BUFFER_BIT', + 32769: 'CONSTANT_COLOR', + 32770: 'ONE_MINUS_CONSTANT_COLOR', + 32771: 'CONSTANT_ALPHA', + 32772: 'ONE_MINUS_CONSTANT_ALPHA', + 32773: 'BLEND_COLOR', + 32774: 'FUNC_ADD', + 32777: 'BLEND_EQUATION_RGB', + 32778: 'FUNC_SUBTRACT', + 32779: 'FUNC_REVERSE_SUBTRACT', + 32819: 'UNSIGNED_SHORT_4_4_4_4', + 32820: 'UNSIGNED_SHORT_5_5_5_1', + 32823: 'POLYGON_OFFSET_FILL', + 32824: 'POLYGON_OFFSET_FACTOR', + 32854: 'RGBA4', + 32855: 'RGB5_A1', + 32873: 'TEXTURE_BINDING_2D', + 32926: 'SAMPLE_ALPHA_TO_COVERAGE', + 32928: 'SAMPLE_COVERAGE', + 32936: 'SAMPLE_BUFFERS', + 32937: 'SAMPLES', + 32938: 'SAMPLE_COVERAGE_VALUE', + 32939: 'SAMPLE_COVERAGE_INVERT', + 32968: 'BLEND_DST_RGB', + 32969: 'BLEND_SRC_RGB', + 32970: 'BLEND_DST_ALPHA', + 32971: 'BLEND_SRC_ALPHA', + 33071: 'CLAMP_TO_EDGE', + 33170: 'GENERATE_MIPMAP_HINT', + 33189: 'DEPTH_COMPONENT16', + 33306: 'DEPTH_STENCIL_ATTACHMENT', + 33635: 'UNSIGNED_SHORT_5_6_5', + 33648: 'MIRRORED_REPEAT', + 33901: 'ALIASED_POINT_SIZE_RANGE', + 33902: 'ALIASED_LINE_WIDTH_RANGE', + 33984: 'TEXTURE0', + 33985: 'TEXTURE1', + 33986: 'TEXTURE2', + 33987: 'TEXTURE3', + 33988: 'TEXTURE4', + 33989: 'TEXTURE5', + 33990: 'TEXTURE6', + 33991: 'TEXTURE7', + 33992: 'TEXTURE8', + 33993: 'TEXTURE9', + 33994: 'TEXTURE10', + 33995: 'TEXTURE11', + 33996: 'TEXTURE12', + 33997: 'TEXTURE13', + 33998: 'TEXTURE14', + 33999: 'TEXTURE15', + 34000: 'TEXTURE16', + 34001: 'TEXTURE17', + 34002: 'TEXTURE18', + 34003: 'TEXTURE19', + 34004: 'TEXTURE20', + 34005: 'TEXTURE21', + 34006: 'TEXTURE22', + 34007: 'TEXTURE23', + 34008: 'TEXTURE24', + 34009: 'TEXTURE25', + 34010: 'TEXTURE26', + 34011: 'TEXTURE27', + 34012: 'TEXTURE28', + 34013: 'TEXTURE29', + 34014: 'TEXTURE30', + 34015: 'TEXTURE31', + 34016: 'ACTIVE_TEXTURE', + 34024: 'MAX_RENDERBUFFER_SIZE', + 34041: 'DEPTH_STENCIL', + 34055: 'INCR_WRAP', + 34056: 'DECR_WRAP', + 34067: 'TEXTURE_CUBE_MAP', + 34068: 'TEXTURE_BINDING_CUBE_MAP', + 34069: 'TEXTURE_CUBE_MAP_POSITIVE_X', + 34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X', + 34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y', + 34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y', + 34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z', + 34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z', + 34076: 'MAX_CUBE_MAP_TEXTURE_SIZE', + 34338: 'VERTEX_ATTRIB_ARRAY_ENABLED', + 34339: 'VERTEX_ATTRIB_ARRAY_SIZE', + 34340: 'VERTEX_ATTRIB_ARRAY_STRIDE', + 34341: 'VERTEX_ATTRIB_ARRAY_TYPE', + 34342: 'CURRENT_VERTEX_ATTRIB', + 34373: 'VERTEX_ATTRIB_ARRAY_POINTER', + 34466: 'NUM_COMPRESSED_TEXTURE_FORMATS', + 34467: 'COMPRESSED_TEXTURE_FORMATS', + 34660: 'BUFFER_SIZE', + 34661: 'BUFFER_USAGE', + 34816: 'STENCIL_BACK_FUNC', + 34817: 'STENCIL_BACK_FAIL', + 34818: 'STENCIL_BACK_PASS_DEPTH_FAIL', + 34819: 'STENCIL_BACK_PASS_DEPTH_PASS', + 34877: 'BLEND_EQUATION_ALPHA', + 34921: 'MAX_VERTEX_ATTRIBS', + 34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED', + 34930: 'MAX_TEXTURE_IMAGE_UNITS', + 34962: 'ARRAY_BUFFER', + 34963: 'ELEMENT_ARRAY_BUFFER', + 34964: 'ARRAY_BUFFER_BINDING', + 34965: 'ELEMENT_ARRAY_BUFFER_BINDING', + 34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING', + 35040: 'STREAM_DRAW', + 35044: 'STATIC_DRAW', + 35048: 'DYNAMIC_DRAW', + 35632: 'FRAGMENT_SHADER', + 35633: 'VERTEX_SHADER', + 35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS', + 35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS', + 35663: 'SHADER_TYPE', + 35664: 'FLOAT_VEC2', + 35665: 'FLOAT_VEC3', + 35666: 'FLOAT_VEC4', + 35667: 'INT_VEC2', + 35668: 'INT_VEC3', + 35669: 'INT_VEC4', + 35670: 'BOOL', + 35671: 'BOOL_VEC2', + 35672: 'BOOL_VEC3', + 35673: 'BOOL_VEC4', + 35674: 'FLOAT_MAT2', + 35675: 'FLOAT_MAT3', + 35676: 'FLOAT_MAT4', + 35678: 'SAMPLER_2D', + 35680: 'SAMPLER_CUBE', + 35712: 'DELETE_STATUS', + 35713: 'COMPILE_STATUS', + 35714: 'LINK_STATUS', + 35715: 'VALIDATE_STATUS', + 35716: 'INFO_LOG_LENGTH', + 35717: 'ATTACHED_SHADERS', + 35718: 'ACTIVE_UNIFORMS', + 35719: 'ACTIVE_UNIFORM_MAX_LENGTH', + 35720: 'SHADER_SOURCE_LENGTH', + 35721: 'ACTIVE_ATTRIBUTES', + 35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH', + 35724: 'SHADING_LANGUAGE_VERSION', + 35725: 'CURRENT_PROGRAM', + 36003: 'STENCIL_BACK_REF', + 36004: 'STENCIL_BACK_VALUE_MASK', + 36005: 'STENCIL_BACK_WRITEMASK', + 36006: 'FRAMEBUFFER_BINDING', + 36007: 'RENDERBUFFER_BINDING', + 36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE', + 36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME', + 36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL', + 36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE', + 36053: 'FRAMEBUFFER_COMPLETE', + 36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT', + 36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT', + 36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS', + 36061: 'FRAMEBUFFER_UNSUPPORTED', + 36064: 'COLOR_ATTACHMENT0', + 36096: 'DEPTH_ATTACHMENT', + 36128: 'STENCIL_ATTACHMENT', + 36160: 'FRAMEBUFFER', + 36161: 'RENDERBUFFER', + 36162: 'RENDERBUFFER_WIDTH', + 36163: 'RENDERBUFFER_HEIGHT', + 36164: 'RENDERBUFFER_INTERNAL_FORMAT', + 36168: 'STENCIL_INDEX8', + 36176: 'RENDERBUFFER_RED_SIZE', + 36177: 'RENDERBUFFER_GREEN_SIZE', + 36178: 'RENDERBUFFER_BLUE_SIZE', + 36179: 'RENDERBUFFER_ALPHA_SIZE', + 36180: 'RENDERBUFFER_DEPTH_SIZE', + 36181: 'RENDERBUFFER_STENCIL_SIZE', + 36194: 'RGB565', + 36336: 'LOW_FLOAT', + 36337: 'MEDIUM_FLOAT', + 36338: 'HIGH_FLOAT', + 36339: 'LOW_INT', + 36340: 'MEDIUM_INT', + 36341: 'HIGH_INT', + 36346: 'SHADER_COMPILER', + 36347: 'MAX_VERTEX_UNIFORM_VECTORS', + 36348: 'MAX_VARYING_VECTORS', + 36349: 'MAX_FRAGMENT_UNIFORM_VECTORS', + 37440: 'UNPACK_FLIP_Y_WEBGL', + 37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL', + 37442: 'CONTEXT_LOST_WEBGL', + 37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL', + 37444: 'BROWSER_DEFAULT_WEBGL' +} + +},{}],208:[function(require,module,exports){ +var gl10 = require('./1.0/numbers') + +module.exports = function lookupConstant (number) { + return gl10[number] +} + +},{"./1.0/numbers":207}],209:[function(require,module,exports){ +var tokenize = require('glsl-tokenizer') +var atob = require('atob-lite') + +module.exports = getName + +function getName(src) { + var tokens = Array.isArray(src) + ? src + : tokenize(src) + + for (var i = 0; i < tokens.length; i++) { + var token = tokens[i] + if (token.type !== 'preprocessor') continue + var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/) + if (!match) continue + if (!match[2]) continue - var OurWeakMap = function() { - if (!(this instanceof OurWeakMap)) { // approximate test for new ...() - calledAsFunctionWarning(); - } + var b64 = match[1] + var name = match[2] - // We are currently (12/25/2012) never encountering any prematurely - // non-extensible keys. - var keys = []; // brute force for prematurely non-extensible keys. - var values = []; // brute force for corresponding values. - var id = nextId++; + return (b64 ? atob(name) : name).trim() + } +} - function get___(key, opt_default) { - var index; - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - return id in hiddenRecord ? hiddenRecord[id] : opt_default; - } else { - index = keys.indexOf(key); - return index >= 0 ? values[index] : opt_default; - } - } +},{"atob-lite":210,"glsl-tokenizer":234}],210:[function(require,module,exports){ +module.exports = function _atob(str) { + return atob(str) +} - function has___(key) { - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - return id in hiddenRecord; - } else { - return keys.indexOf(key) >= 0; - } +},{}],211:[function(require,module,exports){ +(function(window) { + var re = { + not_string: /[^s]/, + number: /[diefg]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ } - function set___(key, value) { - var index; - var hiddenRecord = getHiddenRecord(key); - if (hiddenRecord) { - hiddenRecord[id] = value; - } else { - index = keys.indexOf(key); - if (index >= 0) { - values[index] = value; - } else { - // Since some browsers preemptively terminate slow turns but - // then continue computing with presumably corrupted heap - // state, we here defensively get keys.length first and then - // use it to update both the values and keys arrays, keeping - // them in sync. - index = keys.length; - values[index] = value; - // If we crash here, values will be one longer than keys. - keys[index] = key; + function sprintf() { + var key = arguments[0], cache = sprintf.cache + if (!(cache[key] && cache.hasOwnProperty(key))) { + cache[key] = sprintf.parse(key) } - } - return this; + return sprintf.format.call(null, cache[key], arguments) } - function delete___(key) { - var hiddenRecord = getHiddenRecord(key); - var index, lastIndex; - if (hiddenRecord) { - return id in hiddenRecord && delete hiddenRecord[id]; - } else { - index = keys.indexOf(key); - if (index < 0) { - return false; + sprintf.format = function(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = "" + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]) + if (node_type === "string") { + output[output.length] = parse_tree[i] + } + else if (node_type === "array") { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (get_type(arg) == "function") { + arg = arg() + } + + if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) { + throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg))) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case "b": + arg = arg.toString(2) + break + case "c": + arg = String.fromCharCode(arg) + break + case "d": + case "i": + arg = parseInt(arg, 10) + break + case "j": + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case "e": + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential() + break + case "f": + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case "g": + arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg) + break + case "o": + arg = arg.toString(8) + break + case "s": + arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg) + break + case "u": + arg = arg >>> 0 + break + case "x": + arg = arg.toString(16) + break + case "X": + arg = arg.toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output[output.length] = arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? "+" : "-" + arg = arg.toString().replace(re.sign, "") + } + else { + sign = "" + } + pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " " + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : "" + output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg) + } + } } - // Since some browsers preemptively terminate slow turns but - // then continue computing with potentially corrupted heap - // state, we here defensively get keys.length first and then use - // it to update both the keys and the values array, keeping - // them in sync. We update the two with an order of assignments, - // such that any prefix of these assignments will preserve the - // key/value correspondence, either before or after the delete. - // Note that this needs to work correctly when index === lastIndex. - lastIndex = keys.length - 1; - keys[index] = void 0; - // If we crash here, there's a void 0 in the keys array, but - // no operation will cause a "keys.indexOf(void 0)", since - // getHiddenRecord(void 0) will always throw an error first. - values[index] = values[lastIndex]; - // If we crash here, values[index] cannot be found here, - // because keys[index] is void 0. - keys[index] = keys[lastIndex]; - // If index === lastIndex and we crash here, then keys[index] - // is still void 0, since the aliasing killed the previous key. - keys.length = lastIndex; - // If we crash here, keys will be one shorter than values. - values.length = lastIndex; - return true; - } + return output.join("") } - return Object.create(OurWeakMap.prototype, { - get___: { value: constFunc(get___) }, - has___: { value: constFunc(has___) }, - set___: { value: constFunc(set___) }, - delete___: { value: constFunc(delete___) } - }); - }; - - OurWeakMap.prototype = Object.create(Object.prototype, { - get: { - /** - * Return the value most recently associated with key, or - * opt_default if none. - */ - value: function get(key, opt_default) { - return this.get___(key, opt_default); - }, - writable: true, - configurable: true - }, + sprintf.cache = {} - has: { - /** - * Is there a value associated with key in this WeakMap? - */ - value: function has(key) { - return this.has___(key); - }, - writable: true, - configurable: true - }, + sprintf.parse = function(fmt) { + var _fmt = fmt, match = [], parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = match[0] + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree[parse_tree.length] = "%" + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list[field_list.length] = field_match[1] + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + } + } + else { + throw new SyntaxError("[sprintf] failed to parse named argument key") + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported") + } + parse_tree[parse_tree.length] = match + } + else { + throw new SyntaxError("[sprintf] unexpected placeholder") + } + _fmt = _fmt.substring(match[0].length) + } + return parse_tree + } - set: { - /** - * Associate value with key in this WeakMap, overwriting any - * previous association if present. - */ - value: function set(key, value) { - return this.set___(key, value); - }, - writable: true, - configurable: true - }, + var vsprintf = function(fmt, argv, _argv) { + _argv = (argv || []).slice(0) + _argv.splice(0, 0, fmt) + return sprintf.apply(null, _argv) + } - 'delete': { - /** - * Remove any association for key in this WeakMap, returning - * whether there was one. - * - *

Note that the boolean return here does not work like the - * {@code delete} operator. The {@code delete} operator returns - * whether the deletion succeeds at bringing about a state in - * which the deleted property is absent. The {@code delete} - * operator therefore returns true if the property was already - * absent, whereas this {@code delete} method returns false if - * the association was already absent. - */ - value: function remove(key) { - return this.delete___(key); - }, - writable: true, - configurable: true + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase() } - }); - if (typeof HostWeakMap === 'function') { - (function() { - // If we got here, then the platform has a WeakMap but we are concerned - // that it may refuse to store some key types. Therefore, make a map - // implementation which makes use of both as possible. + function str_repeat(input, multiplier) { + return Array(multiplier + 1).join(input) + } - // In this mode we are always using double maps, so we are not proxy-safe. - // This combination does not occur in any known browser, but we had best - // be safe. - if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') { - Proxy = undefined; - } + /** + * export to either browser or node.js + */ + if (typeof exports !== "undefined") { + exports.sprintf = sprintf + exports.vsprintf = vsprintf + } + else { + window.sprintf = sprintf + window.vsprintf = vsprintf - function DoubleWeakMap() { - if (!(this instanceof OurWeakMap)) { // approximate test for new ...() - calledAsFunctionWarning(); + if (typeof define === "function" && define.amd) { + define(function() { + return { + sprintf: sprintf, + vsprintf: vsprintf + } + }) } + } +})(typeof window === "undefined" ? this : window); - // Preferable, truly weak map. - var hmap = new HostWeakMap(); - - // Our hidden-property-based pseudo-weak-map. Lazily initialized in the - // 'set' implementation; thus we can avoid performing extra lookups if - // we know all entries actually stored are entered in 'hmap'. - var omap = undefined; +},{}],212:[function(require,module,exports){ +var hiddenStore = require('./hidden-store.js'); - // Hidden-property maps are not compatible with proxies because proxies - // can observe the hidden name and either accidentally expose it or fail - // to allow the hidden property to be set. Therefore, we do not allow - // arbitrary WeakMaps to switch to using hidden properties, but only - // those which need the ability, and unprivileged code is not allowed - // to set the flag. - // - // (Except in doubleWeakMapCheckSilentFailure mode in which case we - // disable proxies.) - var enableSwitching = false; +module.exports = createStore; - function dget(key, opt_default) { - if (omap) { - return hmap.has(key) ? hmap.get(key) - : omap.get___(key, opt_default); - } else { - return hmap.get(key, opt_default); - } - } +function createStore() { + var key = {}; - function dhas(key) { - return hmap.has(key) || (omap ? omap.has___(key) : false); + return function (obj) { + if ((typeof obj !== 'object' || obj === null) && + typeof obj !== 'function' + ) { + throw new Error('Weakmap-shim: Key must be object') } - var dset; - if (doubleWeakMapCheckSilentFailure) { - dset = function(key, value) { - hmap.set(key, value); - if (!hmap.has(key)) { - if (!omap) { omap = new OurWeakMap(); } - omap.set(key, value); - } - return this; - }; - } else { - dset = function(key, value) { - if (enableSwitching) { - try { - hmap.set(key, value); - } catch (e) { - if (!omap) { omap = new OurWeakMap(); } - omap.set___(key, value); - } - } else { - hmap.set(key, value); - } - return this; - }; - } + var store = obj.valueOf(key); + return store && store.identity === key ? + store : hiddenStore(obj, key); + }; +} - function ddelete(key) { - var result = !!hmap['delete'](key); - if (omap) { return omap.delete___(key) || result; } - return result; - } +},{"./hidden-store.js":213}],213:[function(require,module,exports){ +module.exports = hiddenStore; - return Object.create(OurWeakMap.prototype, { - get___: { value: constFunc(dget) }, - has___: { value: constFunc(dhas) }, - set___: { value: constFunc(dset) }, - delete___: { value: constFunc(ddelete) }, - permitHostObjects___: { value: constFunc(function(token) { - if (token === weakMapPermitHostObjects) { - enableSwitching = true; - } else { - throw new Error('bogus call to permitHostObjects___'); - } - })} - }); - } - DoubleWeakMap.prototype = OurWeakMap.prototype; - module.exports = DoubleWeakMap; +function hiddenStore(obj, key) { + var store = { identity: key }; + var valueOf = obj.valueOf; - // define .constructor to hide OurWeakMap ctor - Object.defineProperty(WeakMap.prototype, 'constructor', { - value: WeakMap, - enumerable: false, // as default .constructor is - configurable: true, + Object.defineProperty(obj, "valueOf", { + value: function (value) { + return value !== key ? + valueOf.apply(this, arguments) : store; + }, writable: true - }); - })(); - } else { - // There is no host WeakMap, so we must use the emulation. - - // Emulated WeakMaps are incompatible with native proxies (because proxies - // can observe the hidden name), so we must disable Proxy usage (in - // ArrayLike and Domado, currently). - if (typeof Proxy !== 'undefined') { - Proxy = undefined; - } + }); - module.exports = OurWeakMap; - } -})(); + return store; +} -},{}],464:[function(require,module,exports){ -'use strict' +},{}],214:[function(require,module,exports){ +// Original - @Gozola. +// https://gist.github.com/Gozala/1269991 +// This is a reimplemented version (with a few bug fixes). -var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') +var createStore = require('./create-store.js'); -var TriangleCache = new weakMap() +module.exports = weakMap; -function createABigTriangle(gl) { +function weakMap() { + var privates = createStore(); - var triangleVAO = TriangleCache.get(gl) - if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) { - var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1])) - triangleVAO = createVAO(gl, [ - { buffer: buf, - type: gl.FLOAT, - size: 2 - } - ]) - triangleVAO._triangleBuffer = buf - TriangleCache.set(gl, triangleVAO) - } - triangleVAO.bind() - gl.drawArrays(gl.TRIANGLES, 0, 3) - triangleVAO.unbind() + return { + 'get': function (key, fallback) { + var store = privates(key) + return store.hasOwnProperty('value') ? + store.value : fallback + }, + 'set': function (key, value) { + privates(key).value = value; + }, + 'has': function(key) { + return 'value' in privates(key); + }, + 'delete': function (key) { + return delete privates(key).value; + } + } } -module.exports = createABigTriangle - -},{"gl-buffer":455,"gl-vao":462,"weak-map":463}],465:[function(require,module,exports){ +},{"./create-store.js":212}],215:[function(require,module,exports){ 'use strict' -module.exports = createAxes +module.exports = createSpikes2D -var createText = require('./lib/text.js') -var createLines = require('./lib/lines.js') -var createBackground = require('./lib/background.js') -var getCubeProperties = require('./lib/cube.js') -var Ticks = require('./lib/ticks.js') +function GLSpikes2D(plot) { + this.plot = plot + this.enable = [true, true, false, false] + this.width = [1, 1, 1, 1] + this.color = [[0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]] + this.center = [Infinity, Infinity] +} -var identity = new Float32Array([ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]) +var proto = GLSpikes2D.prototype -function copyVec3(a, b) { - a[0] = b[0] - a[1] = b[1] - a[2] = b[2] - return a +proto.update = function(options) { + options = options || {} + this.enable = (options.enable || [true,true,false,false]).slice() + this.width = (options.width || [1,1,1,1]).slice() + this.color = (options.color || [ + [0,0,0,1], + [0,0,0,1], + [0,0,0,1], + [0,0,0,1]]).map(function(x) { return x.slice() }) + this.center = (options.center || [Infinity,Infinity]).slice() + this.plot.setOverlayDirty() } -function Axes(gl) { - this.gl = gl +proto.draw = function() { + var spikeEnable = this.enable + var spikeWidth = this.width + var spikeColor = this.color + var spikeCenter = this.center + var plot = this.plot + var line = plot.line - this.pixelRatio = 1 + var dataBox = plot.dataBox + var viewPixels = plot.viewBox - this.bounds = [ [-10, -10, -10], - [ 10, 10, 10] ] - this.ticks = [ [], [], [] ] - this.autoTicks = true - this.tickSpacing = [ 1, 1, 1 ] + line.bind() - this.tickEnable = [ true, true, true ] - this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ] - this.tickSize = [ 12, 12, 12 ] - this.tickAngle = [ 0, 0, 0 ] - this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.tickPad = [ 10, 10, 10 ] + if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] && + dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) { - this.lastCubeProps = { - cubeEdges: [0,0,0], - axis: [0,0,0] - } + var centerX = viewPixels[0] + (spikeCenter[0] - dataBox[0]) / (dataBox[2] - dataBox[0]) * (viewPixels[2] - viewPixels[0]) + var centerY = viewPixels[1] + (spikeCenter[1] - dataBox[1]) / (dataBox[3] - dataBox[1]) * (viewPixels[3] - viewPixels[1]) - this.labels = [ 'x', 'y', 'z' ] - this.labelEnable = [ true, true, true ] - this.labelFont = 'sans-serif' - this.labelSize = [ 20, 20, 20 ] - this.labelAngle = [ 0, 0, 0 ] - this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.labelPad = [ 10, 10, 10 ] + if(spikeEnable[0]) { + line.drawLine( + centerX, centerY, + viewPixels[0], centerY, + spikeWidth[0], spikeColor[0]) + } + if(spikeEnable[1]) { + line.drawLine( + centerX, centerY, + centerX, viewPixels[1], + spikeWidth[1], spikeColor[1]) + } + if(spikeEnable[2]) { + line.drawLine( + centerX, centerY, + viewPixels[2], centerY, + spikeWidth[2], spikeColor[2]) + } + if(spikeEnable[3]) { + line.drawLine( + centerX, centerY, + centerX, viewPixels[3], + spikeWidth[3], spikeColor[3]) + } + } +} - this.lineEnable = [ true, true, true ] - this.lineMirror = [ false, false, false ] - this.lineWidth = [ 1, 1, 1 ] - this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] +proto.dispose = function() { + this.plot.removeOverlay(this) +} - this.lineTickEnable = [ true, true, true ] - this.lineTickMirror = [ false, false, false ] - this.lineTickLength = [ 0, 0, 0 ] - this.lineTickWidth = [ 1, 1, 1 ] - this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] +function createSpikes2D(plot, options) { + var spikes = new GLSpikes2D(plot) + spikes.update(options) + plot.addOverlay(spikes) + return spikes +} - this.gridEnable = [ true, true, true ] - this.gridWidth = [ 1, 1, 1 ] - this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] +},{}],216:[function(require,module,exports){ +var createShader = require('gl-shader') - this.zeroEnable = [ true, true, true ] - this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ] - this.zeroLineWidth = [ 2, 2, 2 ] - this.backgroundEnable = [ false, false, false ] - this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5], - [0.8, 0.8, 0.8, 0.5], - [0.8, 0.8, 0.8, 0.5] ] +var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n" +var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n" +var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n" +var pickSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n" - this._firstInit = true - this._text = null - this._lines = null - this._background = createBackground(gl) +exports.createShader = function (gl) { + var shader = createShader(gl, vertSrc, fragSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + shader.attributes.normal.location = 2 + return shader +} +exports.createPickShader = function (gl) { + var shader = createShader(gl, vertSrc, pickSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'vec3'}, + {name: 'normal', type: 'vec3'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + shader.attributes.normal.location = 2 + return shader +} +exports.createContourShader = function (gl) { + var shader = createShader(gl, contourVertSrc, fragSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'float'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + return shader +} +exports.createPickContourShader = function (gl) { + var shader = createShader(gl, contourVertSrc, pickSrc, null, [ + {name: 'uv', type: 'vec4'}, + {name: 'f', type: 'float'} + ]) + shader.attributes.uv.location = 0 + shader.attributes.f.location = 1 + return shader } -var proto = Axes.prototype +},{"gl-shader":197}],217:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],218:[function(require,module,exports){ +'use strict' -proto.update = function(options) { - options = options || {} +module.exports = gradient - //Option parsing helper functions - function parseOption(nest, cons, name) { - if(name in options) { - var opt = options[name] - var prev = this[name] - var next - if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : - Array.isArray(opt) ) { - this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] - } else { - this[name] = next = [ cons(opt), cons(opt), cons(opt) ] - } - for(var i=0; i<3; ++i) { - if(next[i] !== prev[i]) { - return true - } - } - } - return false - } +var dup = require('dup') +var cwiseCompiler = require('cwise-compiler') - var NUMBER = parseOption.bind(this, false, Number) - var BOOLEAN = parseOption.bind(this, false, Boolean) - var STRING = parseOption.bind(this, false, String) - var COLOR = parseOption.bind(this, true, function(v) { - if(Array.isArray(v)) { - if(v.length === 3) { - return [ +v[0], +v[1], +v[2], 1.0 ] - } else if(v.length === 4) { - return [ +v[0], +v[1], +v[2], +v[3] ] - } - } - return [ 0, 0, 0, 1 ] - }) +var TEMPLATE_CACHE = {} +var GRADIENT_CACHE = {} - //Tick marks and bounds - var nextTicks - var ticksUpdate = false - var boundsChanged = false - if('bounds' in options) { - var bounds = options.bounds -i_loop: - for(var i=0; i<2; ++i) { - for(var j=0; j<3; ++j) { - if(bounds[i][j] !== this.bounds[i][j]) { - boundsChanged = true - } - this.bounds[i][j] = bounds[i][j] - } - } - } - if('ticks' in options) { - nextTicks = options.ticks - ticksUpdate = true - this.autoTicks = false - for(var i=0; i<3; ++i) { - this.tickSpacing[i] = 0.0 - } - } else if(NUMBER('tickSpacing')) { - this.autoTicks = true - boundsChanged = true - } +var EmptyProc = { + body: "", + args: [], + thisVars: [], + localVars: [] +} - if(this._firstInit) { - if(!('ticks' in options || 'tickSpacing' in options)) { - this.autoTicks = true - } +var centralDiff = cwiseCompiler({ + args: [ 'array', 'array', 'array' ], + pre: EmptyProc, + post: EmptyProc, + body: { + args: [ { + name: 'out', + lvalue: true, + rvalue: false, + count: 1 + }, { + name: 'left', + lvalue: false, + rvalue: true, + count: 1 + }, { + name: 'right', + lvalue: false, + rvalue: true, + count: 1 + }], + body: "out=0.5*(left-right)", + thisVars: [], + localVars: [] + }, + funcName: 'cdiff' +}) - //Force tick recomputation on first update - boundsChanged = true - ticksUpdate = true - this._firstInit = false - } +var zeroOut = cwiseCompiler({ + args: [ 'array' ], + pre: EmptyProc, + post: EmptyProc, + body: { + args: [ { + name: 'out', + lvalue: true, + rvalue: false, + count: 1 + }], + body: "out=0", + thisVars: [], + localVars: [] + }, + funcName: 'zero' +}) - if(boundsChanged && this.autoTicks) { - nextTicks = Ticks.create(this.bounds, this.tickSpacing) - ticksUpdate = true +function generateTemplate(d) { + if(d in TEMPLATE_CACHE) { + return TEMPLATE_CACHE[d] } - - //Compare next ticks to previous ticks, only update if needed - if(ticksUpdate) { - for(var i=0; i<3; ++i) { - nextTicks[i].sort(function(a,b) { - return a.x-b.x - }) - } - if(Ticks.equal(nextTicks, this.ticks)) { - ticksUpdate = false - } else { - this.ticks = nextTicks - } + var code = [] + for(var i=0; i= 0) { + pickStr.push('0') + } else if(facet.indexOf(-(i+1)) >= 0) { + pickStr.push('s['+i+']-1') + } else { + pickStr.push('-1') + loStr.push('1') + hiStr.push('s['+i+']-2') + } + } + var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')' + if(loStr.length === 0) { + boundStr = '' + } + + if(cod > 0) { + code.push('if(1') + for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { + continue + } + code.push('&&s[', i, ']>2') + } + code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) + for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { + continue + } + code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr) + } + code.push(');') + } - //Grid lines - BOOLEAN('gridEnable') - NUMBER('gridWidth') - COLOR('gridColor') + for(var i=0; i1){dst.set(', + pickStr.join(), ',', bnd, ',0.5*(src.get(', + cPickStr.join(), ')-src.get(', + dPickStr.join(), ')))}else{dst.set(', + pickStr.join(), ',', bnd, ',0)};') + } else { + code.push('if(s[', bnd, ']>1){diff(', outStr, + ',src.pick(', cPickStr.join(), ')', boundStr, + ',src.pick(', dPickStr.join(), ')', boundStr, + ');}else{zero(', outStr, ');};') + } + break + + case 'mirror': + if(cod === 0) { + code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') + } else { + code.push('zero(', outStr, ');') + } + break + + case 'wrap': + var aPickStr = pickStr.slice() + var bPickStr = pickStr.slice() + if(facet[i] < 0) { + aPickStr[bnd] = 's[' + bnd + ']-2' + bPickStr[bnd] = '0' + + } else { + aPickStr[bnd] = 's[' + bnd + ']-1' + bPickStr[bnd] = '1' + } + if(cod === 0) { + code.push('if(s[', bnd, ']>2){dst.set(', + pickStr.join(), ',', bnd, ',0.5*(src.get(', + aPickStr.join(), ')-src.get(', + bPickStr.join(), ')))}else{dst.set(', + pickStr.join(), ',', bnd, ',0)};') + } else { + code.push('if(s[', bnd, ']>2){diff(', outStr, + ',src.pick(', aPickStr.join(), ')', boundStr, + ',src.pick(', bPickStr.join(), ')', boundStr, + ');}else{zero(', outStr, ');};') + } + break - //Background - BOOLEAN('backgroundEnable') - COLOR('backgroundColor') + default: + throw new Error('ndarray-gradient: Invalid boundary condition') + } + } - //Update text if necessary - if(!this._text) { - this._text = createText( - this.gl, - this.bounds, - this.labels, - this.labelFont, - this.ticks, - this.tickFont) - } else if(this._text && (labelUpdate || ticksUpdate)) { - this._text.update( - this.bounds, - this.labels, - this.labelFont, - this.ticks, - this.tickFont) + if(cod > 0) { + code.push('};') + } } - //Update lines if necessary - if(this._lines && ticksUpdate) { - this._lines.dispose() - this._lines = null - } - if(!this._lines) { - this._lines = createLines(this.gl, this.bounds, this.ticks) + //Enumerate ridges, facets, etc. of hypercube + for(var i=0; i<(1< 0) { - c[j] = -1 - d[j] = 0 - } else { - c[j] = 0 - d[j] = +1 + } else if(typeof bc === 'string') { + bc = dup(inp.dimension, bc) + } else { + bc = dup(inp.dimension, 'clamp') + } + if(out.dimension !== inp.dimension + 1) { + throw new Error('ndarray-gradient: output dimension must be +1 input dimension') + } + if(out.shape[inp.dimension] !== inp.dimension) { + throw new Error('ndarray-gradient: output shape must match input shape') + } + for(var i=0; i 0) { - x[i] = bounds[1][i] - } else { - x[i] = bounds[0][i] - } + this._contourShader = contourShader + this._contourPickShader = contourPickShader + this._contourBuffer = contourBuffer + this._contourVAO = contourVAO + this._contourOffsets = [[], [], []] + this._contourCounts = [[], [], []] + this._vertexCount = 0 - //Draw grid lines - for(var j=0; j<2; ++j) { - var u = (i + 1 + j) % 3 - var v = (i + 1 + (j^1)) % 3 - if(this.gridEnable[u]) { - this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio) - } - } + this._pickResult = new SurfacePickResult([0, 0, 0], [0, 0], [0, 0], [0, 0, 0], [0, 0, 0]) - //Draw zero lines (need to do this AFTER all grid lines are drawn) - for(var j=0; j<2; ++j) { - var u = (i + 1 + j) % 3 - var v = (i + 1 + (j^1)) % 3 - if(this.zeroEnable[v]) { - //Check if zero line in bounds - if(bounds[0][v] <= 0 && bounds[1][v] >= 0) { - this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio) - } - } - } - } + this._dynamicBuffer = dynamicBuffer + this._dynamicVAO = dynamicVAO + this._dynamicOffsets = [0, 0, 0] + this._dynamicCounts = [0, 0, 0] - //Then draw axis lines and tick marks - for(var i=0; i<3; ++i) { + this.contourWidth = [ 1, 1, 1 ] + this.contourLevels = [[1], [1], [1]] + this.contourTint = [0, 0, 0] + this.contourColor = [[0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1]] - //Draw axis lines - if(this.lineEnable[i]) { - this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) - } - if(this.lineMirror[i]) { - this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio) - } + this.showContour = true + this.showSurface = true - //Compute minor axes - var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor) - var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor) - var tickLength = this.lineTickLength - var op = 0 - for(var j=0; j<3; ++j) { - var scaleFactor = pixelScaleF / model[5*j] - primalMinor[j] *= tickLength[j] * scaleFactor - mirrorMinor[j] *= tickLength[j] * scaleFactor - } + this.enableHighlight = [true, true, true] + this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]] + this.highlightTint = [ 1, 1, 1 ] + this.highlightLevel = [-1, -1, -1] - //Draw axis line ticks - if(this.lineTickEnable[i]) { - this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) - } - if(this.lineTickMirror[i]) { - this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio) - } - } + // Dynamic contour options + this.enableDynamic = [ true, true, true ] + this.dynamicLevel = [ NaN, NaN, NaN ] + this.dynamicColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ] + this.dynamicTint = [ 1, 1, 1 ] + this.dynamicWidth = [ 1, 1, 1 ] - //Draw text sprites - this._text.bind( - model, - view, - projection, - this.pixelRatio) + this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]] + this.surfaceProject = [ false, false, false ] + this.contourProject = [[ false, false, false ], + [ false, false, false ], + [ false, false, false ]] - for(var i=0; i<3; ++i) { + this.colorBounds = [ false, false ] - var minor = lineOffset[i].primalMinor - var offset = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset) + // Store xyz fields, need this for picking + this._field = [ + ndarray(pool.mallocFloat(1024), [0, 0]), + ndarray(pool.mallocFloat(1024), [0, 0]), + ndarray(pool.mallocFloat(1024), [0, 0]) ] - for(var j=0; j<3; ++j) { - if(this.lineTickEnable[i]) { - offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0) / model[5*j] - } - } + this.pickId = 1 + this.clipBounds = [[-Infinity, -Infinity, -Infinity], [Infinity, Infinity, Infinity]] - //Draw tick text - if(this.tickEnable[i]) { + this.snapToData = false - //Add tick padding - for(var j=0; j<3; ++j) { - offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j] - } + this.opacity = 1.0 - //Draw axis - this._text.drawTicks( - i, - this.tickSize[i], - this.tickAngle[i], - offset, - this.tickColor[i]) - } + this.lightPosition = [10, 10000, 0] + this.ambientLight = 0.8 + this.diffuseLight = 0.8 + this.specularLight = 2.0 + this.roughness = 0.5 + this.fresnel = 1.5 - //Draw labels - if(this.labelEnable[i]) { + this.dirty = true +} - //Add label padding - for(var j=0; j<3; ++j) { - offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j] - } - offset[i] += 0.5 * (bounds[0][i] + bounds[1][i]) +var proto = SurfacePlot.prototype - //Draw axis - this._text.drawLabel( - i, - this.labelSize[i], - this.labelAngle[i], - offset, - this.labelColor[i]) +proto.isTransparent = function () { + return this.opacity < 1 +} + +proto.isOpaque = function () { + if (this.opacity >= 1) { + return true + } + for (var i = 0; i < 3; ++i) { + if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) { + return true } } + return false } -proto.dispose = function() { - this._text.dispose() - this._lines.dispose() - this._background.dispose() - this._lines = null - this._text = null - this._background = null - this.gl = null -} +proto.pickSlots = 1 -function createAxes(gl, options) { - var axes = new Axes(gl) - axes.update(options) - return axes +proto.setPickBase = function (id) { + this.pickId = id } -},{"./lib/background.js":466,"./lib/cube.js":467,"./lib/lines.js":468,"./lib/text.js":470,"./lib/ticks.js":471}],466:[function(require,module,exports){ -'use strict' - -module.exports = createBackgroundCube - -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createShader = require('./shaders').bg +var ZERO_VEC = [0, 0, 0] -function BackgroundCube(gl, buffer, vao, shader) { - this.gl = gl - this.buffer = buffer - this.vao = vao - this.shader = shader +var PROJECT_DATA = { + showSurface: false, + showContour: false, + projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()], + clipBounds: [ + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]], + [[0, 0, 0], [0, 0, 0]]] } -var proto = BackgroundCube.prototype - -proto.draw = function(model, view, projection, bounds, enable, colors) { - var needsBG = false - for(var i=0; i<3; ++i) { - needsBG = needsBG || enable[i] - } - if(!needsBG) { - return - } +function computeProjectionData (camera, obj) { + var i, j, k - var gl = this.gl + // Compute cube properties + var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC - gl.enable(gl.POLYGON_OFFSET_FILL) - gl.polygonOffset(1, 2) + var showSurface = obj.showSurface + var showContour = obj.showContour - this.shader.bind() - this.shader.uniforms = { - model: model, - view: view, - projection: projection, - bounds: bounds, - enable: enable, - colors: colors + for (i = 0; i < 3; ++i) { + showSurface = showSurface || obj.surfaceProject[i] + for (j = 0; j < 3; ++j) { + showContour = showContour || obj.contourProject[i][j] + } } - this.vao.bind() - this.vao.draw(this.gl.TRIANGLES, 36) - gl.disable(gl.POLYGON_OFFSET_FILL) -} - -proto.dispose = function() { - this.vao.dispose() - this.buffer.dispose() - this.shader.dispose() -} + for (i = 0; i < 3; ++i) { + // Construct projection onto axis + var axisSquish = PROJECT_DATA.projections[i] + for (j = 0; j < 16; ++j) { + axisSquish[j] = 0 + } + for (j = 0; j < 4; ++j) { + axisSquish[5 * j] = 1 + } + axisSquish[5 * i] = 0 + axisSquish[12 + i] = obj.axesBounds[+(cubeAxis[i] > 0)][i] + multiply(axisSquish, camera.model, axisSquish) -function createBackgroundCube(gl) { - //Create cube vertices - var vertices = [] - var indices = [] - var ptr = 0 - for(var d=0; d<3; ++d) { - var u = (d+1) % 3 - var v = (d+2) % 3 - var x = [0,0,0] - var c = [0,0,0] - for(var s=-1; s<=1; s+=2) { - indices.push(ptr, ptr+2, ptr+1, - ptr+1, ptr+2, ptr+3) - x[d] = s - c[d] = s - for(var i=-1; i<=1; i+=2) { - x[u] = i - for(var j=-1; j<=1; j+=2) { - x[v] = j - vertices.push(x[0], x[1], x[2], - c[0], c[1], c[2]) - ptr += 1 - } + var nclipBounds = PROJECT_DATA.clipBounds[i] + for (k = 0; k < 2; ++k) { + for (j = 0; j < 3; ++j) { + nclipBounds[k][j] = camera.clipBounds[k][j] } - //Swap u and v - var tt = u - u = v - v = tt } + nclipBounds[0][i] = -1e8 + nclipBounds[1][i] = 1e8 } - //Allocate buffer and vertex array - var buffer = createBuffer(gl, new Float32Array(vertices)) - var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER) - var vao = createVAO(gl, [ - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 0, - stride: 24 - }, - { - buffer: buffer, - type: gl.FLOAT, - size: 3, - offset: 12, - stride: 24 - } - ], elements) + PROJECT_DATA.showSurface = showSurface + PROJECT_DATA.showContour = showContour - //Create shader object - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.normal.location = 1 + return PROJECT_DATA +} - return new BackgroundCube(gl, buffer, vao, shader) +var UNIFORMS = { + model: IDENTITY, + view: IDENTITY, + projection: IDENTITY, + inverseModel: IDENTITY.slice(), + lowerBound: [0, 0, 0], + upperBound: [0, 0, 0], + colorMap: 0, + clipBounds: [[0, 0, 0], [0, 0, 0]], + height: 0.0, + contourTint: 0, + contourColor: [0, 0, 0, 1], + permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], + zOffset: -1e-4, + kambient: 1, + kdiffuse: 1, + kspecular: 1, + lightPosition: [1000, 1000, 1000], + eyePosition: [0, 0, 0], + roughness: 1, + fresnel: 1, + opacity: 1 } -},{"./shaders":469,"gl-buffer":475,"gl-vao":480}],467:[function(require,module,exports){ -"use strict" +var MATRIX_INVERSE = IDENTITY.slice() +var DEFAULT_PERM = [1, 0, 0, 0, 1, 0, 0, 0, 1] -module.exports = getCubeEdges +function drawCore (params, transparent) { + params = params || {} + var gl = this.gl -var bits = require('bit-twiddle') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var splitPoly = require('split-polygon') -var orient = require('robust-orientation') + gl.disable(gl.CULL_FACE) -var mvp = new Array(16) -var imvp = new Array(16) -var pCubeVerts = new Array(8) -var cubeVerts = new Array(8) -var x = new Array(3) -var zero3 = [0,0,0] + this._colorMap.bind(0) -;(function() { - for(var i=0; i<8; ++i) { - pCubeVerts[i] =[1,1,1,1] - cubeVerts[i] = [1,1,1] - } -})() + var uniforms = UNIFORMS + uniforms.model = params.model || IDENTITY + uniforms.view = params.view || IDENTITY + uniforms.projection = params.projection || IDENTITY + uniforms.lowerBound = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]] + uniforms.upperBound = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]] + uniforms.contourColor = this.contourColor[0] + uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model) -function transformHg(result, x, mat) { - for(var i=0; i<4; ++i) { - result[i] = mat[12+i] - for(var j=0; j<3; ++j) { - result[i] += x[j]*mat[4*j+i] + for (var i = 0; i < 2; ++i) { + var clipClamped = uniforms.clipBounds[i] + for (var j = 0; j < 3; ++j) { + clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) } } -} - -var FRUSTUM_PLANES = [ - [ 0, 0, 1, 0, 0], - [ 0, 0,-1, 1, 0], - [ 0,-1, 0, 1, 0], - [ 0, 1, 0, 1, 0], - [-1, 0, 0, 1, 0], - [ 1, 0, 0, 1, 0] -] -function polygonArea(p) { - for(var i=0; i o0) { - closest |= 1< o0) { - closest |= 1< cubeVerts[i][1]) { - bottom = i - } - } - - //Find left/right neighbors of bottom vertex - var left = -1 - for(var i=0; i<3; ++i) { - var idx = bottom ^ (1< cubeVerts[right][0]) { - right = idx - } - } - - //Determine edge axis coordinates - var cubeEdges = CUBE_EDGES - cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0 - cubeEdges[bits.log2(left^bottom)] = bottom&left - cubeEdges[bits.log2(bottom^right)] = bottom&right - var top = right ^ 7 - if(top === closest || top === farthest) { - top = left ^ 7 - cubeEdges[bits.log2(right^top)] = top&right - } else { - cubeEdges[bits.log2(left^top)] = top&left - } - - //Determine visible faces - var axis = CUBE_AXIS - var cutCorner = closest - for(var d=0; d<3; ++d) { - if(cutCorner & (1<> 4) / 16.0) / 255.0 + var ix = Math.floor(x) + var fx = x - ix -proto.dispose = function() { - this.vao.dispose() - this.vertBuffer.dispose() - this.shader.dispose() -} + var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0 + var iy = Math.floor(y) + var fy = y - iy -function createLines(gl, bounds, ticks) { - var vertices = [] - var tickOffset = [0,0,0] - var tickCount = [0,0,0] + ix += 1 + iy += 1 - //Create grid lines for each axis/direction - var gridOffset = [0,0,0] - var gridCount = [0,0,0] + // Compute xyz coordinate + var pos = result.position + pos[0] = pos[1] = pos[2] = 0 + for (var dx = 0; dx < 2; ++dx) { + var s = dx ? fx : 1.0 - fx + for (var dy = 0; dy < 2; ++dy) { + var t = dy ? fy : 1.0 - fy - //Add zero line - vertices.push( - 0,0,1, 0,1,1, 0,0,-1, - 0,0,-1, 0,1,1, 0,1,-1) + var r = ix + dx + var c = iy + dy + var w = s * t - for(var i=0; i<3; ++i) { - //Axis tick marks - var start = ((vertices.length / 3)|0) - for(var j=0; j 0) { + levelIndex[j] = 0 + } + } else if (levelIndex[j] < this.contourLevels[j].length - 1) { + var a = this.contourLevels[j][levelIndex[j]] + var b = this.contourLevels[j][levelIndex[j] + 1] + if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) { + levelIndex[j] += 1 + } } - var end = ((vertices.length / 3)|0) - gridOffset[i] = start - gridCount[i] = end - start } - //Create cube VAO - var vertBuf = createBuffer(gl, new Float32Array(vertices)) - var vao = createVAO(gl, [ - { "buffer": vertBuf, - "type": gl.FLOAT, - "size": 3, - "stride": 0, - "offset": 0 - } - ]) - var shader = createShader(gl) - shader.attributes.position.location = 0 - return new Lines(gl, vertBuf, vao, shader, tickCount, tickOffset, gridCount, gridOffset) + result.index[0] = fx < 0.5 ? ix : (ix + 1) + result.index[1] = fy < 0.5 ? iy : (iy + 1) + + result.uv[0] = x / shape[0] + result.uv[1] = y / shape[1] + + for (i = 0; i < 3; ++i) { + result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]) + } + + return result } -},{"./shaders":469,"gl-buffer":475,"gl-vao":480}],469:[function(require,module,exports){ -'use strict' +function padField (nfield, field) { + var shape = field.shape.slice() + var nshape = nfield.shape.slice() + // Center + ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) -var createShader = require('gl-shader') + // Edges + ops.assign(nfield.lo(1).hi(shape[0], 1), + field.hi(shape[0], 1)) + ops.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), + field.lo(0, shape[1] - 1).hi(shape[0], 1)) + ops.assign(nfield.lo(0, 1).hi(1, shape[1]), + field.hi(1)) + ops.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), + field.lo(shape[0] - 1)) + // Corners + nfield.set(0, 0, field.get(0, 0)) + nfield.set(0, nshape[1] - 1, field.get(0, shape[1] - 1)) + nfield.set(nshape[0] - 1, 0, field.get(shape[0] - 1, 0)) + nfield.set(nshape[0] - 1, nshape[1] - 1, field.get(shape[0] - 1, shape[1] - 1)) +} -var lineVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n vec4 pp = projection * view * model * vec4(p, 1.0);\n return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n vec3 major = position.x * majorAxis;\n vec3 minor = position.y * minorAxis;\n\n vec3 vPosition = major + minor + offset;\n vec3 pPosition = project(vPosition);\n vec3 offset = project(vPosition + screenAxis * position.z);\n\n vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n" -var lineFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" -exports.line = function(gl) { - return createShader(gl, lineVert, lineFrag, null, [ - {name: 'position', type: 'vec3'} - ]) +function handleArray (param, ctor) { + if (Array.isArray(param)) { + return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ] + } + return [ ctor(param), ctor(param), ctor(param) ] } -var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() { \n //Compute plane offset\n vec2 planeCoord = position.xy * pixelScale;\n mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n -sin(angle), cos(angle));\n vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n //Compute world offset\n float axisDistance = position.z;\n vec3 dataPosition = axisDistance * axis + offset;\n vec4 worldPosition = model * vec4(dataPosition, 1);\n \n //Compute clip position\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n\n //Apply text offset in clip coordinates\n clipPosition += vec4(viewOffset, 0, 0);\n\n //Done\n gl_Position = clipPosition;\n}" -var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = color;\n}" -exports.text = function(gl) { - return createShader(gl, textVert, textFrag, null, [ - {name: 'position', type: 'vec3'} - ]) +function toColor (x) { + if (Array.isArray(x)) { + if (x.length === 3) { + return [x[0], x[1], x[2], 1] + } + return [x[0], x[1], x[2], x[3]] + } + return [0, 0, 0, 1] } -var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n if(dot(normal, enable) > 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n gl_Position = projection * view * model * vec4(nPosition, 1.0);\n } else {\n gl_Position = vec4(0,0,0,0);\n }\n colorChannel = abs(normal);\n}" -var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n gl_FragColor = colorChannel.x * colors[0] + \n colorChannel.y * colors[1] +\n colorChannel.z * colors[2];\n}" -exports.bg = function(gl) { - return createShader(gl, bgVert, bgFrag, null, [ - {name: 'position', type: 'vec3'}, - {name: 'normal', type: 'vec3'} - ]) +function handleColor (param) { + if (Array.isArray(param)) { + if (Array.isArray(param)) { + return [ + toColor(param[0]), + toColor(param[1]), + toColor(param[2]) ] + } else { + var c = toColor(param) + return [ + c.slice(), + c.slice(), + c.slice() ] + } + } } -},{"gl-shader":590}],470:[function(require,module,exports){ -(function (process){ -"use strict" +proto.update = function (params) { + params = params || {} -module.exports = createTextSprites + this.dirty = true -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var vectorizeText = require('vectorize-text') -var createShader = require('./shaders').text + if ('contourWidth' in params) { + this.contourWidth = handleArray(params.contourWidth, Number) + } + if ('showContour' in params) { + this.showContour = handleArray(params.showContour, Boolean) + } + if ('showSurface' in params) { + this.showSurface = !!params.showSurface + } + if ('contourTint' in params) { + this.contourTint = handleArray(params.contourTint, Boolean) + } + if ('contourColor' in params) { + this.contourColor = handleColor(params.contourColor) + } + if ('contourProject' in params) { + this.contourProject = handleArray(params.contourProject, function (x) { + return handleArray(x, Boolean) + }) + } + if ('surfaceProject' in params) { + this.surfaceProject = params.surfaceProject + } + if ('dynamicColor' in params) { + this.dynamicColor = handleColor(params.dynamicColor) + } + if ('dynamicTint' in params) { + this.dynamicTint = handleArray(params.dynamicTint, Number) + } + if ('dynamicWidth' in params) { + this.dynamicWidth = handleArray(params.dynamicWidth, Number) + } + if ('opacity' in params) { + this.opacity = params.opacity + } + if ('colorBounds' in params) { + this.colorBounds = params.colorBounds + } -var globals = window || process.global || {} -var __TEXT_CACHE = globals.__TEXT_CACHE || {} -globals.__TEXT_CACHE = {} + var field = params.field || (params.coords && params.coords[2]) || null + var levelsChanged = false -//Vertex buffer format for text is: -// -/// [x,y,z] = Spatial coordinate -// + if (!field) { + if (this._field[2].shape[0] || this._field[2].shape[2]) { + field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2) + } else { + field = this._field[2].hi(0, 0) + } + } -var VERTEX_SIZE = 3 -var VERTEX_STRIDE = VERTEX_SIZE * 4 + // Update field + if ('field' in params || 'coords' in params) { + var fsize = (field.shape[0] + 2) * (field.shape[1] + 2) -function TextSprites( - gl, - shader, - buffer, - vao) { - this.gl = gl - this.shader = shader - this.buffer = buffer - this.vao = vao - this.tickOffset = - this.tickCount = - this.labelOffset = - this.labelCount = null -} + // Resize if necessary + if (fsize > this._field[2].data.length) { + pool.freeFloat(this._field[2].data) + this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize)) + } -var proto = TextSprites.prototype + // Pad field + this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) + padField(this._field[2], field) -//Bind textures for rendering -var SHAPE = [0,0] -proto.bind = function(model, view, projection, pixelScale) { - this.vao.bind() - this.shader.bind() - var uniforms = this.shader.uniforms - uniforms.model = model - uniforms.view = view - uniforms.projection = projection - uniforms.pixelScale = pixelScale - SHAPE[0] = this.gl.drawingBufferWidth - SHAPE[1] = this.gl.drawingBufferHeight - this.shader.uniforms.resolution = SHAPE -} + // Save shape of field + this.shape = field.shape.slice() + var shape = this.shape + + // Resize coordinate fields if necessary + for (var i = 0; i < 2; ++i) { + if (this._field[2].size > this._field[i].data.length) { + pool.freeFloat(this._field[i].data) + this._field[i].data = pool.mallocFloat(this._field[2].size) + } + this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]) + } + + // Generate x/y coordinates + if (params.coords) { + var coords = params.coords + if (!Array.isArray(coords) || coords.length !== 3) { + throw new Error('gl-surface: invalid coordinates for x/y') + } + for (i = 0; i < 2; ++i) { + var coord = coords[i] + for (j = 0; j < 2; ++j) { + if (coord.shape[j] !== shape[j]) { + throw new Error('gl-surface: coords have incorrect shape') + } + } + padField(this._field[i], coord) + } + } else if (params.ticks) { + var ticks = params.ticks + if (!Array.isArray(ticks) || ticks.length !== 2) { + throw new Error('gl-surface: invalid ticks') + } + for (i = 0; i < 2; ++i) { + var tick = ticks[i] + if (Array.isArray(tick) || tick.length) { + tick = ndarray(tick) + } + if (tick.shape[0] !== shape[i]) { + throw new Error('gl-surface: invalid tick length') + } + // Make a copy view of the tick array + var tick2 = ndarray(tick.data, shape) + tick2.stride[i] = tick.stride[0] + tick2.stride[i ^ 1] = 0 + + // Fill in field array + padField(this._field[i], tick2) + } + } else { + for (i = 0; i < 2; ++i) { + var offset = [0, 0] + offset[i] = 1 + this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) + } + this._field[0].set(0, 0, 0) + for (var j = 0; j < shape[0]; ++j) { + this._field[0].set(j + 1, 0, j) + } + this._field[0].set(shape[0] + 1, 0, shape[0] - 1) + this._field[1].set(0, 0, 0) + for (j = 0; j < shape[1]; ++j) { + this._field[1].set(0, j + 1, j) + } + this._field[1].set(0, shape[1] + 1, shape[1] - 1) + } -proto.update = function(bounds, labels, labelFont, ticks, tickFont) { - var gl = this.gl - var data = [] + // Save shape + var fields = this._field - function addItem(t, text, font, size) { - var fontcache = __TEXT_CACHE[font] - if(!fontcache) { - fontcache = __TEXT_CACHE[font] = {} - } - var mesh = fontcache[text] - if(!mesh) { - mesh = fontcache[text] = tryVectorizeText(text, { - triangles: true, - font: font, - textAlign: 'center', - textBaseline: 'middle' - }) - } - var scale = (size || 12) / 12 - var positions = mesh.positions - var cells = mesh.cells - var lo = [ Infinity, Infinity] - var hi = [-Infinity,-Infinity] - for(var i=0, nc=cells.length; i=0; --j) { - var p = positions[c[j]] - data.push(scale*p[0], -scale*p[1], t) - } + // Compute surface normals + var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) + for (i = 0; i < 3; ++i) { + gradient(dfields.pick(i), fields[i], 'mirror') } - } + var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) + for (i = 0; i < shape[0] + 2; ++i) { + for (j = 0; j < shape[1] + 2; ++j) { + var dxdu = dfields.get(0, i, j, 0) + var dxdv = dfields.get(0, i, j, 1) + var dydu = dfields.get(1, i, j, 0) + var dydv = dfields.get(1, i, j, 1) + var dzdu = dfields.get(2, i, j, 0) + var dzdv = dfields.get(2, i, j, 1) - //Generate sprites for all 3 axes, store data in texture atlases - var tickOffset = [0,0,0] - var tickCount = [0,0,0] - var labelOffset = [0,0,0] - var labelCount = [0,0,0] - for(var d=0; d<3; ++d) { + var nx = dydu * dzdv - dydv * dzdu + var ny = dzdu * dxdv - dzdv * dxdu + var nz = dxdu * dydv - dxdv * dydu - //Generate label - labelOffset[d] = (data.length/VERTEX_SIZE)|0 - addItem(0.5*(bounds[0][d]+bounds[1][d]), labels[d], labelFont) - labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d] + var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) + if (nl < 1e-8) { + nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz)) + if (nl < 1e-8) { + nz = 1.0 + ny = nx = 0.0 + nl = 1.0 + } else { + nl = 1.0 / nl + } + } else { + nl = 1.0 / Math.sqrt(nl) + } - //Generate sprites for tick marks - tickOffset[d] = (data.length/VERTEX_SIZE)|0 - for(var i=0; i= 0) { - sigFigs = stepStr.length - u - 1 - } - var shift = Math.pow(10, sigFigs) - var x = Math.round(spacing * i * shift) - var xstr = x + "" - if(xstr.indexOf("e") >= 0) { - return xstr - } - var xi = x / shift, xf = x % shift - if(x < 0) { - xi = -Math.ceil(xi)|0 - xf = (-xf)|0 - } else { - xi = Math.floor(xi)|0 - xf = xf|0 - } - var xis = "" + xi - if(x < 0) { - xis = "-" + xis - } - if(sigFigs) { - var xs = "" + xf - while(xs.length < sigFigs) { - xs = "0" + xs + if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) { + levelsChanged = true } - return xis + "." + xs - } else { - return xis - } -} -function defaultTicks(bounds, tickSpacing) { - var array = [] - for(var d=0; d<3; ++d) { - var ticks = [] - var m = 0.5*(bounds[0][d]+bounds[1][d]) - for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) { - ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) - } - for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) { - ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)}) - } - array.push(ticks) + // Save intensity bound + this.intensityBounds = [lo_intensity, hi_intensity] } - return array -} -function ticksEqual(ticksA, ticksB) { - for(var i=0; i<3; ++i) { - if(ticksA[i].length !== ticksB[i].length) { - return false + // Update level crossings + if ('levels' in params) { + var levels = params.levels + if (!Array.isArray(levels[0])) { + levels = [ [], [], levels ] + } else { + levels = levels.slice() } - for(var j=0; j 1.0) { - t = 1.0 - } - var ti = 1.0 - t - var n = a.length - var r = new Array(n) - for(var i=0; i 0) || (a > 0 && b < 0)) { - var p = lerpW(s, b, t, a) - pos.push(p) - neg.push(p.slice()) + if (dd < 2) { + f = this._field[iu].get(r, c) + } else { + f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]) + } + if (!isFinite(f) || isNaN(f)) { + hole = true + break dd_loop + } + + var w = s * t + parts[dd] += w * f + } + } + } + + if (!hole) { + contourVerts.push(parts[0], parts[1], p[0], p[1], parts[2]) + vertexCount += 1 + } else { + if (k > 0) { + // If we already added first edge, pop off verts + for (var l = 0; l < 5; ++l) { + contourVerts.pop() + } + vertexCount -= 1 + } + continue edge_loop + } + } + } + levelCounts.push(vertexCount) + } + + // Store results + this._contourOffsets[dim] = levelOffsets + this._contourCounts[dim] = levelCounts } - if(b < 0) { - neg.push(t.slice()) - } else if(b > 0) { - pos.push(t.slice()) - } else { - pos.push(t.slice()) - neg.push(t.slice()) + + var floatBuffer = pool.mallocFloat(contourVerts.length) + for (i = 0; i < contourVerts.length; ++i) { + floatBuffer[i] = contourVerts[i] } - a = b + this._contourBuffer.update(floatBuffer) + pool.freeFloat(floatBuffer) } - return { positive: pos, negative: neg } -} -function positive(points, plane) { - var pos = [] - var a = planeT(points[points.length-1], plane) - for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { - pos.push(lerpW(s, b, t, a)) - } - if(b >= 0) { - pos.push(t.slice()) - } - a = b + if (params.colormap) { + this._colorMap.setPixels(genColormap(params.colormap)) } - return pos } -function negative(points, plane) { - var neg = [] - var a = planeT(points[points.length-1], plane) - for(var s=points[points.length-1], t=points[0], i=0; i 0) || (a > 0 && b < 0)) { - neg.push(lerpW(s, b, t, a)) - } - if(b <= 0) { - neg.push(t.slice()) - } - a = b +proto.dispose = function () { + this._shader.dispose() + this._vao.dispose() + this._coordinateBuffer.dispose() + this._colorMap.dispose() + this._contourBuffer.dispose() + this._contourVAO.dispose() + this._contourShader.dispose() + this._contourPickShader.dispose() + this._dynamicBuffer.dispose() + this._dynamicVAO.dispose() + for (var i = 0; i < 3; ++i) { + pool.freeFloat(this._field[i].data) } - return neg } -},{"robust-dot-product":483,"robust-sum":485}],483:[function(require,module,exports){ -"use strict" -var twoProduct = require("two-product") -var robustSum = require("robust-sum") +proto.highlight = function (selection) { + if (!selection) { + this._dynamicCounts = [0, 0, 0] + this.dyanamicLevel = [NaN, NaN, NaN] + this.highlightLevel = [-1, -1, -1] + return + } -module.exports = robustDotProduct + for (var i = 0; i < 3; ++i) { + if (this.enableHighlight[i]) { + this.highlightLevel[i] = selection.level[i] + } else { + this.highlightLevel[i] = -1 + } + } -function robustDotProduct(a, b) { - var r = twoProduct(a[0], b[0]) - for(var i=1; i_inline_4_arg0_||255>_inline_4_arg1_||255>_inline_4_arg2_||255>_inline_4_arg3_){var _inline_4_l=_inline_4_arg4_-_inline_4_arg6_[0],_inline_4_a=_inline_4_arg5_-_inline_4_arg6_[1],_inline_4_f=_inline_4_l*_inline_4_l+_inline_4_a*_inline_4_a;_inline_4_f maxSize || h < 0 || h > maxSize) { + throw new Error('gl-texture2d: Invalid texture size') + } + tex._shape = [w, h] + tex.bind() + gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null) + tex._mipLevels = [0] + return tex +} - this._readCallback = function() { - if(!self.gl) { - return +function Texture2D(gl, handle, width, height, format, type) { + this.gl = gl + this.handle = handle + this.format = format + this.type = type + this._shape = [width, height] + this._mipLevels = [0] + this._magFilter = gl.NEAREST + this._minFilter = gl.NEAREST + this._wrapS = gl.CLAMP_TO_EDGE + this._wrapT = gl.CLAMP_TO_EDGE + this._anisoSamples = 1 + + var parent = this + var wrapVector = [this._wrapS, this._wrapT] + Object.defineProperties(wrapVector, [ + { + get: function() { + return parent._wrapS + }, + set: function(v) { + return parent.wrapS = v + } + }, + { + get: function() { + return parent._wrapT + }, + set: function(v) { + return parent.wrapT = v + } + } + ]) + this._wrapVector = wrapVector + + var shapeVector = [this._shape[0], this._shape[1]] + Object.defineProperties(shapeVector, [ + { + get: function() { + return parent._shape[0] + }, + set: function(v) { + return parent.width = v + } + }, + { + get: function() { + return parent._shape[1] + }, + set: function(v) { + return parent.height = v + } + } + ]) + this._shapeVector = shapeVector +} + +var proto = Texture2D.prototype + +Object.defineProperties(proto, { + minFilter: { + get: function() { + return this._minFilter + }, + set: function(v) { + this.bind() + var gl = this.gl + if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { + if(!gl.getExtension('OES_texture_float_linear')) { + v = gl.NEAREST + } + } + if(filterTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown filter mode ' + v) + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v) + return this._minFilter = v + } + }, + magFilter: { + get: function() { + return this._magFilter + }, + set: function(v) { + this.bind() + var gl = this.gl + if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) { + if(!gl.getExtension('OES_texture_float_linear')) { + v = gl.NEAREST + } + } + if(filterTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown filter mode ' + v) + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v) + return this._magFilter = v + } + }, + mipSamples: { + get: function() { + return this._anisoSamples + }, + set: function(i) { + var psamples = this._anisoSamples + this._anisoSamples = Math.max(i, 1)|0 + if(psamples !== this._anisoSamples) { + var ext = gl.getExtension('EXT_texture_filter_anisotropic') + if(ext) { + this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples) + } + } + return this._anisoSamples + } + }, + wrapS: { + get: function() { + return this._wrapS + }, + set: function(v) { + this.bind() + if(wrapTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v) + return this._wrapS = v + } + }, + wrapT: { + get: function() { + return this._wrapT + }, + set: function(v) { + this.bind() + if(wrapTypes.indexOf(v) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v) + return this._wrapT = v } - fbo.bind() - gl.readPixels(0,0,fbo.shape[0],fbo.shape[1],gl.RGBA,gl.UNSIGNED_BYTE,self.buffer) - self._readTimeout = null - } -} + }, + wrap: { + get: function() { + return this._wrapVector + }, + set: function(v) { + if(!Array.isArray(v)) { + v = [v,v] + } + if(v.length !== 2) { + throw new Error('gl-texture2d: Must specify wrap mode for rows and columns') + } + for(var i=0; i<2; ++i) { + if(wrapTypes.indexOf(v[i]) < 0) { + throw new Error('gl-texture2d: Unknown wrap mode ' + v) + } + } + this._wrapS = v[0] + this._wrapT = v[1] -var proto = SelectBuffer.prototype + var gl = this.gl + this.bind() + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT) -Object.defineProperty(proto, 'shape', { - get: function() { - if(!this.gl) { - return [0,0] + return v } - return this.fbo.shape.slice() }, - set: function(v) { - if(!this.gl) { - return - } - this.fbo.shape = v - var c = this.fbo.shape[0] - var r = this.fbo.shape[1] - if(r*c*4 > this.buffer.length) { - pool.free(this.buffer) - var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4)) - for(var i=0; i0; ++i, l>>>=1) { + if(this._mipLevels.indexOf(i) < 0) { + this._mipLevels.push(i) + } + } } -proto.drawTransparent = function(camera) {} - -proto.draw = function(camera) { +proto.setPixels = function(data, x_off, y_off, mip_level) { var gl = this.gl - var vao = this.vao - var shader = this.shader - - vao.bind() - shader.bind() - - var model = camera.model || identity - var view = camera.view || identity - var projection = camera.projection || identity - - var axis - if(this.axes) { - axis = this.axes.lastCubeProps.axis + this.bind() + if(Array.isArray(x_off)) { + mip_level = y_off + y_off = x_off[1]|0 + x_off = x_off[0]|0 + } else { + x_off = x_off || 0 + y_off = y_off || 0 } - - var outerFace = OUTER_FACE - var innerFace = INNER_FACE - for(var i=0; i<3; ++i) { - if(axis && axis[i] < 0) { - outerFace[i] = this.bounds[0][i] - innerFace[i] = this.bounds[1][i] + mip_level = mip_level || 0 + if(data instanceof HTMLCanvasElement || + data instanceof ImageData || + data instanceof HTMLImageElement || + data instanceof HTMLVideoElement) { + var needsMip = this._mipLevels.indexOf(mip_level) < 0 + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data) + this._mipLevels.push(mip_level) } else { - outerFace[i] = this.bounds[1][i] - innerFace[i] = this.bounds[0][i] + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data) + } + } else if(data.shape && data.stride && data.data) { + if(data.shape.length < 2 || + x_off + data.shape[1] > this._shape[1]>>>mip_level || + y_off + data.shape[0] > this._shape[0]>>>mip_level || + x_off < 0 || + y_off < 0) { + throw new Error('gl-texture2d: Texture dimensions are out of bounds') } + texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data) + } else { + throw new Error('gl-texture2d: Unsupported data type') } +} - SHAPE[0] = gl.drawingBufferWidth - SHAPE[1] = gl.drawingBufferHeight - - shader.uniforms.model = model - shader.uniforms.view = view - shader.uniforms.projection = projection - shader.uniforms.coordinates = [this.position, outerFace, innerFace] - shader.uniforms.colors = this.colors - shader.uniforms.screenShape = SHAPE - for(var i=0; i<3; ++i) { - shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio - if(this.enabled[i]) { - vao.draw(gl.TRIANGLES, 6, 6*i) - if(this.drawSides[i]) { - vao.draw(gl.TRIANGLES, 12, 18+12*i) - } - } +function isPacked(shape, stride) { + if(shape.length === 3) { + return (stride[2] === 1) && + (stride[1] === shape[0]*shape[2]) && + (stride[0] === shape[2]) } - - vao.unbind() + return (stride[0] === 1) && + (stride[1] === shape[0]) } -proto.update = function(options) { - if(!options) { - return - } - if("bounds" in options) { - this.bounds = options.bounds - } - if("position" in options) { - this.position = options.position +function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) { + var dtype = array.dtype + var shape = array.shape.slice() + if(shape.length < 2 || shape.length > 3) { + throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d') } - if("lineWidth" in options) { - this.lineWidth = options.lineWidth + var type = 0, format = 0 + var packed = isPacked(shape, array.stride.slice()) + if(dtype === 'float32') { + type = gl.FLOAT + } else if(dtype === 'float64') { + type = gl.FLOAT + packed = false + dtype = 'float32' + } else if(dtype === 'uint8') { + type = gl.UNSIGNED_BYTE + } else { + type = gl.UNSIGNED_BYTE + packed = false + dtype = 'uint8' } - if("colors" in options) { - this.colors = options.colors + var channels = 1 + if(shape.length === 2) { + format = gl.LUMINANCE + shape = [shape[0], shape[1], 1] + array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + } else if(shape.length === 3) { + if(shape[2] === 1) { + format = gl.ALPHA + } else if(shape[2] === 2) { + format = gl.LUMINANCE_ALPHA + } else if(shape[2] === 3) { + format = gl.RGB + } else if(shape[2] === 4) { + format = gl.RGBA + } else { + throw new Error('gl-texture2d: Invalid shape for pixel coords') + } + channels = shape[2] + } else { + throw new Error('gl-texture2d: Invalid shape for texture') } - if("enabled" in options) { - this.enabled = options.enabled + //For 1-channel textures allow conversion between formats + if((format === gl.LUMINANCE || format === gl.ALPHA) && + (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) { + format = cformat } - if("drawSides" in options) { - this.drawSides = options.drawSides + if(format !== cformat) { + throw new Error('gl-texture2d: Incompatible texture format for setPixels') } -} - -proto.dispose = function() { - this.vao.dispose() - this.buffer.dispose() - this.shader.dispose() -} - - - -function createSpikes(gl, options) { - //Create buffers - var data = [ ] - - function line(x,y,z,i,l,h) { - var row = [x,y,z, 0,0,0, 1] - row[i+3] = 1 - row[i] = l - data.push.apply(data, row) - row[6] = -1 - data.push.apply(data, row) - row[i] = h - data.push.apply(data, row) - data.push.apply(data, row) - row[6] = 1 - data.push.apply(data, row) - row[i] = l - data.push.apply(data, row) + var size = array.size + var needsMip = mipLevels.indexOf(mip_level) < 0 + if(needsMip) { + mipLevels.push(mip_level) } - - line(0,0,0, 0, 0, 1) - line(0,0,0, 1, 0, 1) - line(0,0,0, 2, 0, 1) - - line(1,0,0, 1, -1,1) - line(1,0,0, 2, -1,1) - - line(0,1,0, 0, -1,1) - line(0,1,0, 2, -1,1) - - line(0,0,1, 0, -1,1) - line(0,0,1, 1, -1,1) - - var buffer = createBuffer(gl, data) - var vao = createVAO(gl, [{ - type: gl.FLOAT, - buffer: buffer, - size: 3, - offset: 0, - stride: 28 - }, { - type: gl.FLOAT, - buffer: buffer, - size: 3, - offset: 12, - stride: 28 - }, { - type: gl.FLOAT, - buffer: buffer, - size: 1, - offset: 24, - stride: 28 - }]) - - //Create shader - var shader = createShader(gl) - shader.attributes.position.location = 0 - shader.attributes.color.location = 1 - shader.attributes.weight.location = 2 - - //Create spike object - var spikes = new AxisSpikes(gl, buffer, vao, shader) - - //Set parameters - spikes.update(options) - - //Return resulting object - return spikes -} - -},{"./shaders/index":624,"gl-buffer":616,"gl-vao":623}],626:[function(require,module,exports){ -'use strict' - -module.exports = createScene - -var createCamera = require('3d-view-controls') -var createAxes = require('gl-axes3d') -var axesRanges = require('gl-axes3d/properties') -var createSpikes = require('gl-spikes3d') -var createSelect = require('gl-select-static') -var createFBO = require('gl-fbo') -var drawTriangle = require('a-big-triangle') -var mouseChange = require('mouse-change') -var perspective = require('gl-mat4/perspective') -var createShader = require('./lib/shader') - -function MouseSelect() { - this.mouse = [-1,-1] - this.screen = null - this.distance = Infinity - this.index = null - this.dataCoordinate = null - this.dataPosition = null - this.object = null - this.data = null -} - -function getContext(canvas, options) { - var gl = null - try { - gl = canvas.getContext('webgl', options) - if(!gl) { - gl = canvas.getContext('experimental-webgl', options) + if(type === ctype && packed) { + //Array data types are compatible, can directly copy into texture + if(array.offset === 0 && array.data.length === size) { + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data) + } + } else { + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size)) + } + } + } else { + //Need to do type conversion to pack data into buffer + var pack_buffer + if(ctype === gl.FLOAT) { + pack_buffer = pool.mallocFloat32(size) + } else { + pack_buffer = pool.mallocUint8(size) + } + var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1]) + if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) { + convertFloatToUint8(pack_view, array) + } else { + ops.assign(pack_view, array) + } + if(needsMip) { + gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size)) + } else { + gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size)) + } + if(ctype === gl.FLOAT) { + pool.freeFloat32(pack_buffer) + } else { + pool.freeUint8(pack_buffer) } - } catch(e) { - return null } - return gl } -function roundUpPow10(x) { - var y = Math.round(Math.log(Math.abs(x)) / Math.log(10)) - if(y < 0) { - var base = Math.round(Math.pow(10, -y)) - return Math.ceil(x*base) / base - } else if(y > 0) { - var base = Math.round(Math.pow(10, y)) - return Math.ceil(x/base) * base - } - return Math.ceil(x) +function initTexture(gl) { + var tex = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, tex) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + return tex } -function defaultBool(x) { - if(typeof x === 'boolean') { - return x +function createTextureShape(gl, width, height, format, type) { + var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(width < 0 || width > maxTextureSize || height < 0 || height > maxTextureSize) { + throw new Error('gl-texture2d: Invalid texture shape') } - return true + if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { + throw new Error('gl-texture2d: Floating point textures not supported on this platform') + } + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null) + return new Texture2D(gl, tex, width, height, format, type) } -function createScene(options) { - options = options || {} - - var stopped = false - - var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio) +function createTextureDOM(gl, element, format, type) { + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element) + return new Texture2D(gl, tex, element.width|0, element.height|0, format, type) +} - var canvas = options.canvas - if(!canvas) { - canvas = document.createElement('canvas') - if(options.container) { - var container = options.container - container.appendChild(canvas) +//Creates a texture from an ndarray +function createTextureArray(gl, array) { + var dtype = array.dtype + var shape = array.shape.slice() + var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE) + if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) { + throw new Error('gl-texture2d: Invalid texture size') + } + var packed = isPacked(shape, array.stride.slice()) + var type = 0 + if(dtype === 'float32') { + type = gl.FLOAT + } else if(dtype === 'float64') { + type = gl.FLOAT + packed = false + dtype = 'float32' + } else if(dtype === 'uint8') { + type = gl.UNSIGNED_BYTE + } else { + type = gl.UNSIGNED_BYTE + packed = false + dtype = 'uint8' + } + var format = 0 + if(shape.length === 2) { + format = gl.LUMINANCE + shape = [shape[0], shape[1], 1] + array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset) + } else if(shape.length === 3) { + if(shape[2] === 1) { + format = gl.ALPHA + } else if(shape[2] === 2) { + format = gl.LUMINANCE_ALPHA + } else if(shape[2] === 3) { + format = gl.RGB + } else if(shape[2] === 4) { + format = gl.RGBA } else { - document.body.appendChild(canvas) + throw new Error('gl-texture2d: Invalid shape for pixel coords') } + } else { + throw new Error('gl-texture2d: Invalid shape for texture') } - - var gl = options.gl - if(!gl) { - gl = getContext(canvas, - options.glOptions || { - premultipliedAlpha: true, - antialias: true - }) + if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) { + type = gl.UNSIGNED_BYTE + packed = false } - if(!gl) { - throw new Error('webgl not supported') + var buffer, buf_store + var size = array.size + if(!packed) { + var stride = [shape[2], shape[2]*shape[0], 1] + buf_store = pool.malloc(size, dtype) + var buf_array = ndarray(buf_store, shape, stride, 0) + if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) { + convertFloatToUint8(buf_array, array) + } else { + ops.assign(buf_array, array) + } + buffer = buf_store.subarray(0, size) + } else if (array.offset === 0 && array.data.length === size) { + buffer = array.data + } else { + buffer = array.data.subarray(array.offset, array.offset + size) } - - //Initial bounds - var bounds = options.bounds || [[-10,-10,-10], [10,10,10]] - - //Create selection - var selection = new MouseSelect() - - //Accumulation buffer - var accumBuffer = createFBO(gl, - [gl.drawingBufferWidth, gl.drawingBufferHeight], { - preferFloat: true - }) - - var accumShader = createShader(gl) - - //Create a camera - var cameraOptions = options.camera || { - eye: [2,0,0], - center: [0,0,0], - up: [0,1,0], - zoomMin: 0.1, - zoomMax: 100, - mode: 'turntable' + var tex = initTexture(gl) + gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer) + if(!packed) { + pool.free(buf_store) } + return new Texture2D(gl, tex, shape[0], shape[1], format, type) +} - //Create axes - var axesOptions = options.axes || {} - var axes = createAxes(gl, axesOptions) - axes.enable = !axesOptions.disable - - //Create spikes - var spikeOptions = options.spikes || {} - var spikes = createSpikes(gl, spikeOptions) - - //Object list is empty initially - var objects = [] - var pickBufferIds = [] - var pickBufferCount = [] - var pickBuffers = [] - - //Dirty flag, skip redraw if scene static - var dirty = true - var pickDirty = true - - var projection = new Array(16) - var model = new Array(16) - - var cameraParams = { - view: null, - projection: projection, - model: model +function createTexture2D(gl) { + if(arguments.length <= 1) { + throw new Error('gl-texture2d: Missing arguments for texture2d constructor') } - - var pickDirty = true - - var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ] - - //Create scene object - var scene = { - gl: gl, - contextLost: false, - pixelRatio: options.pixelRatio || parseFloat(window.devicePixelRatio), - canvas: canvas, - selection: selection, - camera: createCamera(canvas, cameraOptions), - axes: axes, - axesPixels: null, - spikes: spikes, - bounds: bounds, - objects: objects, - shape: viewShape, - aspect: options.aspectRatio || [1,1,1], - pickRadius: options.pickRadius || 10, - zNear: options.zNear || 0.01, - zFar: options.zFar || 1000, - fovy: options.fovy || Math.PI/4, - clearColor: options.clearColor || [0,0,0,0], - autoResize: defaultBool(options.autoResize), - autoBounds: defaultBool(options.autoBounds), - autoScale: !!options.autoScale, - autoCenter: defaultBool(options.autoCenter), - clipToBounds: defaultBool(options.clipToBounds), - snapToData: !!options.snapToData, - onselect: options.onselect || null, - onrender: options.onrender || null, - onclick: options.onclick || null, - cameraParams: cameraParams, - oncontextloss: null, - mouseListener: null + if(!linearTypes) { + lazyInitLinearTypes(gl) } - - var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ] - - function resizeListener() { - if(stopped) { - return - } - if(!scene.autoResize) { - return - } - var parent = canvas.parentNode - var width = 1 - var height = 1 - if(parent && parent !== document.body) { - width = parent.clientWidth - height = parent.clientHeight - } else { - width = window.innerWidth - height = window.innerHeight - } - var nextWidth = Math.ceil(width * scene.pixelRatio)|0 - var nextHeight = Math.ceil(height * scene.pixelRatio)|0 - if(nextWidth !== canvas.width || nextHeight !== canvas.height) { - canvas.width = nextWidth - canvas.height = nextHeight - var style = canvas.style - style.position = style.position || 'absolute' - style.left = '0px' - style.top = '0px' - style.width = width + 'px' - style.height = height + 'px' - dirty = true - } + if(typeof arguments[1] === 'number') { + return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE) } - if(scene.autoResize) { - resizeListener() + if(Array.isArray(arguments[1])) { + return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) } - window.addEventListener('resize', resizeListener) + if(typeof arguments[1] === 'object') { + var obj = arguments[1] + if(obj instanceof HTMLCanvasElement || + obj instanceof HTMLImageElement || + obj instanceof HTMLVideoElement || + obj instanceof ImageData) { + return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE) + } else if(obj.shape && obj.data && obj.stride) { + return createTextureArray(gl, obj) + } + } + throw new Error('gl-texture2d: Invalid arguments for texture2d constructor') +} - function reallocPickIds() { - var numObjs = objects.length - var numPick = pickBuffers.length - for(var i=0; i nattribs) { + throw new Error("gl-vao: Too many vertex attributes") } - obj_loop: - for(var i=0; i 0 && pickBufferCount[numPick-1] === 0) { - pickBufferCount.pop() - pickBuffers.pop().dispose() + for(; i selection.distance) { - continue - } - for(var j=0; j 0) continue + res = buf.slice(0, 1).join('') } - //Unbind framebuffer - gl.bindFramebuffer(gl.FRAMEBUFFER, null) + token(res) - //Draw composite pass - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA) - gl.disable(gl.DEPTH_TEST) - accumShader.bind() - accumBuffer.color[0].bind(0) - accumShader.uniforms.accumBuffer = 0 - drawTriangle(gl) + start += res.length + content = content.slice(res.length) + return content.length + } while(1) + } - //Turn off blending - gl.disable(gl.BLEND) + function hex() { + if(/[^a-fA-F0-9]/.test(c)) { + token(content.join('')) + mode = NORMAL + return i } - //Clear dirty flags - dirty = false - for(var i=0; i -1) { + mode = KEYWORD + } else if(allBuiltins.indexOf(contentstr) > -1) { + mode = BUILTIN + } else { + mode = IDENT + } + token(content.join('')) + mode = NORMAL + return i + } + content.push(c) + last = c + return i + 1 + } } -},{"./lib/shader":453,"3d-view-controls":454,"a-big-triangle":464,"gl-axes3d":465,"gl-axes3d/properties":575,"gl-fbo":576,"gl-mat4/perspective":243,"gl-select-static":589,"gl-spikes3d":625,"mouse-change":1004}],627:[function(require,module,exports){ -'use strict' +},{"./lib/builtins":230,"./lib/builtins-300es":229,"./lib/literals":232,"./lib/literals-300es":231,"./lib/operators":233}],229:[function(require,module,exports){ +// 300es builtins/reserved words that were previously valid in v100 +var v100 = require('./builtins') +// The texture2D|Cube functions have been removed +// And the gl_ features are updated +v100 = v100.slice().filter(function (b) { + return !/^(gl\_|texture)/.test(b) +}) +module.exports = v100.concat([ + // the updated gl_ constants + 'gl_VertexID' + , 'gl_InstanceID' + , 'gl_Position' + , 'gl_PointSize' + , 'gl_FragCoord' + , 'gl_FrontFacing' + , 'gl_FragDepth' + , 'gl_PointCoord' + , 'gl_MaxVertexAttribs' + , 'gl_MaxVertexUniformVectors' + , 'gl_MaxVertexOutputVectors' + , 'gl_MaxFragmentInputVectors' + , 'gl_MaxVertexTextureImageUnits' + , 'gl_MaxCombinedTextureImageUnits' + , 'gl_MaxTextureImageUnits' + , 'gl_MaxFragmentUniformVectors' + , 'gl_MaxDrawBuffers' + , 'gl_MinProgramTexelOffset' + , 'gl_MaxProgramTexelOffset' + , 'gl_DepthRangeParameters' + , 'gl_DepthRange' -module.exports = { - vertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", - fragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n", - pickVertex: "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n", - pickFragment: "precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n" -} + // other builtins + , 'trunc' + , 'round' + , 'roundEven' + , 'isnan' + , 'isinf' + , 'floatBitsToInt' + , 'floatBitsToUint' + , 'intBitsToFloat' + , 'uintBitsToFloat' + , 'packSnorm2x16' + , 'unpackSnorm2x16' + , 'packUnorm2x16' + , 'unpackUnorm2x16' + , 'packHalf2x16' + , 'unpackHalf2x16' + , 'outerProduct' + , 'transpose' + , 'determinant' + , 'inverse' + , 'texture' + , 'textureSize' + , 'textureProj' + , 'textureLod' + , 'textureOffset' + , 'texelFetch' + , 'texelFetchOffset' + , 'textureProjOffset' + , 'textureLodOffset' + , 'textureProjLod' + , 'textureProjLodOffset' + , 'textureGrad' + , 'textureGradOffset' + , 'textureProjGrad' + , 'textureProjGradOffset' +]) -},{}],628:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":658}],629:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":630,"./lib/create-attributes":631,"./lib/create-uniforms":632,"./lib/reflect":633,"./lib/runtime-reflect":634,"./lib/shader-cache":635,"dup":94}],630:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],631:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":630,"dup":96}],632:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":630,"./reflect":633,"dup":97}],633:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],634:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],635:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":630,"dup":100,"gl-format-compiler-error":636,"weakmap-shim":654}],636:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":637,"dup":101,"gl-constants/lookup":641,"glsl-shader-name":642,"sprintf-js":651}],637:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":638}],638:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":639}],639:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],640:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],641:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":640,"dup":106}],642:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":643,"dup":107,"glsl-tokenizer":650}],643:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],644:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":646,"./lib/builtins-300es":645,"./lib/literals":648,"./lib/literals-300es":647,"./lib/operators":649,"dup":109}],645:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":646,"dup":110}],646:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],647:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":648,"dup":112}],648:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],649:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],650:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":644,"dup":115}],651:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],652:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":653,"dup":117}],653:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],654:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":652,"dup":119}],655:[function(require,module,exports){ -arguments[4][451][0].apply(exports,arguments) -},{"_process":70,"dup":451,"vectorize-text":659}],656:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],657:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],658:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":656,"buffer":65,"dup":122}],659:[function(require,module,exports){ -arguments[4][354][0].apply(exports,arguments) -},{"./lib/vtext":660,"dup":354}],660:[function(require,module,exports){ -arguments[4][355][0].apply(exports,arguments) -},{"cdt2d":661,"clean-pslg":673,"dup":355,"ndarray":1031,"planar-graph-to-polyline":728,"simplify-planar-graph":732,"surface-nets":745}],661:[function(require,module,exports){ -arguments[4][356][0].apply(exports,arguments) -},{"./lib/delaunay":662,"./lib/filter":663,"./lib/monotone":664,"./lib/triangulation":665,"dup":356}],662:[function(require,module,exports){ -arguments[4][357][0].apply(exports,arguments) -},{"binary-search-bounds":666,"dup":357,"robust-in-sphere":667}],663:[function(require,module,exports){ -arguments[4][358][0].apply(exports,arguments) -},{"binary-search-bounds":666,"dup":358}],664:[function(require,module,exports){ -arguments[4][359][0].apply(exports,arguments) -},{"binary-search-bounds":666,"dup":359,"robust-orientation":1040}],665:[function(require,module,exports){ -arguments[4][360][0].apply(exports,arguments) -},{"binary-search-bounds":666,"dup":360}],666:[function(require,module,exports){ -arguments[4][312][0].apply(exports,arguments) -},{"dup":312}],667:[function(require,module,exports){ -arguments[4][361][0].apply(exports,arguments) -},{"dup":361,"robust-scale":669,"robust-subtract":670,"robust-sum":671,"two-product":672}],668:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"dup":53}],669:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"dup":54,"two-product":672,"two-sum":668}],670:[function(require,module,exports){ -arguments[4][364][0].apply(exports,arguments) -},{"dup":364}],671:[function(require,module,exports){ -arguments[4][55][0].apply(exports,arguments) -},{"dup":55}],672:[function(require,module,exports){ -arguments[4][56][0].apply(exports,arguments) -},{"dup":56}],673:[function(require,module,exports){ -arguments[4][367][0].apply(exports,arguments) -},{"./lib/rat-seg-intersect":674,"big-rat":678,"big-rat/cmp":676,"big-rat/to-float":693,"box-intersect":694,"compare-cell":702,"dup":367,"nextafter":703,"rat-vec":706,"robust-segment-intersect":709,"union-find":710}],674:[function(require,module,exports){ -arguments[4][368][0].apply(exports,arguments) -},{"big-rat/div":677,"big-rat/mul":687,"big-rat/sign":691,"big-rat/sub":692,"big-rat/to-float":693,"dup":368,"rat-vec/add":705,"rat-vec/muls":707,"rat-vec/sub":708}],675:[function(require,module,exports){ -arguments[4][369][0].apply(exports,arguments) -},{"./lib/rationalize":685,"dup":369}],676:[function(require,module,exports){ -arguments[4][370][0].apply(exports,arguments) -},{"dup":370}],677:[function(require,module,exports){ -arguments[4][371][0].apply(exports,arguments) -},{"./lib/rationalize":685,"dup":371}],678:[function(require,module,exports){ -arguments[4][372][0].apply(exports,arguments) -},{"./div":677,"./is-rat":679,"./lib/is-bn":683,"./lib/num-to-bn":684,"./lib/rationalize":685,"./lib/str-to-bn":686,"dup":372}],679:[function(require,module,exports){ -arguments[4][373][0].apply(exports,arguments) -},{"./lib/is-bn":683,"dup":373}],680:[function(require,module,exports){ -arguments[4][374][0].apply(exports,arguments) -},{"bn.js":689,"dup":374}],681:[function(require,module,exports){ -arguments[4][375][0].apply(exports,arguments) -},{"dup":375}],682:[function(require,module,exports){ -arguments[4][376][0].apply(exports,arguments) -},{"bit-twiddle":688,"double-bits":690,"dup":376}],683:[function(require,module,exports){ -arguments[4][377][0].apply(exports,arguments) -},{"bn.js":689,"dup":377}],684:[function(require,module,exports){ -arguments[4][378][0].apply(exports,arguments) -},{"bn.js":689,"double-bits":690,"dup":378}],685:[function(require,module,exports){ -arguments[4][379][0].apply(exports,arguments) -},{"./bn-sign":680,"./num-to-bn":684,"dup":379}],686:[function(require,module,exports){ -arguments[4][380][0].apply(exports,arguments) -},{"bn.js":689,"dup":380}],687:[function(require,module,exports){ -arguments[4][381][0].apply(exports,arguments) -},{"./lib/rationalize":685,"dup":381}],688:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],689:[function(require,module,exports){ -arguments[4][383][0].apply(exports,arguments) -},{"dup":383}],690:[function(require,module,exports){ -arguments[4][384][0].apply(exports,arguments) -},{"buffer":65,"dup":384}],691:[function(require,module,exports){ -arguments[4][385][0].apply(exports,arguments) -},{"./lib/bn-sign":680,"dup":385}],692:[function(require,module,exports){ -arguments[4][386][0].apply(exports,arguments) -},{"./lib/rationalize":685,"dup":386}],693:[function(require,module,exports){ -arguments[4][387][0].apply(exports,arguments) -},{"./lib/bn-to-num":681,"./lib/ctz":682,"dup":387}],694:[function(require,module,exports){ -arguments[4][388][0].apply(exports,arguments) -},{"./lib/intersect":696,"./lib/sweep":700,"dup":388,"typedarray-pool":658}],695:[function(require,module,exports){ -arguments[4][389][0].apply(exports,arguments) -},{"dup":389}],696:[function(require,module,exports){ -arguments[4][390][0].apply(exports,arguments) -},{"./brute":695,"./median":697,"./partition":698,"./sweep":700,"bit-twiddle":701,"dup":390,"typedarray-pool":658}],697:[function(require,module,exports){ -arguments[4][391][0].apply(exports,arguments) -},{"./partition":698,"dup":391}],698:[function(require,module,exports){ -arguments[4][392][0].apply(exports,arguments) -},{"dup":392}],699:[function(require,module,exports){ -arguments[4][393][0].apply(exports,arguments) -},{"dup":393}],700:[function(require,module,exports){ -arguments[4][394][0].apply(exports,arguments) -},{"./sort":699,"bit-twiddle":701,"dup":394,"typedarray-pool":658}],701:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],702:[function(require,module,exports){ -arguments[4][61][0].apply(exports,arguments) -},{"dup":61}],703:[function(require,module,exports){ -arguments[4][399][0].apply(exports,arguments) -},{"double-bits":704,"dup":399}],704:[function(require,module,exports){ -arguments[4][384][0].apply(exports,arguments) -},{"buffer":65,"dup":384}],705:[function(require,module,exports){ -arguments[4][401][0].apply(exports,arguments) -},{"big-rat/add":675,"dup":401}],706:[function(require,module,exports){ -arguments[4][402][0].apply(exports,arguments) -},{"big-rat":678,"dup":402}],707:[function(require,module,exports){ -arguments[4][403][0].apply(exports,arguments) -},{"big-rat":678,"big-rat/mul":687,"dup":403}],708:[function(require,module,exports){ -arguments[4][404][0].apply(exports,arguments) -},{"big-rat/sub":692,"dup":404}],709:[function(require,module,exports){ -arguments[4][405][0].apply(exports,arguments) -},{"dup":405,"robust-orientation":1040}],710:[function(require,module,exports){ -arguments[4][78][0].apply(exports,arguments) -},{"dup":78}],711:[function(require,module,exports){ -arguments[4][407][0].apply(exports,arguments) -},{"dup":407,"edges-to-adjacency-list":712}],712:[function(require,module,exports){ -arguments[4][408][0].apply(exports,arguments) -},{"dup":408,"uniq":727}],713:[function(require,module,exports){ -arguments[4][409][0].apply(exports,arguments) -},{"compare-angle":714,"dup":409}],714:[function(require,module,exports){ -arguments[4][410][0].apply(exports,arguments) -},{"dup":410,"robust-orientation":1040,"robust-product":716,"robust-sum":725,"signum":717,"two-sum":718}],715:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"dup":54,"two-product":726,"two-sum":718}],716:[function(require,module,exports){ -arguments[4][412][0].apply(exports,arguments) -},{"dup":412,"robust-scale":715,"robust-sum":725}],717:[function(require,module,exports){ -arguments[4][413][0].apply(exports,arguments) -},{"dup":413}],718:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"dup":53}],719:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],720:[function(require,module,exports){ -arguments[4][416][0].apply(exports,arguments) -},{"binary-search-bounds":719,"dup":416}],721:[function(require,module,exports){ -arguments[4][417][0].apply(exports,arguments) -},{"dup":417,"robust-orientation":1040}],722:[function(require,module,exports){ -arguments[4][418][0].apply(exports,arguments) -},{"dup":418}],723:[function(require,module,exports){ -arguments[4][419][0].apply(exports,arguments) -},{"./lib/order-segments":721,"binary-search-bounds":719,"dup":419,"functional-red-black-tree":722,"robust-orientation":1040}],724:[function(require,module,exports){ -arguments[4][420][0].apply(exports,arguments) -},{"binary-search-bounds":719,"dup":420,"interval-tree-1d":720,"robust-orientation":1040,"slab-decomposition":723}],725:[function(require,module,exports){ -arguments[4][55][0].apply(exports,arguments) -},{"dup":55}],726:[function(require,module,exports){ -arguments[4][56][0].apply(exports,arguments) -},{"dup":56}],727:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],728:[function(require,module,exports){ -arguments[4][424][0].apply(exports,arguments) -},{"./lib/trim-leaves":711,"dup":424,"edges-to-adjacency-list":712,"planar-dual":713,"point-in-big-polygon":724,"robust-sum":725,"two-product":726,"uniq":727}],729:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],730:[function(require,module,exports){ -arguments[4][426][0].apply(exports,arguments) -},{"dup":426}],731:[function(require,module,exports){ -arguments[4][79][0].apply(exports,arguments) -},{"bit-twiddle":729,"dup":79,"union-find":730}],732:[function(require,module,exports){ -arguments[4][428][0].apply(exports,arguments) -},{"dup":428,"robust-orientation":1040,"simplicial-complex":731}],733:[function(require,module,exports){ -arguments[4][429][0].apply(exports,arguments) -},{"dup":429,"typedarray-pool":658}],734:[function(require,module,exports){ -arguments[4][433][0].apply(exports,arguments) -},{"dup":433}],735:[function(require,module,exports){ -arguments[4][437][0].apply(exports,arguments) -},{"dup":437,"typedarray-pool":658}],736:[function(require,module,exports){ -arguments[4][438][0].apply(exports,arguments) -},{"dup":438,"invert-permutation":737,"typedarray-pool":658}],737:[function(require,module,exports){ -arguments[4][439][0].apply(exports,arguments) -},{"dup":439}],738:[function(require,module,exports){ -arguments[4][443][0].apply(exports,arguments) -},{"dup":443,"gamma":734,"permutation-parity":735,"permutation-rank":736}],739:[function(require,module,exports){ -arguments[4][444][0].apply(exports,arguments) -},{"cwise-compiler":740,"dup":444}],740:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":742,"dup":319}],741:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":743}],742:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":741,"dup":321}],743:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],744:[function(require,module,exports){ -arguments[4][449][0].apply(exports,arguments) -},{"./lib/zc-core":739,"dup":449}],745:[function(require,module,exports){ -arguments[4][450][0].apply(exports,arguments) -},{"dup":450,"ndarray-extract-contour":733,"triangulate-hypercube":738,"zero-crossings":744}],746:[function(require,module,exports){ -'use strict' +},{"./builtins":230}],230:[function(require,module,exports){ +module.exports = [ + // Keep this list sorted + 'abs' + , 'acos' + , 'all' + , 'any' + , 'asin' + , 'atan' + , 'ceil' + , 'clamp' + , 'cos' + , 'cross' + , 'dFdx' + , 'dFdy' + , 'degrees' + , 'distance' + , 'dot' + , 'equal' + , 'exp' + , 'exp2' + , 'faceforward' + , 'floor' + , 'fract' + , 'gl_BackColor' + , 'gl_BackLightModelProduct' + , 'gl_BackLightProduct' + , 'gl_BackMaterial' + , 'gl_BackSecondaryColor' + , 'gl_ClipPlane' + , 'gl_ClipVertex' + , 'gl_Color' + , 'gl_DepthRange' + , 'gl_DepthRangeParameters' + , 'gl_EyePlaneQ' + , 'gl_EyePlaneR' + , 'gl_EyePlaneS' + , 'gl_EyePlaneT' + , 'gl_Fog' + , 'gl_FogCoord' + , 'gl_FogFragCoord' + , 'gl_FogParameters' + , 'gl_FragColor' + , 'gl_FragCoord' + , 'gl_FragData' + , 'gl_FragDepth' + , 'gl_FragDepthEXT' + , 'gl_FrontColor' + , 'gl_FrontFacing' + , 'gl_FrontLightModelProduct' + , 'gl_FrontLightProduct' + , 'gl_FrontMaterial' + , 'gl_FrontSecondaryColor' + , 'gl_LightModel' + , 'gl_LightModelParameters' + , 'gl_LightModelProducts' + , 'gl_LightProducts' + , 'gl_LightSource' + , 'gl_LightSourceParameters' + , 'gl_MaterialParameters' + , 'gl_MaxClipPlanes' + , 'gl_MaxCombinedTextureImageUnits' + , 'gl_MaxDrawBuffers' + , 'gl_MaxFragmentUniformComponents' + , 'gl_MaxLights' + , 'gl_MaxTextureCoords' + , 'gl_MaxTextureImageUnits' + , 'gl_MaxTextureUnits' + , 'gl_MaxVaryingFloats' + , 'gl_MaxVertexAttribs' + , 'gl_MaxVertexTextureImageUnits' + , 'gl_MaxVertexUniformComponents' + , 'gl_ModelViewMatrix' + , 'gl_ModelViewMatrixInverse' + , 'gl_ModelViewMatrixInverseTranspose' + , 'gl_ModelViewMatrixTranspose' + , 'gl_ModelViewProjectionMatrix' + , 'gl_ModelViewProjectionMatrixInverse' + , 'gl_ModelViewProjectionMatrixInverseTranspose' + , 'gl_ModelViewProjectionMatrixTranspose' + , 'gl_MultiTexCoord0' + , 'gl_MultiTexCoord1' + , 'gl_MultiTexCoord2' + , 'gl_MultiTexCoord3' + , 'gl_MultiTexCoord4' + , 'gl_MultiTexCoord5' + , 'gl_MultiTexCoord6' + , 'gl_MultiTexCoord7' + , 'gl_Normal' + , 'gl_NormalMatrix' + , 'gl_NormalScale' + , 'gl_ObjectPlaneQ' + , 'gl_ObjectPlaneR' + , 'gl_ObjectPlaneS' + , 'gl_ObjectPlaneT' + , 'gl_Point' + , 'gl_PointCoord' + , 'gl_PointParameters' + , 'gl_PointSize' + , 'gl_Position' + , 'gl_ProjectionMatrix' + , 'gl_ProjectionMatrixInverse' + , 'gl_ProjectionMatrixInverseTranspose' + , 'gl_ProjectionMatrixTranspose' + , 'gl_SecondaryColor' + , 'gl_TexCoord' + , 'gl_TextureEnvColor' + , 'gl_TextureMatrix' + , 'gl_TextureMatrixInverse' + , 'gl_TextureMatrixInverseTranspose' + , 'gl_TextureMatrixTranspose' + , 'gl_Vertex' + , 'greaterThan' + , 'greaterThanEqual' + , 'inversesqrt' + , 'length' + , 'lessThan' + , 'lessThanEqual' + , 'log' + , 'log2' + , 'matrixCompMult' + , 'max' + , 'min' + , 'mix' + , 'mod' + , 'normalize' + , 'not' + , 'notEqual' + , 'pow' + , 'radians' + , 'reflect' + , 'refract' + , 'sign' + , 'sin' + , 'smoothstep' + , 'sqrt' + , 'step' + , 'tan' + , 'texture2D' + , 'texture2DLod' + , 'texture2DProj' + , 'texture2DProjLod' + , 'textureCube' + , 'textureCubeLod' + , 'texture2DLodEXT' + , 'texture2DProjLodEXT' + , 'textureCubeLodEXT' + , 'texture2DGradEXT' + , 'texture2DProjGradEXT' + , 'textureCubeGradEXT' +] -module.exports = createFancyScatter2D +},{}],231:[function(require,module,exports){ +var v100 = require('./literals') -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var textCache = require('text-cache') -var pool = require('typedarray-pool') -var vectorizeText = require('vectorize-text') -var shaders = require('./lib/shaders') +module.exports = v100.slice().concat([ + 'layout' + , 'centroid' + , 'smooth' + , 'case' + , 'mat2x2' + , 'mat2x3' + , 'mat2x4' + , 'mat3x2' + , 'mat3x3' + , 'mat3x4' + , 'mat4x2' + , 'mat4x3' + , 'mat4x4' + , 'uint' + , 'uvec2' + , 'uvec3' + , 'uvec4' + , 'samplerCubeShadow' + , 'sampler2DArray' + , 'sampler2DArrayShadow' + , 'isampler2D' + , 'isampler3D' + , 'isamplerCube' + , 'isampler2DArray' + , 'usampler2D' + , 'usampler3D' + , 'usamplerCube' + , 'usampler2DArray' + , 'coherent' + , 'restrict' + , 'readonly' + , 'writeonly' + , 'resource' + , 'atomic_uint' + , 'noperspective' + , 'patch' + , 'sample' + , 'subroutine' + , 'common' + , 'partition' + , 'active' + , 'filter' + , 'image1D' + , 'image2D' + , 'image3D' + , 'imageCube' + , 'iimage1D' + , 'iimage2D' + , 'iimage3D' + , 'iimageCube' + , 'uimage1D' + , 'uimage2D' + , 'uimage3D' + , 'uimageCube' + , 'image1DArray' + , 'image2DArray' + , 'iimage1DArray' + , 'iimage2DArray' + , 'uimage1DArray' + , 'uimage2DArray' + , 'image1DShadow' + , 'image2DShadow' + , 'image1DArrayShadow' + , 'image2DArrayShadow' + , 'imageBuffer' + , 'iimageBuffer' + , 'uimageBuffer' + , 'sampler1DArray' + , 'sampler1DArrayShadow' + , 'isampler1D' + , 'isampler1DArray' + , 'usampler1D' + , 'usampler1DArray' + , 'isampler2DRect' + , 'usampler2DRect' + , 'samplerBuffer' + , 'isamplerBuffer' + , 'usamplerBuffer' + , 'sampler2DMS' + , 'isampler2DMS' + , 'usampler2DMS' + , 'sampler2DMSArray' + , 'isampler2DMSArray' + , 'usampler2DMSArray' +]) -var BOUNDARIES = {} +},{"./literals":232}],232:[function(require,module,exports){ +module.exports = [ + // current + 'precision' + , 'highp' + , 'mediump' + , 'lowp' + , 'attribute' + , 'const' + , 'uniform' + , 'varying' + , 'break' + , 'continue' + , 'do' + , 'for' + , 'while' + , 'if' + , 'else' + , 'in' + , 'out' + , 'inout' + , 'float' + , 'int' + , 'void' + , 'bool' + , 'true' + , 'false' + , 'discard' + , 'return' + , 'mat2' + , 'mat3' + , 'mat4' + , 'vec2' + , 'vec3' + , 'vec4' + , 'ivec2' + , 'ivec3' + , 'ivec4' + , 'bvec2' + , 'bvec3' + , 'bvec4' + , 'sampler1D' + , 'sampler2D' + , 'sampler3D' + , 'samplerCube' + , 'sampler1DShadow' + , 'sampler2DShadow' + , 'struct' -function getBoundary(glyph) { - if(glyph in BOUNDARIES) { - return BOUNDARIES[glyph] - } + // future + , 'asm' + , 'class' + , 'union' + , 'enum' + , 'typedef' + , 'template' + , 'this' + , 'packed' + , 'goto' + , 'switch' + , 'default' + , 'inline' + , 'noinline' + , 'volatile' + , 'public' + , 'static' + , 'extern' + , 'external' + , 'interface' + , 'long' + , 'short' + , 'double' + , 'half' + , 'fixed' + , 'unsigned' + , 'input' + , 'output' + , 'hvec2' + , 'hvec3' + , 'hvec4' + , 'dvec2' + , 'dvec3' + , 'dvec4' + , 'fvec2' + , 'fvec3' + , 'fvec4' + , 'sampler2DRect' + , 'sampler3DRect' + , 'sampler2DRectShadow' + , 'sizeof' + , 'cast' + , 'namespace' + , 'using' +] - var polys = vectorizeText(glyph, { - polygons: true, - font: 'sans-serif', - textAlign: 'left', - textBaseline: 'alphabetic' - }) +},{}],233:[function(require,module,exports){ +module.exports = [ + '<<=' + , '>>=' + , '++' + , '--' + , '<<' + , '>>' + , '<=' + , '>=' + , '==' + , '!=' + , '&&' + , '||' + , '+=' + , '-=' + , '*=' + , '/=' + , '%=' + , '&=' + , '^^' + , '^=' + , '|=' + , '(' + , ')' + , '[' + , ']' + , '.' + , '!' + , '~' + , '*' + , '/' + , '%' + , '+' + , '-' + , '<' + , '>' + , '&' + , '^' + , '|' + , '?' + , ':' + , '=' + , ',' + , ';' + , '{' + , '}' +] - var coords = [] - var normals = [] +},{}],234:[function(require,module,exports){ +var tokenize = require('./index') - polys.forEach(function(loops) { - loops.forEach(function(loop) { - for(var i=0; i 0) { + code.push(",") } - - var gl = plot.gl - - calcScales.call(this) - - shader.bind() - - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.viewTransform = MATRIX - - this.positionBuffer.bind() - shader.attributes.position.pointer() - - this.offsetBuffer.bind() - shader.attributes.offset.pointer() - - this.colorBuffer.bind() - shader.attributes.color.pointer(gl.UNSIGNED_BYTE, true) - - gl.drawArrays(gl.TRIANGLES, 0, numVertices) + code.push("tuple[", i, "]") } + code.push(")}return orient") + var proc = new Function("test", code.join("")) + var test = orient[d+1] + if(!test) { + test = orient + } + return proc(test) +} - var PICK_OFFSET = [0,0,0,0] - - proto.drawPick = function(offset) { - var plot = this.plot - var shader = this.pickShader - var numVertices = this.numVertices - - var gl = plot.gl - - this.pickOffset = offset - - if(!numVertices) { - return offset - } - - for(var i=0; i<4; ++i) { - PICK_OFFSET[i] = ((offset>>(i*8)) & 0xff) - } - - calcScales.call(this) - - shader.bind() - - shader.uniforms.pixelScale = PIXEL_SCALE - shader.uniforms.viewTransform = MATRIX - shader.uniforms.pickOffset = PICK_OFFSET - - this.positionBuffer.bind() - shader.attributes.position.pointer() - - this.offsetBuffer.bind() - shader.attributes.offset.pointer() - - this.idBuffer.bind() - shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false) +var BAKED = [] - gl.drawArrays(gl.TRIANGLES, 0, numVertices) +function Triangulation(dimension, vertices, simplices) { + this.dimension = dimension + this.vertices = vertices + this.simplices = simplices + this.interior = simplices.filter(function(c) { + return !c.boundary + }) - return offset + this.numPoints + this.tuple = new Array(dimension+1) + for(var i=0; i<=dimension; ++i) { + this.tuple[i] = this.vertices[i] } -})() -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.numPoints - if(value < pickOffset || value >= pickOffset + pointCount) { - return null - } - var pointId = value - pickOffset - var points = this.points - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + var o = BAKED[dimension] + if(!o) { + o = BAKED[dimension] = bakeOrient(dimension) } + this.orient = o } -proto.update = function(options) { - options = options || {} - - var positions = options.positions || [] - var colors = options.colors || [] - var glyphs = options.glyphs || [] - var sizes = options.sizes || [] - var borderWidths = options.borderWidths || [] - var borderColors = options.borderColors || [] +var proto = Triangulation.prototype - this.points = positions +//Degenerate situation where we are on boundary, but coplanar to face +proto.handleBoundaryDegeneracy = function(cell, point) { + var d = this.dimension + var n = this.vertices.length - 1 + var tuple = this.tuple + var verts = this.vertices - var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity] - var numVertices = 0 - for(var i=0; i> 1 - for(var j=0; j<2; ++j) { - bounds[j] = Math.min(bounds[j], positions[2*i+j]) - bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j]) + //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate + var toVisit = [ cell ] + cell.lastVisited = -n + while(toVisit.length > 0) { + cell = toVisit.pop() + var cellVerts = cell.vertices + var cellAdj = cell.adjacent + for(var i=0; i<=d; ++i) { + var neighbor = cellAdj[i] + if(!neighbor.boundary || neighbor.lastVisited <= -n) { + continue + } + var nv = neighbor.vertices + for(var j=0; j<=d; ++j) { + var vv = nv[j] + if(vv < 0) { + tuple[j] = point + } else { + tuple[j] = verts[vv] + } + } + var o = this.orient() + if(o > 0) { + return neighbor + } + neighbor.lastVisited = -n + if(o === 0) { + toVisit.push(neighbor) + } } } + return null +} - if(bounds[0] === bounds[2]) { - bounds[2] += 1 - } - if(bounds[3] === bounds[1]) { - bounds[3] += 1 - } - - var sx = 1/(bounds[2] - bounds[0]) - var sy = 1/(bounds[3] - bounds[1]) - var tx = bounds[0] - var ty = bounds[1] - - var v_position = pool.mallocFloat32(2 * numVertices) - var v_offset = pool.mallocFloat32(2 * numVertices) - var v_color = pool.mallocUint8(4 * numVertices) - var v_ids = pool.mallocUint32(numVertices) - var ptr = 0 - - for(var i=0; i= n) { + continue + } + var prev = tuple[i] + tuple[i] = point + var o = this.orient() + tuple[i] = prev + if(o < 0) { + cell = neighbor + continue outerLoop + } else { + if(!neighbor.boundary) { + neighbor.lastVisited = n + } else { + neighbor.lastVisited = -n + } + } } + return } - this.numPoints = glyphs.length - this.numVertices = numVertices - - this.positionBuffer.update(v_position) - this.offsetBuffer.update(v_offset) - this.colorBuffer.update(v_color) - this.idBuffer.update(v_ids) - - pool.free(v_position) - pool.free(v_offset) - pool.free(v_color) - pool.free(v_ids) -} - -proto.dispose = function() { - this.shader.dispose() - this.pickShader.dispose() - this.positionBuffer.dispose() - this.offsetBuffer.dispose() - this.colorBuffer.dispose() - this.idBuffer.dispose() - this.plot.removeObject(this) + return cell } -function createFancyScatter2D(plot, options) { - var gl = plot.gl +proto.addPeaks = function(point, cell) { + var n = this.vertices.length - 1 + var d = this.dimension + var verts = this.vertices + var tuple = this.tuple + var interior = this.interior + var simplices = this.simplices - var shader = createShader(gl, shaders.vertex, shaders.fragment) - var pickShader = createShader(gl, shaders.pickVertex, shaders.pickFragment) + //Walking finished at boundary, time to add peaks + var tovisit = [ cell ] - var positionBuffer = createBuffer(gl) - var offsetBuffer = createBuffer(gl) - var colorBuffer = createBuffer(gl) - var idBuffer = createBuffer(gl) + //Stretch initial boundary cell into a peak + cell.lastVisited = n + cell.vertices[cell.vertices.indexOf(-1)] = n + cell.boundary = false + interior.push(cell) - var scatter = new GLScatterFancy( - plot, - shader, - pickShader, - positionBuffer, - offsetBuffer, - colorBuffer, - idBuffer) + //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done + var glueFacets = [] - scatter.update(options) + //Do a traversal of the boundary walking outward from starting peak + while(tovisit.length > 0) { + //Pop off peak and walk over adjacent cells + var cell = tovisit.pop() + var cellVerts = cell.vertices + var cellAdj = cell.adjacent + var indexOfN = cellVerts.indexOf(n) + if(indexOfN < 0) { + continue + } - plot.addObject(scatter) + for(var i=0; i<=d; ++i) { + if(i === indexOfN) { + continue + } - return scatter -} + //For each boundary neighbor of the cell + var neighbor = cellAdj[i] + if(!neighbor.boundary || neighbor.lastVisited >= n) { + continue + } -},{"./lib/shaders":627,"gl-buffer":628,"gl-shader":629,"text-cache":655,"typedarray-pool":658,"vectorize-text":659}],747:[function(require,module,exports){ + var nv = neighbor.vertices + //Test if neighbor is a peak + if(neighbor.lastVisited !== -n) { + //Compute orientation of p relative to each boundary peak + var indexOfNeg1 = 0 + for(var j=0; j<=d; ++j) { + if(nv[j] < 0) { + indexOfNeg1 = j + tuple[j] = point + } else { + tuple[j] = verts[nv[j]] + } + } + var o = this.orient() -exports.pointVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute float weight;\n\nuniform mat3 matrix;\nuniform float pointSize, useWeight;\n\nvarying float fragWeight;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n fragWeight = mix(1.0, weight, useWeight);\n}\n" -exports.pointFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\n\nvarying float fragWeight;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n float alpha = 1.0 - pow(1.0 - baseColor.a, fragWeight);\n gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n" -exports.pickVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n vec3 hgPosition = matrix * vec3(position, 1);\n gl_Position = vec4(hgPosition.xy, 0, hgPosition.z);\n gl_PointSize = pointSize;\n\n vec4 id = pickId + pickOffset;\n id.y += floor(id.x / 256.0);\n id.x -= floor(id.x / 256.0) * 256.0;\n\n id.z += floor(id.y / 256.0);\n id.y -= floor(id.y / 256.0) * 256.0;\n\n id.w += floor(id.z / 256.0);\n id.z -= floor(id.z / 256.0) * 256.0;\n\n fragId = id;\n}\n" -exports.pickFragment = "precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragId;\n\nvoid main() {\n float radius = length(2.0*gl_PointCoord.xy-1.0);\n if(radius > 1.0) {\n discard;\n }\n gl_FragColor = fragId / 255.0;\n}\n" + //Test if neighbor cell is also a peak + if(o > 0) { + nv[indexOfNeg1] = n + neighbor.boundary = false + interior.push(neighbor) + tovisit.push(neighbor) + neighbor.lastVisited = n + continue + } else { + neighbor.lastVisited = -n + } + } -},{}],748:[function(require,module,exports){ -arguments[4][312][0].apply(exports,arguments) -},{"dup":312}],749:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":780}],750:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":751,"./lib/create-attributes":752,"./lib/create-uniforms":753,"./lib/reflect":754,"./lib/runtime-reflect":755,"./lib/shader-cache":756,"dup":94}],751:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],752:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":751,"dup":96}],753:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":751,"./reflect":754,"dup":97}],754:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],755:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],756:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":751,"dup":100,"gl-format-compiler-error":757,"weakmap-shim":775}],757:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":758,"dup":101,"gl-constants/lookup":762,"glsl-shader-name":763,"sprintf-js":772}],758:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":759}],759:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":760}],760:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],761:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],762:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":761,"dup":106}],763:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":764,"dup":107,"glsl-tokenizer":771}],764:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],765:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":767,"./lib/builtins-300es":766,"./lib/literals":769,"./lib/literals-300es":768,"./lib/operators":770,"dup":109}],766:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":767,"dup":110}],767:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],768:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":769,"dup":112}],769:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],770:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],771:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":765,"dup":115}],772:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],773:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":774,"dup":117}],774:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],775:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":773,"dup":119}],776:[function(require,module,exports){ -'use strict' + var na = neighbor.adjacent -module.exports = sortLevels + //Otherwise, replace neighbor with new face + var vverts = cellVerts.slice() + var vadj = cellAdj.slice() + var ncell = new Simplex(vverts, vadj, true) + simplices.push(ncell) -var INSERT_SORT_CUTOFF = 32 + //Connect to neighbor + var opposite = na.indexOf(cell) + if(opposite < 0) { + continue + } + na[opposite] = ncell + vadj[indexOfN] = neighbor -function sortLevels(data_levels, data_points, data_ids, data_weights, n0) { - if (n0 <= 4*INSERT_SORT_CUTOFF) { - insertionSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } else { - quickSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights) - } -} + //Connect to cell + vverts[i] = -1 + vadj[i] = cell + cellAdj[i] = ncell -function insertionSort(left, right, data_levels, data_points, data_ids, data_weights) { - for(var i=left+1; i<=right; ++i) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] + //Flip facet + ncell.flip() - var j = i - while(j > left) { - var b_level = data_levels[j-1] - var b_x = data_points[2*(j-1)] - if(((b_level - a_level) || (a_x - b_x)) >= 0) { - break + //Add to glue list + for(var j=0; j<=d; ++j) { + var uu = vverts[j] + if(uu < 0 || uu === n) { + continue + } + var nface = new Array(d-1) + var nptr = 0 + for(var k=0; k<=d; ++k) { + var vv = vverts[k] + if(vv < 0 || k === j) { + continue + } + nface[nptr++] = vv + } + glueFacets.push(new GlueFacet(nface, ncell, j)) } - data_levels[j] = b_level - data_points[2*j] = b_x - data_points[2*j+1] = data_points[2*j-1] - data_ids[j] = data_ids[j-1] - data_weights[j] = data_weights[j-1] - j -= 1 } - - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight } -} - -function swap(i, j, data_levels, data_points, data_ids, data_weights) { - var a_level = data_levels[i] - var a_x = data_points[2*i] - var a_y = data_points[2*i+1] - var a_id = data_ids[i] - var a_weight = data_weights[i] - - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] - data_levels[j] = a_level - data_points[2*j] = a_x - data_points[2*j+1] = a_y - data_ids[j] = a_id - data_weights[j] = a_weight -} + //Glue boundary facets together + glueFacets.sort(compareGlue) -function move(i, j, data_levels, data_points, data_ids, data_weights) { - data_levels[i] = data_levels[j] - data_points[2*i] = data_points[2*j] - data_points[2*i+1] = data_points[2*j+1] - data_ids[i] = data_ids[j] - data_weights[i] = data_weights[j] + for(var i=0; i+1= 0) { + bcell[ptr++] = cv[j] + } else { + parity = j&1 + } + } + if(parity === (d&1)) { + var t = bcell[0] + bcell[0] = bcell[1] + bcell[1] = t + } + boundary.push(bcell) + } + } + return boundary } -function quickSort(left, right, data_levels, data_points, data_ids, data_weights) { - var sixth = (right - left + 1) / 6 | 0, - index1 = left + sixth, - index5 = right - sixth, - index3 = left + right >> 1, - index2 = index3 - sixth, - index4 = index3 + sixth, - el1 = index1, - el2 = index2, - el3 = index3, - el4 = index4, - el5 = index5, - less = left + 1, - great = right - 1, - tmp = 0 - if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el2 - el2 = tmp - } - if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp - } - if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el3 - el3 = tmp - } - if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp - } - if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el1 - el1 = el4 - el4 = tmp +function incrementalConvexHull(points, randomSearch) { + var n = points.length + if(n === 0) { + throw new Error("Must have at least d+1 points") } - if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) { - tmp = el3 - el3 = el4 - el4 = tmp + var d = points[0].length + if(n <= d) { + throw new Error("Must input at least d+1 points") } - if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el5 - el5 = tmp + + //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process + var initialSimplex = points.slice(0, d+1) + + //Make sure initial simplex is positively oriented + var o = orient.apply(void 0, initialSimplex) + if(o === 0) { + throw new Error("Input not in general position") } - if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) { - tmp = el2 - el2 = el3 - el3 = tmp + var initialCoords = new Array(d+1) + for(var i=0; i<=d; ++i) { + initialCoords[i] = i } - if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) { - tmp = el4 - el4 = el5 - el5 = tmp + if(o < 0) { + initialCoords[0] = 1 + initialCoords[1] = 0 } - var pivot1_level = data_levels[el2] - var pivot1_x = data_points[2*el2] - var pivot1_y = data_points[2*el2+1] - var pivot1_id = data_ids[el2] - var pivot1_weight = data_weights[el2] - - var pivot2_level = data_levels[el4] - var pivot2_x = data_points[2*el4] - var pivot2_y = data_points[2*el4+1] - var pivot2_id = data_ids[el4] - var pivot2_weight = data_weights[el4] + //Create initial topological index, glue pointers together (kind of messy) + var initialCell = new Simplex(initialCoords, new Array(d+1), false) + var boundary = initialCell.adjacent + var list = new Array(d+2) + for(var i=0; i<=d; ++i) { + var verts = initialCoords.slice() + for(var j=0; j<=d; ++j) { + if(j === i) { + verts[j] = -1 + } + } + var t = verts[0] + verts[0] = verts[1] + verts[1] = t + var cell = new Simplex(verts, new Array(d+1), true) + boundary[i] = cell + list[i] = cell + } + list[d+1] = initialCell + for(var i=0; i<=d; ++i) { + var verts = boundary[i].vertices + var adj = boundary[i].adjacent + for(var j=0; j<=d; ++j) { + var v = verts[j] + if(v < 0) { + adj[j] = initialCell + continue + } + for(var k=0; k<=d; ++k) { + if(boundary[k].vertices.indexOf(v) < 0) { + adj[j] = boundary[k] + } + } + } + } - var ptr0 = el1 - var ptr2 = el3 - var ptr4 = el5 - var ptr5 = index1 - var ptr6 = index3 - var ptr7 = index5 + //Initialize triangles + var triangles = new Triangulation(d, initialSimplex, list) - var level_x = data_levels[ptr0] - var level_y = data_levels[ptr2] - var level_z = data_levels[ptr4] - data_levels[ptr5] = level_x - data_levels[ptr6] = level_y - data_levels[ptr7] = level_z + //Insert remaining points + var useRandom = !!randomSearch + for(var i=d+1; i> 1 + , s = compareCells(cells[mid], c) + if(s <= 0) { + if(s === 0) { + r = mid } + lo = mid + 1 + } else if(s > 0) { + hi = mid - 1 } } - return mid + return r } +exports.findCell = findCell; -function SnapInterval(pixelSize, offset, count) { - this.pixelSize = pixelSize - this.offset = offset - this.count = count +//Builds an index for an n-cell. This is more general than dual, but less efficient +function incidence(from_cells, to_cells) { + var index = new Array(from_cells.length) + for(var i=0, il=index.length; i= from_cells.length || compareCells(from_cells[idx], b) !== 0) { + break + } + } + } + } + return index } +exports.incidence = incidence -function snapPoints(points, ids, weights, bounds) { - var n = points.length >>> 1 - if(n < 1) { - return [] +//Computes the dual of the mesh. This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices +function dual(cells, vertex_count) { + if(!vertex_count) { + return incidence(unique(skeleton(cells, 0)), cells, 0) + } + var res = new Array(vertex_count) + for(var i=0; i>> k) & 1) { + b.push(c[k]) + } + } + result.push(b) + } } + return normalize(result) +} +exports.explode = explode - if(lox === hix) { - hix += 1 + Math.abs(hix) +//Enumerates all of the n-cells of a cell complex +function skeleton(cells, n) { + if(n < 0) { + return [] } - if(loy === hiy) { - hiy += 1 + Math.abs(hix) + var result = [] + , k0 = (1<<(n+1))-1 + for(var i=0; i= Math.max(0.9 * count, 32)) { - var mid = (end + start)>>>1 - snapRec(nx, ny, diam_2, offset, mid, level+1) - offset = mid +//Computes the boundary of all cells, does not remove duplicates +function boundary(cells) { + var res = [] + for(var i=0,il=cells.length; i=0; --ptr) { - points[2*ptr] = (points[2*ptr] - lox) * scaleX - points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY +//Computes connected components for a dense cell complex +function connectedComponents_dense(cells, vertex_count) { + var labels = new UnionFind(vertex_count) + for(var i=0; i + * License: MIT + * + * `npm install is-buffer` + */ - return lod +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) } -},{"./lib/sort":776,"typedarray-pool":780}],778:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],779:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],780:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":778,"buffer":65,"dup":122}],781:[function(require,module,exports){ +},{}],241:[function(require,module,exports){ 'use strict' -var createShader = require('gl-shader') -var createBuffer = require('gl-buffer') -var bsearch = require('binary-search-bounds') -var snapPoints = require('snap-points-2d') +module.exports = mouseListen -var pool = require('typedarray-pool') +var mouse = require('mouse-event') -var SHADERS = require('./lib/shader') +function mouseListen(element, callback) { -module.exports = createScatter2D + if(!callback) { + callback = element + element = window + } -function Scatter2D(plot, offsetBuffer, pickBuffer, weightBuffer, shader, pickShader) { - this.plot = plot - this.offsetBuffer = offsetBuffer - this.pickBuffer = pickBuffer - this.weightBuffer = weightBuffer - this.shader = shader - this.pickShader = pickShader - this.scales = [] - this.size = 12.0 - this.borderSize = 1.0 - this.pointCount = 0 - this.color = [1,0,0,1] - this.borderColor = [0,0,0,1] - this.bounds = [Infinity,Infinity,-Infinity,-Infinity] - this.pickOffset = 0 - this.points = null - this.xCoords = null -} + var buttonState = 0 + var x = 0 + var y = 0 + var mods = { + shift: false, + alt: false, + control: false, + meta: false + } + var attached = false -var proto = Scatter2D.prototype + function updateMods(ev) { + var changed = false + if('altKey' in ev) { + changed = changed || ev.altKey !== mods.alt + mods.alt = !!ev.altKey + } + if('shiftKey' in ev) { + changed = changed || ev.shiftKey !== mods.shift + mods.shift = !!ev.shiftKey + } + if('ctrlKey' in ev) { + changed = changed || ev.ctrlKey !== mods.control + mods.control = !!ev.ctrlKey + } + if('metaKey' in ev) { + changed = changed || ev.metaKey !== mods.meta + mods.meta = !!ev.metaKey + } + return changed + } -proto.dispose = function() { - this.shader.dispose() - this.pickShader.dispose() - this.offsetBuffer.dispose() - this.pickBuffer.dispose() - if(this.xCoords) { - pool.free(this.xCoords) + function handleEvent(nextButtons, ev) { + var nextX = mouse.x(ev) + var nextY = mouse.y(ev) + if('buttons' in ev) { + nextButtons = ev.buttons|0 + } + if(nextButtons !== buttonState || + nextX !== x || + nextY !== y || + updateMods(ev)) { + buttonState = nextButtons|0 + x = nextX||0 + y = nextY||0 + callback(buttonState, x, y, mods) + } } - this.plot.removeObject(this) -} -proto.update = function(options) { - options = options || {} + function clearState(ev) { + handleEvent(0, ev) + } - function dflt(opt, value) { - if(opt in options) { - return options[opt] + function handleBlur() { + if(buttonState || + x || + y || + mods.shift || + mods.alt || + mods.meta || + mods.control) { + + x = y = 0 + buttonState = 0 + mods.shift = mods.alt = mods.control = mods.meta = false + callback(0, 0, 0, mods) } - return value } - this.size = dflt('size', 12.0) - this.color = dflt('color', [1,0,0,1]).slice() - this.borderSize = dflt('borderSize', 1) - this.borderColor = dflt('borderColor', [0,0,0,1]).slice() - - //Update point data - if(this.xCoords) { - pool.free(this.xCoords) + function handleMods(ev) { + if(updateMods(ev)) { + callback(buttonState, x, y, mods) + } } - var data = options.positions - var packed = pool.mallocFloat32(data.length) - var packedId = pool.mallocInt32(data.length>>>1) - packed.set(data) - var packedW = pool.mallocFloat32(data.length) - this.points = data - this.scales = snapPoints(packed, packedId, packedW, this.bounds) - this.offsetBuffer.update(packed) - this.pickBuffer.update(packedId) - this.weightBuffer.update(packedW) - var xCoords = pool.mallocFloat32(data.length>>>1) - for(var i=0,j=0; i>> 1 - this.pickOffset = 0 -} + function handleMouseUp(ev) { + handleEvent(buttonState & ~mouse.buttons(ev), ev) + } -proto.drawPick = (function() { - var MATRIX = [1,0,0, - 0,1,0, - 0,0,1] - var PICK_VEC4 = [0,0,0,0] -return function(pickOffset) { - var plot = this.plot - var shader = this.pickShader - var scales = this.scales - var offsetBuffer = this.offsetBuffer - var pickBuffer = this.pickBuffer - var bounds = this.bounds - var size = this.size - var borderSize = this.borderSize - var gl = plot.gl - var pixelRatio = plot.pickPixelRatio - var viewBox = plot.viewBox - var dataBox = plot.dataBox + function attachListeners() { + if(attached) { + return + } + attached = true - if(this.pointCount === 0) { - return pickOffset - } + element.addEventListener('mousemove', handleMouseMove) - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - var screenX = (viewBox[2] - viewBox[0]) * pixelRatio / plot.pixelRatio - var screenY = (viewBox[3] - viewBox[1]) * pixelRatio / plot.pixelRatio + element.addEventListener('mousedown', handleMouseDown) - var pixelSize = Math.min(dataX / screenX, dataY / screenY) - var targetScale = pixelSize + element.addEventListener('mouseup', handleMouseUp) + element.addEventListener('mouseleave', clearState) + element.addEventListener('mouseenter', clearState) + element.addEventListener('mouseout', clearState) + element.addEventListener('mouseover', clearState) - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 + element.addEventListener('blur', handleBlur) - this.pickOffset = pickOffset - PICK_VEC4[0] = ( pickOffset & 0xff) - PICK_VEC4[1] = ((pickOffset>>8) & 0xff) - PICK_VEC4[2] = ((pickOffset>>16) & 0xff) - PICK_VEC4[3] = ((pickOffset>>24) & 0xff) + element.addEventListener('keyup', handleMods) + element.addEventListener('keydown', handleMods) + element.addEventListener('keypress', handleMods) - shader.bind() - shader.uniforms.matrix = MATRIX - shader.uniforms.color = this.color - shader.uniforms.borderColor = this.borderColor - shader.uniforms.pointSize = pixelRatio * (size + borderSize) - shader.uniforms.pickOffset = PICK_VEC4 + if(element !== window) { + window.addEventListener('blur', handleBlur) - if(this.borderSize === 0) { - shader.uniforms.centerFraction = 2.0; - } else { - shader.uniforms.centerFraction = size / (size + borderSize + 1.25) + window.addEventListener('keyup', handleMods) + window.addEventListener('keydown', handleMods) + window.addEventListener('keypress', handleMods) + } } - offsetBuffer.bind() - shader.attributes.position.pointer() - pickBuffer.bind() - shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE) + function detachListeners() { + if(!attached) { + return + } + attached = false - var xCoords = this.xCoords - var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX - var xEnd = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX + element.removeEventListener('mousemove', handleMouseMove) - for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) { - var lod = scales[scaleNum] - if(lod.pixelSize < pixelSize && scaleNum > 1) { - continue - } + element.removeEventListener('mousedown', handleMouseDown) - var intervalStart = lod.offset - var intervalEnd = lod.count + intervalStart + element.removeEventListener('mouseup', handleMouseUp) - var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) - var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 + element.removeEventListener('mouseleave', clearState) + element.removeEventListener('mouseenter', clearState) + element.removeEventListener('mouseout', clearState) + element.removeEventListener('mouseover', clearState) - if(endOffset > startOffset) { - gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) + element.removeEventListener('blur', handleBlur) + + element.removeEventListener('keyup', handleMods) + element.removeEventListener('keydown', handleMods) + element.removeEventListener('keypress', handleMods) + + if(element !== window) { + window.removeEventListener('blur', handleBlur) + + window.removeEventListener('keyup', handleMods) + window.removeEventListener('keydown', handleMods) + window.removeEventListener('keypress', handleMods) } } - return pickOffset + this.pointCount -} -})() - -proto.draw = (function() { - var MATRIX = [1, 0, 0, - 0, 1, 0, - 0, 0, 1] + //Attach listeners + attachListeners() - return function() { - var plot = this.plot - var shader = this.shader - var scales = this.scales - var offsetBuffer = this.offsetBuffer - var bounds = this.bounds - var size = this.size - var borderSize = this.borderSize - var gl = plot.gl - var pixelRatio = plot.pixelRatio - var viewBox = plot.viewBox - var dataBox = plot.dataBox + var result = { + element: element + } - if(this.pointCount === 0) { - return + Object.defineProperties(result, { + enabled: { + get: function() { return attached }, + set: function(f) { + if(f) { + attachListeners() + } else { + detachListeners + } + }, + enumerable: true + }, + buttons: { + get: function() { return buttonState }, + enumerable: true + }, + x: { + get: function() { return x }, + enumerable: true + }, + y: { + get: function() { return y }, + enumerable: true + }, + mods: { + get: function() { return mods }, + enumerable: true } + }) - var boundX = bounds[2] - bounds[0] - var boundY = bounds[3] - bounds[1] - var dataX = dataBox[2] - dataBox[0] - var dataY = dataBox[3] - dataBox[1] - var screenX = viewBox[2] - viewBox[0] - var screenY = viewBox[3] - viewBox[1] + return result +} - var pixelSize = Math.min(dataX / screenX, dataY / screenY) - var targetScale = pixelSize +},{"mouse-event":242}],242:[function(require,module,exports){ +'use strict' - MATRIX[0] = 2.0 * boundX / dataX - MATRIX[4] = 2.0 * boundY / dataY - MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0 - MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0 +function mouseButtons(ev) { + if(typeof ev === 'object') { + if('buttons' in ev) { + return ev.buttons + } else if('which' in ev) { + var b = ev.which + if(b === 2) { + return 4 + } else if(b === 3) { + return 2 + } else if(b > 0) { + return 1<<(b-1) + } + } else if('button' in ev) { + var b = ev.button + if(b === 1) { + return 4 + } else if(b === 2) { + return 2 + } else if(b >= 0) { + return 1<= 0; --scaleNum) { - var lod = scales[scaleNum] - if(lod.pixelSize < pixelSize && scaleNum > 1) { - continue - } +var parseUnit = require('parse-unit') - var intervalStart = lod.offset - var intervalEnd = lod.count + intervalStart +module.exports = toPX - var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1) - var endOffset = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1 +var PIXELS_PER_INCH = 96 - if(endOffset > startOffset) { - gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset) - } +function getPropertyInPX(element, prop) { + var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop)) + return parts[0] * toPX(parts[1], element) +} - if(firstLevel) { - firstLevel = false - shader.uniforms.useWeight = 0 - } - } - } -})() +//This brutal hack is needed +function getSizeBrutal(unit, element) { + var testDIV = document.createElement('div') + testDIV.style['font-size'] = '128' + unit + element.appendChild(testDIV) + var size = getPropertyInPX(testDIV, 'font-size') / 128 + element.removeChild(testDIV) + return size +} -proto.pick = function(x, y, value) { - var pickOffset = this.pickOffset - var pointCount = this.pointCount - if(value < pickOffset || value >= pickOffset + pointCount) { - return null +function toPX(str, element) { + element = element || document.body + str = (str || 'px').trim().toLowerCase() + if(element === window || element === document) { + element = document.body } - var pointId = value - pickOffset - var points = this.points - return { - object: this, - pointId: pointId, - dataCoord: [ points[2*pointId], points[2*pointId+1] ] + switch(str) { + case '%': //Ambiguous, not sure if we should use width or height + return element.clientHeight / 100.0 + case 'ch': + case 'ex': + return getSizeBrutal(str, element) + case 'em': + return getPropertyInPX(element, 'font-size') + case 'rem': + return getPropertyInPX(document.body, 'font-size') + case 'vw': + return window.innerWidth/100 + case 'vh': + return window.innerHeight/100 + case 'vmin': + return Math.min(window.innerWidth, window.innerHeight) / 100 + case 'vmax': + return Math.max(window.innerWidth, window.innerHeight) / 100 + case 'in': + return PIXELS_PER_INCH + case 'cm': + return PIXELS_PER_INCH / 2.54 + case 'mm': + return PIXELS_PER_INCH / 25.4 + case 'pt': + return PIXELS_PER_INCH / 72 + case 'pc': + return PIXELS_PER_INCH / 6 } + return 1 } +},{"parse-unit":243}],245:[function(require,module,exports){ +'use strict' -function createScatter2D(plot, options) { - var gl = plot.gl - var buffer = createBuffer(gl) - var pickBuffer = createBuffer(gl) - var weightBuffer = createBuffer(gl) - var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment) - var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment) - - var result = new Scatter2D( - plot, buffer, pickBuffer, weightBuffer, shader, pickShader) - result.update(options) +var toPX = require('to-px') - //Register with plot - plot.addObject(result) +module.exports = mouseWheelListen - return result +function mouseWheelListen(element, callback, noScroll) { + if(typeof element === 'function') { + noScroll = !!callback + callback = element + element = window + } + var lineHeight = toPX('ex', element) + var listener = function(ev) { + if(noScroll) { + ev.preventDefault() + } + var dx = ev.deltaX || 0 + var dy = ev.deltaY || 0 + var dz = ev.deltaZ || 0 + var mode = ev.deltaMode + var scale = 1 + switch(mode) { + case 1: + scale = lineHeight + break + case 2: + scale = window.innerHeight + break + } + dx *= scale + dy *= scale + dz *= scale + if(dx || dy || dz) { + return callback(dx, dy, dz) + } + } + element.addEventListener('wheel', listener) + return listener } -},{"./lib/shader":747,"binary-search-bounds":748,"gl-buffer":749,"gl-shader":750,"snap-points-2d":777,"typedarray-pool":780}],782:[function(require,module,exports){ +},{"to-px":244}],246:[function(require,module,exports){ "use strict" -var vectorizeText = require("vectorize-text") - -module.exports = getGlyph - -var GLYPH_CACHE = {} - -function getGlyph(symbol, font) { - var fontCache = GLYPH_CACHE[font] - if(!fontCache) { - fontCache = GLYPH_CACHE[font] = {} - } - if(symbol in fontCache) { - return fontCache[symbol] - } - //Get line and triangle meshes for glyph - var lineSymbol = vectorizeText(symbol, { - textAlign: "center", - textBaseline: "middle", - lineHeight: 1.0, - font: font - }) - var triSymbol = vectorizeText(symbol, { - triangles: true, - textAlign: "center", - textBaseline: "middle", - lineHeight: 1.0, - font: font - }) - //Calculate bounding box - var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]] - for(var i=0; i= 1) { - return true - } - for(var i=0; i<3; ++i) { - if(this.axesProject[i] && this.projectOpacity[i] >= 1) { - return true + var w = X[(n+1)*(n+1)-1] + for(var j=0; j>", + rrshift: ">>>" +} +;(function(){ + for(var id in assign_ops) { + var op = assign_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a","b","c"], + body: "a=b"+op+"c"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array","array"], + body: {args:["a","b"], + body:"a"+op+"=b"}, + rvalue: true, + funcName: id+"eq" + }) + exports[id+"s"] = makeOp({ + args: ["array", "array", "scalar"], + body: {args:["a","b","s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"seq"] = makeOp({ + args: ["array","scalar"], + body: {args:["a","s"], + body:"a"+op+"=s"}, + rvalue: true, + funcName: id+"seq" + }) } +})(); - VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth - VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight - - shader.bind() - uniforms.view = view - uniforms.projection = projection - uniforms.screenSize = VIEW_SHAPE - uniforms.highlightId = points.highlightId - uniforms.highlightScale = points.highlightScale - uniforms.clipBounds = clipBounds - uniforms.pickGroup = points.pickId / 255.0 - uniforms.pixelRatio = points.pixelRatio - - for(var i=0; i<3; ++i) { - if(!axesProject[i]) { - continue - } - if((points.projectOpacity[i] < 1) !== transparent) { - continue - } +var unary_ops = { + not: "!", + bnot: "~", + neg: "-", + recip: "1.0/" +} +;(function(){ + for(var id in unary_ops) { + var op = unary_ops[id] + exports[id] = makeOp({ + args: ["array", "array"], + body: {args:["a","b"], + body:"a="+op+"b"}, + funcName: id + }) + exports[id+"eq"] = makeOp({ + args: ["array"], + body: {args:["a"], + body:"a="+op+"a"}, + rvalue: true, + count: 2, + funcName: id+"eq" + }) + } +})(); - uniforms.scale = points.projectScale[i] - uniforms.opacity = points.projectOpacity[i] +var binary_ops = { + and: "&&", + or: "||", + eq: "===", + neq: "!==", + lt: "<", + gt: ">", + leq: "<=", + geq: ">=" +} +;(function() { + for(var id in binary_ops) { + var op = binary_ops[id] + exports[id] = makeOp({ + args: ["array","array","array"], + body: {args:["a", "b", "c"], + body:"a=b"+op+"c"}, + funcName: id + }) + exports[id+"s"] = makeOp({ + args: ["array","array","scalar"], + body: {args:["a", "b", "s"], + body:"a=b"+op+"s"}, + funcName: id+"s" + }) + exports[id+"eq"] = makeOp({ + args: ["array", "array"], + body: {args:["a", "b"], + body:"a=a"+op+"b"}, + rvalue:true, + count:2, + funcName: id+"eq" + }) + exports[id+"seq"] = makeOp({ + args: ["array", "scalar"], + body: {args:["a","s"], + body:"a=a"+op+"s"}, + rvalue:true, + count:2, + funcName: id+"seq" + }) + } +})(); - //Project model matrix - var pmodel = SCRATCH_MATRIX - for(var j=0; j<16; ++j) { - pmodel[j] = 0 - } - for(var j=0; j<4; ++j) { - pmodel[5*j] = 1 - } - pmodel[5*i] = 0 - if(cubeAxis[i] < 0) { - pmodel[12+i] = bounds[0][i] - } else { - pmodel[12+i] = bounds[1][i] - } - mat4mult(pmodel, model, pmodel) - uniforms.model = pmodel +var math_unary = [ + "abs", + "acos", + "asin", + "atan", + "ceil", + "cos", + "exp", + "floor", + "log", + "round", + "sin", + "sqrt", + "tan" +] +;(function() { + for(var i=0; i Math.abs(mdv[1])) { - var tmp = mdu - mdu = mdv - mdv = tmp - tmp = du - du = dv - dv = tmp - var t = u - u = v - v = t - } - if(mdu[0] < 0) { - du[u] = -1 - } - if(mdv[1] > 0) { - dv[v] = -1 - } - var su = 0.0 - var sv = 0.0 - for(var j=0; j<4; ++j) { - su += Math.pow(model[4*u+j], 2) - sv += Math.pow(model[4*v+j], 2) - } - du[u] /= Math.sqrt(su) - dv[v] /= Math.sqrt(sv) - uniforms.axes[0] = du - uniforms.axes[1] = dv +var math_noncomm = [ + "atan2", + "pow" +] +;(function(){ + for(var i=0; i 0) { - gl.lineWidth(points.lineWidth) - points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) - } - } -} +exports.sum = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "sum" +}) +exports.prod = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "prod" +}) -var NEG_INFINITY3 = [-1e8, -1e8, -1e8] -var POS_INFINITY3 = [1e8, 1e8, 1e8] -var CLIP_GROUP = [NEG_INFINITY3, POS_INFINITY3] +exports.norm2squared = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norm2squared" +}) + +exports.norm2 = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"}, + funcName: "norm2" +}) + -function drawFull(shader, pshader, points, camera, transparent, forceDraw) { - var gl = points.gl +exports.norminf = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norminf" +}) - points.vao.bind() +exports.norm1 = compile({ + args:["array"], + pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, + body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, + post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, + funcName: "norm1" +}) - if(transparent === (points.opacity < 1) || forceDraw) { - shader.bind() - var uniforms = shader.uniforms +exports.sup = compile({ + args: [ "array" ], + pre: + { body: "this_h=-Infinity", + args: [], + thisVars: [ "this_h" ], + localVars: [] }, + body: + { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", + args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], + thisVars: [ "this_h" ], + localVars: [] }, + post: + { body: "return this_h", + args: [], + thisVars: [ "this_h" ], + localVars: [] } + }) - uniforms.model = camera.model || IDENTITY - uniforms.view = camera.view || IDENTITY - uniforms.projection = camera.projection || IDENTITY +exports.inf = compile({ + args: [ "array" ], + pre: + { body: "this_h=Infinity", + args: [], + thisVars: [ "this_h" ], + localVars: [] }, + body: + { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", + args:[ + {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, + {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], + thisVars:["this_i","this_v"], + localVars:["_inline_1_k"]}, + post:{ + body:"{return this_i}", + args:[], + thisVars:["this_i"], + localVars:[]} +}) - uniforms.fragClipBounds = CLIP_GROUP - uniforms.clipBounds = points.axes.bounds +exports.random = makeOp({ + args: ["array"], + pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, + body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, + funcName: "random" +}) - uniforms.opacity = points.opacity - uniforms.pickGroup = points.pickId / 255.0 +exports.assign = makeOp({ + args:["array", "array"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assign" }) - uniforms.pixelRatio = points.pixelRatio +exports.assigns = makeOp({ + args:["array", "scalar"], + body: {args:["a", "b"], body:"a=b"}, + funcName: "assigns" }) - //Draw interior - points.vao.draw(gl.TRIANGLES, points.vertexCount) - //Draw edges - if(points.lineWidth > 0) { - gl.lineWidth(points.lineWidth) - points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount) - } - } +exports.equals = compile({ + args:["array", "array"], + pre: EmptyProc, + body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}, + {name:"y", lvalue:false, rvalue:true, count:1}], + body: "if(x!==y){return false}", + localVars: [], + thisVars: []}, + post: {args:[], localVars:[], thisVars:[], body:"return true"}, + funcName: "equals" +}) - drawProject(pshader, points, camera, transparent, forceDraw) - points.vao.unbind() -} -proto.draw = function(camera) { - var shader = this.useOrtho ? this.orthoShader : this.shader - drawFull(shader, this.projectShader, this, camera, false, false) -} +},{"cwise-compiler":109}],253:[function(require,module,exports){ +var iota = require("iota-array") +var isBuffer = require("is-buffer") -proto.drawTransparent = function(camera) { - var shader = this.useOrtho ? this.orthoShader : this.shader - drawFull(shader, this.projectShader, this, camera, true, false) -} +var hasTypedArrays = ((typeof Float64Array) !== "undefined") -proto.drawPick = function(camera) { - var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader - drawFull(shader, this.pickProjectShader, this, camera, false, true) +function compare1st(a, b) { + return a[0] - b[0] } -proto.pick = function(selected) { - if(!selected) { - return null - } - if(selected.id !== this.pickId) { - return null - } - var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16) - if(x >= this.pointCount || x < 0) { - return null +function order() { + var stride = this.stride + var terms = new Array(stride.length) + var i + for(i=0; i>8) &0xff - var a2 = (pointId>>16)&0xff - this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0] - } -} - -proto.update = function(options) { - - options = options || {} - - if('perspective' in options) { - this.useOrtho = !options.perspective - } - if('orthographic' in options) { - this.useOrtho = !!options.orthographic - } - if('lineWidth' in options) { - this.lineWidth = options.lineWidth - } - if('project' in options) { - if(Array.isArray(options.project)) { - this.axesProject = options.project - } else { - var v = !!options.project - this.axesProject = [v,v,v] - } - } - if('projectScale' in options) { - if(Array.isArray(options.projectScale)) { - this.projectScale = options.projectScale.slice() - } else { - var s = +options.projectScale - this.projectScale = [s,s,s] - } - } - if('projectOpacity' in options) { - if(Array.isArray(options.projectOpacity)) { - this.projectOpacity = options.projectOpacity.slice() - } else { - var s = +options.projectOpacity - this.projectOpacity = [s,s,s] - } - } - if('opacity' in options) { - this.opacity = options.opacity +function compileConstructor(dtype, dimension) { + var className = ["View", dimension, "d", dtype].join("") + if(dimension < 0) { + className = "View_Nil" + dtype } + var useGetters = (dtype === "generic") - //Set dirty flag - this.dirty = true - - //Create new buffers - var points = options.position - if(!points) { - return + if(dimension === -1) { + //Special case for trivial arrays + var code = + "function "+className+"(a){this.data=a;};\ +var proto="+className+".prototype;\ +proto.dtype='"+dtype+"';\ +proto.index=function(){return -1};\ +proto.size=0;\ +proto.dimension=-1;\ +proto.shape=proto.stride=proto.order=[];\ +proto.lo=proto.hi=proto.transpose=proto.step=\ +function(){return new "+className+"(this.data);};\ +proto.get=proto.set=function(){};\ +proto.pick=function(){return null};\ +return function construct_"+className+"(a){return new "+className+"(a);}" + var procedure = new Function(code) + return procedure() + } else if(dimension === 0) { + //Special case for 0d arrays + var code = + "function "+className+"(a,d) {\ +this.data = a;\ +this.offset = d\ +};\ +var proto="+className+".prototype;\ +proto.dtype='"+dtype+"';\ +proto.index=function(){return this.offset};\ +proto.dimension=0;\ +proto.size=1;\ +proto.shape=\ +proto.stride=\ +proto.order=[];\ +proto.lo=\ +proto.hi=\ +proto.transpose=\ +proto.step=function "+className+"_copy() {\ +return new "+className+"(this.data,this.offset)\ +};\ +proto.pick=function "+className+"_pick(){\ +return TrivialArray(this.data);\ +};\ +proto.valueOf=proto.get=function "+className+"_get(){\ +return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ +"};\ +proto.set=function "+className+"_set(v){\ +return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ +};\ +return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" + var procedure = new Function("TrivialArray", code) + return procedure(CACHED_CONSTRUCTORS[dtype][0]) } - //Text font - var font = options.font || 'normal' - var alignment = options.alignment || [0,0] - - //Bounds - var lowerBound = [ Infinity, Infinity, Infinity] - var upperBound = [-Infinity,-Infinity,-Infinity] - - //Unpack options - var glyphs = options.glyph - var colors = options.color - var sizes = options.size - var angles = options.angle - var lineColors = options.lineColor - - //Picking geometry - var pickCounter = 0 + var code = ["'use strict'"] - //First do pass to compute buffer sizes - var triVertexCount = 0 - var lineVertexCount = 0 + //Create constructor for view + var indices = iota(dimension) + var args = indices.map(function(i) { return "i"+i }) + var index_str = "this.offset+" + indices.map(function(i) { + return "this.stride[" + i + "]*i" + i + }).join("+") + var shapeArg = indices.map(function(i) { + return "b"+i + }).join(",") + var strideArg = indices.map(function(i) { + return "c"+i + }).join(",") + code.push( + "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a", + "this.shape=[" + shapeArg + "]", + "this.stride=[" + strideArg + "]", + "this.offset=d|0}", + "var proto="+className+".prototype", + "proto.dtype='"+dtype+"'", + "proto.dimension="+dimension) - //Count number of points and buffer size - var numPoints = points.length + //view.size: + code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\ +return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"), +"}})") -count_loop: - for(var i=0; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") + } else if(dimension === 3) { + code.push( +"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ +if(s0>s1){\ +if(s1>s2){\ +return [2,1,0];\ +}else if(s0>s2){\ +return [1,2,0];\ +}else{\ +return [1,0,2];\ +}\ +}else if(s0>s2){\ +return [2,0,1];\ +}else if(s2>s1){\ +return [0,1,2];\ +}else{\ +return [0,2,1];\ +}}})") } - } - - var glyphData - if(Array.isArray(glyphs)) { - glyphData = getGlyph(glyphs[i], font) - } else if(glyphs) { - glyphData = getGlyph(glyphs, font) } else { - glyphData = getGlyph('●', font) + code.push("ORDER})") } - var glyphMesh = glyphData[0] - var glyphLines = glyphData[1] - var glyphBounds = glyphData[2] - - triVertexCount += glyphMesh.cells.length * 3 - lineVertexCount += glyphLines.edges.length * 2 } + //view.set(i0, ..., v): + code.push( +"proto.set=function "+className+"_set("+args.join(",")+",v){") + if(useGetters) { + code.push("return this.data.set("+index_str+",v)}") + } else { + code.push("return this.data["+index_str+"]=v}") + } - //Preallocate data - var vertexCount = triVertexCount + lineVertexCount - var positionArray = pool.mallocFloat(3*vertexCount) - var colorArray = pool.mallocFloat(4*vertexCount) - var glyphArray = pool.mallocFloat(2*vertexCount) - var idArray = pool.mallocUint32(vertexCount) - - var textOffset = [0,alignment[1]] - - var triOffset = 0 - var lineOffset = triVertexCount - var color = [0,0,0,1] - var lineColor = [0,0,0,1] + //view.get(i0, ...): + code.push("proto.get=function "+className+"_get("+args.join(",")+"){") + if(useGetters) { + code.push("return this.data.get("+index_str+")}") + } else { + code.push("return this.data["+index_str+"]}") + } - var isColorArray = Array.isArray(colors) && Array.isArray(colors[0]) - var isLineColorArray = Array.isArray(lineColors) && Array.isArray(lineColors[0]) + //view.index: + code.push( + "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") -fill_loop: - for(var i=0; i=0){\ +d=i"+i+"|0;\ +b+=c"+i+"*d;\ +a"+i+"-=d}") + } + code.push("return new "+className+"(this.data,"+ + indices.map(function(i) { + return "a"+i + }).join(",")+","+ + indices.map(function(i) { + return "c"+i + }).join(",")+",b)}") - var glyphData - if(Array.isArray(glyphs)) { - glyphData = getGlyph(glyphs[i], font) - } else if(glyphs) { - glyphData = getGlyph(glyphs, font) - } else { - glyphData = getGlyph('●', font) - } - var glyphMesh = glyphData[0] - var glyphLines = glyphData[1] - var glyphBounds = glyphData[2] + //view.step(): + code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ + indices.map(function(i) { + return "a"+i+"=this.shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "b"+i+"=this.stride["+i+"]" + }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") + for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + } + code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") - //Get lineColor - if(Array.isArray(lineColors)) { - var c - if(isLineColorArray) { - c = lineColors[i] - } else { - c = lineColors - } - if(c.length === 3) { - for(var j=0; j<3; ++j) { - lineColor[j] = c[j] - } - lineColor[j] = 1 - } else if(c.length === 4) { - for(var j=0; j<4; ++j) { - lineColor[j] = c[j] - } - } - } else { - lineColor[0] = lineColor[1] = lineColor[2] = 0 - lineColor[3] = 1 - } + //Add return statement + code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ + indices.map(function(i) { + return "shape["+i+"]" + }).join(",")+","+ + indices.map(function(i) { + return "stride["+i+"]" + }).join(",")+",offset)}") - var size = 0.5 - if(Array.isArray(sizes)) { - size = +sizes[i] - } else if(sizes) { - size = +sizes - } else if(this.useOrtho) { - size = 12 - } + //Compile procedure + var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) + return procedure(CACHED_CONSTRUCTORS[dtype], order) +} - var angle = 0 - if(Array.isArray(angles)) { - angle = +angles[i] - } else if(angles) { - angle = +angles +function arrayDType(data) { + if(isBuffer(data)) { + return "buffer" + } + if(hasTypedArrays) { + switch(Object.prototype.toString.call(data)) { + case "[object Float64Array]": + return "float64" + case "[object Float32Array]": + return "float32" + case "[object Int8Array]": + return "int8" + case "[object Int16Array]": + return "int16" + case "[object Int32Array]": + return "int32" + case "[object Uint8Array]": + return "uint8" + case "[object Uint16Array]": + return "uint16" + case "[object Uint32Array]": + return "uint32" + case "[object Uint8ClampedArray]": + return "uint8_clamped" } + } + if(Array.isArray(data)) { + return "array" + } + return "generic" +} - //Loop through markers and append to buffers - var cos = Math.cos(angle) - var sin = Math.sin(angle) +var CACHED_CONSTRUCTORS = { + "float32":[], + "float64":[], + "int8":[], + "int16":[], + "int32":[], + "uint8":[], + "uint16":[], + "uint32":[], + "array":[], + "uint8_clamped":[], + "buffer":[], + "generic":[] +} - var x = points[i] - for(var j=0; j<3; ++j) { - upperBound[j] = Math.max(upperBound[j], x[j]) - lowerBound[j] = Math.min(lowerBound[j], x[j]) - } +;(function() { + for(var id in CACHED_CONSTRUCTORS) { + CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) + } +}); - //Calculate text offset - if(alignment[0] < 0) { - textOffset[0] = alignment[0] * (1+glyphBounds[1][0]) - } else if(alignment[0] > 0) { - textOffset[0] = -alignment[0] * (1+glyphBounds[0][0]) +function wrappedNDArrayCtor(data, shape, stride, offset) { + if(data === undefined) { + var ctor = CACHED_CONSTRUCTORS.array[0] + return ctor([]) + } else if(typeof data === "number") { + data = [data] + } + if(shape === undefined) { + shape = [ data.length ] + } + var d = shape.length + if(stride === undefined) { + stride = new Array(d) + for(var i=d-1, sz=1; i>=0; --i) { + stride[i] = sz + sz *= shape[i] } - - //Write out inner marker - var cells = glyphMesh.cells - var verts = glyphMesh.positions - - for(var j=0; j + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - //Increment pickCounter - pickCounter += 1 - } +'use strict'; +/** + * Results cache + */ - //Update vertex counts - this.vertexCount = triVertexCount - this.lineVertexCount = lineVertexCount +var res = ''; +var cache; - //Update buffers - this.pointBuffer.update(positionArray) - this.colorBuffer.update(colorArray) - this.glyphBuffer.update(glyphArray) - this.idBuffer.update(new Uint32Array(idArray)) +/** + * Expose `repeat` + */ - pool.free(positionArray) - pool.free(colorArray) - pool.free(glyphArray) - pool.free(idArray) +module.exports = repeat; - //Update bounds - this.bounds = [lowerBound, upperBound] +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ - //Save points - this.points = points +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('repeat-string expects a string.'); + } - //Save number of points - this.pointCount = points.length -} + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; -proto.dispose = function() { - //Shaders - this.shader.dispose() - this.orthoShader.dispose() - this.pickPerspectiveShader.dispose() - this.pickOrthoShader.dispose() + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } - //Vertex array - this.vao.dispose() + while (max > res.length && num > 0) { + if (num & 1) { + res += str; + } - //Buffers - this.pointBuffer.dispose() - this.colorBuffer.dispose() - this.glyphBuffer.dispose() - this.idBuffer.dispose() + num >>= 1; + if (!num) break; + str += str; + } + + return res.substr(0, max); } -function createPointCloud(options) { - var gl = options.gl - var shader = shaders.createPerspective(gl) - var orthoShader = shaders.createOrtho(gl) - var projectShader = shaders.createProject(gl) - var pickPerspectiveShader = shaders.createPickPerspective(gl) - var pickOrthoShader = shaders.createPickOrtho(gl) - var pickProjectShader = shaders.createPickProject(gl) +},{}],255:[function(require,module,exports){ +(function (global){ +module.exports = + global.performance && + global.performance.now ? function now() { + return performance.now() + } : Date.now || function now() { + return +new Date + } - var pointBuffer = createBuffer(gl) - var colorBuffer = createBuffer(gl) - var glyphBuffer = createBuffer(gl) - var idBuffer = createBuffer(gl) - var vao = createVAO(gl, [ - { - buffer: pointBuffer, - size: 3, - type: gl.FLOAT - }, - { - buffer: colorBuffer, - size: 4, - type: gl.FLOAT - }, - { - buffer: glyphBuffer, - size: 2, - type: gl.FLOAT - }, - { - buffer: idBuffer, - size: 4, - type: gl.UNSIGNED_BYTE, - normalized: true - } - ]) +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],256:[function(require,module,exports){ +"use strict" - var pointCloud = new PointCloud( - gl, - shader, - orthoShader, - projectShader, - pointBuffer, - colorBuffer, - glyphBuffer, - idBuffer, - vao, - pickPerspectiveShader, - pickOrthoShader, - pickProjectShader) +var determinant = require("robust-determinant") - pointCloud.update(options) +var NUM_EXPAND = 6 - return pointCloud +function generateSolver(n) { + var funcName = "robustLinearSolve" + n + "d" + var code = ["function ", funcName, "(A,b){return ["] + for(var i=0; i 0) { + code.push(",") + } + code.push("[") + for(var k=0; k 0) { + code.push(",") + } + if(k === i) { + code.push("+b[", j, "]") + } else { + code.push("+A[", j, "][", k, "]") + } + } + code.push("]") + } + code.push("]),") + } + code.push("det(A)]}return ", funcName) + var proc = new Function("det", code.join("")) + if(n < 6) { + return proc(determinant[n]) + } + return proc(determinant) } -},{"./lib/glyphs":782,"./lib/shaders":783,"gl-buffer":784,"gl-mat4/multiply":242,"gl-vao":814,"typedarray-pool":817}],906:[function(require,module,exports){ -'use strict' +function robustLinearSolve0d() { + return [ 0 ] +} +function robustLinearSolve1d(A, b) { + return [ [ b[0] ], [ A[0][0] ] ] +} +var CACHE = [ + robustLinearSolve0d, + robustLinearSolve1d +] -exports.boxVertex = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n" -exports.boxFragment = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n" +function generateDispatch() { + while(CACHE.length < NUM_EXPAND) { + CACHE.push(generateSolver(CACHE.length)) + } + var procArgs = [] + var code = ["function dispatchLinearSolve(A,b){switch(A.length){"] + for(var i=0; i=0; --i) { + var a = Q + var b = e[i] + Q = a + b + var bv = Q - a + var q = b - bv + if(q) { + e[--bottom] = Q + Q = q + } + } + var top = 0 + for(var i=bottom; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") + } +} -proto.draw = function() { - if(!this.enabled) { - return +function determinant(m) { + if(m.length === 2) { + return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("") + } else { + var expr = [] + for(var i=0; i>1 + return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") } +} - //Draw border - if(lineWidth > 0) { +function determinant(m) { + if(m.length === 2) { + return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] + } else { + var expr = [] + for(var i=0; i 0) { + if(r <= 0) { + return det + } else { + s = l + r + } + } else if(l < 0) { + if(r >= 0) { + return det + } else { + s = -(l + r) + } + } else { + return det + } + var tol = ERRBOUND3 * s + if(det >= tol || det <= -tol) { + return det + } + return orientation3Exact(a, b, c) + }, + function orientation4(a,b,c,d) { + var adx = a[0] - d[0] + var bdx = b[0] - d[0] + var cdx = c[0] - d[0] + var ady = a[1] - d[1] + var bdy = b[1] - d[1] + var cdy = c[1] - d[1] + var adz = a[2] - d[2] + var bdz = b[2] - d[2] + var cdz = c[2] - d[2] + var bdxcdy = bdx * cdy + var cdxbdy = cdx * bdy + var cdxady = cdx * ady + var adxcdy = adx * cdy + var adxbdy = adx * bdy + var bdxady = bdx * ady + var det = adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady) + var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) + var tol = ERRBOUND4 * permanent + if ((det > tol) || (-det > tol)) { + return det + } + return orientation4Exact(a,b,c,d) + } +] -proto.dispose = function() { - this.boxBuffer.dispose() - this.boxShader.dispose() - this.plot.removeOverlay(this) +function slowOrient(args) { + var proc = CACHED[args.length] + if(!proc) { + proc = CACHED[args.length] = orientation(args.length) + } + return proc.apply(undefined, args) } -function createSelectBox(plot, options) { - var gl = plot.gl - var buffer = createBuffer(gl, [ - 0, 0, - 0, 1, - 1, 0, - 1, 1 ]) - var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment) - var selectBox = new SelectBox(plot, buffer, shader) - selectBox.update(options) - plot.addOverlay(selectBox) - return selectBox -} +function generateOrientationProc() { + while(CACHED.length <= NUM_EXPAND) { + CACHED.push(orientation(CACHED.length)) + } + var args = [] + var procArgs = ["slow"] + for(var i=0; i<=NUM_EXPAND; ++i) { + args.push("a" + i) + procArgs.push("o" + i) + } + var code = [ + "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" + ] + for(var i=2; i<=NUM_EXPAND; ++i) { + code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") + } + code.push("}var s=new Array(arguments.length);for(var i=0;i= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } + } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + fa = abs(fi) + } + } + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + } + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = -f[fptr] + } + } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g +} +},{}],262:[function(require,module,exports){ +"use strict" - if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] && - dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) { +module.exports = linearExpansionSum - var centerX = viewPixels[0] + (spikeCenter[0] - dataBox[0]) / (dataBox[2] - dataBox[0]) * (viewPixels[2] - viewPixels[0]) - var centerY = viewPixels[1] + (spikeCenter[1] - dataBox[1]) / (dataBox[3] - dataBox[1]) * (viewPixels[3] - viewPixels[1]) +//Easy case: Add two scalars +function scalarScalar(a, b) { + var x = a + b + var bv = x - a + var av = x - bv + var br = b - bv + var ar = a - av + var y = ar + br + if(y) { + return [y, x] + } + return [x] +} - if(spikeEnable[0]) { - line.drawLine( - centerX, centerY, - viewPixels[0], centerY, - spikeWidth[0], spikeColor[0]) +function linearExpansionSum(e, f) { + var ne = e.length|0 + var nf = f.length|0 + if(ne === 1 && nf === 1) { + return scalarScalar(e[0], f[0]) + } + var n = ne + nf + var g = new Array(n) + var count = 0 + var eptr = 0 + var fptr = 0 + var abs = Math.abs + var ei = e[eptr] + var ea = abs(ei) + var fi = f[fptr] + var fa = abs(fi) + var a, b + if(ea < fa) { + b = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + b = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } + } + if((eptr < ne && ea < fa) || (fptr >= nf)) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } + } + var x = a + b + var bv = x - a + var y = b - bv + var q0 = y + var q1 = x + var _x, _bv, _av, _br, _ar + while(eptr < ne && fptr < nf) { + if(ea < fa) { + a = ei + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + ea = abs(ei) + } + } else { + a = fi + fptr += 1 + if(fptr < nf) { + fi = f[fptr] + fa = abs(fi) + } } - if(spikeEnable[1]) { - line.drawLine( - centerX, centerY, - centerX, viewPixels[1], - spikeWidth[1], spikeColor[1]) + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y } - if(spikeEnable[2]) { - line.drawLine( - centerX, centerY, - viewPixels[2], centerY, - spikeWidth[2], spikeColor[2]) + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + } + while(eptr < ne) { + a = ei + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y } - if(spikeEnable[3]) { - line.drawLine( - centerX, centerY, - centerX, viewPixels[3], - spikeWidth[3], spikeColor[3]) + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + eptr += 1 + if(eptr < ne) { + ei = e[eptr] + } + } + while(fptr < nf) { + a = fi + b = q0 + x = a + b + bv = x - a + y = b - bv + if(y) { + g[count++] = y + } + _x = q1 + x + _bv = _x - q1 + _av = _x - _bv + _br = x - _bv + _ar = q1 - _av + q0 = _ar + _br + q1 = _x + fptr += 1 + if(fptr < nf) { + fi = f[fptr] } } + if(q0) { + g[count++] = q0 + } + if(q1) { + g[count++] = q1 + } + if(!count) { + g[count++] = 0.0 + } + g.length = count + return g } +},{}],263:[function(require,module,exports){ +'use strict' -proto.dispose = function() { - this.plot.removeOverlay(this) +module.exports = toSuperScript + +var SUPERSCRIPTS = { + ' ': ' ', + '0': '⁰', + '1': '¹', + '2': '²', + '3': '³', + '4': '⁴', + '5': '⁵', + '6': '⁶', + '7': '⁷', + '8': '⁸', + '9': '⁹', + '+': '⁺', + '-': '⁻', + 'a': 'ᵃ', + 'b': 'ᵇ', + 'c': 'ᶜ', + 'd': 'ᵈ', + 'e': 'ᵉ', + 'f': 'ᶠ', + 'g': 'ᵍ', + 'h': 'ʰ', + 'i': 'ⁱ', + 'j': 'ʲ', + 'k': 'ᵏ', + 'l': 'ˡ', + 'm': 'ᵐ', + 'n': 'ⁿ', + 'o': 'ᵒ', + 'p': 'ᵖ', + 'r': 'ʳ', + 's': 'ˢ', + 't': 'ᵗ', + 'u': 'ᵘ', + 'v': 'ᵛ', + 'w': 'ʷ', + 'x': 'ˣ', + 'y': 'ʸ', + 'z': 'ᶻ' } -function createSpikes2D(plot, options) { - var spikes = new GLSpikes2D(plot) - spikes.update(options) - plot.addOverlay(spikes) - return spikes +function toSuperScript(x) { + return x.split('').map(function(c) { + if(c in SUPERSCRIPTS) { + return SUPERSCRIPTS[c] + } + return '' + }).join('') } -},{}],939:[function(require,module,exports){ -var createShader = require('gl-shader') +},{}],264:[function(require,module,exports){ +"use strict" +var pool = require("typedarray-pool") -var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n" -var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n" -var contourVertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n" -var pickSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n" +module.exports = createSurfaceExtractor -exports.createShader = function (gl) { - var shader = createShader(gl, vertSrc, fragSrc, null, [ - {name: 'uv', type: 'vec4'}, - {name: 'f', type: 'vec3'}, - {name: 'normal', type: 'vec3'} - ]) - shader.attributes.uv.location = 0 - shader.attributes.f.location = 1 - shader.attributes.normal.location = 2 - return shader +//Helper macros +function array(i) { + return "a" + i } -exports.createPickShader = function (gl) { - var shader = createShader(gl, vertSrc, pickSrc, null, [ - {name: 'uv', type: 'vec4'}, - {name: 'f', type: 'vec3'}, - {name: 'normal', type: 'vec3'} - ]) - shader.attributes.uv.location = 0 - shader.attributes.f.location = 1 - shader.attributes.normal.location = 2 - return shader +function data(i) { + return "d" + i } -exports.createContourShader = function (gl) { - var shader = createShader(gl, contourVertSrc, fragSrc, null, [ - {name: 'uv', type: 'vec4'}, - {name: 'f', type: 'float'} - ]) - shader.attributes.uv.location = 0 - shader.attributes.f.location = 1 - return shader +function cube(i,bitmask) { + return "c" + i + "_" + bitmask } -exports.createPickContourShader = function (gl) { - var shader = createShader(gl, contourVertSrc, pickSrc, null, [ - {name: 'uv', type: 'vec4'}, - {name: 'f', type: 'float'} - ]) - shader.attributes.uv.location = 0 - shader.attributes.f.location = 1 - return shader +function shape(i) { + return "s" + i } +function stride(i,j) { + return "t" + i + "_" + j +} +function offset(i) { + return "o" + i +} +function scalar(i) { + return "x" + i +} +function pointer(i) { + return "p" + i +} +function delta(i,bitmask) { + return "d" + i + "_" + bitmask +} +function index(i) { + return "i" + i +} +function step(i,j) { + return "u" + i + "_" + j +} +function pcube(bitmask) { + return "b" + bitmask +} +function qcube(bitmask) { + return "y" + bitmask +} +function pdelta(bitmask) { + return "e" + bitmask +} +function vert(i) { + return "v" + i +} +var VERTEX_IDS = "V" +var PHASES = "P" +var VERTEX_COUNT = "N" +var POOL_SIZE = "Q" +var POINTER = "X" +var TEMPORARY = "T" -},{"gl-shader":947}],940:[function(require,module,exports){ -arguments[4][21][0].apply(exports,arguments) -},{"dup":21}],941:[function(require,module,exports){ -arguments[4][77][0].apply(exports,arguments) -},{"dup":77}],942:[function(require,module,exports){ -arguments[4][262][0].apply(exports,arguments) -},{"dup":262}],943:[function(require,module,exports){ -arguments[4][263][0].apply(exports,arguments) -},{"./colorScales":942,"arraytools":64,"clone":944,"dup":263}],944:[function(require,module,exports){ -arguments[4][264][0].apply(exports,arguments) -},{"buffer":65,"dup":264}],945:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],946:[function(require,module,exports){ -arguments[4][93][0].apply(exports,arguments) -},{"dup":93,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":1002}],947:[function(require,module,exports){ -arguments[4][94][0].apply(exports,arguments) -},{"./lib/GLError":948,"./lib/create-attributes":949,"./lib/create-uniforms":950,"./lib/reflect":951,"./lib/runtime-reflect":952,"./lib/shader-cache":953,"dup":94}],948:[function(require,module,exports){ -arguments[4][95][0].apply(exports,arguments) -},{"dup":95}],949:[function(require,module,exports){ -arguments[4][96][0].apply(exports,arguments) -},{"./GLError":948,"dup":96}],950:[function(require,module,exports){ -arguments[4][97][0].apply(exports,arguments) -},{"./GLError":948,"./reflect":951,"dup":97}],951:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],952:[function(require,module,exports){ -arguments[4][99][0].apply(exports,arguments) -},{"dup":99}],953:[function(require,module,exports){ -arguments[4][100][0].apply(exports,arguments) -},{"./GLError":948,"dup":100,"gl-format-compiler-error":954,"weakmap-shim":972}],954:[function(require,module,exports){ -arguments[4][101][0].apply(exports,arguments) -},{"add-line-numbers":955,"dup":101,"gl-constants/lookup":959,"glsl-shader-name":960,"sprintf-js":969}],955:[function(require,module,exports){ -arguments[4][102][0].apply(exports,arguments) -},{"dup":102,"pad-left":956}],956:[function(require,module,exports){ -arguments[4][103][0].apply(exports,arguments) -},{"dup":103,"repeat-string":957}],957:[function(require,module,exports){ -arguments[4][104][0].apply(exports,arguments) -},{"dup":104}],958:[function(require,module,exports){ -arguments[4][105][0].apply(exports,arguments) -},{"dup":105}],959:[function(require,module,exports){ -arguments[4][106][0].apply(exports,arguments) -},{"./1.0/numbers":958,"dup":106}],960:[function(require,module,exports){ -arguments[4][107][0].apply(exports,arguments) -},{"atob-lite":961,"dup":107,"glsl-tokenizer":968}],961:[function(require,module,exports){ -arguments[4][108][0].apply(exports,arguments) -},{"dup":108}],962:[function(require,module,exports){ -arguments[4][109][0].apply(exports,arguments) -},{"./lib/builtins":964,"./lib/builtins-300es":963,"./lib/literals":966,"./lib/literals-300es":965,"./lib/operators":967,"dup":109}],963:[function(require,module,exports){ -arguments[4][110][0].apply(exports,arguments) -},{"./builtins":964,"dup":110}],964:[function(require,module,exports){ -arguments[4][111][0].apply(exports,arguments) -},{"dup":111}],965:[function(require,module,exports){ -arguments[4][112][0].apply(exports,arguments) -},{"./literals":966,"dup":112}],966:[function(require,module,exports){ -arguments[4][113][0].apply(exports,arguments) -},{"dup":113}],967:[function(require,module,exports){ -arguments[4][114][0].apply(exports,arguments) -},{"dup":114}],968:[function(require,module,exports){ -arguments[4][115][0].apply(exports,arguments) -},{"./index":962,"dup":115}],969:[function(require,module,exports){ -arguments[4][116][0].apply(exports,arguments) -},{"dup":116}],970:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"./hidden-store.js":971,"dup":117}],971:[function(require,module,exports){ -arguments[4][118][0].apply(exports,arguments) -},{"dup":118}],972:[function(require,module,exports){ -arguments[4][119][0].apply(exports,arguments) -},{"./create-store.js":970,"dup":119}],973:[function(require,module,exports){ -arguments[4][188][0].apply(exports,arguments) -},{"dup":188,"ndarray":1031,"ndarray-ops":1026,"typedarray-pool":1002}],974:[function(require,module,exports){ -arguments[4][154][0].apply(exports,arguments) -},{"dup":154}],975:[function(require,module,exports){ -arguments[4][155][0].apply(exports,arguments) -},{"./do-bind.js":974,"dup":155}],976:[function(require,module,exports){ -arguments[4][156][0].apply(exports,arguments) -},{"./do-bind.js":974,"dup":156}],977:[function(require,module,exports){ -arguments[4][157][0].apply(exports,arguments) -},{"./lib/vao-emulated.js":975,"./lib/vao-native.js":976,"dup":157}],978:[function(require,module,exports){ -'use strict' - -module.exports = gradient - -var dup = require('dup') -var cwiseCompiler = require('cwise-compiler') +function permBitmask(dimension, mask, order) { + var r = 0 + for(var i=0; i 0) { + stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) ) + } + vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0") + } + } + //Create index variables + for(var i=0; i=0; --i) { + sizeVariable.push(shape(order[i])) + } + //Previous phases and vertex_ids + vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0", + PHASES + "=mallocUint32(" + POOL_SIZE + ")", + VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")", + POINTER + "=0") + //Create cube variables for phases + vars.push(pcube(0) + "=0") + for(var j=1; j<(1<=0; --i) { + forLoopBegin(i, 0) + } + var phaseFuncArgs = [] + for(var i=0; i= 0) { - pickStr.push('0') - } else if(facet.indexOf(-(i+1)) >= 0) { - pickStr.push('s['+i+']-1') - } else { - pickStr.push('-1') - loStr.push('1') - hiStr.push('s['+i+']-2') - } + //Check for boundary crossing + var vertexPredicate = [] + for(var j=1; j<(1< 0) { - code.push('if(1') - for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { - continue - } - code.push('&&s[', i, ']>2') - } - code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr) - for(var i=0; i= 0 || facet.indexOf(-(i+1)) >= 0) { - continue + for(var i=0; i1){dst.set(', - pickStr.join(), ',', bnd, ',0.5*(src.get(', - cPickStr.join(), ')-src.get(', - dPickStr.join(), ')))}else{dst.set(', - pickStr.join(), ',', bnd, ',0)};') - } else { - code.push('if(s[', bnd, ']>1){diff(', outStr, - ',src.pick(', cPickStr.join(), ')', boundStr, - ',src.pick(', dPickStr.join(), ')', boundStr, - ');}else{zero(', outStr, ');};') - } - break - - case 'mirror': - if(cod === 0) { - code.push('dst.set(', pickStr.join(), ',', bnd, ',0);') - } else { - code.push('zero(', outStr, ');') - } - break + //Generate vertex + code.push("vertex(", vertexArgs.join(), ");", + vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;") - case 'wrap': - var aPickStr = pickStr.slice() - var bPickStr = pickStr.slice() - if(facet[i] < 0) { - aPickStr[bnd] = 's[' + bnd + ']-2' - bPickStr[bnd] = '0' - - } else { - aPickStr[bnd] = 's[' + bnd + ']-1' - bPickStr[bnd] = '1' - } - if(cod === 0) { - code.push('if(s[', bnd, ']>2){dst.set(', - pickStr.join(), ',', bnd, ',0.5*(src.get(', - aPickStr.join(), ')-src.get(', - bPickStr.join(), ')))}else{dst.set(', - pickStr.join(), ',', bnd, ',0)};') + //Check for face crossings + var base = (1<0; k=(k-1)&subset) { + faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]") + } + faceArgs.push(vert(0)) + for(var k=0; k2){diff(', outStr, - ',src.pick(', aPickStr.join(), ')', boundStr, - ',src.pick(', bPickStr.join(), ')', boundStr, - ');}else{zero(', outStr, ');};') + faceArgs.push(cube(k,subset), cube(k,base)) } - break - - default: - throw new Error('ndarray-gradient: Invalid boundary condition') + } + if(j&1) { + faceArgs.push(corner, edge) + } else { + faceArgs.push(edge, corner) + } + for(var k=0; k 0) { - code.push('};') + function flip() { + for(var j=1; j<(1<0){", + index(order[i]), "=1;") + createLoop(i-1, mask|(1< 0") } - if(inp.dimension <= 0) { - out.set(0) - return out + if(typeof args.vertex !== "function") { + error("Must specify vertex creation function") } - var cached = generateGradient(bc) - return cached(out, inp) -} -},{"cwise-compiler":979,"dup":945}],979:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":981,"dup":319}],980:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":982}],981:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":980,"dup":321}],982:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],983:[function(require,module,exports){ -"use strict" - -var ndarray = require("ndarray") -var do_convert = require("./doConvert.js") - -module.exports = function convert(arr, result) { - var shape = [], c = arr, sz = 1 - while(c instanceof Array) { - shape.push(c.length) - sz *= c.length - c = c[0] + if(typeof args.cell !== "function") { + error("Must specify cell creation function") } - if(shape.length === 0) { - return ndarray() + if(typeof args.phase !== "function") { + error("Must specify phase function") } - if(!result) { - result = ndarray(new Float64Array(sz), shape) + var getters = args.getters || [] + var typesig = new Array(arrays) + for(var i=0; i= 0) { + typesig[i] = true + } else { + typesig[i] = false + } } - do_convert(result, arr) - return result + return compileSurfaceProcedure( + args.vertex, + args.cell, + args.phase, + scalars, + order, + typesig) } +},{"typedarray-pool":278}],265:[function(require,module,exports){ +// transliterated from the python snippet here: +// http://en.wikipedia.org/wiki/Lanczos_approximation -},{"./doConvert.js":984,"ndarray":1031}],984:[function(require,module,exports){ -module.exports=require('cwise-compiler')({"args":["array","scalar","index"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}","args":[{"name":"_inline_1_arg0_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":4}],"thisVars":[],"localVars":["_inline_1_i","_inline_1_v"]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"funcName":"convert","blockSize":64}) - -},{"cwise-compiler":985}],985:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":987,"dup":319}],986:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":988}],987:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":986,"dup":321}],988:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],989:[function(require,module,exports){ -arguments[4][429][0].apply(exports,arguments) -},{"dup":429,"typedarray-pool":1002}],990:[function(require,module,exports){ -arguments[4][433][0].apply(exports,arguments) -},{"dup":433}],991:[function(require,module,exports){ -arguments[4][437][0].apply(exports,arguments) -},{"dup":437,"typedarray-pool":1002}],992:[function(require,module,exports){ -arguments[4][438][0].apply(exports,arguments) -},{"dup":438,"invert-permutation":993,"typedarray-pool":1002}],993:[function(require,module,exports){ -arguments[4][439][0].apply(exports,arguments) -},{"dup":439}],994:[function(require,module,exports){ -arguments[4][443][0].apply(exports,arguments) -},{"dup":443,"gamma":990,"permutation-parity":991,"permutation-rank":992}],995:[function(require,module,exports){ -arguments[4][444][0].apply(exports,arguments) -},{"cwise-compiler":996,"dup":444}],996:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":998,"dup":319}],997:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":999}],998:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":997,"dup":321}],999:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],1000:[function(require,module,exports){ -arguments[4][449][0].apply(exports,arguments) -},{"./lib/zc-core":995,"dup":449}],1001:[function(require,module,exports){ -arguments[4][450][0].apply(exports,arguments) -},{"dup":450,"ndarray-extract-contour":989,"triangulate-hypercube":994,"zero-crossings":1000}],1002:[function(require,module,exports){ -arguments[4][122][0].apply(exports,arguments) -},{"bit-twiddle":941,"buffer":65,"dup":122}],1003:[function(require,module,exports){ -'use strict' - -module.exports = createSurfacePlot - -var bits = require('bit-twiddle') -var createBuffer = require('gl-buffer') -var createVAO = require('gl-vao') -var createTexture = require('gl-texture2d') -var pool = require('typedarray-pool') -var colormap = require('colormap') -var ops = require('ndarray-ops') -var pack = require('ndarray-pack') -var ndarray = require('ndarray') -var surfaceNets = require('surface-nets') -var multiply = require('gl-mat4/multiply') -var invert = require('gl-mat4/invert') -var bsearch = require('binary-search-bounds') -var gradient = require('ndarray-gradient') -var shaders = require('./lib/shaders') - -var createShader = shaders.createShader -var createContourShader = shaders.createContourShader -var createPickShader = shaders.createPickShader -var createPickContourShader = shaders.createPickContourShader - -var SURFACE_VERTEX_SIZE = 4 * (4 + 3 + 3) - -var IDENTITY = [ - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 ] - -var QUAD = [ - [0, 0], - [0, 1], - [1, 0], - [1, 1], - [1, 0], - [0, 1] -] - -var PERMUTATIONS = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0] -] - -;(function () { - for (var i = 0; i < 3; ++i) { - var p = PERMUTATIONS[i] - var u = (i + 1) % 3 - var v = (i + 2) % 3 - p[u + 0] = 1 - p[v + 3] = 1 - p[i + 6] = 1 - } -})() +var g = 7; +var p = [ + 0.99999999999980993, + 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 +]; -function SurfacePickResult (position, index, uv, level, dataCoordinate) { - this.position = position - this.index = index - this.uv = uv - this.level = level - this.dataCoordinate = dataCoordinate -} +var g_ln = 607/128; +var p_ln = [ + 0.99999999999999709182, + 57.156235665862923517, + -59.597960355475491248, + 14.136097974741747174, + -0.49191381609762019978, + 0.33994649984811888699e-4, + 0.46523628927048575665e-4, + -0.98374475304879564677e-4, + 0.15808870322491248884e-3, + -0.21026444172410488319e-3, + 0.21743961811521264320e-3, + -0.16431810653676389022e-3, + 0.84418223983852743293e-4, + -0.26190838401581408670e-4, + 0.36899182659531622704e-5 +]; -var N_COLORS = 265 +// Spouge approximation (suitable for large arguments) +function lngamma(z) { -function genColormap (name) { - var x = pack([colormap({ - colormap: name, - nshades: N_COLORS, - format: 'rgba' - }).map(function (c) { - return [c[0], c[1], c[2], 255 * c[3]] - })]) - ops.divseq(x, 255.0) - return x + if(z < 0) return Number('0/0'); + var x = p_ln[0]; + for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i); + var t = z + g_ln + 0.5; + return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z); } -function SurfacePlot ( - gl, - shape, - bounds, - shader, - pickShader, - coordinates, - vao, - colorMap, - contourShader, - contourPickShader, - contourBuffer, - contourVAO, - dynamicBuffer, - dynamicVAO) { - this.gl = gl - this.shape = shape - this.bounds = bounds - this.intensityBounds = []; - - this._shader = shader - this._pickShader = pickShader - this._coordinateBuffer = coordinates - this._vao = vao - this._colorMap = colorMap - - this._contourShader = contourShader - this._contourPickShader = contourPickShader - this._contourBuffer = contourBuffer - this._contourVAO = contourVAO - this._contourOffsets = [[], [], []] - this._contourCounts = [[], [], []] - this._vertexCount = 0 - - this._pickResult = new SurfacePickResult([0, 0, 0], [0, 0], [0, 0], [0, 0, 0], [0, 0, 0]) +module.exports = function gamma (z) { + if (z < 0.5) { + return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z)); + } + else if(z > 100) return Math.exp(lngamma(z)); + else { + z -= 1; + var x = p[0]; + for (var i = 1; i < g + 2; i++) { + x += p[i] / (z + i); + } + var t = z + g + 0.5; - this._dynamicBuffer = dynamicBuffer - this._dynamicVAO = dynamicVAO - this._dynamicOffsets = [0, 0, 0] - this._dynamicCounts = [0, 0, 0] + return Math.sqrt(2 * Math.PI) + * Math.pow(t, z + 0.5) + * Math.exp(-t) + * x + ; + } +}; - this.contourWidth = [ 1, 1, 1 ] - this.contourLevels = [[1], [1], [1]] - this.contourTint = [0, 0, 0] - this.contourColor = [[0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1], [0.5, 0.5, 0.5, 1]] +module.exports.log = lngamma; - this.showContour = true - this.showSurface = true +},{}],266:[function(require,module,exports){ +"use strict" - this.enableHighlight = [true, true, true] - this.highlightColor = [[0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]] - this.highlightTint = [ 1, 1, 1 ] - this.highlightLevel = [-1, -1, -1] +module.exports = permutationSign - // Dynamic contour options - this.enableDynamic = [ true, true, true ] - this.dynamicLevel = [ NaN, NaN, NaN ] - this.dynamicColor = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ] - this.dynamicTint = [ 1, 1, 1 ] - this.dynamicWidth = [ 1, 1, 1 ] +var BRUTE_FORCE_CUTOFF = 32 - this.axesBounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]] - this.surfaceProject = [ false, false, false ] - this.contourProject = [[ false, false, false ], - [ false, false, false ], - [ false, false, false ]] +var pool = require("typedarray-pool") - this.colorBounds = [ false, false ] +function permutationSign(p) { + var n = p.length + if(n < BRUTE_FORCE_CUTOFF) { + //Use quadratic algorithm for small n + var sgn = 1 + for(var i=0; i0; --i) { + t = pinv[i] + s = p[i] + p[i] = p[t] + p[t] = s + pinv[i] = pinv[s] + pinv[s] = t + r = (r + s) * i + } + pool.freeUint32(pinv) + pool.freeUint32(p) + return r +} - this.snapToData = false +function unrank(n, r, p) { + switch(n) { + case 0: + if(p) { return p } + return [] + case 1: + if(p) { + p[0] = 0 + return p + } else { + return [0] + } + case 2: + if(p) { + if(r) { + p[0] = 0 + p[1] = 1 + } else { + p[0] = 1 + p[1] = 0 + } + return p + } else { + return r ? [0,1] : [1,0] + } + default: + break + } + p = p || new Array(n) + var s, t, i, nf=1 + p[0] = 0 + for(i=1; i0; --i) { + s = (r / nf)|0 + r = (r - s * nf)|0 + nf = (nf / i)|0 + t = p[i]|0 + p[i] = p[s]|0 + p[s] = t|0 + } + return p +} - this.opacity = 1.0 +exports.rank = rank +exports.unrank = unrank - this.lightPosition = [10, 10000, 0] - this.ambientLight = 0.8 - this.diffuseLight = 0.8 - this.specularLight = 2.0 - this.roughness = 0.5 - this.fresnel = 1.5 +},{"invert-permutation":268,"typedarray-pool":278}],268:[function(require,module,exports){ +"use strict" - this.dirty = true +function invertPermutation(pi, result) { + result = result || new Array(pi.length) + for(var i=0; i= 1) { - return true +var perm = require("permutation-rank") +var sgn = require("permutation-parity") +var gamma = require("gamma") + +function triangulateCube(dimension) { + if(dimension < 0) { + return [ ] } - for (var i = 0; i < 3; ++i) { - if (this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) { - return true + if(dimension === 0) { + return [ [0] ] + } + var dfactorial = Math.round(gamma(dimension+1))|0 + var result = [] + for(var i=0; i= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }", + "args": [{ + "name": "_inline_1_arg0_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg1_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg2_", + "lvalue": false, + "rvalue": true, + "count": 1 + }, { + "name": "_inline_1_arg3_", + "lvalue": false, + "rvalue": true, + "count": 2 + }, { + "name": "_inline_1_arg4_", + "lvalue": false, + "rvalue": true, + "count": 1 + }], + "thisVars": [], + "localVars": ["_inline_1_da", "_inline_1_db"] + }, + funcName: 'zeroCrossings' +}) -proto.pickSlots = 1 +},{"cwise-compiler":109}],271:[function(require,module,exports){ +"use strict" -proto.setPickBase = function (id) { - this.pickId = id -} +module.exports = findZeroCrossings -var ZERO_VEC = [0, 0, 0] +var core = require("./lib/zc-core") -var PROJECT_DATA = { - showSurface: false, - showContour: false, - projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()], - clipBounds: [ - [[0, 0, 0], [0, 0, 0]], - [[0, 0, 0], [0, 0, 0]], - [[0, 0, 0], [0, 0, 0]]] +function findZeroCrossings(array, level) { + var cross = [] + level = +level || 0.0 + core(array.hi(array.shape[0]-1), cross, level) + return cross } +},{"./lib/zc-core":270}],272:[function(require,module,exports){ +"use strict" -function computeProjectionData (camera, obj) { - var i, j, k +module.exports = surfaceNets - // Compute cube properties - var cubeAxis = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC +var generateContourExtractor = require("ndarray-extract-contour") +var triangulateCube = require("triangulate-hypercube") +var zeroCrossings = require("zero-crossings") - var showSurface = obj.showSurface - var showContour = obj.showContour +function buildSurfaceNets(order, dtype) { + var dimension = order.length + var code = ["'use strict';"] + var funcName = "surfaceNets" + order.join("_") + "d" + dtype - for (i = 0; i < 3; ++i) { - showSurface = showSurface || obj.surfaceProject[i] - for (j = 0; j < 3; ++j) { - showContour = showContour || obj.contourProject[i][j] - } + //Contour extraction function + code.push( + "var contour=genContour({", + "order:[", order.join(), "],", + "scalarArguments: 3,", + "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },") + if(dtype === "generic") { + code.push("getters:[0],") } - for (i = 0; i < 3; ++i) { - // Construct projection onto axis - var axisSquish = PROJECT_DATA.projections[i] - for (j = 0; j < 16; ++j) { - axisSquish[j] = 0 + //Generate vertex function + var cubeArgs = [] + var extraArgs = [] + for(var i=0; i>>7){") + } + for(var i=0; i<1<<(1< 128) { + if((i%128)===0) { + if(extraFuncs.length > 0) { + currentFunc.push("}}") + } + var efName = "vExtra" + extraFuncs.length + code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;") + currentFunc = [ + "function ", efName, "(m,", extraArgs.join(), "){switch(m){" + ] + extraFuncs.push(currentFunc) + } } - for (j = 0; j < 4; ++j) { - axisSquish[5 * j] = 1 + currentFunc.push("case ", (i&0x7f), ":") + var crossings = new Array(dimension) + var denoms = new Array(dimension) + var crossingCount = new Array(dimension) + var bias = new Array(dimension) + var totalCrossings = 0 + for(var j=0; j 0)][i] - multiply(axisSquish, camera.model, axisSquish) - - var nclipBounds = PROJECT_DATA.clipBounds[i] - for (k = 0; k < 2; ++k) { - for (j = 0; j < 3; ++j) { - nclipBounds[k][j] = camera.clipBounds[k][j] + for(var j=0; j<(1< j) { + continue + } + if(!(i&(1< 0) { + cStr = "+" + crossingCount[k] + "*c" + } + var weight = 0.5 * (crossings[k].length / totalCrossings) + var shift = 0.5 + 0.5 * (bias[k] / totalCrossings) + vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")") + + } + } + currentFunc.push("a.push([", vertexStr.join(), "]);", + "break;") + } + code.push("}},") + if(extraFuncs.length > 0) { + currentFunc.push("}}") } - PROJECT_DATA.showSurface = showSurface - PROJECT_DATA.showContour = showContour + //Create face function + var faceArgs = [] + for(var i=0; i<(1<<(dimension-1)); ++i) { + faceArgs.push("v" + i) + } + faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c") + code.push("cell:function cellFunc(", faceArgs.join(), "){") - return PROJECT_DATA -} + var facets = triangulateCube(dimension-1) + code.push("if(p0){b.push(", + facets.map(function(f) { + return "[" + f.map(function(v) { + return "v" + v + }) + "]" + }).join(), ")}else{b.push(", + facets.map(function(f) { + var e = f.slice() + e.reverse() + return "[" + e.map(function(v) { + return "v" + v + }) + "]" + }).join(), + ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";") -var UNIFORMS = { - model: IDENTITY, - view: IDENTITY, - projection: IDENTITY, - inverseModel: IDENTITY.slice(), - lowerBound: [0, 0, 0], - upperBound: [0, 0, 0], - colorMap: 0, - clipBounds: [[0, 0, 0], [0, 0, 0]], - height: 0.0, - contourTint: 0, - contourColor: [0, 0, 0, 1], - permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], - zOffset: -1e-4, - kambient: 1, - kdiffuse: 1, - kspecular: 1, - lightPosition: [1000, 1000, 1000], - eyePosition: [0, 0, 0], - roughness: 1, - fresnel: 1, - opacity: 1 + for(var i=0; i0) { + shapeX += 0.02 + } + } - uniforms.roughness = this.roughness - uniforms.fresnel = this.fresnel - uniforms.opacity = this.opacity + var data = new Float32Array(bufferSize) + var ptr = 0 + var xOffset = -0.5 * shapeX + for(var i=0; i= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); + + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); } - shader.uniforms.height = this.contourLevels[i][j] - vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j]) - } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + + return formattedString || this.toHexString(); + }, + clone: function() { + return tinycolor(this.toString()); + }, + + _applyModification: function(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function() { + return this._applyModification(lighten, arguments); + }, + brighten: function() { + return this._applyModification(brighten, arguments); + }, + darken: function() { + return this._applyModification(darken, arguments); + }, + desaturate: function() { + return this._applyModification(desaturate, arguments); + }, + saturate: function() { + return this._applyModification(saturate, arguments); + }, + greyscale: function() { + return this._applyModification(greyscale, arguments); + }, + spin: function() { + return this._applyModification(spin, arguments); + }, + + _applyCombination: function(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function() { + return this._applyCombination(analogous, arguments); + }, + complement: function() { + return this._applyCombination(complement, arguments); + }, + monochromatic: function() { + return this._applyCombination(monochromatic, arguments); + }, + splitcomplement: function() { + return this._applyCombination(splitcomplement, arguments); + }, + triad: function() { + return this._applyCombination(triad, arguments); + }, + tetrad: function() { + return this._applyCombination(tetrad, arguments); } +}; - // Draw projections of surface - for (i = 0; i < 3; ++i) { - shader.uniforms.model = projectData.projections[i] - shader.uniforms.clipBounds = projectData.clipBounds[i] - for (j = 0; j < 3; ++j) { - if (!this.contourProject[i][j]) { - continue - } - shader.uniforms.permutation = PERMUTATIONS[j] - gl.lineWidth(this.contourWidth[j]) - for (var k = 0; k < this.contourLevels[j].length; ++k) { - if (k === this.highlightLevel[j]) { - shader.uniforms.contourColor = this.highlightColor[j] - shader.uniforms.contourTint = this.highlightTint[j] - } else if (k === 0 || (k - 1) === this.highlightLevel[j]) { - shader.uniforms.contourColor = this.contourColor[j] - shader.uniforms.contourTint = this.contourTint[j] - } - shader.uniforms.height = this.contourLevels[j][k] - vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) +// If input is an object, force 1 into "1.0" to handle ratios properly +// String input requires "1.0" as input, so 1 will be treated as 1 +tinycolor.fromRatio = function(color, opts) { + if (typeof color == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } + else { + newColor[i] = convertToPercentage(color[i]); + } + } } - } + color = newColor; } - // Draw dynamic contours - vao = this._dynamicVAO - vao.bind() + return tinycolor(color, opts); +}; - // Draw contour levels - for (i = 0; i < 3; ++i) { - if (this._dynamicCounts[i] === 0) { - continue - } +// Given a string or object, convert that input to RGB +// Possible string inputs: +// +// "red" +// "#f00" or "f00" +// "#ff0000" or "ff0000" +// "#ff000000" or "ff000000" +// "rgb 255 0 0" or "rgb (255, 0, 0)" +// "rgb 1.0 0 0" or "rgb (1, 0, 0)" +// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" +// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" +// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" +// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" +// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" +// +function inputToRGB(color) { - shader.uniforms.model = uniforms.model - shader.uniforms.clipBounds = uniforms.clipBounds - shader.uniforms.permutation = PERMUTATIONS[i] - gl.lineWidth(this.dynamicWidth[i]) + var rgb = { r: 0, g: 0, b: 0 }; + var a = 1; + var ok = false; + var format = false; - shader.uniforms.contourColor = this.dynamicColor[i] - shader.uniforms.contourTint = this.dynamicTint[i] - shader.uniforms.height = this.dynamicLevel[i] - vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) + if (typeof color == "string") { + color = stringInputToObject(color); + } - for (j = 0; j < 3; ++j) { - if (!this.contourProject[j][i]) { - continue + if (typeof color == "object") { + if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { + color.s = convertToPercentage(color.s); + color.v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, color.s, color.v); + ok = true; + format = "hsv"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { + color.s = convertToPercentage(color.s); + color.l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, color.s, color.l); + ok = true; + format = "hsl"; + } + + if (color.hasOwnProperty("a")) { + a = color.a; } - - shader.uniforms.model = projectData.projections[j] - shader.uniforms.clipBounds = projectData.clipBounds[j] - vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i]) - } } - vao.unbind() - } -} - -proto.draw = function (params) { - return drawCore.call(this, params, false) -} + a = boundAlpha(a); -proto.drawTransparent = function (params) { - return drawCore.call(this, params, true) + return { + ok: ok, + format: color.format || format, + r: mathMin(255, mathMax(rgb.r, 0)), + g: mathMin(255, mathMax(rgb.g, 0)), + b: mathMin(255, mathMax(rgb.b, 0)), + a: a + }; } -var PICK_UNIFORMS = { - model: IDENTITY, - view: IDENTITY, - projection: IDENTITY, - inverseModel: IDENTITY, - clipBounds: [[0, 0, 0], [0, 0, 0]], - height: 0.0, - shape: [0, 0], - pickId: 0, - lowerBound: [0, 0, 0], - upperBound: [0, 0, 0], - zOffset: 0.0, - permutation: [1, 0, 0, 0, 1, 0, 0, 0, 1], - lightPosition: [0, 0, 0], - eyePosition: [0, 0, 0] -} -proto.drawPick = function (params) { - params = params || {} - var gl = this.gl - gl.disable(gl.CULL_FACE) +// Conversion Functions +// -------------------- - var uniforms = PICK_UNIFORMS - uniforms.model = params.model || IDENTITY - uniforms.view = params.view || IDENTITY - uniforms.projection = params.projection || IDENTITY - uniforms.shape = this._field[2].shape - uniforms.pickId = this.pickId / 255.0 - uniforms.lowerBound = this.bounds[0] - uniforms.upperBound = this.bounds[1] - uniforms.permutation = DEFAULT_PERM +// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: +// - for (var i = 0; i < 2; ++i) { - var clipClamped = uniforms.clipBounds[i] - for (var j = 0; j < 3; ++j) { - clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8) - } - } +// `rgbToRgb` +// Handle bounds / percentage checking to conform to CSS color spec +// +// *Assumes:* r, g, b in [0, 255] or [0, 1] +// *Returns:* { r, g, b } in [0, 255] +function rgbToRgb(r, g, b){ + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; +} - var projectData = computeProjectionData(uniforms, this) +// `rgbToHsl` +// Converts an RGB color value to HSL. +// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] +// *Returns:* { h, s, l } in [0,1] +function rgbToHsl(r, g, b) { - if (projectData.showSurface) { - // Set up uniforms - this._pickShader.bind() - this._pickShader.uniforms = uniforms + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); - // Draw it - this._vao.bind() - this._vao.draw(gl.TRIANGLES, this._vertexCount) + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, l = (max + min) / 2; - // Draw projections of surface - for (i = 0; i < 3; ++i) { - if (!this.surfaceProject[i]) { - continue - } - this._pickShader.uniforms.model = projectData.projections[i] - this._pickShader.uniforms.clipBounds = projectData.clipBounds[i] - this._vao.draw(gl.TRIANGLES, this._vertexCount) + if(max == min) { + h = s = 0; // achromatic } + else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } - this._vao.unbind() - } + h /= 6; + } - if (projectData.showContour) { - var shader = this._contourPickShader + return { h: h, s: s, l: l }; +} - shader.bind() - shader.uniforms = uniforms +// `hslToRgb` +// Converts an HSL color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hslToRgb(h, s, l) { + var r, g, b; - var vao = this._contourVAO - vao.bind() + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); - for (j = 0; j < 3; ++j) { - gl.lineWidth(this.contourWidth[j]) - shader.uniforms.permutation = PERMUTATIONS[j] - for (i = 0; i < this.contourLevels[j].length; ++i) { - if (this._contourCounts[j][i]) { - shader.uniforms.height = this.contourLevels[j][i] - vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i]) - } - } + function hue2rgb(p, q, t) { + if(t < 0) t += 1; + if(t > 1) t -= 1; + if(t < 1/6) return p + (q - p) * 6 * t; + if(t < 1/2) return q; + if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; } - // Draw projections of surface - for (i = 0; i < 3; ++i) { - shader.uniforms.model = projectData.projections[i] - shader.uniforms.clipBounds = projectData.clipBounds[i] - - for (j = 0; j < 3; ++j) { - if (!this.contourProject[i][j]) { - continue - } - - shader.uniforms.permutation = PERMUTATIONS[j] - gl.lineWidth(this.contourWidth[j]) - for (var k = 0; k < this.contourLevels[j].length; ++k) { - if (this._contourCounts[j][k]) { - shader.uniforms.height = this.contourLevels[j][k] - vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k]) - } - } - } + if(s === 0) { + r = g = b = l; // achromatic + } + else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); } - vao.unbind() - } + return { r: r * 255, g: g * 255, b: b * 255 }; } -proto.pick = function (selection) { - if (!selection) { - return null - } +// `rgbToHsv` +// Converts an RGB color value to HSV +// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] +// *Returns:* { h, s, v } in [0,1] +function rgbToHsv(r, g, b) { - if (selection.id !== this.pickId) { - return null - } + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); - var shape = this._field[2].shape + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, v = max; - var result = this._pickResult + var d = max - min; + s = max === 0 ? 0 : d / max; - // Compute uv coordinate - var x = shape[0] * (selection.value[0] + (selection.value[2] >> 4) / 16.0) / 255.0 - var ix = Math.floor(x) - var fx = x - ix + if(max == min) { + h = 0; // achromatic + } + else { + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h, s: s, v: v }; +} - var y = shape[1] * (selection.value[1] + (selection.value[2] & 15) / 16.0) / 255.0 - var iy = Math.floor(y) - var fy = y - iy +// `hsvToRgb` +// Converts an HSV color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { - ix += 1 - iy += 1 + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); - // Compute xyz coordinate - var pos = result.position - pos[0] = pos[1] = pos[2] = 0 - for (var dx = 0; dx < 2; ++dx) { - var s = dx ? fx : 1.0 - fx - for (var dy = 0; dy < 2; ++dy) { - var t = dy ? fy : 1.0 - fy + var i = math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; - var r = ix + dx - var c = iy + dy - var w = s * t + return { r: r * 255, g: g * 255, b: b * 255 }; +} - for (var i = 0; i < 3; ++i) { - pos[i] += this._field[i].get(r, c) * w - } - } - } +// `rgbToHex` +// Converts an RGB color to hex +// Assumes r, g, and b are contained in the set [0, 255] +// Returns a 3 or 6 character hex +function rgbToHex(r, g, b, allow3Char) { - // Find closest level - var levelIndex = this._pickResult.level - for (var j = 0; j < 3; ++j) { - levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j]) - if (levelIndex[j] < 0) { - if (this.contourLevels[j].length > 0) { - levelIndex[j] = 0 - } - } else if (levelIndex[j] < this.contourLevels[j].length - 1) { - var a = this.contourLevels[j][levelIndex[j]] - var b = this.contourLevels[j][levelIndex[j] + 1] - if (Math.abs(a - pos[j]) > Math.abs(b - pos[j])) { - levelIndex[j] += 1 - } + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } - } - result.index[0] = fx < 0.5 ? ix : (ix + 1) - result.index[1] = fy < 0.5 ? iy : (iy + 1) + return hex.join(""); +} - result.uv[0] = x / shape[0] - result.uv[1] = y / shape[1] +// `rgbaToHex` +// Converts an RGBA color plus alpha transparency to hex +// Assumes r, g, b and a are contained in the set [0, 255] +// Returns an 8 character hex +function rgbaToHex(r, g, b, a) { - for (i = 0; i < 3; ++i) { - result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1]) - } + var hex = [ + pad2(convertDecimalToHex(a)), + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; - return result + return hex.join(""); } -function padField (nfield, field) { - var shape = field.shape.slice() - var nshape = nfield.shape.slice() +// `equals` +// Can be called with any tinycolor input +tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) { return false; } + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); +}; - // Center - ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field) +tinycolor.random = function() { + return tinycolor.fromRatio({ + r: mathRandom(), + g: mathRandom(), + b: mathRandom() + }); +}; - // Edges - ops.assign(nfield.lo(1).hi(shape[0], 1), - field.hi(shape[0], 1)) - ops.assign(nfield.lo(1, nshape[1] - 1).hi(shape[0], 1), - field.lo(0, shape[1] - 1).hi(shape[0], 1)) - ops.assign(nfield.lo(0, 1).hi(1, shape[1]), - field.hi(1)) - ops.assign(nfield.lo(nshape[0] - 1, 1).hi(1, shape[1]), - field.lo(shape[0] - 1)) - // Corners - nfield.set(0, 0, field.get(0, 0)) - nfield.set(0, nshape[1] - 1, field.get(0, shape[1] - 1)) - nfield.set(nshape[0] - 1, 0, field.get(shape[0] - 1, 0)) - nfield.set(nshape[0] - 1, nshape[1] - 1, field.get(shape[0] - 1, shape[1] - 1)) -} -function handleArray (param, ctor) { - if (Array.isArray(param)) { - return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ] - } - return [ ctor(param), ctor(param), ctor(param) ] -} +// Modification Functions +// ---------------------- +// Thanks to less.js for some of the basics here +// -function toColor (x) { - if (Array.isArray(x)) { - if (x.length === 3) { - return [x[0], x[1], x[2], 1] - } - return [x[0], x[1], x[2], x[3]] - } - return [0, 0, 0, 1] +function desaturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); } -function handleColor (param) { - if (Array.isArray(param)) { - if (Array.isArray(param)) { - return [ - toColor(param[0]), - toColor(param[1]), - toColor(param[2]) ] - } else { - var c = toColor(param) - return [ - c.slice(), - c.slice(), - c.slice() ] - } - } +function saturate(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); } -proto.update = function (params) { - params = params || {} - - this.dirty = true +function greyscale(color) { + return tinycolor(color).desaturate(100); +} - if ('contourWidth' in params) { - this.contourWidth = handleArray(params.contourWidth, Number) - } - if ('showContour' in params) { - this.showContour = handleArray(params.showContour, Boolean) - } - if ('showSurface' in params) { - this.showSurface = !!params.showSurface - } - if ('contourTint' in params) { - this.contourTint = handleArray(params.contourTint, Boolean) - } - if ('contourColor' in params) { - this.contourColor = handleColor(params.contourColor) - } - if ('contourProject' in params) { - this.contourProject = handleArray(params.contourProject, function (x) { - return handleArray(x, Boolean) - }) - } - if ('surfaceProject' in params) { - this.surfaceProject = params.surfaceProject - } - if ('dynamicColor' in params) { - this.dynamicColor = handleColor(params.dynamicColor) - } - if ('dynamicTint' in params) { - this.dynamicTint = handleArray(params.dynamicTint, Number) - } - if ('dynamicWidth' in params) { - this.dynamicWidth = handleArray(params.dynamicWidth, Number) - } - if ('opacity' in params) { - this.opacity = params.opacity - } - if ('colorBounds' in params) { - this.colorBounds = params.colorBounds - } +function lighten (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} - var field = params.field || (params.coords && params.coords[2]) || null - var levelsChanged = false +function brighten(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var rgb = tinycolor(color).toRgb(); + rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); + rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); + rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); + return tinycolor(rgb); +} - if (!field) { - if (this._field[2].shape[0] || this._field[2].shape[2]) { - field = this._field[2].lo(1, 1).hi(this._field[2].shape[0] - 2, this._field[2].shape[1] - 2) - } else { - field = this._field[2].hi(0, 0) - } - } +function darken (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} - // Update field - if ('field' in params || 'coords' in params) { - var fsize = (field.shape[0] + 2) * (field.shape[1] + 2) +// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. +// Values outside of this range will be wrapped into this range. +function spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (mathRound(hsl.h) + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); +} - // Resize if necessary - if (fsize > this._field[2].data.length) { - pool.freeFloat(this._field[2].data) - this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize)) - } +// Combination Functions +// --------------------- +// Thanks to jQuery xColor for some of the ideas behind these +// - // Pad field - this._field[2] = ndarray(this._field[2].data, [field.shape[0] + 2, field.shape[1] + 2]) - padField(this._field[2], field) +function complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); +} - // Save shape of field - this.shape = field.shape.slice() - var shape = this.shape +function triad(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) + ]; +} - // Resize coordinate fields if necessary - for (var i = 0; i < 2; ++i) { - if (this._field[2].size > this._field[i].data.length) { - pool.freeFloat(this._field[i].data) - this._field[i].data = pool.mallocFloat(this._field[2].size) - } - this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2]) - } +function tetrad(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) + ]; +} - // Generate x/y coordinates - if (params.coords) { - var coords = params.coords - if (!Array.isArray(coords) || coords.length !== 3) { - throw new Error('gl-surface: invalid coordinates for x/y') - } - for (i = 0; i < 2; ++i) { - var coord = coords[i] - for (j = 0; j < 2; ++j) { - if (coord.shape[j] !== shape[j]) { - throw new Error('gl-surface: coords have incorrect shape') - } - } - padField(this._field[i], coord) - } - } else if (params.ticks) { - var ticks = params.ticks - if (!Array.isArray(ticks) || ticks.length !== 2) { - throw new Error('gl-surface: invalid ticks') - } - for (i = 0; i < 2; ++i) { - var tick = ticks[i] - if (Array.isArray(tick) || tick.length) { - tick = ndarray(tick) - } - if (tick.shape[0] !== shape[i]) { - throw new Error('gl-surface: invalid tick length') - } - // Make a copy view of the tick array - var tick2 = ndarray(tick.data, shape) - tick2.stride[i] = tick.stride[0] - tick2.stride[i ^ 1] = 0 +function splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), + tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) + ]; +} - // Fill in field array - padField(this._field[i], tick2) - } - } else { - for (i = 0; i < 2; ++i) { - var offset = [0, 0] - offset[i] = 1 - this._field[i] = ndarray(this._field[i].data, [shape[0] + 2, shape[1] + 2], offset, 0) - } - this._field[0].set(0, 0, 0) - for (var j = 0; j < shape[0]; ++j) { - this._field[0].set(j + 1, 0, j) - } - this._field[0].set(shape[0] + 1, 0, shape[0] - 1) - this._field[1].set(0, 0, 0) - for (j = 0; j < shape[1]; ++j) { - this._field[1].set(0, j + 1, j) - } - this._field[1].set(0, shape[1] + 1, shape[1] - 1) - } +function analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; - // Save shape - var fields = this._field + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; - // Compute surface normals - var dfields = ndarray(pool.mallocFloat(fields[2].size * 3 * 2), [3, shape[0] + 2, shape[1] + 2, 2]) - for (i = 0; i < 3; ++i) { - gradient(dfields.pick(i), fields[i], 'mirror') + for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); } - var normals = ndarray(pool.mallocFloat(fields[2].size * 3), [shape[0] + 2, shape[1] + 2, 3]) - for (i = 0; i < shape[0] + 2; ++i) { - for (j = 0; j < shape[1] + 2; ++j) { - var dxdu = dfields.get(0, i, j, 0) - var dxdv = dfields.get(0, i, j, 1) - var dydu = dfields.get(1, i, j, 0) - var dydv = dfields.get(1, i, j, 1) - var dzdu = dfields.get(2, i, j, 0) - var dzdv = dfields.get(2, i, j, 1) - - var nx = dydu * dzdv - dydv * dzdu - var ny = dzdu * dxdv - dzdv * dxdu - var nz = dxdu * dydv - dxdv * dydu + return ret; +} - var nl = Math.sqrt(nx * nx + ny * ny + nz * nz) - if (nl < 1e-8) { - nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz)) - if (nl < 1e-8) { - nz = 1.0 - ny = nx = 0.0 - nl = 1.0 - } else { - nl = 1.0 / nl - } - } else { - nl = 1.0 / Math.sqrt(nl) - } +function monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, s = hsv.s, v = hsv.v; + var ret = []; + var modification = 1 / results; - normals.set(i, j, 0, nx * nl) - normals.set(i, j, 1, ny * nl) - normals.set(i, j, 2, nz * nl) - } + while (results--) { + ret.push(tinycolor({ h: h, s: s, v: v})); + v = (v + modification) % 1; } - pool.free(dfields.data) - // Initialize surface - var lo = [ Infinity, Infinity, Infinity ] - var hi = [ -Infinity, -Infinity, -Infinity ] - var lo_intensity = Infinity - var hi_intensity = -Infinity - var count = (shape[0] - 1) * (shape[1] - 1) * 6 - var tverts = pool.mallocFloat(bits.nextPow2(10 * count)) - var tptr = 0 - var vertexCount = 0 - for (i = 0; i < shape[0] - 1; ++i) { - j_loop: - for (j = 0; j < shape[1] - 1; ++j) { - // Test for NaNs - for (var dx = 0; dx < 2; ++dx) { - for (var dy = 0; dy < 2; ++dy) { - for (var k = 0; k < 3; ++k) { - var f = this._field[k].get(1 + i + dx, 1 + j + dy) - if (isNaN(f) || !isFinite(f)) { - continue j_loop - } - } - } - } - for (k = 0; k < 6; ++k) { - var r = i + QUAD[k][0] - var c = j + QUAD[k][1] + return ret; +} - var tx = this._field[0].get(r + 1, c + 1) - var ty = this._field[1].get(r + 1, c + 1) - f = this._field[2].get(r + 1, c + 1) - var vf = f - nx = normals.get(r + 1, c + 1, 0) - ny = normals.get(r + 1, c + 1, 1) - nz = normals.get(r + 1, c + 1, 2) +// Utility Functions +// --------------------- - if (params.intensity) { - vf = params.intensity.get(r, c) - } +tinycolor.mix = function(color1, color2, amount) { + amount = (amount === 0) ? 0 : (amount || 50); - tverts[tptr++] = r - tverts[tptr++] = c - tverts[tptr++] = tx - tverts[tptr++] = ty - tverts[tptr++] = f - tverts[tptr++] = 0 - tverts[tptr++] = vf - tverts[tptr++] = nx - tverts[tptr++] = ny - tverts[tptr++] = nz + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); - lo[0] = Math.min(lo[0], tx) - lo[1] = Math.min(lo[1], ty) - lo[2] = Math.min(lo[2], f) - lo_intensity = Math.min(lo_intensity, vf) + var p = amount / 100; + var w = p * 2 - 1; + var a = rgb2.a - rgb1.a; - hi[0] = Math.max(hi[0], tx) - hi[1] = Math.max(hi[1], ty) - hi[2] = Math.max(hi[2], f) - hi_intensity = Math.max(hi_intensity, vf) + var w1; - vertexCount += 1 - } - } + if (w * a == -1) { + w1 = w; + } else { + w1 = (w + a) / (1 + w * a); } - if (params.intensityBounds) { - lo_intensity = +params.intensityBounds[0] - hi_intensity = +params.intensityBounds[1] - } + w1 = (w1 + 1) / 2; - // Scale all vertex intensities - for (i = 6; i < tptr; i += 10) { - tverts[i] = (tverts[i] - lo_intensity) / (hi_intensity - lo_intensity) - } + var w2 = 1 - w1; - this._vertexCount = vertexCount - this._coordinateBuffer.update(tverts.subarray(0, tptr)) - pool.freeFloat(tverts) - pool.free(normals.data) + var rgba = { + r: rgb2.r * w1 + rgb1.r * w2, + g: rgb2.g * w1 + rgb1.g * w2, + b: rgb2.b * w1 + rgb1.b * w2, + a: rgb2.a * p + rgb1.a * (1 - p) + }; - // Update bounds - this.bounds = [lo, hi] + return tinycolor(rgba); +}; - // Save intensity - this.intensity = params.intensity || this._field[2] - if(this.intensityBounds[0] !== lo_intensity || this.intensityBounds[1] !== hi_intensity) { - levelsChanged = true - } +// Readability Functions +// --------------------- +// false +// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false +tinycolor.isReadable = function(color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; - // Update contour lines - var contourVerts = [] + out = false; - for (var dim = 0; dim < 3; ++dim) { - levels = this.contourLevels[dim] - var levelOffsets = [] - var levelCounts = [] + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; - var parts = [0, 0, 0] +}; - for (i = 0; i < levels.length; ++i) { - var graph = surfaceNets(this._field[dim], levels[i]) - levelOffsets.push((contourVerts.length / 5) | 0) - vertexCount = 0 +// `mostReadable` +// Given a base color and a list of possible foreground or background +// colors for that base, returns the most readable color. +// Optionally returns Black or White if the most readable color is unreadable. +// *Example* +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" +tinycolor.mostReadable = function(baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size ; + args = args || {}; + includeFallbackColors = args.includeFallbackColors ; + level = args.level; + size = args.size; - edge_loop: - for (j = 0; j < graph.cells.length; ++j) { - var e = graph.cells[j] - for (k = 0; k < 2; ++k) { - var p = graph.positions[e[k]] + for (var i= 0; i < colorList.length ; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } - var x = p[0] - var ix = Math.floor(x) | 0 - var fx = x - ix + if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { + return bestColor; + } + else { + args.includeFallbackColors=false; + return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); + } +}; - var y = p[1] - var iy = Math.floor(y) | 0 - var fy = y - iy - var hole = false - dd_loop: - for (var dd = 0; dd < 3; ++dd) { - parts[dd] = 0.0 - var iu = (dim + dd + 1) % 3 - for (dx = 0; dx < 2; ++dx) { - var s = dx ? fx : 1.0 - fx - r = Math.min(Math.max(ix + dx, 0), shape[0]) | 0 - for (dy = 0; dy < 2; ++dy) { - var t = dy ? fy : 1.0 - fy - c = Math.min(Math.max(iy + dy, 0), shape[1]) | 0 +// Big List of Colors +// ------------------ +// +var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; - if (dd < 2) { - f = this._field[iu].get(r, c) - } else { - f = (this.intensity.get(r, c) - this.intensityBounds[0]) / (this.intensityBounds[1] - this.intensityBounds[0]) - } - if (!isFinite(f) || isNaN(f)) { - hole = true - break dd_loop - } +// Make it easy to access colors via `hexNames[hex]` +var hexNames = tinycolor.hexNames = flip(names); - var w = s * t - parts[dd] += w * f - } - } - } - if (!hole) { - contourVerts.push(parts[0], parts[1], p[0], p[1], parts[2]) - vertexCount += 1 - } else { - if (k > 0) { - // If we already added first edge, pop off verts - for (var l = 0; l < 5; ++l) { - contourVerts.pop() - } - vertexCount -= 1 - } - continue edge_loop - } - } - } - levelCounts.push(vertexCount) - } +// Utilities +// --------- - // Store results - this._contourOffsets[dim] = levelOffsets - this._contourCounts[dim] = levelCounts +// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` +function flip(o) { + var flipped = { }; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } } + return flipped; +} - var floatBuffer = pool.mallocFloat(contourVerts.length) - for (i = 0; i < contourVerts.length; ++i) { - floatBuffer[i] = contourVerts[i] +// Return a valid alpha value [0,1] with all invalid values being set to 1 +function boundAlpha(a) { + a = parseFloat(a); + + if (isNaN(a) || a < 0 || a > 1) { + a = 1; } - this._contourBuffer.update(floatBuffer) - pool.freeFloat(floatBuffer) - } - if (params.colormap) { - this._colorMap.setPixels(genColormap(params.colormap)) - } + return a; } -proto.dispose = function () { - this._shader.dispose() - this._vao.dispose() - this._coordinateBuffer.dispose() - this._colorMap.dispose() - this._contourBuffer.dispose() - this._contourVAO.dispose() - this._contourShader.dispose() - this._contourPickShader.dispose() - this._dynamicBuffer.dispose() - this._dynamicVAO.dispose() - for (var i = 0; i < 3; ++i) { - pool.freeFloat(this._field[i].data) - } -} +// Take input from [0, n] and return it as [0, 1] +function bound01(n, max) { + if (isOnePointZero(n)) { n = "100%"; } -proto.highlight = function (selection) { - if (!selection) { - this._dynamicCounts = [0, 0, 0] - this.dyanamicLevel = [NaN, NaN, NaN] - this.highlightLevel = [-1, -1, -1] - return - } + var processPercent = isPercentage(n); + n = mathMin(max, mathMax(0, parseFloat(n))); - for (var i = 0; i < 3; ++i) { - if (this.enableHighlight[i]) { - this.highlightLevel[i] = selection.level[i] - } else { - this.highlightLevel[i] = -1 + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; } - } - - var levels - if (this.snapToData) { - levels = selection.dataCoordinate - } else { - levels = selection.position - } - if ((!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) && - (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) && - (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2])) { - return - } - - var vertexCount = 0 - var shape = this.shape - var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1]) - for (var d = 0; d < 3; ++d) { - if (!this.enableDynamic[d]) { - this.dynamicLevel[d] = NaN - this._dynamicCounts[d] = 0 - continue + // Handle floating point rounding errors + if ((math.abs(n - max) < 0.000001)) { + return 1; } - this.dynamicLevel[d] = levels[d] - - var u = (d + 1) % 3 - var v = (d + 2) % 3 + // Convert into [0, 1] range if it isn't already + return (n % max) / parseFloat(max); +} - var f = this._field[d] - var g = this._field[u] - var h = this._field[v] - var intensity = this.intensity +// Force a number between 0 and 1 +function clamp01(val) { + return mathMin(1, mathMax(0, val)); +} - var graph = surfaceNets(f, levels[d]) - var edges = graph.cells - var positions = graph.positions +// Parse a base-16 hex value into a base-10 integer +function parseIntFromHex(val) { + return parseInt(val, 16); +} - this._dynamicOffsets[d] = vertexCount +// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 +// +function isOnePointZero(n) { + return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; +} - for (i = 0; i < edges.length; ++i) { - var e = edges[i] - for (var j = 0; j < 2; ++j) { - var p = positions[e[j]] +// Check to see if string passed in is a percentage +function isPercentage(n) { + return typeof n === "string" && n.indexOf('%') != -1; +} - var x = +p[0] - var ix = x | 0 - var jx = Math.min(ix + 1, shape[0]) | 0 - var fx = x - ix - var hx = 1.0 - fx +// Force a hex value to have 2 characters +function pad2(c) { + return c.length == 1 ? '0' + c : '' + c; +} - var y = +p[1] - var iy = y | 0 - var jy = Math.min(iy + 1, shape[1]) | 0 - var fy = y - iy - var hy = 1.0 - fy +// Replace a decimal with it's percentage value +function convertToPercentage(n) { + if (n <= 1) { + n = (n * 100) + "%"; + } - var w00 = hx * hy - var w01 = hx * fy - var w10 = fx * hy - var w11 = fx * fy + return n; +} - var cu = w00 * g.get(ix, iy) + - w01 * g.get(ix, jy) + - w10 * g.get(jx, iy) + - w11 * g.get(jx, jy) +// Converts a decimal to a hex value +function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); +} +// Converts a hex value to a decimal +function convertHexToDecimal(h) { + return (parseIntFromHex(h) / 255); +} - var cv = w00 * h.get(ix, iy) + - w01 * h.get(ix, jy) + - w10 * h.get(jx, iy) + - w11 * h.get(jx, jy) +var matchers = (function() { - if (isNaN(cu) || isNaN(cv)) { - if (j) { - vertexCount -= 1 - } - break - } + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; - scratchBuffer[2 * vertexCount + 0] = cu - scratchBuffer[2 * vertexCount + 1] = cv + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; - vertexCount += 1 - } - } + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; - this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d] - } + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - this._dynamicBuffer.update(scratchBuffer.subarray(0, 2 * vertexCount)) - pool.freeFloat(scratchBuffer) -} + return { + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; +})(); -function createSurfacePlot (params) { - var gl = params.gl - var shader = createShader(gl) - var pickShader = createPickShader(gl) - var contourShader = createContourShader(gl) - var contourPickShader = createPickContourShader(gl) +// `stringInputToObject` +// Permissive string parsing. Take in a number of formats, and output an object +// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` +function stringInputToObject(color) { - var coordinateBuffer = createBuffer(gl) - var vao = createVAO(gl, [ - { buffer: coordinateBuffer, - size: 4, - stride: SURFACE_VERTEX_SIZE, - offset: 0 - }, - { buffer: coordinateBuffer, - size: 3, - stride: SURFACE_VERTEX_SIZE, - offset: 16 - }, - { - buffer: coordinateBuffer, - size: 3, - stride: SURFACE_VERTEX_SIZE, - offset: 28 + color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; } - ]) - - var contourBuffer = createBuffer(gl) - var contourVAO = createVAO(gl, [ - { - buffer: contourBuffer, - size: 4, - stride: 20, - offset: 0 - }, - { - buffer: contourBuffer, - size: 1, - stride: 20, - offset: 16 + else if (color == 'transparent') { + return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } - ]) - - var dynamicBuffer = createBuffer(gl) - var dynamicVAO = createVAO(gl, [ - { - buffer: dynamicBuffer, - size: 2, - type: gl.FLOAT - }]) - - var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE) - cmap.minFilter = gl.LINEAR - cmap.magFilter = gl.LINEAR - var surface = new SurfacePlot( - gl, - [0, 0], - [[0, 0, 0], [0, 0, 0]], - shader, - pickShader, - coordinateBuffer, - vao, - cmap, - contourShader, - contourPickShader, - contourBuffer, - contourVAO, - dynamicBuffer, - dynamicVAO) + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if ((match = matchers.rgb.exec(color))) { + return { r: match[1], g: match[2], b: match[3] }; + } + if ((match = matchers.rgba.exec(color))) { + return { r: match[1], g: match[2], b: match[3], a: match[4] }; + } + if ((match = matchers.hsl.exec(color))) { + return { h: match[1], s: match[2], l: match[3] }; + } + if ((match = matchers.hsla.exec(color))) { + return { h: match[1], s: match[2], l: match[3], a: match[4] }; + } + if ((match = matchers.hsv.exec(color))) { + return { h: match[1], s: match[2], v: match[3] }; + } + if ((match = matchers.hsva.exec(color))) { + return { h: match[1], s: match[2], v: match[3], a: match[4] }; + } + if ((match = matchers.hex8.exec(color))) { + return { + a: convertHexToDecimal(match[1]), + r: parseIntFromHex(match[2]), + g: parseIntFromHex(match[3]), + b: parseIntFromHex(match[4]), + format: named ? "name" : "hex8" + }; + } + if ((match = matchers.hex6.exec(color))) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if ((match = matchers.hex3.exec(color))) { + return { + r: parseIntFromHex(match[1] + '' + match[1]), + g: parseIntFromHex(match[2] + '' + match[2]), + b: parseIntFromHex(match[3] + '' + match[3]), + format: named ? "name" : "hex" + }; + } - var nparams = { - levels: [[], [], []] - } - for (var id in params) { - nparams[id] = params[id] - } - nparams.colormap = nparams.colormap || 'jet' + return false; +} - surface.update(nparams) +function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || {"level":"AA", "size":"small"}; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return {"level":level, "size":size}; +} - return surface +// Node: Export function +if (typeof module !== "undefined" && module.exports) { + module.exports = tinycolor; +} +// AMD/requirejs: Define the module +else if (typeof define === 'function' && define.amd) { + define(function () {return tinycolor;}); +} +// Browser: Expose to window +else { + window.tinycolor = tinycolor; } -},{"./lib/shaders":939,"binary-search-bounds":940,"bit-twiddle":941,"colormap":943,"gl-buffer":946,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-texture2d":973,"gl-vao":977,"ndarray":1031,"ndarray-gradient":978,"ndarray-ops":1026,"ndarray-pack":983,"surface-nets":1001,"typedarray-pool":1002}],1004:[function(require,module,exports){ -'use strict' +})(); -module.exports = mouseListen +},{}],275:[function(require,module,exports){ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.topojson = {}))); +}(this, function (exports) { 'use strict'; -var mouse = require('mouse-event') + function noop() {} -function mouseListen(element, callback) { - if(!callback) { - callback = element - element = window + function absolute(transform) { + if (!transform) return noop; + var x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + point[0] = (x0 += point[0]) * kx + dx; + point[1] = (y0 += point[1]) * ky + dy; + }; } - var buttonState = 0 - var x = 0 - var y = 0 - var mods = { - shift: false, - alt: false, - control: false, - meta: false + function relative(transform) { + if (!transform) return noop; + var x0, + y0, + kx = transform.scale[0], + ky = transform.scale[1], + dx = transform.translate[0], + dy = transform.translate[1]; + return function(point, i) { + if (!i) x0 = y0 = 0; + var x1 = (point[0] - dx) / kx | 0, + y1 = (point[1] - dy) / ky | 0; + point[0] = x1 - x0; + point[1] = y1 - y0; + x0 = x1; + y0 = y1; + }; } - var attached = false - function updateMods(ev) { - var changed = false - if('altKey' in ev) { - changed = changed || ev.altKey !== mods.alt - mods.alt = !!ev.altKey - } - if('shiftKey' in ev) { - changed = changed || ev.shiftKey !== mods.shift - mods.shift = !!ev.shiftKey - } - if('ctrlKey' in ev) { - changed = changed || ev.ctrlKey !== mods.control - mods.control = !!ev.ctrlKey - } - if('metaKey' in ev) { - changed = changed || ev.metaKey !== mods.meta - mods.meta = !!ev.metaKey - } - return changed + function reverse(array, n) { + var t, j = array.length, i = j - n; + while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; } - function handleEvent(nextButtons, ev) { - var nextX = mouse.x(ev) - var nextY = mouse.y(ev) - if('buttons' in ev) { - nextButtons = ev.buttons|0 - } - if(nextButtons !== buttonState || - nextX !== x || - nextY !== y || - updateMods(ev)) { - buttonState = nextButtons|0 - x = nextX||0 - y = nextY||0 - callback && callback(buttonState, x, y, mods) + function bisect(a, x) { + var lo = 0, hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (a[mid] < x) lo = mid + 1; + else hi = mid; } + return lo; } - function clearState(ev) { - handleEvent(0, ev) + function feature(topology, o) { + return o.type === "GeometryCollection" ? { + type: "FeatureCollection", + features: o.geometries.map(function(o) { return feature$1(topology, o); }) + } : feature$1(topology, o); + } + + function feature$1(topology, o) { + var f = { + type: "Feature", + id: o.id, + properties: o.properties || {}, + geometry: object(topology, o) + }; + if (o.id == null) delete f.id; + return f; } - function handleBlur() { - if(buttonState || - x || - y || - mods.shift || - mods.alt || - mods.meta || - mods.control) { + function object(topology, o) { + var absolute$$ = absolute(topology.transform), + arcs = topology.arcs; - x = y = 0 - buttonState = 0 - mods.shift = mods.alt = mods.control = mods.meta = false - callback && callback(0, 0, 0, mods) + function arc(i, points) { + if (points.length) points.pop(); + for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { + points.push(p = a[k].slice()); + absolute$$(p, k); + } + if (i < 0) reverse(points, n); } - } - function handleMods(ev) { - if(updateMods(ev)) { - callback && callback(buttonState, x, y, mods) + function point(p) { + p = p.slice(); + absolute$$(p, 0); + return p; } - } - function handleMouseMove(ev) { - if(mouse.buttons(ev) === 0) { - handleEvent(0, ev) - } else { - handleEvent(buttonState, ev) + function line(arcs) { + var points = []; + for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); + if (points.length < 2) points.push(points[0].slice()); + return points; } - } - - function handleMouseDown(ev) { - handleEvent(buttonState | mouse.buttons(ev), ev) - } - function handleMouseUp(ev) { - handleEvent(buttonState & ~mouse.buttons(ev), ev) - } + function ring(arcs) { + var points = line(arcs); + while (points.length < 4) points.push(points[0].slice()); + return points; + } - function attachListeners() { - if(attached) { - return + function polygon(arcs) { + return arcs.map(ring); } - attached = true - element.addEventListener('mousemove', handleMouseMove) + function geometry(o) { + var t = o.type; + return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} + : t in geometryType ? {type: t, coordinates: geometryType[t](o)} + : null; + } - element.addEventListener('mousedown', handleMouseDown) + var geometryType = { + Point: function(o) { return point(o.coordinates); }, + MultiPoint: function(o) { return o.coordinates.map(point); }, + LineString: function(o) { return line(o.arcs); }, + MultiLineString: function(o) { return o.arcs.map(line); }, + Polygon: function(o) { return polygon(o.arcs); }, + MultiPolygon: function(o) { return o.arcs.map(polygon); } + }; - element.addEventListener('mouseup', handleMouseUp) + return geometry(o); + } - element.addEventListener('mouseleave', clearState) - element.addEventListener('mouseenter', clearState) - element.addEventListener('mouseout', clearState) - element.addEventListener('mouseover', clearState) + function stitchArcs(topology, arcs) { + var stitchedArcs = {}, + fragmentByStart = {}, + fragmentByEnd = {}, + fragments = [], + emptyIndex = -1; - element.addEventListener('blur', handleBlur) + // Stitch empty arcs first, since they may be subsumed by other arcs. + arcs.forEach(function(i, j) { + var arc = topology.arcs[i < 0 ? ~i : i], t; + if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { + t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; + } + }); - element.addEventListener('keyup', handleMods) - element.addEventListener('keydown', handleMods) - element.addEventListener('keypress', handleMods) + arcs.forEach(function(i) { + var e = ends(i), + start = e[0], + end = e[1], + f, g; - if(element !== window) { - window.addEventListener('blur', handleBlur) + if (f = fragmentByEnd[start]) { + delete fragmentByEnd[f.end]; + f.push(i); + f.end = end; + if (g = fragmentByStart[end]) { + delete fragmentByStart[g.start]; + var fg = g === f ? f : f.concat(g); + fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else if (f = fragmentByStart[end]) { + delete fragmentByStart[f.start]; + f.unshift(i); + f.start = start; + if (g = fragmentByEnd[start]) { + delete fragmentByEnd[g.end]; + var gf = g === f ? f : g.concat(f); + fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; + } else { + fragmentByStart[f.start] = fragmentByEnd[f.end] = f; + } + } else { + f = [i]; + fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; + } + }); - window.addEventListener('keyup', handleMods) - window.addEventListener('keydown', handleMods) - window.addEventListener('keypress', handleMods) + function ends(i) { + var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; + if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); + else p1 = arc[arc.length - 1]; + return i < 0 ? [p1, p0] : [p0, p1]; } - } - function detachListeners() { - if(!attached) { - return + function flush(fragmentByEnd, fragmentByStart) { + for (var k in fragmentByEnd) { + var f = fragmentByEnd[k]; + delete fragmentByStart[f.start]; + delete f.start; + delete f.end; + f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); + fragments.push(f); + } } - attached = false - element.removeEventListener('mousemove', handleMouseMove) + flush(fragmentByEnd, fragmentByStart); + flush(fragmentByStart, fragmentByEnd); + arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); - element.removeEventListener('mousedown', handleMouseDown) + return fragments; + } - element.removeEventListener('mouseup', handleMouseUp) + function mesh(topology) { + return object(topology, meshArcs.apply(this, arguments)); + } - element.removeEventListener('mouseleave', clearState) - element.removeEventListener('mouseenter', clearState) - element.removeEventListener('mouseout', clearState) - element.removeEventListener('mouseover', clearState) + function meshArcs(topology, o, filter) { + var arcs = []; - element.removeEventListener('blur', handleBlur) + function arc(i) { + var j = i < 0 ? ~i : i; + (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); + } - element.removeEventListener('keyup', handleMods) - element.removeEventListener('keydown', handleMods) - element.removeEventListener('keypress', handleMods) + function line(arcs) { + arcs.forEach(arc); + } - if(element !== window) { - window.removeEventListener('blur', handleBlur) + function polygon(arcs) { + arcs.forEach(line); + } - window.removeEventListener('keyup', handleMods) - window.removeEventListener('keydown', handleMods) - window.removeEventListener('keypress', handleMods) + function geometry(o) { + if (o.type === "GeometryCollection") o.geometries.forEach(geometry); + else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs); } - } - //Attach listeners - attachListeners() + if (arguments.length > 1) { + var geomsByArc = [], + geom; - var result = { - element: element - } + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs) { arcs.forEach(polygon); } + }; - Object.defineProperties(result, { - enabled: { - get: function() { return attached }, - set: function(f) { - if(f) { - attachListeners() - } else { - detachListeners - } - }, - enumerable: true - }, - buttons: { - get: function() { return buttonState }, - enumerable: true - }, - x: { - get: function() { return x }, - enumerable: true - }, - y: { - get: function() { return y }, - enumerable: true - }, - mods: { - get: function() { return mods }, - enumerable: true - } - }) + geometry(o); - return result -} + geomsByArc.forEach(arguments.length < 3 + ? function(geoms) { arcs.push(geoms[0].i); } + : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); + } else { + for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); + } -},{"mouse-event":1005}],1005:[function(require,module,exports){ -'use strict' + return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)}; + } -function mouseButtons(ev) { - if(typeof ev === 'object') { - if('buttons' in ev) { - return ev.buttons - } else if('which' in ev) { - var b = ev.which - if(b === 2) { - return 4 - } else if(b === 3) { - return 2 - } else if(b > 0) { - return 1<<(b-1) - } - } else if('button' in ev) { - var b = ev.button - if(b === 1) { - return 4 - } else if(b === 2) { - return 2 - } else if(b >= 0) { - return 1< 0; // TODO allow spherical? + } -var PIXELS_PER_INCH = 96 + polygons.forEach(function(polygon) { + if (!polygon._) { + var component = [], + neighbors = [polygon]; + polygon._ = 1; + components.push(component); + while (polygon = neighbors.pop()) { + component.push(polygon); + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { + if (!polygon._) { + polygon._ = 1; + neighbors.push(polygon); + } + }); + }); + }); + } + } + }); -function getPropertyInPX(element, prop) { - var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop)) - return parts[0] * toPX(parts[1], element) -} + polygons.forEach(function(polygon) { + delete polygon._; + }); -//This brutal hack is needed -function getSizeBrutal(unit, element) { - var testDIV = document.createElement('div') - testDIV.style['font-size'] = '128' + unit - element.appendChild(testDIV) - var size = getPropertyInPX(testDIV, 'font-size') / 128 - element.removeChild(testDIV) - return size -} + return { + type: "MultiPolygon", + arcs: components.map(function(polygons) { + var arcs = [], n; -function toPX(str, element) { - element = element || document.body - str = (str || 'px').trim().toLowerCase() - if(element === window || element === document) { - element = document.body - } - switch(str) { - case '%': //Ambiguous, not sure if we should use width or height - return element.clientHeight / 100.0 - case 'ch': - case 'ex': - return getSizeBrutal(str, element) - case 'em': - return getPropertyInPX(element, 'font-size') - case 'rem': - return getPropertyInPX(document.body, 'font-size') - case 'vw': - return window.innerWidth/100 - case 'vh': - return window.innerHeight/100 - case 'vmin': - return Math.min(window.innerWidth, window.innerHeight) / 100 - case 'vmax': - return Math.max(window.innerWidth, window.innerHeight) / 100 - case 'in': - return PIXELS_PER_INCH - case 'cm': - return PIXELS_PER_INCH / 2.54 - case 'mm': - return PIXELS_PER_INCH / 25.4 - case 'pt': - return PIXELS_PER_INCH / 72 - case 'pc': - return PIXELS_PER_INCH / 6 - } - return 1 -} -},{"parse-unit":1006}],1008:[function(require,module,exports){ -'use strict' + // Extract the exterior (unique) arcs. + polygons.forEach(function(polygon) { + polygon.forEach(function(ring$$) { + ring$$.forEach(function(arc) { + if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { + arcs.push(arc); + } + }); + }); + }); -var toPX = require('to-px') + // Stitch the arcs into one or more rings. + arcs = stitchArcs(topology, arcs); -module.exports = mouseWheelListen + // If more than one ring is returned, + // at most one of these rings can be the exterior; + // this exterior ring has the same winding order + // as any exterior ring in the original polygons. + if ((n = arcs.length) > 1) { + var sgn = exterior(polygons[0][0]); + for (var i = 0, t; i < n; ++i) { + if (sgn === exterior(arcs[i])) { + t = arcs[0], arcs[0] = arcs[i], arcs[i] = t; + break; + } + } + } -function mouseWheelListen(element, callback, noScroll) { - if(typeof element === 'function') { - noScroll = !!callback - callback = element - element = window - } - var lineHeight = toPX('ex', element) - var listener = function(ev) { - if(noScroll) { - ev.preventDefault() - } - var dx = ev.deltaX || 0 - var dy = ev.deltaY || 0 - var dz = ev.deltaZ || 0 - var mode = ev.deltaMode - var scale = 1 - switch(mode) { - case 1: - scale = lineHeight - break - case 2: - scale = window.innerHeight - break - } - dx *= scale - dy *= scale - dz *= scale - if(dx || dy || dz) { - return callback(dx, dy, dz) - } + return arcs; + }) + }; } - element.addEventListener('wheel', listener) - return listener -} -},{"to-px":1007}],1009:[function(require,module,exports){ -"use strict" + function neighbors(objects) { + var indexesByArc = {}, // arc index -> array of object indexes + neighbors = objects.map(function() { return []; }); + function line(arcs, i) { + arcs.forEach(function(a) { + if (a < 0) a = ~a; + var o = indexesByArc[a]; + if (o) o.push(i); + else indexesByArc[a] = [i]; + }); + } + function polygon(arcs, i) { + arcs.forEach(function(arc) { line(arc, i); }); + } -var fill = require('cwise/lib/wrapper')({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_4_arg1_=_inline_4_arg2_.apply(void 0,_inline_4_arg0_)}","args":[{"name":"_inline_4_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_4_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_4_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64}) + function geometry(o, i) { + if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); + else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + } -module.exports = function(array, f) { - fill(array, f) - return array -} + var geometryType = { + LineString: line, + MultiLineString: polygon, + Polygon: polygon, + MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } + }; -},{"cwise/lib/wrapper":1010}],1010:[function(require,module,exports){ -arguments[4][318][0].apply(exports,arguments) -},{"cwise-compiler":1011,"dup":318}],1011:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":1013,"dup":319}],1012:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":1014}],1013:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":1012,"dup":321}],1014:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],1015:[function(require,module,exports){ -'use strict' + objects.forEach(geometry); -module.exports = invert + for (var i in indexesByArc) { + for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { + for (var k = j + 1; k < m; ++k) { + var ij = indexes[j], ik = indexes[k], n; + if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); + if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); + } + } + } -var invert2 = require('gl-mat2/invert') -var invert3 = require('gl-mat3/invert') -var invert4 = require('gl-mat4/invert') + return neighbors; + } -function invert(out, M) { - switch(M.length) { - case 0: - break - case 1: - out[0] = 1.0 / M[0] - break - case 4: - invert2(out, M) - break - case 9: - invert3(out, M) - break - case 16: - invert4(out, M) - break - default: - throw new Error('currently supports matrices up to 4x4') - break + function compareArea(a, b) { + return a[1][2] - b[1][2]; } - return out -} -},{"gl-mat2/invert":1016,"gl-mat3/invert":1017,"gl-mat4/invert":240}],1016:[function(require,module,exports){ -module.exports = invert -/** - * Inverts a mat2 - * - * @alias mat2.invert - * @param {mat2} out the receiving matrix - * @param {mat2} a the source matrix - * @returns {mat2} out - */ -function invert(out, a) { - var a0 = a[0] - var a1 = a[1] - var a2 = a[2] - var a3 = a[3] - var det = a0 * a3 - a2 * a1 + function minAreaHeap() { + var heap = {}, + array = [], + size = 0; - if (!det) return null - det = 1.0 / det + heap.push = function(object) { + up(array[object._ = size] = object, size++); + return size; + }; - out[0] = a3 * det - out[1] = -a1 * det - out[2] = -a2 * det - out[3] = a0 * det + heap.pop = function() { + if (size <= 0) return; + var removed = array[0], object; + if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0); + return removed; + }; - return out -} + heap.remove = function(removed) { + var i = removed._, object; + if (array[i] !== removed) return; // invalid request + if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); + return i; + }; -},{}],1017:[function(require,module,exports){ -module.exports = invert + function up(object, i) { + while (i > 0) { + var j = ((i + 1) >> 1) - 1, + parent = array[j]; + if (compareArea(object, parent) >= 0) break; + array[parent._ = i] = parent; + array[object._ = i = j] = object; + } + } -/** - * Inverts a mat3 - * - * @alias mat3.invert - * @param {mat3} out the receiving matrix - * @param {mat3} a the source matrix - * @returns {mat3} out - */ -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2] - var a10 = a[3], a11 = a[4], a12 = a[5] - var a20 = a[6], a21 = a[7], a22 = a[8] + function down(object, i) { + while (true) { + var r = (i + 1) << 1, + l = r - 1, + j = i, + child = array[j]; + if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; + if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; + if (j === i) break; + array[child._ = i] = child; + array[object._ = i = j] = object; + } + } - var b01 = a22 * a11 - a12 * a21 - var b11 = -a22 * a10 + a12 * a20 - var b21 = a21 * a10 - a11 * a20 + return heap; + } - // Calculate the determinant - var det = a00 * b01 + a01 * b11 + a02 * b21 + function presimplify(topology, triangleArea) { + var absolute$$ = absolute(topology.transform), + relative$$ = relative(topology.transform), + heap = minAreaHeap(); - if (!det) return null - det = 1.0 / det + if (!triangleArea) triangleArea = triangle; - out[0] = b01 * det - out[1] = (-a22 * a01 + a02 * a21) * det - out[2] = (a12 * a01 - a02 * a11) * det - out[3] = b11 * det - out[4] = (a22 * a00 - a02 * a20) * det - out[5] = (-a12 * a00 + a02 * a10) * det - out[6] = b21 * det - out[7] = (-a21 * a00 + a01 * a20) * det - out[8] = (a11 * a00 - a01 * a10) * det + topology.arcs.forEach(function(arc) { + var triangles = [], + maxArea = 0, + triangle, + i, + n, + p; - return out -} + // To store each point’s effective area, we create a new array rather than + // extending the passed-in point to workaround a Chrome/V8 bug (getting + // stuck in smi mode). For midpoints, the initial effective area of + // Infinity will be computed in the next step. + for (i = 0, n = arc.length; i < n; ++i) { + p = arc[i]; + absolute$$(arc[i] = [p[0], p[1], Infinity], i); + } -},{}],1018:[function(require,module,exports){ -arguments[4][318][0].apply(exports,arguments) -},{"cwise-compiler":1019,"dup":318}],1019:[function(require,module,exports){ -arguments[4][319][0].apply(exports,arguments) -},{"./lib/thunk.js":1021,"dup":319}],1020:[function(require,module,exports){ -arguments[4][320][0].apply(exports,arguments) -},{"dup":320,"uniq":1022}],1021:[function(require,module,exports){ -arguments[4][321][0].apply(exports,arguments) -},{"./compile.js":1020,"dup":321}],1022:[function(require,module,exports){ -arguments[4][87][0].apply(exports,arguments) -},{"dup":87}],1023:[function(require,module,exports){ -"use strict" + for (i = 1, n = arc.length - 1; i < n; ++i) { + triangle = arc.slice(i - 1, i + 2); + triangle[1][2] = triangleArea(triangle); + triangles.push(triangle); + heap.push(triangle); + } -function interp1d(arr, x) { - var ix = Math.floor(x) - , fx = x - ix - , s0 = 0 <= ix && ix < arr.shape[0] - , s1 = 0 <= ix+1 && ix+1 < arr.shape[0] - , w0 = s0 ? +arr.get(ix) : 0.0 - , w1 = s1 ? +arr.get(ix+1) : 0.0 - return (1.0-fx)*w0 + fx*w1 -} + for (i = 0, n = triangles.length; i < n; ++i) { + triangle = triangles[i]; + triangle.previous = triangles[i - 1]; + triangle.next = triangles[i + 1]; + } -function interp2d(arr, x, y) { - var ix = Math.floor(x) - , fx = x - ix - , s0 = 0 <= ix && ix < arr.shape[0] - , s1 = 0 <= ix+1 && ix+1 < arr.shape[0] - , iy = Math.floor(y) - , fy = y - iy - , t0 = 0 <= iy && iy < arr.shape[1] - , t1 = 0 <= iy+1 && iy+1 < arr.shape[1] - , w00 = s0&&t0 ? arr.get(ix ,iy ) : 0.0 - , w01 = s0&&t1 ? arr.get(ix ,iy+1) : 0.0 - , w10 = s1&&t0 ? arr.get(ix+1,iy ) : 0.0 - , w11 = s1&&t1 ? arr.get(ix+1,iy+1) : 0.0 - return (1.0-fy) * ((1.0-fx)*w00 + fx*w10) + fy * ((1.0-fx)*w01 + fx*w11) -} + while (triangle = heap.pop()) { + var previous = triangle.previous, + next = triangle.next; -function interp3d(arr, x, y, z) { - var ix = Math.floor(x) - , fx = x - ix - , s0 = 0 <= ix && ix < arr.shape[0] - , s1 = 0 <= ix+1 && ix+1 < arr.shape[0] - , iy = Math.floor(y) - , fy = y - iy - , t0 = 0 <= iy && iy < arr.shape[1] - , t1 = 0 <= iy+1 && iy+1 < arr.shape[1] - , iz = Math.floor(z) - , fz = z - iz - , u0 = 0 <= iz && iz < arr.shape[2] - , u1 = 0 <= iz+1 && iz+1 < arr.shape[2] - , w000 = s0&&t0&&u0 ? arr.get(ix,iy,iz) : 0.0 - , w010 = s0&&t1&&u0 ? arr.get(ix,iy+1,iz) : 0.0 - , w100 = s1&&t0&&u0 ? arr.get(ix+1,iy,iz) : 0.0 - , w110 = s1&&t1&&u0 ? arr.get(ix+1,iy+1,iz) : 0.0 - , w001 = s0&&t0&&u1 ? arr.get(ix,iy,iz+1) : 0.0 - , w011 = s0&&t1&&u1 ? arr.get(ix,iy+1,iz+1) : 0.0 - , w101 = s1&&t0&&u1 ? arr.get(ix+1,iy,iz+1) : 0.0 - , w111 = s1&&t1&&u1 ? arr.get(ix+1,iy+1,iz+1) : 0.0 - return (1.0-fz) * ((1.0-fy) * ((1.0-fx)*w000 + fx*w100) + fy * ((1.0-fx)*w010 + fx*w110)) + fz * ((1.0-fy) * ((1.0-fx)*w001 + fx*w101) + fy * ((1.0-fx)*w011 + fx*w111)) -} + // If the area of the current point is less than that of the previous point + // to be eliminated, use the latter's area instead. This ensures that the + // current point cannot be eliminated without eliminating previously- + // eliminated points. + if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; + else maxArea = triangle[1][2]; -function interpNd(arr) { - var d = arr.shape.length|0 - , ix = new Array(d) - , fx = new Array(d) - , s0 = new Array(d) - , s1 = new Array(d) - , i, t - for(i=0; i>", - rrshift: ">>>" -} -;(function(){ - for(var id in assign_ops) { - var op = assign_ops[id] - exports[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a","b","c"], - body: "a=b"+op+"c"}, - funcName: id - }) - exports[id+"eq"] = makeOp({ - args: ["array","array"], - body: {args:["a","b"], - body:"a"+op+"=b"}, - rvalue: true, - funcName: id+"eq" - }) - exports[id+"s"] = makeOp({ - args: ["array", "array", "scalar"], - body: {args:["a","b","s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - exports[id+"seq"] = makeOp({ - args: ["array","scalar"], - body: {args:["a","s"], - body:"a"+op+"=s"}, - rvalue: true, - funcName: id+"seq" - }) +function freeArrayBuffer(buffer) { + if(!buffer) { + return } -})(); + var n = buffer.length || buffer.byteLength + var log_n = bits.log2(n) + DATA[log_n].push(buffer) +} -var unary_ops = { - not: "!", - bnot: "~", - neg: "-", - recip: "1.0/" +function freeTypedArray(array) { + freeArrayBuffer(array.buffer) } -;(function(){ - for(var id in unary_ops) { - var op = unary_ops[id] - exports[id] = makeOp({ - args: ["array", "array"], - body: {args:["a","b"], - body:"a="+op+"b"}, - funcName: id - }) - exports[id+"eq"] = makeOp({ - args: ["array"], - body: {args:["a"], - body:"a="+op+"a"}, - rvalue: true, - count: 2, - funcName: id+"eq" - }) - } -})(); -var binary_ops = { - and: "&&", - or: "||", - eq: "===", - neq: "!==", - lt: "<", - gt: ">", - leq: "<=", - geq: ">=" +exports.freeUint8 = +exports.freeUint16 = +exports.freeUint32 = +exports.freeInt8 = +exports.freeInt16 = +exports.freeInt32 = +exports.freeFloat32 = +exports.freeFloat = +exports.freeFloat64 = +exports.freeDouble = +exports.freeUint8Clamped = +exports.freeDataView = freeTypedArray + +exports.freeArrayBuffer = freeArrayBuffer + +exports.freeBuffer = function freeBuffer(array) { + BUFFER[bits.log2(array.length)].push(array) } -;(function() { - for(var id in binary_ops) { - var op = binary_ops[id] - exports[id] = makeOp({ - args: ["array","array","array"], - body: {args:["a", "b", "c"], - body:"a=b"+op+"c"}, - funcName: id - }) - exports[id+"s"] = makeOp({ - args: ["array","array","scalar"], - body: {args:["a", "b", "s"], - body:"a=b"+op+"s"}, - funcName: id+"s" - }) - exports[id+"eq"] = makeOp({ - args: ["array", "array"], - body: {args:["a", "b"], - body:"a=a"+op+"b"}, - rvalue:true, - count:2, - funcName: id+"eq" - }) - exports[id+"seq"] = makeOp({ - args: ["array", "scalar"], - body: {args:["a","s"], - body:"a=a"+op+"s"}, - rvalue:true, - count:2, - funcName: id+"seq" - }) - } -})(); -var math_unary = [ - "abs", - "acos", - "asin", - "atan", - "ceil", - "cos", - "exp", - "floor", - "log", - "round", - "sin", - "sqrt", - "tan" -] -;(function() { - for(var i=0; i 0) { + return d.pop() } -})(); - -exports.any = compile({ - args:["array"], - pre: EmptyProc, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []}, - post: {args:[], localVars:[], thisVars:[], body:"return false"}, - funcName: "any" -}) + return new ArrayBuffer(n) +} +exports.mallocArrayBuffer = mallocArrayBuffer -exports.all = compile({ - args:["array"], - pre: EmptyProc, - body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []}, - post: {args:[], localVars:[], thisVars:[], body:"return true"}, - funcName: "all" -}) +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocUint8 = mallocUint8 -exports.sum = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "sum" -}) +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocUint16 = mallocUint16 -exports.prod = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "prod" -}) +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocUint32 = mallocUint32 -exports.norm2squared = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norm2squared" -}) - -exports.norm2 = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"}, - funcName: "norm2" -}) - +function mallocInt8(n) { + return new Int8Array(mallocArrayBuffer(n), 0, n) +} +exports.mallocInt8 = mallocInt8 -exports.norminf = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norminf" -}) +function mallocInt16(n) { + return new Int16Array(mallocArrayBuffer(2*n), 0, n) +} +exports.mallocInt16 = mallocInt16 -exports.norm1 = compile({ - args:["array"], - pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"}, - body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]}, - post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"}, - funcName: "norm1" -}) +function mallocInt32(n) { + return new Int32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocInt32 = mallocInt32 -exports.sup = compile({ - args: [ "array" ], - pre: - { body: "this_h=-Infinity", - args: [], - thisVars: [ "this_h" ], - localVars: [] }, - body: - { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_", - args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ], - thisVars: [ "this_h" ], - localVars: [] }, - post: - { body: "return this_h", - args: [], - thisVars: [ "this_h" ], - localVars: [] } - }) +function mallocFloat(n) { + return new Float32Array(mallocArrayBuffer(4*n), 0, n) +} +exports.mallocFloat32 = exports.mallocFloat = mallocFloat -exports.inf = compile({ - args: [ "array" ], - pre: - { body: "this_h=Infinity", - args: [], - thisVars: [ "this_h" ], - localVars: [] }, - body: - { body: "if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}", - args:[ - {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2}, - {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}], - thisVars:["this_i","this_v"], - localVars:["_inline_1_k"]}, - post:{ - body:"{return this_i}", - args:[], - thisVars:["this_i"], - localVars:[]} -}) +function mallocDataView(n) { + return new DataView(mallocArrayBuffer(n), 0, n) +} +exports.mallocDataView = mallocDataView -exports.random = makeOp({ - args: ["array"], - pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]}, - body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]}, - funcName: "random" -}) +function mallocBuffer(n) { + n = bits.nextPow2(n) + var log_n = bits.log2(n) + var cache = BUFFER[log_n] + if(cache.length > 0) { + return cache.pop() + } + return new Buffer(n) +} +exports.mallocBuffer = mallocBuffer -exports.assign = makeOp({ - args:["array", "array"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assign" }) +exports.clearCache = function clearCache() { + for(var i=0; i<32; ++i) { + POOL.UINT8[i].length = 0 + POOL.UINT16[i].length = 0 + POOL.UINT32[i].length = 0 + POOL.INT8[i].length = 0 + POOL.INT16[i].length = 0 + POOL.INT32[i].length = 0 + POOL.FLOAT[i].length = 0 + POOL.DOUBLE[i].length = 0 + POOL.UINT8C[i].length = 0 + DATA[i].length = 0 + BUFFER[i].length = 0 + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) +},{"bit-twiddle":50,"buffer":51,"dup":115}],279:[function(require,module,exports){ +"use strict" -exports.assigns = makeOp({ - args:["array", "scalar"], - body: {args:["a", "b"], body:"a=b"}, - funcName: "assigns" }) +function unique_pred(list, compare) { + var ptr = 1 + , len = list.length + , a=list[0], b=list[0] + for(var i=1; iMath.abs(this.stride[1]))?[1,0]:[0,1]}})") - } else if(dimension === 3) { - code.push( -"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ -if(s0>s1){\ -if(s1>s2){\ -return [2,1,0];\ -}else if(s0>s2){\ -return [1,2,0];\ -}else{\ -return [1,0,2];\ -}\ -}else if(s0>s2){\ -return [2,0,1];\ -}else if(s2>s1){\ -return [0,1,2];\ -}else{\ -return [0,2,1];\ -}}})") - } - } else { - code.push("ORDER})") + var lo = [1<<30, 1<<30] + var hi = [0,0] + var n = positions.length + for(var i=0; i=0){\ -d=i"+i+"|0;\ -b+=c"+i+"*d;\ -a"+i+"-=d}") - } - code.push("return new "+className+"(this.data,"+ - indices.map(function(i) { - return "a"+i - }).join(",")+","+ - indices.map(function(i) { - return "c"+i - }).join(",")+",b)}") + case "alphabetic": + case "ideographic": + yShift = -3 * size + break - //view.step(): - code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ - indices.map(function(i) { - return "a"+i+"=this.shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "b"+i+"=this.stride["+i+"]" - }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") - for(var i=0; i=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") + return positions.map(function(p) { + return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ] + }) +} + +function getPixels(canvas, context, str, size) { + var width = Math.ceil(context.measureText(str).width + 2*size)|0 + if(width > 8192) { + throw new Error("vectorize-text: String too long (sorry, this will get fixed later)") + } + var height = 3 * size + if(canvas.height < height) { + canvas.height = height } - code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") - //Add return statement - code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ - indices.map(function(i) { - return "shape["+i+"]" - }).join(",")+","+ - indices.map(function(i) { - return "stride["+i+"]" - }).join(",")+",offset)}") + context.fillStyle = "#000" + context.fillRect(0, 0, canvas.width, canvas.height) - //Compile procedure - var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) - return procedure(CACHED_CONSTRUCTORS[dtype], order) + context.fillStyle = "#fff" + context.fillText(str, size, 2*size) + + //Cut pixels from image + var pixelData = context.getImageData(0, 0, width, height) + var pixels = ndarray(pixelData.data, [height, width, 4]) + + return pixels.pick(-1,-1,0).transpose(1,0) } -function arrayDType(data) { - if(isBuffer(data)) { - return "buffer" - } - if(hasTypedArrays) { - switch(Object.prototype.toString.call(data)) { - case "[object Float64Array]": - return "float64" - case "[object Float32Array]": - return "float32" - case "[object Int8Array]": - return "int8" - case "[object Int16Array]": - return "int16" - case "[object Int32Array]": - return "int32" - case "[object Uint8Array]": - return "uint8" - case "[object Uint16Array]": - return "uint16" - case "[object Uint32Array]": - return "uint32" - case "[object Uint8ClampedArray]": - return "uint8_clamped" - } +function getContour(pixels, doSimplify) { + var contour = surfaceNets(pixels, 128) + if(doSimplify) { + return simplify(contour.cells, contour.positions, 0.25) } - if(Array.isArray(data)) { - return "array" + return { + edges: contour.cells, + positions: contour.positions } - return "generic" } -var CACHED_CONSTRUCTORS = { - "float32":[], - "float64":[], - "int8":[], - "int16":[], - "int32":[], - "uint8":[], - "uint16":[], - "uint32":[], - "array":[], - "uint8_clamped":[], - "buffer":[], - "generic":[] -} +function processPixelsImpl(pixels, options, size, simplify) { + //Extract contour + var contour = getContour(pixels, simplify) -;(function() { - for(var id in CACHED_CONSTRUCTORS) { - CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) - } -}); + //Apply warp to positions + var positions = transformPositions(contour.positions, options, size) + var edges = contour.edges + var flip = "ccw" === options.orientation -function wrappedNDArrayCtor(data, shape, stride, offset) { - if(data === undefined) { - var ctor = CACHED_CONSTRUCTORS.array[0] - return ctor([]) - } else if(typeof data === "number") { - data = [data] - } - if(shape === undefined) { - shape = [ data.length ] - } - var d = shape.length - if(stride === undefined) { - stride = new Array(d) - for(var i=d-1, sz=1; i>=0; --i) { - stride[i] = sz - sz *= shape[i] - } - } - if(offset === undefined) { - offset = 0 - for(var i=0; i - * License: MIT - * - * `npm install is-buffer` - */ +function vectorizeText(str, canvas, context, options) { + var size = options.size || 64 + var family = options.font || "normal" + + context.font = size + "px " + family + context.textAlign = "start" + context.textBaseline = "alphabetic" + context.direction = "ltr" -module.exports = function (obj) { - return !!(obj != null && - (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) - (obj.constructor && - typeof obj.constructor.isBuffer === 'function' && - obj.constructor.isBuffer(obj)) - )) + var pixels = getPixels(canvas, context, str, size) + + return processPixels(pixels, options, size) } -},{}],1034:[function(require,module,exports){ -(function (global){ -module.exports = - global.performance && - global.performance.now ? function now() { - return performance.now() - } : Date.now || function now() { - return +new Date - } +},{"cdt2d":57,"clean-pslg":64,"ndarray":253,"planar-graph-to-polyline":294,"simplify-planar-graph":298,"surface-nets":272}],282:[function(require,module,exports){ +'use strict' -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],1035:[function(require,module,exports){ -arguments[4][53][0].apply(exports,arguments) -},{"dup":53}],1036:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"dup":54,"two-product":1039,"two-sum":1035}],1037:[function(require,module,exports){ -arguments[4][364][0].apply(exports,arguments) -},{"dup":364}],1038:[function(require,module,exports){ -arguments[4][55][0].apply(exports,arguments) -},{"dup":55}],1039:[function(require,module,exports){ -arguments[4][56][0].apply(exports,arguments) -},{"dup":56}],1040:[function(require,module,exports){ -"use strict" +module.exports = trimLeaves -var twoProduct = require("two-product") -var robustSum = require("robust-sum") -var robustScale = require("robust-scale") -var robustSubtract = require("robust-subtract") +var e2a = require('edges-to-adjacency-list') -var NUM_EXPAND = 5 +function trimLeaves(edges, positions) { + var adj = e2a(edges, positions.length) + var live = new Array(positions.length) + var nbhd = new Array(positions.length) -var EPSILON = 1.1102230246251565e-16 -var ERRBOUND3 = (3.0 + 16.0 * EPSILON) * EPSILON -var ERRBOUND4 = (7.0 + 56.0 * EPSILON) * EPSILON + var dead = [] + for(var i=0; i 0) { + var v = dead.pop() + live[v] = false + var n = adj[v] + for(var i=0; i>1 - return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("") - } -} +module.exports = edgeToAdjacency -function determinant(m) { - if(m.length === 2) { - return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")] - } else { - var expr = [] - for(var i=0; i 0) { - if(r <= 0) { - return det - } else { - s = l + r + //Find next vertex and cut edge + function next(a, b, noCut) { + var nextCell, nextVertex, nextDir + for(var i=0; i<2; ++i) { + if(adj[i][b].length > 0) { + nextCell = adj[i][b][0] + nextDir = i + break } - } else if(l < 0) { - if(r >= 0) { - return det - } else { - s = -(l + r) + } + nextVertex = nextCell[nextDir^1] + + for(var dir=0; dir<2; ++dir) { + var nbhd = adj[dir][b] + for(var k=0; k 0) { + nextCell = e + nextVertex = p + nextDir = dir + } } - } else { - return det } - var tol = ERRBOUND3 * s - if(det >= tol || det <= -tol) { - return det + if(noCut) { + return nextVertex } - return orientation3Exact(a, b, c) - }, - function orientation4(a,b,c,d) { - var adx = a[0] - d[0] - var bdx = b[0] - d[0] - var cdx = c[0] - d[0] - var ady = a[1] - d[1] - var bdy = b[1] - d[1] - var cdy = c[1] - d[1] - var adz = a[2] - d[2] - var bdz = b[2] - d[2] - var cdz = c[2] - d[2] - var bdxcdy = bdx * cdy - var cdxbdy = cdx * bdy - var cdxady = cdx * ady - var adxcdy = adx * cdy - var adxbdy = adx * bdy - var bdxady = bdx * ady - var det = adz * (bdxcdy - cdxbdy) - + bdz * (cdxady - adxcdy) - + cdz * (adxbdy - bdxady) - var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) - + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) - + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz) - var tol = ERRBOUND4 * permanent - if ((det > tol) || (-det > tol)) { - return det + if(nextCell) { + cut(nextCell, nextDir) } - return orientation4Exact(a,b,c,d) + return nextVertex } -] -function slowOrient(args) { - var proc = CACHED[args.length] - if(!proc) { - proc = CACHED[args.length] = orientation(args.length) + function extractCycle(v, dir) { + var e0 = adj[dir][v][0] + var cycle = [v] + cut(e0, dir) + var u = e0[dir^1] + var d0 = dir + while(true) { + while(u !== v) { + cycle.push(u) + u = next(cycle[cycle.length-2], u, false) + } + if(adj[0][v].length + adj[1][v].length === 0) { + break + } + var a = cycle[cycle.length-1] + var b = v + var c = cycle[1] + var d = next(a, b, true) + if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) { + break + } + cycle.push(v) + u = next(a, b) + } + return cycle } - return proc.apply(undefined, args) -} -function generateOrientationProc() { - while(CACHED.length <= NUM_EXPAND) { - CACHED.push(orientation(CACHED.length)) - } - var args = [] - var procArgs = ["slow"] - for(var i=0; i<=NUM_EXPAND; ++i) { - args.push("a" + i) - procArgs.push("o" + i) - } - var code = [ - "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;" - ] - for(var i=2; i<=NUM_EXPAND; ++i) { - code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");") + function shouldGlue(pcycle, ncycle) { + return (ncycle[1] === ncycle[ncycle.length-1]) } - code.push("}var s=new Array(arguments.length);for(var i=0;i 0) { + var ni = adj[0][i].length + var ncycle = extractCycle(i,j) + if(shouldGlue(pcycle, ncycle)) { + //Glue together trivial cycles + pcycle.push.apply(pcycle, ncycle) + } else { + if(pcycle.length > 0) { + cycles.push(pcycle) + } + pcycle = ncycle + } + } + if(pcycle.length > 0) { + cycles.push(pcycle) + } + } } + + //Combine paths and loops together + return cycles } +},{"compare-angle":285}],285:[function(require,module,exports){ +"use strict" -generateOrientationProc() -},{"robust-scale":1036,"robust-subtract":1037,"robust-sum":1038,"two-product":1039}],1041:[function(require,module,exports){ -'use strict' +module.exports = compareAngle -module.exports = toSuperScript +var orient = require("robust-orientation") +var sgn = require("signum") +var twoSum = require("two-sum") +var robustProduct = require("robust-product") +var robustSum = require("robust-sum") -var SUPERSCRIPTS = { - ' ': ' ', - '0': '⁰', - '1': '¹', - '2': '²', - '3': '³', - '4': '⁴', - '5': '⁵', - '6': '⁶', - '7': '⁷', - '8': '⁸', - '9': '⁹', - '+': '⁺', - '-': '⁻', - 'a': 'ᵃ', - 'b': 'ᵇ', - 'c': 'ᶜ', - 'd': 'ᵈ', - 'e': 'ᵉ', - 'f': 'ᶠ', - 'g': 'ᵍ', - 'h': 'ʰ', - 'i': 'ⁱ', - 'j': 'ʲ', - 'k': 'ᵏ', - 'l': 'ˡ', - 'm': 'ᵐ', - 'n': 'ⁿ', - 'o': 'ᵒ', - 'p': 'ᵖ', - 'r': 'ʳ', - 's': 'ˢ', - 't': 'ᵗ', - 'u': 'ᵘ', - 'v': 'ᵛ', - 'w': 'ʷ', - 'x': 'ˣ', - 'y': 'ʸ', - 'z': 'ᶻ' +function testInterior(a, b, c) { + var x0 = twoSum(a[0], -b[0]) + var y0 = twoSum(a[1], -b[1]) + var x1 = twoSum(c[0], -b[0]) + var y1 = twoSum(c[1], -b[1]) + + var d = robustSum( + robustProduct(x0, x1), + robustProduct(y0, y1)) + + return d[d.length-1] >= 0 } -function toSuperScript(x) { - return x.split('').map(function(c) { - if(c in SUPERSCRIPTS) { - return SUPERSCRIPTS[c] +function compareAngle(a, b, c, d) { + var bcd = orient(b, c, d) + if(bcd === 0) { + //Handle degenerate cases + var sabc = sgn(orient(a, b, c)) + var sabd = sgn(orient(a, b, d)) + if(sabc === sabd) { + if(sabc === 0) { + var ic = testInterior(a, b, c) + var id = testInterior(a, b, d) + if(ic === id) { + return 0 + } else if(ic) { + return 1 + } else { + return -1 + } + } + return 0 + } else if(sabd === 0) { + if(sabc > 0) { + return -1 + } else if(testInterior(a, b, d)) { + return -1 + } else { + return 1 + } + } else if(sabc === 0) { + if(sabd > 0) { + return 1 + } else if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } } - return '' - }).join('') + return sgn(sabd - sabc) + } + var abc = orient(a, b, c) + if(abc > 0) { + if(bcd > 0 && orient(a, b, d) > 0) { + return 1 + } + return -1 + } else if(abc < 0) { + if(bcd > 0 || orient(a, b, d) > 0) { + return 1 + } + return -1 + } else { + var abd = orient(a, b, d) + if(abd > 0) { + return 1 + } else { + if(testInterior(a, b, c)) { + return 1 + } else { + return -1 + } + } + } } +},{"robust-orientation":259,"robust-product":286,"robust-sum":262,"signum":287,"two-sum":277}],286:[function(require,module,exports){ +"use strict" -},{}],1042:[function(require,module,exports){ -// TinyColor v1.3.0 -// https://github.com/bgrins/TinyColor -// Brian Grinstead, MIT License - -(function() { +var robustSum = require("robust-sum") +var robustScale = require("robust-scale") -var trimLeft = /^\s+/, - trimRight = /\s+$/, - tinyCounter = 0, - math = Math, - mathRound = math.round, - mathMin = math.min, - mathMax = math.max, - mathRandom = math.random; +module.exports = robustProduct -function tinycolor (color, opts) { +function robustProduct(a, b) { + if(a.length === 1) { + return robustScale(b, a[0]) + } + if(b.length === 1) { + return robustScale(a, b[0]) + } + if(a.length === 0 || b.length === 0) { + return [0] + } + var r = [0] + if(a.length < b.length) { + for(var i=0; i 0) { return 1 } + return 0.0 +} +},{}],288:[function(require,module,exports){ +arguments[4][21][0].apply(exports,arguments) +},{"dup":21}],289:[function(require,module,exports){ +"use strict" - // If input is already a tinycolor, return itself - if (color instanceof tinycolor) { - return color; - } - // If we are called as a function, call using new instead - if (!(this instanceof tinycolor)) { - return new tinycolor(color, opts); - } +var bounds = require("binary-search-bounds") - var rgb = inputToRGB(color); - this._originalInput = color, - this._r = rgb.r, - this._g = rgb.g, - this._b = rgb.b, - this._a = rgb.a, - this._roundA = mathRound(100*this._a) / 100, - this._format = opts.format || rgb.format; - this._gradientType = opts.gradientType; +var NOT_FOUND = 0 +var SUCCESS = 1 +var EMPTY = 2 - // Don't let the range of [0,255] come back in [0,1]. - // Potentially lose a little bit of precision here, but will fix issues where - // .5 gets interpreted as half of the total, instead of half of 1 - // If it was supposed to be 128, this was already taken care of by `inputToRgb` - if (this._r < 1) { this._r = mathRound(this._r); } - if (this._g < 1) { this._g = mathRound(this._g); } - if (this._b < 1) { this._b = mathRound(this._b); } +module.exports = createWrapper - this._ok = rgb.ok; - this._tc_id = tinyCounter++; +function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) { + this.mid = mid + this.left = left + this.right = right + this.leftPoints = leftPoints + this.rightPoints = rightPoints + this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length } -tinycolor.prototype = { - isDark: function() { - return this.getBrightness() < 128; - }, - isLight: function() { - return !this.isDark(); - }, - isValid: function() { - return this._ok; - }, - getOriginalInput: function() { - return this._originalInput; - }, - getFormat: function() { - return this._format; - }, - getAlpha: function() { - return this._a; - }, - getBrightness: function() { - //http://www.w3.org/TR/AERT#color-contrast - var rgb = this.toRgb(); - return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; - }, - getLuminance: function() { - //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef - var rgb = this.toRgb(); - var RsRGB, GsRGB, BsRGB, R, G, B; - RsRGB = rgb.r/255; - GsRGB = rgb.g/255; - BsRGB = rgb.b/255; +var proto = IntervalTreeNode.prototype - if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);} - if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);} - if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);} - return (0.2126 * R) + (0.7152 * G) + (0.0722 * B); - }, - setAlpha: function(value) { - this._a = boundAlpha(value); - this._roundA = mathRound(100*this._a) / 100; - return this; - }, - toHsv: function() { - var hsv = rgbToHsv(this._r, this._g, this._b); - return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; - }, - toHsvString: function() { - var hsv = rgbToHsv(this._r, this._g, this._b); - var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); - return (this._a == 1) ? - "hsv(" + h + ", " + s + "%, " + v + "%)" : - "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")"; - }, - toHsl: function() { - var hsl = rgbToHsl(this._r, this._g, this._b); - return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; - }, - toHslString: function() { - var hsl = rgbToHsl(this._r, this._g, this._b); - var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); - return (this._a == 1) ? - "hsl(" + h + ", " + s + "%, " + l + "%)" : - "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")"; - }, - toHex: function(allow3Char) { - return rgbToHex(this._r, this._g, this._b, allow3Char); - }, - toHexString: function(allow3Char) { - return '#' + this.toHex(allow3Char); - }, - toHex8: function() { - return rgbaToHex(this._r, this._g, this._b, this._a); - }, - toHex8String: function() { - return '#' + this.toHex8(); - }, - toRgb: function() { - return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a }; - }, - toRgbString: function() { - return (this._a == 1) ? - "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : - "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")"; - }, - toPercentageRgb: function() { - return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a }; - }, - toPercentageRgbString: function() { - return (this._a == 1) ? - "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : - "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; - }, - toName: function() { - if (this._a === 0) { - return "transparent"; - } +function copy(a, b) { + a.mid = b.mid + a.left = b.left + a.right = b.right + a.leftPoints = b.leftPoints + a.rightPoints = b.rightPoints + a.count = b.count +} - if (this._a < 1) { - return false; - } +function rebuild(node, intervals) { + var ntree = createIntervalTree(intervals) + node.mid = ntree.mid + node.left = ntree.left + node.right = ntree.right + node.leftPoints = ntree.leftPoints + node.rightPoints = ntree.rightPoints + node.count = ntree.count +} - return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; - }, - toFilter: function(secondColor) { - var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a); - var secondHex8String = hex8String; - var gradientType = this._gradientType ? "GradientType = 1, " : ""; +function rebuildWithInterval(node, interval) { + var intervals = node.intervals([]) + intervals.push(interval) + rebuild(node, intervals) +} - if (secondColor) { - var s = tinycolor(secondColor); - secondHex8String = s.toHex8String(); - } +function rebuildWithoutInterval(node, interval) { + var intervals = node.intervals([]) + var idx = intervals.indexOf(interval) + if(idx < 0) { + return NOT_FOUND + } + intervals.splice(idx, 1) + rebuild(node, intervals) + return SUCCESS +} - return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; - }, - toString: function(format) { - var formatSet = !!format; - format = format || this._format; +proto.intervals = function(result) { + result.push.apply(result, this.leftPoints) + if(this.left) { + this.left.intervals(result) + } + if(this.right) { + this.right.intervals(result) + } + return result +} - var formattedString = false; - var hasAlpha = this._a < 1 && this._a >= 0; - var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); +proto.insert = function(interval) { + var weight = this.count - this.leftPoints.length + this.count += 1 + if(interval[1] < this.mid) { + if(this.left) { + if(4*(this.left.count+1) > 3*(weight+1)) { + rebuildWithInterval(this, interval) + } else { + this.left.insert(interval) + } + } else { + this.left = createIntervalTree([interval]) + } + } else if(interval[0] > this.mid) { + if(this.right) { + if(4*(this.right.count+1) > 3*(weight+1)) { + rebuildWithInterval(this, interval) + } else { + this.right.insert(interval) + } + } else { + this.right = createIntervalTree([interval]) + } + } else { + var l = bounds.ge(this.leftPoints, interval, compareBegin) + var r = bounds.ge(this.rightPoints, interval, compareEnd) + this.leftPoints.splice(l, 0, interval) + this.rightPoints.splice(r, 0, interval) + } +} - if (needsAlphaFormat) { - // Special case for "transparent", all other non-alpha formats - // will return rgba when there is transparency. - if (format === "name" && this._a === 0) { - return this.toName(); - } - return this.toRgbString(); - } - if (format === "rgb") { - formattedString = this.toRgbString(); - } - if (format === "prgb") { - formattedString = this.toPercentageRgbString(); - } - if (format === "hex" || format === "hex6") { - formattedString = this.toHexString(); - } - if (format === "hex3") { - formattedString = this.toHexString(true); - } - if (format === "hex8") { - formattedString = this.toHex8String(); - } - if (format === "name") { - formattedString = this.toName(); +proto.remove = function(interval) { + var weight = this.count - this.leftPoints + if(interval[1] < this.mid) { + if(!this.left) { + return NOT_FOUND + } + var rw = this.right ? this.right.count : 0 + if(4 * rw > 3 * (weight-1)) { + return rebuildWithoutInterval(this, interval) + } + var r = this.left.remove(interval) + if(r === EMPTY) { + this.left = null + this.count -= 1 + return SUCCESS + } else if(r === SUCCESS) { + this.count -= 1 + } + return r + } else if(interval[0] > this.mid) { + if(!this.right) { + return NOT_FOUND + } + var lw = this.left ? this.left.count : 0 + if(4 * lw > 3 * (weight-1)) { + return rebuildWithoutInterval(this, interval) + } + var r = this.right.remove(interval) + if(r === EMPTY) { + this.right = null + this.count -= 1 + return SUCCESS + } else if(r === SUCCESS) { + this.count -= 1 + } + return r + } else { + if(this.count === 1) { + if(this.leftPoints[0] === interval) { + return EMPTY + } else { + return NOT_FOUND + } + } + if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) { + if(this.left && this.right) { + var p = this + var n = this.left + while(n.right) { + p = n + n = n.right } - if (format === "hsl") { - formattedString = this.toHslString(); + if(p === this) { + n.right = this.right + } else { + var l = this.left + var r = this.right + p.count -= n.count + p.right = n.left + n.left = l + n.right = r } - if (format === "hsv") { - formattedString = this.toHsvString(); + copy(this, n) + this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length + } else if(this.left) { + copy(this, this.left) + } else { + copy(this, this.right) + } + return SUCCESS + } + for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l=0 && arr[i][1] >= lo; --i) { + var r = cb(arr[i]) + if(r) { return r } + } +} - _applyCombination: function(fn, args) { - return fn.apply(null, [this].concat([].slice.call(args))); - }, - analogous: function() { - return this._applyCombination(analogous, arguments); - }, - complement: function() { - return this._applyCombination(complement, arguments); - }, - monochromatic: function() { - return this._applyCombination(monochromatic, arguments); - }, - splitcomplement: function() { - return this._applyCombination(splitcomplement, arguments); - }, - triad: function() { - return this._applyCombination(triad, arguments); - }, - tetrad: function() { - return this._applyCombination(tetrad, arguments); - } -}; +function reportRange(arr, cb) { + for(var i=0; i this.mid) { + if(this.right) { + var r = this.right.queryPoint(x, cb) + if(r) { return r } } + return reportRightRange(this.rightPoints, x, cb) + } else { + return reportRange(this.leftPoints, cb) + } +} - return tinycolor(color, opts); -}; +proto.queryInterval = function(lo, hi, cb) { + if(lo < this.mid && this.left) { + var r = this.left.queryInterval(lo, hi, cb) + if(r) { return r } + } + if(hi > this.mid && this.right) { + var r = this.right.queryInterval(lo, hi, cb) + if(r) { return r } + } + if(hi < this.mid) { + return reportLeftRange(this.leftPoints, hi, cb) + } else if(lo > this.mid) { + return reportRightRange(this.rightPoints, lo, cb) + } else { + return reportRange(this.leftPoints, cb) + } +} -// Given a string or object, convert that input to RGB -// Possible string inputs: -// -// "red" -// "#f00" or "f00" -// "#ff0000" or "ff0000" -// "#ff000000" or "ff000000" -// "rgb 255 0 0" or "rgb (255, 0, 0)" -// "rgb 1.0 0 0" or "rgb (1, 0, 0)" -// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" -// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" -// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" -// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" -// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" -// -function inputToRGB(color) { +function compareNumbers(a, b) { + return a - b +} + +function compareBegin(a, b) { + var d = a[0] - b[0] + if(d) { return d } + return a[1] - b[1] +} - var rgb = { r: 0, g: 0, b: 0 }; - var a = 1; - var ok = false; - var format = false; +function compareEnd(a, b) { + var d = a[1] - b[1] + if(d) { return d } + return a[0] - b[0] +} - if (typeof color == "string") { - color = stringInputToObject(color); - } +function createIntervalTree(intervals) { + if(intervals.length === 0) { + return null + } + var pts = [] + for(var i=0; i>1] - if (color.hasOwnProperty("a")) { - a = color.a; - } + var leftIntervals = [] + var rightIntervals = [] + var centerIntervals = [] + for(var i=0; i +var tproto = IntervalTree.prototype -// `rgbToRgb` -// Handle bounds / percentage checking to conform to CSS color spec -// -// *Assumes:* r, g, b in [0, 255] or [0, 1] -// *Returns:* { r, g, b } in [0, 255] -function rgbToRgb(r, g, b){ - return { - r: bound01(r, 255) * 255, - g: bound01(g, 255) * 255, - b: bound01(b, 255) * 255 - }; +tproto.insert = function(interval) { + if(this.root) { + this.root.insert(interval) + } else { + this.root = new IntervalTreeNode(interval[0], null, null, [interval], [interval]) + } } -// `rgbToHsl` -// Converts an RGB color value to HSL. -// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] -// *Returns:* { h, s, l } in [0,1] -function rgbToHsl(r, g, b) { +tproto.remove = function(interval) { + if(this.root) { + var r = this.root.remove(interval) + if(r === EMPTY) { + this.root = null + } + return r !== NOT_FOUND + } + return false +} - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); +tproto.queryPoint = function(p, cb) { + if(this.root) { + return this.root.queryPoint(p, cb) + } +} - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, l = (max + min) / 2; +tproto.queryInterval = function(lo, hi, cb) { + if(lo <= hi && this.root) { + return this.root.queryInterval(lo, hi, cb) + } +} - if(max == min) { - h = s = 0; // achromatic +Object.defineProperty(tproto, "count", { + get: function() { + if(this.root) { + return this.root.count } - else { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } + return 0 + } +}) - h /= 6; +Object.defineProperty(tproto, "intervals", { + get: function() { + if(this.root) { + return this.root.intervals([]) } + return [] + } +}) - return { h: h, s: s, l: l }; +function createWrapper(intervals) { + if(!intervals || intervals.length === 0) { + return new IntervalTree(null) + } + return new IntervalTree(createIntervalTree(intervals)) } -// `hslToRgb` -// Converts an HSL color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] -function hslToRgb(h, s, l) { - var r, g, b; +},{"binary-search-bounds":288}],290:[function(require,module,exports){ +"use strict" - h = bound01(h, 360); - s = bound01(s, 100); - l = bound01(l, 100); +module.exports = orderSegments - function hue2rgb(p, q, t) { - if(t < 0) t += 1; - if(t > 1) t -= 1; - if(t < 1/6) return p + (q - p) * 6 * t; - if(t < 1/2) return q; - if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; +var orient = require("robust-orientation") + +function horizontalOrder(a, b) { + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + var alo = Math.min(a[0][1], a[1][1]) + var ahi = Math.max(a[0][1], a[1][1]) + var blo = Math.min(b[0][1], b[1][1]) + var bhi = Math.max(b[0][1], b[1][1]) + if(ahi < blo) { + return ahi - blo + } + if(alo > bhi) { + return alo - bhi } + return ahi - bhi + } + var al, ar + if(a[0][1] < a[1][1]) { + al = a[0] + ar = a[1] + } else { + al = a[1] + ar = a[0] + } + var d = orient(br, bl, al) + if(d) { + return d + } + d = orient(br, bl, ar) + if(d) { + return d + } + return ar - br +} - if(s === 0) { - r = g = b = l; // achromatic +function orderSegments(b, a) { + var al, ar + if(a[0][0] < a[1][0]) { + al = a[0] + ar = a[1] + } else if(a[0][0] > a[1][0]) { + al = a[1] + ar = a[0] + } else { + return horizontalOrder(a, b) + } + var bl, br + if(b[0][0] < b[1][0]) { + bl = b[0] + br = b[1] + } else if(b[0][0] > b[1][0]) { + bl = b[1] + br = b[0] + } else { + return -horizontalOrder(b, a) + } + var d1 = orient(al, ar, br) + var d2 = orient(al, ar, bl) + if(d1 < 0) { + if(d2 <= 0) { + return d1 } - else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 + } + } else if(d2) { + return d2 + } + d1 = orient(br, bl, ar) + d2 = orient(br, bl, al) + if(d1 < 0) { + if(d2 <= 0) { + return d1 + } + } else if(d1 > 0) { + if(d2 >= 0) { + return d1 } + } else if(d2) { + return d2 + } + return ar[0] - br[0] +} +},{"robust-orientation":259}],291:[function(require,module,exports){ +"use strict" - return { r: r * 255, g: g * 255, b: b * 255 }; +module.exports = createRBTree + +var RED = 0 +var BLACK = 1 + +function RBNode(color, key, value, left, right, count) { + this._color = color + this.key = key + this.value = value + this.left = left + this.right = right + this._count = count } -// `rgbToHsv` -// Converts an RGB color value to HSV -// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] -// *Returns:* { h, s, v } in [0,1] -function rgbToHsv(r, g, b) { +function cloneNode(node) { + return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) +} - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); +function repaint(color, node) { + return new RBNode(color, node.key, node.value, node.left, node.right, node._count) +} - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, v = max; +function recount(node) { + node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) +} - var d = max - min; - s = max === 0 ? 0 : d / max; +function RedBlackTree(compare, root) { + this._compare = compare + this.root = root +} - if(max == min) { - h = 0; // achromatic +var proto = RedBlackTree.prototype + +Object.defineProperty(proto, "keys", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(k) + }) + return result + } +}) + +Object.defineProperty(proto, "values", { + get: function() { + var result = [] + this.forEach(function(k,v) { + result.push(v) + }) + return result + } +}) + +//Returns the number of nodes in the tree +Object.defineProperty(proto, "length", { + get: function() { + if(this.root) { + return this.root._count } - else { - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; + return 0 + } +}) + +//Insert a new item into the tree +proto.insert = function(key, value) { + var cmp = this._compare + //Find point to insert new node at + var n = this.root + var n_stack = [] + var d_stack = [] + while(n) { + var d = cmp(key, n.key) + n_stack.push(n) + d_stack.push(d) + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + //Rebuild path to leaf node + n_stack.push(new RBNode(RED, key, value, null, null, 1)) + for(var s=n_stack.length-2; s>=0; --s) { + var n = n_stack[s] + if(d_stack[s] <= 0) { + n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) + } else { + n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) + } + } + //Rebalance tree using rotations + //console.log("start insert", key, d_stack) + for(var s=n_stack.length-1; s>1; --s) { + var p = n_stack[s-1] + var n = n_stack[s] + if(p._color === BLACK || n._color === BLACK) { + break + } + var pp = n_stack[s-2] + if(pp.left === p) { + if(p.left === n) { + var y = pp.right + if(y && y._color === RED) { + //console.log("LLr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LLb") + pp._color = RED + pp.left = p.right + p._color = BLACK + p.right = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = p + } else { + ppp.right = p + } + } + break + } + } else { + var y = pp.right + if(y && y._color === RED) { + //console.log("LRr") + p._color = BLACK + pp.right = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("LRb") + p.right = n.left + pp._color = RED + pp.left = n.right + n._color = BLACK + n.left = p + n.right = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.left === pp) { + ppp.left = n + } else { + ppp.right = n + } + } + break + } + } + } else { + if(p.right === n) { + var y = pp.left + if(y && y._color === RED) { + //console.log("RRr", y.key) + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RRb") + pp._color = RED + pp.right = p.left + p._color = BLACK + p.left = pp + n_stack[s-2] = p + n_stack[s-1] = n + recount(pp) + recount(p) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = p + } else { + ppp.left = p + } + } + break + } + } else { + var y = pp.left + if(y && y._color === RED) { + //console.log("RLr") + p._color = BLACK + pp.left = repaint(BLACK, y) + pp._color = RED + s -= 1 + } else { + //console.log("RLb") + p.left = n.right + pp._color = RED + pp.right = n.left + n._color = BLACK + n.right = p + n.left = pp + n_stack[s-2] = n + n_stack[s-1] = p + recount(pp) + recount(p) + recount(n) + if(s >= 3) { + var ppp = n_stack[s-3] + if(ppp.right === pp) { + ppp.right = n + } else { + ppp.left = n + } + } + break } - h /= 6; + } } - return { h: h, s: s, v: v }; + } + //Return new tree + n_stack[0]._color = BLACK + return new RedBlackTree(cmp, n_stack[0]) } -// `hsvToRgb` -// Converts an HSV color value to RGB. -// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] -// *Returns:* { r, g, b } in the set [0, 255] - function hsvToRgb(h, s, v) { - - h = bound01(h, 360) * 6; - s = bound01(s, 100); - v = bound01(v, 100); - - var i = math.floor(h), - f = h - i, - p = v * (1 - s), - q = v * (1 - f * s), - t = v * (1 - (1 - f) * s), - mod = i % 6, - r = [v, q, p, p, t, v][mod], - g = [t, v, v, q, p, p][mod], - b = [p, p, t, v, v, q][mod]; - return { r: r * 255, g: g * 255, b: b * 255 }; +//Visit all nodes inorder +function doVisitFull(visit, node) { + if(node.left) { + var v = doVisitFull(visit, node.left) + if(v) { return v } + } + var v = visit(node.key, node.value) + if(v) { return v } + if(node.right) { + return doVisitFull(visit, node.right) + } } -// `rgbToHex` -// Converts an RGB color to hex -// Assumes r, g, and b are contained in the set [0, 255] -// Returns a 3 or 6 character hex -function rgbToHex(r, g, b, allow3Char) { - - var hex = [ - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; - - // Return a 3 character hex if possible - if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { - return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); +//Visit half nodes in order +function doVisitHalf(lo, compare, visit, node) { + var l = compare(lo, node.key) + if(l <= 0) { + if(node.left) { + var v = doVisitHalf(lo, compare, visit, node.left) + if(v) { return v } } - - return hex.join(""); -} - -// `rgbaToHex` -// Converts an RGBA color plus alpha transparency to hex -// Assumes r, g, b and a are contained in the set [0, 255] -// Returns an 8 character hex -function rgbaToHex(r, g, b, a) { - - var hex = [ - pad2(convertDecimalToHex(a)), - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; - - return hex.join(""); -} - -// `equals` -// Can be called with any tinycolor input -tinycolor.equals = function (color1, color2) { - if (!color1 || !color2) { return false; } - return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); -}; - -tinycolor.random = function() { - return tinycolor.fromRatio({ - r: mathRandom(), - g: mathRandom(), - b: mathRandom() - }); -}; - - -// Modification Functions -// ---------------------- -// Thanks to less.js for some of the basics here -// - -function desaturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s -= amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); -} - -function saturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s += amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); + var v = visit(node.key, node.value) + if(v) { return v } + } + if(node.right) { + return doVisitHalf(lo, compare, visit, node.right) + } } -function greyscale(color) { - return tinycolor(color).desaturate(100); +//Visit all nodes within a range +function doVisit(lo, hi, compare, visit, node) { + var l = compare(lo, node.key) + var h = compare(hi, node.key) + var v + if(l <= 0) { + if(node.left) { + v = doVisit(lo, hi, compare, visit, node.left) + if(v) { return v } + } + if(h > 0) { + v = visit(node.key, node.value) + if(v) { return v } + } + } + if(h > 0 && node.right) { + return doVisit(lo, hi, compare, visit, node.right) + } } -function lighten (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l += amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); -} -function brighten(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var rgb = tinycolor(color).toRgb(); - rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); - rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); - rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); - return tinycolor(rgb); -} +proto.forEach = function rbTreeForEach(visit, lo, hi) { + if(!this.root) { + return + } + switch(arguments.length) { + case 1: + return doVisitFull(visit, this.root) + break -function darken (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l -= amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); -} + case 2: + return doVisitHalf(lo, this._compare, visit, this.root) + break -// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. -// Values outside of this range will be wrapped into this range. -function spin(color, amount) { - var hsl = tinycolor(color).toHsl(); - var hue = (mathRound(hsl.h) + amount) % 360; - hsl.h = hue < 0 ? 360 + hue : hue; - return tinycolor(hsl); + case 3: + if(this._compare(lo, hi) >= 0) { + return + } + return doVisit(lo, hi, this._compare, visit, this.root) + break + } } -// Combination Functions -// --------------------- -// Thanks to jQuery xColor for some of the ideas behind these -// +//First item in list +Object.defineProperty(proto, "begin", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.left + } + return new RedBlackTreeIterator(this, stack) + } +}) -function complement(color) { - var hsl = tinycolor(color).toHsl(); - hsl.h = (hsl.h + 180) % 360; - return tinycolor(hsl); -} +//Last item in list +Object.defineProperty(proto, "end", { + get: function() { + var stack = [] + var n = this.root + while(n) { + stack.push(n) + n = n.right + } + return new RedBlackTreeIterator(this, stack) + } +}) -function triad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) - ]; +//Find the ith item in the tree +proto.at = function(idx) { + if(idx < 0) { + return new RedBlackTreeIterator(this, []) + } + var n = this.root + var stack = [] + while(true) { + stack.push(n) + if(n.left) { + if(idx < n.left._count) { + n = n.left + continue + } + idx -= n.left._count + } + if(!idx) { + return new RedBlackTreeIterator(this, stack) + } + idx -= 1 + if(n.right) { + if(idx >= n.right._count) { + break + } + n = n.right + } else { + break + } + } + return new RedBlackTreeIterator(this, []) } -function tetrad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) - ]; +proto.ge = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d <= 0) { + last_ptr = stack.length + } + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) } -function splitcomplement(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), - tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) - ]; +proto.gt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d < 0) { + last_ptr = stack.length + } + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) } -function analogous(color, results, slices) { - results = results || 6; - slices = slices || 30; - - var hsl = tinycolor(color).toHsl(); - var part = 360 / slices; - var ret = [tinycolor(color)]; - - for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { - hsl.h = (hsl.h + part) % 360; - ret.push(tinycolor(hsl)); +proto.lt = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d > 0) { + last_ptr = stack.length } - return ret; + if(d <= 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) } -function monochromatic(color, results) { - results = results || 6; - var hsv = tinycolor(color).toHsv(); - var h = hsv.h, s = hsv.s, v = hsv.v; - var ret = []; - var modification = 1 / results; - - while (results--) { - ret.push(tinycolor({ h: h, s: s, v: v})); - v = (v + modification) % 1; +proto.le = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + var last_ptr = 0 + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d >= 0) { + last_ptr = stack.length } - - return ret; + if(d < 0) { + n = n.left + } else { + n = n.right + } + } + stack.length = last_ptr + return new RedBlackTreeIterator(this, stack) } -// Utility Functions -// --------------------- - -tinycolor.mix = function(color1, color2, amount) { - amount = (amount === 0) ? 0 : (amount || 50); - - var rgb1 = tinycolor(color1).toRgb(); - var rgb2 = tinycolor(color2).toRgb(); - - var p = amount / 100; - var w = p * 2 - 1; - var a = rgb2.a - rgb1.a; - - var w1; - - if (w * a == -1) { - w1 = w; +//Finds the item with key if it exists +proto.find = function(key) { + var cmp = this._compare + var n = this.root + var stack = [] + while(n) { + var d = cmp(key, n.key) + stack.push(n) + if(d === 0) { + return new RedBlackTreeIterator(this, stack) + } + if(d <= 0) { + n = n.left } else { - w1 = (w + a) / (1 + w * a); + n = n.right } + } + return new RedBlackTreeIterator(this, []) +} - w1 = (w1 + 1) / 2; - - var w2 = 1 - w1; - - var rgba = { - r: rgb2.r * w1 + rgb1.r * w2, - g: rgb2.g * w1 + rgb1.g * w2, - b: rgb2.b * w1 + rgb1.b * w2, - a: rgb2.a * p + rgb1.a * (1 - p) - }; - - return tinycolor(rgba); -}; - - -// Readability Functions -// --------------------- -// false -// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false -tinycolor.isReadable = function(color1, color2, wcag2) { - var readability = tinycolor.readability(color1, color2); - var wcag2Parms, out; - - out = false; +//Removes item with key from tree +proto.remove = function(key) { + var iter = this.find(key) + if(iter) { + return iter.remove() + } + return this +} - wcag2Parms = validateWCAG2Parms(wcag2); - switch (wcag2Parms.level + wcag2Parms.size) { - case "AAsmall": - case "AAAlarge": - out = readability >= 4.5; - break; - case "AAlarge": - out = readability >= 3; - break; - case "AAAsmall": - out = readability >= 7; - break; +//Returns the item at `key` +proto.get = function(key) { + var cmp = this._compare + var n = this.root + while(n) { + var d = cmp(key, n.key) + if(d === 0) { + return n.value } - return out; - -}; - -// `mostReadable` -// Given a base color and a list of possible foreground or background -// colors for that base, returns the most readable color. -// Optionally returns Black or White if the most readable color is unreadable. -// *Example* -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" -// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" -// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" -tinycolor.mostReadable = function(baseColor, colorList, args) { - var bestColor = null; - var bestScore = 0; - var readability; - var includeFallbackColors, level, size ; - args = args || {}; - includeFallbackColors = args.includeFallbackColors ; - level = args.level; - size = args.size; - - for (var i= 0; i < colorList.length ; i++) { - readability = tinycolor.readability(baseColor, colorList[i]); - if (readability > bestScore) { - bestScore = readability; - bestColor = tinycolor(colorList[i]); - } + if(d <= 0) { + n = n.left + } else { + n = n.right } + } + return +} - if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { - return bestColor; - } - else { - args.includeFallbackColors=false; - return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); - } -}; +//Iterator for red black tree +function RedBlackTreeIterator(tree, stack) { + this.tree = tree + this._stack = stack +} +var iproto = RedBlackTreeIterator.prototype -// Big List of Colors -// ------------------ -// -var names = tinycolor.names = { - aliceblue: "f0f8ff", - antiquewhite: "faebd7", - aqua: "0ff", - aquamarine: "7fffd4", - azure: "f0ffff", - beige: "f5f5dc", - bisque: "ffe4c4", - black: "000", - blanchedalmond: "ffebcd", - blue: "00f", - blueviolet: "8a2be2", - brown: "a52a2a", - burlywood: "deb887", - burntsienna: "ea7e5d", - cadetblue: "5f9ea0", - chartreuse: "7fff00", - chocolate: "d2691e", - coral: "ff7f50", - cornflowerblue: "6495ed", - cornsilk: "fff8dc", - crimson: "dc143c", - cyan: "0ff", - darkblue: "00008b", - darkcyan: "008b8b", - darkgoldenrod: "b8860b", - darkgray: "a9a9a9", - darkgreen: "006400", - darkgrey: "a9a9a9", - darkkhaki: "bdb76b", - darkmagenta: "8b008b", - darkolivegreen: "556b2f", - darkorange: "ff8c00", - darkorchid: "9932cc", - darkred: "8b0000", - darksalmon: "e9967a", - darkseagreen: "8fbc8f", - darkslateblue: "483d8b", - darkslategray: "2f4f4f", - darkslategrey: "2f4f4f", - darkturquoise: "00ced1", - darkviolet: "9400d3", - deeppink: "ff1493", - deepskyblue: "00bfff", - dimgray: "696969", - dimgrey: "696969", - dodgerblue: "1e90ff", - firebrick: "b22222", - floralwhite: "fffaf0", - forestgreen: "228b22", - fuchsia: "f0f", - gainsboro: "dcdcdc", - ghostwhite: "f8f8ff", - gold: "ffd700", - goldenrod: "daa520", - gray: "808080", - green: "008000", - greenyellow: "adff2f", - grey: "808080", - honeydew: "f0fff0", - hotpink: "ff69b4", - indianred: "cd5c5c", - indigo: "4b0082", - ivory: "fffff0", - khaki: "f0e68c", - lavender: "e6e6fa", - lavenderblush: "fff0f5", - lawngreen: "7cfc00", - lemonchiffon: "fffacd", - lightblue: "add8e6", - lightcoral: "f08080", - lightcyan: "e0ffff", - lightgoldenrodyellow: "fafad2", - lightgray: "d3d3d3", - lightgreen: "90ee90", - lightgrey: "d3d3d3", - lightpink: "ffb6c1", - lightsalmon: "ffa07a", - lightseagreen: "20b2aa", - lightskyblue: "87cefa", - lightslategray: "789", - lightslategrey: "789", - lightsteelblue: "b0c4de", - lightyellow: "ffffe0", - lime: "0f0", - limegreen: "32cd32", - linen: "faf0e6", - magenta: "f0f", - maroon: "800000", - mediumaquamarine: "66cdaa", - mediumblue: "0000cd", - mediumorchid: "ba55d3", - mediumpurple: "9370db", - mediumseagreen: "3cb371", - mediumslateblue: "7b68ee", - mediumspringgreen: "00fa9a", - mediumturquoise: "48d1cc", - mediumvioletred: "c71585", - midnightblue: "191970", - mintcream: "f5fffa", - mistyrose: "ffe4e1", - moccasin: "ffe4b5", - navajowhite: "ffdead", - navy: "000080", - oldlace: "fdf5e6", - olive: "808000", - olivedrab: "6b8e23", - orange: "ffa500", - orangered: "ff4500", - orchid: "da70d6", - palegoldenrod: "eee8aa", - palegreen: "98fb98", - paleturquoise: "afeeee", - palevioletred: "db7093", - papayawhip: "ffefd5", - peachpuff: "ffdab9", - peru: "cd853f", - pink: "ffc0cb", - plum: "dda0dd", - powderblue: "b0e0e6", - purple: "800080", - rebeccapurple: "663399", - red: "f00", - rosybrown: "bc8f8f", - royalblue: "4169e1", - saddlebrown: "8b4513", - salmon: "fa8072", - sandybrown: "f4a460", - seagreen: "2e8b57", - seashell: "fff5ee", - sienna: "a0522d", - silver: "c0c0c0", - skyblue: "87ceeb", - slateblue: "6a5acd", - slategray: "708090", - slategrey: "708090", - snow: "fffafa", - springgreen: "00ff7f", - steelblue: "4682b4", - tan: "d2b48c", - teal: "008080", - thistle: "d8bfd8", - tomato: "ff6347", - turquoise: "40e0d0", - violet: "ee82ee", - wheat: "f5deb3", - white: "fff", - whitesmoke: "f5f5f5", - yellow: "ff0", - yellowgreen: "9acd32" -}; +//Test if iterator is valid +Object.defineProperty(iproto, "valid", { + get: function() { + return this._stack.length > 0 + } +}) -// Make it easy to access colors via `hexNames[hex]` -var hexNames = tinycolor.hexNames = flip(names); +//Node of the iterator +Object.defineProperty(iproto, "node", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1] + } + return null + }, + enumerable: true +}) +//Makes a copy of an iterator +iproto.clone = function() { + return new RedBlackTreeIterator(this.tree, this._stack.slice()) +} -// Utilities -// --------- +//Swaps two nodes +function swapNode(n, v) { + n.key = v.key + n.value = v.value + n.left = v.left + n.right = v.right + n._color = v._color + n._count = v._count +} -// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` -function flip(o) { - var flipped = { }; - for (var i in o) { - if (o.hasOwnProperty(i)) { - flipped[o[i]] = i; +//Fix up a double black node in a tree +function fixDoubleBlack(stack) { + var n, p, s, z + for(var i=stack.length-1; i>=0; --i) { + n = stack[i] + if(i === 0) { + n._color = BLACK + return + } + //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) + p = stack[i-1] + if(p.left === n) { + //console.log("left child") + s = p.right + if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.right = cloneNode(s) + z = s.right = cloneNode(s.right) + p.right = s.left + s.left = p + s.right = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + return + } else if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red") + s = p.right = cloneNode(s) + z = s.left = cloneNode(s.left) + p.right = z.left + s.left = z.right + z.left = p + z.right = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = z + } else { + pp.right = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent", p.right.value) + p._color = BLACK + p.right = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent", p.right.value) + p.right = repaint(RED, s) + continue + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.right = s.left + s.left = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.left === p) { + pp.left = s + } else { + pp.right = s + } + } + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) + } + i = i+2 + } + } else { + //console.log("right child") + s = p.left + if(s.left && s.left._color === RED) { + //console.log("case 1: left sibling child red", p.value, p._color) + s = p.left = cloneNode(s) + z = s.left = cloneNode(s.left) + p.left = s.right + s.right = p + s.left = z + s._color = p._color + n._color = BLACK + p._color = BLACK + z._color = BLACK + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + return + } else if(s.right && s.right._color === RED) { + //console.log("case 1: right sibling child red") + s = p.left = cloneNode(s) + z = s.right = cloneNode(s.right) + p.left = z.right + s.right = z.left + z.right = p + z.left = s + z._color = p._color + p._color = BLACK + s._color = BLACK + n._color = BLACK + recount(p) + recount(s) + recount(z) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = z + } else { + pp.left = z + } + } + stack[i-1] = z + return + } + if(s._color === BLACK) { + if(p._color === RED) { + //console.log("case 2: black sibling, red parent") + p._color = BLACK + p.left = repaint(RED, s) + return + } else { + //console.log("case 2: black sibling, black parent") + p.left = repaint(RED, s) + continue + } + } else { + //console.log("case 3: red sibling") + s = cloneNode(s) + p.left = s.right + s.right = p + s._color = p._color + p._color = RED + recount(p) + recount(s) + if(i > 1) { + var pp = stack[i-2] + if(pp.right === p) { + pp.right = s + } else { + pp.left = s + } + } + stack[i-1] = s + stack[i] = p + if(i+1 < stack.length) { + stack[i+1] = n + } else { + stack.push(n) } + i = i+2 + } } - return flipped; + } } -// Return a valid alpha value [0,1] with all invalid values being set to 1 -function boundAlpha(a) { - a = parseFloat(a); - - if (isNaN(a) || a < 0 || a > 1) { - a = 1; +//Removes item at iterator from tree +iproto.remove = function() { + var stack = this._stack + if(stack.length === 0) { + return this.tree + } + //First copy path to node + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + var n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) } + } - return a; -} + //Get node + n = cstack[cstack.length-1] + //console.log("start remove: ", n.value) -// Take input from [0, n] and return it as [0, 1] -function bound01(n, max) { - if (isOnePointZero(n)) { n = "100%"; } + //If not leaf, then swap with previous node + if(n.left && n.right) { + //console.log("moving to leaf") - var processPercent = isPercentage(n); - n = mathMin(max, mathMax(0, parseFloat(n))); + //First walk to previous leaf + var split = cstack.length + n = n.left + while(n.right) { + cstack.push(n) + n = n.right + } + //Copy path to leaf + var v = cstack[split-1] + cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) + cstack[split-1].key = n.key + cstack[split-1].value = n.value - // Automatically convert percentage into number - if (processPercent) { - n = parseInt(n * max, 10) / 100; + //Fix up stack + for(var i=cstack.length-2; i>=split; --i) { + n = cstack[i] + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + cstack[split-1].left = cstack[split] + } + //console.log("stack=", cstack.map(function(v) { return v.value })) + + //Remove leaf node + n = cstack[cstack.length-1] + if(n._color === RED) { + //Easy case: removing red leaf + //console.log("RED leaf") + var p = cstack[cstack.length-2] + if(p.left === n) { + p.left = null + } else if(p.right === n) { + p.right = null + } + cstack.pop() + for(var i=0; i 0) { + return this._stack[this._stack.length-1].key } + return + }, + enumerable: true +}) - // Handle floating point rounding errors - if ((math.abs(n - max) < 0.000001)) { - return 1; +//Returns value +Object.defineProperty(iproto, "value", { + get: function() { + if(this._stack.length > 0) { + return this._stack[this._stack.length-1].value } + return + }, + enumerable: true +}) - // Convert into [0, 1] range if it isn't already - return (n % max) / parseFloat(max); -} -// Force a number between 0 and 1 -function clamp01(val) { - return mathMin(1, mathMax(0, val)); -} +//Returns the position of this iterator in the sorted list +Object.defineProperty(iproto, "index", { + get: function() { + var idx = 0 + var stack = this._stack + if(stack.length === 0) { + var r = this.tree.root + if(r) { + return r._count + } + return 0 + } else if(stack[stack.length-1].left) { + idx = stack[stack.length-1].left._count + } + for(var s=stack.length-2; s>=0; --s) { + if(stack[s+1] === stack[s].right) { + ++idx + if(stack[s].left) { + idx += stack[s].left._count + } + } + } + return idx + }, + enumerable: true +}) -// Parse a base-16 hex value into a base-10 integer -function parseIntFromHex(val) { - return parseInt(val, 16); +//Advances iterator to next element in list +iproto.next = function() { + var stack = this._stack + if(stack.length === 0) { + return + } + var n = stack[stack.length-1] + if(n.right) { + n = n.right + while(n) { + stack.push(n) + n = n.left + } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].right === n) { + n = stack[stack.length-1] + stack.pop() + } + } } -// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 -// -function isOnePointZero(n) { - return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; -} +//Checks if iterator is at end of tree +Object.defineProperty(iproto, "hasNext", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].right) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].left === stack[s]) { + return true + } + } + return false + } +}) -// Check to see if string passed in is a percentage -function isPercentage(n) { - return typeof n === "string" && n.indexOf('%') != -1; +//Update value +iproto.update = function(value) { + var stack = this._stack + if(stack.length === 0) { + throw new Error("Can't update empty node!") + } + var cstack = new Array(stack.length) + var n = stack[stack.length-1] + cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) + for(var i=stack.length-2; i>=0; --i) { + n = stack[i] + if(n.left === stack[i+1]) { + cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) + } else { + cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) + } + } + return new RedBlackTree(this.tree._compare, cstack[0]) } -// Force a hex value to have 2 characters -function pad2(c) { - return c.length == 1 ? '0' + c : '' + c; +//Moves iterator backward one element +iproto.prev = function() { + var stack = this._stack + if(stack.length === 0) { + return + } + var n = stack[stack.length-1] + if(n.left) { + n = n.left + while(n) { + stack.push(n) + n = n.right + } + } else { + stack.pop() + while(stack.length > 0 && stack[stack.length-1].left === n) { + n = stack[stack.length-1] + stack.pop() + } + } } -// Replace a decimal with it's percentage value -function convertToPercentage(n) { - if (n <= 1) { - n = (n * 100) + "%"; +//Checks if iterator is at start of tree +Object.defineProperty(iproto, "hasPrev", { + get: function() { + var stack = this._stack + if(stack.length === 0) { + return false + } + if(stack[stack.length-1].left) { + return true + } + for(var s=stack.length-1; s>0; --s) { + if(stack[s-1].right === stack[s]) { + return true + } } + return false + } +}) - return n; +//Default comparison function +function defaultCompare(a, b) { + if(a < b) { + return -1 + } + if(a > b) { + return 1 + } + return 0 } -// Converts a decimal to a hex value -function convertDecimalToHex(d) { - return Math.round(parseFloat(d) * 255).toString(16); -} -// Converts a hex value to a decimal -function convertHexToDecimal(h) { - return (parseIntFromHex(h) / 255); +//Build a tree +function createRBTree(compare) { + return new RedBlackTree(compare || defaultCompare, null) } +},{}],292:[function(require,module,exports){ +"use strict" -var matchers = (function() { - - // - var CSS_INTEGER = "[-\\+]?\\d+%?"; - - // - var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; +module.exports = createSlabDecomposition - // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. - var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; +var bounds = require("binary-search-bounds") +var createRBTree = require("functional-red-black-tree") +var orient = require("robust-orientation") +var orderSegments = require("./lib/order-segments") - // Actual matching. - // Parentheses and commas are optional, but not required. - // Whitespace can take the place of commas or opening paren - var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; +function SlabDecomposition(slabs, coordinates, horizontal) { + this.slabs = slabs + this.coordinates = coordinates + this.horizontal = horizontal +} - return { - rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), - rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), - hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), - hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), - hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), - hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), - hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, - hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ - }; -})(); +var proto = SlabDecomposition.prototype -// `stringInputToObject` -// Permissive string parsing. Take in a number of formats, and output an object -// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` -function stringInputToObject(color) { +function compareHorizontal(e, y) { + return e.y - y +} - color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); - var named = false; - if (names[color]) { - color = names[color]; - named = true; +function searchBucket(root, p) { + var lastNode = null + while(root) { + var seg = root.key + var l, r + if(seg[0][0] < seg[1][0]) { + l = seg[0] + r = seg[1] + } else { + l = seg[1] + r = seg[0] } - else if (color == 'transparent') { - return { r: 0, g: 0, b: 0, a: 0, format: "name" }; + var o = orient(l, r, p) + if(o < 0) { + root = root.left + } else if(o > 0) { + if(p[0] !== seg[1][0]) { + lastNode = root + root = root.right + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } + } else { + if(p[0] !== seg[1][0]) { + return root + } else { + var val = searchBucket(root.right, p) + if(val) { + return val + } + root = root.left + } } + } + return lastNode +} - // Try to match string input using regular expressions. - // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] - // Just return an object and let the conversion functions handle that. - // This way the result will be the same whether the tinycolor is initialized with string or object. - var match; - if ((match = matchers.rgb.exec(color))) { - return { r: match[1], g: match[2], b: match[3] }; - } - if ((match = matchers.rgba.exec(color))) { - return { r: match[1], g: match[2], b: match[3], a: match[4] }; - } - if ((match = matchers.hsl.exec(color))) { - return { h: match[1], s: match[2], l: match[3] }; +proto.castUp = function(p) { + var bucket = bounds.le(this.coordinates, p[0]) + if(bucket < 0) { + return -1 + } + var root = this.slabs[bucket] + var hitNode = searchBucket(this.slabs[bucket], p) + var lastHit = -1 + if(hitNode) { + lastHit = hitNode.value + } + //Edge case: need to handle horizontal segments (sucks) + if(this.coordinates[bucket] === p[0]) { + var lastSegment = null + if(hitNode) { + lastSegment = hitNode.key } - if ((match = matchers.hsla.exec(color))) { - return { h: match[1], s: match[2], l: match[3], a: match[4] }; + if(bucket > 0) { + var otherHitNode = searchBucket(this.slabs[bucket-1], p) + if(otherHitNode) { + if(lastSegment) { + if(orderSegments(otherHitNode.key, lastSegment) > 0) { + lastSegment = otherHitNode.key + lastHit = otherHitNode.value + } + } else { + lastHit = otherHitNode.value + lastSegment = otherHitNode.key + } + } } - if ((match = matchers.hsv.exec(color))) { - return { h: match[1], s: match[2], v: match[3] }; + var horiz = this.horizontal[bucket] + if(horiz.length > 0) { + var hbucket = bounds.ge(horiz, p[1], compareHorizontal) + if(hbucket < horiz.length) { + var e = horiz[hbucket] + if(p[1] === e.y) { + if(e.closed) { + return e.index + } else { + while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) { + hbucket = hbucket+1 + e = horiz[hbucket] + if(e.closed) { + return e.index + } + } + if(e.y === p[1] && !e.start) { + hbucket = hbucket+1 + if(hbucket >= horiz.length) { + return lastHit + } + e = horiz[hbucket] + } + } + } + //Check if e is above/below last segment + if(e.start) { + if(lastSegment) { + var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y]) + if(lastSegment[0][0] > lastSegment[1][0]) { + o = -o + } + if(o > 0) { + lastHit = e.index + } + } else { + lastHit = e.index + } + } else if(e.y !== p[1]) { + lastHit = e.index + } + } } - if ((match = matchers.hsva.exec(color))) { - return { h: match[1], s: match[2], v: match[3], a: match[4] }; + } + return lastHit +} + +function IntervalSegment(y, index, start, closed) { + this.y = y + this.index = index + this.start = start + this.closed = closed +} + +function Event(x, segment, create, index) { + this.x = x + this.segment = segment + this.create = create + this.index = index +} + + +function createSlabDecomposition(segments) { + var numSegments = segments.length + var numEvents = 2 * numSegments + var events = new Array(numEvents) + for(var i=0; i 0 && coordinates[bucket] === p[0]) { + root = slabs[bucket-1] + } else { + return 1 + } } - return {"level":level, "size":size}; + var lastOrientation = 1 + while(root) { + var s = root.key + var o = orient(p, s[0], s[1]) + if(s[0][0] < s[1][0]) { + if(o < 0) { + root = root.left + } else if(o > 0) { + lastOrientation = -1 + root = root.right + } else { + return 0 + } + } else { + if(o > 0) { + root = root.left + } else if(o < 0) { + lastOrientation = 1 + root = root.right + } else { + return 0 + } + } + } + return lastOrientation + } } -// Node: Export function -if (typeof module !== "undefined" && module.exports) { - module.exports = tinycolor; -} -// AMD/requirejs: Define the module -else if (typeof define === 'function' && define.amd) { - define(function () {return tinycolor;}); -} -// Browser: Expose to window -else { - window.tinycolor = tinycolor; +function classifyEmpty(p) { + return 1 } -})(); +function createClassifyVertical(testVertical) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return 1 + } +} -},{}],1043:[function(require,module,exports){ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.topojson = global.topojson || {}))); -}(this, function (exports) { 'use strict'; +function createClassifyPointDegen(testVertical, testNormal) { + return function classify(p) { + if(testVertical(p[0], p[1])) { + return 0 + } + return testNormal(p) + } +} - function noop() {} +function preprocessPolygon(loops) { + //Compute number of loops + var numLoops = loops.length - function transformAbsolute(transform) { - if (!transform) return noop; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(point, i) { - if (!i) x0 = y0 = 0; - point[0] = (x0 += point[0]) * kx + dx; - point[1] = (y0 += point[1]) * ky + dy; - }; + //Unpack segments + var segments = [] + var vsegments = [] + var ptr = 0 + for(var i=0; i>> 1; - if (a[mid] < x) lo = mid + 1; - else hi = mid; - } - return lo; + if(vsegments.length === 0) { + return testSlab + } else { + return createClassifyPointDegen( + buildVerticalIndex(vsegments), + testSlab) } +} +},{"binary-search-bounds":288,"interval-tree-1d":289,"robust-orientation":259,"slab-decomposition":292}],294:[function(require,module,exports){ +'use strict' - function feature(topology, o) { - return o.type === "GeometryCollection" ? { - type: "FeatureCollection", - features: o.geometries.map(function(o) { return feature$1(topology, o); }) - } : feature$1(topology, o); +module.exports = planarGraphToPolyline + +var e2a = require('edges-to-adjacency-list') +var planarDual = require('planar-dual') +var preprocessPolygon = require('point-in-big-polygon') +var twoProduct = require('two-product') +var robustSum = require('robust-sum') +var uniq = require('uniq') +var trimLeaves = require('./lib/trim-leaves') + +function makeArray(length, fill) { + var result = new Array(length) + for(var i=0; i 0 } - function stitchArcs(topology, arcs) { - var stitchedArcs = {}, - fragmentByStart = {}, - fragmentByEnd = {}, - fragments = [], - emptyIndex = -1; + //Extract all clockwise faces + faces = faces.filter(ccw) - // Stitch empty arcs first, since they may be subsumed by other arcs. - arcs.forEach(function(i, j) { - var arc = topology.arcs[i < 0 ? ~i : i], t; - if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { - t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; + //Detect which loops are contained in one another to handle parent-of relation + var numFaces = faces.length + var parent = new Array(numFaces) + var containment = new Array(numFaces) + for(var i=0; i 0) { + var top = toVisit.pop() + var nbhd = fadj[top] + uniq(nbhd, function(a,b) { + return a-b + }) + var nnbhr = nbhd.length + var p = parity[top] + var polyline + if(p === 0) { + var c = faces[top] + polyline = [c] + } + for(var i=0; i= 0) { + continue + } + parity[f] = p^1 + toVisit.push(f) + if(p === 0) { + var c = faces[f] + if(!sharedBoundary(c)) { + c.reverse() + polyline.push(c) + } } } + if(p === 0) { + result.push(polyline) + } + } - flush(fragmentByEnd, fragmentByStart); - flush(fragmentByStart, fragmentByEnd); - arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); + return result +} +},{"./lib/trim-leaves":282,"edges-to-adjacency-list":283,"planar-dual":284,"point-in-big-polygon":293,"robust-sum":262,"two-product":276,"uniq":279}],295:[function(require,module,exports){ +arguments[4][50][0].apply(exports,arguments) +},{"dup":50}],296:[function(require,module,exports){ +"use strict"; "use restrict"; - return fragments; +module.exports = UnionFind; + +function UnionFind(count) { + this.roots = new Array(count); + this.ranks = new Array(count); + + for(var i=0; i 1) { - var geomsByArc = [], - geom; +function errorWeight(base, a, b) { + var area = Math.abs(orient(base, a, b)) + var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2)) + return area / perim +} - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs) { arcs.forEach(polygon); } - }; +function simplifyPolygon(cells, positions, minArea) { - geometry(o); + var n = positions.length + var nc = cells.length + var inv = new Array(n) + var outv = new Array(n) + var weights = new Array(n) + var dead = new Array(n) + + //Initialize tables + for(var i=0; i> 1 } + return (i >> 1) - 1 + } - polygons.forEach(function(polygon) { - if (!polygon._) { - var component = [], - neighbors = [polygon]; - polygon._ = 1; - components.push(component); - while (polygon = neighbors.pop()) { - component.push(polygon); - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) { - if (!polygon._) { - polygon._ = 1; - neighbors.push(polygon); - } - }); - }); - }); + //Bubble element i down the heap + function heapDown(i) { + var w = heapWeight(i) + while(true) { + var tw = w + var left = 2*i + 1 + var right = 2*(i + 1) + var next = i + if(left < heapCount) { + var lw = heapWeight(left) + if(lw < tw) { + next = left + tw = lw } } - }); - - polygons.forEach(function(polygon) { - delete polygon._; - }); - - return { - type: "MultiPolygon", - arcs: components.map(function(polygons) { - var arcs = [], n; - - // Extract the exterior (unique) arcs. - polygons.forEach(function(polygon) { - polygon.forEach(function(ring$$) { - ring$$.forEach(function(arc) { - if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) { - arcs.push(arc); - } - }); - }); - }); - - // Stitch the arcs into one or more rings. - arcs = stitchArcs(topology, arcs); - - // If more than one ring is returned, - // at most one of these rings can be the exterior; - // choose the one with the greatest absolute area. - if ((n = arcs.length) > 1) { - for (var i = 1, k = area(arcs[0]), ki, t; i < n; ++i) { - if ((ki = area(arcs[i])) > k) { - t = arcs[0], arcs[0] = arcs[i], arcs[i] = t, k = ki; - } - } + if(right < heapCount) { + var rw = heapWeight(right) + if(rw < tw) { + next = right } - - return arcs; - }) - }; + } + if(next === i) { + return i + } + heapSwap(i, next) + i = next + } } - function neighbors(objects) { - var indexesByArc = {}, // arc index -> array of object indexes - neighbors = objects.map(function() { return []; }); - - function line(arcs, i) { - arcs.forEach(function(a) { - if (a < 0) a = ~a; - var o = indexesByArc[a]; - if (o) o.push(i); - else indexesByArc[a] = [i]; - }); + //Bubbles element i up the heap + function heapUp(i) { + var w = heapWeight(i) + while(i > 0) { + var parent = heapParent(i) + if(parent >= 0) { + var pw = heapWeight(parent) + if(w < pw) { + heapSwap(i, parent) + i = parent + continue + } + } + return i } + } - function polygon(arcs, i) { - arcs.forEach(function(arc) { line(arc, i); }); + //Pop minimum element + function heapPop() { + if(heapCount > 0) { + var head = heap[0] + heapSwap(0, heapCount-1) + heapCount -= 1 + heapDown(0) + return head } + return -1 + } - function geometry(o, i) { - if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); - else if (o.type in geometryType) geometryType[o.type](o.arcs, i); + //Update heap item i + function heapUpdate(i, w) { + var a = heap[i] + if(weights[a] === w) { + return i } + weights[a] = -Infinity + heapUp(i) + heapPop() + weights[a] = w + heapCount += 1 + return heapUp(heapCount-1) + } - var geometryType = { - LineString: line, - MultiLineString: polygon, - Polygon: polygon, - MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } - }; - - objects.forEach(geometry); - - for (var i in indexesByArc) { - for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { - for (var k = j + 1; k < m; ++k) { - var ij = indexes[j], ik = indexes[k], n; - if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); - if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); - } - } + //Kills a vertex (assume vertex already removed from heap) + function kill(i) { + if(dead[i]) { + return + } + //Kill vertex + dead[i] = true + //Fixup topology + var s = inv[i] + var t = outv[i] + if(inv[t] >= 0) { + inv[t] = s + } + if(outv[s] >= 0) { + outv[s] = t } - return neighbors; + //Update weights on s and t + if(index[s] >= 0) { + heapUpdate(index[s], computeWeight(s)) + } + if(index[t] >= 0) { + heapUpdate(index[t], computeWeight(t)) + } } - function compareArea(a, b) { - return a[1][2] - b[1][2]; + //Initialize weights and heap + var heap = [] + var index = new Array(n) + for(var i=0; i 0) object = array[size], down(array[object._ = 0] = object, 0); - return removed; - }; - - heap.remove = function(removed) { - var i = removed._, object; - if (array[i] !== removed) return; // invalid request - if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i); - return i; - }; - - function up(object, i) { - while (i > 0) { - var j = ((i + 1) >> 1) - 1, - parent = array[j]; - if (compareArea(object, parent) >= 0) break; - array[parent._ = i] = parent; - array[object._ = i = j] = object; - } + var heapCount = heap.length + for(var i=heapCount>>1; i>=0; --i) { + heapDown(i) + } + + //Kill vertices + while(true) { + var hmin = heapPop() + if((hmin < 0) || (weights[hmin] > minArea)) { + break } + kill(hmin) + } - function down(object, i) { - while (true) { - var r = (i + 1) << 1, - l = r - 1, - j = i, - child = array[j]; - if (l < size && compareArea(array[l], child) < 0) child = array[j = l]; - if (r < size && compareArea(array[r], child) < 0) child = array[j = r]; - if (j === i) break; - array[child._ = i] = child; - array[object._ = i = j] = object; - } + //Build collapsed vertex table + var npositions = [] + for(var i=0; i= 0 && tout >= 0 && tin !== tout) { + var cin = index[tin] + var cout = index[tout] + if(cin !== cout) { + ncells.push([ cin, cout ]) + } + } + }) - exports.version = version; - exports.mesh = mesh; - exports.meshArcs = meshArcs; - exports.merge = merge; - exports.mergeArcs = mergeArcs; - exports.feature = feature; - exports.neighbors = neighbors; - exports.presimplify = presimplify; + //Normalize result + sc.unique(sc.normalize(ncells)) -})); -},{}],1044:[function(require,module,exports){ + //Return final list of cells + return { + positions: npositions, + edges: ncells + } +} +},{"robust-orientation":259,"simplicial-complex":297}],299:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52313,7 +50296,7 @@ module.exports = [ } ]; -},{}],1045:[function(require,module,exports){ +},{}],300:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -52486,7 +50469,7 @@ module.exports = { } }; -},{"../../lib/extend":1122,"../../plots/cartesian/constants":1155,"../../plots/font_attributes":1168,"./arrow_paths":1044}],1046:[function(require,module,exports){ +},{"../../lib/extend":376,"../../plots/cartesian/constants":408,"../../plots/font_attributes":421,"./arrow_paths":299}],301:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53415,7 +51398,7 @@ function lineIntersect(x1, y1, x2, y2, x3, y3, x4, y4) { return {x: x1 + a * t, y: y1 + d * t}; } -},{"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../dragelement":1069,"../drawing":1071,"./arrow_paths":1044,"./attributes":1045,"d3":82,"fast-isnumeric":90}],1047:[function(require,module,exports){ +},{"../../lib":381,"../../lib/setcursor":389,"../../lib/svg_text_utils":393,"../../plotly":400,"../../plots/cartesian/axes":403,"../color":303,"../dragelement":323,"../drawing":325,"./arrow_paths":299,"./attributes":300,"d3":113,"fast-isnumeric":117}],302:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53453,7 +51436,7 @@ exports.background = '#fff'; // gives back exactly lightLine if the other colors are defaults. exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4); -},{}],1048:[function(require,module,exports){ +},{}],303:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53597,7 +51580,7 @@ function cleanOne(val) { return 'rgb(' + rgbStr + ')'; } -},{"./attributes":1047,"fast-isnumeric":90,"tinycolor2":1042}],1049:[function(require,module,exports){ +},{"./attributes":302,"fast-isnumeric":117,"tinycolor2":274}],304:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53752,7 +51735,7 @@ module.exports = { } }; -},{"../../lib/extend":1122,"../../plots/cartesian/layout_attributes":1159,"../../plots/font_attributes":1168}],1050:[function(require,module,exports){ +},{"../../lib/extend":376,"../../plots/cartesian/layout_attributes":412,"../../plots/font_attributes":421}],305:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -53819,7 +51802,7 @@ module.exports = function colorbarDefaults(containerIn, containerOut, layout) { coerce('titleside'); }; -},{"../../lib":1127,"../../plots/cartesian/tick_label_defaults":1165,"../../plots/cartesian/tick_mark_defaults":1166,"../../plots/cartesian/tick_value_defaults":1167,"./attributes":1049}],1051:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/tick_label_defaults":418,"../../plots/cartesian/tick_mark_defaults":419,"../../plots/cartesian/tick_value_defaults":420,"./attributes":304}],306:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54449,7 +52432,7 @@ module.exports = function draw(gd, id) { return component; }; -},{"../../lib":1127,"../../lib/extend":1122,"../../lib/setcursor":1136,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../../plots/cartesian/axis_defaults":1151,"../../plots/cartesian/layout_attributes":1159,"../../plots/cartesian/position_defaults":1162,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"../titles":1111,"./attributes":1049,"d3":82,"tinycolor2":1042}],1052:[function(require,module,exports){ +},{"../../lib":381,"../../lib/extend":376,"../../lib/setcursor":389,"../../plotly":400,"../../plots/cartesian/axes":403,"../../plots/cartesian/axis_defaults":404,"../../plots/cartesian/layout_attributes":412,"../../plots/cartesian/position_defaults":415,"../../plots/plots":452,"../color":303,"../dragelement":323,"../drawing":325,"../titles":365,"./attributes":304,"d3":113,"tinycolor2":274}],307:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54469,7 +52452,7 @@ module.exports = function hasColorbar(container) { ); }; -},{}],1053:[function(require,module,exports){ +},{}],308:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54490,7 +52473,7 @@ exports.draw = require('./draw'); exports.hasColorbar = require('./has_colorbar'); -},{"./attributes":1049,"./defaults":1050,"./draw":1051,"./has_colorbar":1052}],1054:[function(require,module,exports){ +},{"./attributes":304,"./defaults":305,"./draw":306,"./has_colorbar":307}],309:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54501,6 +52484,7 @@ exports.hasColorbar = require('./has_colorbar'); 'use strict'; + module.exports = { zauto: { valType: 'boolean', @@ -54542,10 +52526,23 @@ module.exports = { dflt: true, + }, + + _deprecated: { + scl: { + valType: 'colorscale', + + + }, + reversescl: { + valType: 'boolean', + + + } } }; -},{}],1055:[function(require,module,exports){ +},{}],310:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54610,50 +52607,7 @@ module.exports = function calc(trace, vals, containerStr, cLetter) { } }; -},{"../../lib":1127,"./flip_scale":1059,"./scales":1066}],1056:[function(require,module,exports){ -/** -* Copyright 2012-2016, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var colorScaleAttributes = require('./attributes'); -var extendDeep = require('../../lib/extend').extendDeep; - -module.exports = function makeColorScaleAttributes(context) { - return { - color: { - valType: 'color', - arrayOk: true, - - - }, - colorscale: extendDeep({}, colorScaleAttributes.colorscale, { - - }), - cauto: extendDeep({}, colorScaleAttributes.zauto, { - - }), - cmax: extendDeep({}, colorScaleAttributes.zmax, { - - }), - cmin: extendDeep({}, colorScaleAttributes.zmin, { - - }), - autocolorscale: extendDeep({}, colorScaleAttributes.autocolorscale, { - - }), - reversescale: extendDeep({}, colorScaleAttributes.reversescale, { - - }) - }; -}; - -},{"../../lib/extend":1122,"./attributes":1054}],1057:[function(require,module,exports){ +},{"../../lib":381,"./flip_scale":313,"./scales":320}],311:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54669,7 +52623,7 @@ var scales = require('./scales'); module.exports = scales.RdBu; -},{"./scales":1066}],1058:[function(require,module,exports){ +},{"./scales":320}],312:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54733,7 +52687,7 @@ module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, if(showScale) colorbarDefaults(containerIn, containerOut, layout); }; -},{"../../lib":1127,"../colorbar/defaults":1050,"../colorbar/has_colorbar":1052,"./flip_scale":1059,"./is_valid_scale":1063,"fast-isnumeric":90}],1059:[function(require,module,exports){ +},{"../../lib":381,"../colorbar/defaults":305,"../colorbar/has_colorbar":307,"./flip_scale":313,"./is_valid_scale":317,"fast-isnumeric":117}],313:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54758,7 +52712,7 @@ module.exports = function flipScale(scl) { return sclNew; }; -},{}],1060:[function(require,module,exports){ +},{}],314:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54798,7 +52752,7 @@ module.exports = function getScale(scl, dflt) { return scl; }; -},{"./default_scale":1057,"./is_valid_scale_array":1064,"./scales":1066}],1061:[function(require,module,exports){ +},{"./default_scale":311,"./is_valid_scale_array":318,"./scales":320}],315:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54844,7 +52798,7 @@ module.exports = function hasColorscale(trace, containerStr) { ); }; -},{"../../lib":1127,"./is_valid_scale":1063,"fast-isnumeric":90}],1062:[function(require,module,exports){ +},{"../../lib":381,"./is_valid_scale":317,"fast-isnumeric":117}],316:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54876,7 +52830,7 @@ exports.flipScale = require('./flip_scale'); exports.makeScaleFunction = require('./make_scale_function'); -},{"./attributes":1054,"./calc":1055,"./default_scale":1057,"./defaults":1058,"./flip_scale":1059,"./get_scale":1060,"./has_colorscale":1061,"./is_valid_scale":1063,"./make_scale_function":1065,"./scales":1066}],1063:[function(require,module,exports){ +},{"./attributes":309,"./calc":310,"./default_scale":311,"./defaults":312,"./flip_scale":313,"./get_scale":314,"./has_colorscale":315,"./is_valid_scale":317,"./make_scale_function":319,"./scales":320}],317:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54897,7 +52851,7 @@ module.exports = function isValidScale(scl) { else return isValidScaleArray(scl); }; -},{"./is_valid_scale_array":1064,"./scales":1066}],1064:[function(require,module,exports){ +},{"./is_valid_scale_array":318,"./scales":320}],318:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54932,7 +52886,7 @@ module.exports = function isValidScaleArray(scl) { } }; -},{"tinycolor2":1042}],1065:[function(require,module,exports){ +},{"tinycolor2":274}],319:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -54981,7 +52935,7 @@ module.exports = function makeScaleFunction(scl, cmin, cmax) { }; }; -},{"../../lib":1127,"../color":1048,"d3":82,"fast-isnumeric":90,"tinycolor2":1042}],1066:[function(require,module,exports){ +},{"../../lib":381,"../color":303,"d3":113,"fast-isnumeric":117,"tinycolor2":274}],320:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55112,7 +53066,7 @@ module.exports = { ] }; -},{}],1067:[function(require,module,exports){ +},{}],321:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55145,7 +53099,7 @@ module.exports = function align(v, dv, v0, v1, anchor) { return vc; }; -},{}],1068:[function(require,module,exports){ +},{}],322:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55183,7 +53137,7 @@ module.exports = function getCursor(x, y, xanchor, yanchor) { return cursorset[y][x]; }; -},{"../../lib":1127}],1069:[function(require,module,exports){ +},{"../../lib":381}],323:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55352,7 +53306,7 @@ function finishDrag(gd) { if(gd._replotPending) Plotly.plot(gd); } -},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/constants":1155,"./align":1067,"./cursor":1068,"./unhover":1070}],1070:[function(require,module,exports){ +},{"../../lib":381,"../../plotly":400,"../../plots/cartesian/constants":408,"./align":321,"./cursor":322,"./unhover":324}],324:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55403,7 +53357,7 @@ unhover.raw = function unhoverRaw(gd, evt) { gd._hoverdata = undefined; }; -},{"../../lib/events":1121}],1071:[function(require,module,exports){ +},{"../../lib/events":375}],325:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -55452,61 +53406,16 @@ drawing.setRect = function(s, x, y, w, h) { s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); }; -drawing.translatePoints = function(s, xa, ya, trace, transitionConfig, joinDirection) { - - var hasTransition = transitionConfig && (transitionConfig || {}).duration > 0; - - if (hasTransition) { - var size = s.size(); - } - - s.each(function(d, i) { +drawing.translatePoints = function(s, xa, ya) { + s.each(function(d) { // put xp and yp into d if pixel scaling is already done var x = d.xp || xa.c2p(d.x), y = d.yp || ya.c2p(d.y), p = d3.select(this); if(isNumeric(x) && isNumeric(y)) { // for multiline text this works better - if(this.nodeName==='text') { - p.attr('x',x).attr('y',y); - } else { - if (hasTransition) { - var trans; - if (!joinDirection) { - trans = p.transition() - .delay(transitionConfig.delay + transitionConfig.cascade / size * i) - .duration(transitionConfig.duration) - .ease(transitionConfig.easing) - .attr('transform', 'translate('+x+','+y+')') - - if (trace) { - trans.call(drawing.pointStyle, trace) - } - } else if (joinDirection === -1) { - trans = p.style('opacity', 1) - .transition() - .duration(transitionConfig.duration) - .ease(transitionConfig.easing) - .style('opacity', 0) - .remove(); - } else if (joinDirection === 1) { - trans = p.attr('transform', 'translate('+x+','+y+')') - - if (trace) { - trans.call(drawing.pointStyle, trace) - } - - trans.style('opacity', 0) - .transition() - .duration(transitionConfig.duration) - .ease(transitionConfig.easing) - .style('opacity', 1) - } - - } else { - p.attr('transform', 'translate('+x+','+y+')'); - } - } + if(this.nodeName === 'text') p.attr('x', x).attr('y', y); + else p.attr('transform', 'translate(' + x + ',' + y + ')'); } else p.remove(); }); @@ -55573,7 +53482,7 @@ drawing.fillGroupStyle = function(s) { shape.call(Color.fill, d[0].trace.fillcolor); } catch(e) { - Lib.error(e, s); + console.log(e, s); shape.remove(); } }); @@ -55669,7 +53578,7 @@ drawing.pointStyle = function(s, trace) { markerScale = drawing.tryColorscale(marker, markerIn, ''), lineScale = drawing.tryColorscale(marker, markerIn, 'line.'); - s.each(function(d, i) { + s.each(function(d) { // 'so' is suspected outliers, for box plots var fillColor, lineColor, @@ -55686,11 +53595,11 @@ drawing.pointStyle = function(s, trace) { if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc); // weird case: array wasn't long enough to apply to every point - else if(Array.isArray(markerLine.color)) lineColor = marker.color[i]; + else if(Array.isArray(markerLine.color)) lineColor = Color.defaultLine; else lineColor = markerLine.color; if('mc' in d) fillColor = d.mcc = markerScale(d.mc); - else if(Array.isArray(marker.color)) fillColor = marker.color[i]; + else if(Array.isArray(marker.color)) fillColor = Color.defaultLine; else fillColor = marker.color || 'rgba(0,0,0,0)'; } @@ -56011,7 +53920,7 @@ drawing.setClipUrl = function(s, localId) { s.attr('clip-path', 'url(' + url + ')'); }; -},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plots/plots":1199,"../../traces/scatter/make_bubble_size_func":1315,"../../traces/scatter/subtypes":1322,"../color":1048,"../colorscale":1062,"./symbol_defs":1072,"d3":82,"fast-isnumeric":90}],1072:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":369,"../../lib":381,"../../lib/svg_text_utils":393,"../../plots/plots":452,"../../traces/scatter/make_bubble_size_func":567,"../../traces/scatter/subtypes":573,"../color":303,"../colorscale":316,"./symbol_defs":326,"d3":113,"fast-isnumeric":117}],326:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56487,7 +54396,7 @@ module.exports = { } }; -},{"d3":82}],1073:[function(require,module,exports){ +},{"d3":113}],327:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56586,7 +54495,7 @@ module.exports = { } }; -},{}],1074:[function(require,module,exports){ +},{}],328:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56649,7 +54558,7 @@ function calcOneAxis(calcTrace, trace, axis, coord) { Axes.expand(axis, vals, {padded: true}); } -},{"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"./compute_error":1075,"fast-isnumeric":90}],1075:[function(require,module,exports){ +},{"../../plots/cartesian/axes":403,"../../plots/plots":452,"./compute_error":329,"fast-isnumeric":117}],329:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56745,7 +54654,7 @@ function makeComputeErrorValue(type, value) { } } -},{}],1076:[function(require,module,exports){ +},{}],330:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56822,7 +54731,7 @@ module.exports = function(traceIn, traceOut, defaultColor, opts) { } }; -},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1073,"fast-isnumeric":90}],1077:[function(require,module,exports){ +},{"../../lib":381,"../../plots/plots":452,"./attributes":327,"fast-isnumeric":117}],331:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -56881,7 +54790,7 @@ errorBars.hoverInfo = function(calcPoint, trace, hoverPoint) { } }; -},{"./attributes":1073,"./calc":1074,"./defaults":1076,"./plot":1078,"./style":1079}],1078:[function(require,module,exports){ +},{"./attributes":327,"./calc":328,"./defaults":330,"./plot":332,"./style":333}],332:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57002,7 +54911,7 @@ function errorCoords(d, xa, ya) { return out; } -},{"../../lib":1127,"../../traces/scatter/subtypes":1322,"d3":82,"fast-isnumeric":90}],1079:[function(require,module,exports){ +},{"../../lib":381,"../../traces/scatter/subtypes":573,"d3":113,"fast-isnumeric":117}],333:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57039,7 +54948,7 @@ module.exports = function style(traces) { }); }; -},{"../color":1048,"d3":82}],1080:[function(require,module,exports){ +},{"../color":303,"d3":113}],334:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57154,7 +55063,7 @@ module.exports = { } }; -},{"../../plots/cartesian/constants":1155}],1081:[function(require,module,exports){ +},{"../../plots/cartesian/constants":408}],335:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57220,7 +55129,7 @@ function imageDefaults(imageIn, imageOut, fullLayout) { return imageOut; } -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./attributes":1080}],1082:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"./attributes":334}],336:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57393,7 +55302,7 @@ module.exports = function draw(gd) { imagesAbove.each(applyAttributes); }; -},{"../../plots/cartesian/axes":1150,"../drawing":1071,"d3":82}],1083:[function(require,module,exports){ +},{"../../plots/cartesian/axes":403,"../drawing":325,"d3":113}],337:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57416,7 +55325,7 @@ module.exports = { supplyLayoutDefaults: supplyLayoutDefaults }; -},{"./attributes":1080,"./defaults":1081,"./draw":1082}],1084:[function(require,module,exports){ +},{"./attributes":334,"./defaults":335,"./draw":336}],338:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57465,7 +55374,7 @@ exports.isMiddleAnchor = function isMiddleAnchor(opts) { ); }; -},{}],1085:[function(require,module,exports){ +},{}],339:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57556,7 +55465,7 @@ module.exports = { } }; -},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047}],1086:[function(require,module,exports){ +},{"../../lib/extend":376,"../../plots/font_attributes":421,"../color/attributes":302}],340:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57574,7 +55483,7 @@ module.exports = { scrollBarMargin: 4 }; -},{}],1087:[function(require,module,exports){ +},{}],341:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57666,7 +55575,7 @@ module.exports = function legendDefaults(layoutIn, layoutOut, fullData) { Lib.noneOrAll(containerIn, containerOut, ['x', 'y']); }; -},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1085,"./helpers":1090}],1088:[function(require,module,exports){ +},{"../../lib":381,"../../plots/plots":452,"./attributes":339,"./helpers":344}],342:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -57712,6 +55621,9 @@ module.exports = function draw(gd) { return; } + if(typeof gd.firstRender === 'undefined') gd.firstRender = true; + else if(gd.firstRender) gd.firstRender = false; + var legend = fullLayout._infolayer.selectAll('g.legend') .data([0]); @@ -57788,8 +55700,7 @@ module.exports = function draw(gd) { .call(setupTraceToggle, gd); }); - var firstRender = legend.enter().size() !== 0; - if(firstRender) { + if(gd.firstRender) { computeLegendDimensions(gd, groups, traces); expandMargin(gd); } @@ -57865,36 +55776,28 @@ module.exports = function draw(gd) { // legend, background and border, scroll box and scroll bar Lib.setTranslate(legend, lx, ly); - var scrollBarYMax = legendHeight - - constants.scrollBarHeight - - 2 * constants.scrollBarMargin, - scrollBoxYMax = opts.height - legendHeight, - scrollBarY, - scrollBoxY; + bg.attr({ + width: legendWidth - opts.borderwidth, + height: legendHeight - opts.borderwidth, + x: opts.borderwidth / 2, + y: opts.borderwidth / 2 + }); - if(opts.height <= legendHeight || gd._context.staticPlot) { - // if scrollbar should not be shown. - bg.attr({ - width: legendWidth - opts.borderwidth, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 - }); + var scrollPosition = scrollBox.attr('data-scroll') || 0; - Lib.setTranslate(scrollBox, 0, 0); + Lib.setTranslate(scrollBox, 0, scrollPosition); - clipPath.select('rect').attr({ - width: legendWidth - 2 * opts.borderwidth, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth - }); + clipPath.select('rect').attr({ + width: legendWidth - 2 * opts.borderwidth, + height: legendHeight - 2 * opts.borderwidth, + x: opts.borderwidth - scrollPosition, + y: opts.borderwidth + }); - scrollBox.call(Drawing.setClipUrl, clipId); - } - else { - scrollBarY = constants.scrollBarMargin, - scrollBoxY = scrollBox.attr('data-scroll') || 0; + scrollBox.call(Drawing.setClipUrl, clipId); + + // If scrollbar should be shown. + if(opts.height - legendHeight > 0 && !gd._context.staticPlot) { // increase the background and clip-path width // by the scrollbar width and margin @@ -57902,27 +55805,31 @@ module.exports = function draw(gd) { width: legendWidth - 2 * opts.borderwidth + constants.scrollBarWidth + - constants.scrollBarMargin, - height: legendHeight - opts.borderwidth, - x: opts.borderwidth / 2, - y: opts.borderwidth / 2 + constants.scrollBarMargin }); clipPath.select('rect').attr({ width: legendWidth - 2 * opts.borderwidth + constants.scrollBarWidth + - constants.scrollBarMargin, - height: legendHeight - 2 * opts.borderwidth, - x: opts.borderwidth, - y: opts.borderwidth - scrollBoxY + constants.scrollBarMargin }); - scrollBox.call(Drawing.setClipUrl, clipId); + if(gd.firstRender) { + // Move scrollbar to starting position + scrollHandler(constants.scrollBarMargin, 0); + } + + var scrollBarYMax = legendHeight - + constants.scrollBarHeight - + 2 * constants.scrollBarMargin, + scrollBoxYMax = opts.height - legendHeight, + scrollBarY = constants.scrollBarMargin, + scrollBoxY = 0; - if(firstRender) scrollHandler(scrollBarY, scrollBoxY); + scrollHandler(scrollBarY, scrollBoxY); - legend.on('wheel', null); // to be safe, remove previous listeners + legend.on('wheel', null); legend.on('wheel', function() { scrollBoxY = Lib.constrain( scrollBox.attr('data-scroll') - @@ -57934,10 +55841,8 @@ module.exports = function draw(gd) { d3.event.preventDefault(); }); - // to be safe, remove previous listeners scrollBar.on('.drag', null); scrollBox.on('.drag', null); - var drag = d3.behavior.drag().on('drag', function() { scrollBarY = Lib.constrain( d3.event.y - constants.scrollBarHeight / 2, @@ -57950,6 +55855,7 @@ module.exports = function draw(gd) { scrollBar.call(drag); scrollBox.call(drag); + } @@ -58317,7 +56223,7 @@ function expandHorizontalMargin(gd) { }); } -},{"../../lib":1127,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"./anchor_utils":1084,"./constants":1086,"./get_legend_data":1089,"./helpers":1090,"./style":1092,"d3":82}],1089:[function(require,module,exports){ +},{"../../lib":381,"../../plotly":400,"../../plots/plots":452,"../color":303,"../dragelement":323,"../drawing":325,"./anchor_utils":338,"./constants":340,"./get_legend_data":343,"./helpers":344,"./style":346,"d3":113}],343:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58423,7 +56329,7 @@ module.exports = function getLegendData(calcdata, opts) { return legendData; }; -},{"../../plots/plots":1199,"./helpers":1090}],1090:[function(require,module,exports){ +},{"../../plots/plots":452,"./helpers":344}],344:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58454,7 +56360,7 @@ exports.isReversed = function isReversed(legendLayout) { return (legendLayout.traceorder || '').indexOf('reversed') !== -1; }; -},{"../../plots/plots":1199}],1091:[function(require,module,exports){ +},{"../../plots/plots":452}],345:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58477,7 +56383,7 @@ legend.draw = require('./draw'); legend.style = require('./style'); -},{"./attributes":1085,"./defaults":1087,"./draw":1088,"./style":1092}],1092:[function(require,module,exports){ +},{"./attributes":339,"./defaults":341,"./draw":342,"./style":346}],346:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -58699,7 +56605,7 @@ function stylePies(d) { if(pts.size()) pts.call(stylePie, d[0], trace); } -},{"../../lib":1127,"../../plots/plots":1199,"../../traces/pie/style_one":1299,"../../traces/scatter/subtypes":1322,"../color":1048,"../drawing":1071,"d3":82}],1093:[function(require,module,exports){ +},{"../../lib":381,"../../plots/plots":452,"../../traces/pie/style_one":552,"../../traces/scatter/subtypes":573,"../color":303,"../drawing":325,"d3":113}],347:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59226,7 +57132,7 @@ modeBarButtons.resetViews = { } }; -},{"../../../build/ploticon":2,"../../lib":1127,"../../lib/setcursor":1136,"../../plotly":1147,"../../snapshot/download":1214}],1094:[function(require,module,exports){ +},{"../../../build/ploticon":2,"../../lib":381,"../../lib/setcursor":389,"../../plotly":400,"../../snapshot/download":467}],348:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59516,7 +57422,7 @@ function createModeBar(gd, buttons) { module.exports = createModeBar; -},{"../../../build/ploticon":2,"../../lib":1127,"d3":82}],1095:[function(require,module,exports){ +},{"../../../build/ploticon":2,"../../lib":381,"d3":113}],349:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59744,7 +57650,7 @@ function fillCustomButton(customButtons) { return customButtons; } -},{"../../plotly":1147,"../../traces/scatter/subtypes":1322,"./":1094,"./buttons":1093}],1096:[function(require,module,exports){ +},{"../../plotly":400,"../../traces/scatter/subtypes":573,"./":348,"./buttons":347}],350:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59828,7 +57734,7 @@ module.exports = { } }; -},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047,"./button_attributes":1097}],1097:[function(require,module,exports){ +},{"../../lib/extend":376,"../../plots/font_attributes":421,"../color/attributes":302,"./button_attributes":351}],351:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59869,7 +57775,7 @@ module.exports = { } }; -},{}],1098:[function(require,module,exports){ +},{}],352:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59897,7 +57803,7 @@ module.exports = { activeColor: '#d3d3d3' }; -},{}],1099:[function(require,module,exports){ +},{}],353:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -59984,7 +57890,7 @@ function getPosDflt(containerOut, layout, counterAxes) { return [containerOut.domain[0], posY + constants.yPad]; } -},{"../../lib":1127,"./attributes":1096,"./button_attributes":1097,"./constants":1098}],1100:[function(require,module,exports){ +},{"../../lib":381,"./attributes":350,"./button_attributes":351,"./constants":352}],354:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60259,7 +58165,7 @@ function reposition(gd, buttons, opts, axName) { }); } -},{"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axis_ids":1152,"../../plots/plots":1199,"../color":1048,"../drawing":1071,"../legend/anchor_utils":1084,"./constants":1098,"./get_update_object":1101,"d3":82}],1101:[function(require,module,exports){ +},{"../../lib/svg_text_utils":393,"../../plotly":400,"../../plots/cartesian/axis_ids":405,"../../plots/plots":452,"../color":303,"../drawing":325,"../legend/anchor_utils":338,"./constants":352,"./get_update_object":355,"d3":113}],355:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60317,7 +58223,7 @@ function getXRange(axisLayout, buttonLayout) { return [range0, range1]; } -},{"d3":82}],1102:[function(require,module,exports){ +},{"d3":113}],356:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60335,7 +58241,7 @@ exports.supplyLayoutDefaults = require('./defaults'); exports.draw = require('./draw'); -},{"./attributes":1096,"./defaults":1099,"./draw":1100}],1103:[function(require,module,exports){ +},{"./attributes":350,"./defaults":353,"./draw":354}],357:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60393,7 +58299,7 @@ module.exports = { } }; -},{"../color/attributes":1047}],1104:[function(require,module,exports){ +},{"../color/attributes":302}],358:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60689,7 +58595,7 @@ module.exports = function createSlider(gd) { }); }; -},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"./helpers":1106,"./range_plot":1108}],1105:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":369,"../../lib":381,"../../plotly":400,"../../plots/cartesian/axes":403,"./helpers":360,"./range_plot":362}],359:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60743,7 +58649,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, axName, coun } }; -},{"../../lib":1127,"./attributes":1103}],1106:[function(require,module,exports){ +},{"../../lib":381,"./attributes":357}],360:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60769,7 +58675,7 @@ exports.appendChildren = function appendChildren(el, children) { } }; -},{}],1107:[function(require,module,exports){ +},{}],361:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60826,7 +58732,7 @@ function draw(gd) { }); } -},{"../../plots/plots":1199,"./create_slider":1104,"./defaults":1105}],1108:[function(require,module,exports){ +},{"../../plots/plots":452,"./create_slider":358,"./defaults":359}],362:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -60839,7 +58745,6 @@ function draw(gd) { var d3 = require('d3'); -var Lib = require('../../lib'); var Symbols = require('../drawing/symbol_defs'); var Drawing = require('../drawing'); @@ -60883,7 +58788,7 @@ module.exports = function rangePlot(gd, w, h) { pointPairs = []; if(allowedTypes.indexOf(trace.type) < 0) { - Lib.warn('Trace type ' + trace.type + ' not supported for range slider!'); + console.log('Trace type ' + trace.type + ' not supported for range slider!'); continue; } @@ -60991,7 +58896,7 @@ function makeScatter(trace, pointPairs, w, h) { break; default: - Lib.warn('Fill type ' + trace.fill + ' not supported for range slider! (yet...)'); + console.log('Fill type ' + trace.fill + ' not supported for range slider! (yet...)'); break; } @@ -61007,7 +58912,7 @@ function makeScatter(trace, pointPairs, w, h) { return [line, markers, fill]; } -},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../drawing":1071,"../drawing/symbol_defs":1072,"./helpers":1106,"d3":82}],1109:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":369,"../drawing":325,"../drawing/symbol_defs":326,"./helpers":360,"d3":113}],363:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61098,7 +59003,7 @@ module.exports = { } }; -},{"../../lib/extend":1122,"../../traces/scatter/attributes":1301,"../annotations/attributes":1045}],1110:[function(require,module,exports){ +},{"../../lib/extend":376,"../../traces/scatter/attributes":554,"../annotations/attributes":300}],364:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61426,7 +59331,7 @@ function updateShape(gd, index, opt, value) { plotinfo = plots[subplots[i]]; clipAxes = subplots[i]; - if(isShapeInSubplot(gd, options, plotinfo)) { + if(isShapeInSubplot(gd, options, plotinfo.id)) { drawShape(plotinfo.shapelayer); } } @@ -61452,7 +59357,7 @@ function getShapeLayer(gd, index) { shapeLayer = gd._fullLayout._shapeUpperLayer; if(!shape) { - Lib.log('getShapeLayer: undefined shape: index', index); + console.log('getShapeLayer: undefined shape: index', index); } else if(shape.layer === 'below') { shapeLayer = (shape.xref === 'paper' && shape.yref === 'paper') ? @@ -61463,13 +59368,10 @@ function getShapeLayer(gd, index) { return shapeLayer; } -function isShapeInSubplot(gd, shape, plotinfo) { - var xa = Plotly.Axes.getFromId(gd, plotinfo.id, 'x')._id, - ya = Plotly.Axes.getFromId(gd, plotinfo.id, 'y')._id, - isBelow = shape.layer === 'below', - inSuplotAxis = (xa === shape.xref || ya === shape.yref), - isNotAnOverlaidSubplot = !!plotinfo.shapelayer; - return isBelow && inSuplotAxis && isNotAnOverlaidSubplot; +function isShapeInSubplot(gd, shape, subplot) { + var xa = Plotly.Axes.getFromId(gd, subplot, 'x')._id, + ya = Plotly.Axes.getFromId(gd, subplot, 'y')._id; + return shape.layer === 'below' && (xa === shape.xref || ya === shape.yref); } function decodeDate(convertToPx) { @@ -61595,7 +59497,7 @@ shapes.convertPath = function(pathIn, x2p, y2p) { if(paramNumber > nParams) { paramString = paramString.replace(/[\s,]*X.*/, ''); - Lib.log('Ignoring extra params in segment ' + segment); + console.log('ignoring extra params in segment ' + segment); } return segmentType + paramString; @@ -61661,7 +59563,7 @@ function shapeBounds(ax, v0, v1, path, paramsToUse) { if(max >= min) return [min, max]; } -},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../drawing":1071,"./attributes":1109,"fast-isnumeric":90}],1111:[function(require,module,exports){ +},{"../../lib":381,"../../plotly":400,"../../plots/cartesian/axes":403,"../color":303,"../drawing":325,"./attributes":363,"fast-isnumeric":117}],365:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61891,7 +59793,7 @@ Titles.draw = function(gd, titleClass, options) { el.classed('js-placeholder', isplaceholder); }; -},{"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../drawing":1071,"d3":82,"fast-isnumeric":90}],1112:[function(require,module,exports){ +},{"../../lib":381,"../../lib/svg_text_utils":393,"../../plotly":400,"../../plots/plots":452,"../color":303,"../drawing":325,"d3":113,"fast-isnumeric":117}],366:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61912,7 +59814,7 @@ module.exports = { longdashdot: [8, 1, 1, 1] }; -},{}],1113:[function(require,module,exports){ +},{}],367:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61933,7 +59835,7 @@ module.exports = { longdashdot: [[0.5, 0.7, 0.8, 1], 10] }; -},{}],1114:[function(require,module,exports){ +},{}],368:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61956,7 +59858,7 @@ module.exports = { x: '❌' }; -},{}],1115:[function(require,module,exports){ +},{}],369:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61980,7 +59882,7 @@ exports.svgAttrs = { 'xmlns:xlink': exports.xlink }; -},{}],1116:[function(require,module,exports){ +},{}],370:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -61998,13 +59900,12 @@ exports.svgAttrs = { var Plotly = require('./plotly'); // package version injected by `npm run preprocess` -exports.version = '1.13.0'; +exports.version = '1.12.0'; // plot api exports.plot = Plotly.plot; exports.newPlot = Plotly.newPlot; exports.restyle = Plotly.restyle; -exports.animate = Plotly.animate; exports.relayout = Plotly.relayout; exports.redraw = Plotly.redraw; exports.extendTraces = Plotly.extendTraces; @@ -62031,7 +59932,7 @@ exports.Queue = Plotly.Queue; // export d3 used in the bundle exports.d3 = require('d3'); -},{"../build/ploticon":2,"./plot_api/set_plot_config":1145,"./plot_api/to_image":1146,"./plotly":1147,"./snapshot/download":1214,"d3":82}],1117:[function(require,module,exports){ +},{"../build/ploticon":2,"./plot_api/set_plot_config":398,"./plot_api/to_image":399,"./plotly":400,"./snapshot/download":467,"d3":113}],371:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62064,7 +59965,7 @@ if(typeof MathJax !== 'undefined') { exports.MathJax = false; } -},{}],1118:[function(require,module,exports){ +},{}],372:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62081,7 +59982,7 @@ module.exports = function arrayToCalcItem(traceAttr, calcItem, calcAttr, i) { if(Array.isArray(traceAttr)) calcItem[calcAttr] = traceAttr[i]; }; -},{}],1119:[function(require,module,exports){ +},{}],373:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62345,7 +60246,7 @@ exports.coerceFont = function(coerce, attr, dfltObj) { return out; }; -},{"../components/colorscale/get_scale":1060,"../components/colorscale/scales":1066,"./nested_property":1131,"fast-isnumeric":90,"tinycolor2":1042}],1120:[function(require,module,exports){ +},{"../components/colorscale/get_scale":314,"../components/colorscale/scales":320,"./nested_property":384,"fast-isnumeric":117,"tinycolor2":274}],374:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62360,8 +60261,6 @@ exports.coerceFont = function(coerce, attr, dfltObj) { var d3 = require('d3'); var isNumeric = require('fast-isnumeric'); -var Lib = require('../lib'); - /** * dateTime2ms - turn a date object or string s of the form @@ -62472,7 +60371,7 @@ function lpad(val, digits) { */ exports.ms2DateTime = function(ms, r) { if(typeof(d3) === 'undefined') { - Lib.error('d3 is not defined.'); + console.log('d3 is not defined'); return; } @@ -62684,7 +60583,7 @@ exports.parseDate = function(v) { return out; }; -},{"../lib":1127,"d3":82,"fast-isnumeric":90}],1121:[function(require,module,exports){ +},{"d3":113,"fast-isnumeric":117}],375:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62818,7 +60717,7 @@ var Events = { module.exports = Events; -},{"events":69}],1122:[function(require,module,exports){ +},{"events":55}],376:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62898,7 +60797,7 @@ function _extend(inputs, isDeep, keepAllKeys) { return target; } -},{"./is_plain_object.js":1128}],1123:[function(require,module,exports){ +},{"./is_plain_object.js":382}],377:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62922,7 +60821,7 @@ module.exports = function filterVisible(dataIn) { return dataOut; }; -},{}],1124:[function(require,module,exports){ +},{}],378:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -62935,7 +60834,7 @@ module.exports = function filterVisible(dataIn) { 'use strict'; var countryRegex = require('country-regex'); -var Lib = require('../lib'); +var Lib = require('./'); // make list of all country iso3 ids from at runtime @@ -62957,8 +60856,8 @@ exports.locationToFeature = function(locationmode, location, features) { if(feature.id === locationId) return feature; } - Lib.warn([ - 'Location with id', locationId, + console.warn([ + 'location with id', locationId, 'does not have a matching topojson feature at this resolution.' ].join(' ')); }; @@ -62978,10 +60877,10 @@ function countryNameToISO3(countryName) { if(regex.test(countryName.toLowerCase())) return iso3; } - Lib.warn('Unrecognized country name: ' + countryName + '.'); + console.warn('unrecognized country name: ' + countryName + '.'); } -},{"../lib":1127,"country-regex":81}],1125:[function(require,module,exports){ +},{"./":381,"country-regex":108}],379:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -63060,7 +60959,7 @@ function formatColor(containerIn, opacityIn, len) { module.exports = formatColor; -},{"../components/color/attributes":1047,"../components/colorscale/make_scale_function":1065,"./str2rgbarray":1139,"fast-isnumeric":90,"tinycolor2":1042}],1126:[function(require,module,exports){ +},{"../components/color/attributes":302,"../components/colorscale/make_scale_function":319,"./str2rgbarray":392,"fast-isnumeric":117,"tinycolor2":274}],380:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -63134,7 +61033,7 @@ function convertHTMLToUnicode(html) { module.exports = convertHTMLToUnicode; -},{"superscript-text":1041}],1127:[function(require,module,exports){ +},{"superscript-text":263}],381:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -63195,11 +61094,6 @@ lib.extendFlat = extendModule.extendFlat; lib.extendDeep = extendModule.extendDeep; lib.extendDeepAll = extendModule.extendDeepAll; -var loggersModule = require('./loggers'); -lib.log = loggersModule.log; -lib.warn = loggersModule.warn; -lib.error = loggersModule.error; - lib.notifier = require('./notifier'); /** @@ -63234,6 +61128,35 @@ lib.pauseEvent = function(e) { return false; }; +/** + * ------------------------------------------ + * debugging tools + * ------------------------------------------ + */ + +// set VERBOSE to true to get a lot more logging and tracing +lib.VERBOSE = false; + +// first markTime call will return time from page load +lib.TIMER = new Date().getTime(); + +// console.log that only runs if VERBOSE is on +lib.log = function() { + if(lib.VERBOSE) console.log.apply(console, arguments); +}; + +/** + * markTime - for debugging, mark the number of milliseconds + * since the previous call to markTime and log arbitrary info too + */ +lib.markTime = function(v) { + if(!lib.VERBOSE) return; + var t2 = new Date().getTime(); + console.log(v, t2 - lib.TIMER, '(msec)'); + if(lib.VERBOSE === 'trace') console.trace(); + lib.TIMER = t2; +}; + // constrain - restrict a number v to be between v0 and v1 lib.constrain = function(v, v0, v1) { if(v0 > v1) return Math.max(v1, Math.min(v0, v)); @@ -63384,17 +61307,18 @@ lib.syncOrAsync = function(sequence, arg, finalStep) { var ret, fni; function continueAsync() { + lib.markTime('async done ' + fni.name); return lib.syncOrAsync(sequence, arg, finalStep); } - while(sequence.length) { fni = sequence.splice(0, 1)[0]; ret = fni(arg); - + // lib.markTime('done calling '+fni.name) if(ret && ret.then) { return ret.then(continueAsync) .then(undefined, lib.promiseError); } + lib.markTime('sync done ' + fni.name); } return finalStep && finalStep(arg); @@ -63545,7 +61469,7 @@ lib.addStyleRule = function(selector, styleString) { else if(styleSheet.addRule) { styleSheet.addRule(selector, styleString, 0); } - else lib.warn('addStyleRule failed'); + else console.warn('addStyleRule failed'); }; lib.getTranslate = function(element) { @@ -63723,93 +61647,7 @@ lib.numSeparate = function(value, separators) { return x1 + x2; }; -/* - * Deep copy of an object, subject to some caveats. Adapted from - * http://stackoverflow.com/questions/10728412/in-javascript-when-performing-a-deep-copy-how-do-i-avoid-a-cycle-due-to-a-pro#answer-10729242 - * - * It does some basics like avoiding infinite loops, but leaves some gaps - * regarding prototypes and functions. But those shouldn't be part of the - * layout anyway, which is the intended use. - * - * @param {object} object the object to be cloned - * @param {function} shallowFilter a callback executed on each attribute name - * @param {Array} path a stack representing the current attr path - * - * @return {object} the cloned object - */ -lib.deepClone = function deepClone (object, shallowFilter, path) { - var nextPath, isShallow; - var gdcc = "__getDeepCircularCopy__"; - if (object !== Object(object)) { - return object; // primitive value - } - - var set = gdcc in object; - var cache = object[gdcc]; - var result; - if (set && typeof cache == "function") { - return cache(); - } - // else - object[gdcc] = function () { return result; }; // overwrite - - if (object instanceof Array) { - result = []; - for (var i=0; i 1) { - var messages = ['LOG:']; - - for(var i = 0; i < arguments.length; i++) { - messages.push(arguments[i]); - } - - if(console.trace) { - console.trace.apply(console, messages); - } else { - console.log.apply(console, messages); - } - } -}; - -loggers.warn = function() { - if(config.logging > 0) { - var messages = ['WARN:']; - - for(var i = 0; i < arguments.length; i++) { - messages.push(arguments[i]); - } - - if(console.trace) { - console.trace.apply(console, messages); - } else { - console.log.apply(console, messages); - } - } -}; - -loggers.error = function() { - if(config.logging > 0) { - var messages = ['ERROR:']; - - for(var i = 0; i < arguments.length; i++) { - messages.push(arguments[i]); - } - - console.error.apply(console, arguments); - } -}; -/* eslint-enable no-console */ - -},{"../plot_api/plot_config":1143}],1130:[function(require,module,exports){ +},{}],383:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64006,7 +61777,7 @@ exports.apply2DTransform2 = function(transform) { }; }; -},{}],1131:[function(require,module,exports){ +},{}],384:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64262,7 +62033,7 @@ function badContainer(container, propStr, propParts) { }; } -},{"fast-isnumeric":90}],1132:[function(require,module,exports){ +},{"fast-isnumeric":117}],385:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64339,7 +62110,7 @@ module.exports = function(text, displayLength) { }); }; -},{"d3":82,"fast-isnumeric":90}],1133:[function(require,module,exports){ +},{"d3":113,"fast-isnumeric":117}],386:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64579,7 +62350,7 @@ polygon.filter = function filter(pts, tolerance) { }; }; -},{"./matrix":1130}],1134:[function(require,module,exports){ +},{"./matrix":383}],387:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64782,7 +62553,7 @@ queue.plotDo = function(gd, func, args) { module.exports = queue; -},{"../plotly":1147}],1135:[function(require,module,exports){ +},{"../plotly":400}],388:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64796,8 +62567,6 @@ module.exports = queue; var isNumeric = require('fast-isnumeric'); -var Lib = require('../lib'); - /** * findBin - find the bin for val - note that it can return outside the @@ -64832,7 +62601,7 @@ exports.findBin = function(val, bins, linelow) { if(test(bins[n], val)) n1 = n + 1; else n2 = n; } - if(c > 90) Lib.log('Long binary search...'); + if(c > 90) console.log('Long binary search...'); return n1 - 1; } }; @@ -64894,7 +62663,7 @@ exports.roundUp = function(val, arrayIn, reverse) { return arrayIn[low]; }; -},{"../lib":1127,"fast-isnumeric":90}],1136:[function(require,module,exports){ +},{"fast-isnumeric":117}],389:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64917,7 +62686,7 @@ module.exports = function setCursor(el3, csr) { if(csr) el3.classed('cursor-' + csr, true); }; -},{}],1137:[function(require,module,exports){ +},{}],390:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -64966,7 +62735,7 @@ module.exports = function showWebGlMsg(scene) { return false; }; -},{"../components/color":1048}],1138:[function(require,module,exports){ +},{"../components/color":303}],391:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -65062,7 +62831,7 @@ exports.interp = function(arr, n) { return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; }; -},{"fast-isnumeric":90}],1139:[function(require,module,exports){ +},{"fast-isnumeric":117}],392:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -65084,7 +62853,7 @@ function str2RgbaArray(color) { module.exports = str2RgbaArray; -},{"arraytools":64,"tinycolor2":1042}],1140:[function(require,module,exports){ +},{"arraytools":49,"tinycolor2":274}],393:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -65101,7 +62870,6 @@ module.exports = str2RgbaArray; var Plotly = require('../plotly'); var d3 = require('d3'); -var Lib = require('../lib'); var xmlnsNamespaces = require('../constants/xmlns_namespaces'); var util = module.exports = {}; @@ -65124,7 +62892,7 @@ d3.selection.prototype.appendSVG = function(_svgString) { childNode = childNode.nextSibling; } if(dom.querySelector('parsererror')) { - Lib.log(dom.querySelector('parsererror div').textContent); + console.log(dom.querySelector('parsererror div').textContent); return null; } return d3.select(this.node().lastChild); @@ -65290,7 +63058,7 @@ function texToSVG(_texString, _config, _callback) { var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs'); if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) { - Lib.log('There was an error in the tex syntax.', _texString); + console.log('There was an error in the tex syntax.', _texString); _callback(); } else { @@ -65568,7 +63336,7 @@ util.makeEditable = function(context, _delegate, options) { return d3.rebind(this, dispatch, 'on'); }; -},{"../constants/xmlns_namespaces":1115,"../lib":1127,"../plotly":1147,"d3":82}],1141:[function(require,module,exports){ +},{"../constants/xmlns_namespaces":369,"../plotly":400,"d3":113}],394:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -65604,7 +63372,7 @@ topojsonUtils.getTopojsonFeatures = function(trace, topojson) { return topojsonFeature(topojson, obj).features; }; -},{"../plots/geo/constants":1169,"topojson":1043}],1142:[function(require,module,exports){ +},{"../plots/geo/constants":422,"topojson":275}],395:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -65658,6 +63426,7 @@ var xmlnsNamespaces = require('../constants/xmlns_namespaces'); * */ Plotly.plot = function(gd, data, layout, config) { + Lib.markTime('in plot'); gd = getGraphDiv(gd); @@ -65670,7 +63439,7 @@ Plotly.plot = function(gd, data, layout, config) { // if there's no data or layout, and this isn't yet a plotly plot // container, log a warning to help plotly.js users debug if(!data && !layout && !Lib.isPlotDiv(gd)) { - Lib.warn('Calling Plotly.plot as if redrawing ' + + console.log('Warning: calling Plotly.plot as if redrawing ' + 'but this container doesn\'t yet have a plot.', gd); } @@ -65829,9 +63598,11 @@ Plotly.plot = function(gd, data, layout, config) { } } + Lib.markTime('done with bar/box adjustments'); // calc and autorange for errorbars ErrorBars.calc(gd); + Lib.markTime('done ErrorBars.calc'); // TODO: autosize extra for text markers return Lib.syncOrAsync([ @@ -65886,6 +63657,7 @@ Plotly.plot = function(gd, data, layout, config) { // styling separate from drawing Plots.style(gd); + Lib.markTime('done Plots.style'); // show annotations and shapes Shapes.drawAll(gd); @@ -65915,6 +63687,7 @@ Plotly.plot = function(gd, data, layout, config) { function cleanUp() { // now we're REALLY TRULY done plotting... // so mark it as done and let other procedures call a replot + Lib.markTime('done plot'); gd.emit('plotly_afterplot'); } @@ -66146,7 +63919,7 @@ function cleanLayout(layout) { } if(layout.annotations !== undefined && !Array.isArray(layout.annotations)) { - Lib.warn('Annotations must be an array.'); + console.log('annotations must be an array'); delete layout.annotations; } var annotationsLen = (layout.annotations || []).length; @@ -66168,7 +63941,7 @@ function cleanLayout(layout) { } if(layout.shapes !== undefined && !Array.isArray(layout.shapes)) { - Lib.warn('Shapes must be an array.'); + console.log('shapes must be an array'); delete layout.shapes; } var shapesLen = (layout.shapes || []).length; @@ -66243,7 +64016,9 @@ function cleanLayout(layout) { // sanitize rgb(fractions) and rgba(fractions) that old tinycolor // supported, but new tinycolor does not because they're not valid css + Lib.markTime('finished rest of cleanLayout, starting color'); Color.clean(layout); + Lib.markTime('finished cleanLayout color.clean'); return layout; } @@ -66392,7 +64167,9 @@ function cleanData(data, existingData) { // sanitize rgb(fractions) and rgba(fractions) that old tinycolor // supported, but new tinycolor does not because they're not valid css + Lib.markTime('finished rest of cleanData, starting color'); Color.clean(trace); + Lib.markTime('finished cleanData color.clean'); } } @@ -66421,7 +64198,7 @@ Plotly.redraw = function(gd) { gd = getGraphDiv(gd); if(!Lib.isPlotDiv(gd)) { - Lib.warn('This element is not a Plotly plot.', gd); + console.log('This element is not a Plotly Plot', gd); return; } @@ -66446,14 +64223,13 @@ Plotly.newPlot = function(gd, data, layout, config) { return Plotly.plot(gd, data, layout, config); }; -function doCalcdata(gd, traces) { +function doCalcdata(gd) { var axList = Plotly.Axes.list(gd), fullData = gd._fullData, fullLayout = gd._fullLayout; var i, trace, module, cd; - var oldCalcdata = (gd.calcdata || []).slice(0); var calcdata = gd.calcdata = new Array(fullData.length); // extra helper variables @@ -66478,13 +64254,6 @@ function doCalcdata(gd, traces) { } for(i = 0; i < fullData.length; i++) { - // If traces were specified and this trace was not included, then transfer it over from - // the old calcdata: - if (Array.isArray(traces) && traces.indexOf(i) === -1) { - calcdata[i] = oldCalcdata[i]; - continue; - } - trace = fullData[i]; module = trace._module; cd = []; @@ -66504,6 +64273,7 @@ function doCalcdata(gd, traces) { if(!cd[0].t) cd[0].t = {}; cd[0].trace = trace; + Lib.markTime('done with calcdata for ' + i); calcdata[i] = cd; } } @@ -67125,172 +64895,6 @@ Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) { return promise; }; -// ----------------------------------------------------- -// animate the changing of data -// ----------------------------------------------------- -// Sequence is: -// -// 1. prepare for animation (store copy of current data, if necessary) -// 2. update gd.data -// 3. update gl._fullData -// 4. doCalcdata -// 5. begin animation -Plotly.animate = function animate (gd, newData, transitionOpts, traces) { - gd = getGraphDiv(gd); - - var fullLayout = gd._fullLayout; - var i, newTraceData, curData, value, traceIdx; - - if (!Array.isArray(newData)) { - Lib.warn('Animate fail. newData must be an array of traces'); - return Promise.reject(); - } - - transitionOpts = transitionOpts || {}; - transitionOpts.duration = transitionOpts.duration === undefined ? 250 : transitionOpts.duration; - transitionOpts.easing = transitionOpts.easing === undefined ? 'cubic-in-out' : transitionOpts.easing; - transitionOpts.cascade = transitionOpts.cascade === undefined ? 0 : transitionOpts.cascade; - transitionOpts.leadingEdgeRestyle = transitionOpts.leadingEdgeRestyle === undefined ? false : transitionOpts.leadingEdgeRestyle; - - gd = getGraphDiv(gd); - - if(isNumeric(traces)) traces = [traces]; - else if(!Array.isArray(traces) || !traces.length) { - traces = gd._fullData.map(function (v,i) {return i;}); - } - - cloneTraceDefinitions(gd); - - var animatedTraces = []; - - for (i = 0; i < traces.length; i++) { - var traceIdx = traces[i]; - var trace = gd._fullData[traceIdx]; - var module = trace._module; - - if (!module.animatable) { - continue; - } - - animatedTraces.push(traceIdx); - - newTraceData = newData[i]; - curData = gd.data[traces[i]]; - - for (var ai in newTraceData) { - var value = newTraceData[ai]; - Lib.nestedProperty(curData, ai).set(value); - } - - - var traceIdx = traces[i]; - if (gd.data[traceIdx].marker && gd.data[traceIdx].marker.size) { - gd._fullData[traceIdx].marker.size = gd.data[traceIdx].marker.size - } - gd._fullData[traceIdx].x = gd.data[traceIdx].x; - gd._fullData[traceIdx].y = gd.data[traceIdx].y; - gd._fullData[traceIdx].z = gd.data[traceIdx].z; - gd._fullData[traceIdx].key = gd.data[traceIdx].key; - } - - doCalcdata(gd, animatedTraces); - - function doSetPositions () { - var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'); - var modules = fullLayout._modules; - - // position and range calculations for traces that - // depend on each other ie bars (stacked or grouped) - // and boxes (grouped) push each other out of the way - - var subplotInfo, _module; - - for(var i = 0; i < subplots.length; i++) { - subplotInfo = fullLayout._plots[subplots[i]]; - - for(var j = 0; j < modules.length; j++) { - _module = modules[j]; - if(_module.setPositions) _module.setPositions(gd, subplotInfo); - } - } - } - - doSetPositions(); - - var restyleList = []; - - function doAnimations () { - var a, i, j; - var basePlotModules = fullLayout._basePlotModules; - for(j = 0; j < basePlotModules.length; j++) { - basePlotModules[j].plot(gd, animatedTraces, transitionOpts); - } - if (!transitionOpts.leadingEdgeRestyle) { - return new Promise(function(resolve, reject) { - setTimeout(resolve, transitionOpts.duration); - }); - } - } - - /*for (var i = 0; i < animatedTraces.length; i++) { - var trace = gd._fullData[animatedTraces[i]]; - var module = trace._module; - var cd = []; - - if(module && trace.visible === true) { - if(module.calc) cd = module.calc(gd, trace); - } - - // make sure there is a first point - // this ensures there is a calcdata item for every trace, - // even if cartesian logic doesn't handle it - if(!Array.isArray(cd) || !cd[0]) cd = [{x: false, y: false}]; - - // add the trace-wide properties to the first point, - // per point properties to every point - // t is the holder for trace-wide properties - if(!cd[0].t) cd[0].t = {}; - - cd[0].trace = trace; - - gd.calcdata[traces[i]] = cd; - }*/ - - for (i = 0; i < traces.length; i++) { - var traceIdx = traces[i]; - var contFull = gd._fullData[traceIdx]; - var module = contFull._module; - - if (!module.animatable) { - var thisTrace = [traceIdx]; - var thisUpdate = {}; - - for (ai in newData[i]) { - thisUpdate[ai] = [newData[i][ai]]; - } - - restyleList.push((function (md, data, traces) { - return function () { - return Plotly.restyle(gd, data, traces); - } - }(module, thisUpdate, [traceIdx]))); - } - } - - var seq = [Plots.previousPromises]; - seq.push(doAnimations); - seq = seq.concat(restyleList); - - var plotDone = Lib.syncOrAsync(seq, gd); - - if(!plotDone || !plotDone.then) plotDone = Promise.resolve(); - - return plotDone.then(function() { - gd.emit('plotly_animate', []); - return gd; - }); -} - // ----------------------------------------------------- // restyle and relayout: these two control all redrawing // for data (restyle) and everything else (relayout) @@ -67326,7 +64930,7 @@ Plotly.restyle = function restyle(gd, astr, val, traces) { if(traces === undefined) traces = val; // the 3-arg form } else { - Lib.warn('Restyle fail.', astr, val, traces); + console.log('restyle fail', astr, val, traces); return Promise.reject(); } @@ -67433,7 +65037,7 @@ Plotly.restyle = function restyle(gd, astr, val, traces) { // to not go through a full replot var doPlotWhiteList = ['cartesian', 'pie', 'ternary']; fullLayout._basePlotModules.forEach(function(_module) { - if(doPlotWhiteList.indexOf(_module.name) === -1) docalc = true; + if(doPlotWhiteList.indexOf(_module.name) === -1) doplot = true; }); // make a new empty vals array for undoit @@ -67870,7 +65474,7 @@ Plotly.relayout = function relayout(gd, astr, val) { if(typeof astr === 'string') aobj[astr] = val; else if(Lib.isPlainObject(astr)) aobj = astr; else { - Lib.warn('Relayout fail.', astr, val); + console.log('relayout fail', astr, val); return Promise.reject(); } @@ -68061,7 +65665,7 @@ Plotly.relayout = function relayout(gd, astr, val) { } else undoit[ai] = obji; } - else Lib.log('???', aobj); + else console.log('???', aobj); } if((refAutorange(obji, 'x') || refAutorange(obji, 'y')) && !Lib.containsAny(ai, ['color', 'opacity', 'align', 'dash'])) { @@ -68071,27 +65675,13 @@ Plotly.relayout = function relayout(gd, astr, val) { // as it is we get separate calls for x and y (or ax and ay) on move objModule.draw(gd, objNum, p.parts.slice(2).join('.'), aobj[ai]); delete aobj[ai]; - } - else if(p.parts[0] === 'images') { - var update = Lib.objectFromPath(ai, vi); + } else if(p.parts[0] === 'images') { + var update = Lib.objectFromPath(astr, vi); Lib.extendDeepAll(gd.layout, update); Images.supplyLayoutDefaults(gd.layout, gd._fullLayout); Images.draw(gd); } - else if(p.parts[0] === 'mapbox' && p.parts[1] === 'layers') { - Lib.extendDeepAll(gd.layout, Lib.objectFromPath(ai, vi)); - - // append empty container to mapbox.layers - // so that relinkPrivateKeys does not complain - - var fullLayers = (gd._fullLayout.mapbox || {}).layers || []; - var diff = (p.parts[2] + 1) - fullLayers.length; - - for(i = 0; i < diff; i++) fullLayers.push({}); - - doplot = true; - } // alter gd.layout else { // check whether we can short-circuit a full redraw @@ -68866,34 +66456,7 @@ function drawMainTitle(gd) { }); } -// Clone gd.data *excluding* the actual data arrays. So ideally this should be a -// relatively cheap operation and only needs to be called once in order to sever -// the connection between a trace and plotly's representation of the trace. -function cloneTraceDefinitions (gd) { - var i, type, schema; - var isClonedFlag = '__isCloned__'; - - // Clone the traces array reference if it's not already cloned: - if (!gd.data[isClonedFlag]) { - gd.data = gd.data.slice(0); - gd.data[isClonedFlag] = true; - } - - // Now clone individual traces - for (i = gd.data.length - 1; i >= 0; i--) { - if (gd.data[i][isClonedFlag]) continue; - - // Clone this trace if it's not already cloned. Otherwise the original input - // to Plotly.plot gets mangled and we can't use it again, which is inconvenient. - // Notably, this does *not* copy data arrays. - type = gd._fullData[i].type; - schema = Plotly.PlotSchema.get().traces[type] - gd.data[i] = Lib.deepCloneTrace(gd.data[i], schema); - gd.data[i][isClonedFlag] = true; - } -} - -},{"../components/color":1048,"../components/drawing":1071,"../components/errorbars":1077,"../components/images":1083,"../components/legend":1091,"../components/modebar/manage":1095,"../components/rangeselector":1102,"../components/rangeslider":1107,"../components/shapes":1110,"../components/titles":1111,"../constants/xmlns_namespaces":1115,"../lib":1127,"../lib/events":1121,"../lib/queue":1134,"../plotly":1147,"../plots/cartesian/graph_interact":1157,"../plots/plots":1199,"d3":82,"fast-isnumeric":90,"gl-mat4/fromQuat":237}],1143:[function(require,module,exports){ +},{"../components/color":303,"../components/drawing":325,"../components/errorbars":331,"../components/images":337,"../components/legend":345,"../components/modebar/manage":349,"../components/rangeselector":356,"../components/rangeslider":361,"../components/shapes":364,"../components/titles":365,"../constants/xmlns_namespaces":369,"../lib":381,"../lib/events":375,"../lib/queue":387,"../plotly":400,"../plots/cartesian/graph_interact":410,"../plots/plots":452,"d3":113,"fast-isnumeric":117,"gl-mat4/fromQuat":134}],396:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -68902,9 +66465,8 @@ function cloneTraceDefinitions (gd) { * LICENSE file in the root directory of this source tree. */ -'use strict'; -var Lib = require('../lib'); +'use strict'; /** * This will be transfered over to gd and overridden by @@ -68980,14 +66542,8 @@ module.exports = { setBackground: defaultSetBackground, // URL to topojson files used in geo charts - topojsonURL: 'https://cdn.plot.ly/', - - // Mapbox access token (required to plot mapbox trace types) - mapboxAccessToken: null, + topojsonURL: 'https://cdn.plot.ly/' - // Turn all console logging on or off (errors will be thrown) - // This should ONLY be set via Plotly.setPlotConfig - logging: false }; // where and how the background gets set can be overridden by context @@ -68996,10 +66552,10 @@ function defaultSetBackground(gd, bgColor) { try { gd._fullLayout._paper.style('background', bgColor); } - catch(e) { Lib.error(e); } + catch(e) { console.log(e); } } -},{"../lib":1127}],1144:[function(require,module,exports){ +},{}],397:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69322,7 +66878,7 @@ function handleLinkedToArray(layoutAttributes) { PlotSchema.crawl(layoutAttributes, callback); } -},{"../lib":1127,"../plotly":1147,"../plots/plots":1199,"../plots/polar/area_attributes":1200,"../plots/polar/axis_attributes":1201}],1145:[function(require,module,exports){ +},{"../lib":381,"../plotly":400,"../plots/plots":452,"../plots/polar/area_attributes":453,"../plots/polar/axis_attributes":454}],398:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69348,7 +66904,7 @@ module.exports = function setPlotConfig(configObj) { return Lib.extendFlat(Plotly.defaultConfig, configObj); }; -},{"../lib":1127,"../plotly":1147}],1146:[function(require,module,exports){ +},{"../lib":381,"../plotly":400}],399:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69461,7 +67017,7 @@ function toImage(gd, opts) { module.exports = toImage; -},{"../lib":1127,"../plotly":1147,"../snapshot":1216,"fast-isnumeric":90}],1147:[function(require,module,exports){ +},{"../lib":381,"../plotly":400,"../snapshot":469,"fast-isnumeric":117}],400:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69548,7 +67104,7 @@ exports.PlotSchema = require('./plot_api/plot_schema'); // imaging routines exports.Snapshot = require('./snapshot'); -},{"../build/plotcss":1,"./components/annotations":1046,"./components/color":1048,"./components/colorbar":1053,"./components/colorscale":1062,"./components/drawing":1071,"./components/errorbars":1077,"./components/images":1083,"./components/legend":1091,"./components/modebar":1094,"./components/shapes":1110,"./fonts/mathjax_config":1117,"./lib":1127,"./lib/queue":1134,"./lib/svg_text_utils":1140,"./plot_api/plot_api":1142,"./plot_api/plot_config":1143,"./plot_api/plot_schema":1144,"./plots/cartesian/axes":1150,"./plots/cartesian/graph_interact":1157,"./plots/plots":1199,"./plots/polar/micropolar":1202,"./snapshot":1216,"./traces/scatter":1310,"es6-promise":89}],1148:[function(require,module,exports){ +},{"../build/plotcss":1,"./components/annotations":301,"./components/color":303,"./components/colorbar":308,"./components/colorscale":316,"./components/drawing":325,"./components/errorbars":331,"./components/images":337,"./components/legend":345,"./components/modebar":348,"./components/shapes":364,"./fonts/mathjax_config":371,"./lib":381,"./lib/queue":387,"./lib/svg_text_utils":393,"./plot_api/plot_api":395,"./plot_api/plot_config":396,"./plot_api/plot_schema":397,"./plots/cartesian/axes":403,"./plots/cartesian/graph_interact":410,"./plots/plots":452,"./plots/polar/micropolar":455,"./snapshot":469,"./traces/scatter":563,"es6-promise":116}],401:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69629,7 +67185,7 @@ module.exports = { } }; -},{}],1149:[function(require,module,exports){ +},{}],402:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -69656,7 +67212,7 @@ module.exports = { } }; -},{}],1150:[function(require,module,exports){ +},{}],403:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -71071,7 +68627,7 @@ axes.doTicks = function(gd, axid, skipTitle) { }; } else { - Lib.warn('Unrecognized doTicks axis:', axid); + console.log('unrecognized doTicks axis', axid); return; } var axside = ax.side || sides[0], @@ -71629,7 +69185,7 @@ function swapAxisAttrs(layout, key, xFullAxes, yFullAxes) { // rather than built-in % which gives a negative value for negative v function mod(v, d) { return ((v % d) + d) % d; } -},{"../../components/color":1048,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"./axis_ids":1152,"./layout_attributes":1159,"./layout_defaults":1160,"./set_convert":1164,"d3":82,"fast-isnumeric":90}],1151:[function(require,module,exports){ +},{"../../components/color":303,"../../components/drawing":325,"../../components/titles":365,"../../lib":381,"../../lib/svg_text_utils":393,"../../plotly":400,"./axis_ids":405,"./layout_attributes":412,"./layout_defaults":413,"./set_convert":417,"d3":113,"fast-isnumeric":117}],404:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -71912,7 +69468,7 @@ function category(a) { return curvecats > curvenums * 2; } -},{"../../components/color/attributes":1047,"../../lib":1127,"../plots":1199,"./axis_ids":1152,"./category_order_defaults":1153,"./clean_datum":1154,"./layout_attributes":1159,"./ordered_categories":1161,"./set_convert":1164,"./tick_label_defaults":1165,"./tick_mark_defaults":1166,"./tick_value_defaults":1167,"fast-isnumeric":90,"tinycolor2":1042}],1152:[function(require,module,exports){ +},{"../../components/color/attributes":302,"../../lib":381,"../plots":452,"./axis_ids":405,"./category_order_defaults":406,"./clean_datum":407,"./layout_attributes":412,"./ordered_categories":414,"./set_convert":417,"./tick_label_defaults":418,"./tick_mark_defaults":419,"./tick_value_defaults":420,"fast-isnumeric":117,"tinycolor2":274}],405:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72033,7 +69589,7 @@ exports.getFromTrace = function(gd, fullTrace, type) { return ax; }; -},{"../../lib":1127,"../plots":1199,"./constants":1155}],1153:[function(require,module,exports){ +},{"../../lib":381,"../plots":452,"./constants":408}],406:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72067,7 +69623,7 @@ module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, } }; -},{}],1154:[function(require,module,exports){ +},{}],407:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72100,13 +69656,13 @@ module.exports = function cleanDatum(c) { c = c.toString().replace(/['"%,$# ]/g, ''); } catch(e) { - Lib.error(e, c); + console.log(e, c); } return c; }; -},{"../../lib":1127,"fast-isnumeric":90}],1155:[function(require,module,exports){ +},{"../../lib":381,"fast-isnumeric":117}],408:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72184,7 +69740,7 @@ module.exports = { REDRAWDELAY: 50 }; -},{}],1156:[function(require,module,exports){ +},{}],409:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -72559,7 +70115,7 @@ module.exports = function dragBox(gd, plotinfo, x, y, w, h, ns, ew) { var wheelDelta = -e.deltaY; if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; if(!isFinite(wheelDelta)) { - Lib.log('Did not find wheel motion attributes: ', e); + console.log('did not find wheel motion attributes', e); return; } @@ -72856,7 +70412,7 @@ function removeZoombox(gd) { .remove(); } -},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"./axes":1150,"./constants":1155,"./select":1163,"d3":82,"tinycolor2":1042}],1157:[function(require,module,exports){ +},{"../../components/color":303,"../../components/dragelement":323,"../../components/drawing":325,"../../lib":381,"../../lib/setcursor":389,"../../lib/svg_text_utils":393,"../../plotly":400,"./axes":403,"./constants":408,"./select":416,"d3":113,"tinycolor2":274}],410:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -73164,50 +70720,27 @@ function hover(gd, evt, subplot) { if(!subplot) subplot = 'xy'; - // if the user passed in an array of subplots, - // use those instead of finding overlayed plots - var subplots = Array.isArray(subplot) ? subplot : [subplot]; - var fullLayout = gd._fullLayout, - plots = fullLayout._plots || [], - plotinfo = plots[subplot]; - - // list of all overlaid subplots to look at - if(plotinfo) { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); - - subplots = subplots.concat(overlayedSubplots); - } - - var len = subplots.length, - xaArray = new Array(len), - yaArray = new Array(len); - - for(var i = 0; i < len; i++) { - var spId = subplots[i]; - - // 'cartesian' case - var plotObj = plots[spId]; - if(plotObj) { - - // TODO make sure that fullLayout_plots axis refs - // get updated properly so that we don't have - // to use Axes.getFromId in general. - - xaArray[i] = Axes.getFromId(gd, plotObj.xaxis._id); - yaArray[i] = Axes.getFromId(gd, plotObj.yaxis._id); - continue; - } - - // other subplot types - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; - } - - var hovermode = evt.hovermode || fullLayout.hovermode; + plotinfo = fullLayout._plots[subplot], + + //If the user passed in an array of subplots, use those instead of finding overlayed plots + subplots = Array.isArray(subplot) ? + subplot : + // list of all overlaid subplots to look at + [subplot].concat(plotinfo.overlays + .map(function(pi) { return pi.id; })), + + xaArray = subplots.map(function(spId) { + var ternary = (gd._fullLayout[spId] || {})._ternary; + if(ternary) return ternary.xaxis; + return Axes.getFromId(gd, spId, 'x'); + }), + yaArray = subplots.map(function(spId) { + var ternary = (gd._fullLayout[spId] || {})._ternary; + if(ternary) return ternary.yaxis; + return Axes.getFromId(gd, spId, 'y'); + }), + hovermode = evt.hovermode || fullLayout.hovermode; if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata || gd.querySelector('.zoombox') || gd._dragging) { @@ -73301,7 +70834,7 @@ function hover(gd, evt, subplot) { else yvalArray = p2c(yaArray, ypx); if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) { - Lib.warn('Plotly.Fx.hover failed', evt, gd); + console.log('Plotly.Fx.hover failed', evt, gd); return dragElement.unhoverRaw(gd, evt); } } @@ -73388,7 +70921,7 @@ function hover(gd, evt, subplot) { } } else { - Lib.log('Unrecognized trace type in hover:', trace); + console.log('unrecognized trace type in hover', trace); } // in closest mode, remove any existing (farther) points @@ -74198,7 +71731,7 @@ fx.inbox = function(v0, v1) { return Infinity; }; -},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/events":1121,"../../lib/svg_text_utils":1140,"./axes":1150,"./constants":1155,"./dragbox":1156,"d3":82,"fast-isnumeric":90,"tinycolor2":1042}],1158:[function(require,module,exports){ +},{"../../components/color":303,"../../components/dragelement":323,"../../components/drawing":325,"../../lib":381,"../../lib/events":375,"../../lib/svg_text_utils":393,"./axes":403,"./constants":408,"./dragbox":409,"d3":113,"fast-isnumeric":117,"tinycolor2":274}],411:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74210,10 +71743,9 @@ fx.inbox = function(v0, v1) { 'use strict'; +var Lib = require('../../lib'); var Plots = require('../plots'); -var d3 = require('d3'); - var constants = require('./constants'); exports.name = 'cartesian'; @@ -74228,7 +71760,7 @@ exports.attrRegex = constants.attrRegex; exports.attributes = require('./attributes'); -exports.plot = function(gd, traces, transitionOpts) { +exports.plot = function(gd) { var fullLayout = gd._fullLayout, subplots = Plots.getSubplotIds(fullLayout, 'cartesian'), calcdata = gd.calcdata, @@ -74241,9 +71773,6 @@ exports.plot = function(gd, traces, transitionOpts) { var cd = calcdata[i]; var trace = cd[0].trace; - // Skip trace if whitelist provided and it's not whitelisted: - // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue; - if(trace.xaxis + trace.yaxis === subplot) { cdSubplot.push(cd); } @@ -74273,13 +71802,9 @@ exports.plot = function(gd, traces, transitionOpts) { cdSubplot = getCdSubplot(calcdata, subplot); // remove old traces, then redraw everything - // TODO: scatterlayer is manually excluded from this since it knows how - // to update instead of fully removing and redrawing every time. The - // remaining plot traces should also be able to do this. Once implemented, - // we won't need this - which should sometimes be a big speedup. - if(subplotInfo.plot) { - subplotInfo.plot.selectAll('g:not(.scatterlayer)').selectAll('g.trace').remove(); - } + // TODO: use enter/exit appropriately in the plot functions + // so we don't need this - should sometimes be a big speedup + if(subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove(); for(var j = 0; j < modules.length; j++) { var _module = modules[j]; @@ -74289,13 +71814,14 @@ exports.plot = function(gd, traces, transitionOpts) { // plot all traces of this type on this subplot at once var cdModule = getCdModule(cdSubplot, _module); + _module.plot(gd, subplotInfo, cdModule); - _module.plot(gd, subplotInfo, cdModule, traces, transitionOpts); + Lib.markTime('done ' + (cdModule[0] && cdModule[0][0].trace.type)); } } }; -},{"../plots":1199,"./attributes":1149,"./constants":1155,"d3":82}],1159:[function(require,module,exports){ +},{"../../lib":381,"../plots":452,"./attributes":402,"./constants":408}],412:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74640,7 +72166,7 @@ module.exports = { } }; -},{"../../components/color/attributes":1047,"../../components/rangeselector/attributes":1096,"../../components/rangeslider/attributes":1103,"../../lib/extend":1122,"../font_attributes":1168,"./constants":1155}],1160:[function(require,module,exports){ +},{"../../components/color/attributes":302,"../../components/rangeselector/attributes":350,"../../components/rangeslider/attributes":357,"../../lib/extend":376,"../font_attributes":421,"./constants":408}],413:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74813,7 +72339,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { }); }; -},{"../../components/color":1048,"../../components/rangeselector":1102,"../../components/rangeslider":1107,"../../lib":1127,"../plots":1199,"./axis_defaults":1151,"./axis_ids":1152,"./constants":1155,"./layout_attributes":1159,"./position_defaults":1162}],1161:[function(require,module,exports){ +},{"../../components/color":303,"../../components/rangeselector":356,"../../components/rangeslider":361,"../../lib":381,"../plots":452,"./axis_defaults":404,"./axis_ids":405,"./constants":408,"./layout_attributes":412,"./position_defaults":415}],414:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74892,7 +72418,7 @@ module.exports = function orderedCategories(axisLetter, categoryorder, categorya } }; -},{"d3":82}],1162:[function(require,module,exports){ +},{"d3":113}],415:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -74957,7 +72483,7 @@ module.exports = function handlePositionDefaults(containerIn, containerOut, coer return containerOut; }; -},{"../../lib":1127,"fast-isnumeric":90}],1163:[function(require,module,exports){ +},{"../../lib":381,"fast-isnumeric":117}],416:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75157,7 +72683,7 @@ module.exports = function prepSelect(e, startX, startY, dragOptions, mode) { }; }; -},{"../../components/color":1048,"../../lib/polygon":1133,"./axes":1150,"./constants":1155}],1164:[function(require,module,exports){ +},{"../../components/color":303,"../../lib/polygon":386,"./axes":403,"./constants":408}],417:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75327,7 +72853,7 @@ module.exports = function setConvert(ax) { ax.range[1] = ar1[1]; } } - catch(e) { Lib.error(e, ax.range); } + catch(e) { console.log(e, ax.range); } } } else if(ax.type === 'category') { @@ -75401,7 +72927,7 @@ module.exports = function setConvert(ax) { ax._forceTick0 = null; }; -},{"../../lib":1127,"./axis_ids":1152,"./clean_datum":1154,"./constants":1155,"d3":82,"fast-isnumeric":90}],1165:[function(require,module,exports){ +},{"../../lib":381,"./axis_ids":405,"./clean_datum":407,"./constants":408,"d3":113,"fast-isnumeric":117}],418:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75484,7 +73010,7 @@ function getShowAttrDflt(containerIn) { } } -},{"../../lib":1127}],1166:[function(require,module,exports){ +},{"../../lib":381}],419:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75517,7 +73043,7 @@ module.exports = function handleTickDefaults(containerIn, containerOut, coerce, } }; -},{"../../lib":1127,"./layout_attributes":1159}],1167:[function(require,module,exports){ +},{"../../lib":381,"./layout_attributes":412}],420:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75558,7 +73084,7 @@ module.exports = function handleTickValueDefaults(containerIn, containerOut, coe } }; -},{"fast-isnumeric":90}],1168:[function(require,module,exports){ +},{"fast-isnumeric":117}],421:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75589,7 +73115,7 @@ module.exports = { } }; -},{}],1169:[function(require,module,exports){ +},{}],422:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -75747,7 +73273,7 @@ params.layerNameToAdjective = { // base layers drawn over choropleth params.baseLayersOverChoropleth = ['rivers', 'lakes']; -},{}],1170:[function(require,module,exports){ +},{}],423:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76241,7 +73767,7 @@ function createMockAxis(fullLayout) { return mockAxis; } -},{"../../components/color":1048,"../../components/drawing":1071,"../../constants/xmlns_namespaces":1115,"../../lib/filter_visible":1123,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"./constants":1169,"./projections":1177,"./set_scale":1178,"./zoom":1179,"./zoom_reset":1180,"d3":82,"topojson":1043}],1171:[function(require,module,exports){ +},{"../../components/color":303,"../../components/drawing":325,"../../constants/xmlns_namespaces":369,"../../lib/filter_visible":377,"../../lib/topojson_utils":394,"../../plots/cartesian/axes":403,"./constants":422,"./projections":430,"./set_scale":431,"./zoom":432,"./zoom_reset":433,"d3":113,"topojson":275}],424:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76347,7 +73873,7 @@ exports.toSVG = function(gd) { } }; -},{"../../plots/plots":1199,"./geo":1170,"./layout/attributes":1172,"./layout/defaults":1175,"./layout/layout_attributes":1176}],1172:[function(require,module,exports){ +},{"../../plots/plots":452,"./geo":423,"./layout/attributes":425,"./layout/defaults":428,"./layout/layout_attributes":429}],425:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76368,7 +73894,7 @@ module.exports = { } }; -},{}],1173:[function(require,module,exports){ +},{}],426:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76423,7 +73949,7 @@ module.exports = { } }; -},{"../../../components/color/attributes":1047}],1174:[function(require,module,exports){ +},{"../../../components/color/attributes":302}],427:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76497,7 +74023,7 @@ module.exports = function supplyGeoAxisLayoutDefaults(geoLayoutIn, geoLayoutOut) } }; -},{"../../../lib":1127,"../constants":1169,"./axis_attributes":1173}],1175:[function(require,module,exports){ +},{"../../../lib":381,"../constants":422,"./axis_attributes":426}],428:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76616,7 +74142,7 @@ function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) { ]; } -},{"../../subplot_defaults":1205,"../constants":1169,"./axis_defaults":1174,"./layout_attributes":1176}],1176:[function(require,module,exports){ +},{"../../subplot_defaults":458,"../constants":422,"./axis_defaults":427,"./layout_attributes":429}],429:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -76849,7 +74375,7 @@ module.exports = { lataxis: geoAxesAttrs }; -},{"../../../components/color/attributes":1047,"../constants":1169,"./axis_attributes":1173}],1177:[function(require,module,exports){ +},{"../../../components/color/attributes":302,"../constants":422,"./axis_attributes":426}],430:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77295,7 +74821,7 @@ function addProjectionsToD3(d3) { module.exports = addProjectionsToD3; -},{}],1178:[function(require,module,exports){ +},{}],431:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77309,7 +74835,7 @@ module.exports = addProjectionsToD3; var d3 = require('d3'); -var clipPad = require('./constants').clipPad; +var clipPad = require('./constants/').clipPad; function createGeoScale(geoLayout, graphSize) { var projLayout = geoLayout.projection, @@ -77446,7 +74972,7 @@ function getBounds(projection, rangeBox) { return d3.geo.path().projection(projection).bounds(rangeBox); } -},{"./constants":1169,"d3":82}],1179:[function(require,module,exports){ +},{"./constants/":422,"d3":113}],432:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77873,7 +75399,7 @@ function d3_eventDispatch(target) { return dispatch; } -},{"d3":82}],1180:[function(require,module,exports){ +},{"d3":113}],433:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -77908,7 +75434,7 @@ function createGeoZoomReset(geo, geoLayout) { module.exports = createGeoZoomReset; -},{"../cartesian/graph_interact":1157}],1181:[function(require,module,exports){ +},{"../cartesian/graph_interact":410}],434:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78063,7 +75589,7 @@ function createCamera(scene) { return result; } -},{"mouse-change":1004,"mouse-wheel":1008}],1182:[function(require,module,exports){ +},{"mouse-change":241,"mouse-wheel":245}],435:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78306,7 +75832,7 @@ function createAxes2D(scene) { module.exports = createAxes2D; -},{"../../lib/html2unicode":1126,"../../lib/str2rgbarray":1139,"../../plotly":1147}],1183:[function(require,module,exports){ +},{"../../lib/html2unicode":380,"../../lib/str2rgbarray":392,"../../plotly":400}],436:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78419,7 +75945,7 @@ exports.toSVG = function(gd) { } }; -},{"../../constants/xmlns_namespaces":1115,"../cartesian/attributes":1149,"../plots":1199,"./scene2d":1184}],1184:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":369,"../cartesian/attributes":402,"../plots":452,"./scene2d":437}],437:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -78956,7 +76482,7 @@ proto.hoverFormatter = function(axisName, val) { return Axes.tickText(axis, axis.c2l(val), 'hover').text; }; -},{"../../lib/html2unicode":1126,"../../lib/show_no_webgl_msg":1137,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"./camera":1181,"./convert":1182,"gl-plot2d":452,"gl-select-box":937,"gl-spikes2d":938}],1185:[function(require,module,exports){ +},{"../../lib/html2unicode":380,"../../lib/show_no_webgl_msg":390,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"./camera":434,"./convert":435,"gl-plot2d":165,"gl-select-box":195,"gl-spikes2d":215}],438:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79199,7 +76725,7 @@ function createCamera(element, options) { return camera; } -},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],1186:[function(require,module,exports){ +},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],439:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79333,7 +76859,7 @@ function initAxes(gd, sceneLayout) { } } -},{"../../constants/xmlns_namespaces":1115,"../plots":1199,"./layout/attributes":1187,"./layout/defaults":1191,"./layout/layout_attributes":1192,"./scene":1196,"./set_convert":1197}],1187:[function(require,module,exports){ +},{"../../constants/xmlns_namespaces":369,"../plots":452,"./layout/attributes":440,"./layout/defaults":444,"./layout/layout_attributes":445,"./scene":449,"./set_convert":450}],440:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79354,7 +76880,7 @@ module.exports = { } }; -},{}],1188:[function(require,module,exports){ +},{}],441:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79460,7 +76986,7 @@ module.exports = { zerolinewidth: axesAttrs.zerolinewidth }; -},{"../../../components/color":1048,"../../../lib/extend":1122,"../../cartesian/layout_attributes":1159}],1189:[function(require,module,exports){ +},{"../../../components/color":303,"../../../lib/extend":376,"../../cartesian/layout_attributes":412}],442:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79529,7 +77055,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) { } }; -},{"../../../lib":1127,"../../cartesian/axis_defaults":1151,"./axis_attributes":1188,"tinycolor2":1042}],1190:[function(require,module,exports){ +},{"../../../lib":381,"../../cartesian/axis_defaults":404,"./axis_attributes":441,"tinycolor2":274}],443:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79685,7 +77211,7 @@ function createAxesOptions(plotlyOptions) { module.exports = createAxesOptions; -},{"../../../lib/html2unicode":1126,"../../../lib/str2rgbarray":1139,"arraytools":64}],1191:[function(require,module,exports){ +},{"../../../lib/html2unicode":380,"../../../lib/str2rgbarray":392,"arraytools":49}],444:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79792,7 +77318,7 @@ function handleGl3dDefaults(sceneLayoutIn, sceneLayoutOut, coerce, opts) { coerce('hovermode', opts.getDfltFromLayout('hovermode')); } -},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1189,"./layout_attributes":1192}],1192:[function(require,module,exports){ +},{"../../../components/color":303,"../../subplot_defaults":458,"./axis_defaults":442,"./layout_attributes":445}],445:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79920,7 +77446,7 @@ module.exports = { } }; -},{"../../../lib/extend":1122,"./axis_attributes":1188}],1193:[function(require,module,exports){ +},{"../../../lib/extend":376,"./axis_attributes":441}],446:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -79966,7 +77492,7 @@ function createSpikeOptions(layout) { module.exports = createSpikeOptions; -},{"../../../lib/str2rgbarray":1139}],1194:[function(require,module,exports){ +},{"../../../lib/str2rgbarray":392}],447:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80061,7 +77587,7 @@ function computeTickMarks(scene) { scene.contourLevels = contourLevelsFromTicks(ticks); } -},{"../../../lib/html2unicode":1126,"../../../plotly":1147}],1195:[function(require,module,exports){ +},{"../../../lib/html2unicode":380,"../../../plotly":400}],448:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80095,7 +77621,7 @@ function project(camera, v) { module.exports = project; -},{}],1196:[function(require,module,exports){ +},{}],449:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80281,7 +77807,7 @@ function initializeGLPlot(scene, fullLayout, canvas, gl) { if(!scene.staticMode) { scene.glplot.canvas.addEventListener('webglcontextlost', function(ev) { - Lib.warn('Lost WebGL context.'); + console.log('lost context'); ev.preventDefault(); }); } @@ -80379,7 +77905,7 @@ proto.recoverContext = function() { return; } if(!initializeGLPlot(scene, scene.fullLayout, canvas, gl)) { - Lib.error('Catastrophic and unrecoverable WebGL error. Context lost.'); + console.error('catastrophic/unrecoverable webgl error. context lost.'); return; } scene.plot.apply(scene, scene.plotArgs); @@ -80824,7 +78350,7 @@ proto.toImage = function(format) { module.exports = Scene; -},{"../../lib":1127,"../../lib/show_no_webgl_msg":1137,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/plots":1199,"./camera":1185,"./layout/convert":1190,"./layout/spikes":1193,"./layout/tick_marks":1194,"./project":1195,"./set_convert":1197,"gl-plot3d":626}],1197:[function(require,module,exports){ +},{"../../lib":381,"../../lib/show_no_webgl_msg":390,"../../lib/str2rgbarray":392,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"../../plots/plots":452,"./camera":438,"./layout/convert":443,"./layout/spikes":446,"./layout/tick_marks":447,"./project":448,"./set_convert":450,"gl-plot3d":183}],450:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -80846,7 +78372,7 @@ module.exports = function setConvert(containerOut) { containerOut.setScale = noop; }; -},{"../cartesian/axes":1150}],1198:[function(require,module,exports){ +},{"../cartesian/axes":403}],451:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81005,12 +78531,11 @@ module.exports = { 'annotations': 'Annotations', 'shapes': 'Shapes', 'images': 'Images', - 'ternary': 'ternary', - 'mapbox': 'mapbox' + 'ternary': 'ternary' } }; -},{"../components/color/attributes":1047,"../plotly":1147,"./font_attributes":1168}],1199:[function(require,module,exports){ +},{"../components/color/attributes":302,"../plotly":400,"./font_attributes":421}],452:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -81055,7 +78580,7 @@ plots.fontWeight = 'normal'; */ plots.register = function(_module, thisType, categoriesIn, meta) { if(modules[thisType]) { - Lib.log('Type ' + thisType + ' already registered'); + console.log('type ' + thisType + ' already registered'); return; } @@ -81084,7 +78609,7 @@ function getTraceType(traceType) { plots.getModule = function(trace) { if(trace.r !== undefined) { - Lib.warn('Tried to put a polar trace ' + + console.log('Oops, tried to put a polar trace ' + 'on an incompatible graph of cartesian ' + 'data. Ignoring this dataset.', trace ); @@ -81112,7 +78637,7 @@ plots.traceIs = function traceIs(traceType, category) { if(!_module) { if(traceType !== undefined) { - Lib.log('Unrecognized trace type ' + traceType + '.'); + console.warn('unrecognized trace type ' + traceType); } _module = modules[plots.attributes.type.dflt]; } @@ -81146,7 +78671,7 @@ plots.registerSubplot = function(_module) { var plotType = _module.name; if(subplotsRegistry[plotType]) { - Lib.log('Plot type ' + plotType + ' already registered.'); + console.log('plot type ' + plotType + ' already registered'); return; } @@ -82116,7 +79641,7 @@ plots.graphJson = function(gd, dataonly, mode, output, useDefaults) { return (output === 'object') ? obj : JSON.stringify(obj); }; -},{"../components/color":1048,"../lib":1127,"../plotly":1147,"./attributes":1148,"./font_attributes":1168,"./layout_attributes":1198,"d3":82,"fast-isnumeric":90}],1200:[function(require,module,exports){ +},{"../components/color":303,"../lib":381,"../plotly":400,"./attributes":401,"./font_attributes":421,"./layout_attributes":451,"d3":113,"fast-isnumeric":117}],453:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82141,7 +79666,7 @@ module.exports = { } }; -},{"../../traces/scatter/attributes":1301}],1201:[function(require,module,exports){ +},{"../../traces/scatter/attributes":554}],454:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -82256,7 +79781,7 @@ module.exports = { } }; -},{"../../lib/extend":1122,"../cartesian/layout_attributes":1159}],1202:[function(require,module,exports){ +},{"../../lib/extend":376,"../cartesian/layout_attributes":412}],455:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83679,7 +81204,7 @@ var extendDeepAll = Plotly.Lib.extendDeepAll; return exports; }; -},{"../../plotly":1147,"./micropolar_manager":1203,"d3":82}],1203:[function(require,module,exports){ +},{"../../plotly":400,"./micropolar_manager":456,"d3":113}],456:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83732,9 +81257,11 @@ manager.framework = function(_gd) { (function(_configClone, _previousConfigClone) { undoManager.add({ undo: function() { + //console.log('undo', _previousConfigClone); if(_previousConfigClone) that(_previousConfigClone); }, redo: function() { + //console.log('redo', _configClone); that(_configClone); } }); @@ -83762,7 +81289,7 @@ manager.fillLayout = function(_gd) { _gd._fullLayout = extendDeepAll(dflts, _gd.layout); }; -},{"../../plotly":1147,"./undo_manager":1204,"d3":82}],1204:[function(require,module,exports){ +},{"../../plotly":400,"./undo_manager":457,"d3":113}],457:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83828,7 +81355,7 @@ module.exports = function UndoManager() { }; }; -},{}],1205:[function(require,module,exports){ +},{}],458:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83903,7 +81430,7 @@ module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, o } }; -},{"../lib":1127,"./plots":1199}],1206:[function(require,module,exports){ +},{"../lib":381,"./plots":452}],459:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83944,7 +81471,7 @@ exports.plot = function plotTernary(gd) { for(var i = 0; i < ternaryIds.length; i++) { var ternaryId = ternaryIds[i], fullTernaryData = Plots.getSubplotData(fullData, 'ternary', ternaryId), - ternary = fullLayout[ternaryId]._subplot; + ternary = fullLayout[ternaryId]._ternary; // If ternary is not instantiated, create one! if(ternary === undefined) { @@ -83956,7 +81483,7 @@ exports.plot = function plotTernary(gd) { fullLayout ); - fullLayout[ternaryId]._subplot = ternary; + fullLayout[ternaryId]._ternary = ternary; } ternary.plot(fullTernaryData, fullLayout, gd._promises); @@ -83968,7 +81495,7 @@ exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) for(var i = 0; i < oldTernaryKeys.length; i++) { var oldTernaryKey = oldTernaryKeys[i]; - var oldTernary = oldFullLayout[oldTernaryKey]._subplot; + var oldTernary = oldFullLayout[oldTernaryKey]._ternary; if(!newFullLayout[oldTernaryKey] && !!oldTernary) { oldTernary.plotContainer.remove(); @@ -83977,7 +81504,7 @@ exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) } }; -},{"../../plots/plots":1199,"./layout/attributes":1207,"./layout/defaults":1210,"./layout/layout_attributes":1211,"./ternary":1212}],1207:[function(require,module,exports){ +},{"../../plots/plots":452,"./layout/attributes":460,"./layout/defaults":463,"./layout/layout_attributes":464,"./ternary":465}],460:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -83998,7 +81525,7 @@ module.exports = { } }; -},{}],1208:[function(require,module,exports){ +},{}],461:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84057,7 +81584,7 @@ module.exports = { } }; -},{"../../../lib/extend":1122,"../../cartesian/layout_attributes":1159}],1209:[function(require,module,exports){ +},{"../../../lib/extend":376,"../../cartesian/layout_attributes":412}],462:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84141,7 +81668,7 @@ module.exports = function supplyLayoutDefaults(containerIn, containerOut, option } }; -},{"../../../lib":1127,"../../cartesian/tick_label_defaults":1165,"../../cartesian/tick_mark_defaults":1166,"../../cartesian/tick_value_defaults":1167,"./axis_attributes":1208,"tinycolor2":1042}],1210:[function(require,module,exports){ +},{"../../../lib":381,"../../cartesian/tick_label_defaults":418,"../../cartesian/tick_mark_defaults":419,"../../cartesian/tick_value_defaults":420,"./axis_attributes":461,"tinycolor2":274}],463:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84204,7 +81731,7 @@ function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, option } } -},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1209,"./layout_attributes":1211}],1211:[function(require,module,exports){ +},{"../../../components/color":303,"../../subplot_defaults":458,"./axis_defaults":462,"./layout_attributes":464}],464:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84260,7 +81787,7 @@ module.exports = { caxis: ternaryAxesAttrs }; -},{"../../../components/color/attributes":1047,"./axis_attributes":1208}],1212:[function(require,module,exports){ +},{"../../../components/color/attributes":302,"./axis_attributes":461}],465:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -84938,6 +82465,19 @@ proto.initInteractions = function() { dragger.onclick = function(evt) { fx.click(gd, evt); }; + + // make a fake plotinfo for fx.hover + // it hardly uses it, could probably be refactored out... + // but specifying subplot by name does seem nice for js applications + // that want to hook into this. + if(!gd._fullLayout._plots) gd._fullLayout._plots = {}; + gd._fullLayout._plots[_this.id] = { + overlays: [], + xaxis: _this.xaxis, + yaxis: _this.yaxis, + x: function() { return _this.xaxis; }, + y: function() { return _this.yaxis; } + }; }; function removeZoombox(gd) { @@ -84946,7 +82486,7 @@ function removeZoombox(gd) { .remove(); } -},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/extend":1122,"../../lib/filter_visible":1123,"../../plotly":1147,"../cartesian/axes":1150,"../cartesian/constants":1155,"../cartesian/graph_interact":1157,"../cartesian/select":1163,"../cartesian/set_convert":1164,"d3":82,"tinycolor2":1042}],1213:[function(require,module,exports){ +},{"../../components/color":303,"../../components/dragelement":323,"../../components/drawing":325,"../../components/titles":365,"../../lib":381,"../../lib/extend":376,"../../lib/filter_visible":377,"../../plotly":400,"../cartesian/axes":403,"../cartesian/constants":408,"../cartesian/graph_interact":410,"../cartesian/select":416,"../cartesian/set_convert":417,"d3":113,"tinycolor2":274}],466:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85102,7 +82642,7 @@ module.exports = function clonePlot(graphObj, options) { return plotTile; }; -},{"../plotly":1147}],1214:[function(require,module,exports){ +},{"../plotly":400}],467:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85168,7 +82708,7 @@ function downloadImage(gd, opts) { module.exports = downloadImage; -},{"../lib":1127,"../plot_api/to_image":1146,"./filesaver":1215}],1215:[function(require,module,exports){ +},{"../lib":381,"../plot_api/to_image":399,"./filesaver":468}],468:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85236,7 +82776,7 @@ var fileSaver = function(url, name) { module.exports = fileSaver; -},{}],1216:[function(require,module,exports){ +},{}],469:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85281,7 +82821,7 @@ var Snapshot = { module.exports = Snapshot; -},{"./cloneplot":1213,"./download":1214,"./svgtoimg":1217,"./toimage":1218,"./tosvg":1219}],1217:[function(require,module,exports){ +},{"./cloneplot":466,"./download":467,"./svgtoimg":470,"./toimage":471,"./tosvg":472}],470:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85370,7 +82910,7 @@ function svgToImg(opts) { imgData = canvas.toDataURL('image/webp'); break; case 'svg': - imgData = url; + imgData = svg; break; default: reject(new Error('Image format is not jpeg, png or svg')); @@ -85412,7 +82952,7 @@ function svgToImg(opts) { module.exports = svgToImg; -},{"../lib":1127,"events":69}],1218:[function(require,module,exports){ +},{"../lib":381,"events":55}],471:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85491,7 +83031,7 @@ function toImage(gd, opts) { module.exports = toImage; -},{"../lib":1127,"../plotly":1147,"events":69}],1219:[function(require,module,exports){ +},{"../lib":381,"../plotly":400,"events":55}],472:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85572,12 +83112,24 @@ module.exports = function toSVG(gd, format) { return; } - // Font family styles break things because of quotation marks, - // so we must remove them *after* the SVG DOM has been serialized - // to a string (browsers convert singles back) + // I've seen font-family styles with non-escaped double quotes in them - breaks the + // serialized svg because the style attribute itself is double-quoted! + // Is this an IE thing? Any other attributes or style elements that can have quotes in them? + // TODO: this looks like a noop right now - what happened to it? + + /* + * Font-family styles with double quotes in them breaks the to-image + * step in FF42 because the style attribute itself is wrapped in + * double quotes. See: + * + * - http://codepen.io/etpinard/pen/bEdQWK + * - https://github.com/plotly/plotly.js/pull/104 + * + * for more info. + */ var ff = txt.style('font-family'); if(ff && ff.indexOf('"') !== -1) { - txt.style('font-family', ff.replace(/"/g, 'TOBESTRIPPED')); + txt.style('font-family', ff.replace(/"/g, '\\\'')); } }); @@ -85597,13 +83149,10 @@ module.exports = function toSVG(gd, format) { s = svgTextUtils.html_entity_decode(s); s = svgTextUtils.xml_entity_encode(s); - // Fix quotations around font strings - s = s.replace(/("TOBESTRIPPED)|(TOBESTRIPPED")/g, '\''); - return s; }; -},{"../components/color":1048,"../components/drawing":1071,"../constants/xmlns_namespaces":1115,"../lib/svg_text_utils":1140,"d3":82}],1220:[function(require,module,exports){ +},{"../components/color":303,"../components/drawing":325,"../constants/xmlns_namespaces":369,"../lib/svg_text_utils":393,"d3":113}],473:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85631,7 +83180,7 @@ module.exports = function arraysToCalcdata(cd) { mergeArray(markerLine.width, cd, 'mlw'); }; -},{"../../lib":1127}],1221:[function(require,module,exports){ +},{"../../lib":381}],474:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85642,12 +83191,10 @@ module.exports = function arraysToCalcdata(cd) { 'use strict'; -var scatterAttrs = require('../scatter/attributes'); -var colorAttributes = require('../../components/colorscale/color_attributes'); -var extendFlat = require('../../lib/extend').extendFlat; +var scatterAttrs = require('../scatter/attributes'), + scatterMarkerAttrs = scatterAttrs.marker, + scatterMarkerLineAttrs = scatterMarkerAttrs.line; -var scatterMarkerAttrs = scatterAttrs.marker; -var scatterMarkerLineAttrs = scatterMarkerAttrs.line; module.exports = { x: scatterAttrs.x, @@ -85663,14 +83210,26 @@ module.exports = { values: ['v', 'h'], }, - marker: extendFlat({}, { + marker: { + color: scatterMarkerAttrs.color, + colorscale: scatterMarkerAttrs.colorscale, + cauto: scatterMarkerAttrs.cauto, + cmax: scatterMarkerAttrs.cmax, + cmin: scatterMarkerAttrs.cmin, + autocolorscale: scatterMarkerAttrs.autocolorscale, + reversescale: scatterMarkerAttrs.reversescale, showscale: scatterMarkerAttrs.showscale, - line: extendFlat({}, - {width: scatterMarkerLineAttrs.width}, - colorAttributes('marker.line') - )}, - colorAttributes('marker') - ), + line: { + color: scatterMarkerLineAttrs.color, + colorscale: scatterMarkerLineAttrs.colorscale, + cauto: scatterMarkerLineAttrs.cauto, + cmax: scatterMarkerLineAttrs.cmax, + cmin: scatterMarkerLineAttrs.cmin, + width: scatterMarkerLineAttrs.width, + autocolorscale: scatterMarkerLineAttrs.autocolorscale, + reversescale: scatterMarkerLineAttrs.reversescale + } + }, r: scatterAttrs.r, t: scatterAttrs.t, @@ -85691,7 +83250,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../scatter/attributes":1301}],1222:[function(require,module,exports){ +},{"../scatter/attributes":554}],475:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85750,7 +83309,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1223:[function(require,module,exports){ +},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":315,"../../plots/cartesian/axes":403,"fast-isnumeric":117}],476:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85792,7 +83351,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'}); }; -},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"../scatter/xy_defaults":1324,"./attributes":1221}],1224:[function(require,module,exports){ +},{"../../components/color":303,"../../components/errorbars/defaults":330,"../../lib":381,"../bar/style_defaults":484,"../scatter/xy_defaults":575,"./attributes":474}],477:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85883,7 +83442,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return [pointData]; }; -},{"../../components/color":1048,"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157}],1225:[function(require,module,exports){ +},{"../../components/color":303,"../../components/errorbars":331,"../../plots/cartesian/graph_interact":410}],478:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85919,7 +83478,7 @@ Bar.meta = { module.exports = Bar; -},{"../../plots/cartesian":1158,"../scatter/colorbar":1304,"./arrays_to_calcdata":1220,"./attributes":1221,"./calc":1222,"./defaults":1223,"./hover":1224,"./layout_attributes":1226,"./layout_defaults":1227,"./plot":1228,"./set_positions":1229,"./style":1230}],1226:[function(require,module,exports){ +},{"../../plots/cartesian":411,"../scatter/colorbar":557,"./arrays_to_calcdata":473,"./attributes":474,"./calc":475,"./defaults":476,"./hover":477,"./layout_attributes":479,"./layout_defaults":480,"./plot":481,"./set_positions":482,"./style":483}],479:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -85963,7 +83522,7 @@ module.exports = { } }; -},{}],1227:[function(require,module,exports){ +},{}],480:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86021,7 +83580,7 @@ module.exports = function(layoutIn, layoutOut, fullData) { coerce('bargroupgap'); }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"./layout_attributes":1226}],1228:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"../../plots/plots":452,"./layout_attributes":479}],481:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86133,7 +83692,7 @@ module.exports = function plot(gd, plotinfo, cdbar) { }; -},{"../../components/color":1048,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1220,"d3":82,"fast-isnumeric":90}],1229:[function(require,module,exports){ +},{"../../components/color":303,"../../components/errorbars":331,"../../lib":381,"./arrays_to_calcdata":473,"d3":113,"fast-isnumeric":117}],482:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86347,7 +83906,7 @@ module.exports = function setPositions(gd, plotinfo) { }); }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"fast-isnumeric":90}],1230:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"../../plots/plots":452,"fast-isnumeric":117}],483:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86426,7 +83985,7 @@ module.exports = function style(gd) { s.call(ErrorBars.style); }; -},{"../../components/color":1048,"../../components/drawing":1071,"../../components/errorbars":1077,"d3":82}],1231:[function(require,module,exports){ +},{"../../components/color":303,"../../components/drawing":325,"../../components/errorbars":331,"d3":113}],484:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86463,7 +84022,7 @@ module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, default coerce('marker.line.width'); }; -},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061}],1232:[function(require,module,exports){ +},{"../../components/color":303,"../../components/colorscale/defaults":312,"../../components/colorscale/has_colorscale":315}],485:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86594,7 +84153,7 @@ module.exports = { fillcolor: scatterAttrs.fillcolor }; -},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../scatter/attributes":1301}],1233:[function(require,module,exports){ +},{"../../components/color/attributes":302,"../../lib/extend":376,"../scatter/attributes":554}],486:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86743,7 +84302,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1234:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"fast-isnumeric":117}],487:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86812,7 +84371,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) { } }; -},{"../../components/color":1048,"../../lib":1127,"./attributes":1232}],1235:[function(require,module,exports){ +},{"../../components/color":303,"../../lib":381,"./attributes":485}],488:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86921,7 +84480,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return closeData; }; -},{"../../components/color":1048,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157}],1236:[function(require,module,exports){ +},{"../../components/color":303,"../../lib":381,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410}],489:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86954,7 +84513,7 @@ Box.meta = { module.exports = Box; -},{"../../plots/cartesian":1158,"./attributes":1232,"./calc":1233,"./defaults":1234,"./hover":1235,"./layout_attributes":1237,"./layout_defaults":1238,"./plot":1239,"./set_positions":1240,"./style":1241}],1237:[function(require,module,exports){ +},{"../../plots/cartesian":411,"./attributes":485,"./calc":486,"./defaults":487,"./hover":488,"./layout_attributes":490,"./layout_defaults":491,"./plot":492,"./set_positions":493,"./style":494}],490:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -86992,7 +84551,7 @@ module.exports = { } }; -},{}],1238:[function(require,module,exports){ +},{}],491:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87026,7 +84585,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) { coerce('boxgroupgap'); }; -},{"../../lib":1127,"../../plots/plots":1199,"./layout_attributes":1237}],1239:[function(require,module,exports){ +},{"../../lib":381,"../../plots/plots":452,"./layout_attributes":490}],492:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87253,7 +84812,7 @@ module.exports = function plot(gd, plotinfo, cdbox) { }); }; -},{"../../components/drawing":1071,"../../lib":1127,"d3":82}],1240:[function(require,module,exports){ +},{"../../components/drawing":325,"../../lib":381,"d3":113}],493:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87346,7 +84905,7 @@ module.exports = function setPositions(gd, plotinfo) { } }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199}],1241:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"../../plots/plots":452}],494:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87385,7 +84944,7 @@ module.exports = function style(gd) { }); }; -},{"../../components/color":1048,"../../components/drawing":1071,"d3":82}],1242:[function(require,module,exports){ +},{"../../components/color":303,"../../components/drawing":325,"d3":113}],495:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87403,7 +84962,7 @@ var extendFlat = require('../../lib/extend').extendFlat; var ScatterGeoMarkerLineAttrs = ScatterGeoAttrs.marker.line; -module.exports = extendFlat({}, { +module.exports = { locations: { valType: 'data_array', @@ -87423,17 +84982,22 @@ module.exports = extendFlat({}, { width: ScatterGeoMarkerLineAttrs.width } }, + zauto: colorscaleAttrs.zauto, + zmin: colorscaleAttrs.zmin, + zmax: colorscaleAttrs.zmax, + colorscale: colorscaleAttrs.colorscale, + autocolorscale: colorscaleAttrs.autocolorscale, + reversescale: colorscaleAttrs.reversescale, + showscale: colorscaleAttrs.showscale, hoverinfo: extendFlat({}, plotAttrs.hoverinfo, { flags: ['location', 'z', 'text', 'name'] }), _nestedModules: { 'colorbar': 'Colorbar' } -}, - colorscaleAttrs -); +}; -},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../../plots/attributes":1148,"../scattergeo/attributes":1331}],1243:[function(require,module,exports){ +},{"../../components/colorscale/attributes":309,"../../lib/extend":376,"../../plots/attributes":401,"../scattergeo/attributes":582}],496:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87452,7 +85016,7 @@ module.exports = function calc(gd, trace) { colorscaleCalc(trace, trace.z, '', 'z'); }; -},{"../../components/colorscale/calc":1055}],1244:[function(require,module,exports){ +},{"../../components/colorscale/calc":310}],497:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87507,7 +85071,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('hoverinfo', (layout._dataLength === 1) ? 'location+z+text' : undefined); }; -},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1242}],1245:[function(require,module,exports){ +},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":495}],498:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87537,7 +85101,7 @@ Choropleth.meta = { module.exports = Choropleth; -},{"../../plots/geo":1171,"../heatmap/colorbar":1259,"./attributes":1242,"./calc":1243,"./defaults":1244,"./plot":1246}],1246:[function(require,module,exports){ +},{"../../plots/geo":424,"../heatmap/colorbar":512,"./attributes":495,"./calc":496,"./defaults":497,"./plot":499}],499:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87758,7 +85322,7 @@ function makeEventDataFunc(trace) { }; } -},{"../../components/color":1048,"../../components/colorscale/get_scale":1060,"../../components/colorscale/make_scale_function":1065,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/geo/constants":1169,"./attributes":1242,"d3":82}],1247:[function(require,module,exports){ +},{"../../components/color":303,"../../components/colorscale/get_scale":314,"../../components/colorscale/make_scale_function":319,"../../components/drawing":325,"../../lib/array_to_calc_item":372,"../../lib/geo_location_utils":378,"../../lib/topojson_utils":394,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"../../plots/geo/constants":422,"./attributes":495,"d3":113}],500:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87771,94 +85335,97 @@ function makeEventDataFunc(trace) { var heatmapAttrs = require('../heatmap/attributes'); var scatterAttrs = require('../scatter/attributes'); -var colorscaleAttrs = require('../../components/colorscale/attributes'); var extendFlat = require('../../lib/extend').extendFlat; var scatterLineAttrs = scatterAttrs.line; -module.exports = extendFlat({}, - { - z: heatmapAttrs.z, - x: heatmapAttrs.x, - x0: heatmapAttrs.x0, - dx: heatmapAttrs.dx, - y: heatmapAttrs.y, - y0: heatmapAttrs.y0, - dy: heatmapAttrs.dy, - text: heatmapAttrs.text, - transpose: heatmapAttrs.transpose, - xtype: heatmapAttrs.xtype, - ytype: heatmapAttrs.ytype, - - connectgaps: heatmapAttrs.connectgaps, - - autocontour: { - valType: 'boolean', - dflt: true, +module.exports = { + z: heatmapAttrs.z, + x: heatmapAttrs.x, + x0: heatmapAttrs.x0, + dx: heatmapAttrs.dx, + y: heatmapAttrs.y, + y0: heatmapAttrs.y0, + dy: heatmapAttrs.dy, + text: heatmapAttrs.text, + transpose: heatmapAttrs.transpose, + xtype: heatmapAttrs.xtype, + ytype: heatmapAttrs.ytype, + + zauto: heatmapAttrs.zauto, + zmin: heatmapAttrs.zmin, + zmax: heatmapAttrs.zmax, + colorscale: heatmapAttrs.colorscale, + autocolorscale: heatmapAttrs.autocolorscale, + reversescale: heatmapAttrs.reversescale, + showscale: heatmapAttrs.showscale, + + connectgaps: heatmapAttrs.connectgaps, + + autocontour: { + valType: 'boolean', + dflt: true, + + + }, + ncontours: { + valType: 'integer', + dflt: 0, + + + }, + + contours: { + start: { + valType: 'number', + dflt: null, }, - ncontours: { - valType: 'integer', - dflt: 0, + end: { + valType: 'number', + dflt: null, }, - - contours: { - start: { - valType: 'number', - dflt: null, - - - }, - end: { - valType: 'number', - dflt: null, - - - }, - size: { - valType: 'number', - dflt: null, - - - }, - coloring: { - valType: 'enumerated', - values: ['fill', 'heatmap', 'lines', 'none'], - dflt: 'fill', - - - }, - showlines: { - valType: 'boolean', - dflt: true, - - - } + size: { + valType: 'number', + dflt: null, + + }, - - line: { - color: extendFlat({}, scatterLineAttrs.color, { - - }), - width: scatterLineAttrs.width, - dash: scatterLineAttrs.dash, - smoothing: extendFlat({}, scatterLineAttrs.smoothing, { - - }) + coloring: { + valType: 'enumerated', + values: ['fill', 'heatmap', 'lines', 'none'], + dflt: 'fill', + + }, - - _nestedModules: { - 'colorbar': 'Colorbar' + showlines: { + valType: 'boolean', + dflt: true, + + } }, - colorscaleAttrs, - {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} -); -},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../scatter/attributes":1301}],1248:[function(require,module,exports){ + line: { + color: extendFlat({}, scatterLineAttrs.color, { + + }), + width: scatterLineAttrs.width, + dash: scatterLineAttrs.dash, + smoothing: extendFlat({}, scatterLineAttrs.smoothing, { + + }) + }, + + _nestedModules: { + 'colorbar': 'Colorbar' + } +}; + +},{"../../lib/extend":376,"../heatmap/attributes":510,"../scatter/attributes":554}],501:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87911,7 +85478,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../plots/cartesian/axes":1150,"../heatmap/calc":1258}],1249:[function(require,module,exports){ +},{"../../plots/cartesian/axes":403,"../heatmap/calc":511}],502:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -87972,7 +85539,7 @@ module.exports = function colorbar(gd, cd) { .options(trace.colorbar)(); }; -},{"../../components/colorbar/draw":1051,"../../plots/plots":1199,"./make_color_map":1253}],1250:[function(require,module,exports){ +},{"../../components/colorbar/draw":306,"../../plots/plots":452,"./make_color_map":506}],503:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88016,7 +85583,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout handleStyleDefaults(traceIn, traceOut, coerce, layout); }; -},{"../../lib":1127,"../contour/style_defaults":1256,"../heatmap/has_columns":1262,"../heatmap/xyz_defaults":1268,"./attributes":1247}],1251:[function(require,module,exports){ +},{"../../lib":381,"../contour/style_defaults":509,"../heatmap/has_columns":515,"../heatmap/xyz_defaults":521,"./attributes":500}],504:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88035,7 +85602,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return heatmapHoverPoints(pointData, xval, yval, hovermode, true); }; -},{"../heatmap/hover":1263}],1252:[function(require,module,exports){ +},{"../heatmap/hover":516}],505:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88067,7 +85634,7 @@ Contour.meta = { module.exports = Contour; -},{"../../plots/cartesian":1158,"./attributes":1247,"./calc":1248,"./colorbar":1249,"./defaults":1250,"./hover":1251,"./plot":1254,"./style":1255}],1253:[function(require,module,exports){ +},{"../../plots/cartesian":411,"./attributes":500,"./calc":501,"./colorbar":502,"./defaults":503,"./hover":504,"./plot":507,"./style":508}],506:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88147,7 +85714,7 @@ module.exports = function makeColorMap(trace) { return colorMap; }; -},{"../../components/colorscale/get_scale":1060,"d3":82}],1254:[function(require,module,exports){ +},{"../../components/colorscale/get_scale":314,"d3":113}],507:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88201,6 +85768,7 @@ var BOTTOMSTART = [1, 9, 13, 104, 713], SADDLEREMAINDER = {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11}; function plotOne(gd, plotinfo, cd) { + Lib.markTime('in Contour.plot'); var trace = cd[0].trace, x = cd[0].x, y = cd[0].y, @@ -88252,6 +85820,8 @@ function plotOne(gd, plotinfo, cd) { makeFills(plotGroup, pathinfo, perimeter, contours); makeLines(plotGroup, pathinfo, contours); clipGaps(plotGroup, plotinfo, cd[0], perimeter); + + Lib.markTime('done Contour.plot'); } function emptyPathinfo(contours, plotinfo, cd0) { @@ -88385,7 +85955,7 @@ function makePath(pi, loc, edgeflag) { marchStep = NEWDELTA[mi]; if(!marchStep) { - Lib.log('Found bad marching index:', mi, loc, pi.level); + console.log('found bad marching index', mi, loc, pi.level); break; } @@ -88409,7 +85979,7 @@ function makePath(pi, loc, edgeflag) { } if(cnt === 10000) { - Lib.log('Infinite loop in contour?'); + console.log('Infinite loop in contour?'); } var closedpath = equalPts(pts[0], pts[pts.length - 1]), totaldist = 0, @@ -88493,7 +86063,7 @@ function makePath(pi, loc, edgeflag) { } else { if(!edgeflag) { - Lib.log('Unclosed interior contour?', + console.log('unclosed interior contour?', pi.level, startLocStr, pts.join('L')); } @@ -88560,7 +86130,7 @@ function findAllPaths(pathinfo) { startLoc = Object.keys(pi.crossings)[0].split(',').map(Number); makePath(pi, startLoc); } - if(cnt === 10000) Lib.log('Infinite loop in contour?'); + if(cnt === 10000) console.log('Infinite loop in contour?'); } } @@ -88695,7 +86265,7 @@ function joinAllPaths(pi, perimeter) { //now loop through sides, moving our endpoint until we find a new start for(cnt = 0; cnt < 4; cnt++) { // just to prevent infinite loops if(!endpt) { - Lib.log('Missing end?', i, pi); + console.log('missing end?', i, pi); break; } @@ -88722,7 +86292,7 @@ function joinAllPaths(pi, perimeter) { } } else { - Lib.log('endpt to newendpt is not vert. or horz.', + console.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew); } } @@ -88734,7 +86304,7 @@ function joinAllPaths(pi, perimeter) { } if(nexti === pi.edgepaths.length) { - Lib.log('unclosed perimeter path'); + console.log('unclosed perimeter path'); break; } @@ -88857,7 +86427,7 @@ function makeClipMask(cd0) { return z; } -},{"../../components/drawing":1071,"../../lib":1127,"../heatmap/plot":1266,"d3":82}],1255:[function(require,module,exports){ +},{"../../components/drawing":325,"../../lib":381,"../heatmap/plot":519,"d3":113}],508:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88914,7 +86484,7 @@ module.exports = function style(gd) { heatmapStyle(gd); }; -},{"../../components/drawing":1071,"../heatmap/style":1267,"./make_color_map":1253,"d3":82}],1256:[function(require,module,exports){ +},{"../../components/drawing":325,"../heatmap/style":520,"./make_color_map":506,"d3":113}],509:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88950,7 +86520,7 @@ module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout) } }; -},{"../../components/colorscale/defaults":1058}],1257:[function(require,module,exports){ +},{"../../components/colorscale/defaults":312}],510:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -88966,63 +86536,68 @@ var colorscaleAttrs = require('../../components/colorscale/attributes'); var extendFlat = require('../../lib/extend').extendFlat; -module.exports = extendFlat({}, - { - z: { - valType: 'data_array', - - }, - x: scatterAttrs.x, - x0: scatterAttrs.x0, - dx: scatterAttrs.dx, - y: scatterAttrs.y, - y0: scatterAttrs.y0, - dy: scatterAttrs.dy, - text: { - valType: 'data_array', - - }, - transpose: { - valType: 'boolean', - dflt: false, - - - }, - xtype: { - valType: 'enumerated', - values: ['array', 'scaled'], - - - }, - ytype: { - valType: 'enumerated', - values: ['array', 'scaled'], - - - }, - zsmooth: { - valType: 'enumerated', - values: ['fast', 'best', false], - dflt: false, - - - }, - connectgaps: { - valType: 'boolean', - dflt: false, - - - }, - _nestedModules: { - 'colorbar': 'Colorbar' - } +module.exports = { + z: { + valType: 'data_array', + + }, + x: scatterAttrs.x, + x0: scatterAttrs.x0, + dx: scatterAttrs.dx, + y: scatterAttrs.y, + y0: scatterAttrs.y0, + dy: scatterAttrs.dy, + text: { + valType: 'data_array', + + }, + transpose: { + valType: 'boolean', + dflt: false, + + + }, + xtype: { + valType: 'enumerated', + values: ['array', 'scaled'], + + + }, + ytype: { + valType: 'enumerated', + values: ['array', 'scaled'], + + + }, + zauto: colorscaleAttrs.zauto, + zmin: colorscaleAttrs.zmin, + zmax: colorscaleAttrs.zmax, + colorscale: colorscaleAttrs.colorscale, + autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, + {dflt: false}), + reversescale: colorscaleAttrs.reversescale, + showscale: colorscaleAttrs.showscale, + zsmooth: { + valType: 'enumerated', + values: ['fast', 'best', false], + dflt: false, + + + }, + connectgaps: { + valType: 'boolean', + dflt: false, + + }, - colorscaleAttrs, - {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} -); -},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../scatter/attributes":1301}],1258:[function(require,module,exports){ + _nestedModules: { + 'colorbar': 'Colorbar' + } +}; + +},{"../../components/colorscale/attributes":309,"../../lib/extend":376,"../scatter/attributes":554}],511:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89048,6 +86623,8 @@ var maxRowLength = require('./max_row_length'); module.exports = function calc(gd, trace) { + Lib.markTime('start convert x&y'); + // prepare the raw data // run makeCalcdata on x and y even for heatmaps, in case of category mappings var xa = Axes.getFromId(gd, trace.xaxis || 'x'), @@ -89068,6 +86645,8 @@ module.exports = function calc(gd, trace) { xa._minDtick = 0; ya._minDtick = 0; + Lib.markTime('done convert x&y'); + if(isHist) { var binned = histogram2dCalc(gd, trace); x = binned.x; @@ -89289,7 +86868,7 @@ function interp2d(z, emptyPoints, savedInterpZ) { correctionOvershoot(maxFractionalChange)); } if(maxFractionalChange > INTERPTHRESHOLD) { - Lib.log('interp2d didn\'t converge quickly', maxFractionalChange); + console.log('interp2d didn\'t converge quickly', maxFractionalChange); } return z; @@ -89458,7 +87037,7 @@ function iterateInterp2d(z, emptyPoints, overshoot) { return maxFractionalChange; } -},{"../../components/colorscale/calc":1055,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"../histogram2d/calc":1278,"./convert_column_xyz":1260,"./has_columns":1262,"./max_row_length":1265,"fast-isnumeric":90}],1259:[function(require,module,exports){ +},{"../../components/colorscale/calc":310,"../../lib":381,"../../plots/cartesian/axes":403,"../../plots/plots":452,"../histogram2d/calc":531,"./convert_column_xyz":513,"./has_columns":515,"./max_row_length":518,"fast-isnumeric":117}],512:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89502,9 +87081,11 @@ module.exports = function colorbar(gd, cd) { .range(scl.map(function(v) { return v[1]; }))) .filllevels({start: zmin, end: zmax, size: (zmax - zmin) / 254}) .options(trace.colorbar)(); + + Lib.markTime('done colorbar'); }; -},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1260:[function(require,module,exports){ +},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":314,"../../lib":381,"../../plots/plots":452,"d3":113,"fast-isnumeric":117}],513:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89561,7 +87142,7 @@ module.exports = function convertColumnXYZ(trace, xa, ya) { if(hasColumnText) trace.text = text; }; -},{"../../lib":1127}],1261:[function(require,module,exports){ +},{"../../lib":381}],514:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89599,7 +87180,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}); }; -},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1257,"./has_columns":1262,"./xyz_defaults":1268}],1262:[function(require,module,exports){ +},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":510,"./has_columns":515,"./xyz_defaults":521}],515:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89615,7 +87196,7 @@ module.exports = function(trace) { return !Array.isArray(trace.z[0]); }; -},{}],1263:[function(require,module,exports){ +},{}],516:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89656,7 +87237,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode, contour) ny = Math.round(pointData.index[0]); } catch(e) { - Lib.error('Error hovering on heatmap, ' + + console.log('Error hovering on heatmap, ' + 'pointNumber must be [row,col], found:', pointData.index); return; } @@ -89729,7 +87310,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode, contour) })]; }; -},{"../../lib":1127,"../../plots/cartesian/graph_interact":1157}],1264:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/graph_interact":410}],517:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89761,7 +87342,7 @@ Heatmap.meta = { module.exports = Heatmap; -},{"../../plots/cartesian":1158,"./attributes":1257,"./calc":1258,"./colorbar":1259,"./defaults":1261,"./hover":1263,"./plot":1266,"./style":1267}],1265:[function(require,module,exports){ +},{"../../plots/cartesian":411,"./attributes":510,"./calc":511,"./colorbar":512,"./defaults":514,"./hover":516,"./plot":519,"./style":520}],518:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89783,7 +87364,7 @@ module.exports = function maxRowLength(z) { return len; }; -},{}],1266:[function(require,module,exports){ +},{}],519:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -89814,6 +87395,8 @@ module.exports = function(gd, plotinfo, cdheatmaps) { // From http://www.xarg.org/2010/03/generate-client-side-png-files-using-javascript/ function plotOne(gd, plotinfo, cd) { + Lib.markTime('in Heatmap.plot'); + var trace = cd[0].trace, uid = trace.uid, xa = plotinfo.x(), @@ -90070,6 +87653,8 @@ function plotOne(gd, plotinfo, cd) { return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy)); } + Lib.markTime('done init png'); + if(zsmooth) { // best or fast, works fastest with imageData var pxIndex = 0, pixels = new Uint8Array(imageWidth * imageHeight * 4); @@ -90141,6 +87726,8 @@ function plotOne(gd, plotinfo, cd) { } } + Lib.markTime('done filling png'); + rcount = Math.round(rcount / pixcount); gcount = Math.round(gcount / pixcount); bcount = Math.round(bcount / pixcount); @@ -90171,9 +87758,11 @@ function plotOne(gd, plotinfo, cd) { y: top, preserveAspectRatio: 'none' }); + + Lib.markTime('done showing png'); } -},{"../../components/colorscale/get_scale":1060,"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plots/plots":1199,"./max_row_length":1265,"d3":82,"tinycolor2":1042}],1267:[function(require,module,exports){ +},{"../../components/colorscale/get_scale":314,"../../constants/xmlns_namespaces":369,"../../lib":381,"../../plots/plots":452,"./max_row_length":518,"d3":113,"tinycolor2":274}],520:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90194,7 +87783,7 @@ module.exports = function style(gd) { }); }; -},{"d3":82}],1268:[function(require,module,exports){ +},{"d3":113}],521:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90283,7 +87872,7 @@ function isValidZ(z) { return (allRowsAreArrays && oneRowIsFilled && hasOneNumber); } -},{"./has_columns":1262,"fast-isnumeric":90}],1269:[function(require,module,exports){ +},{"./has_columns":515,"fast-isnumeric":117}],522:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90292,16 +87881,16 @@ function isValidZ(z) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; var barAttrs = require('../bar/attributes'); -var colorAttributes = require('../../components/colorscale/color_attributes'); - -var extendFlat = require('../../lib/extend').extendDeep; +var extendFlat = require('../../lib').extendFlat; var barMarkerAttrs = barAttrs.marker; var barMarkerLineAttrs = barMarkerAttrs.line; + module.exports = { x: { valType: 'data_array', @@ -90360,14 +87949,26 @@ module.exports = { }, ybins: makeBinsAttr('y'), - marker: extendFlat({}, { + marker: { + color: barMarkerAttrs.color, + colorscale: barMarkerAttrs.colorscale, + cauto: barMarkerAttrs.cauto, + cmax: barMarkerAttrs.cmax, + cmin: barMarkerAttrs.cmin, + autocolorscale: barMarkerAttrs.autocolorscale, + reversescale: barMarkerAttrs.reversescale, showscale: barMarkerAttrs.showscale, - line: extendFlat({}, - {width: extendFlat({}, barMarkerLineAttrs.width, {dflt: 0})}, - colorAttributes('marker.line')) + line: { + color: barMarkerLineAttrs.color, + colorscale: barMarkerLineAttrs.colorscale, + cauto: barMarkerLineAttrs.cauto, + cmax: barMarkerLineAttrs.cmax, + cmin: barMarkerLineAttrs.cmin, + autocolorscale: barMarkerLineAttrs.autocolorscale, + reversescale: barMarkerLineAttrs.reversescale, + width: extendFlat({}, barMarkerLineAttrs.width, {dflt: 0}) + } }, - colorAttributes('marker') - ), _nestedModules: { 'error_y': 'ErrorBars', @@ -90403,7 +88004,7 @@ function makeBinsAttr(axLetter) { }; } -},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../bar/attributes":1221}],1270:[function(require,module,exports){ +},{"../../lib":381,"../bar/attributes":474}],523:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90429,7 +88030,7 @@ module.exports = function doAvg(size, counts) { return total; }; -},{}],1271:[function(require,module,exports){ +},{}],524:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90459,7 +88060,7 @@ module.exports = function handleBinDefaults(traceIn, traceOut, coerce, binDirect return traceOut; }; -},{}],1272:[function(require,module,exports){ +},{}],525:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90533,7 +88134,7 @@ module.exports = { } }; -},{"fast-isnumeric":90}],1273:[function(require,module,exports){ +},{"fast-isnumeric":117}],526:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90663,7 +88264,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./average":1270,"./bin_functions":1272,"./norm_functions":1276,"fast-isnumeric":90}],1274:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"./average":523,"./bin_functions":525,"./norm_functions":529,"fast-isnumeric":117}],527:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90715,7 +88316,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'}); }; -},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"./attributes":1269,"./bin_defaults":1271}],1275:[function(require,module,exports){ +},{"../../components/color":303,"../../components/errorbars/defaults":330,"../../lib":381,"../bar/style_defaults":484,"./attributes":522,"./bin_defaults":524}],528:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90764,7 +88365,7 @@ Histogram.meta = { module.exports = Histogram; -},{"../../plots/cartesian":1158,"../bar/hover":1224,"../bar/layout_attributes":1226,"../bar/layout_defaults":1227,"../bar/plot":1228,"../bar/set_positions":1229,"../bar/style":1230,"../scatter/colorbar":1304,"./attributes":1269,"./calc":1273,"./defaults":1274}],1276:[function(require,module,exports){ +},{"../../plots/cartesian":411,"../bar/hover":477,"../bar/layout_attributes":479,"../bar/layout_defaults":480,"../bar/plot":481,"../bar/set_positions":482,"../bar/style":483,"../scatter/colorbar":557,"./attributes":522,"./calc":526,"./defaults":527}],529:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90799,7 +88400,7 @@ module.exports = { } }; -},{}],1277:[function(require,module,exports){ +},{}],530:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90812,46 +88413,47 @@ module.exports = { var histogramAttrs = require('../histogram/attributes'); var heatmapAttrs = require('../heatmap/attributes'); -var colorscaleAttrs = require('../../components/colorscale/attributes'); -var extendFlat = require('../../lib/extend').extendFlat; - -module.exports = extendFlat({}, - { - x: histogramAttrs.x, - y: histogramAttrs.y, +module.exports = { + x: histogramAttrs.x, + y: histogramAttrs.y, - z: { + z: { + valType: 'data_array', + + }, + marker: { + color: { valType: 'data_array', - }, - marker: { - color: { - valType: 'data_array', - - } - }, + } + }, - histnorm: histogramAttrs.histnorm, - histfunc: histogramAttrs.histfunc, - autobinx: histogramAttrs.autobinx, - nbinsx: histogramAttrs.nbinsx, - xbins: histogramAttrs.xbins, - autobiny: histogramAttrs.autobiny, - nbinsy: histogramAttrs.nbinsy, - ybins: histogramAttrs.ybins, + histnorm: histogramAttrs.histnorm, + histfunc: histogramAttrs.histfunc, + autobinx: histogramAttrs.autobinx, + nbinsx: histogramAttrs.nbinsx, + xbins: histogramAttrs.xbins, + autobiny: histogramAttrs.autobiny, + nbinsy: histogramAttrs.nbinsy, + ybins: histogramAttrs.ybins, - zsmooth: heatmapAttrs.zsmooth, + zauto: heatmapAttrs.zauto, + zmin: heatmapAttrs.zmin, + zmax: heatmapAttrs.zmax, + colorscale: heatmapAttrs.colorscale, + autocolorscale: heatmapAttrs.autocolorscale, + reversescale: heatmapAttrs.reversescale, + showscale: heatmapAttrs.showscale, - _nestedModules: { - 'colorbar': 'Colorbar' - } - }, - colorscaleAttrs, - {autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale, {dflt: false})} -); + zsmooth: heatmapAttrs.zsmooth, -},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../histogram/attributes":1269}],1278:[function(require,module,exports){ + _nestedModules: { + 'colorbar': 'Colorbar' + } +}; + +},{"../heatmap/attributes":510,"../histogram/attributes":522}],531:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -90887,6 +88489,7 @@ module.exports = function calc(gd, trace) { if(x.length > serieslen) x.splice(serieslen, x.length - serieslen); if(y.length > serieslen) y.splice(serieslen, y.length - serieslen); + Lib.markTime('done convert data'); // calculate the bins if(trace.autobinx || !('xbins' in trace)) { @@ -90907,6 +88510,7 @@ module.exports = function calc(gd, trace) { } trace._input.ybins = trace.ybins; } + Lib.markTime('done autoBin'); // make the empty bin array & scale the map z = []; @@ -90990,6 +88594,7 @@ module.exports = function calc(gd, trace) { } + Lib.markTime('done making bins'); // put data into bins for(i = 0; i < serieslen; i++) { n = Lib.findBin(x[i], xbins); @@ -91005,6 +88610,7 @@ module.exports = function calc(gd, trace) { if(normfunc) { for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]); } + Lib.markTime('done binning'); return { x: x, @@ -91017,7 +88623,7 @@ module.exports = function calc(gd, trace) { }; }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../histogram/average":1270,"../histogram/bin_functions":1272,"../histogram/norm_functions":1276}],1279:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"../histogram/average":523,"../histogram/bin_functions":525,"../histogram/norm_functions":529}],532:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91050,7 +88656,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, layout) { ); }; -},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1277,"./sample_defaults":1281}],1280:[function(require,module,exports){ +},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":530,"./sample_defaults":534}],533:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91083,7 +88689,7 @@ Histogram2D.meta = { module.exports = Histogram2D; -},{"../../plots/cartesian":1158,"../heatmap/calc":1258,"../heatmap/colorbar":1259,"../heatmap/hover":1263,"../heatmap/plot":1266,"../heatmap/style":1267,"./attributes":1277,"./defaults":1279}],1281:[function(require,module,exports){ +},{"../../plots/cartesian":411,"../heatmap/calc":511,"../heatmap/colorbar":512,"../heatmap/hover":516,"../heatmap/plot":519,"../heatmap/style":520,"./attributes":530,"./defaults":532}],534:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91119,7 +88725,7 @@ module.exports = function handleSampleDefaults(traceIn, traceOut, coerce) { handleBinDefaults(traceIn, traceOut, coerce, binDirections); }; -},{"../histogram/bin_defaults":1271}],1282:[function(require,module,exports){ +},{"../histogram/bin_defaults":524}],535:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91132,11 +88738,8 @@ module.exports = function handleSampleDefaults(traceIn, traceOut, coerce) { var histogram2dAttrs = require('../histogram2d/attributes'); var contourAttrs = require('../contour/attributes'); -var colorscaleAttrs = require('../../components/colorscale/attributes'); - -var extendFlat = require('../../lib/extend').extendFlat; -module.exports = extendFlat({}, { +module.exports = { x: histogram2dAttrs.x, y: histogram2dAttrs.y, z: histogram2dAttrs.z, @@ -91151,6 +88754,14 @@ module.exports = extendFlat({}, { nbinsy: histogram2dAttrs.nbinsy, ybins: histogram2dAttrs.ybins, + zauto: contourAttrs.zauto, + zmin: contourAttrs.zmin, + zmax: contourAttrs.zmax, + colorscale: contourAttrs.colorscale, + autocolorscale: contourAttrs.autocolorscale, + reversescale: contourAttrs.reversescale, + showscale: contourAttrs.showscale, + autocontour: contourAttrs.autocontour, ncontours: contourAttrs.ncontours, contours: contourAttrs.contours, @@ -91159,11 +88770,9 @@ module.exports = extendFlat({}, { _nestedModules: { 'colorbar': 'Colorbar' } -}, - colorscaleAttrs -); +}; -},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../contour/attributes":1247,"../histogram2d/attributes":1277}],1283:[function(require,module,exports){ +},{"../contour/attributes":500,"../histogram2d/attributes":530}],536:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91199,7 +88808,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout handleStyleDefaults(traceIn, traceOut, coerce, layout); }; -},{"../../lib":1127,"../contour/style_defaults":1256,"../histogram2d/sample_defaults":1281,"./attributes":1282}],1284:[function(require,module,exports){ +},{"../../lib":381,"../contour/style_defaults":509,"../histogram2d/sample_defaults":534,"./attributes":535}],537:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91232,7 +88841,7 @@ Histogram2dContour.meta = { module.exports = Histogram2dContour; -},{"../../plots/cartesian":1158,"../contour/calc":1248,"../contour/colorbar":1249,"../contour/hover":1251,"../contour/plot":1254,"../contour/style":1255,"./attributes":1282,"./defaults":1283}],1285:[function(require,module,exports){ +},{"../../plots/cartesian":411,"../contour/calc":501,"../contour/colorbar":502,"../contour/hover":504,"../contour/plot":507,"../contour/style":508,"./attributes":535,"./defaults":536}],538:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91269,12 +88878,10 @@ module.exports = { j: { valType: 'data_array', - }, k: { valType: 'data_array', - }, delaunayaxis: { @@ -91366,7 +88973,7 @@ module.exports = { } }; -},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../surface/attributes":1348}],1286:[function(require,module,exports){ +},{"../../components/colorscale/attributes":309,"../../lib/extend":376,"../surface/attributes":599}],539:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91528,7 +89135,7 @@ function createMesh3DTrace(scene, data) { module.exports = createMesh3DTrace; -},{"../../lib/str2rgbarray":1139,"alpha-shape":46,"convex-hull":71,"delaunay-triangulate":88,"gl-mesh3d":253,"tinycolor2":1042}],1287:[function(require,module,exports){ +},{"../../lib/str2rgbarray":392,"alpha-shape":40,"convex-hull":102,"delaunay-triangulate":114,"gl-mesh3d":150,"tinycolor2":274}],540:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91625,7 +89232,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout } }; -},{"../../components/colorbar/defaults":1050,"../../lib":1127,"./attributes":1285}],1288:[function(require,module,exports){ +},{"../../components/colorbar/defaults":305,"../../lib":381,"./attributes":538}],541:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91654,7 +89261,7 @@ Mesh3D.meta = { module.exports = Mesh3D; -},{"../../plots/gl3d":1186,"../heatmap/colorbar":1259,"./attributes":1285,"./convert":1286,"./defaults":1287}],1289:[function(require,module,exports){ +},{"../../plots/gl3d":439,"../heatmap/colorbar":512,"./attributes":538,"./convert":539,"./defaults":540}],542:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91874,7 +89481,7 @@ module.exports = { } }; -},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../../plots/attributes":1148,"../../plots/font_attributes":1168}],1290:[function(require,module,exports){ +},{"../../components/color/attributes":302,"../../lib/extend":376,"../../plots/attributes":401,"../../plots/font_attributes":421}],543:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -91921,7 +89528,7 @@ function getCdModule(calcdata, _module) { return cdModule; } -},{"../../plots/plots":1199}],1291:[function(require,module,exports){ +},{"../../plots/plots":452}],544:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92073,7 +89680,7 @@ function nextDefaultColor(index) { return pieDefaultColors[index % pieDefaultColors.length]; } -},{"../../components/color":1048,"./helpers":1293,"fast-isnumeric":90,"tinycolor2":1042}],1292:[function(require,module,exports){ +},{"../../components/color":303,"./helpers":546,"fast-isnumeric":117,"tinycolor2":274}],545:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92157,7 +89764,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('pull'); }; -},{"../../lib":1127,"./attributes":1289}],1293:[function(require,module,exports){ +},{"../../lib":381,"./attributes":542}],546:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92186,7 +89793,7 @@ exports.formatPieValue = function formatPieValue(v, separators) { return Lib.numSeparate(vRounded, separators); }; -},{"../../lib":1127}],1294:[function(require,module,exports){ +},{"../../lib":381}],547:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92218,7 +89825,7 @@ Pie.meta = { module.exports = Pie; -},{"./attributes":1289,"./base_plot":1290,"./calc":1291,"./defaults":1292,"./layout_attributes":1295,"./layout_defaults":1296,"./plot":1297,"./style":1298,"./style_one":1299}],1295:[function(require,module,exports){ +},{"./attributes":542,"./base_plot":543,"./calc":544,"./defaults":545,"./layout_attributes":548,"./layout_defaults":549,"./plot":550,"./style":551,"./style_one":552}],548:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92238,7 +89845,7 @@ module.exports = { hiddenlabels: {valType: 'data_array'} }; -},{}],1296:[function(require,module,exports){ +},{}],549:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92260,7 +89867,7 @@ module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) { coerce('hiddenlabels'); }; -},{"../../lib":1127,"./layout_attributes":1295}],1297:[function(require,module,exports){ +},{"../../lib":381,"./layout_attributes":548}],550:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92955,7 +90562,7 @@ function maxExtent(tilt, tiltAxisFraction, depth) { 2 * Math.sqrt(1 - sinTilt * sinTilt * tiltAxisFraction * tiltAxisFraction)); } -},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/svg_text_utils":1140,"../../plots/cartesian/graph_interact":1157,"./helpers":1293,"d3":82}],1298:[function(require,module,exports){ +},{"../../components/color":303,"../../components/drawing":325,"../../lib/svg_text_utils":393,"../../plots/cartesian/graph_interact":410,"./helpers":546,"d3":113}],551:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -92984,7 +90591,7 @@ module.exports = function style(gd) { }); }; -},{"./style_one":1299,"d3":82}],1299:[function(require,module,exports){ +},{"./style_one":552,"d3":113}],552:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93011,7 +90618,7 @@ module.exports = function styleOne(s, pt, trace) { .call(Color.stroke, lineColor); }; -},{"../../components/color":1048}],1300:[function(require,module,exports){ +},{"../../components/color":303}],553:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93049,7 +90656,7 @@ module.exports = function arraysToCalcdata(cd) { } }; -},{"../../lib":1127}],1301:[function(require,module,exports){ +},{"../../lib":381}],554:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93060,13 +90667,10 @@ module.exports = function arraysToCalcdata(cd) { 'use strict'; -var colorAttributes = require('../../components/colorscale/color_attributes'); - var Drawing = require('../../components/drawing'); var constants = require('./constants'); -var extendFlat = require('../../lib/extend').extendFlat; module.exports = { x: { @@ -93100,10 +90704,6 @@ module.exports = { dflt: 1, - }, - key: { - valType: 'data_array', - }, text: { valType: 'string', @@ -93177,7 +90777,7 @@ module.exports = { }, - marker: extendFlat({}, { + marker: { symbol: { valType: 'enumerated', values: Drawing.symbolList, @@ -93201,6 +90801,12 @@ module.exports = { arrayOk: true, + }, + color: { + valType: 'color', + arrayOk: true, + + }, maxdisplayed: { valType: 'number', @@ -93228,6 +90834,41 @@ module.exports = { dflt: 'diameter', + }, + colorscale: { + valType: 'colorscale', + + + }, + cauto: { + valType: 'boolean', + dflt: true, + + + }, + cmax: { + valType: 'number', + dflt: null, + + + }, + cmin: { + valType: 'number', + dflt: null, + + + }, + autocolorscale: { + valType: 'boolean', + dflt: true, + + + }, + reversescale: { + valType: 'boolean', + + dflt: false, + }, showscale: { valType: 'boolean', @@ -93235,20 +90876,57 @@ module.exports = { dflt: false, }, - line: extendFlat({}, { + line: { + color: { + valType: 'color', + arrayOk: true, + + + }, width: { valType: 'number', min: 0, arrayOk: true, + }, + colorscale: { + valType: 'colorscale', + + + }, + cauto: { + valType: 'boolean', + dflt: true, + + + }, + cmax: { + valType: 'number', + dflt: null, + + + }, + cmin: { + valType: 'number', + dflt: null, + + + }, + autocolorscale: { + valType: 'boolean', + dflt: true, + + + }, + reversescale: { + valType: 'boolean', + dflt: false, + + } - }, - colorAttributes('marker.line') - ) + } }, - colorAttributes('marker') - ), textposition: { valType: 'enumerated', values: [ @@ -93297,7 +90975,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":1056,"../../components/drawing":1071,"../../lib/extend":1122,"./constants":1305}],1302:[function(require,module,exports){ +},{"../../components/drawing":325,"./constants":558}],555:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93321,9 +90999,13 @@ var calcMarkerColorscale = require('./marker_colorscale_calc'); module.exports = function calc(gd, trace) { var xa = Axes.getFromId(gd, trace.xaxis || 'x'), ya = Axes.getFromId(gd, trace.yaxis || 'y'); + Lib.markTime('in Scatter.calc'); + + var x = xa.makeCalcdata(trace, 'x'); + Lib.markTime('finished convert x'); - var x = xa.makeCalcdata(trace, 'x'), - y = ya.makeCalcdata(trace, 'y'); + var y = ya.makeCalcdata(trace, 'y'); + Lib.markTime('finished convert y'); var serieslen = Math.min(x.length, y.length), marker, @@ -93407,18 +91089,17 @@ module.exports = function calc(gd, trace) { yOptions.padded = false; } + Lib.markTime('ready for Axes.expand'); Axes.expand(xa, x, xOptions); + Lib.markTime('done expand x'); Axes.expand(ya, y, yOptions); + Lib.markTime('done expand y'); // create the "calculated data" to plot var cd = new Array(serieslen); for(i = 0; i < serieslen; i++) { cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ? {x: x[i], y: y[i]} : {x: false, y: false}; - - if (trace.key && trace.key[i] !== undefined) { - cd[i].key = trace.key[i]; - } } // this has migrated up from arraysToCalcdata as we have a reference to 's' here @@ -93428,7 +91109,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./marker_colorscale_calc":1316,"./subtypes":1322,"fast-isnumeric":90}],1303:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"./marker_colorscale_calc":568,"./subtypes":573,"fast-isnumeric":117}],556:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93469,7 +91150,7 @@ module.exports = function cleanData(fullData) { } }; -},{}],1304:[function(require,module,exports){ +},{}],557:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93520,9 +91201,11 @@ module.exports = function colorbar(gd, cd) { .range(scl.map(function(v) { return v[1]; }))) .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254}) .options(marker.colorbar)(); + + Lib.markTime('done colorbar'); }; -},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1305:[function(require,module,exports){ +},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":314,"../../lib":381,"../../plots/plots":452,"d3":113,"fast-isnumeric":117}],558:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93538,7 +91221,7 @@ module.exports = { PTS_LINESONLY: 20 }; -},{}],1306:[function(require,module,exports){ +},{}],559:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93577,7 +91260,6 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout return; } - coerce('key'); coerce('text'); coerce('mode', defaultMode); @@ -93609,7 +91291,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); }; -},{"../../components/errorbars/defaults":1076,"../../lib":1127,"./attributes":1301,"./constants":1305,"./fillcolor_defaults":1307,"./line_defaults":1311,"./line_shape_defaults":1313,"./marker_defaults":1317,"./subtypes":1322,"./text_defaults":1323,"./xy_defaults":1324}],1307:[function(require,module,exports){ +},{"../../components/errorbars/defaults":330,"../../lib":381,"./attributes":554,"./constants":558,"./fillcolor_defaults":560,"./line_defaults":564,"./line_shape_defaults":566,"./marker_defaults":569,"./subtypes":573,"./text_defaults":574,"./xy_defaults":575}],560:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93648,7 +91330,7 @@ module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coe )); }; -},{"../../components/color":1048}],1308:[function(require,module,exports){ +},{"../../components/color":303}],561:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93701,7 +91383,7 @@ module.exports = function getTraceColor(trace, di) { } }; -},{"../../components/color":1048,"./subtypes":1322}],1309:[function(require,module,exports){ +},{"../../components/color":303,"./subtypes":573}],562:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93772,7 +91454,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return [pointData]; }; -},{"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157,"./get_trace_color":1308}],1310:[function(require,module,exports){ +},{"../../components/errorbars":331,"../../plots/cartesian/graph_interact":410,"./get_trace_color":561}],563:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93798,7 +91480,6 @@ Scatter.attributes = require('./attributes'); Scatter.supplyDefaults = require('./defaults'); Scatter.cleanData = require('./clean_data'); Scatter.calc = require('./calc'); -Scatter.setPositions = require('./set_positions'); Scatter.arraysToCalcdata = require('./arrays_to_calcdata'); Scatter.plot = require('./plot'); Scatter.colorbar = require('./colorbar'); @@ -93808,7 +91489,6 @@ Scatter.selectPoints = require('./select'); Scatter.moduleType = 'trace'; Scatter.name = 'scatter'; -Scatter.animatable = true; Scatter.basePlotModule = require('../../plots/cartesian'); Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend']; Scatter.meta = { @@ -93817,7 +91497,7 @@ Scatter.meta = { module.exports = Scatter; -},{"../../plots/cartesian":1158,"./arrays_to_calcdata":1300,"./attributes":1301,"./calc":1302,"./clean_data":1303,"./colorbar":1304,"./defaults":1306,"./hover":1309,"./plot":1318,"./select":1319,"./set_positions":1320,"./style":1321,"./subtypes":1322}],1311:[function(require,module,exports){ +},{"../../plots/cartesian":411,"./arrays_to_calcdata":553,"./attributes":554,"./calc":555,"./clean_data":556,"./colorbar":557,"./defaults":559,"./hover":562,"./plot":570,"./select":571,"./style":572,"./subtypes":573}],564:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93841,7 +91521,7 @@ module.exports = function lineDefaults(traceIn, traceOut, defaultColor, coerce) coerce('line.dash'); }; -},{}],1312:[function(require,module,exports){ +},{}],565:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -93904,7 +91584,7 @@ module.exports = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length, yFrac = pt[1] / ya._length; - return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance * 0; + return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { @@ -94010,7 +91690,7 @@ module.exports = function linePoints(d, opts) { return segments; }; -},{"../../plots/cartesian/axes":1150}],1313:[function(require,module,exports){ +},{"../../plots/cartesian/axes":403}],566:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94029,59 +91709,7 @@ module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) { if(shape === 'spline') coerce('line.smoothing'); }; -},{}],1314:[function(require,module,exports){ -/** -* Copyright 2012-2016, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var Plots = require('../../plots/plots'); - -module.exports = function linkTraces(gd, plotinfo, cdscatter) { - var i, cd, trace; - var fullLayout = gd._fullLayout; - var xa = plotinfo.x(); - var ya = plotinfo.y(); - - var prevtrace = null; - - for(i = 0; i < cdscatter.length; ++i) { - cd = cdscatter[i]; - trace = cd[0].trace; - - // console.log('visible:', trace.uid, trace.visible); - if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && - trace.xaxis === xa._id && - trace.yaxis === ya._id) { - - trace._nexttrace = null; - - if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { - trace._prevtrace = prevtrace; - - if (prevtrace) { - prevtrace._nexttrace = trace; - } - } - - prevtrace = trace; - } else { - trace._prevtrace = trace._nexttrace = null; - } - } - - /*for(i = 0; i < cdscatter.length; ++i) { - var trace = cdscatter[i][0].trace; - console.log('gd.cdscatter[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) - }*/ -} - -},{"../../plots/plots":1199}],1315:[function(require,module,exports){ +},{}],567:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94123,7 +91751,7 @@ module.exports = function makeBubbleSizeFn(trace) { }; }; -},{"fast-isnumeric":90}],1316:[function(require,module,exports){ +},{"fast-isnumeric":117}],568:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94157,7 +91785,7 @@ module.exports = function calcMarkerColorscale(trace) { } }; -},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1317:[function(require,module,exports){ +},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":315,"./subtypes":573}],569:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94220,7 +91848,7 @@ module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout } }; -},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1318:[function(require,module,exports){ +},{"../../components/color":303,"../../components/colorscale/defaults":312,"../../components/colorscale/has_colorscale":315,"./subtypes":573}],570:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94241,176 +91869,74 @@ var ErrorBars = require('../../components/errorbars'); var subTypes = require('./subtypes'); var arraysToCalcdata = require('./arrays_to_calcdata'); var linePoints = require('./line_points'); -var linkTraces = require('./link_traces'); - -function cdscatterKey (d) { - return d[0].trace.uid; -} - -module.exports = function plot(gd, plotinfo, cdscatter, traces, transitionOpts) { - var i, uids, noremove; - var transitionConfig = Lib.extendFlat({}, transitionOpts || {}); - transitionConfig = Lib.extendFlat({ - duration: 0, - easing: 'in-out-cubic', - cascade: 0, - delay: 0, - }, transitionConfig); - - var hasTransition = transitionConfig.duration > 0; +module.exports = function plot(gd, plotinfo, cdscatter) { + selectMarkers(gd, plotinfo, cdscatter); - if (!traces) { - // If no traces provided, redraw all: - for (i = 0, traces = []; i < cdscatter.length; i++) { - traces[i] = i; - } - noremove = false; - } else { - // If this is a partial update, then don't remove traces whose data is not updated - noremove = true; - } + var xa = plotinfo.x(), + ya = plotinfo.y(); - var scatterlayer = plotinfo.plot.select('g.scatterlayer'); - var traceJoin = scatterlayer.selectAll('g.trace').data(cdscatter, cdscatterKey); + // make the container for scatter plots + // (so error bars can find them along with bars) + var scattertraces = plotinfo.plot.select('.scatterlayer') + .selectAll('g.trace.scatter') + .data(cdscatter); - var traceEnter = traceJoin.enter().append('g') + scattertraces.enter().append('g') .attr('class', 'trace scatter') - .style('stroke-miterlimit', 2) - - // After the elements are created but before they've been draw, we have to do - // this extra step of linking the traces due to z-ordering - linkTraces(gd, plotinfo, cdscatter) - createFills(gd, scatterlayer, cdscatter, traces) - - traceEnter.each(function(d) { - //console.log('enter:', d[0].trace.uid); - plotOne(gd, plotinfo, d, this, transitionConfig) - }); - - traceJoin.transition() - .duration(0) - .each(function(d) { - //console.log('transition:', d[0].trace.uid); - plotOne(gd, plotinfo, d, this, transitionConfig) - }); + .style('stroke-miterlimit', 2); + // error bars are at the bottom + scattertraces.call(ErrorBars.plot, plotinfo); - if (!noremove) { - traceJoin.exit().remove(); - } + // BUILD LINES AND FILLS + var prevpath = '', + ownFillEl3, ownFillDir, tonext, nexttonext; - // Sort the traces, once created, so that the ordering is preserved even when - // traces are shown and hidden. This is now needed since we're not just wiping - // everything out and recreating on every update. - for (i = 0, uids = []; i < cdscatter.length; i++) { - uids[i] = cdscatter[i][0].trace.uid; - } + scattertraces.each(function(d) { + var trace = d[0].trace, + line = trace.line, + tr = d3.select(this); + if(trace.visible !== true) return; - scatterlayer.selectAll('g.trace').sort(function (a, b) { - var idx1 = uids.indexOf(a[0].trace.uid); - var idx2 = uids.indexOf(b[0].trace.uid); - return idx1 > idx2 ? 1 : -1; - }); + ownFillDir = trace.fill.charAt(trace.fill.length - 1); + if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; - // remove paths that didn't get used - // scatterlayer.selectAll('path:not([d])').remove(); -}; + d[0].node3 = tr; // store node for tweaking by selectPoints -function createFills (gd, scatterlayer, cdscatter, traces) { - var i, trace, prevtrace; + arraysToCalcdata(d); - scatterlayer.selectAll('g.trace').each(function (d) { - var tr = d3.select(this); + if(!subTypes.hasLines(trace) && trace.fill === 'none') return; - // Loop only over the traces being redrawn: - trace = d[0].trace; + var thispath, + thisrevpath, + // fullpath is all paths for this curve, joined together straight + // across gaps, for filling + fullpath = '', + // revpath is fullpath reversed, for fill-to-next + revpath = '', + // functions for converting a point array to a path + pathfn, revpathbase, revpathfn; + // make the fill-to-zero path now, so it shows behind the line + // fill to next puts the fill associated with one trace + // grouped with the previous if(trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || - (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)) { - trace._ownFill = tr.select('.js-fill.js-tozero'); - if (!trace._ownFill.size()) { - trace._ownFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tozero'); - } - } else { - tr.selectAll('.js-fill.js-tozero').remove(); - trace._ownFill = null; + (trace.fill.substr(0, 2) === 'to' && !prevpath)) { + ownFillEl3 = tr.append('path') + .classed('js-fill', true); } + else ownFillEl3 = null; // make the fill-to-next path now for the NEXT trace, so it shows // behind both lines. - if (trace._nexttrace) { - trace._nextFill = tr.select('.js-fill.js-tonext'); - if (!trace._nextFill.size()) { - trace._nextFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tonext'); - } - } else { - tr.selectAll('.js-fill.js-tonext').remove(); - trace._nextFill = null; - } - }); -} - - -function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { - selectMarkers(gd, plotinfo, cdscatter); - - function transition (selection) { - return selection.transition() - .duration(transitionConfig.duration) - .ease(transitionConfig.easing); - } - - var xa = plotinfo.x(), - ya = plotinfo.y(); + // nexttonext was created last time, but give it + // this curve's data for fill color + if(nexttonext) tonext = nexttonext.datum(d); - var trace = cdscatter[0].trace, - line = trace.line, - tr = d3.select(group); - - // (so error bars can find them along with bars) - // error bars are at the bottom - tr.call(ErrorBars.plot, plotinfo); - - if(trace.visible !== true) return; - - // BUILD LINES AND FILLS - var ownFillEl3, tonext, nexttonext; - var ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = ''; - - // store node for tweaking by selectPoints - cdscatter[0].node3 = tr; - - arraysToCalcdata(cdscatter); - - var prevpath = ''; - var prevtrace = trace._prevtrace; - - if (prevtrace) { - prevpath = prevtrace._revpath || ''; - tonext = prevtrace._nextFill; - } - - var thispath, - thisrevpath, - // fullpath is all paths for this curve, joined together straight - // across gaps, for filling - fullpath = '', - // revpath is fullpath reversed, for fill-to-next - revpath = '', - // functions for converting a point array to a path - pathfn, revpathbase, revpathfn; - - ownFillEl3 = trace._ownFill; - - if(subTypes.hasLines(trace) || trace.fill !== 'none') { - - if (tonext) { - // This tells .style which trace to use for fill information: - tonext.datum(cdscatter); - } + // now make a new nexttonext for next time + nexttonext = tr.append('path').classed('js-fill', true); if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) { pathfn = Drawing.steps(line.shape); @@ -94442,7 +91968,7 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { return revpathbase(pts.reverse()); }; - var segments = linePoints(cdscatter, { + var segments = linePoints(d, { xaxis: xa, yaxis: ya, connectGaps: trace.connectgaps, @@ -94472,12 +91998,7 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { revpath = thisrevpath + 'Z' + revpath; } if(subTypes.hasLines(trace) && pts.length > 1) { - var lineJoin = tr.selectAll('.js-line').data([cdscatter]); - - lineJoin.enter() - .append('path').classed('js-line', true).attr('d', thispath); - - transition(lineJoin).attr('d', thispath); + tr.append('path').classed('js-line', true).attr('d', thispath); } } if(ownFillEl3) { @@ -94492,11 +92013,10 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { // fill to zero: full trace path, plus extension of // the endpoints to the appropriate axis - transition(ownFillEl3).attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); - } else { - // fill to self: just join the path to itself - transition(ownFillEl3).attr('d', fullpath + 'Z'); + ownFillEl3.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z'); } + // fill to self: just join the path to itself + else ownFillEl3.attr('d', fullpath + 'Z'); } } else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) { @@ -94506,7 +92026,7 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { // contours, we just add the two paths closed on themselves. // This makes strange results if one path is *not* entirely // inside the other, but then that is a strange usage. - transition(tonext).attr('d', fullpath + 'Z' + prevpath + 'Z'); + tonext.attr('d', fullpath + 'Z' + prevpath + 'Z'); } else { // tonextx/y: for now just connect endpoints with lines. This is @@ -94514,77 +92034,48 @@ function plotOne(gd, plotinfo, cdscatter, group, transitionConfig) { // y/x, but if they *aren't*, we should ideally do more complicated // things depending on whether the new endpoint projects onto the // existing curve or off the end of it - transition(tonext).attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); + tonext.attr('d', fullpath + 'L' + prevpath.substr(1) + 'Z'); } } + prevpath = revpath; } + }); - trace._revpath = revpath; - } - + // remove paths that didn't get used + scattertraces.selectAll('path:not([d])').remove(); function visFilter(d) { return d.filter(function(v) { return v.vis; }); } - function keyFunc (d) { - return d.key; - } - - function getKeyFunc(trace) { - if (trace.key) { - return keyFunc; - } - } - - - function makePoints (d) { - var trace = d[0].trace, - s = d3.select(this), - showMarkers = subTypes.hasMarkers(trace), - showText = subTypes.hasText(trace); - - if((!showMarkers && !showText) || trace.visible !== true) s.remove(); - else { - if(showMarkers) { - var join = s.selectAll('path.point') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity, getKeyFunc(trace)) - - join.enter().append('path') - .classed('point', true) - .call(Drawing.pointStyle, trace) - .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1) - - join.transition() - .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 0) - .call(Drawing.pointStyle, trace) + scattertraces.append('g') + .attr('class', 'points') + .each(function(d) { + var trace = d[0].trace, + s = d3.select(this), + showMarkers = subTypes.hasMarkers(trace), + showText = subTypes.hasText(trace); - join.exit() - .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, -1); - } - if(showText) { - s.selectAll('g') - .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) - // each text needs to go in its own 'g' in case - // it gets converted to mathjax - .enter().append('g') - .append('text') - .call(Drawing.translatePoints, xa, ya, trace, transitionConfig, 1); + if((!showMarkers && !showText) || trace.visible !== true) s.remove(); + else { + if(showMarkers) { + s.selectAll('path.point') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + .enter().append('path') + .classed('point', true) + .call(Drawing.translatePoints, xa, ya); + } + if(showText) { + s.selectAll('g') + .data(trace.marker.maxdisplayed ? visFilter : Lib.identity) + // each text needs to go in its own 'g' in case + // it gets converted to mathjax + .enter().append('g') + .append('text') + .call(Drawing.translatePoints, xa, ya); + } } - } - } - - var pointJoin = tr.selectAll('.points').data([cdscatter]); - - pointJoin.enter().append('g') - .classed('points', true) - .each(makePoints); - - pointJoin.transition() - .duration(0) - .each(makePoints); - - pointJoin.exit().remove(); + }); }; function selectMarkers(gd, plotinfo, cdscatter) { @@ -94593,46 +92084,45 @@ function selectMarkers(gd, plotinfo, cdscatter) { xr = d3.extent(xa.range.map(xa.l2c)), yr = d3.extent(ya.range.map(ya.l2c)); - // XXX: Not okay. Just makes it work for now. - var i = 0; + cdscatter.forEach(function(d, i) { + var trace = d[0].trace; + if(!subTypes.hasMarkers(trace)) return; + // if marker.maxdisplayed is used, select a maximum of + // mnum markers to show, from the set that are in the viewport + var mnum = trace.marker.maxdisplayed; - var trace = cdscatter[0].trace; - if(!subTypes.hasMarkers(trace)) return; - // if marker.maxdisplayed is used, select a maximum of - // mnum markers to show, from the set that are in the viewport - var mnum = trace.marker.maxdisplayed; - - // TODO: remove some as we get away from the viewport? - if(mnum === 0) return; + // TODO: remove some as we get away from the viewport? + if(mnum === 0) return; - var cd = cdscatter.filter(function(v) { - return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; - }), - inc = Math.ceil(cd.length / mnum), - tnum = 0; - cdscatter.forEach(function(cdj, j) { - var tracei = cdj[0].trace; - if(subTypes.hasMarkers(tracei) && - tracei.marker.maxdisplayed > 0 && j < i) { - tnum++; - } - }); + var cd = d.filter(function(v) { + return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; + }), + inc = Math.ceil(cd.length / mnum), + tnum = 0; + cdscatter.forEach(function(cdj, j) { + var tracei = cdj[0].trace; + if(subTypes.hasMarkers(tracei) && + tracei.marker.maxdisplayed > 0 && j < i) { + tnum++; + } + }); - // if multiple traces use maxdisplayed, stagger which markers we - // display this formula offsets successive traces by 1/3 of the - // increment, adding an extra small amount after each triplet so - // it's not quite periodic - var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); - - // for error bars: save in cd which markers to show - // so we don't have to repeat this - cdscatter.forEach(function(v) { delete v.vis; }); - cd.forEach(function(v, i) { - if(Math.round((i + i0) % inc) === 0) v.vis = true; + // if multiple traces use maxdisplayed, stagger which markers we + // display this formula offsets successive traces by 1/3 of the + // increment, adding an extra small amount after each triplet so + // it's not quite periodic + var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); + + // for error bars: save in cd which markers to show + // so we don't have to repeat this + d.forEach(function(v) { delete v.vis; }); + cd.forEach(function(v, i) { + if(Math.round((i + i0) % inc) === 0) v.vis = true; + }); }); } -},{"../../components/drawing":1071,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1300,"./line_points":1312,"./link_traces":1314,"./subtypes":1322,"d3":82}],1319:[function(require,module,exports){ +},{"../../components/drawing":325,"../../components/errorbars":331,"../../lib":381,"./arrays_to_calcdata":553,"./line_points":565,"./subtypes":573,"d3":113}],571:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94702,67 +92192,7 @@ module.exports = function selectPoints(searchInfo, polygon) { return selection; }; -},{"./subtypes":1322}],1320:[function(require,module,exports){ -/** -* Copyright 2012-2016, Plotly, Inc. -* All rights reserved. -* -* This source code is licensed under the MIT license found in the -* LICENSE file in the root directory of this source tree. -*/ - -'use strict'; - -var Plots = require('../../plots/plots'); -var Axes = require('../../plots/cartesian/axes'); -var Lib = require('../../lib'); - -/** - * setPositions is a bit of a misnomer here. It comes from the box plot - * type that actually does setting of positions. It's the hook though - * that we need to set up links between traces so that trace-level .plot - * doesn't require any links between traces. - */ -module.exports = function setPositions(gd, plotinfo) { - // console.log('setPositions:', plotinfo); - var i, cd, trace; - var fullLayout = gd._fullLayout; - var xa = plotinfo.x(); - var ya = plotinfo.y(); - - var prevtrace = null; - - for(i = 0; i < gd.calcdata.length; ++i) { - cd = gd.calcdata[i]; - trace = cd[0].trace; - - // console.log('visible:', trace.uid, trace.visible); - if(trace.visible === true && Plots.traceIs(trace, 'cartesian') && - trace.xaxis === xa._id && - trace.yaxis === ya._id) { - - trace._nexttrace = null; - - if (['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) { - trace._prevtrace = prevtrace; - - if (prevtrace) { - prevtrace._nexttrace = trace; - } - } - - prevtrace = trace; - } else { - trace._prevtrace = trace._nexttrace = null; - } - } - for(i = 0; i < gd.calcdata.length; ++i) { - var trace = gd.calcdata[i][0].trace; - // console.log('gd.calcdata[i]:', trace.uid, 'prev:', trace._prevtrace && trace._prevtrace.uid, 'next:', trace._nexttrace && trace._nexttrace.uid) - } -}; - -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199}],1321:[function(require,module,exports){ +},{"./subtypes":573}],572:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94804,7 +92234,7 @@ module.exports = function style(gd) { s.call(ErrorBars.style); }; -},{"../../components/drawing":1071,"../../components/errorbars":1077,"d3":82}],1322:[function(require,module,exports){ +},{"../../components/drawing":325,"../../components/errorbars":331,"d3":113}],573:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94838,7 +92268,7 @@ module.exports = { } }; -},{}],1323:[function(require,module,exports){ +},{}],574:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94859,7 +92289,7 @@ module.exports = function(traceIn, traceOut, layout, coerce) { Lib.coerceFont(coerce, 'textfont', layout.font); }; -},{"../../lib":1127}],1324:[function(require,module,exports){ +},{"../../lib":381}],575:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94904,7 +92334,7 @@ module.exports = function handleXYDefaults(traceIn, traceOut, coerce) { return len; }; -},{}],1325:[function(require,module,exports){ +},{}],576:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -94913,11 +92343,10 @@ module.exports = function handleXYDefaults(traceIn, traceOut, coerce) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; var scatterAttrs = require('../scatter/attributes'); -var colorAttributes = require('../../components/colorscale/color_attributes'); - var MARKER_SYMBOLS = require('../../constants/gl_markers'); var extendFlat = require('../../lib/extend').extendFlat; @@ -94993,7 +92422,8 @@ module.exports = { width: scatterLineAttrs.width, dash: scatterLineAttrs.dash }, - marker: extendFlat({}, { // Parity with scatter.js? + marker: { // Parity with scatter.js? + color: scatterMarkerAttrs.color, symbol: { valType: 'enumerated', values: Object.keys(MARKER_SYMBOLS), @@ -95010,14 +92440,24 @@ module.exports = { arrayOk: false, }), + colorscale: scatterMarkerAttrs.colorscale, + cauto: scatterMarkerAttrs.cauto, + cmax: scatterMarkerAttrs.cmax, + cmin: scatterMarkerAttrs.cmin, + autocolorscale: scatterMarkerAttrs.autocolorscale, + reversescale: scatterMarkerAttrs.reversescale, showscale: scatterMarkerAttrs.showscale, - line: extendFlat({}, - {width: extendFlat({}, scatterMarkerLineAttrs.width, {arrayOk: false})}, - colorAttributes('marker.line') - ) + line: { + color: scatterMarkerLineAttrs.color, + width: extendFlat({}, scatterMarkerLineAttrs.width, {arrayOk: false}), + colorscale: scatterMarkerLineAttrs.colorscale, + cauto: scatterMarkerLineAttrs.cauto, + cmax: scatterMarkerLineAttrs.cmax, + cmin: scatterMarkerLineAttrs.cmin, + autocolorscale: scatterMarkerLineAttrs.autocolorscale, + reversescale: scatterMarkerLineAttrs.reversescale + } }, - colorAttributes('marker') - ), textposition: extendFlat({}, scatterAttrs.textposition, {dflt: 'top center'}), textfont: scatterAttrs.textfont, _nestedModules: { @@ -95028,7 +92468,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":1056,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1326:[function(require,module,exports){ +},{"../../constants/gl_markers":368,"../../lib/extend":376,"../scatter/attributes":554}],577:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95057,7 +92497,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../scatter/arrays_to_calcdata":1300,"../scatter/marker_colorscale_calc":1316}],1327:[function(require,module,exports){ +},{"../scatter/arrays_to_calcdata":553,"../scatter/marker_colorscale_calc":568}],578:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95128,7 +92568,7 @@ function calculateErrors(data, scaleFactor) { module.exports = calculateErrors; -},{"../../components/errorbars/compute_error":1075}],1328:[function(require,module,exports){ +},{"../../components/errorbars/compute_error":329}],579:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95587,7 +93027,7 @@ function createLineWithMarkers(scene, data) { module.exports = createLineWithMarkers; -},{"../../constants/gl3d_dashes":1113,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../scatter/make_bubble_size_func":1315,"./calc_errors":1327,"delaunay-triangulate":88,"gl-error3d":123,"gl-line3d":193,"gl-mesh3d":253,"gl-scatter3d":905}],1329:[function(require,module,exports){ +},{"../../constants/gl3d_dashes":367,"../../constants/gl_markers":368,"../../lib":381,"../../lib/gl_format_color":379,"../../lib/str2rgbarray":392,"../scatter/make_bubble_size_func":567,"./calc_errors":578,"delaunay-triangulate":114,"gl-error3d":121,"gl-line3d":127,"gl-mesh3d":150,"gl-scatter3d":193}],580:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95672,7 +93112,7 @@ function handleXYZDefaults(traceIn, traceOut, coerce) { return len; } -},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1325}],1330:[function(require,module,exports){ +},{"../../components/errorbars/defaults":330,"../../lib":381,"../scatter/line_defaults":564,"../scatter/marker_defaults":569,"../scatter/subtypes":573,"../scatter/text_defaults":574,"./attributes":576}],581:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95703,7 +93143,7 @@ Scatter3D.meta = { module.exports = Scatter3D; -},{"../../constants/gl_markers":1114,"../../plots/gl3d":1186,"../scatter/colorbar":1304,"./attributes":1325,"./calc":1326,"./convert":1328,"./defaults":1329}],1331:[function(require,module,exports){ +},{"../../constants/gl_markers":368,"../../plots/gl3d":439,"../scatter/colorbar":557,"./attributes":576,"./calc":577,"./convert":579,"./defaults":580}],582:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95716,14 +93156,13 @@ module.exports = Scatter3D; var scatterAttrs = require('../scatter/attributes'); var plotAttrs = require('../../plots/attributes'); -var colorAttributes = require('../../components/colorscale/color_attributes'); - var extendFlat = require('../../lib/extend').extendFlat; var scatterMarkerAttrs = scatterAttrs.marker, scatterLineAttrs = scatterAttrs.line, scatterMarkerLineAttrs = scatterMarkerAttrs.line; + module.exports = { lon: { valType: 'data_array', @@ -95753,21 +93192,32 @@ module.exports = { width: scatterLineAttrs.width, dash: scatterLineAttrs.dash }, - marker: extendFlat({}, { + marker: { symbol: scatterMarkerAttrs.symbol, opacity: scatterMarkerAttrs.opacity, size: scatterMarkerAttrs.size, sizeref: scatterMarkerAttrs.sizeref, sizemin: scatterMarkerAttrs.sizemin, sizemode: scatterMarkerAttrs.sizemode, + color: scatterMarkerAttrs.color, + colorscale: scatterMarkerAttrs.colorscale, + cauto: scatterMarkerAttrs.cauto, + cmax: scatterMarkerAttrs.cmax, + cmin: scatterMarkerAttrs.cmin, + autocolorscale: scatterMarkerAttrs.autocolorscale, + reversescale: scatterMarkerAttrs.reversescale, showscale: scatterMarkerAttrs.showscale, - line: extendFlat({}, - {width: scatterMarkerLineAttrs.width}, - colorAttributes('marker.line') - ) + line: { + color: scatterMarkerLineAttrs.color, + width: scatterMarkerLineAttrs.width, + colorscale: scatterMarkerLineAttrs.colorscale, + cauto: scatterMarkerLineAttrs.cauto, + cmax: scatterMarkerLineAttrs.cmax, + cmin: scatterMarkerLineAttrs.cmin, + autocolorscale: scatterMarkerLineAttrs.autocolorscale, + reversescale: scatterMarkerLineAttrs.reversescale + } }, - colorAttributes('marker') - ), textfont: scatterAttrs.textfont, textposition: scatterAttrs.textposition, hoverinfo: extendFlat({}, plotAttrs.hoverinfo, { @@ -95778,7 +93228,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1332:[function(require,module,exports){ +},{"../../lib/extend":376,"../../plots/attributes":401,"../scatter/attributes":554}],583:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95801,7 +93251,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../scatter/marker_colorscale_calc":1316}],1333:[function(require,module,exports){ +},{"../scatter/marker_colorscale_calc":568}],584:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95874,7 +93324,7 @@ function handleLonLatLocDefaults(traceIn, traceOut, coerce) { return len; } -},{"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1331}],1334:[function(require,module,exports){ +},{"../../lib":381,"../scatter/line_defaults":564,"../scatter/marker_defaults":569,"../scatter/subtypes":573,"../scatter/text_defaults":574,"./attributes":582}],585:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -95905,7 +93355,7 @@ ScatterGeo.meta = { module.exports = ScatterGeo; -},{"../../plots/geo":1171,"../scatter/colorbar":1304,"./attributes":1331,"./calc":1332,"./defaults":1333,"./plot":1335}],1335:[function(require,module,exports){ +},{"../../plots/geo":424,"../scatter/colorbar":557,"./attributes":582,"./calc":583,"./defaults":584,"./plot":586}],586:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96205,7 +93655,7 @@ function makeEventDataFunc(trace) { }; } -},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../scatter/subtypes":1322,"./attributes":1331,"d3":82}],1336:[function(require,module,exports){ +},{"../../components/color":303,"../../components/drawing":325,"../../lib/array_to_calc_item":372,"../../lib/geo_location_utils":378,"../../lib/topojson_utils":394,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"../scatter/subtypes":573,"./attributes":582,"d3":113}],587:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96217,12 +93667,9 @@ function makeEventDataFunc(trace) { 'use strict'; var scatterAttrs = require('../scatter/attributes'); -var colorAttributes = require('../../components/colorscale/color_attributes'); - var DASHES = require('../../constants/gl2d_dashes'); var MARKERS = require('../../constants/gl_markers'); var extendFlat = require('../../lib/extend').extendFlat; -var extendDeep = require('../../lib/extend').extendDeep; var scatterLineAttrs = scatterAttrs.line, scatterMarkerAttrs = scatterAttrs.marker, @@ -96256,7 +93703,8 @@ module.exports = { } }, - marker: extendDeep({}, colorAttributes('marker'), { + marker: { + color: scatterMarkerAttrs.color, symbol: { valType: 'enumerated', values: Object.keys(MARKERS), @@ -96270,11 +93718,24 @@ module.exports = { sizemin: scatterMarkerAttrs.sizemin, sizemode: scatterMarkerAttrs.sizemode, opacity: scatterMarkerAttrs.opacity, + colorscale: scatterMarkerAttrs.colorscale, + cauto: scatterMarkerAttrs.cauto, + cmax: scatterMarkerAttrs.cmax, + cmin: scatterMarkerAttrs.cmin, + autocolorscale: scatterMarkerAttrs.autocolorscale, + reversescale: scatterMarkerAttrs.reversescale, showscale: scatterMarkerAttrs.showscale, - line: extendDeep({}, colorAttributes('marker.line'), { - width: scatterMarkerLineAttrs.width - }) - }), + line: { + color: scatterMarkerLineAttrs.color, + width: scatterMarkerLineAttrs.width, + colorscale: scatterMarkerLineAttrs.colorscale, + cauto: scatterMarkerLineAttrs.cauto, + cmax: scatterMarkerLineAttrs.cmax, + cmin: scatterMarkerLineAttrs.cmin, + autocolorscale: scatterMarkerLineAttrs.autocolorscale, + reversescale: scatterMarkerLineAttrs.reversescale + } + }, connectgaps: scatterAttrs.connectgaps, fill: extendFlat({}, scatterAttrs.fill, { values: ['none', 'tozeroy', 'tozerox'] @@ -96287,7 +93748,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":1056,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1337:[function(require,module,exports){ +},{"../../constants/gl2d_dashes":366,"../../constants/gl_markers":368,"../../lib/extend":376,"../scatter/attributes":554}],588:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96397,7 +93858,6 @@ var proto = LineWithMarkers.prototype; proto.handlePick = function(pickResult) { var index = pickResult.pointId; - if(pickResult.object !== this.line || this.connectgaps) { index = this.idToIndex[pickResult.pointId]; } @@ -96427,20 +93887,19 @@ proto.isFancy = function(options) { if(!options.x || !options.y) return true; - if(this.hasMarkers) { - var marker = options.marker || {}; + var marker = options.marker || {}; + if(Array.isArray(marker.symbol) || + marker.symbol !== 'circle' || + Array.isArray(marker.size) || + Array.isArray(marker.line.width) || + Array.isArray(marker.opacity) + ) return true; - if(Array.isArray(marker.symbol) || - marker.symbol !== 'circle' || - Array.isArray(marker.size) || - Array.isArray(marker.color) || - Array.isArray(marker.line.width) || - Array.isArray(marker.line.color) || - Array.isArray(marker.opacity) - ) return true; - } + var markerColor = marker.color; + if(Array.isArray(markerColor)) return true; - if(this.hasLines && !this.connectgaps) return true; + var lineColor = Array.isArray(marker.line.color); + if(Array.isArray(lineColor)) return true; if(this.hasErrorX) return true; if(this.hasErrorY) return true; @@ -96763,10 +94222,8 @@ proto.updateFancy = function(options) { proto.updateLines = function(options, positions) { var i; - if(this.hasLines) { var linePositions = positions; - if(!options.connectgaps) { var p = 0; var x = this.xData; @@ -96778,11 +94235,12 @@ proto.updateLines = function(options, positions) { linePositions[p++] = y[i]; } } - this.lineOptions.positions = linePositions; - var lineColor = convertColor(options.line.color, options.opacity, 1), - lineWidth = Math.round(0.5 * this.lineOptions.width), + var lineColor = str2RGBArray(options.line.color); + if(this.hasMarkers) lineColor[3] *= options.marker.opacity; + + var lineWidth = Math.round(0.5 * this.lineOptions.width), dashes = (DASHES[options.line.dash] || [1]).slice(); for(i = 0; i < dashes.length; ++i) dashes[i] *= lineWidth; @@ -96879,7 +94337,7 @@ function createLineWithMarkers(scene, data) { module.exports = createLineWithMarkers; -},{"../../components/errorbars":1077,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../scatter/get_trace_color":1308,"../scatter/make_bubble_size_func":1315,"../scatter/subtypes":1322,"fast-isnumeric":90,"gl-error2d":91,"gl-line2d":160,"gl-scatter2d":781,"gl-scatter2d-fancy":746}],1338:[function(require,module,exports){ +},{"../../components/errorbars":331,"../../constants/gl2d_dashes":366,"../../constants/gl_markers":368,"../../lib":381,"../../lib/gl_format_color":379,"../../lib/str2rgbarray":392,"../../plots/cartesian/axes":403,"../scatter/get_trace_color":561,"../scatter/make_bubble_size_func":567,"../scatter/subtypes":573,"fast-isnumeric":117,"gl-error2d":119,"gl-line2d":125,"gl-scatter2d":190,"gl-scatter2d-fancy":185}],589:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96936,7 +94394,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'}); }; -},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/constants":1305,"../scatter/fillcolor_defaults":1307,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/xy_defaults":1324,"./attributes":1336}],1339:[function(require,module,exports){ +},{"../../components/errorbars/defaults":330,"../../lib":381,"../scatter/constants":558,"../scatter/fillcolor_defaults":560,"../scatter/line_defaults":564,"../scatter/marker_defaults":569,"../scatter/subtypes":573,"../scatter/xy_defaults":575,"./attributes":587}],590:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96967,7 +94425,7 @@ ScatterGl.meta = { module.exports = ScatterGl; -},{"../../plots/gl2d":1183,"../scatter/colorbar":1304,"../scatter3d/calc":1326,"./attributes":1336,"./convert":1337,"./defaults":1338}],1340:[function(require,module,exports){ +},{"../../plots/gl2d":436,"../scatter/colorbar":557,"../scatter3d/calc":577,"./attributes":587,"./convert":588,"./defaults":589}],591:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -96980,14 +94438,13 @@ module.exports = ScatterGl; var scatterAttrs = require('../scatter/attributes'); var plotAttrs = require('../../plots/attributes'); -var colorAttributes = require('../../components/colorscale/color_attributes'); - var extendFlat = require('../../lib/extend').extendFlat; var scatterMarkerAttrs = scatterAttrs.marker, scatterLineAttrs = scatterAttrs.line, scatterMarkerLineAttrs = scatterMarkerAttrs.line; + module.exports = { a: { valType: 'data_array', @@ -97026,7 +94483,7 @@ module.exports = { }), fillcolor: scatterAttrs.fillcolor, - marker: extendFlat({}, { + marker: { symbol: scatterMarkerAttrs.symbol, opacity: scatterMarkerAttrs.opacity, maxdisplayed: scatterMarkerAttrs.maxdisplayed, @@ -97034,14 +94491,25 @@ module.exports = { sizeref: scatterMarkerAttrs.sizeref, sizemin: scatterMarkerAttrs.sizemin, sizemode: scatterMarkerAttrs.sizemode, + color: scatterMarkerAttrs.color, + colorscale: scatterMarkerAttrs.colorscale, + cauto: scatterMarkerAttrs.cauto, + cmax: scatterMarkerAttrs.cmax, + cmin: scatterMarkerAttrs.cmin, + autocolorscale: scatterMarkerAttrs.autocolorscale, + reversescale: scatterMarkerAttrs.reversescale, showscale: scatterMarkerAttrs.showscale, - line: extendFlat({}, - {width: scatterMarkerLineAttrs.width}, - colorAttributes('marker'.line) - ) + line: { + color: scatterMarkerLineAttrs.color, + width: scatterMarkerLineAttrs.width, + colorscale: scatterMarkerLineAttrs.colorscale, + cauto: scatterMarkerLineAttrs.cauto, + cmax: scatterMarkerLineAttrs.cmax, + cmin: scatterMarkerLineAttrs.cmin, + autocolorscale: scatterMarkerLineAttrs.autocolorscale, + reversescale: scatterMarkerLineAttrs.reversescale + } }, - colorAttributes('marker') - ), textfont: scatterAttrs.textfont, textposition: scatterAttrs.textposition, hoverinfo: extendFlat({}, plotAttrs.hoverinfo, { @@ -97052,7 +94520,7 @@ module.exports = { } }; -},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1341:[function(require,module,exports){ +},{"../../lib/extend":376,"../../plots/attributes":401,"../scatter/attributes":554}],592:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97151,7 +94619,7 @@ module.exports = function calc(gd, trace) { return cd; }; -},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../scatter/marker_colorscale_calc":1316,"../scatter/subtypes":1322,"fast-isnumeric":90}],1342:[function(require,module,exports){ +},{"../../lib":381,"../../plots/cartesian/axes":403,"../scatter/marker_colorscale_calc":568,"../scatter/subtypes":573,"fast-isnumeric":117}],593:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97248,7 +94716,7 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout coerce('hoverinfo', (layout._dataLength === 1) ? 'a+b+c+text' : undefined); }; -},{"../../lib":1127,"../scatter/constants":1305,"../scatter/fillcolor_defaults":1307,"../scatter/line_defaults":1311,"../scatter/line_shape_defaults":1313,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1340}],1343:[function(require,module,exports){ +},{"../../lib":381,"../scatter/constants":558,"../scatter/fillcolor_defaults":560,"../scatter/line_defaults":564,"../scatter/line_shape_defaults":566,"../scatter/marker_defaults":569,"../scatter/subtypes":573,"../scatter/text_defaults":574,"./attributes":591}],594:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97298,7 +94766,7 @@ module.exports = function hoverPoints(pointData, xval, yval, hovermode) { return scatterPointData; }; -},{"../../plots/cartesian/axes":1150,"../scatter/hover":1309}],1344:[function(require,module,exports){ +},{"../../plots/cartesian/axes":403,"../scatter/hover":562}],595:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97331,7 +94799,7 @@ ScatterTernary.meta = { module.exports = ScatterTernary; -},{"../../plots/ternary":1206,"../scatter/colorbar":1304,"./attributes":1340,"./calc":1341,"./defaults":1342,"./hover":1343,"./plot":1345,"./select":1346,"./style":1347}],1345:[function(require,module,exports){ +},{"../../plots/ternary":459,"../scatter/colorbar":557,"./attributes":591,"./calc":592,"./defaults":593,"./hover":594,"./plot":596,"./select":597,"./style":598}],596:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97347,16 +94815,11 @@ var scatterPlot = require('../scatter/plot'); module.exports = function plot(ternary, data) { - var plotContainer = ternary.plotContainer; - - // remove all nodes inside the scatter layer - plotContainer.select('.scatterlayer').selectAll('*').remove(); - // mimic cartesian plotinfo var plotinfo = { x: function() { return ternary.xaxis; }, y: function() { return ternary.yaxis; }, - plot: plotContainer + plot: ternary.plotContainer }; var calcdata = new Array(data.length), @@ -97377,7 +94840,7 @@ module.exports = function plot(ternary, data) { scatterPlot(ternary.graphDiv, plotinfo, calcdata); }; -},{"../scatter/plot":1318}],1346:[function(require,module,exports){ +},{"../scatter/plot":570}],597:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97412,7 +94875,7 @@ module.exports = function selectPoints(searchInfo, polygon) { return selection; }; -},{"../scatter/select":1319}],1347:[function(require,module,exports){ +},{"../scatter/select":571}],598:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97441,7 +94904,7 @@ module.exports = function style(gd) { scatterStyle(gd); }; -},{"../scatter/style":1321}],1348:[function(require,module,exports){ +},{"../scatter/style":572}],599:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97450,12 +94913,14 @@ module.exports = function style(gd) { * LICENSE file in the root directory of this source tree. */ + 'use strict'; var Color = require('../../components/color'); var colorscaleAttrs = require('../../components/colorscale/attributes'); var extendFlat = require('../../lib/extend').extendFlat; + function makeContourProjAttr(axLetter) { return { valType: 'boolean', @@ -97543,7 +95008,6 @@ module.exports = { }, - // Todo this block has a structure of colorscale/attributes.js but with colorscale/color_attributes.js names cauto: colorscaleAttrs.zauto, cmin: colorscaleAttrs.zmin, cmax: colorscaleAttrs.zmax, @@ -97579,7 +95043,7 @@ module.exports = { min: -1e5, max: 1e5, - dflt: 1e4, + dflt: 1e5, }, z: { @@ -97661,7 +95125,7 @@ module.exports = { } }; -},{"../../components/color":1048,"../../components/colorscale/attributes":1054,"../../lib/extend":1122}],1349:[function(require,module,exports){ +},{"../../components/color":303,"../../components/colorscale/attributes":309,"../../lib/extend":376}],600:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97685,7 +95149,7 @@ module.exports = function calc(gd, trace) { } }; -},{"../../components/colorscale/calc":1055}],1350:[function(require,module,exports){ +},{"../../components/colorscale/calc":310}],601:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -97730,9 +95194,11 @@ module.exports = function colorbar(gd, cd) { .range(scl.map(function(v) { return v[1]; }))) .filllevels({start: zmin, end: zmax, size: (zmax - zmin) / 254}) .options(trace.colorbar)(); + + Lib.markTime('done colorbar'); }; -},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,"d3":82,"fast-isnumeric":90}],1351:[function(require,module,exports){ +},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":314,"../../lib":381,"../../plots/plots":452,"d3":113,"fast-isnumeric":117}],602:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -98070,7 +95536,13 @@ proto.update = function(data) { } if('lightposition' in data) { - surface.lightPosition = [data.lightposition.x, data.lightposition.y, data.lightposition.z]; + if(surface.lightPosition === void(0)) { + surface.lightPosition = [data.lightposition.x, data.lightposition.y, data.lightposition.z]; + } else { + surface.lightPosition.x = data.lightposition.x; + surface.lightPosition.y = data.lightposition.y; + surface.lightPosition.z = data.lightposition.z; + } } if(alpha && alpha < 1) { @@ -98095,7 +95567,7 @@ function createSurfaceTrace(scene, data) { module.exports = createSurfaceTrace; -},{"../../lib/str2rgbarray":1139,"gl-surface3d":1003,"ndarray":1031,"ndarray-fill":1009,"ndarray-homography":1025,"ndarray-ops":1026,"tinycolor2":1042}],1352:[function(require,module,exports){ +},{"../../lib/str2rgbarray":392,"gl-surface3d":221,"ndarray":253,"ndarray-fill":246,"ndarray-homography":251,"ndarray-ops":252,"tinycolor2":274}],603:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -98212,7 +95684,7 @@ function mapLegacy(traceIn, oldAttr, newAttr) { } } -},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1348}],1353:[function(require,module,exports){ +},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":599}],604:[function(require,module,exports){ /** * Copyright 2012-2016, Plotly, Inc. * All rights reserved. @@ -98242,5 +95714,5 @@ Surface.meta = { module.exports = Surface; -},{"../../plots/gl3d":1186,"./attributes":1348,"./calc":1349,"./colorbar":1350,"./convert":1351,"./defaults":1352}]},{},[12])(12) +},{"../../plots/gl3d":439,"./attributes":599,"./calc":600,"./colorbar":601,"./convert":602,"./defaults":603}]},{},[12])(12) }); \ No newline at end of file diff --git a/dist/plotly.min.js b/dist/plotly.min.js index d5f378c3112..d15e36dbd86 100644 --- a/dist/plotly.min.js +++ b/dist/plotly.min.js @@ -1,47 +1,45 @@ /** -* plotly.js v1.13.0 +* plotly.js v1.12.0 * Copyright 2012-2016, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ -!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.Plotly=t()}}(function(){var t;return function e(t,r,n){function i(o,s){if(!r[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[o]={exports:{}};t[o][0].call(c.exports,function(e){var r=t[o][1][e];return i(r?r:e)},c,c.exports,e,t,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;or)){var i=this._components;if(r===e.length-1)for(var l=16*r,u=0;16>u;++u)n[u]=i[l++];else{for(var c=e[r+1]-e[r],l=16*r,f=this.prevMatrix,h=!0,u=0;16>u;++u)f[u]=i[l++];for(var d=this.nextMatrix,u=0;16>u;++u)d[u]=i[l++],h=h&&f[u]===d[u];if(1e-6>c||h)for(var u=0;16>u;++u)n[u]=f[u];else o(n,f,d,(t-e[r])/c)}var g=this.computedUp;g[0]=n[1],g[1]=n[5],g[2]=n[6],p(g,g);var v=this.computedInverse;s(v,n);var m=this.computedEye,y=v[15];m[0]=v[12]/y,m[1]=v[13]/y,m[2]=v[14]/y;for(var b=this.computedCenter,x=Math.exp(this.computedRadius[0]),u=0;3>u;++u)b[u]=m[u]-n[2+4*u]*x}},g.idle=function(t){if(!(tn;++n)e.push(e[r++]);this._time.push(t)}},g.flush=function(t){var e=a.gt(this._time,t)-2;0>e||(this._time.slice(0,e),this._components.slice(0,16*e))},g.lastT=function(){return this._time[this._time.length-1]},g.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||d,n=n||this.computedUp,this.setMatrix(t,f(this.computedMatrix,e,r,n));for(var i=0,a=0;3>a;++a)i+=Math.pow(r[a]-e[a],2);i=Math.log(Math.sqrt(i)),this.computedRadius[0]=i},g.rotate=function(t,e,r,n){this.recalcMatrix(t);var i=this.computedInverse;e&&u(i,i,e),r&&l(i,i,r),n&&c(i,i,n),this.setMatrix(t,s(this.computedMatrix,i))};var v=[0,0,0];g.pan=function(t,e,r,n){v[0]=-(e||0),v[1]=-(r||0),v[2]=-(n||0),this.recalcMatrix(t);var i=this.computedInverse;h(i,i,v),this.setMatrix(t,s(i,i))},g.translate=function(t,e,r,n){v[0]=e||0,v[1]=r||0,v[2]=n||0,this.recalcMatrix(t);var i=this.computedMatrix;h(i,i,v),this.setMatrix(t,i)},g.setMatrix=function(t,e){if(!(tr;++r)this._components.push(e[r])}},g.setDistance=function(t,e){this.computedRadius[0]=e},g.setDistanceLimits=function(t,e){var r=this._limits;r[0]=t,r[1]=e},g.getDistanceLimits=function(t){var e=this._limits;return t?(t[0]=e[0],t[1]=e[1],t):e}},{"binary-search-bounds":21,"gl-mat4/invert":240,"gl-mat4/lookAt":241,"gl-mat4/rotateX":245,"gl-mat4/rotateY":246,"gl-mat4/rotateZ":247,"gl-mat4/scale":248,"gl-mat4/translate":249,"gl-vec3/normalize":26,"mat4-interpolate":27}],21:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],22:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t}e.exports=n},{}],23:[function(t,e,r){function n(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}e.exports=n},{}],24:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}e.exports=n},{}],25:[function(t,e,r){function n(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}e.exports=n},{}],26:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a),t}e.exports=n},{}],27:[function(t,e,r){function n(t,e,r,n){if(0===c(e)||0===c(r))return!1;var i=u(e,h.translate,h.scale,h.skew,h.perspective,h.quaternion),a=u(r,p.translate,p.scale,p.skew,p.perspective,p.quaternion);return i&&a?(s(d.translate,h.translate,p.translate,n),s(d.skew,h.skew,p.skew,n),s(d.scale,h.scale,p.scale,n),s(d.perspective,h.perspective,p.perspective,n),f(d.quaternion,h.quaternion,p.quaternion,n),l(t,d.translate,d.scale,d.skew,d.perspective,d.quaternion),!0):!1}function i(){return{translate:a(),scale:a(1),skew:a(),perspective:o(),quaternion:o()}}function a(t){return[t||0,t||0,t||0]}function o(){return[0,0,0,1]}var s=t("gl-vec3/lerp"),l=t("mat4-recompose"),u=t("mat4-decompose"),c=t("gl-mat4/determinant"),f=t("quat-slerp"),h=i(),p=i(),d=i();e.exports=n},{"gl-mat4/determinant":236,"gl-vec3/lerp":25,"mat4-decompose":28,"mat4-recompose":30,"quat-slerp":31}],28:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function i(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}function a(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var o=t("./normalize"),s=t("gl-mat4/create"),l=t("gl-mat4/clone"),u=t("gl-mat4/determinant"),c=t("gl-mat4/invert"),f=t("gl-mat4/transpose"),h={length:t("gl-vec3/length"),normalize:t("gl-vec3/normalize"),dot:t("gl-vec3/dot"),cross:t("gl-vec3/cross")},p=s(),d=s(),g=[0,0,0,0],v=[[0,0,0],[0,0,0],[0,0,0]],m=[0,0,0];e.exports=function(t,e,r,s,y,b){if(e||(e=[0,0,0]),r||(r=[0,0,0]),s||(s=[0,0,0]),y||(y=[0,0,0,1]),b||(b=[0,0,0,1]),!o(p,t))return!1;if(l(d,p),d[3]=0,d[7]=0,d[11]=0,d[15]=1,Math.abs(u(d)<1e-8))return!1;var x=p[3],_=p[7],w=p[11],k=p[12],A=p[13],M=p[14],T=p[15];if(0!==x||0!==_||0!==w){g[0]=x,g[1]=_,g[2]=w,g[3]=T;var E=c(d,d);if(!E)return!1;f(d,d),n(y,g,d)}else y[0]=y[1]=y[2]=0,y[3]=1;if(e[0]=k,e[1]=A,e[2]=M,i(v,p),r[0]=h.length(v[0]),h.normalize(v[0],v[0]),s[0]=h.dot(v[0],v[1]),a(v[1],v[1],v[0],1,-s[0]),r[1]=h.length(v[1]),h.normalize(v[1],v[1]),s[0]/=r[1],s[1]=h.dot(v[0],v[2]),a(v[2],v[2],v[0],1,-s[1]),s[2]=h.dot(v[1],v[2]),a(v[2],v[2],v[1],1,-s[2]),r[2]=h.length(v[2]),h.normalize(v[2],v[2]),s[1]/=r[2],s[2]/=r[2],h.cross(m,v[1],v[2]),h.dot(v[0],m)<0)for(var L=0;3>L;L++)r[L]*=-1,v[L][0]*=-1,v[L][1]*=-1,v[L][2]*=-1;return b[0]=.5*Math.sqrt(Math.max(1+v[0][0]-v[1][1]-v[2][2],0)),b[1]=.5*Math.sqrt(Math.max(1-v[0][0]+v[1][1]-v[2][2],0)),b[2]=.5*Math.sqrt(Math.max(1-v[0][0]-v[1][1]+v[2][2],0)),b[3]=.5*Math.sqrt(Math.max(1+v[0][0]+v[1][1]+v[2][2],0)),v[2][1]>v[1][2]&&(b[0]=-b[0]),v[0][2]>v[2][0]&&(b[1]=-b[1]),v[1][0]>v[0][1]&&(b[2]=-b[2]),!0}},{"./normalize":29,"gl-mat4/clone":234,"gl-mat4/create":235,"gl-mat4/determinant":236,"gl-mat4/invert":240,"gl-mat4/transpose":250,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],29:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;16>i;i++)t[i]=e[i]*n;return!0}},{}],30:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":235,"gl-mat4/fromRotationTranslation":238,"gl-mat4/identity":239,"gl-mat4/multiply":242,"gl-mat4/scale":248,"gl-mat4/translate":249}],31:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":32}],32:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],f=e[2],h=e[3],p=r[0],d=r[1],g=r[2],v=r[3];return a=u*p+c*d+f*g+h*v,0>a&&(a=-a,p=-p,d=-d,g=-g,v=-v),1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n),t[0]=s*u+l*p,t[1]=s*c+l*d,t[2]=s*f+l*g,t[3]=s*h+l*v,t}e.exports=n},{}],33:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(f>0){var f=Math.sqrt(c+1);t[0]=.5*(o-l)/f,t[1]=.5*(s-n)/f,t[2]=.5*(r-a)/f,t[3]=.5*f}else{var h=Math.max(e,a,u),f=Math.sqrt(2*h-c+1);e>=h?(t[0]=.5*f,t[1]=.5*(i+r)/f,t[2]=.5*(s+n)/f,t[3]=.5*(o-l)/f):a>=h?(t[0]=.5*(r+i)/f,t[1]=.5*f,t[2]=.5*(l+o)/f,t[3]=.5*(s-n)/f):(t[0]=.5*(n+s)/f,t[1]=.5*(o+l)/f,t[2]=.5*f,t[3]=.5*(r-i)/f)}return t}e.exports=n},{}],34:[function(t,e,r){"use strict";function n(t,e,r){return Math.min(e,Math.max(t,r))}function i(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;nr;++r)e[r]=0;return e}function o(t,e,r){switch(arguments.length){case 0:return new i([0],[0],0);case 1:if("number"==typeof t){var n=a(t);return new i(n,n,0)}return new i(t,a(t.length),0);case 2:if("number"==typeof e){var n=a(t.length);return new i(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new i(t,e,r)}}e.exports=o;var s=t("cubic-hermite"),l=t("binary-search-bounds"),u=i.prototype;u.flush=function(t){var e=l.gt(this._time,t)-1;0>=e||(this._time.splice(0,e),this._state.splice(0,e*this.dimension),this._velocity.splice(0,e*this.dimension))},u.curve=function(t){var e=this._time,r=e.length,i=l.le(e,t),a=this._scratch[0],o=this._state,u=this._velocity,c=this.dimension,f=this.bounds;if(0>i)for(var h=c-1,p=0;c>p;++p,--h)a[p]=o[h];else if(i>=r-1)for(var h=o.length-1,d=t-e[r-1],p=0;c>p;++p,--h)a[p]=o[h]+d*u[h];else{for(var h=c*(i+1)-1,g=e[i],v=e[i+1],m=v-g||1,y=this._scratch[1],b=this._scratch[2],x=this._scratch[3],_=this._scratch[4],w=!0,p=0;c>p;++p,--h)y[p]=o[h],x[p]=u[h]*m,b[p]=o[h+c],_[p]=u[h+c]*m,w=w&&y[p]===b[p]&&x[p]===_[p]&&0===x[p];if(w)for(var p=0;c>p;++p)a[p]=y[p];else s(y,x,b,_,(t-g)/m,a)}for(var k=f[0],A=f[1],p=0;c>p;++p)a[p]=n(k[p],A[p],a[p]);return a},u.dcurve=function(t){var e=this._time,r=e.length,n=l.le(e,t),i=this._scratch[0],a=this._state,o=this._velocity,u=this.dimension;if(n>=r-1)for(var c=a.length-1,f=(t-e[r-1],0);u>f;++f,--c)i[f]=o[c];else{for(var c=u*(n+1)-1,h=e[n],p=e[n+1],d=p-h||1,g=this._scratch[1],v=this._scratch[2],m=this._scratch[3],y=this._scratch[4],b=!0,f=0;u>f;++f,--c)g[f]=a[c],m[f]=o[c]*d,v[f]=a[c+u],y[f]=o[c+u]*d,b=b&&g[f]===v[f]&&m[f]===y[f]&&0===m[f];if(b)for(var f=0;u>f;++f)i[f]=0;else{s.derivative(g,m,v,y,(t-h)/d,i);for(var f=0;u>f;++f)i[f]/=d}}return i},u.lastT=function(){var t=this._time;return t[t.length-1]},u.stable=function(){for(var t=this._velocity,e=t.length,r=this.dimension-1;r>=0;--r)if(t[--e])return!1;return!0},u.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],u=s[1];this._time.push(e,t);for(var c=0;2>c;++c)for(var f=0;r>f;++f)i.push(i[o++]),a.push(0);this._time.push(t);for(var f=r;f>0;--f)i.push(n(l[f-1],u[f-1],arguments[f])),a.push(0)}},u.push=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=t-e,l=this.bounds,u=l[0],c=l[1],f=s>1e-6?1/s:0;this._time.push(t);for(var h=r;h>0;--h){var p=n(u[h-1],c[h-1],arguments[h]);i.push(p),a.push((p-i[o++])*f)}}},u.set=function(t){var e=this.dimension;if(!(t0;--l)r.push(n(o[l-1],s[l-1],arguments[l])),i.push(0)}},u.move=function(t){var e=this.lastT(),r=this.dimension;if(!(e>=t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],u=s[1],c=t-e,f=c>1e-6?1/c:0;this._time.push(t);for(var h=r;h>0;--h){var p=arguments[h];i.push(n(l[h-1],u[h-1],i[o++]+p)),a.push(p*f)}}},u.idle=function(t){var e=this.lastT();if(!(e>t)){var r=this.dimension,i=this._state,a=this._velocity,o=i.length-r,s=this.bounds,l=s[0],u=s[1],c=t-e;this._time.push(t);for(var f=r-1;f>=0;--f)i.push(n(l[f],u[f],i[o]+c*a[o])),a.push(0),o+=1}}},{"binary-search-bounds":35,"cubic-hermite":36}],35:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],36:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n}function i(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,u=(1+2*i)*l,c=i*l,f=s*(3-2*i),h=s*o;if(t.length){a||(a=new Array(t.length));for(var p=t.length-1;p>=0;--p)a[p]=u*t[p]+c*e[p]+f*r[p]+h*n[p];return a}return u*t+c*e+f*r+h*n}e.exports=i,e.exports.derivative=n},{}],37:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function a(t,e){var r=e[0],n=e[1],a=e[2],o=e[3],s=i(r,n,a,o);s>1e-6?(t[0]=r/s,t[1]=n/s,t[2]=a/s,t[3]=o/s):(t[0]=t[1]=t[2]=0,t[3]=1)}function o(t,e,r){this.radius=l([r]),this.center=l(e),this.rotation=l(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),r=[].slice.call(r,0,4),a(r,r);var i=new o(r,e,Math.log(n));return i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up),i}e.exports=s;var l=t("filtered-vector"),u=t("gl-mat4/lookAt"),c=t("gl-mat4/fromQuat"),f=t("gl-mat4/invert"),h=t("./lib/quatFromFrame"),p=o.prototype;p.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},p.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;a(e,e);var r=this.computedMatrix;c(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;3>l;++l){for(var u=0,f=0;3>f;++f)u+=r[l+4*f]*i[f];r[12+l]=-u}},p.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r},p.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},p.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},p.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=a[1],s=a[5],l=a[9],u=n(o,s,l);o/=u,s/=u,l/=u;var c=a[0],f=a[4],h=a[8],p=c*o+f*s+h*l;c-=o*p,f-=s*p,h-=l*p;var d=n(c,f,h);c/=d,f/=d,h/=d;var g=a[2],v=a[6],m=a[10],y=g*o+v*s+m*l,b=g*c+v*f+m*h;g-=y*o+b*c,v-=y*s+b*f,m-=y*l+b*h;var x=n(g,v,m);g/=x,v/=x,m/=x;var _=c*e+o*r,w=f*e+s*r,k=h*e+l*r;this.center.move(t,_,w,k);var A=Math.exp(this.computedRadius[0]);A=Math.max(1e-4,A+i),this.radius.set(t,Math.log(A))},p.rotate=function(t,e,r,a){this.recalcMatrix(t),e=e||0,r=r||0;var o=this.computedMatrix,s=o[0],l=o[4],u=o[8],c=o[1],f=o[5],h=o[9],p=o[2],d=o[6],g=o[10],v=e*s+r*c,m=e*l+r*f,y=e*u+r*h,b=-(d*y-g*m),x=-(g*v-p*y),_=-(p*m-d*v),w=Math.sqrt(Math.max(0,1-Math.pow(b,2)-Math.pow(x,2)-Math.pow(_,2))),k=i(b,x,_,w);k>1e-6?(b/=k,x/=k,_/=k,w/=k):(b=x=_=0,w=1);var A=this.computedRotation,M=A[0],T=A[1],E=A[2],L=A[3],S=M*w+L*b+T*_-E*x,C=T*w+L*x+E*b-M*_,z=E*w+L*_+M*x-T*b,P=L*w-M*b-T*x-E*_;if(a){b=p,x=d,_=g;var R=Math.sin(a)/n(b,x,_);b*=R,x*=R,_*=R,w=Math.cos(e),S=S*w+P*b+C*_-z*x,C=C*w+P*x+z*b-S*_,z=z*w+P*_+S*x-C*b,P=P*w-S*b-C*x-z*_}var j=i(S,C,z,P);j>1e-6?(S/=j,C/=j,z/=j,P/=j):(S=C=z=0,P=1),this.rotation.set(t,S,C,z,P)},p.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;u(i,e,r,n);var o=this.computedRotation;h(o,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),a(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var s=0,l=0;3>l;++l)s+=Math.pow(r[l]-e[l],2);this.radius.set(t,.5*Math.log(Math.max(s,1e-6))),this.center.set(t,r[0],r[1],r[2])},p.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},p.setMatrix=function(t,e){var r=this.computedRotation;h(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),a(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;f(n,e);var i=n[15];if(Math.abs(i)>1e-6){var o=n[12]/i,s=n[13]/i,l=n[14]/i;this.recalcMatrix(t);var u=Math.exp(this.computedRadius[0]);this.center.set(t,o-n[2]*u,s-n[6]*u,l-n[10]*u),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},p.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},p.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},p.getDistanceLimits=function(t){ -var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},p.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},p.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":33,"filtered-vector":34,"gl-mat4/fromQuat":237,"gl-mat4/invert":240,"gl-mat4/lookAt":241}],38:[function(t,e,r){arguments[4][34][0].apply(r,arguments)},{"binary-search-bounds":39,"cubic-hermite":40,dup:34}],39:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],40:[function(t,e,r){arguments[4][36][0].apply(r,arguments)},{dup:36}],41:[function(t,e,r){arguments[4][22][0].apply(r,arguments)},{dup:22}],42:[function(t,e,r){arguments[4][23][0].apply(r,arguments)},{dup:23}],43:[function(t,e,r){arguments[4][26][0].apply(r,arguments)},{dup:26}],44:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t){return Math.min(1,Math.max(-1,t))}function a(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;3>s;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(var s=0;3>s;++s)i[s]-=o/a*t[s];return h(i,i),i}function o(t,e,r,n,i,a,o,s){this.center=l(r),this.up=l(n),this.right=l(i),this.radius=l([a]),this.angle=l([o,s]),this.angle.bounds=[[-(1/0),-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var u=0;16>u;++u)this.computedMatrix[u]=.5;this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.up||[0,1,0],i=t.right||a(r),s=t.radius||1,l=t.theta||0,u=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),h(r,r),i=[].slice.call(i,0,3),h(i,i),"eye"in t){var c=t.eye,d=[c[0]-e[0],c[1]-e[1],c[2]-e[2]];f(i,d,r),n(i[0],i[1],i[2])<1e-6?i=a(r):h(i,i),s=n(d[0],d[1],d[2]);var g=p(r,d)/s,v=p(i,d)/s;u=Math.acos(g),l=Math.acos(v)}return s=Math.log(s),new o(t.zoomMin,t.zoomMax,e,r,i,s,l,u)}e.exports=s;var l=t("filtered-vector"),u=t("gl-mat4/invert"),c=t("gl-mat4/rotate"),f=t("gl-vec3/cross"),h=t("gl-vec3/normalize"),p=t("gl-vec3/dot"),d=o.prototype;d.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},d.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},d.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,i=0,a=0,o=0;3>o;++o)a+=e[o]*r[o],i+=e[o]*e[o];for(var s=Math.sqrt(i),l=0,o=0;3>o;++o)r[o]-=e[o]*a/i,l+=r[o]*r[o],e[o]/=s;for(var u=Math.sqrt(l),o=0;3>o;++o)r[o]/=u;var c=this.computedToward;f(c,e,r),h(c,c);for(var p=Math.exp(this.computedRadius[0]),d=this.computedAngle[0],g=this.computedAngle[1],v=Math.cos(d),m=Math.sin(d),y=Math.cos(g),b=Math.sin(g),x=this.computedCenter,_=v*y,w=m*y,k=b,A=-v*b,M=-m*b,T=y,E=this.computedEye,L=this.computedMatrix,o=0;3>o;++o){var S=_*r[o]+w*c[o]+k*e[o];L[4*o+1]=A*r[o]+M*c[o]+T*e[o],L[4*o+2]=S,L[4*o+3]=0}var C=L[1],z=L[5],P=L[9],R=L[2],j=L[6],O=L[10],I=z*O-P*j,N=P*R-C*O,F=C*j-z*R,D=n(I,N,F);I/=D,N/=D,F/=D,L[0]=I,L[4]=N,L[8]=F;for(var o=0;3>o;++o)E[o]=x[o]+L[2+4*o]*p;for(var o=0;3>o;++o){for(var l=0,B=0;3>B;++B)l+=L[o+4*B]*E[B];L[12+o]=-l}L[15]=1},d.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r};var g=[0,0,0];d.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;g[0]=i[2],g[1]=i[6],g[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;3>l;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];c(i,i,n,g);for(var l=0;3>l;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},d.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=(Math.exp(this.computedRadius[0]),a[1]),s=a[5],l=a[9],u=n(o,s,l);o/=u,s/=u,l/=u;var c=a[0],f=a[4],h=a[8],p=c*o+f*s+h*l;c-=o*p,f-=s*p,h-=l*p;var d=n(c,f,h);c/=d,f/=d,h/=d;var g=c*e+o*r,v=f*e+s*r,m=h*e+l*r;this.center.move(t,g,v,m);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+i),this.radius.set(t,Math.log(y))},d.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},d.setMatrix=function(t,e,r,a){var o=1;"number"==typeof r&&(o=0|r),(0>o||o>3)&&(o=1);var s=(o+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var l=e[o],c=e[o+4],f=e[o+8];if(a){var h=Math.abs(l),p=Math.abs(c),d=Math.abs(f),g=Math.max(h,p,d);h===g?(l=0>l?-1:1,c=f=0):d===g?(f=0>f?-1:1,l=c=0):(c=0>c?-1:1,l=f=0)}else{var v=n(l,c,f);l/=v,c/=v,f/=v}var m=e[s],y=e[s+4],b=e[s+8],x=m*l+y*c+b*f;m-=l*x,y-=c*x,b-=f*x;var _=n(m,y,b);m/=_,y/=_,b/=_;var w=c*b-f*y,k=f*m-l*b,A=l*y-c*m,M=n(w,k,A);w/=M,k/=M,A/=M,this.center.jump(t,G,H,Y),this.radius.idle(t),this.up.jump(t,l,c,f),this.right.jump(t,m,y,b);var T,E;if(2===o){var L=e[1],S=e[5],C=e[9],z=L*m+S*y+C*b,P=L*w+S*k+C*A;T=0>I?-Math.PI/2:Math.PI/2,E=Math.atan2(P,z)}else{var R=e[2],j=e[6],O=e[10],I=R*l+j*c+O*f,N=R*m+j*y+O*b,F=R*w+j*k+O*A;T=Math.asin(i(I)),E=Math.atan2(F,N)}this.angle.jump(t,E,T),this.recalcMatrix(t);var D=e[2],B=e[6],U=e[10],V=this.computedMatrix;u(V,e);var q=V[15],G=V[12]/q,H=V[13]/q,Y=V[14]/q,X=Math.exp(this.computedRadius[0]);this.center.jump(t,G-D*X,H-B*X,Y-U*X)},d.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},d.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},d.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},d.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},d.lookAt=function(t,e,r,a){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter,a=a||this.computedUp;var o=a[0],s=a[1],l=a[2],u=n(o,s,l);if(!(1e-6>u)){o/=u,s/=u,l/=u;var c=e[0]-r[0],f=e[1]-r[1],h=e[2]-r[2],p=n(c,f,h);if(!(1e-6>p)){c/=p,f/=p,h/=p;var d=this.computedRight,g=d[0],v=d[1],m=d[2],y=o*g+s*v+l*m;g-=y*o,v-=y*s,m-=y*l;var b=n(g,v,m);if(!(.01>b&&(g=s*h-l*f,v=l*c-o*h,m=o*f-s*c,b=n(g,v,m),1e-6>b))){g/=b,v/=b,m/=b,this.up.set(t,o,s,l),this.right.set(t,g,v,m),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(p));var x=s*m-l*v,_=l*g-o*m,w=o*v-s*g,k=n(x,_,w);x/=k,_/=k,w/=k;var A=o*c+s*f+l*h,M=g*c+v*f+m*h,T=x*c+_*f+w*h,E=Math.asin(i(A)),L=Math.atan2(T,M),S=this.angle._state,C=S[S.length-1],z=S[S.length-2];C%=2*Math.PI;var P=Math.abs(C+2*Math.PI-L),R=Math.abs(C-L),j=Math.abs(C-2*Math.PI-L);R>P&&(C+=2*Math.PI),R>j&&(C-=2*Math.PI),this.angle.jump(this.angle.lastT(),C,z),this.angle.set(t,L,E)}}}}},{"filtered-vector":38,"gl-mat4/invert":240,"gl-mat4/rotate":244,"gl-vec3/cross":41,"gl-vec3/dot":42,"gl-vec3/normalize":43}],45:[function(t,e,r){"use strict";function n(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}function i(t){t=t||{};var e=t.eye||[0,0,1],r=t.center||[0,0,0],i=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],u=t.mode||"turntable",c=a(),f=o(),h=s();return c.setDistanceLimits(l[0],l[1]),c.lookAt(0,e,r,i),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,i),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,i),new n({turntable:c,orbit:f,matrix:h},u)}e.exports=i;var a=t("turntable-camera-controller"),o=t("orbit-camera-controller"),s=t("matrix-camera-controller"),l=n.prototype,u=[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]];u.forEach(function(t){for(var e=t[0],r=[],n=0;ne)){var r=this._active,n=this._controllerList[e],i=Math.max(r.lastT(),n.lastT());r.recalcMatrix(i),n.setMatrix(i,r.computedMatrix),this._active=n,this._mode=t,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}}},l.getMode=function(){return this._mode}},{"matrix-camera-controller":20,"orbit-camera-controller":37,"turntable-camera-controller":44}],46:[function(t,e,r){function n(t,e){return a(i(t,e))}e.exports=n;var i=t("alpha-complex"),a=t("simplicial-complex-boundary")},{"alpha-complex":47,"simplicial-complex-boundary":58}],47:[function(t,e,r){"use strict";function n(t,e){return i(e).filter(function(r){for(var n=new Array(r.length),i=0;ii;++i)r+=t[i]*e[i];return r}function i(t){var e=t.length;if(0===e)return[];var r=(t[0].length,o([t.length+1,t.length+1],1)),i=o([t.length+1],1);r[e][e]=0;for(var a=0;e>a;++a){for(var l=0;a>=l;++l)r[l][a]=r[a][l]=2*n(t[a],t[l]);i[a]=n(t[a],t[a])}for(var u=s(r,i),c=0,f=u[e+1],a=0;aa;++a){for(var f=u[a],p=0,l=0;ls;++s)r[s]+=t[a][s]*n[a];return r}var o=t("dup"),s=t("robust-linear-solve");a.barycenetric=i,e.exports=a},{dup:50,"robust-linear-solve":51}],50:[function(t,e,r){"use strict";function n(t,e,r){var i=0|t[r];if(0>=i)return[];var a,o=new Array(i);if(r===t.length-1)for(a=0;i>a;++a)o[a]=e;else for(a=0;i>a;++a)o[a]=n(t,e,r+1);return o}function i(t,e){var r,n;for(r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e){switch("undefined"==typeof e&&(e=0),typeof t){case"number":if(t>0)return i(0|t,e);break;case"object":if("number"==typeof t.length)return n(t,e,0)}return[]}e.exports=a},{}],51:[function(t,e,r){"use strict";function n(t){for(var e="robustLinearSolve"+t+"d",r=["function ",e,"(A,b){return ["],n=0;t>n;++n){r.push("det([");for(var i=0;t>i;++i){i>0&&r.push(","),r.push("[");for(var a=0;t>a;++a)a>0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(6>t?s[t]:s)}function i(){return[0]}function a(t,e){return[[e[0]],[t[0][0]]]}function o(){for(;u.lengthi;++i)t.push("s"+i),r.push("case ",i,":return s",i,"(A,b);");r.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve"),t.push("CACHE","g",r.join(""));var a=Function.apply(void 0,t);e.exports=a.apply(void 0,u.concat([u,n]));for(var i=0;l>i;++i)e.exports[i]=u[i]}var s=t("robust-determinant"),l=6,u=[i,a];o()},{"robust-determinant":57}],52:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=t[t.length-1],n=e,i=e-2;i>=0;--i){var a=r,o=t[i];r=a+o;var s=r-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;e>i;++i){var a=t[i],o=r;r=a+o;var s=r-a,l=o-s;l&&(t[u++]=l)}return t[u++]=r,t.length=u,t}e.exports=n},{}],53:[function(t,e,r){"use strict";function n(t,e,r){var n=t+e,i=n-t,a=n-i,o=e-i,s=t-a;return r?(r[0]=s+o,r[1]=n,r):[s+o,n]}e.exports=n},{}],54:[function(t,e,r){"use strict";function n(t,e){var r=t.length;if(1===r){var n=i(t[0],e);return n[0]?n:[n[1]]}var o=new Array(2*r),s=[.1,.1],l=[.1,.1],u=0;i(t[0],e,s),s[0]&&(o[u++]=s[0]);for(var c=1;r>c;++c){i(t[c],e,l);var f=s[1];a(f,l[0],s),s[0]&&(o[u++]=s[0]);var h=l[1],p=s[1],d=h+p,g=d-h,v=p-g;s[1]=d,v&&(o[u++]=v)}return s[1]&&(o[u++]=s[1]),0===u&&(o[u++]=0),o.length=u,o}var i=t("two-product"),a=t("two-sum");e.exports=n},{"two-product":56,"two-sum":53}],55:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],e[0]);var a,o,s=r+i,l=new Array(s),u=0,c=0,f=0,h=Math.abs,p=t[c],d=h(p),g=e[f],v=h(g);v>d?(o=p,c+=1,r>c&&(p=t[c],d=h(p))):(o=g,f+=1,i>f&&(g=e[f],v=h(g))),r>c&&v>d||f>=i?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>c&&i>f;)v>d?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>c;)a=p,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,c+=1,r>c&&(p=t[c]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=e[f]);return M&&(l[u++]=M),T&&(l[u++]=T),u||(l[u++]=0),l.length=u,l}e.exports=i},{}],56:[function(t,e,r){"use strict";function n(t,e,r){var n=t*e,a=i*t,o=a-t,s=a-o,l=t-s,u=i*e,c=u-e,f=u-c,h=e-f,p=n-s*f,d=p-l*f,g=d-s*h,v=l*h-g;return r?(r[0]=v,r[1]=n,r):[v,n]}e.exports=n;var i=+(Math.pow(2,27)+1)},{}],57:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m[",r,"][",n,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("");for(var e=[],r=0;rn;++n)t.push("det"+n),r.push("case ",n,":return det",n,"(m);");r.push("}var det=CACHE[m.length];if(!det)det=CACHE[m.length]=gen(m.length);return det(m);}return robustDeterminant"),t.push("CACHE","gen",r.join(""));var i=Function.apply(void 0,t);e.exports=i.apply(void 0,g.concat([g,l]));for(var n=0;ne;++e)a+=t[e].length;var o=new Array(a),s=0;for(e=0;i>e;++e){var l=t[e],u=l.length;for(r=0;u>r;++r){var c=o[s++]=new Array(u-1),f=0;for(n=0;u>n;++n)n!==r&&(c[f++]=l[n]);if(1&r){var h=c[1];c[1]=c[0],c[0]=h}}}return o}e.exports=n},{}],60:[function(t,e,r){"use strict";function n(t){for(var e=1,r=1;rn;++n)if(t[r]x;++x)if(i=y[x]-b[x])return i;return 0}}e.exports=i;var a=Math.min},{}],62:[function(t,e,r){"use strict";function n(t,e){return i(t,e)||a(t)-a(e)}var i=t("compare-cell"),a=t("cell-orientation");e.exports=n},{"cell-orientation":60,"compare-cell":61}],63:[function(t,e,r){"use strict";function n(t){t.sort(a);for(var e=t.length,r=0,n=0;e>n;++n){var s=t[n],l=o(s);if(0!==l){if(r>0){var u=t[r-1];if(0===i(s,u)&&o(u)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}var i=t("compare-cell"),a=t("compare-oriented-cell"),o=t("cell-orientation");e.exports=n},{"cell-orientation":60,"compare-cell":61,"compare-oriented-cell":62}],64:[function(t,e,r){"use strict";var n=function(){function t(t){return!Array.isArray(t)&&null!==t&&"object"==typeof t}function e(t,e,r){for(var n=(e-t)/Math.max(r-1,1),i=[],a=0;r>a;a++)i.push(t+a*n);return i}function r(){for(var t=[].slice.call(arguments),e=t.map(function(t){return t.length}),r=Math.min.apply(null,e),n=[],i=0;r>i;i++){n[i]=[];for(var a=0;aa;a++)i.push([t[a],e[a],r[a]]);return i}function i(t){function e(t){for(var n=0;n>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3])),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}function u(t,e){var r,n;if("string"!=typeof t)return t;if(r=[],"#"===t[0]?(t=t.substr(1),3===t.length&&(t+=t),n=parseInt(t,16),r[0]=n>>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3]),n[4]?r[3]=parseFloat(n[4]):r[3]=1),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}var c={},f=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/,h=/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/;return c.isPlainObject=t,c.linspace=e,c.zip3=n,c.sum=i,c.zip=r,c.isEqual=s,c.copy2D=a,c.copy1D=o,c.str2RgbArray=l,c.str2RgbaArray=u,c};e.exports=n()},{}],65:[function(t,e,r){(function(e){"use strict";function n(){try{var t=new Uint8Array(1);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(e){return!1}}function i(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(i()=e?a(t,e):void 0!==r?"string"==typeof n?a(t,e).fill(r,n):a(t,e).fill(r):a(t,e)}function c(t,e){if(l(e),t=a(t,0>e?0:0|g(e)),!o.TYPED_ARRAY_SUPPORT)for(var r=0;e>r;r++)t[r]=0;return t}function f(t,e,r){if("string"==typeof r&&""!==r||(r="utf8"),!o.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|m(e,r);return t=a(t,n),t.write(e,r),t}function h(t,e){var r=0|g(e.length);t=a(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function p(t,e,r,n){if(e.byteLength,0>r||e.byteLength=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function v(t){return+t!=t&&(t=0),o.alloc(+t)}function m(t,e){if(o.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"binary":case"raw":case"raws":return r;case"utf8":case"utf-8":case void 0:return G(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return X(t).length;default:if(n)return G(t).length;e=(""+e).toLowerCase(),n=!0}}function y(t,e,r){var n=!1;if((void 0===e||0>e)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),0>=r)return"";if(r>>>=0,e>>>=0,e>=r)return"";for(t||(t="utf8");;)switch(t){case"hex":return P(this,e,r);case"utf8":case"utf-8":return L(this,e,r);case"ascii":return C(this,e,r);case"binary":return z(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function b(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function x(t,e,r,n){function i(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}var a=1,o=t.length,s=e.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;a=2,o/=2,s/=2,r/=2}for(var l=-1,u=0;o>r+u;u++)if(i(t,r+u)===i(e,-1===l?0:u-l)){if(-1===l&&(l=u),u-l+1===s)return(r+l)*a}else-1!==l&&(u-=u-l),l=-1;return-1}function _(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var a=e.length;if(a%2!==0)throw new Error("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;n>o;o++){var s=parseInt(e.substr(2*o,2),16);if(isNaN(s))return o;t[r+o]=s}return o}function w(t,e,r,n){return W(G(e,t.length-r),t,r,n)}function k(t,e,r,n){return W(H(e),t,r,n)}function A(t,e,r,n){return k(t,e,r,n)}function M(t,e,r,n){return W(X(e),t,r,n)}function T(t,e,r,n){return W(Y(e,t.length-r),t,r,n)}function E(t,e,r){return 0===e&&r===t.length?K.fromByteArray(t):K.fromByteArray(t.slice(e,r))}function L(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;r>i;){var a=t[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(r>=i+s){var l,u,c,f;switch(s){case 1:128>a&&(o=a);break;case 2:l=t[i+1],128===(192&l)&&(f=(31&a)<<6|63&l,f>127&&(o=f));break;case 3:l=t[i+1],u=t[i+2],128===(192&l)&&128===(192&u)&&(f=(15&a)<<12|(63&l)<<6|63&u,f>2047&&(55296>f||f>57343)&&(o=f));break;case 4:l=t[i+1],u=t[i+2],c=t[i+3],128===(192&l)&&128===(192&u)&&128===(192&c)&&(f=(15&a)<<18|(63&l)<<12|(63&u)<<6|63&c,f>65535&&1114112>f&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return S(n)}function S(t){var e=t.length;if(J>=e)return String.fromCharCode.apply(String,t);for(var r="",n=0;e>n;)r+=String.fromCharCode.apply(String,t.slice(n,n+=J));return r}function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(127&t[i]);return n}function z(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function P(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",a=e;r>a;a++)i+=q(t[a]);return i}function R(t,e,r){for(var n=t.slice(e,r),i="",a=0;at)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,a){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||a>e)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function I(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,a=Math.min(t.length-r,2);a>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function N(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,a=Math.min(t.length-r,4);a>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function F(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("Index out of range");if(0>r)throw new RangeError("Index out of range")}function D(t,e,r,n,i){return i||F(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),$.write(t,e,r,n,23,4),r+4}function B(t,e,r,n,i){return i||F(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),$.write(t,e,r,n,52,8),r+8}function U(t){if(t=V(t).replace(tt,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function V(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function q(t){return 16>t?"0"+t.toString(16):t.toString(16)}function G(t,e){e=e||1/0;for(var r,n=t.length,i=null,a=[],o=0;n>o;o++){if(r=t.charCodeAt(o),r>55295&&57344>r){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(56320>r){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,128>r){if((e-=1)<0)break;a.push(r)}else if(2048>r){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(65536>r){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(1114112>r))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(t){for(var e=[],r=0;r>8,i=r%256,a.push(i),a.push(n);return a}function X(t){return K.toByteArray(U(t))}function W(t,e,r,n){for(var i=0;n>i&&!(i+r>=e.length||i>=t.length);i++)e[i+r]=t[i];return i}function Z(t){return t!==t}var K=t("base64-js"),$=t("ieee754"),Q=t("isarray");r.Buffer=o,r.SlowBuffer=v,r.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),r.kMaxLength=i(),o.poolSize=8192,o._augment=function(t){return t.__proto__=o.prototype,t},o.from=function(t,e,r){return s(null,t,e,r)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(t,e,r){return u(null,t,e,r)},o.allocUnsafe=function(t){return c(null,t)},o.allocUnsafeSlow=function(t){return c(null,t)},o.isBuffer=function(t){return!(null==t||!t._isBuffer)},o.compare=function(t,e){if(!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,a=Math.min(r,n);a>i;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return n>r?-1:r>n?1:0},o.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(t,e){if(!Q(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);var r;if(void 0===e)for(e=0,r=0;re;e+=2)b(this,e,e+1);return this},o.prototype.swap32=function(){var t=this.length;if(t%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;t>e;e+=4)b(this,e,e+3),b(this,e+1,e+2);return this},o.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?L(this,0,t):y.apply(this,arguments)},o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:0===o.compare(this,t)},o.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},o.prototype.compare=function(t,e,r,n,i){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),0>e||r>t.length||0>n||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var a=i-n,s=r-e,l=Math.min(a,s),u=this.slice(n,i),c=t.slice(e,r),f=0;l>f;++f)if(u[f]!==c[f]){a=u[f],s=c[f];break}return s>a?-1:a>s?1:0},o.prototype.indexOf=function(t,e,r){if("string"==typeof e?(r=e,e=0):e>2147483647?e=2147483647:-2147483648>e&&(e=-2147483648),e>>=0,0===this.length)return-1;if(e>=this.length)return-1;if(0>e&&(e=Math.max(this.length+e,0)),"string"==typeof t&&(t=o.from(t,r)),o.isBuffer(t))return 0===t.length?-1:x(this,t,e,r);if("number"==typeof t)return o.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,e):x(this,[t],e,r);throw new TypeError("val must be string, number or Buffer")},o.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},o.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e=0|e,isFinite(r)?(r=0|r,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(0>r||0>e)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds"); -n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return _(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":return k(this,t,e,r);case"binary":return A(this,t,e,r);case"base64":return M(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,e,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var J=4096;o.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t);var n;if(o.TYPED_ARRAY_SUPPORT)n=this.subarray(t,e),n.__proto__=o.prototype;else{var i=e-t;n=new o(i,void 0);for(var a=0;i>a;a++)n[a]=this[a+t]}return n},o.prototype.readUIntLE=function(t,e,r){t=0|t,e=0|e,r||j(t,e,this.length);for(var n=this[t],i=1,a=0;++a0&&(i*=256);)n+=this[t+--e]*i;return n},o.prototype.readUInt8=function(t,e){return e||j(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,e){return e||j(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,e){return e||j(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,e){return e||j(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,e){return e||j(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,e,r){t=0|t,e=0|e,r||j(t,e,this.length);for(var n=this[t],i=1,a=0;++a=i&&(n-=Math.pow(2,8*e)),n},o.prototype.readIntBE=function(t,e,r){t=0|t,e=0|e,r||j(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*e)),a},o.prototype.readInt8=function(t,e){return e||j(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){e||j(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt16BE=function(t,e){e||j(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},o.prototype.readInt32LE=function(t,e){return e||j(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return e||j(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,e){return e||j(t,4,this.length),$.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return e||j(t,4,this.length),$.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return e||j(t,8,this.length),$.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return e||j(t,8,this.length),$.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,e,r,n){if(t=+t,e=0|e,r=0|r,!n){var i=Math.pow(2,8*r)-1;O(this,t,e,r,i,0)}var a=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+a]=t/o&255;return e+r},o.prototype.writeUInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,255,0),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},o.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},o.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},o.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):N(this,t,e,!0),e+4},o.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},o.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=0,o=1,s=0;for(this[e]=255&t;++at&&0===s&&0!==this[e+a-1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},o.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0;for(this[e+a]=255&t;--a>=0&&(o*=256);)0>t&&0===s&&0!==this[e+a+1]&&(s=1),this[e+a]=(t/o>>0)-s&255;return e+r},o.prototype.writeInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,127,-128),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},o.prototype.writeInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},o.prototype.writeInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):N(this,t,e,!0),e+4},o.prototype.writeInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},o.prototype.writeFloatLE=function(t,e,r){return D(this,t,e,!0,r)},o.prototype.writeFloatBE=function(t,e,r){return D(this,t,e,!1,r)},o.prototype.writeDoubleLE=function(t,e,r){return B(this,t,e,!0,r)},o.prototype.writeDoubleBE=function(t,e,r){return B(this,t,e,!1,r)},o.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(0>e)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-er&&n>e)for(i=a-1;i>=0;i--)t[i+e]=this[i+r];else if(1e3>a||!o.TYPED_ARRAY_SUPPORT)for(i=0;a>i;i++)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+a),e);return a},o.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===t.length){var i=t.charCodeAt(0);256>i&&(t=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t=255&t);if(0>e||this.length=r)return this;e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0);var a;if("number"==typeof t)for(a=e;r>a;a++)this[a]=t;else{var s=o.isBuffer(t)?t:G(new o(t,n).toString()),l=s.length;for(a=0;r-e>a;a++)this[a+e]=s[a%l]}return this};var tt=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":66,ieee754:67,isarray:68}],66:[function(t,e,r){"use strict";function n(){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0,r=t.length;r>e;++e)l[e]=t[e],u[t.charCodeAt(e)]=e;u["-".charCodeAt(0)]=62,u["_".charCodeAt(0)]=63}function i(t){var e,r,n,i,a,o,s=t.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===t[s-2]?2:"="===t[s-1]?1:0,o=new c(3*s/4-a),n=a>0?s-4:s;var l=0;for(e=0,r=0;n>e;e+=4,r+=3)i=u[t.charCodeAt(e)]<<18|u[t.charCodeAt(e+1)]<<12|u[t.charCodeAt(e+2)]<<6|u[t.charCodeAt(e+3)],o[l++]=i>>16&255,o[l++]=i>>8&255,o[l++]=255&i;return 2===a?(i=u[t.charCodeAt(e)]<<2|u[t.charCodeAt(e+1)]>>4,o[l++]=255&i):1===a&&(i=u[t.charCodeAt(e)]<<10|u[t.charCodeAt(e+1)]<<4|u[t.charCodeAt(e+2)]>>2,o[l++]=i>>8&255,o[l++]=255&i),o}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function o(t,e,r){for(var n,i=[],o=e;r>o;o+=3)n=(t[o]<<16)+(t[o+1]<<8)+t[o+2],i.push(a(n));return i.join("")}function s(t){for(var e,r=t.length,n=r%3,i="",a=[],s=16383,u=0,c=r-n;c>u;u+=s)a.push(o(t,u,u+s>c?c:u+s));return 1===n?(e=t[r-1],i+=l[e>>2],i+=l[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=l[e>>10],i+=l[e>>4&63],i+=l[e<<2&63],i+="="),a.push(i),a.join("")}r.toByteArray=i,r.fromByteArray=s;var l=[],u=[],c="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],67:[function(t,e,r){r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,c=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,a=p&(1<<-c)-1,p>>=-c,c+=s;c>0;a=256*a+t[e+f],f+=h,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+f],f+=h,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:(p?-1:1)*(1/0);o+=Math.pow(2,n),a-=u}return(p?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:a-1,d=n?1:-1,g=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),e+=o+f>=1?h/l:h*Math.pow(2,1-f),e*l>=2&&(o++,l/=2),o+f>=c?(s=0,o=c):o+f>=1?(s=(e*l-1)*Math.pow(2,i),o+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+p]=255&s,p+=d,s/=256,i-=8);for(o=o<0;t[r+p]=255&o,p+=d,o/=256,u-=8);t[r+p-d]|=128*g}},{}],68:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],69:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!a(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,a,l,u;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(o(r))for(a=Array.prototype.slice.call(arguments,1),u=r.slice(),n=u.length,l=0;n>l;l++)u[l].apply(this,a);return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(r=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],70:[function(t,e,r){function n(){h&&c&&(h=!1,c.length?f=c.concat(f):p=-1,f.length&&i())}function i(){if(!h){var t=s(n);h=!0;for(var e=f.length;e;){for(c=f,f=[];++p1)for(var r=1;rt[r][0]&&(r=n);return r>e?[[e],[r]]:e>r?[[r],[e]]:[[e]]}e.exports=n},{}],73:[function(t,e,r){"use strict";function n(t){var e=i(t),r=e.length;if(2>=r)return[];for(var n=new Array(r),a=e[r-1],o=0;r>o;++o){var s=e[o];n[o]=[a,s],a=s}return n}e.exports=n;var i=t("monotone-convex-hull-2d")},{"monotone-convex-hull-2d":80}],74:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),i=0;ii;++i)e.indexOf(i)<0&&(n[a++]=t[i]);return n}function i(t,e){for(var r=t.length,n=e.length,i=0;r>i;++i)for(var a=t[i],o=0;os)a[o]=e[s];else{s-=n;for(var l=0;n>l;++l)s>=e[l]&&(s+=1);a[o]=s}}return t}function a(t,e){try{return o(t,!0)}catch(r){var a=s(t);if(a.length<=e)return[];var l=n(t,a),u=o(l,!0);return i(u,a)}}e.exports=a;var o=t("incremental-convex-hull"),s=t("affine-hull")},{"affine-hull":75,"incremental-convex-hull":76}],75:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(e+1),n=0;n=i;++i){for(var o=new Array(e),s=0;e>s;++s)o[s]=Math.pow(i+1-n,s);r[i]=o}var l=a.apply(void 0,r);if(l)return!0}return!1}function i(t){var e=t.length;if(0===e)return[];if(1===e)return[0];for(var r=t[0].length,i=[t[0]],a=[0],o=1;e>o;++o)if(i.push(t[o]),n(i,r)){if(a.push(o),a.length===r+1)return a}else i.pop();return a}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":1040}],76:[function(t,e,r){"use strict";function n(t,e,r){this.vertices=t,this.adjacent=e,this.boundary=r,this.lastVisited=-1}function i(t,e,r){this.vertices=t,this.cell=e,this.index=r}function a(t,e){return c(t.vertices,e.vertices)}function o(t){for(var e=["function orient(){var tuple=this.tuple;return test("],r=0;t>=r;++r)r>0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=u[t+1];return i||(i=u),n(i)}function s(t,e,r){this.dimension=t,this.vertices=e,this.simplices=r,this.interior=r.filter(function(t){return!t.boundary}),this.tuple=new Array(t+1);for(var n=0;t>=n;++n)this.tuple[n]=this.vertices[n];var i=f[t];i||(i=f[t]=o(t)),this.orient=i}function l(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(i>=r)throw new Error("Must input at least d+1 points");var a=t.slice(0,i+1),o=u.apply(void 0,a);if(0===o)throw new Error("Input not in general position");for(var l=new Array(i+1),c=0;i>=c;++c)l[c]=c;0>o&&(l[0]=1,l[1]=0);for(var f=new n(l,new Array(i+1),!1),h=f.adjacent,p=new Array(i+2),c=0;i>=c;++c){for(var d=l.slice(),g=0;i>=g;++g)g===c&&(d[g]=-1);var v=d[0];d[0]=d[1],d[1]=v;var m=new n(d,new Array(i+1),!0);h[c]=m,p[c]=m}p[i+1]=f;for(var c=0;i>=c;++c)for(var d=h[c].vertices,y=h[c].adjacent,g=0;i>=g;++g){var b=d[g];if(0>b)y[g]=f;else for(var x=0;i>=x;++x)h[x].vertices.indexOf(b)<0&&(y[g]=h[x])}for(var _=new s(i,a,p),w=!!e,c=i+1;r>c;++c)_.insert(t[c],w);return _.boundary()}e.exports=l;var u=t("robust-orientation"),c=t("simplicial-complex").compareCells;n.prototype.flip=function(){var t=this.vertices[0];this.vertices[0]=this.vertices[1],this.vertices[1]=t;var e=this.adjacent[0];this.adjacent[0]=this.adjacent[1],this.adjacent[1]=e};var f=[],h=s.prototype;h.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){t=o.pop();for(var s=(t.vertices,t.adjacent),l=0;r>=l;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,f=0;r>=f;++f){var h=c[f];0>h?i[f]=e:i[f]=a[h]}var p=this.orient();if(p>0)return u;u.lastVisited=-n,0===p&&o.push(u)}}}return null},h.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;n>=c;++c)a[c]=i[l[c]];s.lastVisited=r;for(var c=0;n>=c;++c){var f=u[c];if(!(f.lastVisited>=r)){var h=a[c];a[c]=t;var p=this.orient();if(a[c]=h,0>p){s=f;continue t}f.boundary?f.lastVisited=-r:f.lastVisited=r}}return}return s},h.addPeaks=function(t,e){var r=this.vertices.length-1,o=this.dimension,s=this.vertices,l=this.tuple,u=this.interior,c=this.simplices,f=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,u.push(e);for(var h=[];f.length>0;){var e=f.pop(),p=e.vertices,d=e.adjacent,g=p.indexOf(r);if(!(0>g))for(var v=0;o>=v;++v)if(v!==g){var m=d[v];if(m.boundary&&!(m.lastVisited>=r)){var y=m.vertices;if(m.lastVisited!==-r){for(var b=0,x=0;o>=x;++x)y[x]<0?(b=x,l[x]=t):l[x]=s[y[x]];var _=this.orient();if(_>0){y[b]=r,m.boundary=!1,u.push(m),f.push(m),m.lastVisited=r;continue}m.lastVisited=-r}var w=m.adjacent,k=p.slice(),A=d.slice(),M=new n(k,A,!0);c.push(M);var T=w.indexOf(e);if(!(0>T)){w[T]=M,A[g]=m,k[v]=-1,A[v]=e,d[v]=M,M.flip();for(var x=0;o>=x;++x){var E=k[x];if(!(0>E||E===r)){for(var L=new Array(o-1),S=0,C=0;o>=C;++C){var z=k[C];0>z||C===x||(L[S++]=z)}h.push(new i(L,M,x))}}}}}}h.sort(a);for(var v=0;v+1j||0>O||(P.cell.adjacent[P.index]=R.cell,R.cell.adjacent[R.index]=P.cell)}},h.insert=function(t,e){var r=this.vertices;r.push(t);var n=this.walk(t,e);if(n){for(var i=this.dimension,a=this.tuple,o=0;i>=o;++o){var s=n.vertices[o];0>s?a[o]=t:a[o]=r[s]}var l=this.orient(a);0>l||(0!==l||(n=this.handleBoundaryDegeneracy(n,t)))&&this.addPeaks(t,n)}},h.boundary=function(){for(var t=this.dimension,e=[],r=this.simplices,n=r.length,i=0;n>i;++i){var a=r[i];if(a.boundary){for(var o=new Array(t),s=a.vertices,l=0,u=0,c=0;t>=c;++c)s[c]>=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var f=o[0];o[0]=o[1],o[1]=f}e.push(o)}}return e}},{"robust-orientation":1040,"simplicial-complex":79}],77:[function(t,e,r){"use strict";"use restrict";function n(t){var e=32;return t&=-t,t&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}var i=32;r.INT_BITS=i,r.INT_MAX=2147483647,r.INT_MIN=-1<0)-(0>t)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(e>t)},r.max=function(t,e){return t^(t^e)&-(e>t)},r.isPow2=function(t){return!(t&t-1||!t)},r.log2=function(t){var e,r;return e=(t>65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var a=new Array(256);!function(t){for(var e=0;256>e;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|a[t>>>16&255]<<8|a[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],78:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n;var i=n.prototype;Object.defineProperty(i,"length",{get:function(){return this.roots.length}}),i.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},i.find=function(t){for(var e=t,r=this.roots;r[t]!==t;)t=r[t];for(;r[e]!==t;){var n=r[e];r[e]=t,e=n}return t},i.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],79:[function(t,e,r){"use strict";"use restrict";function n(t){for(var e=0,r=Math.max,n=0,i=t.length;i>n;++n)e=r(e,t[n].length);return e-1}function i(t){for(var e=-1,r=Math.max,n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)e=r(e,a[o]);return e+1}function a(t){for(var e=new Array(t.length),r=0,n=t.length;n>r;++r)e[r]=t[r].slice(0);return e}function o(t,e){var r=t.length,n=t.length-e.length,i=Math.min;if(n)return n;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:var a=t[0]+t[1]-e[0]-e[1];return a?a:i(t[0],t[1])-i(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=i(t[0],t[1]),u=i(e[0],e[1]),a=i(l,t[2])-i(u,e[2]);return a?a:i(l+t[2],o)-i(u+e[2],s);default:var c=t.slice(0);c.sort();var f=e.slice(0);f.sort();for(var h=0;r>h;++h)if(n=c[h]-f[h])return n;return 0}}function s(t,e){return o(t[0],e[0])}function l(t,e){if(e){for(var r=t.length,n=new Array(r),i=0;r>i;++i)n[i]=[t[i],e[i]];n.sort(s);for(var i=0;r>i;++i)t[i]=n[i][0],e[i]=n[i][1];return t}return t.sort(o),t}function u(t){if(0===t.length)return[];for(var e=1,r=t.length,n=1;r>n;++n){var i=t[n];if(o(i,t[n-1])){if(n===e){e++;continue}t[e++]=i}}return t.length=e,t}function c(t,e){for(var r=0,n=t.length-1,i=-1;n>=r;){var a=r+n>>1,s=o(t[a],e);0>=s?(0===s&&(i=a),r=a+1):s>0&&(n=a-1)}return i}function f(t,e){for(var r=new Array(t.length),n=0,i=r.length;i>n;++n)r[n]=[];for(var a=[],n=0,s=e.length;s>n;++n)for(var l=e[n],u=l.length,f=1,h=1<f;++f){a.length=b.popCount(f);for(var p=0,d=0;u>d;++d)f&1<g))for(;;)if(r[g++].push(n),g>=t.length||0!==o(t[g],a))break}return r}function h(t,e){if(!e)return f(u(d(t,0)),t,0);for(var r=new Array(e),n=0;e>n;++n)r[n]=[];for(var n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)r[a[o]].push(n);return r}function p(t){for(var e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0|i.length,o=1,s=1<o;++o){for(var u=[],c=0;a>c;++c)o>>>c&1&&u.push(i[c]);e.push(u)}return l(e)}function d(t,e){if(0>e)return[];for(var r=[],n=(1<r;++r)for(var i=t[r],a=0,o=i.length;o>a;++a){for(var s=new Array(i.length-1),u=0,c=0;o>u;++u)u!==a&&(s[c++]=i[u]);e.push(s)}return l(e)}function v(t,e){for(var r=new x(e),n=0;ne){for(var r=new Array(e),n=0;e>n;++n)r[n]=n;return 2===e&&t[0][0]===t[1][0]&&t[0][1]===t[1][1]?[0]:r}for(var a=new Array(e),n=0;e>n;++n)a[n]=n;a.sort(function(e,r){var n=t[e][0]-t[r][0];return n?n:t[e][1]-t[r][1]});for(var o=[a[0],a[1]],s=[a[0],a[1]],n=2;e>n;++n){for(var l=a[n],u=t[l],c=o.length;c>1&&i(t[o[c-2]],t[o[c-1]],u)<=0;)c-=1,o.pop();for(o.push(l),c=s.length;c>1&&i(t[s[c-2]],t[s[c-1]],u)>=0;)c-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),f=0,n=0,h=o.length;h>n;++n)r[f++]=o[n];for(var p=s.length-2;p>0;--p)r[f++]=s[p];return r}e.exports=n;var i=t("robust-orientation")[3]},{"robust-orientation":1040}],81:[function(t,e,r){e.exports={AFG:"afghan",ALA:"\\b\\wland",ALB:"albania",DZA:"algeria",ASM:"^(?=.*americ).*samoa",AND:"andorra",AGO:"angola",AIA:"anguill?a",ATA:"antarctica",ATG:"antigua",ARG:"argentin",ARM:"armenia",ABW:"^(?!.*bonaire).*\\baruba",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baustri.*\\bemp",AZE:"azerbaijan",BHS:"bahamas",BHR:"bahrain",BGD:"bangladesh|^(?=.*east).*paki?stan",BRB:"barbados",BLR:"belarus|byelo",BEL:"^(?!.*luxem).*belgium",BLZ:"belize|^(?=.*british).*honduras",BEN:"benin|dahome",BMU:"bermuda",BTN:"bhutan",BOL:"bolivia",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",BIH:"herzegovina|bosnia",BWA:"botswana|bechuana",BVT:"bouvet",BRA:"brazil",IOT:"british.?indian.?ocean",BRN:"brunei",BGR:"bulgaria",BFA:"burkina|\\bfaso|upper.?volta",BDI:"burundi",KHM:"cambodia|kampuchea|khmer",CMR:"cameroon",CAN:"canada",CPV:"verde",CYM:"cayman",CAF:"\\bcentral.african.republic",TCD:"\\bchad",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china",CXR:"christmas",CCK:"\\bcocos|keeling",COL:"colombia",COM:"comoro",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",COG:"^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",COK:"\\bcook",CRI:"costa.?rica",CIV:"ivoire|ivory",HRV:"croatia",CUB:"\\bcuba",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",CYP:"cyprus",CZE:"^(?=.*rep).*czech|czechia|bohemia",CSK:"czechoslovakia",DNK:"denmark",DJI:"djibouti",DMA:"dominica(?!n)",DOM:"dominican.rep",ECU:"ecuador",EGY:"egypt",SLV:"el.?salvador",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",ERI:"eritrea",EST:"estonia",ETH:"ethiopia|abyssinia",FLK:"falkland|malvinas",FRO:"faroe|faeroe",FJI:"fiji",FIN:"finland",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",GUF:"^(?=.*french).*guiana",PYF:"french.?polynesia|tahiti",ATF:"french.?southern",GAB:"gabon",GMB:"gambia",GEO:"^(?!.*south).*georgia",DDR:"german.?democratic.?republic|democratic.?republic.*germany|east.germany",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GHA:"ghana|gold.?coast",GIB:"gibraltar",GRC:"greece|hellenic|hellas",GRL:"greenland",GRD:"grenada",GLP:"guadeloupe",GUM:"\\bguam",GTM:"guatemala",GGY:"guernsey",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",GNB:"bissau|^(?=.*portu).*guinea",GUY:"guyana|british.?guiana",HTI:"haiti",HMD:"heard.*mcdonald",VAT:"holy.?see|vatican|papal.?st",HND:"^(?!.*brit).*honduras",HKG:"hong.?kong",HUN:"^(?!.*austr).*hungary",ISL:"iceland",IND:"india(?!.*ocea)",IDN:"indonesia",IRN:"\\biran|persia",IRQ:"\\biraq|mesopotamia",IRL:"ireland",IMN:"^(?=.*isle).*\\bman",ISR:"israel",ITA:"italy",JAM:"jamaica",JPN:"japan",JEY:"jersey",JOR:"jordan",KAZ:"kazak",KEN:"kenya|british.?east.?africa|east.?africa.?prot",KIR:"kiribati",PRK:"^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk",KOR:"^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea",KWT:"kuwait",KGZ:"kyrgyz|kirghiz",LAO:"\\blaos?\\b",LVA:"latvia",LBN:"lebanon",LSO:"lesotho|basuto",LBR:"liberia",LBY:"libya",LIE:"liechtenstein",LTU:"lithuania",LUX:"^(?!.*belg).*luxem",MAC:"maca(o|u)",MKD:"macedonia|fyrom",MDG:"madagascar|malagasy",MWI:"malawi|nyasa",MYS:"malaysia",MDV:"maldive",MLI:"\\bmali\\b",MLT:"\\bmalta",MHL:"marshall",MTQ:"martinique",MRT:"mauritania",MUS:"mauritius",MYT:"\\bmayotte",MEX:"\\bmexic",FSM:"micronesia",MDA:"moldov|b(a|e)ssarabia",MCO:"monaco",MNG:"mongolia",MNE:"^(?!.*serbia).*montenegro",MSR:"montserrat",MAR:"morocco|\\bmaroc",MOZ:"mozambique",MMR:"myanmar|burma",NAM:"namibia",NRU:"nauru",NPL:"nepal",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",ANT:"^(?=.*\\bant).*(nether|dutch)",NCL:"new.?caledonia",NZL:"new.?zealand",NIC:"nicaragua",NER:"\\bniger(?!ia)",NGA:"nigeria",NIU:"niue",NFK:"norfolk",MNP:"mariana",NOR:"norway",OMN:"\\boman|trucial",PAK:"^(?!.*east).*paki?stan",PLW:"palau",PSE:"palestin|\\bgaza|west.?bank",PAN:"panama",PNG:"papua|new.?guinea",PRY:"paraguay",PER:"peru",PHL:"philippines",PCN:"pitcairn",POL:"poland",PRT:"portugal",PRI:"puerto.?rico",QAT:"qatar",REU:"r(e|\xe9)union",ROU:"r(o|u|ou)mania",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",RWA:"rwanda",BLM:"barth(e|\xe9)lemy",SHN:"helena",KNA:"kitts|\\bnevis",LCA:"\\blucia",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",SPM:"miquelon",VCT:"vincent",WSM:"^(?!.*amer).*samoa",SMR:"san.?marino",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SAU:"\\bsa\\w*.?arabia",SEN:"senegal",SRB:"^(?!.*monte).*serbia",SYC:"seychell",SLE:"sierra", -SGP:"singapore",SXM:"^(?!.*martin)(?!.*saba).*maarten",SVK:"^(?!.*cze).*slovak",SVN:"slovenia",SLB:"solomon",SOM:"somali",ZAF:"\\bs\\w*.?africa",SGS:"south.?georgia|sandwich",SSD:"\\bs\\w*.?sudan",ESP:"spain",LKA:"sri.?lanka|ceylon",SDN:"^(?!.*\\bs(?!u)).*sudan",SUR:"surinam|dutch.?guiana",SJM:"svalbard",SWZ:"swaziland",SWE:"sweden",CHE:"switz|swiss",SYR:"syria",TWN:"taiwan|taipei|formosa",TJK:"tajik",TZA:"tanzania",THA:"thailand|\\bsiam",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TGO:"togo",TKL:"tokelau",TON:"tonga",TTO:"trinidad|tobago",TUN:"tunisia",TUR:"turkey",TKM:"turkmen",TCA:"turks",TUV:"tuvalu",UGA:"uganda",UKR:"ukrain",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",USA:"united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)",UMI:"minor.?outlying.?is",URY:"uruguay",UZB:"uzbek",VUT:"vanuatu|new.?hebrides",VEN:"venezuela",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",WLF:"futuna|wallis",ESH:"western.sahara",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",YUG:"yugoslavia",ZMB:"zambia|northern.?rhodesia",EAZ:"zanzibar",ZWE:"zimbabwe|^(?!.*northern).*rhodesia"}},{}],82:[function(e,r,n){!function(){function e(t){return t&&(t.ownerDocument||t.document||t).documentElement}function n(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}function i(t,e){return e>t?-1:t>e?1:t>=e?0:NaN}function a(t){return null===t?NaN:+t}function o(t){return!isNaN(t)}function s(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}function l(t){return t.length}function u(t){for(var e=1;t*e%1;)e*=10;return e}function c(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function f(){this._=Object.create(null)}function h(t){return(t+="")===ko||t[0]===Ao?Ao+t:t}function p(t){return(t+="")[0]===Ao?t.slice(1):t}function d(t){return h(t)in this._}function g(t){return(t=h(t))in this._&&delete this._[t]}function v(){var t=[];for(var e in this._)t.push(p(e));return t}function m(){var t=0;for(var e in this._)++t;return t}function y(){for(var t in this._)return!1;return!0}function b(){this._=Object.create(null)}function x(t){return t}function _(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function w(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=Mo.length;n>r;++r){var i=Mo[r]+e;if(i in t)return i}}function k(){}function A(){}function M(t){function e(){for(var e,n=r,i=-1,a=n.length;++ir;r++)for(var i,a=t[r],o=0,s=a.length;s>o;o++)(i=a[o])&&e(i,o,r);return t}function Y(t){return Eo(t,jo),t}function X(t){var e,r;return function(n,i,a){var o,s=t[a].update,l=s.length;for(a!=r&&(r=a,e=0),i>=e&&(e=i+1);!(o=s[e])&&++e0&&(t=t.slice(0,s));var u=Oo.get(t);return u&&(t=u,l=K),s?e?i:n:e?k:a}function Z(t,e){return function(r){var n=uo.event;uo.event=r,e[0]=this.__data__;try{t.apply(this,e)}finally{uo.event=n}}}function K(t,e){var r=Z(t,e);return function(t){var e=this,n=t.relatedTarget;n&&(n===e||8&n.compareDocumentPosition(e))||r.call(e,t)}}function $(t){var r=".dragsuppress-"+ ++No,i="click"+r,a=uo.select(n(t)).on("touchmove"+r,T).on("dragstart"+r,T).on("selectstart"+r,T);if(null==Io&&(Io="onselectstart"in t?!1:w(t.style,"userSelect")),Io){var o=e(t).style,s=o[Io];o[Io]="none"}return function(t){if(a.on(r,null),Io&&(o[Io]=s),t){var e=function(){a.on(i,null)};a.on(i,function(){T(),e()},!0),setTimeout(e,0)}}}function Q(t,e){e.changedTouches&&(e=e.changedTouches[0]);var r=t.ownerSVGElement||t;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Fo){var a=n(t);if(a.scrollX||a.scrollY){r=uo.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Fo=!(o.f||o.e),r.remove()}}return Fo?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}function J(){return uo.event.changedTouches[0].identifier}function tt(t){return t>0?1:0>t?-1:0}function et(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function rt(t){return t>1?0:-1>t?Uo:Math.acos(t)}function nt(t){return t>1?Go:-1>t?-Go:Math.asin(t)}function it(t){return((t=Math.exp(t))-1/t)/2}function at(t){return((t=Math.exp(t))+1/t)/2}function ot(t){return((t=Math.exp(2*t))-1)/(t+1)}function st(t){return(t=Math.sin(t/2))*t}function lt(){}function ut(t,e,r){return this instanceof ut?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof ut?new ut(t.h,t.s,t.l):kt(""+t,At,ut):new ut(t,e,r)}function ct(t,e,r){function n(t){return t>360?t-=360:0>t&&(t+=360),60>t?a+(o-a)*t/60:180>t?o:240>t?a+(o-a)*(240-t)/60:a}function i(t){return Math.round(255*n(t))}var a,o;return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:0>e?0:e>1?1:e,r=0>r?0:r>1?1:r,o=.5>=r?r*(1+e):r+e-r*e,a=2*r-o,new bt(i(t+120),i(t),i(t-120))}function ft(t,e,r){return this instanceof ft?(this.h=+t,this.c=+e,void(this.l=+r)):arguments.length<2?t instanceof ft?new ft(t.h,t.c,t.l):t instanceof pt?gt(t.l,t.a,t.b):gt((t=Mt((t=uo.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ft(t,e,r)}function ht(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new pt(r,Math.cos(t*=Ho)*e,Math.sin(t)*e)}function pt(t,e,r){return this instanceof pt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof pt?new pt(t.l,t.a,t.b):t instanceof ft?ht(t.h,t.c,t.l):Mt((t=bt(t)).r,t.g,t.b):new pt(t,e,r)}function dt(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return i=vt(i)*rs,n=vt(n)*ns,a=vt(a)*is,new bt(yt(3.2404542*i-1.5371385*n-.4985314*a),yt(-.969266*i+1.8760108*n+.041556*a),yt(.0556434*i-.2040259*n+1.0572252*a))}function gt(t,e,r){return t>0?new ft(Math.atan2(r,e)*Yo,Math.sqrt(e*e+r*r),t):new ft(NaN,NaN,t)}function vt(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function mt(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function yt(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function bt(t,e,r){return this instanceof bt?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof bt?new bt(t.r,t.g,t.b):kt(""+t,bt,ct):new bt(t,e,r)}function xt(t){return new bt(t>>16,t>>8&255,255&t)}function _t(t){return xt(t)+""}function wt(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function kt(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(Et(i[0]),Et(i[1]),Et(i[2]))}return(a=ss.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o=o>>4|o,s=240&a,s=s>>4|s,l=15&a,l=l<<4|l):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function At(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=.5>l?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(r>e?6:0):e==o?(r-t)/s+2:(t-e)/s+4,n*=60):(n=NaN,i=l>0&&1>l?0:n),new ut(n,i,l)}function Mt(t,e,r){t=Tt(t),e=Tt(e),r=Tt(r);var n=mt((.4124564*t+.3575761*e+.1804375*r)/rs),i=mt((.2126729*t+.7151522*e+.072175*r)/ns),a=mt((.0193339*t+.119192*e+.9503041*r)/is);return pt(116*i-16,500*(n-i),200*(i-a))}function Tt(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Et(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Lt(t){return"function"==typeof t?t:function(){return t}}function St(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),Ct(e,r,t,n)}}function Ct(t,e,r,n){function i(){var t,e=l.status;if(!e&&Pt(l)||e>=200&&300>e||304===e){try{t=r.call(a,l)}catch(n){return void o.error.call(a,n)}o.load.call(a,t)}else o.error.call(a,l)}var a={},o=uo.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,u=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(t){var e=uo.event;uo.event=t;try{o.progress.call(a,l)}finally{uo.event=e}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(e=null==t?null:t+"",a):e},a.responseType=function(t){return arguments.length?(u=t,a):u},a.response=function(t){return r=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(fo(arguments)))}}),a.send=function(r,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),l.open(r,t,!0),null==e||"accept"in s||(s.accept=e+",*/*"),l.setRequestHeader)for(var c in s)l.setRequestHeader(c,s[c]);return null!=e&&l.overrideMimeType&&l.overrideMimeType(e),null!=u&&(l.responseType=u),null!=i&&a.on("error",i).on("load",function(t){i(null,t)}),o.beforesend.call(a,l),l.send(null==n?null:n),a},a.abort=function(){return l.abort(),a},uo.rebind(a,o,"on"),null==n?a:a.get(zt(n))}function zt(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}function Pt(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function Rt(t,e,r){var n=arguments.length;2>n&&(e=0),3>n&&(r=Date.now());var i=r+e,a={c:t,t:i,n:null};return us?us.n=a:ls=a,us=a,cs||(fs=clearTimeout(fs),cs=1,hs(jt)),a}function jt(){var t=Ot(),e=It()-t;e>24?(isFinite(e)&&(clearTimeout(fs),fs=setTimeout(jt,e)),cs=0):(cs=1,hs(jt))}function Ot(){for(var t=Date.now(),e=ls;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function It(){for(var t,e=ls,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}}function Dt(t){var e=t.decimal,r=t.thousands,n=t.grouping,i=t.currency,a=n&&r?function(t,e){for(var i=t.length,a=[],o=0,s=n[0],l=0;i>0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(i-=s,i+s)),!((l+=s+1)>e));)s=n[o=(o+1)%n.length];return a.reverse().join(r)}:x;return function(t){var r=ds.exec(t),n=r[1]||" ",o=r[2]||">",s=r[3]||"-",l=r[4]||"",u=r[5],c=+r[6],f=r[7],h=r[8],p=r[9],d=1,g="",v="",m=!1,y=!0;switch(h&&(h=+h.substring(1)),(u||"0"===n&&"="===o)&&(u=n="0",o="="),p){case"n":f=!0,p="g";break;case"%":d=100,v="%",p="f";break;case"p":d=100,v="%",p="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+p.toLowerCase());case"c":y=!1;case"d":m=!0,h=0;break;case"s":d=-1,p="r"}"$"===l&&(g=i[0],v=i[1]),"r"!=p||h||(p="g"),null!=h&&("g"==p?h=Math.max(1,Math.min(21,h)):"e"!=p&&"f"!=p||(h=Math.max(0,Math.min(20,h)))),p=gs.get(p)||Bt;var b=u&&f;return function(t){var r=v;if(m&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>d){var l=uo.formatPrefix(t,h);t=l.scale(t),r=l.symbol+v}else t*=d;t=p(t,h);var x,_,w=t.lastIndexOf(".");if(0>w){var k=y?t.lastIndexOf("e"):-1;0>k?(x=t,_=""):(x=t.substring(0,k),_=t.substring(k))}else x=t.substring(0,w),_=e+t.substring(w+1);!u&&f&&(x=a(x,1/0));var A=g.length+x.length+_.length+(b?0:i.length),M=c>A?new Array(A=c-A+1).join(n):"";return b&&(x=a(M+x,M.length?c-_.length:1/0)),i+=g,t=x+_,("<"===o?i+t+M:">"===o?M+i+t:"^"===o?M.substring(0,A>>=1)+i+t+M.substring(A):i+(b?t:M+t))+r}}}function Bt(t){return t+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Vt(t,e,r){function n(e){var r=t(e),n=a(r,1);return n-e>e-r?r:n}function i(r){return e(r=t(new ms(r-1)),1),r}function a(t,r){return e(t=new ms(+t),r),t}function o(t,n,a){var o=i(t),s=[];if(a>1)for(;n>o;)r(o)%a||s.push(new Date(+o)),e(o,1);else for(;n>o;)s.push(new Date(+o)),e(o,1);return s}function s(t,e,r){try{ms=Ut;var n=new Ut;return n._=t,o(n,e,r)}finally{ms=Date}}t.floor=t,t.round=n,t.ceil=i,t.offset=a,t.range=o;var l=t.utc=qt(t);return l.floor=l,l.round=qt(n),l.ceil=qt(i),l.offset=qt(a),l.range=s,t}function qt(t){return function(e,r){try{ms=Ut;var n=new Ut;return n._=e,t(n,r)._}finally{ms=Date}}}function Gt(t){function e(t){function e(e){for(var r,i,a,o=[],s=-1,l=0;++ss;){if(n>=u)return-1;if(i=e.charCodeAt(s++),37===i){if(o=e.charAt(s++),a=S[o in bs?e.charAt(s++):o],!a||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}function n(t,e,r){w.lastIndex=0;var n=w.exec(e.slice(r));return n?(t.w=k.get(n[0].toLowerCase()),r+n[0].length):-1}function i(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.w=_.get(n[0].toLowerCase()),r+n[0].length):-1}function a(t,e,r){T.lastIndex=0;var n=T.exec(e.slice(r));return n?(t.m=E.get(n[0].toLowerCase()),r+n[0].length):-1}function o(t,e,r){A.lastIndex=0;var n=A.exec(e.slice(r));return n?(t.m=M.get(n[0].toLowerCase()),r+n[0].length):-1}function s(t,e,n){return r(t,L.c.toString(),e,n)}function l(t,e,n){return r(t,L.x.toString(),e,n)}function u(t,e,n){return r(t,L.X.toString(),e,n)}function c(t,e,r){var n=b.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)}var f=t.dateTime,h=t.date,p=t.time,d=t.periods,g=t.days,v=t.shortDays,m=t.months,y=t.shortMonths;e.utc=function(t){function r(t){try{ms=Ut;var e=new ms;return e._=t,n(e)}finally{ms=Date}}var n=e(t);return r.parse=function(t){try{ms=Ut;var e=n.parse(t);return e&&e._}finally{ms=Date}},r.toString=n.toString,r},e.multi=e.utc.multi=ce;var b=uo.map(),x=Yt(g),_=Xt(g),w=Yt(v),k=Xt(v),A=Yt(m),M=Xt(m),T=Yt(y),E=Xt(y);d.forEach(function(t,e){b.set(t.toLowerCase(),e)});var L={a:function(t){return v[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:e(f),d:function(t,e){return Ht(t.getDate(),e,2)},e:function(t,e){return Ht(t.getDate(),e,2)},H:function(t,e){return Ht(t.getHours(),e,2)},I:function(t,e){return Ht(t.getHours()%12||12,e,2)},j:function(t,e){return Ht(1+vs.dayOfYear(t),e,3)},L:function(t,e){return Ht(t.getMilliseconds(),e,3)},m:function(t,e){return Ht(t.getMonth()+1,e,2)},M:function(t,e){return Ht(t.getMinutes(),e,2)},p:function(t){return d[+(t.getHours()>=12)]},S:function(t,e){return Ht(t.getSeconds(),e,2)},U:function(t,e){return Ht(vs.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Ht(vs.mondayOfYear(t),e,2)},x:e(h),X:e(p),y:function(t,e){return Ht(t.getFullYear()%100,e,2)},Y:function(t,e){return Ht(t.getFullYear()%1e4,e,4)},Z:le,"%":function(){return"%"}},S={a:n,A:i,b:a,B:o,c:s,d:re,e:re,H:ie,I:ie,j:ne,L:se,m:ee,M:ae,p:c,S:oe,U:Zt,w:Wt,W:Kt,x:l,X:u,y:Qt,Y:$t,Z:Jt,"%":ue};return e}function Ht(t,e,r){var n=0>t?"-":"",i=(n?-t:t)+"",a=i.length;return n+(r>a?new Array(r-a+1).join(e)+i:i)}function Yt(t){return new RegExp("^(?:"+t.map(uo.requote).join("|")+")","i")}function Xt(t){for(var e=new f,r=-1,n=t.length;++r68?1900:2e3)}function ee(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function re(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function ne(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function ie(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function ae(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function oe(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function se(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function le(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=wo(e)/60|0,i=wo(e)%60;return r+Ht(n,"0",2)+Ht(i,"0",2)}function ue(t,e,r){_s.lastIndex=0;var n=_s.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function ce(t){for(var e=t.length,r=-1;++r=0?1:-1,s=o*r,l=Math.cos(e),u=Math.sin(e),c=a*u,f=i*l+c*Math.cos(s),h=c*o*Math.sin(s);Es.add(Math.atan2(h,f)),n=t,i=l,a=u}var e,r,n,i,a;Ls.point=function(o,s){Ls.point=t,n=(e=o)*Ho,i=Math.cos(s=(r=s)*Ho/2+Uo/4),a=Math.sin(s)},Ls.lineEnd=function(){t(e,r)}}function me(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function ye(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function be(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xe(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function _e(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function we(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function ke(t){return[Math.atan2(t[1],t[0]),nt(t[2])]}function Ae(t,e){return wo(t[0]-e[0])s;++s)i.point((r=t[s])[0],r[1]);return void i.lineEnd()}var l=new je(r,t,null,!0),u=new je(r,null,l,!1);l.o=u,a.push(l),o.push(u),l=new je(n,t,null,!1),u=new je(n,null,l,!0),l.o=u,a.push(l),o.push(u)}}),o.sort(e),Re(a),Re(o),a.length){for(var s=0,l=r,u=o.length;u>s;++s)o[s].e=l=!l;for(var c,f,h=a[0];;){for(var p=h,d=!0;p.v;)if((p=p.n)===h)return;c=p.z,i.lineStart();do{if(p.v=p.o.v=!0,p.e){if(d)for(var s=0,u=c.length;u>s;++s)i.point((f=c[s])[0],f[1]);else n(p.x,p.n.x,1,i);p=p.n}else{if(d){c=p.p.z;for(var s=c.length-1;s>=0;--s)i.point((f=c[s])[0],f[1])}else n(p.x,p.p.x,-1,i);p=p.p}p=p.o,c=p.z,d=!d}while(!p.v);i.lineEnd()}}}function Re(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n0){for(_||(a.polygonStart(),_=!0),a.lineStart();++o1&&2&e&&r.push(r.pop().concat(r.shift())),p.push(r.filter(Ie))}var p,d,g,v=e(a),m=i.invert(n[0],n[1]),y={point:o,lineStart:l,lineEnd:u,polygonStart:function(){y.point=c,y.lineStart=f,y.lineEnd=h,p=[],d=[]},polygonEnd:function(){y.point=o,y.lineStart=l,y.lineEnd=u,p=uo.merge(p);var t=Ve(m,d);p.length?(_||(a.polygonStart(),_=!0),Pe(p,Fe,t,r,a)):t&&(_||(a.polygonStart(),_=!0),a.lineStart(),r(null,null,1,a),a.lineEnd()),_&&(a.polygonEnd(),_=!1),p=d=null},sphere:function(){a.polygonStart(),a.lineStart(),r(null,null,1,a),a.lineEnd(),a.polygonEnd()}},b=Ne(),x=e(b),_=!1;return y}}function Ie(t){return t.length>1}function Ne(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:k,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Fe(t,e){return((t=t.x)[0]<0?t[1]-Go-Do:Go-t[1])-((e=e.x)[0]<0?e[1]-Go-Do:Go-e[1])}function De(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Uo:-Uo,l=wo(a-r);wo(l-Uo)0?Go:-Go),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Uo&&(wo(r-i)Do?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}function Ue(t,e,r,n){var i;if(null==t)i=r*Go,n.point(-Uo,i),n.point(0,i),n.point(Uo,i),n.point(Uo,0),n.point(Uo,-i),n.point(0,-i),n.point(-Uo,-i),n.point(-Uo,0),n.point(-Uo,i);else if(wo(t[0]-e[0])>Do){var a=t[0]s;++s){var u=e[s],c=u.length;if(c)for(var f=u[0],h=f[0],p=f[1]/2+Uo/4,d=Math.sin(p),g=Math.cos(p),v=1;;){v===c&&(v=0),t=u[v];var m=t[0],y=t[1]/2+Uo/4,b=Math.sin(y),x=Math.cos(y),_=m-h,w=_>=0?1:-1,k=w*_,A=k>Uo,M=d*b;if(Es.add(Math.atan2(M*w*Math.sin(k),g*x+M*Math.cos(k))),a+=A?_+w*Vo:_,A^h>=r^m>=r){var T=be(me(f),me(t));we(T);var E=be(i,T);we(E);var L=(A^_>=0?-1:1)*nt(E[2]);(n>L||n===L&&(T[0]||T[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;h=m,d=b,g=x,f=t}}return(-Do>a||Do>a&&-Do>Es)^1&o}function qe(t){function e(t,e){return Math.cos(t)*Math.cos(e)>a}function r(t){var r,a,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(f,h){var p,d=[f,h],g=e(f,h),v=o?g?0:i(f,h):g?i(f+(0>f?Uo:-Uo),h):0;if(!r&&(u=l=g)&&t.lineStart(),g!==l&&(p=n(r,d),(Ae(r,p)||Ae(d,p))&&(d[0]+=Do,d[1]+=Do,g=e(d[0],d[1]))),g!==l)c=0,g?(t.lineStart(),p=n(d,r),t.point(p[0],p[1])):(p=n(r,d),t.point(p[0],p[1]),t.lineEnd()),r=p;else if(s&&r&&o^g){var m;v&a||!(m=n(d,r,!0))||(c=0,o?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||r&&Ae(r,d)||t.point(d[0],d[1]),r=d,l=g,a=v},lineEnd:function(){l&&t.lineEnd(),r=null},clean:function(){return c|(u&&l)<<1}}}function n(t,e,r){var n=me(t),i=me(e),o=[1,0,0],s=be(n,i),l=ye(s,s),u=s[0],c=l-u*u;if(!c)return!r&&t;var f=a*l/c,h=-a*u/c,p=be(o,s),d=_e(o,f),g=_e(s,h);xe(d,g);var v=p,m=ye(d,v),y=ye(v,v),b=m*m-y*(ye(d,d)-1);if(!(0>b)){var x=Math.sqrt(b),_=_e(v,(-m-x)/y);if(xe(_,d),_=ke(_),!r)return _;var w,k=t[0],A=e[0],M=t[1],T=e[1];k>A&&(w=k,k=A,A=w);var E=A-k,L=wo(E-Uo)E;if(!L&&M>T&&(w=M,M=T,T=w),S?L?M+T>0^_[1]<(wo(_[0]-k)Uo^(k<=_[0]&&_[0]<=A)){var C=_e(v,(-m+x)/y);return xe(C,d),[_,ke(C)]}}}function i(e,r){var n=o?t:Uo-t,i=0;return-n>e?i|=1:e>n&&(i|=2),-n>r?i|=4:r>n&&(i|=8),i}var a=Math.cos(t),o=a>0,s=wo(a)>Do,l=vr(t,6*Ho);return Oe(e,r,l,o?[0,-t]:[-Uo,t-Uo])}function Ge(t,e,r,n){return function(i){var a,o=i.a,s=i.b,l=o.x,u=o.y,c=s.x,f=s.y,h=0,p=1,d=c-l,g=f-u;if(a=t-l,d||!(a>0)){if(a/=d,0>d){if(h>a)return;p>a&&(p=a)}else if(d>0){if(a>p)return;a>h&&(h=a)}if(a=r-l,d||!(0>a)){if(a/=d,0>d){if(a>p)return;a>h&&(h=a)}else if(d>0){if(h>a)return;p>a&&(p=a)}if(a=e-u,g||!(a>0)){if(a/=g,0>g){if(h>a)return;p>a&&(p=a)}else if(g>0){if(a>p)return;a>h&&(h=a)}if(a=n-u,g||!(0>a)){if(a/=g,0>g){if(a>p)return;a>h&&(h=a)}else if(g>0){if(h>a)return;p>a&&(p=a)}return h>0&&(i.a={x:l+h*d,y:u+h*g}),1>p&&(i.b={x:l+p*d,y:u+p*g}),i}}}}}}function He(t,e,r,n){function i(n,i){return wo(n[0]-t)0?0:3:wo(n[0]-r)0?2:1:wo(n[1]-e)0?1:0:i>0?3:2}function a(t,e){return o(t.x,e.x)}function o(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,r=v.length,n=t[1],i=0;r>i;++i)for(var a,o=1,s=v[i],l=s.length,u=s[0];l>o;++o)a=s[o],u[1]<=n?a[1]>n&&et(u,a,t)>0&&++e:a[1]<=n&&et(u,a,t)<0&&--e,u=a;return 0!==e}function u(a,s,l,u){var c=0,f=0;if(null==a||(c=i(a,l))!==(f=i(s,l))||o(a,s)<0^l>0){do u.point(0===c||3===c?t:r,c>1?n:e);while((c=(c+l+4)%4)!==f)}else u.point(s[0],s[1])}function c(i,a){return i>=t&&r>=i&&a>=e&&n>=a}function f(t,e){c(t,e)&&s.point(t,e)}function h(){S.point=d,v&&v.push(m=[]),A=!0,k=!1,_=w=NaN}function p(){g&&(d(y,b),x&&k&&E.rejoin(),g.push(E.buffer())),S.point=f,k&&s.lineEnd()}function d(t,e){t=Math.max(-Vs,Math.min(Vs,t)),e=Math.max(-Vs,Math.min(Vs,e));var r=c(t,e);if(v&&m.push([t,e]),A)y=t,b=e,x=r,A=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&k)s.point(t,e);else{var n={a:{x:_,y:w},b:{x:t,y:e}};L(n)?(k||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),M=!1):r&&(s.lineStart(),s.point(t,e),M=!1)}_=t,w=e,k=r}var g,v,m,y,b,x,_,w,k,A,M,T=s,E=Ne(),L=Ge(t,e,r,n),S={point:f,lineStart:h,lineEnd:p,polygonStart:function(){s=E,g=[],v=[],M=!0},polygonEnd:function(){s=T,g=uo.merge(g);var e=l([t,n]),r=M&&e,i=g.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),u(null,null,1,s),s.lineEnd()),i&&Pe(g,a,e,u,s),s.polygonEnd()),g=v=m=null}};return S}}function Ye(t){var e=0,r=Uo/3,n=lr(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Uo/180,r=t[1]*Uo/180):[e/Uo*180,r/Uo*180]},i}function Xe(t,e){function r(t,e){var r=Math.sqrt(a-2*i*Math.sin(e))/i;return[r*Math.sin(t*=i),o-r*Math.cos(t)]}var n=Math.sin(t),i=(n+Math.sin(e))/2,a=1+n*(2*i-n),o=Math.sqrt(a)/i;return r.invert=function(t,e){var r=o-e;return[Math.atan2(t,r)/i,nt((a-(t*t+r*r)*i*i)/(2*i))]},r}function We(){function t(t,e){Gs+=i*t-n*e,n=t,i=e}var e,r,n,i;Zs.point=function(a,o){Zs.point=t,e=n=a,r=i=o},Zs.lineEnd=function(){t(e,r)}}function Ze(t,e){Hs>t&&(Hs=t),t>Xs&&(Xs=t),Ys>e&&(Ys=e),e>Ws&&(Ws=e)}function Ke(){function t(t,e){o.push("M",t,",",e,a)}function e(t,e){o.push("M",t,",",e),s.point=r}function r(t,e){o.push("L",t,",",e)}function n(){s.point=t}function i(){o.push("Z")}var a=$e(4.5),o=[],s={point:t,lineStart:function(){s.point=e},lineEnd:n,polygonStart:function(){ -s.lineEnd=i},polygonEnd:function(){s.lineEnd=n,s.point=t},pointRadius:function(t){return a=$e(t),s},result:function(){if(o.length){var t=o.join("");return o=[],t}}};return s}function $e(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Qe(t,e){zs+=t,Ps+=e,++Rs}function Je(){function t(t,n){var i=t-e,a=n-r,o=Math.sqrt(i*i+a*a);js+=o*(e+t)/2,Os+=o*(r+n)/2,Is+=o,Qe(e=t,r=n)}var e,r;$s.point=function(n,i){$s.point=t,Qe(e=n,r=i)}}function tr(){$s.point=Qe}function er(){function t(t,e){var r=t-n,a=e-i,o=Math.sqrt(r*r+a*a);js+=o*(n+t)/2,Os+=o*(i+e)/2,Is+=o,o=i*t-n*e,Ns+=o*(n+t),Fs+=o*(i+e),Ds+=3*o,Qe(n=t,i=e)}var e,r,n,i;$s.point=function(a,o){$s.point=t,Qe(e=n=a,r=i=o)},$s.lineEnd=function(){t(e,r)}}function rr(t){function e(e,r){t.moveTo(e+o,r),t.arc(e,r,o,0,Vo)}function r(e,r){t.moveTo(e,r),s.point=n}function n(e,r){t.lineTo(e,r)}function i(){s.point=e}function a(){t.closePath()}var o=4.5,s={point:e,lineStart:function(){s.point=r},lineEnd:i,polygonStart:function(){s.lineEnd=a},polygonEnd:function(){s.lineEnd=i,s.point=e},pointRadius:function(t){return o=t,s},result:k};return s}function nr(t){function e(t){return(s?n:r)(t)}function r(e){return or(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})}function n(e){function r(r,n){r=t(r,n),e.point(r[0],r[1])}function n(){b=NaN,A.point=a,e.lineStart()}function a(r,n){var a=me([r,n]),o=t(r,n);i(b,x,y,_,w,k,b=o[0],x=o[1],y=r,_=a[0],w=a[1],k=a[2],s,e),e.point(b,x)}function o(){A.point=r,e.lineEnd()}function l(){n(),A.point=u,A.lineEnd=c}function u(t,e){a(f=t,h=e),p=b,d=x,g=_,v=w,m=k,A.point=a}function c(){i(b,x,y,_,w,k,p,d,f,g,v,m,s,e),A.lineEnd=o,o()}var f,h,p,d,g,v,m,y,b,x,_,w,k,A={point:r,lineStart:n,lineEnd:o,polygonStart:function(){e.polygonStart(),A.lineStart=l},polygonEnd:function(){e.polygonEnd(),A.lineStart=n}};return A}function i(e,r,n,s,l,u,c,f,h,p,d,g,v,m){var y=c-e,b=f-r,x=y*y+b*b;if(x>4*a&&v--){var _=s+p,w=l+d,k=u+g,A=Math.sqrt(_*_+w*w+k*k),M=Math.asin(k/=A),T=wo(wo(k)-1)a||wo((y*C+b*z)/x-.5)>.3||o>s*p+l*d+u*g)&&(i(e,r,n,s,l,u,L,S,T,_/=A,w/=A,k,v,m),m.point(L,S),i(L,S,T,_,w,k,c,f,h,p,d,g,v,m))}}var a=.5,o=Math.cos(30*Ho),s=16;return e.precision=function(t){return arguments.length?(s=(a=t*t)>0&&16,e):Math.sqrt(a)},e}function ir(t){var e=nr(function(e,r){return t([e*Yo,r*Yo])});return function(t){return ur(e(t))}}function ar(t){this.stream=t}function or(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){return t=s(t[0]*Ho,t[1]*Ho),[t[0]*h+l,u-t[1]*h]}function r(t){return t=s.invert((t[0]-l)/h,(u-t[1])/h),t&&[t[0]*Yo,t[1]*Yo]}function n(){s=Ce(o=hr(m,y,b),a);var t=a(g,v);return l=p-t[0]*h,u=d+t[1]*h,i()}function i(){return c&&(c.valid=!1,c=null),e}var a,o,s,l,u,c,f=nr(function(t,e){return t=a(t,e),[t[0]*h+l,u-t[1]*h]}),h=150,p=480,d=250,g=0,v=0,m=0,y=0,b=0,_=Us,w=x,k=null,A=null;return e.stream=function(t){return c&&(c.valid=!1),c=ur(_(o,f(w(t)))),c.valid=!0,c},e.clipAngle=function(t){return arguments.length?(_=null==t?(k=t,Us):qe((k=+t)*Ho),i()):k},e.clipExtent=function(t){return arguments.length?(A=t,w=t?He(t[0][0],t[0][1],t[1][0],t[1][1]):x,i()):A},e.scale=function(t){return arguments.length?(h=+t,n()):h},e.translate=function(t){return arguments.length?(p=+t[0],d=+t[1],n()):[p,d]},e.center=function(t){return arguments.length?(g=t[0]%360*Ho,v=t[1]%360*Ho,n()):[g*Yo,v*Yo]},e.rotate=function(t){return arguments.length?(m=t[0]%360*Ho,y=t[1]%360*Ho,b=t.length>2?t[2]%360*Ho:0,n()):[m*Yo,y*Yo,b*Yo]},uo.rebind(e,f,"precision"),function(){return a=t.apply(this,arguments),e.invert=a.invert&&r,n()}}function ur(t){return or(t,function(e,r){t.point(e*Ho,r*Ho)})}function cr(t,e){return[t,e]}function fr(t,e){return[t>Uo?t-Vo:-Uo>t?t+Vo:t,e]}function hr(t,e,r){return t?e||r?Ce(dr(t),gr(e,r)):dr(t):e||r?gr(e,r):fr}function pr(t){return function(e,r){return e+=t,[e>Uo?e-Vo:-Uo>e?e+Vo:e,r]}}function dr(t){var e=pr(t);return e.invert=pr(-t),e}function gr(t,e){function r(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,u=Math.sin(e),c=u*n+s*i;return[Math.atan2(l*a-c*o,s*n-u*i),nt(c*a+l*o)]}var n=Math.cos(t),i=Math.sin(t),a=Math.cos(e),o=Math.sin(e);return r.invert=function(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,u=Math.sin(e),c=u*a-l*o;return[Math.atan2(l*a+u*o,s*n+c*i),nt(c*n-s*i)]},r}function vr(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=mr(r,i),a=mr(r,a),(o>0?a>i:i>a)&&(i+=o*Vo)):(i=t+o*Vo,a=t-.5*l);for(var u,c=i;o>0?c>a:a>c;c-=l)s.point((u=ke([r,-n*Math.cos(c),-n*Math.sin(c)]))[0],u[1])}}function mr(t,e){var r=me(e);r[0]-=t,we(r);var n=rt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-Do)%(2*Math.PI)}function yr(t,e,r){var n=uo.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[t,e]})}}function br(t,e,r){var n=uo.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[e,t]})}}function xr(t){return t.source}function _r(t){return t.target}function wr(t,e,r,n){var i=Math.cos(e),a=Math.sin(e),o=Math.cos(n),s=Math.sin(n),l=i*Math.cos(t),u=i*Math.sin(t),c=o*Math.cos(r),f=o*Math.sin(r),h=2*Math.asin(Math.sqrt(st(n-e)+i*o*st(r-t))),p=1/Math.sin(h),d=h?function(t){var e=Math.sin(t*=h)*p,r=Math.sin(h-t)*p,n=r*l+e*c,i=r*u+e*f,o=r*a+e*s;return[Math.atan2(i,n)*Yo,Math.atan2(o,Math.sqrt(n*n+i*i))*Yo]}:function(){return[t*Yo,e*Yo]};return d.distance=h,d}function kr(){function t(t,i){var a=Math.sin(i*=Ho),o=Math.cos(i),s=wo((t*=Ho)-e),l=Math.cos(s);Qs+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=n*a-r*o*l)*s),r*a+n*o*l),e=t,r=a,n=o}var e,r,n;Js.point=function(i,a){e=i*Ho,r=Math.sin(a*=Ho),n=Math.cos(a),Js.point=t},Js.lineEnd=function(){Js.point=Js.lineEnd=k}}function Ar(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}function Mr(t,e){function r(t,e){o>0?-Go+Do>e&&(e=-Go+Do):e>Go-Do&&(e=Go-Do);var r=o/Math.pow(i(e),a);return[r*Math.sin(a*t),o-r*Math.cos(a*t)]}var n=Math.cos(t),i=function(t){return Math.tan(Uo/4+t/2)},a=t===e?Math.sin(t):Math.log(n/Math.cos(e))/Math.log(i(e)/i(t)),o=n*Math.pow(i(t),a)/a;return a?(r.invert=function(t,e){var r=o-e,n=tt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(o/n,1/a))-Go]},r):Er}function Tr(t,e){function r(t,e){var r=a-e;return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}var n=Math.cos(t),i=t===e?Math.sin(t):(n-Math.cos(e))/(e-t),a=n/i+t;return wo(i)i;i++){for(;n>1&&et(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function Rr(t,e){return t[0]-e[0]||t[1]-e[1]}function jr(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function Or(t,e,r,n){var i=t[0],a=r[0],o=e[0]-i,s=n[0]-a,l=t[1],u=r[1],c=e[1]-l,f=n[1]-u,h=(s*(l-u)-f*(i-a))/(f*o-s*c);return[i+h*o,l+h*c]}function Ir(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}function Nr(){an(this),this.edge=this.site=this.circle=null}function Fr(t){var e=fl.pop()||new Nr;return e.site=t,e}function Dr(t){Zr(t),ll.remove(t),fl.push(t),an(t)}function Br(t){var e=t.circle,r=e.x,n=e.cy,i={x:r,y:n},a=t.P,o=t.N,s=[t];Dr(t);for(var l=a;l.circle&&wo(r-l.circle.x)c;++c)u=s[c],l=s[c-1],en(u.edge,l.site,u.site,i);l=s[0],u=s[f-1],u.edge=Jr(l.site,u.site,null,i),Wr(l),Wr(u)}function Ur(t){for(var e,r,n,i,a=t.x,o=t.y,s=ll._;s;)if(n=Vr(s,o)-a,n>Do)s=s.L;else{if(i=a-qr(s,o),!(i>Do)){n>-Do?(e=s.P,r=s):i>-Do?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=Fr(t);if(ll.insert(e,l),e||r){if(e===r)return Zr(e),r=Fr(e.site),ll.insert(l,r),l.edge=r.edge=Jr(e.site,l.site),Wr(e),void Wr(r);if(!r)return void(l.edge=Jr(e.site,l.site));Zr(e),Zr(r);var u=e.site,c=u.x,f=u.y,h=t.x-c,p=t.y-f,d=r.site,g=d.x-c,v=d.y-f,m=2*(h*v-p*g),y=h*h+p*p,b=g*g+v*v,x={x:(v*y-p*b)/m+c,y:(h*b-g*y)/m+f};en(r.edge,u,d,x),l.edge=Jr(u,t,null,x),r.edge=Jr(t,d,null,x),Wr(e),Wr(r)}}function Vr(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-(1/0);r=o.site;var s=r.x,l=r.y,u=l-e;if(!u)return s;var c=s-n,f=1/a-1/u,h=c/u;return f?(-h+Math.sqrt(h*h-2*f*(c*c/(-2*u)-l+u/2+i-a/2)))/f+n:(n+s)/2}function qr(t,e){var r=t.N;if(r)return Vr(r,e);var n=t.site;return n.y===e?n.x:1/0}function Gr(t){this.site=t,this.edges=[]}function Hr(t){for(var e,r,n,i,a,o,s,l,u,c,f=t[0][0],h=t[1][0],p=t[0][1],d=t[1][1],g=sl,v=g.length;v--;)if(a=g[v],a&&a.prepare())for(s=a.edges,l=s.length,o=0;l>o;)c=s[o].end(),n=c.x,i=c.y,u=s[++o%l].start(),e=u.x,r=u.y,(wo(n-e)>Do||wo(i-r)>Do)&&(s.splice(o,0,new rn(tn(a.site,c,wo(n-f)Do?{x:f,y:wo(e-f)Do?{x:wo(r-d)Do?{x:h,y:wo(e-h)Do?{x:wo(r-p)=-Bo)){var p=l*l+u*u,d=c*c+f*f,g=(f*p-u*d)/h,v=(l*d-c*p)/h,f=v+s,m=hl.pop()||new Xr;m.arc=t,m.site=i,m.x=g+o,m.y=f+Math.sqrt(g*g+v*v),m.cy=f,t.circle=m;for(var y=null,b=cl._;b;)if(m.yv||v>=s)return;if(h>d){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.yn||n>1)if(h>d){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.yp){if(a){if(a.x>=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xa||f>o||n>h||i>p)){if(d=t.point){var d,g=e-t.x,v=r-t.y,m=g*g+v*v;if(l>m){var y=Math.sqrt(l=m);n=e-y,i=r-y,a=e+y,o=r+y,s=d}}for(var b=t.nodes,x=.5*(c+h),_=.5*(f+p),w=e>=x,k=r>=_,A=k<<1|w,M=A+4;M>A;++A)if(t=b[3&A])switch(3&A){case 0:u(t,c,f,x,_);break;case 1:u(t,x,f,h,_);break;case 2:u(t,c,_,x,p);break;case 3:u(t,x,_,h,p)}}}(t,n,i,a,o),s}function mn(t,e){t=uo.rgb(t),e=uo.rgb(e);var r=t.r,n=t.g,i=t.b,a=e.r-r,o=e.g-n,s=e.b-i;return function(t){return"#"+wt(Math.round(r+a*t))+wt(Math.round(n+o*t))+wt(Math.round(i+s*t))}}function yn(t,e){var r,n={},i={};for(r in t)r in e?n[r]=_n(t[r],e[r]):i[r]=t[r];for(r in e)r in t||(i[r]=e[r]);return function(t){for(r in n)i[r]=n[r](t);return i}}function bn(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function xn(t,e){var r,n,i,a=dl.lastIndex=gl.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=dl.exec(t))&&(n=gl.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:bn(r,n)})),a=gl.lastIndex;return an;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}function _n(t,e){for(var r,n=uo.interpolators.length;--n>=0&&!(r=uo.interpolators[n](t,e)););return r}function wn(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;s>r;++r)n.push(_n(t[r],e[r]));for(;a>r;++r)i[r]=t[r];for(;o>r;++r)i[r]=e[r];return function(t){for(r=0;s>r;++r)i[r]=n[r](t);return i}}function kn(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function An(t){return function(e){return 1-t(1-e)}}function Mn(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Tn(t){return t*t}function En(t){return t*t*t}function Ln(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(.5>t?r:3*(t-e)+r-.75)}function Sn(t){return function(e){return Math.pow(e,t)}}function Cn(t){return 1-Math.cos(t*Go)}function zn(t){return Math.pow(2,10*(t-1))}function Pn(t){return 1-Math.sqrt(1-t*t)}function Rn(t,e){var r;return arguments.length<2&&(e=.45),arguments.length?r=e/Vo*Math.asin(1/t):(t=1,r=e/4),function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*Vo/e)}}function jn(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}}function On(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function In(t,e){t=uo.hcl(t),e=uo.hcl(e);var r=t.h,n=t.c,i=t.l,a=e.h-r,o=e.c-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.c:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ht(r+a*t,n+o*t,i+s*t)+""}}function Nn(t,e){t=uo.hsl(t),e=uo.hsl(e);var r=t.h,n=t.s,i=t.l,a=e.h-r,o=e.s-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.s:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ct(r+a*t,n+o*t,i+s*t)+""}}function Fn(t,e){t=uo.lab(t),e=uo.lab(e);var r=t.l,n=t.a,i=t.b,a=e.l-r,o=e.a-n,s=e.b-i;return function(t){return dt(r+a*t,n+o*t,i+s*t)+""}}function Dn(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function Bn(t){var e=[t.a,t.b],r=[t.c,t.d],n=Vn(e),i=Un(e,r),a=Vn(qn(r,e,-i))||0;e[0]*r[1]180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(Gn(r)+"rotate(",null,")")-2,x:bn(t,e)})):e&&r.push(Gn(r)+"rotate("+e+")")}function Xn(t,e,r,n){t!==e?n.push({i:r.push(Gn(r)+"skewX(",null,")")-2,x:bn(t,e)}):e&&r.push(Gn(r)+"skewX("+e+")")}function Wn(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(Gn(r)+"scale(",null,",",null,")");n.push({i:i-4,x:bn(t[0],e[0])},{i:i-2,x:bn(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(Gn(r)+"scale("+e+")")}function Zn(t,e){var r=[],n=[];return t=uo.transform(t),e=uo.transform(e),Hn(t.translate,e.translate,r,n),Yn(t.rotate,e.rotate,r,n),Xn(t.skew,e.skew,r,n),Wn(t.scale,e.scale,r,n),t=e=null,function(t){for(var e,i=-1,a=n.length;++i=0;)r.push(i[n])}function li(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++or;++r)(e=t[r][1])>i&&(n=r,i=e);return n}function bi(t){return t.reduce(xi,0)}function xi(t,e){return t+e[1]}function _i(t,e){return wi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function wi(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function ki(t){return[uo.min(t),uo.max(t)]}function Ai(t,e){return t.value-e.value}function Mi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ti(t,e){t._pack_next=e,e._pack_prev=t}function Ei(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Li(t){function e(t){c=Math.min(t.x-t.r,c),f=Math.max(t.x+t.r,f),h=Math.min(t.y-t.r,h),p=Math.max(t.y+t.r,p)}if((r=t.children)&&(u=r.length)){var r,n,i,a,o,s,l,u,c=1/0,f=-(1/0),h=1/0,p=-(1/0);if(r.forEach(Si),n=r[0],n.x=-n.r,n.y=0,e(n),u>1&&(i=r[1],i.x=i.r,i.y=0,e(i),u>2))for(a=r[2],Pi(n,i,a),e(a),Mi(n,a),n._pack_prev=a,Mi(a,i),i=n._pack_next,o=3;u>o;o++){Pi(n,i,a=r[o]);var d=0,g=1,v=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(Ei(s,a)){d=1;break}if(1==d)for(l=n._pack_prev;l!==s._pack_prev&&!Ei(l,a);l=l._pack_prev,v++);d?(v>g||g==v&&i.ro;o++)a=r[o],a.x-=m,a.y-=y,b=Math.max(b,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=b,r.forEach(Ci)}}function Si(t){t._pack_next=t._pack_prev=t}function Ci(t){delete t._pack_next,delete t._pack_prev}function zi(t,e,r,n){var i=t.children;if(t.x=e+=n*t.x,t.y=r+=n*t.y,t.r*=n,i)for(var a=-1,o=i.length;++a=0;)e=i[a],e.z+=r,e.m+=r,r+=e.s+(n+=e.c)}function Fi(t,e,r){return t.a.parent===e.parent?t.a:r}function Di(t){return 1+uo.max(t,function(t){return t.y})}function Bi(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Ui(t){var e=t.children;return e&&e.length?Ui(e[0]):t}function Vi(t){var e,r=t.children;return r&&(e=r.length)?Vi(r[e-1]):t}function qi(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Gi(t,e){var r=t.x+e[3],n=t.y+e[0],i=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return 0>i&&(r+=i/2,i=0),0>a&&(n+=a/2,a=0),{x:r,y:n,dx:i,dy:a}}function Hi(t){var e=t[0],r=t[t.length-1];return r>e?[e,r]:[r,e]}function Yi(t){return t.rangeExtent?t.rangeExtent():Hi(t.range())}function Xi(t,e,r,n){var i=r(t[0],t[1]),a=n(e[0],e[1]);return function(t){return a(i(t))}}function Wi(t,e){var r,n=0,i=t.length-1,a=t[n],o=t[i];return a>o&&(r=n,n=i,i=r,r=a,a=o,o=r),t[n]=e.floor(a),t[i]=e.ceil(o),t}function Zi(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:Tl}function Ki(t,e,r,n){var i=[],a=[],o=0,s=Math.min(t.length,e.length)-1;for(t[s]2?Ki:Xi,l=n?$n:Kn;return o=i(t,e,l,r),s=i(e,t,l,_n),a}function a(t){return o(t)}var o,s;return a.invert=function(t){return s(t)},a.domain=function(e){return arguments.length?(t=e.map(Number),i()):t},a.range=function(t){return arguments.length?(e=t,i()):e},a.rangeRound=function(t){return a.range(t).interpolate(Dn)},a.clamp=function(t){return arguments.length?(n=t,i()):n},a.interpolate=function(t){return arguments.length?(r=t,i()):r},a.ticks=function(e){return ea(t,e)},a.tickFormat=function(e,r){return ra(t,e,r)},a.nice=function(e){return Ji(t,e),i()},a.copy=function(){return $i(t,e,r,n)},i()}function Qi(t,e){return uo.rebind(t,e,"range","rangeRound","interpolate","clamp")}function Ji(t,e){return Wi(t,Zi(ta(t,e)[2])),Wi(t,Zi(ta(t,e)[2])),t}function ta(t,e){null==e&&(e=10);var r=Hi(t),n=r[1]-r[0],i=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),a=e/n*i;return.15>=a?i*=10:.35>=a?i*=5:.75>=a&&(i*=2),r[0]=Math.ceil(r[0]/i)*i,r[1]=Math.floor(r[1]/i)*i+.5*i,r[2]=i,r}function ea(t,e){return uo.range.apply(uo,ta(t,e))}function ra(t,e,r){var n=ta(t,e);if(r){var i=ds.exec(r);if(i.shift(),"s"===i[8]){var a=uo.formatPrefix(Math.max(wo(n[0]),wo(n[1])));return i[7]||(i[7]="."+na(a.scale(n[2]))),i[8]="f",r=uo.format(i.join("")),function(t){return r(a.scale(t))+a.symbol}}i[7]||(i[7]="."+ia(i[8],n)),r=i.join("")}else r=",."+na(n[2])+"f";return uo.format(r)}function na(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function ia(t,e){var r=na(e[2]);return t in El?Math.abs(r-na(Math.max(wo(e[0]),wo(e[1]))))+ +("e"!==t):r-2*("%"===t)}function aa(t,e,r,n){function i(t){return(r?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function a(t){return r?Math.pow(e,t):-Math.pow(e,-t)}function o(e){return t(i(e))}return o.invert=function(e){return a(t.invert(e))},o.domain=function(e){return arguments.length?(r=e[0]>=0,t.domain((n=e.map(Number)).map(i)),o):n},o.base=function(r){return arguments.length?(e=+r,t.domain(n.map(i)),o):e},o.nice=function(){var e=Wi(n.map(i),r?Math:Sl);return t.domain(e),n=e.map(a),o},o.ticks=function(){var t=Hi(n),o=[],s=t[0],l=t[1],u=Math.floor(i(s)),c=Math.ceil(i(l)),f=e%1?2:e;if(isFinite(c-u)){if(r){for(;c>u;u++)for(var h=1;f>h;h++)o.push(a(u)*h);o.push(a(u))}else for(o.push(a(u));u++0;h--)o.push(a(u)*h);for(u=0;o[u]l;c--);o=o.slice(u,c)}return o},o.tickFormat=function(t,r){if(!arguments.length)return Ll;arguments.length<2?r=Ll:"function"!=typeof r&&(r=uo.format(r));var n=Math.max(1,e*t/o.ticks().length);return function(t){var o=t/a(Math.round(i(t)));return e-.5>o*e&&(o*=e),n>=o?r(t):""}},o.copy=function(){return aa(t.copy(),e,r,n)},Qi(o,t)}function oa(t,e,r){function n(e){return t(i(e))}var i=sa(e),a=sa(1/e);return n.invert=function(e){return a(t.invert(e))},n.domain=function(e){return arguments.length?(t.domain((r=e.map(Number)).map(i)),n):r},n.ticks=function(t){return ea(r,t)},n.tickFormat=function(t,e){return ra(r,t,e)},n.nice=function(t){return n.domain(Ji(r,t))},n.exponent=function(o){return arguments.length?(i=sa(e=o),a=sa(1/e),t.domain(r.map(i)),n):e},n.copy=function(){return oa(t.copy(),e,r)},Qi(n,t)}function sa(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function la(t,e){function r(r){return a[((i.get(r)||("range"===e.t?i.set(r,t.push(r)):NaN))-1)%a.length]}function n(e,r){return uo.range(t.length).map(function(t){return e+r*t})}var i,a,o;return r.domain=function(n){if(!arguments.length)return t;t=[],i=new f;for(var a,o=-1,s=n.length;++or?[NaN,NaN]:[r>0?s[r-1]:t[0],re?NaN:e/a+t,[e,e+1/a]},n.copy=function(){return ca(t,e,r)},i()}function fa(t,e){function r(r){return r>=r?e[uo.bisect(t,r)]:void 0}return r.domain=function(e){return arguments.length?(t=e,r):t},r.range=function(t){return arguments.length?(e=t,r):e},r.invertExtent=function(r){return r=e.indexOf(r),[t[r-1],t[r]]},r.copy=function(){return fa(t,e)},r}function ha(t){function e(t){return+t}return e.invert=e,e.domain=e.range=function(r){return arguments.length?(t=r.map(e),e):t},e.ticks=function(e){return ea(t,e)},e.tickFormat=function(e,r){return ra(t,e,r)},e.copy=function(){return ha(t)},e}function pa(){return 0}function da(t){return t.innerRadius}function ga(t){return t.outerRadius}function va(t){return t.startAngle}function ma(t){return t.endAngle}function ya(t){return t&&t.padAngle}function ba(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function xa(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,f=t[1]+u,h=e[0]+l,p=e[1]+u,d=(c+h)/2,g=(f+p)/2,v=h-c,m=p-f,y=v*v+m*m,b=r-n,x=c*p-h*f,_=(0>m?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,k=(-x*v-m*_)/y,A=(x*m+v*_)/y,M=(-x*v+m*_)/y,T=w-d,E=k-g,L=A-d,S=M-g;return T*T+E*E>L*L+S*S&&(w=A,k=M),[[w-l,k-u],[w*r/b,k*r/b]]}function _a(t){function e(e){function o(){u.push("M",a(t(c),s))}for(var l,u=[],c=[],f=-1,h=e.length,p=Lt(r),d=Lt(n);++f1?t.join("L"):t+"Z"}function ka(t){return t.join("L")+"Z"}function Aa(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1&&i.push("H",n[0]),i.join("")}function Ma(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;u9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));for(s=-1;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}function Ua(t){return t.length<3?wa(t):t[0]+Ca(t,Ba(t))}function Va(t){for(var e,r,n,i=-1,a=t.length;++i=e?o(t-e):void(u.c=o)}function o(r){var i=d.active,a=d[i];a&&(a.timer.c=null,a.timer.t=NaN,--d.count,delete d[i],a.event&&a.event.interrupt.call(t,t.__data__,a.index));for(var o in d)if(n>+o){var f=d[o];f.timer.c=null,f.timer.t=NaN,--d.count,delete d[o]}u.c=s,Rt(function(){return u.c&&s(r||1)&&(u.c=null,u.t=NaN),1},0,l),d.active=n,g.event&&g.event.start.call(t,t.__data__,e),p=[],g.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&p.push(n)}),h=g.ease,c=g.duration}function s(i){for(var a=i/c,o=h(a),s=p.length;s>0;)p[--s].call(t,o);return a>=1?(g.event&&g.event.end.call(t,t.__data__,e),--d.count?delete d[n]:delete t[r],1):void 0}var l,u,c,h,p,d=t[r]||(t[r]={active:0,count:0}),g=d[n];g||(l=i.time,u=Rt(a,0,l),g=d[n]={tween:new f,time:l,timer:u,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++d.count)}function ro(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function no(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}function io(t){return t.toISOString()}function ao(t,e,r){function n(e){return t(e)}function i(t,r){var n=t[1]-t[0],i=n/r,a=uo.bisect(tu,i);return a==tu.length?[e.year,ta(t.map(function(t){return t/31536e6}),r)[2]]:a?e[i/tu[a-1]1?{floor:function(e){for(;r(e=t.floor(e));)e=oo(e-1);return e},ceil:function(e){for(;r(e=t.ceil(e));)e=oo(+e+1);return e}}:t))},n.ticks=function(t,e){var r=Hi(n.domain()),a=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return a&&(t=a[0],e=a[1]),t.range(r[0],oo(+r[1]+1),1>e?1:e)},n.tickFormat=function(){return r},n.copy=function(){return ao(t.copy(),e,r)},Qi(n,t)}function oo(t){return new Date(t)}function so(t){return JSON.parse(t.responseText)}function lo(t){var e=ho.createRange();return e.selectNode(ho.body),e.createContextualFragment(t.responseText)}var uo={version:"3.5.17"},co=[].slice,fo=function(t){return co.call(t)},ho=this.document;if(ho)try{fo(ho.documentElement.childNodes)[0].nodeType}catch(po){fo=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),ho)try{ho.createElement("DIV").style.setProperty("opacity",0,"")}catch(go){var vo=this.Element.prototype,mo=vo.setAttribute,yo=vo.setAttributeNS,bo=this.CSSStyleDeclaration.prototype,xo=bo.setProperty;vo.setAttribute=function(t,e){mo.call(this,t,e+"")},vo.setAttributeNS=function(t,e,r){yo.call(this,t,e,r+"")},bo.setProperty=function(t,e,r){xo.call(this,t,e+"",r)}}uo.ascending=i,uo.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:NaN},uo.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},uo.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},uo.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}else{for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}return[r,i]},uo.sum=function(t,e){var r,n=0,i=t.length,a=-1;if(1===arguments.length)for(;++a1?l/(c-1):void 0},uo.deviation=function(){var t=uo.variance.apply(this,arguments);return t?Math.sqrt(t):t};var _o=s(i);uo.bisectLeft=_o.left,uo.bisect=uo.bisectRight=_o.right,uo.bisector=function(t){return s(1===t.length?function(e,r){return i(t(e),r)}:t)},uo.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,2>a&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},uo.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},uo.pairs=function(t){for(var e,r=0,n=t.length-1,i=t[0],a=new Array(0>n?0:n);n>r;)a[r]=[e=i,i=t[++r]];return a},uo.transpose=function(t){if(!(i=t.length))return[];for(var e=-1,r=uo.min(t,l),n=new Array(r);++e=0;)for(n=t[i],e=n.length;--e>=0;)r[--o]=n[e];return r};var wo=Math.abs;uo.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r===1/0)throw new Error("infinite range");var n,i=[],a=u(wo(r)),o=-1;if(t*=a,e*=a,r*=a,0>r)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=a.length)return n?n.call(i,o):r?o.sort(r):o;for(var l,u,c,h,p=-1,d=o.length,g=a[s++],v=new f;++p=a.length)return t;var n=[],i=o[r++];return t.forEach(function(t,i){n.push({key:t,values:e(i,r)})}),i?n.sort(function(t,e){return i(t.key,e.key)}):n}var r,n,i={},a=[],o=[];return i.map=function(e,r){return t(r,e,0)},i.entries=function(r){return e(t(uo.map,r,0),0)},i.key=function(t){return a.push(t),i},i.sortKeys=function(t){return o[a.length-1]=t,i},i.sortValues=function(t){return r=t,i},i.rollup=function(t){return n=t,i},i},uo.set=function(t){var e=new b;if(t)for(var r=0,n=t.length;n>r;++r)e.add(t[r]);return e},c(b,{has:d,add:function(t){return this._[h(t+="")]=!0,t},remove:g,values:v,size:m,empty:y,forEach:function(t){for(var e in this._)t.call(this,p(e))}}),uo.behavior={},uo.rebind=function(t,e){for(var r,n=1,i=arguments.length;++n=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},uo.event=null,uo.requote=function(t){return t.replace(To,"\\$&")};var To=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Eo={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]},Lo=function(t,e){return e.querySelector(t)},So=function(t,e){return e.querySelectorAll(t)},Co=function(t,e){var r=t.matches||t[w(t,"matchesSelector")];return(Co=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(Lo=function(t,e){return Sizzle(t,e)[0]||null},So=Sizzle,Co=Sizzle.matchesSelector),uo.selection=function(){return uo.select(ho.documentElement)};var zo=uo.selection.prototype=[];zo.select=function(t){var e,r,n,i,a=[];t=C(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),Ro.hasOwnProperty(r)?{space:Ro[r],local:t}:t}},zo.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node();return t=uo.ns.qualify(t),t.local?r.getAttributeNS(t.space,t.local):r.getAttribute(t)}for(e in t)this.each(P(e,t[e]));return this}return this.each(P(t,e))},zo.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=O(t)).length,i=-1;if(e=r.classList){for(;++ii){if("string"!=typeof t){2>i&&(e="");for(r in t)this.each(F(r,t[r],e));return this}if(2>i){var a=this.node();return n(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(F(t,e,r))},zo.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(D(e,t[e]));return this}return this.each(D(t,e))},zo.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},zo.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},zo.append=function(t){return t=B(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},zo.insert=function(t,e){return t=B(t),e=C(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},zo.remove=function(){return this.each(U)},zo.data=function(t,e){function r(t,r){var n,i,a,o=t.length,c=r.length,h=Math.min(o,c),p=new Array(c),d=new Array(c),g=new Array(o);if(e){var v,m=new f,y=new Array(o);for(n=-1;++nn;++n)d[n]=V(r[n]);for(;o>n;++n)g[n]=t[n]}d.update=p,d.parentNode=p.parentNode=g.parentNode=t.parentNode,s.push(d),l.push(p),u.push(g)}var n,i,a=-1,o=this.length;if(!arguments.length){for(t=new Array(o=(n=this[0]).length);++aa;a++){i.push(e=[]),e.parentNode=(r=this[a]).parentNode;for(var s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return S(i)},zo.order=function(){for(var t=-1,e=this.length;++t=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},zo.sort=function(t){t=G.apply(this,arguments);for(var e=-1,r=this.length;++et;t++)for(var r=this[t],n=0,i=r.length;i>n;n++){var a=r[n];if(a)return a}return null},zo.size=function(){var t=0;return H(this,function(){++t}),t};var jo=[];uo.selection.enter=Y,uo.selection.enter.prototype=jo,jo.append=zo.append,jo.empty=zo.empty,jo.node=zo.node,jo.call=zo.call,jo.size=zo.size,jo.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++sn){if("string"!=typeof t){2>n&&(e=!1);for(r in t)this.each(W(r,t[r],e));return this}if(2>n)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(W(t,e,r))};var Oo=uo.map({mouseenter:"mouseover",mouseleave:"mouseout"});ho&&Oo.forEach(function(t){"on"+t in ho&&Oo.remove(t)});var Io,No=0;uo.mouse=function(t){return Q(t,E())};var Fo=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;uo.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=E().changedTouches),e)for(var n,i=0,a=e.length;a>i;++i)if((n=e[i]).identifier===r)return Q(t,n)},uo.behavior.drag=function(){function t(){this.on("mousedown.drag",a).on("touchstart.drag",o)}function e(t,e,n,a,o){return function(){function s(){var t,r,n=e(h,g);n&&(t=n[0]-b[0],r=n[1]-b[1],d|=t|r,b=n,p({type:"drag",x:n[0]+u[0],y:n[1]+u[1],dx:t,dy:r}))}function l(){e(h,g)&&(m.on(a+v,null).on(o+v,null),y(d),p({type:"dragend"}))}var u,c=this,f=uo.event.target.correspondingElement||uo.event.target,h=c.parentNode,p=r.of(c,arguments),d=0,g=t(),v=".drag"+(null==g?"":"-"+g),m=uo.select(n(f)).on(a+v,s).on(o+v,l),y=$(f),b=e(h,g);i?(u=i.apply(c,arguments),u=[u.x-b[0],u.y-b[1]]):u=[0,0],p({type:"dragstart"})}}var r=L(t,"drag","dragstart","dragend"),i=null,a=e(k,uo.mouse,n,"mousemove","mouseup"),o=e(J,uo.touch,x,"touchmove","touchend");return t.origin=function(e){return arguments.length?(i=e,t):i},uo.rebind(t,r,"on")},uo.touches=function(t,e){return arguments.length<2&&(e=E().touches),e?fo(e).map(function(e){var r=Q(t,e);return r.identifier=e.identifier,r}):[]};var Do=1e-6,Bo=Do*Do,Uo=Math.PI,Vo=2*Uo,qo=Vo-Do,Go=Uo/2,Ho=Uo/180,Yo=180/Uo,Xo=Math.SQRT2,Wo=2,Zo=4;uo.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,f=l-a,h=c*c+f*f;if(Bo>h)n=Math.log(u/o)/Xo,r=function(t){return[i+t*c,a+t*f,o*Math.exp(Xo*t*n)]};else{var p=Math.sqrt(h),d=(u*u-o*o+Zo*h)/(2*o*Wo*p),g=(u*u-o*o-Zo*h)/(2*u*Wo*p),v=Math.log(Math.sqrt(d*d+1)-d),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/Xo,r=function(t){var e=t*n,r=at(v),s=o/(Wo*p)*(r*ot(Xo*e+v)-it(v));return[i+s*c,a+s*f,o*r/at(Xo*e+v)]}}return r.duration=1e3*n,r},uo.behavior.zoom=function(){function t(t){t.on(z,f).on($o+".zoom",p).on("dblclick.zoom",d).on(j,h)}function e(t){return[(t[0]-A.x)/A.k,(t[1]-A.y)/A.k]}function r(t){return[t[0]*A.k+A.x,t[1]*A.k+A.y]}function i(t){A.k=Math.max(E[0],Math.min(E[1],t))}function a(t,e){e=r(e),A.x+=t[0]-e[0],A.y+=t[1]-e[1]}function o(e,r,n,o){e.__chart__={x:A.x,y:A.y,k:A.k},i(Math.pow(2,o)),a(v=r,n),e=uo.select(e),S>0&&(e=e.transition().duration(S)),e.call(t.event)}function s(){_&&_.domain(x.range().map(function(t){return(t-A.x)/A.k}).map(x.invert)),k&&k.domain(w.range().map(function(t){return(t-A.y)/A.k}).map(w.invert))}function l(t){C++||t({type:"zoomstart"})}function u(t){s(),t({type:"zoom",scale:A.k,translate:[A.x,A.y]})}function c(t){--C||(t({type:"zoomend"}),v=null)}function f(){function t(){s=1,a(uo.mouse(i),h),u(o)}function r(){f.on(P,null).on(R,null),p(s),c(o)}var i=this,o=O.of(i,arguments),s=0,f=uo.select(n(i)).on(P,t).on(R,r),h=e(uo.mouse(i)),p=$(i);Gl.call(i),l(o)}function h(){function t(){var t=uo.touches(d);return p=A.k,t.forEach(function(t){t.identifier in v&&(v[t.identifier]=e(t))}),t}function r(){var e=uo.event.target;uo.select(e).on(x,n).on(_,s),w.push(e);for(var r=uo.event.changedTouches,i=0,a=r.length;a>i;++i)v[r[i].identifier]=null;var l=t(),u=Date.now();if(1===l.length){if(500>u-b){var c=l[0];o(d,c,v[c.identifier],Math.floor(Math.log(A.k)/Math.LN2)+1),T()}b=u}else if(l.length>1){var c=l[0],f=l[1],h=c[0]-f[0],p=c[1]-f[1];m=h*h+p*p}}function n(){var t,e,r,n,o=uo.touches(d);Gl.call(d);for(var s=0,l=o.length;l>s;++s,n=null)if(r=o[s],n=v[r.identifier]){if(e)break;t=r,e=n}if(n){var c=(c=r[0]-t[0])*c+(c=r[1]-t[1])*c,f=m&&Math.sqrt(c/m);t=[(t[0]+r[0])/2,(t[1]+r[1])/2],e=[(e[0]+n[0])/2,(e[1]+n[1])/2],i(f*p)}b=null,a(t,e),u(g)}function s(){if(uo.event.touches.length){for(var e=uo.event.changedTouches,r=0,n=e.length;n>r;++r)delete v[e[r].identifier];for(var i in v)return void t()}uo.selectAll(w).on(y,null),k.on(z,f).on(j,h),M(),c(g)}var p,d=this,g=O.of(d,arguments),v={},m=0,y=".zoom-"+uo.event.changedTouches[0].identifier,x="touchmove"+y,_="touchend"+y,w=[],k=uo.select(d),M=$(d);r(),l(g),k.on(z,null).on(j,r)}function p(){var t=O.of(this,arguments);y?clearTimeout(y):(Gl.call(this),g=e(v=m||uo.mouse(this)),l(t)),y=setTimeout(function(){y=null,c(t)},50),T(),i(Math.pow(2,.002*Ko())*A.k),a(v,g),u(t)}function d(){var t=uo.mouse(this),r=Math.log(A.k)/Math.LN2;o(this,t,e(t),uo.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}var g,v,m,y,b,x,_,w,k,A={x:0,y:0,k:1},M=[960,500],E=Qo,S=250,C=0,z="mousedown.zoom",P="mousemove.zoom",R="mouseup.zoom",j="touchstart.zoom",O=L(t,"zoomstart","zoom","zoomend");return $o||($o="onwheel"in ho?(Ko=function(){return-uo.event.deltaY*(uo.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ho?(Ko=function(){return uo.event.wheelDelta},"mousewheel"):(Ko=function(){return-uo.event.detail},"MozMousePixelScroll")),t.event=function(t){t.each(function(){var t=O.of(this,arguments),e=A;Vl?uo.select(this).transition().each("start.zoom",function(){A=this.__chart__||{x:0,y:0,k:1},l(t)}).tween("zoom:zoom",function(){var r=M[0],n=M[1],i=v?v[0]:r/2,a=v?v[1]:n/2,o=uo.interpolateZoom([(i-A.x)/A.k,(a-A.y)/A.k,r/A.k],[(i-e.x)/e.k,(a-e.y)/e.k,r/e.k]);return function(e){var n=o(e),s=r/n[2];this.__chart__=A={x:i-n[0]*s,y:a-n[1]*s,k:s},u(t)}}).each("interrupt.zoom",function(){c(t)}).each("end.zoom",function(){c(t)}):(this.__chart__=A,l(t),u(t),c(t))})},t.translate=function(e){return arguments.length?(A={x:+e[0],y:+e[1],k:A.k},s(),t):[A.x,A.y]},t.scale=function(e){return arguments.length?(A={x:A.x,y:A.y,k:null},i(+e),s(),t):A.k},t.scaleExtent=function(e){return arguments.length?(E=null==e?Qo:[+e[0],+e[1]],t):E},t.center=function(e){return arguments.length?(m=e&&[+e[0],+e[1]],t):m},t.size=function(e){return arguments.length?(M=e&&[+e[0],+e[1]],t):M},t.duration=function(e){return arguments.length?(S=+e,t):S},t.x=function(e){return arguments.length?(_=e,x=e.copy(),A={x:0,y:0,k:1},t):_},t.y=function(e){return arguments.length?(k=e,w=e.copy(),A={x:0,y:0,k:1},t):k},uo.rebind(t,O,"on")};var Ko,$o,Qo=[0,1/0];uo.color=lt,lt.prototype.toString=function(){return this.rgb()+""},uo.hsl=ut;var Jo=ut.prototype=new lt;Jo.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new ut(this.h,this.s,this.l/t)},Jo.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new ut(this.h,this.s,t*this.l)},Jo.rgb=function(){return ct(this.h,this.s,this.l)},uo.hcl=ft;var ts=ft.prototype=new lt;ts.brighter=function(t){return new ft(this.h,this.c,Math.min(100,this.l+es*(arguments.length?t:1)))},ts.darker=function(t){return new ft(this.h,this.c,Math.max(0,this.l-es*(arguments.length?t:1)))},ts.rgb=function(){return ht(this.h,this.c,this.l).rgb()},uo.lab=pt;var es=18,rs=.95047,ns=1,is=1.08883,as=pt.prototype=new lt;as.brighter=function(t){return new pt(Math.min(100,this.l+es*(arguments.length?t:1)),this.a,this.b)},as.darker=function(t){return new pt(Math.max(0,this.l-es*(arguments.length?t:1)),this.a,this.b)},as.rgb=function(){return dt(this.l,this.a,this.b)},uo.rgb=bt;var os=bt.prototype=new lt;os.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&i>e&&(e=i),r&&i>r&&(r=i),n&&i>n&&(n=i),new bt(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new bt(i,i,i)},os.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new bt(t*this.r,t*this.g,t*this.b)},os.hsl=function(){return At(this.r,this.g,this.b)},os.toString=function(){return"#"+wt(this.r)+wt(this.g)+wt(this.b)};var ss=uo.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});ss.forEach(function(t,e){ss.set(t,xt(e))}),uo.functor=Lt,uo.xhr=St(x),uo.dsv=function(t,e){function r(t,r,a){arguments.length<3&&(a=r,r=null);var o=Ct(t,e,null==r?n:i(r),a);return o.row=function(t){return arguments.length?o.response(null==(r=t)?n:i(t)):r},o}function n(t){return r.parse(t.responseText)}function i(t){return function(e){return r.parse(e.responseText,t)}}function a(e){return e.map(o).join(t)}function o(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);return r.parse=function(t,e){var n;return r.parseRows(t,function(t,r){if(n)return n(t,r-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");n=e?function(t,r){return e(i(t),r)}:i})},r.parseRows=function(t,e){function r(){if(c>=u)return o;if(i)return i=!1,a;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++c;){var n=t.charCodeAt(c++),s=1;if(10===n)i=!0;else if(13===n)i=!0,10===t.charCodeAt(c)&&(++c,++s);else if(n!==l)continue;return t.slice(e,c-s)}return t.slice(e)}for(var n,i,a={},o={},s=[],u=t.length,c=0,f=0;(n=r())!==o;){for(var h=[];n!==a&&n!==o;)h.push(n),n=r();e&&null==(h=e(h,f++))||s.push(h)}return s},r.format=function(e){if(Array.isArray(e[0]))return r.formatRows(e);var n=new b,i=[];return e.forEach(function(t){for(var e in t)n.has(e)||i.push(n.add(e))}),[i.map(o).join(t)].concat(e.map(function(e){return i.map(function(t){return o(e[t])}).join(t)})).join("\n")},r.formatRows=function(t){return t.map(a).join("\n")},r},uo.csv=uo.dsv(",","text/csv"),uo.tsv=uo.dsv(" ","text/tab-separated-values");var ls,us,cs,fs,hs=this[w(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};uo.timer=function(){Rt.apply(this,arguments)},uo.timer.flush=function(){Ot(),It()},uo.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var ps=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Ft);uo.formatPrefix=function(t,e){var r=0;return(t=+t)&&(0>t&&(t*=-1),e&&(t=uo.round(t,Nt(t,e))),r=1+Math.floor(1e-12+Math.log(t)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),ps[8+r/3]};var ds=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,gs=uo.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=uo.round(t,Nt(t,e))).toFixed(Math.max(0,Math.min(20,Nt(t*(1+1e-15),e))))}}),vs=uo.time={},ms=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ys.setUTCDate.apply(this._,arguments)},setDay:function(){ys.setUTCDay.apply(this._,arguments)},setFullYear:function(){ys.setUTCFullYear.apply(this._,arguments)},setHours:function(){ys.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ys.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ys.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ys.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ -ys.setUTCSeconds.apply(this._,arguments)},setTime:function(){ys.setTime.apply(this._,arguments)}};var ys=Date.prototype;vs.year=Vt(function(t){return t=vs.day(t),t.setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),vs.years=vs.year.range,vs.years.utc=vs.year.utc.range,vs.day=Vt(function(t){var e=new ms(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),vs.days=vs.day.range,vs.days.utc=vs.day.utc.range,vs.dayOfYear=function(t){var e=vs.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=vs[t]=Vt(function(t){return(t=vs.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});vs[t+"s"]=r.range,vs[t+"s"].utc=r.utc.range,vs[t+"OfYear"]=function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)}}),vs.week=vs.sunday,vs.weeks=vs.sunday.range,vs.weeks.utc=vs.sunday.utc.range,vs.weekOfYear=vs.sundayOfYear;var bs={"-":"",_:" ",0:"0"},xs=/^\s*\d+/,_s=/^%/;uo.locale=function(t){return{numberFormat:Dt(t),timeFormat:Gt(t)}};var ws=uo.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});uo.format=ws.numberFormat,uo.geo={},fe.prototype={s:0,t:0,add:function(t){he(t,this.t,ks),he(ks.s,this.s,this),this.s?this.t+=ks.t:this.s=ks.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ks=new fe;uo.geo.stream=function(t,e){t&&As.hasOwnProperty(t.type)?As[t.type](t,e):pe(t,e)};var As={Feature:function(t,e){pe(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++nt?4*Uo+t:t,Ls.lineStart=Ls.lineEnd=Ls.point=k}};uo.geo.bounds=function(){function t(t,e){b.push(x=[c=t,h=t]),f>e&&(f=e),e>p&&(p=e)}function e(e,r){var n=me([e*Ho,r*Ho]);if(m){var i=be(m,n),a=[i[1],-i[0],0],o=be(a,i);we(o),o=ke(o);var l=e-d,u=l>0?1:-1,g=o[0]*Yo*u,v=wo(l)>180;if(v^(g>u*d&&u*e>g)){var y=o[1]*Yo;y>p&&(p=y)}else if(g=(g+360)%360-180,v^(g>u*d&&u*e>g)){var y=-o[1]*Yo;f>y&&(f=y)}else f>r&&(f=r),r>p&&(p=r);v?d>e?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e):h>=c?(c>e&&(c=e),e>h&&(h=e)):e>d?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e)}else t(e,r);m=n,d=e}function r(){_.point=e}function n(){x[0]=c,x[1]=h,_.point=t,m=null}function i(t,r){if(m){var n=t-d;y+=wo(n)>180?n+(n>0?360:-360):n}else g=t,v=r;Ls.point(t,r),e(t,r)}function a(){Ls.lineStart()}function o(){i(g,v),Ls.lineEnd(),wo(y)>Do&&(c=-(h=180)),x[0]=c,x[1]=h,m=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function u(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:tEs?(c=-(h=180),f=-(p=90)):y>Do?p=90:-Do>y&&(f=-90),x[0]=c,x[1]=h}};return function(t){p=h=-(c=f=1/0),b=[],uo.geo.stream(t,_);var e=b.length;if(e){b.sort(l);for(var r,n=1,i=b[0],a=[i];e>n;++n)r=b[n],u(r[0],i)||u(r[1],i)?(s(i[0],r[1])>s(i[0],i[1])&&(i[1]=r[1]),s(r[0],i[1])>s(i[0],i[1])&&(i[0]=r[0])):a.push(i=r);for(var o,r,d=-(1/0),e=a.length-1,n=0,i=a[e];e>=n;i=r,++n)r=a[n],(o=s(i[1],r[0]))>d&&(d=o,c=r[0],h=i[1])}return b=x=null,c===1/0||f===1/0?[[NaN,NaN],[NaN,NaN]]:[[c,f],[h,p]]}}(),uo.geo.centroid=function(t){Ss=Cs=zs=Ps=Rs=js=Os=Is=Ns=Fs=Ds=0,uo.geo.stream(t,Bs);var e=Ns,r=Fs,n=Ds,i=e*e+r*r+n*n;return Bo>i&&(e=js,r=Os,n=Is,Do>Cs&&(e=zs,r=Ps,n=Rs),i=e*e+r*r+n*n,Bo>i)?[NaN,NaN]:[Math.atan2(r,e)*Yo,nt(n/Math.sqrt(i))*Yo]};var Ss,Cs,zs,Ps,Rs,js,Os,Is,Ns,Fs,Ds,Bs={sphere:k,point:Me,lineStart:Ee,lineEnd:Le,polygonStart:function(){Bs.lineStart=Se},polygonEnd:function(){Bs.lineStart=Ee}},Us=Oe(ze,De,Ue,[-Uo,-Uo/2]),Vs=1e9;uo.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),i=a(t),i.valid=!0,i},extent:function(s){return arguments.length?(a=He(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(uo.geo.conicEqualArea=function(){return Ye(Xe)}).raw=Xe,uo.geo.albers=function(){return uo.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},uo.geo.albersUsa=function(){function t(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}var e,r,n,i,a=uo.geo.albers(),o=uo.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=uo.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};return t.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&.234>i&&n>=-.425&&-.214>n?o:i>=.166&&.234>i&&n>=-.214&&-.115>n?s:a).invert(t)},t.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},t.precision=function(e){return arguments.length?(a.precision(e),o.precision(e),s.precision(e),t):a.precision()},t.scale=function(e){return arguments.length?(a.scale(e),o.scale(.35*e),s.scale(e),t.translate(a.translate())):a.scale()},t.translate=function(e){if(!arguments.length)return a.translate();var u=a.scale(),c=+e[0],f=+e[1];return r=a.translate(e).clipExtent([[c-.455*u,f-.238*u],[c+.455*u,f+.238*u]]).stream(l).point,n=o.translate([c-.307*u,f+.201*u]).clipExtent([[c-.425*u+Do,f+.12*u+Do],[c-.214*u-Do,f+.234*u-Do]]).stream(l).point,i=s.translate([c-.205*u,f+.212*u]).clipExtent([[c-.214*u+Do,f+.166*u+Do],[c-.115*u-Do,f+.234*u-Do]]).stream(l).point,t},t.scale(1070)};var qs,Gs,Hs,Ys,Xs,Ws,Zs={point:k,lineStart:k,lineEnd:k,polygonStart:function(){Gs=0,Zs.lineStart=We},polygonEnd:function(){Zs.lineStart=Zs.lineEnd=Zs.point=k,qs+=wo(Gs/2)}},Ks={point:Ze,lineStart:k,lineEnd:k,polygonStart:k,polygonEnd:k},$s={point:Qe,lineStart:Je,lineEnd:tr,polygonStart:function(){$s.lineStart=er},polygonEnd:function(){$s.point=Qe,$s.lineStart=Je,$s.lineEnd=tr}};uo.geo.path=function(){function t(t){return t&&("function"==typeof s&&a.pointRadius(+s.apply(this,arguments)),o&&o.valid||(o=i(a)),uo.geo.stream(t,o)),a.result()}function e(){return o=null,t}var r,n,i,a,o,s=4.5;return t.area=function(t){return qs=0,uo.geo.stream(t,i(Zs)),qs},t.centroid=function(t){return zs=Ps=Rs=js=Os=Is=Ns=Fs=Ds=0,uo.geo.stream(t,i($s)),Ds?[Ns/Ds,Fs/Ds]:Is?[js/Is,Os/Is]:Rs?[zs/Rs,Ps/Rs]:[NaN,NaN]},t.bounds=function(t){return Xs=Ws=-(Hs=Ys=1/0),uo.geo.stream(t,i(Ks)),[[Hs,Ys],[Xs,Ws]]},t.projection=function(t){return arguments.length?(i=(r=t)?t.stream||ir(t):x,e()):r},t.context=function(t){return arguments.length?(a=null==(n=t)?new Ke:new rr(t),"function"!=typeof s&&a.pointRadius(s),e()):n},t.pointRadius=function(e){return arguments.length?(s="function"==typeof e?e:(a.pointRadius(+e),+e),t):s},t.projection(uo.geo.albersUsa()).context(null)},uo.geo.transform=function(t){return{stream:function(e){var r=new ar(e);for(var n in t)r[n]=t[n];return r}}},ar.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},uo.geo.projection=sr,uo.geo.projectionMutator=lr,(uo.geo.equirectangular=function(){return sr(cr)}).raw=cr.invert=cr,uo.geo.rotation=function(t){function e(e){return e=t(e[0]*Ho,e[1]*Ho),e[0]*=Yo,e[1]*=Yo,e}return t=hr(t[0]%360*Ho,t[1]*Ho,t.length>2?t[2]*Ho:0),e.invert=function(e){return e=t.invert(e[0]*Ho,e[1]*Ho),e[0]*=Yo,e[1]*=Yo,e},e},fr.invert=cr,uo.geo.circle=function(){function t(){var t="function"==typeof n?n.apply(this,arguments):n,e=hr(-t[0]*Ho,-t[1]*Ho,0).invert,i=[];return r(null,null,1,{point:function(t,r){i.push(t=e(t,r)),t[0]*=Yo,t[1]*=Yo}}),{type:"Polygon",coordinates:[i]}}var e,r,n=[0,0],i=6;return t.origin=function(e){return arguments.length?(n=e,t):n},t.angle=function(n){return arguments.length?(r=vr((e=+n)*Ho,i*Ho),t):e},t.precision=function(n){return arguments.length?(r=vr(e*Ho,(i=+n)*Ho),t):i},t.angle(90)},uo.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ho,i=t[1]*Ho,a=e[1]*Ho,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),f=Math.cos(a);return Math.atan2(Math.sqrt((r=f*o)*r+(r=u*c-l*f*s)*r),l*c+u*f*s)},uo.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return uo.range(Math.ceil(a/v)*v,i,v).map(h).concat(uo.range(Math.ceil(u/m)*m,l,m).map(p)).concat(uo.range(Math.ceil(n/d)*d,r,d).filter(function(t){return wo(t%v)>Do}).map(c)).concat(uo.range(Math.ceil(s/g)*g,o,g).filter(function(t){return wo(t%m)>Do}).map(f))}var r,n,i,a,o,s,l,u,c,f,h,p,d=10,g=d,v=90,m=360,y=2.5;return t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})},t.outline=function(){return{type:"Polygon",coordinates:[h(a).concat(p(l).slice(1),h(i).reverse().slice(1),p(u).reverse().slice(1))]}},t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()},t.majorExtent=function(e){return arguments.length?(a=+e[0][0],i=+e[1][0],u=+e[0][1],l=+e[1][1],a>i&&(e=a,a=i,i=e),u>l&&(e=u,u=l,l=e),t.precision(y)):[[a,u],[i,l]]},t.minorExtent=function(e){return arguments.length?(n=+e[0][0],r=+e[1][0],s=+e[0][1],o=+e[1][1],n>r&&(e=n,n=r,r=e),s>o&&(e=s,s=o,o=e),t.precision(y)):[[n,s],[r,o]]},t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()},t.majorStep=function(e){return arguments.length?(v=+e[0],m=+e[1],t):[v,m]},t.minorStep=function(e){return arguments.length?(d=+e[0],g=+e[1],t):[d,g]},t.precision=function(e){return arguments.length?(y=+e,c=yr(s,o,90),f=br(n,r,y),h=yr(u,l,90),p=br(a,i,y),t):y},t.majorExtent([[-180,-90+Do],[180,90-Do]]).minorExtent([[-180,-80-Do],[180,80+Do]])},uo.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}var e,r,n=xr,i=_r;return t.distance=function(){return uo.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},t.source=function(r){return arguments.length?(n=r,e="function"==typeof r?null:r,t):n},t.target=function(e){return arguments.length?(i=e,r="function"==typeof e?null:e,t):i},t.precision=function(){return arguments.length?t:0},t},uo.geo.interpolate=function(t,e){return wr(t[0]*Ho,t[1]*Ho,e[0]*Ho,e[1]*Ho)},uo.geo.length=function(t){return Qs=0,uo.geo.stream(t,Js),Qs};var Qs,Js={sphere:k,point:k,lineStart:kr,lineEnd:k,polygonStart:k,polygonEnd:k},tl=Ar(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(uo.geo.azimuthalEqualArea=function(){return sr(tl)}).raw=tl;var el=Ar(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},x);(uo.geo.azimuthalEquidistant=function(){return sr(el)}).raw=el,(uo.geo.conicConformal=function(){return Ye(Mr)}).raw=Mr,(uo.geo.conicEquidistant=function(){return Ye(Tr)}).raw=Tr;var rl=Ar(function(t){return 1/t},Math.atan);(uo.geo.gnomonic=function(){return sr(rl)}).raw=rl,Er.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Go]},(uo.geo.mercator=function(){return Lr(Er)}).raw=Er;var nl=Ar(function(){return 1},Math.asin);(uo.geo.orthographic=function(){return sr(nl)}).raw=nl;var il=Ar(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(uo.geo.stereographic=function(){return sr(il)}).raw=il,Sr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Go]},(uo.geo.transverseMercator=function(){var t=Lr(Sr),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):(t=r(),[t[0],t[1],t[2]-90])},r([0,0,90])}).raw=Sr,uo.geom={},uo.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Lt(r),a=Lt(n),o=t.length,s=[],l=[];for(e=0;o>e;e++)s.push([+i.call(this,t[e],e),+a.call(this,t[e],e),e]);for(s.sort(Rr),e=0;o>e;e++)l.push([s[e][0],-s[e][1]]);var u=Pr(s),c=Pr(l),f=c[0]===u[0],h=c[c.length-1]===u[u.length-1],p=[];for(e=u.length-1;e>=0;--e)p.push(t[s[u[e]][2]]);for(e=+f;e=n&&u.x<=a&&u.y>=i&&u.y<=o?[[n,o],[a,o],[a,i],[n,i]]:[];c.point=t[s]}),e}function r(t){return t.map(function(t,e){return{x:Math.round(a(t,e)/Do)*Do,y:Math.round(o(t,e)/Do)*Do,i:e}})}var n=Cr,i=zr,a=n,o=i,s=pl;return t?e(t):(e.links=function(t){return un(r(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},e.triangles=function(t){var e=[];return un(r(t)).cells.forEach(function(r,n){for(var i,a,o=r.site,s=r.edges.sort(Yr),l=-1,u=s.length,c=s[u-1].edge,f=c.l===o?c.r:c.l;++l=u,h=n>=c,p=h<<1|f;t.leaf=!1,t=t.nodes[p]||(t.nodes[p]=dn()),f?i=u:s=u,h?o=c:l=c,a(t,e,r,n,i,o,s,l)}var c,f,h,p,d,g,v,m,y,b=Lt(s),x=Lt(l);if(null!=e)g=e,v=r,m=n,y=i;else if(m=y=-(g=v=1/0),f=[],h=[],d=t.length,o)for(p=0;d>p;++p)c=t[p],c.xm&&(m=c.x),c.y>y&&(y=c.y),f.push(c.x),h.push(c.y);else for(p=0;d>p;++p){var _=+b(c=t[p],p),w=+x(c,p);g>_&&(g=_),v>w&&(v=w),_>m&&(m=_),w>y&&(y=w),f.push(_),h.push(w)}var k=m-g,A=y-v;k>A?y=v+k:m=g+A;var M=dn();if(M.add=function(t){a(M,t,+b(t,++p),+x(t,p),g,v,m,y)},M.visit=function(t){gn(t,M,g,v,m,y)},M.find=function(t){return vn(M,t[0],t[1],g,v,m,y)},p=-1,null==e){for(;++p=0?t.slice(0,e):t,n=e>=0?t.slice(e+1):"in";return r=ml.get(r)||vl,n=yl.get(n)||x,kn(n(r.apply(null,co.call(arguments,1))))},uo.interpolateHcl=In,uo.interpolateHsl=Nn,uo.interpolateLab=Fn,uo.interpolateRound=Dn,uo.transform=function(t){var e=ho.createElementNS(uo.ns.prefix.svg,"g");return(uo.transform=function(t){if(null!=t){e.setAttribute("transform",t);var r=e.transform.baseVal.consolidate()}return new Bn(r?r.matrix:bl)})(t)},Bn.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var bl={a:1,b:0,c:0,d:1,e:0,f:0};uo.interpolateTransform=Zn,uo.layout={},uo.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++rs*s/m){if(g>l){var u=e.charge/l;t.px-=a*u,t.py-=o*u}return!0}if(e.point&&l&&g>l){var u=e.pointCharge/l;t.px-=a*u,t.py-=o*u}}return!e.charge}}function e(t){t.px=uo.event.x,t.py=uo.event.y,l.resume()}var r,n,i,a,o,s,l={},u=uo.dispatch("start","tick","end"),c=[1,1],f=.9,h=xl,p=_l,d=-30,g=wl,v=.1,m=.64,y=[],b=[];return l.tick=function(){if((i*=.99)<.005)return r=null,u.end({type:"end",alpha:i=0}),!0;var e,n,l,h,p,g,m,x,_,w=y.length,k=b.length;for(n=0;k>n;++n)l=b[n],h=l.source,p=l.target,x=p.x-h.x,_=p.y-h.y,(g=x*x+_*_)&&(g=i*o[n]*((g=Math.sqrt(g))-a[n])/g,x*=g,_*=g,p.x-=x*(m=h.weight+p.weight?h.weight/(h.weight+p.weight):.5),p.y-=_*m,h.x+=x*(m=1-m),h.y+=_*m);if((m=i*v)&&(x=c[0]/2,_=c[1]/2,n=-1,m))for(;++n0?i=t:(r.c=null,r.t=NaN,r=null,u.end({type:"end",alpha:i=0})):t>0&&(u.start({type:"start",alpha:i=t}),r=Rt(l.tick)),l):i},l.start=function(){function t(t,n){if(!r){for(r=new Array(i),l=0;i>l;++l)r[l]=[];for(l=0;u>l;++l){var a=b[l];r[a.source.index].push(a.target),r[a.target.index].push(a.source)}}for(var o,s=r[e],l=-1,c=s.length;++le;++e)(n=y[e]).index=e,n.weight=0;for(e=0;u>e;++e)n=b[e],"number"==typeof n.source&&(n.source=y[n.source]),"number"==typeof n.target&&(n.target=y[n.target]),++n.source.weight,++n.target.weight;for(e=0;i>e;++e)n=y[e],isNaN(n.x)&&(n.x=t("x",f)),isNaN(n.y)&&(n.y=t("y",g)),isNaN(n.px)&&(n.px=n.x),isNaN(n.py)&&(n.py=n.y);if(a=[],"function"==typeof h)for(e=0;u>e;++e)a[e]=+h.call(this,b[e],e);else for(e=0;u>e;++e)a[e]=h;if(o=[],"function"==typeof p)for(e=0;u>e;++e)o[e]=+p.call(this,b[e],e);else for(e=0;u>e;++e)o[e]=p;if(s=[],"function"==typeof d)for(e=0;i>e;++e)s[e]=+d.call(this,y[e],e);else for(e=0;i>e;++e)s[e]=d;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return n||(n=uo.behavior.drag().origin(x).on("dragstart.force",ei).on("drag.force",e).on("dragend.force",ri)),arguments.length?void this.on("mouseover.force",ni).on("mouseout.force",ii).call(n):n},uo.rebind(l,u,"on")};var xl=20,_l=1,wl=1/0;uo.layout.hierarchy=function(){function t(i){var a,o=[i],s=[];for(i.depth=0;null!=(a=o.pop());)if(s.push(a),(u=r.call(t,a,a.depth))&&(l=u.length)){for(var l,u,c;--l>=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;n&&(a.value=0),a.children=u}else n&&(a.value=+n.call(t,a,a.depth)||0),delete a.children;return li(i,function(t){var r,i;e&&(r=t.children)&&r.sort(e),n&&(i=t.parent)&&(i.value+=t.value)}),s}var e=fi,r=ui,n=ci;return t.sort=function(r){return arguments.length?(e=r,t):e},t.children=function(e){return arguments.length?(r=e,t):r},t.value=function(e){return arguments.length?(n=e,t):n},t.revalue=function(e){return n&&(si(e,function(t){t.children&&(t.value=0)}),li(e,function(e){var r;e.children||(e.value=+n.call(t,e,e.depth)||0),(r=e.parent)&&(r.value+=e.value)})),e},t},uo.layout.partition=function(){function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++uf?-1:1),d=uo.sum(u),g=d?(f-l*p)/d:0,v=uo.range(l),m=[];return null!=r&&v.sort(r===kl?function(t,e){return u[e]-u[t]}:function(t,e){return r(o[t],o[e])}),v.forEach(function(t){m[t]={data:o[t],value:s=u[t],startAngle:c,endAngle:c+=s*g+p,padAngle:h}}),m}var e=Number,r=kl,n=0,i=Vo,a=0;return t.value=function(r){return arguments.length?(e=r,t):e},t.sort=function(e){return arguments.length?(r=e,t):r},t.startAngle=function(e){return arguments.length?(n=e,t):n},t.endAngle=function(e){return arguments.length?(i=e,t):i},t.padAngle=function(e){return arguments.length?(a=e,t):a},t};var kl={};uo.layout.stack=function(){function t(s,l){if(!(h=s.length))return s;var u=s.map(function(r,n){return e.call(t,r,n)}),c=u.map(function(e){return e.map(function(e,r){return[a.call(t,e,r),o.call(t,e,r)]})}),f=r.call(t,c,l);u=uo.permute(u,f),c=uo.permute(c,f);var h,p,d,g,v=n.call(t,c,l),m=u[0].length;for(d=0;m>d;++d)for(i.call(t,u[0][d],g=v[d],c[0][d][1]),p=1;h>p;++p)i.call(t,u[p][d],g+=c[p-1][d][1],c[p][d][1]);return s}var e=x,r=vi,n=mi,i=gi,a=pi,o=di;return t.values=function(r){return arguments.length?(e=r,t):e},t.order=function(e){return arguments.length?(r="function"==typeof e?e:Al.get(e)||vi,t):r},t.offset=function(e){return arguments.length?(n="function"==typeof e?e:Ml.get(e)||mi,t):n},t.x=function(e){return arguments.length?(a=e,t):a},t.y=function(e){return arguments.length?(o=e,t):o},t.out=function(e){return arguments.length?(i=e,t):i},t};var Al=uo.map({"inside-out":function(t){var e,r,n=t.length,i=t.map(yi),a=t.map(bi),o=uo.range(n).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,u=[],c=[];for(e=0;n>e;++e)r=o[e],l>s?(s+=a[r],u.push(r)):(l+=a[r],c.push(r));return c.reverse().concat(u)},reverse:function(t){return uo.range(t.length).reverse()},"default":vi}),Ml=uo.map({silhouette:function(t){var e,r,n,i=t.length,a=t[0].length,o=[],s=0,l=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];n>s&&(s=n),o.push(n)}for(r=0;a>r;++r)l[r]=(s-o[r])/2;return l},wiggle:function(t){var e,r,n,i,a,o,s,l,u,c=t.length,f=t[0],h=f.length,p=[];for(p[0]=l=u=0,r=1;h>r;++r){for(e=0,i=0;c>e;++e)i+=t[e][r][1];for(e=0,a=0,s=f[r][0]-f[r-1][0];c>e;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*s);e>n;++n)o+=(t[n][r][1]-t[n][r-1][1])/s;a+=o*t[e][r][1]}p[r]=l-=i?a/i*s:0,u>l&&(u=l)}for(r=0;h>r;++r)p[r]-=u;return p},expand:function(t){var e,r,n,i=t.length,a=t[0].length,o=1/i,s=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];if(n)for(e=0;i>e;e++)t[e][r][1]/=n;else for(e=0;i>e;e++)t[e][r][1]=o}for(r=0;a>r;++r)s[r]=0;return s},zero:mi});uo.layout.histogram=function(){function t(t,a){for(var o,s,l=[],u=t.map(r,this),c=n.call(this,u,a),f=i.call(this,c,u,a),a=-1,h=u.length,p=f.length-1,d=e?1:1/h;++a0)for(a=-1;++a=c[0]&&s<=c[1]&&(o=l[uo.bisect(f,s,1,p)-1],o.y+=d,o.push(t[a]));return l}var e=!0,r=Number,n=ki,i=_i;return t.value=function(e){return arguments.length?(r=e,t):r},t.range=function(e){return arguments.length?(n=Lt(e),t):n},t.bins=function(e){return arguments.length?(i="number"==typeof e?function(t){return wi(t,e)}:Lt(e),t):i},t.frequency=function(r){return arguments.length?(e=!!r,t):e},t},uo.layout.pack=function(){function t(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,li(s,function(t){t.r=+c(t.value)}),li(s,Li),n){var f=n*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;li(s,function(t){t.r+=f}),li(s,Li),li(s,function(t){t.r-=f})}return zi(s,l/2,u/2,e?1:1/Math.max(2*s.r/l,2*s.r/u)),o}var e,r=uo.layout.hierarchy().sort(Ai),n=0,i=[1,1];return t.size=function(e){return arguments.length?(i=e,t):i},t.radius=function(r){return arguments.length?(e=null==r||"function"==typeof r?r:+r,t):e},t.padding=function(e){return arguments.length?(n=+e,t):n},oi(t,r)},uo.layout.tree=function(){function t(t,i){var c=o.call(this,t,i),f=c[0],h=e(f);if(li(h,r),h.parent.m=-h.z,si(h,n),u)si(f,a);else{var p=f,d=f,g=f;si(f,function(t){t.xd.x&&(d=t),t.depth>g.depth&&(g=t)});var v=s(p,d)/2-p.x,m=l[0]/(d.x+s(d,p)/2+v),y=l[1]/(g.depth||1);si(f,function(t){t.x=(t.x+v)*m,t.y=t.depth*y})}return c}function e(t){for(var e,r={A:null,children:[t]},n=[r];null!=(e=n.pop());)for(var i,a=e.children,o=0,s=a.length;s>o;++o)n.push((a[o]=i={_:a[o],parent:e,children:(i=a[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return r.children[0]}function r(t){var e=t.children,r=t.parent.children,n=t.i?r[t.i-1]:null;if(e.length){Ni(t);var a=(e[0].z+e[e.length-1].z)/2;n?(t.z=n.z+s(t._,n._),t.m=t.z-a):t.z=a}else n&&(t.z=n.z+s(t._,n._));t.parent.A=i(t,n,t.parent.A||r[0])}function n(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function i(t,e,r){if(e){for(var n,i=t,a=t,o=e,l=i.parent.children[0],u=i.m,c=a.m,f=o.m,h=l.m;o=Oi(o),i=ji(i),o&&i;)l=ji(l),a=Oi(a),a.a=t,n=o.z+f-i.z-u+s(o._,i._),n>0&&(Ii(Fi(o,t,r),t,n),u+=n,c+=n),f+=o.m,u+=i.m,h+=l.m,c+=a.m;o&&!Oi(a)&&(a.t=o,a.m+=f-c),i&&!ji(l)&&(l.t=i,l.m+=u-h,r=t)}return r}function a(t){t.x*=l[0],t.y=t.depth*l[1]}var o=uo.layout.hierarchy().sort(null).value(null),s=Ri,l=[1,1],u=null;return t.separation=function(e){return arguments.length?(s=e,t):s},t.size=function(e){return arguments.length?(u=null==(l=e)?a:null,t):u?null:l},t.nodeSize=function(e){return arguments.length?(u=null==(l=e)?null:a,t):u?l:null},oi(t,o)},uo.layout.cluster=function(){function t(t,a){ -var o,s=e.call(this,t,a),l=s[0],u=0;li(l,function(t){var e=t.children;e&&e.length?(t.x=Bi(e),t.y=Di(e)):(t.x=o?u+=r(t,o):0,t.y=0,o=t)});var c=Ui(l),f=Vi(l),h=c.x-r(c,f)/2,p=f.x+r(f,c)/2;return li(l,i?function(t){t.x=(t.x-l.x)*n[0],t.y=(l.y-t.y)*n[1]}:function(t){t.x=(t.x-h)/(p-h)*n[0],t.y=(1-(l.y?t.y/l.y:1))*n[1]}),s}var e=uo.layout.hierarchy().sort(null).value(null),r=Ri,n=[1,1],i=!1;return t.separation=function(e){return arguments.length?(r=e,t):r},t.size=function(e){return arguments.length?(i=null==(n=e),t):i?null:n},t.nodeSize=function(e){return arguments.length?(i=null!=(n=e),t):i?n:null},oi(t,e)},uo.layout.treemap=function(){function t(t,e){for(var r,n,i=-1,a=t.length;++ie?0:e),r.area=isNaN(n)||0>=n?0:n}function e(r){var a=r.children;if(a&&a.length){var o,s,l,u=f(r),c=[],h=a.slice(),d=1/0,g="slice"===p?u.dx:"dice"===p?u.dy:"slice-dice"===p?1&r.depth?u.dy:u.dx:Math.min(u.dx,u.dy);for(t(h,u.dx*u.dy/r.value),c.area=0;(l=h.length)>0;)c.push(o=h[l-1]),c.area+=o.area,"squarify"!==p||(s=n(c,g))<=d?(h.pop(),d=s):(c.area-=c.pop().area,i(c,g,u,!1),g=Math.min(u.dx,u.dy),c.length=c.area=0,d=1/0);c.length&&(i(c,g,u,!0),c.length=c.area=0),a.forEach(e)}}function r(e){var n=e.children;if(n&&n.length){var a,o=f(e),s=n.slice(),l=[];for(t(s,o.dx*o.dy/e.value),l.area=0;a=s.pop();)l.push(a),l.area+=a.area,null!=a.z&&(i(l,a.z?o.dx:o.dy,o,!s.length),l.length=l.area=0);n.forEach(r)}}function n(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++or&&(a=r),r>i&&(i=r));return n*=n,e*=e,n?Math.max(e*i*d/n,n/(e*a*d)):1/0}function i(t,e,r,n){var i,a=-1,o=t.length,s=r.x,u=r.y,c=e?l(t.area/e):0;if(e==r.dx){for((n||c>r.dy)&&(c=r.dy);++ar.dx)&&(c=r.dx);++ar&&(e=1),1>r&&(t=0),function(){var r,n,i;do r=2*Math.random()-1,n=2*Math.random()-1,i=r*r+n*n;while(!i||i>1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=uo.random.normal.apply(uo,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=uo.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;t>r;r++)e+=Math.random();return e}}},uo.scale={};var Tl={floor:x,ceil:x};uo.scale.linear=function(){return $i([0,1],[0,1],_n,!1)};var El={s:1,g:1,p:1,r:1,e:1};uo.scale.log=function(){return aa(uo.scale.linear().domain([0,1]),10,!0,[1,10])};var Ll=uo.format(".0e"),Sl={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};uo.scale.pow=function(){return oa(uo.scale.linear(),1,[0,1])},uo.scale.sqrt=function(){return uo.scale.pow().exponent(.5)},uo.scale.ordinal=function(){return la([],{t:"range",a:[[]]})},uo.scale.category10=function(){return uo.scale.ordinal().range(Cl)},uo.scale.category20=function(){return uo.scale.ordinal().range(zl)},uo.scale.category20b=function(){return uo.scale.ordinal().range(Pl)},uo.scale.category20c=function(){return uo.scale.ordinal().range(Rl)};var Cl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(_t),zl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(_t),Pl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(_t),Rl=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(_t);uo.scale.quantile=function(){return ua([],[])},uo.scale.quantize=function(){return ca(0,1,[0,1])},uo.scale.threshold=function(){return fa([.5],[0,1])},uo.scale.identity=function(){return ha([0,1])},uo.svg={},uo.svg.arc=function(){function t(){var t=Math.max(0,+r.apply(this,arguments)),u=Math.max(0,+n.apply(this,arguments)),c=o.apply(this,arguments)-Go,f=s.apply(this,arguments)-Go,h=Math.abs(f-c),p=c>f?0:1;if(t>u&&(d=u,u=t,t=d),h>=qo)return e(u,p)+(t?e(t,1-p):"")+"Z";var d,g,v,m,y,b,x,_,w,k,A,M,T=0,E=0,L=[];if((m=(+l.apply(this,arguments)||0)/2)&&(v=a===jl?Math.sqrt(t*t+u*u):+a.apply(this,arguments),p||(E*=-1),u&&(E=nt(v/u*Math.sin(m))),t&&(T=nt(v/t*Math.sin(m)))),u){y=u*Math.cos(c+E),b=u*Math.sin(c+E),x=u*Math.cos(f-E),_=u*Math.sin(f-E);var S=Math.abs(f-c-2*E)<=Uo?0:1;if(E&&ba(y,b,x,_)===p^S){var C=(c+f)/2;y=u*Math.cos(C),b=u*Math.sin(C),x=_=null}}else y=b=0;if(t){w=t*Math.cos(f-T),k=t*Math.sin(f-T),A=t*Math.cos(c+T),M=t*Math.sin(c+T);var z=Math.abs(c-f+2*T)<=Uo?0:1;if(T&&ba(w,k,A,M)===1-p^z){var P=(c+f)/2;w=t*Math.cos(P),k=t*Math.sin(P),A=M=null}}else w=k=0;if(h>Do&&(d=Math.min(Math.abs(u-t)/2,+i.apply(this,arguments)))>.001){g=u>t^p?0:1;var R=d,j=d;if(Uo>h){var O=null==A?[w,k]:null==x?[y,b]:Or([y,b],[A,M],[x,_],[w,k]),I=y-O[0],N=b-O[1],F=x-O[0],D=_-O[1],B=1/Math.sin(Math.acos((I*F+N*D)/(Math.sqrt(I*I+N*N)*Math.sqrt(F*F+D*D)))/2),U=Math.sqrt(O[0]*O[0]+O[1]*O[1]);j=Math.min(d,(t-U)/(B-1)),R=Math.min(d,(u-U)/(B+1))}if(null!=x){var V=xa(null==A?[w,k]:[A,M],[y,b],u,R,p),q=xa([x,_],[w,k],u,R,p);d===R?L.push("M",V[0],"A",R,",",R," 0 0,",g," ",V[1],"A",u,",",u," 0 ",1-p^ba(V[1][0],V[1][1],q[1][0],q[1][1]),",",p," ",q[1],"A",R,",",R," 0 0,",g," ",q[0]):L.push("M",V[0],"A",R,",",R," 0 1,",g," ",q[0])}else L.push("M",y,",",b);if(null!=A){var G=xa([y,b],[A,M],t,-j,p),H=xa([w,k],null==x?[y,b]:[x,_],t,-j,p);d===j?L.push("L",H[0],"A",j,",",j," 0 0,",g," ",H[1],"A",t,",",t," 0 ",p^ba(H[1][0],H[1][1],G[1][0],G[1][1]),",",1-p," ",G[1],"A",j,",",j," 0 0,",g," ",G[0]):L.push("L",H[0],"A",j,",",j," 0 0,",g," ",G[0])}else L.push("L",w,",",k)}else L.push("M",y,",",b),null!=x&&L.push("A",u,",",u," 0 ",S,",",p," ",x,",",_),L.push("L",w,",",k),null!=A&&L.push("A",t,",",t," 0 ",z,",",1-p," ",A,",",M);return L.push("Z"),L.join("")}function e(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}var r=da,n=ga,i=pa,a=jl,o=va,s=ma,l=ya;return t.innerRadius=function(e){return arguments.length?(r=Lt(e),t):r},t.outerRadius=function(e){return arguments.length?(n=Lt(e),t):n},t.cornerRadius=function(e){return arguments.length?(i=Lt(e),t):i},t.padRadius=function(e){return arguments.length?(a=e==jl?jl:Lt(e),t):a},t.startAngle=function(e){return arguments.length?(o=Lt(e),t):o},t.endAngle=function(e){return arguments.length?(s=Lt(e),t):s},t.padAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.centroid=function(){var t=(+r.apply(this,arguments)+ +n.apply(this,arguments))/2,e=(+o.apply(this,arguments)+ +s.apply(this,arguments))/2-Go;return[Math.cos(e)*t,Math.sin(e)*t]},t};var jl="auto";uo.svg.line=function(){return _a(x)};var Ol=uo.map({linear:wa,"linear-closed":ka,step:Aa,"step-before":Ma,"step-after":Ta,basis:Pa,"basis-open":Ra,"basis-closed":ja,bundle:Oa,cardinal:Sa,"cardinal-open":Ea,"cardinal-closed":La,monotone:Ua});Ol.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Il=[0,2/3,1/3,0],Nl=[0,1/3,2/3,0],Fl=[0,1/6,2/3,1/6];uo.svg.line.radial=function(){var t=_a(Va);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Ma.reverse=Ta,Ta.reverse=Ma,uo.svg.area=function(){return qa(x)},uo.svg.area.radial=function(){var t=qa(Va);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},uo.svg.chord=function(){function t(t,s){var l=e(this,a,t,s),u=e(this,o,t,s);return"M"+l.p0+n(l.r,l.p1,l.a1-l.a0)+(r(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+n(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function e(t,e,r,n){var i=e.call(t,r,n),a=s.call(t,i,n),o=l.call(t,i,n)-Go,c=u.call(t,i,n)-Go;return{r:a,a0:o,a1:c,p0:[a*Math.cos(o),a*Math.sin(o)],p1:[a*Math.cos(c),a*Math.sin(c)]}}function r(t,e){return t.a0==e.a0&&t.a1==e.a1}function n(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Uo)+",1 "+e}function i(t,e,r,n){return"Q 0,0 "+n}var a=xr,o=_r,s=Ga,l=va,u=ma;return t.radius=function(e){return arguments.length?(s=Lt(e),t):s},t.source=function(e){return arguments.length?(a=Lt(e),t):a},t.target=function(e){return arguments.length?(o=Lt(e),t):o},t.startAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.endAngle=function(e){return arguments.length?(u=Lt(e),t):u},t},uo.svg.diagonal=function(){function t(t,i){var a=e.call(this,t,i),o=r.call(this,t,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return l=l.map(n),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,r=_r,n=Ha;return t.source=function(r){return arguments.length?(e=Lt(r),t):e},t.target=function(e){return arguments.length?(r=Lt(e),t):r},t.projection=function(e){return arguments.length?(n=e,t):n},t},uo.svg.diagonal.radial=function(){var t=uo.svg.diagonal(),e=Ha,r=t.projection;return t.projection=function(t){return arguments.length?r(Ya(e=t)):e},t},uo.svg.symbol=function(){function t(t,n){return(Dl.get(e.call(this,t,n))||Za)(r.call(this,t,n))}var e=Wa,r=Xa;return t.type=function(r){return arguments.length?(e=Lt(r),t):e},t.size=function(e){return arguments.length?(r=Lt(e),t):r},t};var Dl=uo.map({circle:Za,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Ul)),r=e*Ul;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});uo.svg.symbolTypes=Dl.keys();var Bl=Math.sqrt(3),Ul=Math.tan(30*Ho);zo.transition=function(t){for(var e,r,n=Vl||++Yl,i=to(t),a=[],o=ql||{time:Date.now(),ease:Ln,delay:0,duration:250},s=-1,l=this.length;++sa;a++){i.push(e=[]);for(var r=this[a],s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return $a(i,this.namespace,this.id)},Hl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):H(this,null==e?function(e){e[n][r].tween.remove(t)}:function(i){i[n][r].tween.set(t,e)})},Hl.attr=function(t,e){function r(){this.removeAttribute(s)}function n(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?r:(t+="",function(){var e,r=this.getAttribute(s);return r!==t&&(e=o(r,t),function(t){this.setAttribute(s,e(t))})})}function a(t){return null==t?n:(t+="",function(){var e,r=this.getAttributeNS(s.space,s.local);return r!==t&&(e=o(r,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var o="transform"==t?Zn:_n,s=uo.ns.qualify(t);return Qa(this,"attr."+t,e,s.local?a:i)},Hl.attrTween=function(t,e){function r(t,r){var n=e.call(this,t,r,this.getAttribute(i));return n&&function(t){this.setAttribute(i,n(t))}}function n(t,r){var n=e.call(this,t,r,this.getAttributeNS(i.space,i.local));return n&&function(t){this.setAttributeNS(i.space,i.local,n(t))}}var i=uo.ns.qualify(t);return this.tween("attr."+t,i.local?n:r)},Hl.style=function(t,e,r){function i(){this.style.removeProperty(t)}function a(e){return null==e?i:(e+="",function(){var i,a=n(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(i=_n(a,e),function(e){this.style.setProperty(t,i(e),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(r in t)this.style(r,t[r],e);return this}r=""}return Qa(this,"style."+t,e,a)},Hl.styleTween=function(t,e,r){function i(i,a){var o=e.call(this,i,a,n(this).getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),r)}}return arguments.length<3&&(r=""),this.tween("style."+t,i)},Hl.text=function(t){return Qa(this,"text",t,Ja)},Hl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},Hl.ease=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].ease:("function"!=typeof t&&(t=uo.ease.apply(uo,arguments)),H(this,function(n){n[r][e].ease=t}))},Hl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:H(this,"function"==typeof t?function(n,i,a){n[r][e].delay=+t.call(n,n.__data__,i,a)}:(t=+t,function(n){n[r][e].delay=t}))},Hl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:H(this,"function"==typeof t?function(n,i,a){n[r][e].duration=Math.max(1,t.call(n,n.__data__,i,a))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},Hl.each=function(t,e){var r=this.id,n=this.namespace;if(arguments.length<2){var i=ql,a=Vl;try{Vl=r,H(this,function(e,i,a){ql=e[n][r],t.call(e,e.__data__,i,a)})}finally{ql=i,Vl=a}}else H(this,function(i){var a=i[n][r];(a.event||(a.event=uo.dispatch("start","end","interrupt"))).on(t,e)});return this},Hl.transition=function(){for(var t,e,r,n,i=this.id,a=++Yl,o=this.namespace,s=[],l=0,u=this.length;u>l;l++){s.push(t=[]);for(var e=this[l],c=0,f=e.length;f>c;c++)(r=e[c])&&(n=r[o][i],eo(r,c,o,a,{time:n.time,ease:n.ease,delay:n.delay+n.duration,duration:n.duration})),t.push(r)}return $a(s,o,a)},uo.svg.axis=function(){function t(t){t.each(function(){var t,u=uo.select(this),c=this.__chart__||r,f=this.__chart__=r.copy(),h=null==l?f.ticks?f.ticks.apply(f,s):f.domain():l,p=null==e?f.tickFormat?f.tickFormat.apply(f,s):x:e,d=u.selectAll(".tick").data(h,f),g=d.enter().insert("g",".domain").attr("class","tick").style("opacity",Do),v=uo.transition(d.exit()).style("opacity",Do).remove(),m=uo.transition(d.order()).style("opacity",1),y=Math.max(i,0)+o,b=Yi(f),_=u.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),uo.transition(_));g.append("line"),g.append("text");var k,A,M,T,E=g.select("line"),L=m.select("line"),S=d.select("text").text(p),C=g.select("text"),z=m.select("text"),P="top"===n||"left"===n?-1:1;if("bottom"===n||"top"===n?(t=ro,k="x",M="y",A="x2",T="y2",S.attr("dy",0>P?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+P*a+"V0H"+b[1]+"V"+P*a)):(t=no,k="y",M="x",A="y2",T="x2",S.attr("dy",".32em").style("text-anchor",0>P?"end":"start"),w.attr("d","M"+P*a+","+b[0]+"H0V"+b[1]+"H"+P*a)),E.attr(T,P*i),C.attr(M,P*y),L.attr(A,0).attr(T,P*i),z.attr(k,0).attr(M,P*y),f.rangeBand){var R=f,j=R.rangeBand()/2;c=f=function(t){return R(t)+j}}else c.rangeBand?c=f:v.call(t,f,c);g.call(t,c,f),m.call(t,f,f)})}var e,r=uo.scale.linear(),n=Xl,i=6,a=6,o=3,s=[10],l=null;return t.scale=function(e){return arguments.length?(r=e,t):r},t.orient=function(e){return arguments.length?(n=e in Wl?e+"":Xl,t):n},t.ticks=function(){return arguments.length?(s=fo(arguments),t):s},t.tickValues=function(e){return arguments.length?(l=e,t):l},t.tickFormat=function(r){return arguments.length?(e=r,t):e},t.tickSize=function(e){var r=arguments.length;return r?(i=+e,a=+arguments[r-1],t):i},t.innerTickSize=function(e){return arguments.length?(i=+e,t):i},t.outerTickSize=function(e){return arguments.length?(a=+e,t):a},t.tickPadding=function(e){return arguments.length?(o=+e,t):o},t.tickSubdivide=function(){return arguments.length&&t},t};var Xl="bottom",Wl={top:1,right:1,bottom:1,left:1};uo.svg.brush=function(){function t(n){n.each(function(){var n=uo.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",a).on("touchstart.brush",a),o=n.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),n.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=n.selectAll(".resize").data(g,x);s.exit().remove(),s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Zl[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),s.style("display",t.empty()?"none":null);var l,f=uo.transition(n),h=uo.transition(o);u&&(l=Yi(u),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(f)),c&&(l=Yi(c),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(f)),e(f)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+f[+/e$/.test(t)]+","+h[+/^s/.test(t)]+")"})}function r(t){t.select(".extent").attr("x",f[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",f[1]-f[0])}function i(t){t.select(".extent").attr("y",h[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function a(){function a(){32==uo.event.keyCode&&(S||(b=null,z[0]-=f[1],z[1]-=h[1],S=2),T())}function g(){32==uo.event.keyCode&&2==S&&(z[0]+=f[1],z[1]+=h[1],S=0,T())}function v(){var t=uo.mouse(_),n=!1;x&&(t[0]+=x[0],t[1]+=x[1]),S||(uo.event.altKey?(b||(b=[(f[0]+f[1])/2,(h[0]+h[1])/2]),z[0]=f[+(t[0]c?(i=n,n=c):i=c),g[0]!=n||g[1]!=i?(r?s=null:o=null,g[0]=n,g[1]=i,!0):void 0}function y(){v(),A.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null),uo.select("body").style("cursor",null),P.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),C(),k({type:"brushend"})}var b,x,_=this,w=uo.select(uo.event.target),k=l.of(_,arguments),A=uo.select(_),M=w.datum(),E=!/^(n|s)$/.test(M)&&u,L=!/^(e|w)$/.test(M)&&c,S=w.classed("extent"),C=$(_),z=uo.mouse(_),P=uo.select(n(_)).on("keydown.brush",a).on("keyup.brush",g);if(uo.event.changedTouches?P.on("touchmove.brush",v).on("touchend.brush",y):P.on("mousemove.brush",v).on("mouseup.brush",y),A.interrupt().selectAll("*").interrupt(),S)z[0]=f[0]-z[0],z[1]=h[0]-z[1];else if(M){var R=+/w$/.test(M),j=+/^n/.test(M);x=[f[1-R]-z[0],h[1-j]-z[1]],z[0]=f[R],z[1]=h[j]}else uo.event.altKey&&(b=z.slice());A.style("pointer-events","none").selectAll(".resize").style("display",null),uo.select("body").style("cursor",w.style("cursor")),k({type:"brushstart"}),v()}var o,s,l=L(t,"brushstart","brush","brushend"),u=null,c=null,f=[0,0],h=[0,0],p=!0,d=!0,g=Kl[0];return t.event=function(t){t.each(function(){var t=l.of(this,arguments),e={x:f,y:h,i:o,j:s},r=this.__chart__||e;this.__chart__=e,Vl?uo.select(this).transition().each("start.brush",function(){o=r.i,s=r.j,f=r.x,h=r.y,t({type:"brushstart"})}).tween("brush:brush",function(){var r=wn(f,e.x),n=wn(h,e.y);return o=s=null,function(i){f=e.x=r(i),h=e.y=n(i),t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i,s=e.j,t({type:"brush",mode:"resize"}),t({type:"brushend"})}):(t({type:"brushstart"}),t({type:"brush",mode:"resize"}),t({type:"brushend"}))})},t.x=function(e){return arguments.length?(u=e,g=Kl[!u<<1|!c],t):u},t.y=function(e){return arguments.length?(c=e,g=Kl[!u<<1|!c],t):c},t.clamp=function(e){return arguments.length?(u&&c?(p=!!e[0],d=!!e[1]):u?p=!!e:c&&(d=!!e),t):u&&c?[p,d]:u?p:c?d:null},t.extent=function(e){var r,n,i,a,l;return arguments.length?(u&&(r=e[0],n=e[1],c&&(r=r[0],n=n[0]),o=[r,n],u.invert&&(r=u(r),n=u(n)),r>n&&(l=r,r=n,n=l),r==f[0]&&n==f[1]||(f=[r,n])),c&&(i=e[0],a=e[1],u&&(i=i[1],a=a[1]),s=[i,a],c.invert&&(i=c(i),a=c(a)),i>a&&(l=i,i=a,a=l),i==h[0]&&a==h[1]||(h=[i,a])),t):(u&&(o?(r=o[0],n=o[1]):(r=f[0],n=f[1],u.invert&&(r=u.invert(r),n=u.invert(n)),r>n&&(l=r,r=n,n=l))),c&&(s?(i=s[0],a=s[1]):(i=h[0],a=h[1],c.invert&&(i=c.invert(i),a=c.invert(a)),i>a&&(l=i,i=a,a=l))),u&&c?[[r,i],[n,a]]:u?[r,n]:c&&[i,a])},t.clear=function(){return t.empty()||(f=[0,0],h=[0,0],o=s=null),t},t.empty=function(){return!!u&&f[0]==f[1]||!!c&&h[0]==h[1]},uo.rebind(t,l,"on")};var Zl={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Kl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],$l=vs.format=ws.timeFormat,Ql=$l.utc,Jl=Ql("%Y-%m-%dT%H:%M:%S.%LZ");$l.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?io:Jl,io.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},io.toString=Jl.toString,vs.second=Vt(function(t){return new ms(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),vs.seconds=vs.second.range,vs.seconds.utc=vs.second.utc.range,vs.minute=Vt(function(t){return new ms(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),vs.minutes=vs.minute.range,vs.minutes.utc=vs.minute.utc.range,vs.hour=Vt(function(t){var e=t.getTimezoneOffset()/60;return new ms(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),vs.hours=vs.hour.range,vs.hours.utc=vs.hour.utc.range,vs.month=Vt(function(t){return t=vs.day(t),t.setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),vs.months=vs.month.range,vs.months.utc=vs.month.utc.range;var tu=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],eu=[[vs.second,1],[vs.second,5],[vs.second,15],[vs.second,30],[vs.minute,1],[vs.minute,5],[vs.minute,15],[vs.minute,30],[vs.hour,1],[vs.hour,3],[vs.hour,6],[vs.hour,12],[vs.day,1],[vs.day,2],[vs.week,1],[vs.month,1],[vs.month,3],[vs.year,1]],ru=$l.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",ze]]),nu={range:function(t,e,r){return uo.range(Math.ceil(t/r)*r,+e,r).map(oo)},floor:x,ceil:x};eu.year=vs.year,vs.scale=function(){return ao(uo.scale.linear(),eu,ru)};var iu=eu.map(function(t){return[t[0].utc,t[1]]}),au=Ql.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",ze]]);iu.year=vs.year.utc,vs.scale.utc=function(){return ao(uo.scale.linear(),iu,au)},uo.text=St(function(t){return t.responseText}),uo.json=function(t,e){return Ct(t,"application/json",so,e)},uo.html=function(t,e){return Ct(t,"text/html",lo,e)},uo.xml=St(function(t){return t.responseXML}),"function"==typeof t&&t.amd?(this.d3=uo,t(uo)):"object"==typeof r&&r.exports?r.exports=uo:this.d3=uo}()},{}],83:[function(t,e,r){arguments[4][76][0].apply(r,arguments)},{dup:76,"robust-orientation":1040,"simplicial-complex":86}],84:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],85:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],86:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":84,dup:79,"union-find":85}],87:[function(t,e,r){"use strict";function n(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;n>o;++o)if(a=i,i=t[o],e(i,a)){if(o===r){r++;continue}t[r++]=i}return t.length=r,t}function i(t){for(var e=1,r=t.length,n=t[0],i=t[0],a=1;r>a;++a,i=n)if(i=n,n=t[a],n!==i){if(a===e){e++;continue}t[e++]=n}return t.length=e,t}function a(t,e,r){return 0===t.length?t:e?(r||t.sort(e),n(t,e)):(r||t.sort(),i(t))}e.exports=a},{}],88:[function(t,e,r){"use strict";function n(t,e){this.point=t,this.index=e}function i(t,e){for(var r=t.point,n=e.point,i=r.length,a=0;i>a;++a){var o=n[a]-r[a];if(o)return o}return 0}function a(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;t>a;++a){var o=n[a-1],s=n[a];i[a-1]=[o[1],s[1]]}return r&&i.push([-1,i[0][1]],[i[t-1][1],-1]),i}function o(t,e){var r=t.length;if(0===r)return[];var o=t[0].length;if(1>o)return[];if(1===o)return a(r,t,e);for(var u=new Array(r),c=1,f=0;r>f;++f){for(var h=t[f],p=new Array(o+1),d=0,g=0;o>g;++g){var v=h[g];p[g]=v,d+=v*v}p[o]=d,u[f]=new n(p,f),c=Math.max(d,c)}l(u,i),r=u.length;for(var m=new Array(r+o+1),y=new Array(r+o+1),b=(o+1)*(o+1)*c,x=new Array(o+1),f=0;o>=f;++f)x[f]=0;x[o]=b,m[0]=x.slice(),y[0]=-1;for(var f=0;o>=f;++f){var p=x.slice();p[f]=1,m[f+1]=p,y[f+1]=-1}for(var f=0;r>f;++f){var _=u[f];m[f+o+1]=_.point,y[f+o+1]=_.index}var w=s(m,!1);if(w=e?w.filter(function(t){for(var e=0,r=0;o>=r;++r){var n=y[t[r]];if(0>n&&++e>=2)return!1;t[r]=n}return!0}):w.filter(function(t){for(var e=0;o>=e;++e){var r=y[t[e]];if(0>r)return!1;t[e]=r}return!0}),1&o)for(var f=0;ft;t+=2){var e=at[t],r=at[t+1];e(r),at[t]=void 0,at[t+1]=void 0}Q=0}function g(){try{var t=e,r=t("vertx");return W=r.runOnLoop||r.runOnContext,c()}catch(n){return p()}}function v(t,e){var r=this,n=new this.constructor(y);void 0===n[lt]&&N(n);var i=r._state;if(i){var a=arguments[i-1];J(function(){j(i,n,a,r._result)})}else C(r,n,t,e);return n}function m(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var r=new e(y);return T(r,t),r}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function x(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return ht.error=e,ht}}function w(t,e,r,n){try{t.call(e,r,n)}catch(i){return i}}function k(t,e,r){J(function(t){var n=!1,i=w(r,e,function(r){n||(n=!0,e!==r?T(t,r):L(t,r))},function(e){n||(n=!0,S(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&i&&(n=!0,S(t,i))},t)}function A(t,e){e._state===ct?L(t,e._result):e._state===ft?S(t,e._result):C(e,void 0,function(e){T(t,e)},function(e){S(t,e)})}function M(t,e,r){e.constructor===t.constructor&&r===ot&&constructor.resolve===st?A(t,e):r===ht?S(t,ht.error):void 0===r?L(t,e):o(r)?k(t,e,r):L(t,e)}function T(t,e){t===e?S(t,b()):a(e)?M(t,e,_(e)):L(t,e)}function E(t){t._onerror&&t._onerror(t._result),z(t)}function L(t,e){t._state===ut&&(t._result=e,t._state=ct,0!==t._subscribers.length&&J(z,t))}function S(t,e){t._state===ut&&(t._state=ft,t._result=e,J(E,t))}function C(t,e,r,n){var i=t._subscribers,a=i.length;t._onerror=null,i[a]=e,i[a+ct]=r,i[a+ft]=n,0===a&&t._state&&J(z,t)}function z(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n,i,a=t._result,o=0;oa;a++)e.resolve(t[a]).then(r,n)}:function(t,e){e(new TypeError("You must pass an array to race."))})}function B(t){var e=this,r=new e(y);return S(r,t),r}function U(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function V(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function q(t){this[lt]=I(),this._result=this._state=void 0,this._subscribers=[],y!==t&&("function"!=typeof t&&U(),this instanceof q?O(this,t):V())}function G(t,e){this._instanceConstructor=t,this.promise=new t(y),this.promise[lt]||N(this.promise),$(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?L(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&L(this.promise,this._result))):S(this.promise,H())}function H(){return new Error("Array Methods must be provided an Array")}function Y(){var t;if("undefined"!=typeof i)t=i;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var r=t.Promise;r&&"[object Promise]"===Object.prototype.toString.call(r.resolve())&&!r.cast||(t.Promise=yt)}var X;X=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var W,Z,K,$=X,Q=0,J=function(t,e){at[Q]=t,at[Q+1]=e,Q+=2,2===Q&&(Z?Z(d):K())},tt="undefined"!=typeof window?window:void 0,et=tt||{},rt=et.MutationObserver||et.WebKitMutationObserver,nt="undefined"==typeof self&&"undefined"!=typeof n&&"[object process]"==={}.toString.call(n),it="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,at=new Array(1e3); -K=nt?u():rt?f():it?h():void 0===tt&&"function"==typeof e?g():p();var ot=v,st=m,lt=Math.random().toString(36).substring(16),ut=void 0,ct=1,ft=2,ht=new P,pt=new P,dt=0,gt=F,vt=D,mt=B,yt=q;q.all=gt,q.race=vt,q.resolve=st,q.reject=mt,q._setScheduler=s,q._setAsap=l,q._asap=J,q.prototype={constructor:q,then:ot,"catch":function(t){return this.then(null,t)}};var bt=G;G.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===ut&&t>r;r++)this._eachEntry(e[r],r)},G.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===st){var i=_(t);if(i===ot&&t._state!==ut)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(r===yt){var a=new r(y);M(a,t,i),this._willSettleAt(a,e)}else this._willSettleAt(new r(function(e){e(t)}),e)}else this._willSettleAt(n(t),e)},G.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===ut&&(this._remaining--,t===ft?S(n,r):this._result[e]=r),0===this._remaining&&L(n,this._result)},G.prototype._willSettleAt=function(t,e){var r=this;C(t,void 0,function(t){r._settledAt(ct,e,t)},function(t){r._settledAt(ft,e,t)})};var xt=Y,_t={Promise:yt,polyfill:xt};"function"==typeof t&&t.amd?t(function(){return _t}):"undefined"!=typeof r&&r.exports?r.exports=_t:"undefined"!=typeof this&&(this.ES6Promise=_t),xt()}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:70}],90:[function(t,e,r){"use strict";function n(t){for(var e,r=t.length,n=0;r>n;n++)if(e=t.charCodeAt(n),(9>e||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(8192>e||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(t=+t,0===t&&n(r))return!1}else if("number"!==e)return!1;return 1>t-t}},{}],91:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.shader=e,this.buffer=r,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.color=[0,0,0,1]}function i(t,e){var r=a(t.gl,l.vertex,l.fragment),i=o(t.gl),s=new n(t,r,i);return s.update(e),t.addObject(s),s}var a=t("gl-shader"),o=t("gl-buffer"),s=t("typedarray-pool"),l=t("./lib/shaders");e.exports=i;var u=[[1,0,0,1,0,0],[1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,1,0,0],[1,0,0,1,0,0],[1,0,-1,0,0,1],[1,0,-1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,1],[1,0,-1,0,0,1],[-1,0,-1,0,0,1],[-1,0,-1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,1],[-1,0,-1,0,0,1],[0,1,1,0,0,0],[0,1,-1,0,0,0],[0,-1,-1,0,0,0],[0,-1,-1,0,0,0],[0,1,1,0,0,0],[0,-1,1,0,0,0],[0,1,0,-1,1,0],[0,1,0,-1,-1,0],[0,1,0,1,-1,0],[0,1,0,1,1,0],[0,1,0,-1,1,0],[0,1,0,1,-1,0],[0,-1,0,-1,1,0],[0,-1,0,-1,-1,0],[0,-1,0,1,-1,0],[0,-1,0,1,1,0],[0,-1,0,-1,1,0],[0,-1,0,1,-1,0]],c=n.prototype;c.draw=function(){var t=[1,0,0,0,1,0,0,0,1],e=[1,1];return function(){var r=this.plot,n=this.shader,i=this.buffer,a=this.bounds,o=this.numPoints;if(o){var s=r.gl,l=r.dataBox,c=r.viewBox,f=r.pixelRatio,h=a[2]-a[0],p=a[3]-a[1],d=l[2]-l[0],g=l[3]-l[1];t[0]=2*h/d,t[4]=2*p/g,t[6]=2*(a[0]-l[0])/d-1,t[7]=2*(a[1]-l[1])/g-1;var v=c[2]-c[0],m=c[3]-c[1];e[0]=2*f/v,e[1]=2*f/m,i.bind(),n.bind(),n.uniforms.viewTransform=t,n.uniforms.pixelScale=e,n.uniforms.color=this.color,n.attributes.position.pointer(s.FLOAT,!1,16,0),n.attributes.pixelOffset.pointer(s.FLOAT,!1,16,8),s.drawArrays(s.TRIANGLES,0,o*u.length)}}}(),c.drawPick=function(t){return t},c.pick=function(t,e){return null},c.update=function(t){t=t||{};var e,r,n,i=t.positions||[],a=t.errors||[],o=1;"lineWidth"in t&&(o=+t.lineWidth);var l=5;"capSize"in t&&(l=+t.capSize),this.color=(t.color||[0,0,0,1]).slice();var c=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=this.numPoints=i.length>>1;for(e=0;f>e;++e)r=i[2*e],n=i[2*e+1],c[0]=Math.min(r,c[0]),c[1]=Math.min(n,c[1]),c[2]=Math.max(r,c[2]),c[3]=Math.max(n,c[3]);c[2]===c[0]&&(c[2]+=1),c[3]===c[1]&&(c[3]+=1);var h=1/(c[2]-c[0]),p=1/(c[3]-c[1]),d=c[0],g=c[1],v=s.mallocFloat32(f*u.length*4),m=0;for(e=0;f>e;++e){r=i[2*e],n=i[2*e+1];for(var y=a[4*e],b=a[4*e+1],x=a[4*e+2],_=a[4*e+3],w=0;wA?A*=y:A>0&&(A*=b),0>M?M*=x:M>0&&(M*=_),v[m++]=h*(r-d+A),v[m++]=p*(n-g+M),v[m++]=o*k[2]+(l+o)*k[4],v[m++]=o*k[3]+(l+o)*k[5]}}this.buffer.update(v),s.free(v)},c.dispose=function(){this.plot.removeObject(this),this.shader.dispose(),this.buffer.dispose()}},{"./lib/shaders":92,"gl-buffer":93,"gl-shader":94,"typedarray-pool":122}],92:[function(t,e,r){e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n",fragment:"precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"}},{}],93:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}function i(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(0>a)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function a(t,e){for(var r=l.malloc(t.length,e),n=t.length,i=0;n>i;++i)r[i]=t[i];return r}function o(t,e){for(var r=1,n=e.length-1;n>=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}function s(t,e,r,i){if(r=r||t.ARRAY_BUFFER,i=i||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(i!==t.DYNAMIC_DRAW&&i!==t.STATIC_DRAW&&i!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=t.createBuffer(),o=new n(t,r,a,0,i);return o.update(e),o}var l=t("typedarray-pool"),u=t("ndarray-ops"),c=t("ndarray"),f=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"],h=n.prototype;h.bind=function(){this.gl.bindBuffer(this.type,this.handle)},h.unbind=function(){this.gl.bindBuffer(this.type,null)},h.dispose=function(){this.gl.deleteBuffer(this.handle)},h.update=function(t,e){if("number"!=typeof e&&(e=-1),this.bind(),"object"==typeof t&&"undefined"!=typeof t.shape){var r=t.dtype;if(f.indexOf(r)<0&&(r="float32"),this.type===this.gl.ELEMENT_ARRAY_BUFFER){var n=gl.getExtension("OES_element_index_uint");r=n&&"uint16"!==r?"uint32":"uint16"}if(r===t.dtype&&o(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=i(this.gl,this.type,this.length,this.usage,t.data,e):this.length=i(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=l.malloc(t.size,r),h=c(s,t.shape);u.assign(h,t),0>e?this.length=i(this.gl,this.type,this.length,this.usage,s,e):this.length=i(this.gl,this.type,this.length,this.usage,s.subarray(0,t.size),e),l.free(s)}}else if(Array.isArray(t)){var p;p=this.type===this.gl.ELEMENT_ARRAY_BUFFER?a(t,"uint16"):a(t,"float32"),0>e?this.length=i(this.gl,this.type,this.length,this.usage,p,e):this.length=i(this.gl,this.type,this.length,this.usage,p.subarray(0,t.length),e),l.free(p)}else if("object"==typeof t&&"number"==typeof t.length)this.length=i(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");t=0|t,0>=t&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=s},{ndarray:1031,"ndarray-ops":1026,"typedarray-pool":122}],94:[function(t,e,r){"use strict";function n(t){this.gl=t,this._vref=this._fref=this._relink=this.vertShader=this.fragShader=this.program=this.attributes=this.uniforms=this.types=null}function i(t,e){return t.name=0){for(var A=0|k.type.charAt(k.type.length-1),M=new Array(A),T=0;A>T;++T)M[T]=_.length,x.push(k.name+"["+T+"]"),"number"==typeof k.location?_.push(k.location+T):Array.isArray(k.location)&&k.location.length===A&&"number"==typeof k.location[T]?_.push(0|k.location[T]):_.push(-1);b.push({name:k.name,type:k.type,locations:M})}else b.push({name:k.name,type:k.type,locations:[_.length]}),x.push(k.name),"number"==typeof k.location?_.push(0|k.location):_.push(-1)}for(var E=0,w=0;w<_.length;++w)if(_[w]<0){for(;_.indexOf(E)>=0;)E+=1;_[w]=E}var L=new Array(r.length);a(),p._relink=a,p.types={uniforms:l(r),attributes:l(n)},p.attributes=s(d,p,b,_),Object.defineProperty(p,"uniforms",o(d,p,r,L))},e.exports=a},{"./lib/GLError":95,"./lib/create-attributes":96,"./lib/create-uniforms":97,"./lib/reflect":98,"./lib/runtime-reflect":99,"./lib/shader-cache":100}],95:[function(t,e,r){function n(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}n.prototype=new Error,n.prototype.name="GLError",n.prototype.constructor=n,e.exports=n},{}],96:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}function i(t,e,r,i,a,o,s){for(var l=["gl","v"],u=[],c=0;a>c;++c)l.push("x"+c),u.push("x"+c);l.push("if(x0.length===void 0){return gl.vertexAttrib"+a+"f(v,"+u.join()+")}else{return gl.vertexAttrib"+a+"fv(v,x0)}");var f=Function.apply(null,l),h=new n(t,e,r,i,a,f);Object.defineProperty(o,s,{set:function(e){return t.disableVertexAttribArray(i[r]),f(t,i[r],e),e},get:function(){return h},enumerable:!0})}function a(t,e,r,n,a,o,s){for(var l=new Array(a),u=new Array(a),c=0;a>c;++c)i(t,e,r[c],n,a,l,c),u[c]=l[c];Object.defineProperty(l,"location",{set:function(t){if(Array.isArray(t))for(var e=0;a>e;++e)u[e].location=t[e];else for(var e=0;a>e;++e)u[e].location=t+e;return t},get:function(){for(var t=new Array(a),e=0;a>e;++e)t[e]=n[r[e]];return t},enumerable:!0}),l.pointer=function(e,i,o,s){e=e||t.FLOAT,i=!!i,o=o||a*a,s=s||0;for(var l=0;a>l;++l){var u=n[r[l]];t.vertexAttribPointer(u,a,e,i,o,s+l*a),t.enableVertexAttribArray(u)}};var f=new Array(a),h=t["vertexAttrib"+a+"fv"];Object.defineProperty(o,s,{set:function(e){for(var i=0;a>i;++i){var o=n[r[i]];if(t.disableVertexAttribArray(o),Array.isArray(e[0]))h.call(t,o,e[i]);else{for(var s=0;a>s;++s)f[s]=e[a*i+s];h.call(t,o,f)}}return e},get:function(){return l},enumerable:!0})}function o(t,e,r,n){for(var o={},l=0,u=r.length;u>l;++l){var c=r[l],f=c.name,h=c.type,p=c.locations;switch(h){case"bool":case"int":case"float":i(t,e,p[0],n,1,o,f);break;default:if(h.indexOf("vec")>=0){var d=h.charCodeAt(h.length-1)-48;if(2>d||d>4)throw new s("","Invalid data type for attribute "+f+": "+h);i(t,e,p[0],n,d,o,f)}else{if(!(h.indexOf("mat")>=0))throw new s("","Unknown data type for attribute "+f+": "+h);var d=h.charCodeAt(h.length-1)-48;if(2>d||d>4)throw new s("","Invalid data type for attribute "+f+": "+h);a(t,e,p,n,d,o,f)}}}return o}e.exports=o;var s=t("./GLError"),l=n.prototype;l.pointer=function(t,e,r,n){var i=this,a=i._gl,o=i._locations[i._index];a.vertexAttribPointer(o,i._dimension,t||a.FLOAT,!!e,r||0,n||0),a.enableVertexAttribArray(o)},l.set=function(t,e,r,n){return this._constFunc(this._locations[this._index],t,e,r,n)},Object.defineProperty(l,"location",{get:function(){return this._locations[this._index]},set:function(t){return t!==this._locations[this._index]&&(this._locations[this._index]=0|t,this._wrapper.program=null),0|t}})},{"./GLError":95}],97:[function(t,e,r){"use strict";function n(t){var e=new Function("y","return function(){return y}");return e(t)}function i(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e,r,a){function l(r){var n=new Function("gl","wrapper","locations","return function(){return gl.getUniform(wrapper.program,locations["+r+"])}");return n(t,e,a)}function u(t,e,r){switch(r){case"bool":case"int":case"sampler2D":case"samplerCube":return"gl.uniform1i(locations["+e+"],obj"+t+")";case"float":return"gl.uniform1f(locations["+e+"],obj"+t+")";default:var n=r.indexOf("vec");if(!(n>=0&&1>=n&&r.length===4+n)){if(0===r.indexOf("mat")&&4===r.length){var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new s("","Unknown uniform data type for "+name+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new s("","Unrecognized data type for vector "+name+": "+r)}}}function c(t,e){if("object"!=typeof e)return[[t,e]];var r=[];for(var n in e){var i=e[n],a=t;a+=parseInt(n)+""===n?"["+n+"]":"."+n,"object"==typeof i?r.push.apply(r,c(a,i)):r.push([a,i])}return r}function f(e){for(var n=["return function updateProperty(obj){"],i=c("",e),o=0;o=0&&1>=e&&t.length===4+e){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid data type");return"b"===t.charAt(0)?i(r,!1):i(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+t);return i(r*r,0)}throw new s("","Unknown uniform data type for "+name+": "+t)}}function p(t,e,i){if("object"==typeof i){var o=d(i);Object.defineProperty(t,e,{get:n(o),set:f(i),enumerable:!0,configurable:!1})}else a[i]?Object.defineProperty(t,e,{get:l(i),set:f(i),enumerable:!0,configurable:!1}):t[e]=h(r[i].type)}function d(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;ua;++a){var o=t.getActiveUniform(e,a);if(o){var s=n(t,o.type);if(o.size>1)for(var l=0;la;++a){var o=t.getActiveAttrib(e,a);o&&i.push({name:o.name,type:n(t,o.type)})}return i}r.uniforms=i,r.attributes=a;var o={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube"},s=null},{}],100:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.id=t,this.src=e,this.type=r,this.shader=n,this.count=a,this.programs=[],this.cache=o}function i(t){this.gl=t,this.shaders=[{},{}],this.programs={}}function a(t,e,r){var n=t.createShader(e);if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){var i=t.getShaderInfoLog(n);try{var a=f(i,r,e)}catch(o){throw console.warn("Failed to format compiler error: "+o),new c(i,"Error compiling shader:\n"+i)}throw new c(i,a.short,a.long)}return n}function o(t,e,r,n,i){var a=t.createProgram();t.attachShader(a,e),t.attachShader(a,r);for(var o=0;on;++n){var a=t.programs[r[n]];a&&(delete t.programs[n],e.deleteProgram(a))}e.deleteShader(this.shader),delete t.shaders[this.type===e.FRAGMENT_SHADER|0][this.src]}};var g=i.prototype;g.getShaderReference=function(t,e){var r=this.gl,i=this.shaders[t===r.FRAGMENT_SHADER|0],o=i[e];if(o&&r.isShader(o.shader))o.count+=1;else{var s=a(r,t,e);o=i[e]=new n(d++,e,t,s,[],1,this)}return o},g.getProgram=function(t,e,r,n){var i=[t.id,e.id,r.join(":"),n.join(":")].join("@"),a=this.programs[i];return a&&this.gl.isProgram(a)||(this.programs[i]=a=o(this.gl,t.shader,e.shader,r,n),t.programs.push(i),e.programs.push(i)),a}},{"./GLError":95,"gl-format-compiler-error":101,"weakmap-shim":119}],101:[function(t,e,r){function n(t,e,r){"use strict";var n=o(e)||"of unknown name (see npm glsl-shader-name)",l="unknown type";void 0!==r&&(l=r===a.FRAGMENT_SHADER?"fragment":"vertex");for(var u=i("Error compiling %s shader %s:\n",l,n),c=i("%s%s",u,t),f=t.split("\n"),h={},p=0;pa.length&&e>0&&(1&e&&(a+=t),e>>=1);)t+=t;return a.substr(0,r)}var i,a="";e.exports=n},{}],105:[function(t,e,r){e.exports={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34e3:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"}},{}],106:[function(t,e,r){var n=t("./1.0/numbers");e.exports=function(t){return n[t]}},{"./1.0/numbers":105}],107:[function(t,e,r){function n(t){for(var e=Array.isArray(t)?t:i(t),r=0;rF;){switch(e=F,B){case f:F=L();break;case h:F=E();break;case p:F=T();break;case d:F=S();break;case g:F=P();break;case w:F=z();break;case v:F=R();break;case c:F=j();break;case x:F=M();break;case u:F=A()}if(e!==F)switch(W[e]){case"\n":G=0,++q;break;default:++G}}return D+=F,W=W.slice(F),V}function n(t){return U.length&&e(U.join("")),B=_,e("(eof)"),V}function A(){return U=U.length?[]:U,"/"===I&&"*"===O?(H=D+F-1,B=f,I=O,F+1):"/"===I&&"/"===O?(H=D+F-1,B=h,I=O,F+1):"#"===O?(B=p,H=D+F,F):/\s/.test(O)?(B=x,H=D+F,F):(Y=/\d/.test(O),X=/[^\w_]/.test(O),H=D+F,B=Y?g:X?d:c,F)}function M(){return/[^\s]/g.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function T(){return"\r"!==O&&"\n"!==O||"\\"===I?(U.push(O),I=O,F+1):(e(U.join("")),B=u,F)}function E(){return T()}function L(){return"/"===O&&"*"===I?(U.push(O),e(U.join("")),B=u,F+1):(U.push(O),I=O,F+1)}function S(){if("."===I&&/\d/.test(O))return B=v,F;if("/"===I&&"*"===O)return B=f,F;if("/"===I&&"/"===O)return B=h,F;if("."===O&&U.length){for(;C(U););return B=v,F}if(";"===O||")"===O||"("===O){if(U.length)for(;C(U););return e(O),B=u,F+1}var t=2===U.length&&"="!==O;if(/[\w_\d\s]/.test(O)||t){for(;C(U););return B=u,F}return U.push(O),I=O,F+1}function C(t){for(var r,n,i=0;;){if(r=a.indexOf(t.slice(0,t.length+i).join("")),n=a[r],-1===r){if(i--+t.length>0)continue;n=t.slice(0,1).join("")}return e(n),H+=n.length,U=U.slice(n.length),U.length}}function z(){return/[^a-fA-F0-9]/.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function P(){return"."===O?(U.push(O),B=v,I=O,F+1):/[eE]/.test(O)?(U.push(O),B=v,I=O,F+1):"x"===O&&1===U.length&&"0"===U[0]?(B=w,U.push(O),I=O,F+1):/[^\d]/.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function R(){return"f"===O&&(U.push(O),I=O,F+=1),/[eE]/.test(O)?(U.push(O),I=O,F+1):"-"===O&&/[eE]/.test(I)?(U.push(O),I=O,F+1):/[^\d]/.test(O)?(e(U.join("")),B=u,F):(U.push(O),I=O,F+1)}function j(){if(/[^\d\w_]/.test(O)){var t=U.join("");return B=K.indexOf(t)>-1?b:Z.indexOf(t)>-1?y:m,e(U.join("")),B=u,F}return U.push(O),I=O,F+1}var O,I,N,F=0,D=0,B=u,U=[],V=[],q=1,G=0,H=0,Y=!1,X=!1,W="";t=t||{};var Z=o,K=i;return"300 es"===t.version&&(Z=l,K=s),function(t){return V=[],null!==t?r(t.replace?t.replace(/\r\n/g,"\n"):t):n()}}e.exports=n;var i=t("./lib/literals"),a=t("./lib/operators"),o=t("./lib/builtins"),s=t("./lib/literals-300es"),l=t("./lib/builtins-300es"),u=999,c=9999,f=0,h=1,p=2,d=3,g=4,v=5,m=6,y=7,b=8,x=9,_=10,w=11,k=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":111,"./lib/builtins-300es":110,"./lib/literals":113,"./lib/literals-300es":112,"./lib/operators":114}],110:[function(t,e,r){var n=t("./builtins");n=n.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)}),e.exports=n.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"]); -},{"./builtins":111}],111:[function(t,e,r){e.exports=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]},{}],112:[function(t,e,r){var n=t("./literals");e.exports=n.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"])},{"./literals":113}],113:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],114:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],115:[function(t,e,r){function n(t,e){var r=i(e),n=[];return n=n.concat(r(t)),n=n.concat(r(null))}var i=t("./index");e.exports=n},{"./index":109}],116:[function(e,r,n){!function(e){function r(){var t=arguments[0],e=r.cache;return e[t]&&e.hasOwnProperty(t)||(e[t]=r.parse(t)),r.format.call(null,e[t],arguments)}function i(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()}function a(t,e){return Array(e+1).join(t)}var o={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};r.format=function(t,e){var n,s,l,u,c,f,h,p=1,d=t.length,g="",v=[],m=!0,y="";for(s=0;d>s;s++)if(g=i(t[s]),"string"===g)v[v.length]=t[s];else if("array"===g){if(u=t[s],u[2])for(n=e[p],l=0;l=0),u[8]){case"b":n=n.toString(2);break;case"c":n=String.fromCharCode(n);break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,u[6]?parseInt(u[6]):0);break;case"e":n=u[7]?n.toExponential(u[7]):n.toExponential();break;case"f":n=u[7]?parseFloat(n).toFixed(u[7]):parseFloat(n);break;case"g":n=u[7]?parseFloat(n).toPrecision(u[7]):parseFloat(n);break;case"o":n=n.toString(8);break;case"s":n=(n=String(n))&&u[7]?n.substring(0,u[7]):n;break;case"u":n>>>=0;break;case"x":n=n.toString(16);break;case"X":n=n.toString(16).toUpperCase()}o.json.test(u[8])?v[v.length]=n:(!o.number.test(u[8])||m&&!u[3]?y="":(y=m?"+":"-",n=n.toString().replace(o.sign,"")),f=u[4]?"0"===u[4]?"0":u[4].charAt(1):" ",h=u[6]-(y+n).length,c=u[6]&&h>0?a(f,h):"",v[v.length]=u[5]?y+n+c:"0"===f?y+c+n:c+y+n)}return v.join("")},r.cache={},r.parse=function(t){for(var e=t,r=[],n=[],i=0;e;){if(null!==(r=o.text.exec(e)))n[n.length]=r[0];else if(null!==(r=o.modulo.exec(e)))n[n.length]="%";else{if(null===(r=o.placeholder.exec(e)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){i|=1;var a=[],s=r[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a[a.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))a[a.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");a[a.length]=l[1]}r[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n[n.length]=r}e=e.substring(r[0].length)}return n};var s=function(t,e,n){return n=(e||[]).slice(0),n.splice(0,0,t),r.apply(null,n)};"undefined"!=typeof n?(n.sprintf=r,n.vsprintf=s):(e.sprintf=r,e.vsprintf=s,"function"==typeof t&&t.amd&&t(function(){return{sprintf:r,vsprintf:s}}))}("undefined"==typeof window?this:window)},{}],117:[function(t,e,r){function n(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:i(e,t)}}var i=t("./hidden-store.js");e.exports=n},{"./hidden-store.js":118}],118:[function(t,e,r){function n(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}e.exports=n},{}],119:[function(t,e,r){function n(){var t=i();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){t(e).value=r},has:function(e){return"value"in t(e)},"delete":function(e){return delete t(e).value}}}var i=t("./create-store.js");e.exports=n},{"./create-store.js":117}],120:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],121:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],122:[function(t,e,r){(function(e,n){"use strict";function i(t){if(t){var e=t.length||t.byteLength,r=y.log2(e);w[r].push(t)}}function a(t){i(t.buffer)}function o(t){var t=y.nextPow2(t),e=y.log2(t),r=w[e];return r.length>0?r.pop():new ArrayBuffer(t)}function s(t){return new Uint8Array(o(t),0,t)}function l(t){return new Uint16Array(o(2*t),0,t)}function u(t){return new Uint32Array(o(4*t),0,t)}function c(t){return new Int8Array(o(t),0,t)}function f(t){return new Int16Array(o(2*t),0,t)}function h(t){return new Int32Array(o(4*t),0,t)}function p(t){return new Float32Array(o(4*t),0,t)}function d(t){return new Float64Array(o(8*t),0,t)}function g(t){return x?new Uint8ClampedArray(o(t),0,t):s(t)}function v(t){return new DataView(o(t),0,t)}function m(t){t=y.nextPow2(t);var e=y.log2(t),r=k[e];return r.length>0?r.pop():new n(t)}var y=t("bit-twiddle"),b=t("dup");e.__TYPEDARRAY_POOL||(e.__TYPEDARRAY_POOL={UINT8:b([32,0]),UINT16:b([32,0]),UINT32:b([32,0]),INT8:b([32,0]),INT16:b([32,0]),INT32:b([32,0]),FLOAT:b([32,0]),DOUBLE:b([32,0]),DATA:b([32,0]),UINT8C:b([32,0]),BUFFER:b([32,0])});var x="undefined"!=typeof Uint8ClampedArray,_=e.__TYPEDARRAY_POOL;_.UINT8C||(_.UINT8C=b([32,0])),_.BUFFER||(_.BUFFER=b([32,0]));var w=_.DATA,k=_.BUFFER;r.free=function(t){if(n.isBuffer(t))k[y.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|y.log2(e);w[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=a,r.freeArrayBuffer=i,r.freeBuffer=function(t){k[y.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return o(t);switch(e){case"uint8":return s(t);case"uint16":return l(t);case"uint32":return u(t);case"int8":return c(t);case"int16":return f(t);case"int32":return h(t);case"float":case"float32":return p(t);case"double":case"float64":return d(t);case"uint8_clamped":return g(t);case"buffer":return m(t);case"data":case"dataview":return v(t);default:return null}return null},r.mallocArrayBuffer=o,r.mallocUint8=s,r.mallocUint16=l,r.mallocUint32=u,r.mallocInt8=c,r.mallocInt16=f,r.mallocInt32=h,r.mallocFloat32=r.mallocFloat=p,r.mallocFloat64=r.mallocDouble=d,r.mallocUint8Clamped=g,r.mallocDataView=v,r.mallocBuffer=m,r.clearCache=function(){for(var t=0;32>t;++t)_.UINT8[t].length=0,_.UINT16[t].length=0,_.UINT32[t].length=0,_.INT8[t].length=0,_.INT16[t].length=0,_.INT32[t].length=0,_.FLOAT[t].length=0,_.DOUBLE[t].length=0,_.UINT8C[t].length=0,w[t].length=0,k[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":120,buffer:65,dup:121}],123:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}function i(t,e){for(var r=0;3>r;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}function a(t,e,r,n){for(var i=h[n],a=0;a=1},f.isTransparent=function(){return this.opacity<1},f.drawTransparent=f.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||c,i=r.projection=t.projection||c;r.model=t.model||c,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var f=0;3>f;++f)e.lineWidth(this.lineWidth[f]),r.capSize=this.capSize[f]*u,e.drawArrays(e.LINES,this.lineOffset[f],this.lineCount[f]);this.vao.unbind()};var h=function(){for(var t=new Array(3),e=0;3>e;++e){for(var r=[],n=1;2>=n;++n)for(var i=-1;1>=i;i+=2){var a=(n+e)%3,o=[0,0,0];o[a]=i,r.push(o)}t[e]=r}return t}();f.update=function(t){t=t||{},"lineWidth"in t&&(this.lineWidth=t.lineWidth,Array.isArray(this.lineWidth)||(this.lineWidth=[this.lineWidth,this.lineWidth,this.lineWidth])),"capSize"in t&&(this.capSize=t.capSize,Array.isArray(this.capSize)||(this.capSize=[this.capSize,this.capSize,this.capSize])),"opacity"in t&&(this.opacity=t.opacity);var e=t.color||[[0,0,0],[0,0,0],[0,0,0]],r=t.position,n=t.error;if(Array.isArray(e[0])||(e=[e,e,e]),r&&n){var o=[],s=r.length,l=0;this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.lineCount=[0,0,0];for(var u=0;3>u;++u){this.lineOffset[u]=l;t:for(var c=0;s>c;++c){for(var f=r[c],h=0;3>h;++h)if(isNaN(f[h])||!isFinite(f[h]))continue t;var p=n[c],d=e[u];if(Array.isArray(d[0])&&(d=e[c]),3===d.length&&(d=[d[0],d[1],d[2],1]),!isNaN(p[0][u])&&!isNaN(p[1][u])){if(p[0][u]<0){var g=f.slice();g[u]+=p[0][u],o.push(f[0],f[1],f[2],d[0],d[1],d[2],d[3],0,0,0,g[0],g[1],g[2],d[0],d[1],d[2],d[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,d,u)}if(p[1][u]>0){var g=f.slice();g[u]+=p[1][u],o.push(f[0],f[1],f[2],d[0],d[1],d[2],d[3],0,0,0,g[0],g[1],g[2],d[0],d[1],d[2],d[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,d,u)}}}this.lineCount[u]=l-this.lineOffset[u]}this.buffer.update(o)}},f.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":158,"gl-buffer":124,"gl-vao":157}],124:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":127}],125:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],126:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],127:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":125,buffer:65,dup:122}],128:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":129,"./lib/create-attributes":130,"./lib/create-uniforms":131,"./lib/reflect":132,"./lib/runtime-reflect":133,"./lib/shader-cache":134,dup:94}],129:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],130:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":129,dup:96}],131:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":129,"./reflect":132,dup:97}],132:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],133:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],134:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":129,dup:100,"gl-format-compiler-error":135,"weakmap-shim":153}],135:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":136,dup:101,"gl-constants/lookup":140,"glsl-shader-name":141,"sprintf-js":150}],136:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":137}],137:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":138}],138:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],139:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],140:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":139,dup:106}],141:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":142,dup:107,"glsl-tokenizer":149}],142:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],143:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":145,"./lib/builtins-300es":144,"./lib/literals":147,"./lib/literals-300es":146,"./lib/operators":148,dup:109}],144:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":145,dup:110}],145:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],146:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":147,dup:112}],147:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],148:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],149:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":143,dup:115}],150:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],151:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":152,dup:117}],152:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],153:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":151,dup:119}],154:[function(t,e,r){"use strict";function n(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;ii;++i)t.disableVertexAttribArray(i)}else{t.bindBuffer(t.ARRAY_BUFFER,null);for(var i=0;n>i;++i)t.disableVertexAttribArray(i)}}e.exports=n},{}],155:[function(t,e,r){"use strict";function n(t){this.gl=t,this._elements=null,this._attributes=null,this._elementsType=t.UNSIGNED_SHORT}function i(t){return new n(t)}var a=t("./do-bind.js");n.prototype.bind=function(){a(this.gl,this._elements,this._attributes)},n.prototype.update=function(t,e,r){this._elements=e,this._attributes=t,this._elementsType=r||this.gl.UNSIGNED_SHORT},n.prototype.dispose=function(){},n.prototype.unbind=function(){},n.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._elements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=i},{"./do-bind.js":154}],156:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.location=t,this.dimension=e,this.a=r,this.b=n,this.c=i,this.d=a}function i(t,e,r){this.gl=t,this._ext=e,this.handle=r,this._attribs=[],this._useElements=!1,this._elementsType=t.UNSIGNED_SHORT}function a(t,e){return new i(t,e,e.createVertexArrayOES())}var o=t("./do-bind.js");n.prototype.bind=function(t){switch(this.dimension){case 1:t.vertexAttrib1f(this.location,this.a);break;case 2:t.vertexAttrib2f(this.location,this.a,this.b);break;case 3:t.vertexAttrib3f(this.location,this.a,this.b,this.c);break;case 4:t.vertexAttrib4f(this.location,this.a,this.b,this.c,this.d)}},i.prototype.bind=function(){this._ext.bindVertexArrayOES(this.handle);for(var t=0;t2&&!this.usingDashes){var C=this.mitreShader;C.bind();var z=C.uniforms;z.matrix=t,z.color=s,z.screenShape=e,z.radius=l*d,C.attributes.p.pointer(f.FLOAT,!1,48,0),f.drawArrays(f.POINTS,0,c/3|0)}}}}(),h.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0],r=[0,0,0,0];return function(n){var i=this.plot,a=this.pickShader,o=this.lineBuffer,s=this.pickBuffer,l=this.width,u=this.numPoints,c=this.bounds,f=this.vertCount,h=i.gl,p=i.viewBox,d=i.dataBox,g=i.pickPixelRatio,v=c[2]-c[0],m=c[3]-c[1],y=d[2]-d[0],b=d[3]-d[1],x=p[2]-p[0],_=p[3]-p[1];if(this.pickOffset=n,!f)return n+u;t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(c[0]-d[0])/y-1,t[7]=2*(c[1]-d[1])/b-1,e[0]=x,e[1]=_,r[0]=255&n,r[1]=n>>>8&255,r[2]=n>>>16&255,r[3]=n>>>24,a.bind();var w=a.uniforms;w.matrix=t,w.width=l*g,w.pickOffset=r,w.screenShape=e;var k=a.attributes;return o.bind(),k.a.pointer(h.FLOAT,!1,16,0),k.d.pointer(h.FLOAT,!1,16,8),s.bind(),k.pick0.pointer(h.UNSIGNED_BYTE,!1,8,0),k.pick1.pointer(h.UNSIGNED_BYTE,!1,8,4),h.drawArrays(h.TRIANGLES,0,f),n+u}}(),h.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.data;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},h.update=function(t){t=t||{};var e=this.plot.gl;!!t.connectGaps;this.color=(t.color||[0,0,1,1]).slice(),this.width=+(t.width||1),this.fill=(t.fill||[!1,!1,!1,!1]).slice(),this.fillColor=i(t.fillColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);for(var r=t.dashes||[1],n=0,a=0;a1,this.dashPattern=l(e,u(o,[n,1,4],[1,0,0])),this.dashPattern.minFilter=e.NEAREST,this.dashPattern.magFilter=e.NEAREST,this.dashLength=n,c.free(o);var p=t.positions;this.data=p;var d=this.bounds;d[0]=d[1]=1/0,d[2]=d[3]=-(1/0);var g=this.numPoints=p.length>>>1;if(0!==g){for(var a=0;g>a;++a){var v=p[2*a],m=p[2*a+1];isNaN(v)||isNaN(m)||(d[0]=Math.min(d[0],v),d[1]=Math.min(d[1],m),d[2]=Math.max(d[2],v),d[3]=Math.max(d[3],m))}d[0]===d[2]&&(d[2]+=1),d[3]===d[1]&&(d[3]+=1);for(var y=c.mallocFloat32(24*(g-1)),b=c.mallocUint32(12*(g-1)),x=y.length,_=b.length,s=g,w=0;s>1;){var k=--s,v=p[2*s],m=p[2*s+1],A=k-1,M=p[2*A],T=p[2*A+1];if(!(isNaN(v)||isNaN(m)||isNaN(M)||isNaN(T))){w+=1,v=(v-d[0])/(d[2]-d[0]),m=(m-d[1])/(d[3]-d[1]),M=(M-d[0])/(d[2]-d[0]),T=(T-d[1])/(d[3]-d[1]);var E=M-v,L=T-m,S=k|1<<24,C=k-1,z=k,P=k-1|1<<24;y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C}}this.vertCount=6*w,this.lineBuffer.update(y.subarray(x)),this.pickBuffer.update(b.subarray(_)),c.free(y),c.free(b)}},h.dispose=function(){this.plot.removeObject(this),this.lineBuffer.dispose(),this.pickBuffer.dispose(),this.lineShader.dispose(),this.mitreShader.dispose(),this.fillShader.dispose(),this.pickShader.dispose(),this.dashPattern.dispose()}},{"./lib/shaders":159,"gl-buffer":161,"gl-shader":162,"gl-texture2d":188,ndarray:1031,"typedarray-pool":191}],161:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":191}],162:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":163,"./lib/create-attributes":164,"./lib/create-uniforms":165,"./lib/reflect":166,"./lib/runtime-reflect":167,"./lib/shader-cache":168,dup:94}],163:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],164:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":163,dup:96}],165:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":163,"./reflect":166,dup:97}],166:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],167:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],168:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":163,dup:100,"gl-format-compiler-error":169,"weakmap-shim":187}],169:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":170,dup:101,"gl-constants/lookup":174,"glsl-shader-name":175,"sprintf-js":184}],170:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":171}],171:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":172}],172:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],173:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],174:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":173,dup:106}],175:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":176,dup:107,"glsl-tokenizer":183}],176:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],177:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":179,"./lib/builtins-300es":178,"./lib/literals":181,"./lib/literals-300es":180,"./lib/operators":182,dup:109}],178:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":179,dup:110}],179:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],180:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":181,dup:112}],181:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],182:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],183:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":177,dup:115}],184:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],185:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":186,dup:117}],186:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],187:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":185,dup:119}],188:[function(t,e,r){"use strict";function n(t){v=[t.LINEAR,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_NEAREST],m=[t.NEAREST,t.LINEAR,t.NEAREST_MIPMAP_NEAREST,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_LINEAR],y=[t.REPEAT,t.CLAMP_TO_EDGE,t.MIRRORED_REPEAT]}function i(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(0>e||e>i||0>r||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function a(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}function o(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function s(t,e,r,n,i,a,s,l){var u=l.dtype,c=l.shape.slice();if(c.length<2||c.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var f=0,h=0,v=o(c,l.stride.slice());"float32"===u?f=t.FLOAT:"float64"===u?(f=t.FLOAT,v=!1,u="float32"):"uint8"===u?f=t.UNSIGNED_BYTE:(f=t.UNSIGNED_BYTE,v=!1,u="uint8");var m=1;if(2===c.length)h=t.LUMINANCE,c=[c[0],c[1],1],l=p(l.data,c,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==c.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===c[2])h=t.ALPHA;else if(2===c[2])h=t.LUMINANCE_ALPHA;else if(3===c[2])h=t.RGB;else{if(4!==c[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}m=c[2]}if(h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i),h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=l.size,x=s.indexOf(n)<0;if(x&&s.push(n),f===a&&v)0===l.offset&&l.data.length===y?x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,l.data):x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,l.data.subarray(l.offset,l.offset+y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,l.data.subarray(l.offset,l.offset+y));else{var _;_=a===t.FLOAT?g.mallocFloat32(y):g.mallocUint8(y);var w=p(_,c,[c[2],c[2]*c[0],1]);f===t.FLOAT&&a===t.UNSIGNED_BYTE?b(w,l):d.assign(w,l),x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,_.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,_.subarray(0,y)),a===t.FLOAT?g.freeFloat32(_):g.freeUint8(_)}}function l(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function u(t,e,r,n,i){var o=t.getParameter(t.MAX_TEXTURE_SIZE);if(0>e||e>o||0>r||r>o)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var s=l(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new a(t,s,e,r,n,i)}function c(t,e,r,n){var i=l(t);return t.texImage2D(t.TEXTURE_2D,0,r,r,n,e),new a(t,i,0|e.width,0|e.height,r,n)}function f(t,e){var r=e.dtype,n=e.shape.slice(),i=t.getParameter(t.MAX_TEXTURE_SIZE);if(n[0]<0||n[0]>i||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var s=o(n,e.stride.slice()),u=0;"float32"===r?u=t.FLOAT:"float64"===r?(u=t.FLOAT,s=!1,r="float32"):"uint8"===r?u=t.UNSIGNED_BYTE:(u=t.UNSIGNED_BYTE,s=!1,r="uint8");var c=0;if(2===n.length)c=t.LUMINANCE,n=[n[0],n[1],1],e=p(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])c=t.ALPHA;else if(2===n[2])c=t.LUMINANCE_ALPHA;else if(3===n[2])c=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");c=t.RGBA}}u!==t.FLOAT||t.getExtension("OES_texture_float")||(u=t.UNSIGNED_BYTE,s=!1);var f,h,v=e.size;if(s)f=0===e.offset&&e.data.length===v?e.data:e.data.subarray(e.offset,e.offset+v);else{var m=[n[2],n[2]*n[0],1];h=g.malloc(v,r);var y=p(h,n,m,0);"float32"!==r&&"float64"!==r||u!==t.UNSIGNED_BYTE?d.assign(y,e):b(y,e),f=h.subarray(0,v)}var x=l(t);return t.texImage2D(t.TEXTURE_2D,0,c,n[0],n[1],0,c,u,f),s||g.free(h),new a(t,x,n[0],n[1],c,u)}function h(t){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(v||n(t),"number"==typeof arguments[1])return u(t,arguments[1],arguments[2],arguments[3]||t.RGBA,arguments[4]||t.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return u(t,0|arguments[1][0],0|arguments[1][1],arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if("object"==typeof arguments[1]){var e=arguments[1];if(e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e instanceof ImageData)return c(t,e,arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return f(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}var p=t("ndarray"),d=t("ndarray-ops"),g=t("typedarray-pool");e.exports=h;var v=null,m=null,y=null,b=function(t,e){d.muls(t,e,255)},x=a.prototype;Object.defineProperties(x,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;2>e;++e)if(y.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return i(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return t=0|t,i(this,t,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t=0|t,i(this,this._shape[0],t),t}}}),x.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},x.dispose=function(){this.gl.deleteTexture(this.handle)},x.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},x.setPixels=function(t,e,r,n){var i=this.gl;if(this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0,t instanceof HTMLCanvasElement||t instanceof ImageData||t instanceof HTMLImageElement||t instanceof HTMLVideoElement){var a=this._mipLevels.indexOf(n)<0;a?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,t),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,t)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||0>e||0>r)throw new Error("gl-texture2d: Texture dimensions are out of bounds");s(i,e,r,n,this.format,this.type,this._mipLevels,t)}}},{ndarray:1031,"ndarray-ops":1026,"typedarray-pool":191}],189:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],190:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],191:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":189,buffer:65,dup:122}],192:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}",s=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return n(t,i,a,null,s)},r.createPickShader=function(t){return n(t,i,o,null,s)}},{"gl-shader":199}],193:[function(t,e,r){"use strict";function n(t,e){for(var r=0,n=0;3>n;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function i(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;3>r;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function a(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function o(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}function s(t){var e=t.gl||t.scene&&t.scene.gl,r=g(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=v(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=l(e),a=u(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),s=p(new Array(1024),[256,1,4]),f=0;1024>f;++f)s.data[f]=255;var h=c(e,s);h.wrap=e.REPEAT;var d=new o(e,r,n,i,a,h);return d.update(t),d}e.exports=s;var l=t("gl-buffer"),u=t("gl-vao"),c=t("gl-texture2d"),f=t("glsl-read-float"),h=t("binary-search-bounds"),p=t("ndarray"),d=t("./lib/shaders"),g=d.createShader,v=d.createPickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],y=o.prototype;y.isTransparent=function(){return this.opacity<1},y.isOpaque=function(){return this.opacity>=1},y.pickSlots=1,y.setPickBase=function(t){this.pickId=t},y.drawTransparent=y.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,clipBounds:i(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,pickId:this.pickId,clipBounds:i(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.update=function(t){var e,r;this.dirty=!0;var i=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var a=t.position||t.positions;if(a){var o=t.color||t.colors||[0,0,0,1],s=t.lineWidth||1,l=[],u=[],c=[],f=0,d=0,g=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],v=!1;t:for(e=1;er;++r){if(isNaN(m[r])||isNaN(y[r])||!isFinite(m[r])||!isFinite(y[r])){if(!i&&l.length>0){for(var b=0;24>b;++b)l.push(l[l.length-12]);d+=2,v=!0}continue t}g[0][r]=Math.min(g[0][r],m[r],y[r]),g[1][r]=Math.max(g[1][r],m[r],y[r])}var x,_;Array.isArray(o[0])?(x=o[e-1],_=o[e]):x=_=o,3===x.length&&(x=[x[0],x[1],x[2],1]),3===_.length&&(_=[_[0],_[1],_[2],1]);var w;w=Array.isArray(s)?s[e-1]:s;var k=f;if(f+=n(m,y),v){for(r=0;2>r;++r)l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3]);d+=2,v=!1}l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3],m[0],m[1],m[2],y[0],y[1],y[2],k,-w,x[0],x[1],x[2],x[3],y[0],y[1],y[2],m[0],m[1],m[2],f,-w,_[0],_[1],_[2],_[3],y[0],y[1],y[2],m[0],m[1],m[2],f,w,_[0],_[1],_[2],_[3]),d+=4}if(this.buffer.update(l),u.push(f),c.push(a[a.length-1].slice()),this.bounds=g,this.vertexCount=d,this.points=c,this.arcLength=u,"dashes"in t){var A=t.dashes,M=A.slice();for(M.unshift(0),e=1;ee;++e){for(r=0;4>r;++r)T.set(e,0,r,0);1&h.le(M,M[M.length-1]*e/255)?T.set(e,0,0,0):T.set(e,0,0,255)}this.texture.setPixels(T)}}},y.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},y.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=f(t.value[0],t.value[1],t.value[2],0),r=h.le(this.arcLength,e);if(0>r)return null;if(r===this.arcLength.length-1)return new a(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],o=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),s=1-o,l=[0,0,0],u=0;3>u;++u)l[u]=s*n[u]+o*i[u];var c=Math.min(.5>o?r:r+1,this.points.length-1);return new a(e,l,c,this.points[c])}},{"./lib/shaders":192,"binary-search-bounds":194,"gl-buffer":195,"gl-texture2d":228,"gl-vao":232,"glsl-read-float":233,ndarray:1031}],194:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],195:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":198}],196:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],197:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],198:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":196,buffer:65,dup:122}],199:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":200,"./lib/create-attributes":201,"./lib/create-uniforms":202,"./lib/reflect":203,"./lib/runtime-reflect":204,"./lib/shader-cache":205,dup:94}],200:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],201:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":200,dup:96}],202:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":200,"./reflect":203,dup:97}],203:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],204:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],205:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":200,dup:100,"gl-format-compiler-error":206,"weakmap-shim":224}],206:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":207,dup:101,"gl-constants/lookup":211,"glsl-shader-name":212,"sprintf-js":221}],207:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":208}],208:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":209}],209:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],210:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],211:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":210,dup:106}],212:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":213,dup:107,"glsl-tokenizer":220}],213:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],214:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":216,"./lib/builtins-300es":215,"./lib/literals":218,"./lib/literals-300es":217,"./lib/operators":219,dup:109}],215:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":216,dup:110}],216:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],217:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":218,dup:112}],218:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],219:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],220:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":214,dup:115}],221:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],222:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":223,dup:117}],223:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],224:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":222,dup:119}],225:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],226:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],227:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":225,buffer:65,dup:122}],228:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":227}],229:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],230:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":229,dup:155}],231:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":229,dup:156}],232:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":230,"./lib/vao-native.js":231,dup:157}],233:[function(t,e,r){function n(t,e,r,n){return i[0]=n,i[1]=r,i[2]=e,i[3]=t,a[0]}e.exports=n;var i=new Uint8Array(4),a=new Float32Array(i.buffer)},{}],234:[function(t,e,r){function n(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}e.exports=n},{}],235:[function(t,e,r){function n(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],236:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],f=t[10],h=t[11],p=t[12],d=t[13],g=t[14],v=t[15],m=e*o-r*a,y=e*s-n*a,b=e*l-i*a,x=r*s-n*o,_=r*l-i*o,w=n*l-i*s,k=u*d-c*p,A=u*g-f*p,M=u*v-h*p,T=c*g-f*d,E=c*v-h*d,L=f*v-h*g;return m*L-y*E+b*T+x*M-_*A+w*k}e.exports=n},{}],237:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,u=r*o,c=n*o,f=n*s,h=i*o,p=i*s,d=i*l,g=a*o,v=a*s,m=a*l;return t[0]=1-f-d,t[1]=c+m,t[2]=h-v,t[3]=0,t[4]=c-m,t[5]=1-u-d,t[6]=p+g,t[7]=0,t[8]=h+v,t[9]=p-g,t[10]=1-u-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],238:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,f=n*l,h=n*u,p=i*l,d=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(p+g),t[1]=f+y,t[2]=h-m,t[3]=0,t[4]=f-y,t[5]=1-(c+g),t[6]=d+v,t[7]=0,t[8]=h+m,t[9]=d-v,t[10]=1-(c+p),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}e.exports=n},{}],239:[function(t,e,r){function n(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],240:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],u=e[7],c=e[8],f=e[9],h=e[10],p=e[11],d=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*u-a*o,_=n*l-i*s,w=n*u-a*s,k=i*u-a*l,A=c*g-f*d,M=c*v-h*d,T=c*m-p*d,E=f*v-h*g,L=f*m-p*g,S=h*m-p*v,C=y*S-b*L+x*E+_*T-w*M+k*A;return C?(C=1/C,t[0]=(s*S-l*L+u*E)*C,t[1]=(i*L-n*S-a*E)*C,t[2]=(g*k-v*w+m*_)*C,t[3]=(h*w-f*k-p*_)*C,t[4]=(l*T-o*S-u*M)*C,t[5]=(r*S-i*T+a*M)*C,t[6]=(v*x-d*k-m*b)*C,t[7]=(c*k-h*x+p*b)*C,t[8]=(o*L-s*T+u*A)*C,t[9]=(n*T-r*L-a*A)*C,t[10]=(d*w-g*x+m*y)*C,t[11]=(f*x-c*w-p*y)*C,t[12]=(s*M-o*E-l*A)*C,t[13]=(r*E-n*M+i*A)*C,t[14]=(g*b-d*_-v*y)*C,t[15]=(c*_-f*b+h*y)*C,t):null}e.exports=n},{}],241:[function(t,e,r){function n(t,e,r,n){var a,o,s,l,u,c,f,h,p,d,g=e[0],v=e[1],m=e[2],y=n[0],b=n[1],x=n[2],_=r[0],w=r[1],k=r[2];return Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6&&Math.abs(m-k)<1e-6?i(t):(f=g-_,h=v-w,p=m-k,d=1/Math.sqrt(f*f+h*h+p*p),f*=d,h*=d,p*=d,a=b*p-x*h,o=x*f-y*p,s=y*h-b*f,d=Math.sqrt(a*a+o*o+s*s),d?(d=1/d,a*=d,o*=d,s*=d):(a=0,o=0,s=0),l=h*s-p*o,u=p*a-f*s,c=f*o-h*a,d=Math.sqrt(l*l+u*u+c*c),d?(d=1/d,l*=d,u*=d,c*=d):(l=0,u=0,c=0),t[0]=a,t[1]=l,t[2]=f,t[3]=0,t[4]=o,t[5]=u,t[6]=h,t[7]=0,t[8]=s,t[9]=c,t[10]=p,t[11]=0,t[12]=-(a*g+o*v+s*m),t[13]=-(l*g+u*v+c*m),t[14]=-(f*g+h*v+p*m),t[15]=1,t)}var i=t("./identity");e.exports=n},{"./identity":239}],242:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],f=e[8],h=e[9],p=e[10],d=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*f+w*g,t[1]=b*i+x*l+_*h+w*v,t[2]=b*a+x*u+_*p+w*m,t[3]=b*o+x*c+_*d+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*f+w*g,t[5]=b*i+x*l+_*h+w*v,t[6]=b*a+x*u+_*p+w*m,t[7]=b*o+x*c+_*d+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*f+w*g,t[9]=b*i+x*l+_*h+w*v,t[10]=b*a+x*u+_*p+w*m,t[11]=b*o+x*c+_*d+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*f+w*g,t[13]=b*i+x*l+_*h+w*v,t[14]=b*a+x*u+_*p+w*m,t[15]=b*o+x*c+_*d+w*y,t}e.exports=n},{}],243:[function(t,e,r){function n(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t}e.exports=n},{}],244:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,u,c,f,h,p,d,g,v,m,y,b,x,_,w,k,A,M,T,E,L=n[0],S=n[1],C=n[2],z=Math.sqrt(L*L+S*S+C*C);return Math.abs(z)<1e-6?null:(z=1/z,L*=z,S*=z,C*=z,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],f=e[4],h=e[5],p=e[6],d=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=S*L*o+C*i,_=C*L*o-S*i,w=L*S*o-C*i,k=S*S*o+a,A=C*S*o+L*i,M=L*C*o+S*i,T=S*C*o-L*i,E=C*C*o+a,t[0]=s*b+f*x+g*_,t[1]=l*b+h*x+v*_,t[2]=u*b+p*x+m*_,t[3]=c*b+d*x+y*_,t[4]=s*w+f*k+g*A,t[5]=l*w+h*k+v*A,t[6]=u*w+p*k+m*A,t[7]=c*w+d*k+y*A,t[8]=s*M+f*T+g*E,t[9]=l*M+h*T+v*E,t[10]=u*M+p*T+m*E, -t[11]=c*M+d*T+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}e.exports=n},{}],245:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],u=e[8],c=e[9],f=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+u*n,t[5]=o*i+c*n,t[6]=s*i+f*n,t[7]=l*i+h*n,t[8]=u*i-a*n,t[9]=c*i-o*n,t[10]=f*i-s*n,t[11]=h*i-l*n,t}e.exports=n},{}],246:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[8],c=e[9],f=e[10],h=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-u*n,t[1]=o*i-c*n,t[2]=s*i-f*n,t[3]=l*i-h*n,t[8]=a*n+u*i,t[9]=o*n+c*i,t[10]=s*n+f*i,t[11]=l*n+h*i,t}e.exports=n},{}],247:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[4],c=e[5],f=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+u*n,t[1]=o*i+c*n,t[2]=s*i+f*n,t[3]=l*i+h*n,t[4]=u*i-a*n,t[5]=c*i-o*n,t[6]=f*i-s*n,t[7]=h*i-l*n,t}e.exports=n},{}],248:[function(t,e,r){function n(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}e.exports=n},{}],249:[function(t,e,r){function n(t,e,r){var n,i,a,o,s,l,u,c,f,h,p,d,g=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],f=e[8],h=e[9],p=e[10],d=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=u,t[7]=c,t[8]=f,t[9]=h,t[10]=p,t[11]=d,t[12]=n*g+s*v+f*m+e[12],t[13]=i*g+l*v+h*m+e[13],t[14]=a*g+u*v+p*m+e[14],t[15]=o*g+c*v+d*m+e[15]),t}e.exports=n},{}],250:[function(t,e,r){function n(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}e.exports=n},{}],251:[function(t,e,r){"use strict";function n(t,e){for(var r=[0,0,0,0],n=0;4>n;++n)for(var i=0;4>i;++i)r[i]+=t[4*n+i]*e[n];return r}function i(t,e,r,i,a){for(var o=n(i,n(r,n(e,[t[0],t[1],t[2],1]))),s=0;3>s;++s)o[s]/=o[3];return[.5*a[0]*(1+o[0]),.5*a[1]*(1-o[1])]}function a(t,e){if(2===t.length){for(var r=0,n=0,i=0;2>i;++i)r+=Math.pow(e[i]-t[0][i],2),n+=Math.pow(e[i]-t[1][i],2);return r=Math.sqrt(r),n=Math.sqrt(n),1e-6>r+n?[1,0]:[n/(r+n),r/(n+r)]}if(3===t.length){var a=[0,0];return u(t[0],t[1],t[2],e,a),l(t,a)}return[]}function o(t,e){for(var r=[0,0,0],n=0;no;++o)r[o]+=a*i[o];return r}function s(t,e,r,n,s,l){if(1===t.length)return[0,t[0].slice()];for(var u=new Array(t.length),c=0;cd;++d)p+=Math.pow(u[c][d]-e[d],2);h>p&&(h=p,f=c)}for(var g=a(u,e),v=0,c=0;3>c;++c){if(g[c]<-.001||g[c]>1.0001)return null;v+=g[c]}return Math.abs(v-1)>.001?null:[f,o(t,g),g]}var l=t("barycentric"),u=t("polytope-closest-point/lib/closest_point_2d.js");e.exports=s},{barycentric:254,"polytope-closest-point/lib/closest_point_2d.js":298}],252:[function(t,e,r){var n="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}",i="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}",a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",u="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}",c="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}",f="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}",h="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}",p="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n";r.meshShader={vertex:n,fragment:i,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:a,fragment:o,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:s,fragment:l,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:u,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:f,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:h,fragment:p,attributes:[{name:"position",type:"vec3"}]}},{}],253:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,u,c,f,h,p,d,g,v,m,y,b,x,_,w,k,A,M,T){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=c,this.triangleNormals=h,this.triangleUVs=f,this.triangleIds=u,this.triangleVAO=p,this.triangleCount=0,this.lineWidth=1,this.edgePositions=d,this.edgeColors=v,this.edgeUVs=m,this.edgeIds=g,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=b,this.pointColors=_,this.pointUVs=w,this.pointSizes=k,this.pointIds=x,this.pointVAO=A,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=M,this.contourVAO=T,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=O,this._view=O,this._projection=O,this._resolution=[1,1]}function i(t){for(var e=A({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;256>n;++n){for(var i=e[n],a=0;3>a;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return k(r,[256,256,4],[4,0,1])}function a(t,e,r){for(var n=new Array(e),i=0;e>i;++i)n[i]=0;for(var a=t.length,i=0;a>i;++i)for(var o=t[i],s=0;sn;++n)r[n]=t[n][2];return r}function s(t){var e=v(t,S);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.normal.location=4,e}function l(t){var e=v(t,C);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e}function u(t){var e=v(t,z);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function c(t){var e=v(t,P);return e.attributes.position.location=0,e.attributes.id.location=1,e}function f(t){var e=v(t,R);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function h(t){var e=v(t,j);return e.attributes.position.location=0,e}function p(t){var e=t.gl,r=s(e),i=l(e),a=u(e),o=c(e),p=f(e),d=h(e),g=b(e,k(new Uint8Array([255,255,255,255]),[1,1,4]));g.generateMipmap(),g.minFilter=e.LINEAR_MIPMAP_LINEAR,g.magFilter=e.LINEAR;var v=m(e),x=m(e),_=m(e),w=m(e),A=m(e),M=y(e,[{buffer:v,type:e.FLOAT,size:3},{buffer:A,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:x,type:e.FLOAT,size:4},{buffer:_,type:e.FLOAT,size:2},{buffer:w,type:e.FLOAT,size:3}]),T=m(e),E=m(e),L=m(e),S=m(e),C=y(e,[{buffer:T,type:e.FLOAT,size:3},{buffer:S,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:E,type:e.FLOAT,size:4},{buffer:L,type:e.FLOAT,size:2}]),z=m(e),P=m(e),R=m(e),j=m(e),O=m(e),I=y(e,[{buffer:z,type:e.FLOAT,size:3},{buffer:O,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:P,type:e.FLOAT,size:4},{buffer:R,type:e.FLOAT,size:2},{buffer:j,type:e.FLOAT,size:1}]),N=m(e),F=y(e,[{buffer:N,type:e.FLOAT,size:3}]),D=new n(e,g,r,i,a,o,p,d,v,A,x,_,w,M,T,S,E,L,C,z,O,P,R,j,I,N,F);return D.update(t),D}var d=1e-6,g=1e-6,v=t("gl-shader"),m=t("gl-buffer"),y=t("gl-vao"),b=t("gl-texture2d"),x=t("normals"),_=t("gl-mat4/multiply"),w=t("gl-mat4/invert"),k=t("ndarray"),A=t("colormap"),M=t("simplicial-complex-contour"),T=t("typedarray-pool"),E=t("./lib/shaders"),L=t("./lib/closest-point"),S=E.meshShader,C=E.wireShader,z=E.pointShader,P=E.pickShader,R=E.pointPickShader,j=E.contourShader,O=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],I=n.prototype;I.isOpaque=function(){return this.opacity>=1},I.isTransparent=function(){return this.opacity<1},I.pickSlots=1,I.setPickBase=function(t){this.pickId=t},I.highlight=function(t){if(!t||!this.contourEnable)return void(this.contourCount=0);for(var e=M(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=T.mallocFloat32(6*a),s=0,l=0;a>l;++l)for(var u=r[l],c=0;2>c;++c){var f=u[0];2===u.length&&(f=u[c]);for(var h=n[f][0],p=n[f][1],d=i[f],g=1-d,v=this.positions[h],m=this.positions[p],y=0;3>y;++y)o[s++]=d*v[y]+g*m[y]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),T.free(o)},I.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),t.texture?(this.texture.dispose(),this.texture=b(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(i(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions;if(n&&r){var s=[],l=[],u=[],c=[],f=[],h=[],p=[],v=[],m=[],y=[],_=[],w=[],k=[],A=[];this.cells=r,this.positions=n;var M=t.vertexNormals,T=t.cellNormals,E=void 0===t.vertexNormalsEpsilon?d:t.vertexNormalsEpsilon,L=void 0===t.faceNormalsEpsilon?g:t.faceNormalsEpsilon;t.useFacetNormals&&!T&&(T=x.faceNormals(r,n,L)),T||M||(M=x.vertexNormals(r,n,E));var S=t.vertexColors,C=t.cellColors,z=t.meshColor||[1,1,1,1],P=t.vertexUVs,R=t.vertexIntensity,j=t.cellUVs,O=t.cellIntensity,I=1/0,N=-(1/0);if(!P&&!j)if(R)for(var F=0;Fq;++q)!isNaN(V[q])&&isFinite(V[q])&&(this.bounds[0][q]=Math.min(this.bounds[0][q],V[q]),this.bounds[1][q]=Math.max(this.bounds[1][q],V[q]));var G=0,H=0,Y=0;t:for(var F=0;Fq;++q)if(isNaN(V[q])||!isFinite(V[q]))continue t;y.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?_.push(Z[0],Z[1],Z[2],1):_.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-I)/(N-I),0]:j?j[F]:O?[(O[F]-I)/(N-I),0]:[(V[2]-I)/(N-I),0],w.push(K[0],K[1]),B?k.push(B[W]):k.push(U),A.push(F),Y+=1;break;case 2:for(var q=0;2>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;2>q;++q){var W=X[q],V=n[W];h.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?p.push(Z[0],Z[1],Z[2],1):p.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-I)/(N-I),0]:j?j[F]:O?[(O[F]-I)/(N-I),0]:[(V[2]-I)/(N-I),0],v.push(K[0],K[1]),m.push(F)}H+=1;break;case 3:for(var q=0;3>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;3>q;++q){var W=X[q],V=n[W];s.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?l.push(Z[0],Z[1],Z[2],1):l.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-I)/(N-I),0]:j?j[F]:O?[(O[F]-I)/(N-I),0]:[(V[2]-I)/(N-I),0],c.push(K[0],K[1]);var Q;Q=M?M[W]:T[F],u.push(Q[0],Q[1],Q[2]),f.push(F)}G+=1}}this.pointCount=Y,this.edgeCount=H,this.triangleCount=G,this.pointPositions.update(y),this.pointColors.update(_),this.pointUVs.update(w),this.pointSizes.update(k),this.pointIds.update(new Uint32Array(A)),this.edgePositions.update(h),this.edgeColors.update(p),this.edgeUVs.update(v),this.edgeIds.update(new Uint32Array(m)),this.trianglePositions.update(s),this.triangleColors.update(l),this.triangleUVs.update(c),this.triangleNormals.update(u),this.triangleIds.update(new Uint32Array(f))}},I.drawTransparent=I.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||O,n=t.view||O,i=t.projection||O,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,contourColor:this.contourColor,texture:0};this.texture.bind(0);var l=new Array(16);_(l,s.view,s.model),_(l,s.projection,l),w(l,l);for(var o=0;3>o;++o)s.eyePosition[o]=l[12+o]/l[15];for(var u=l[15],o=0;3>o;++o)u+=this.lightPosition[o]*l[4*o+3];for(var o=0;3>o;++o){for(var c=l[12+o],f=0;3>f;++f)c+=l[4*f+o]*this.lightPosition[f];s.lightPosition[o]=c/u}if(this.triangleCount>0){var h=this.triShader;h.bind(),h.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}if(this.edgeCount>0&&this.lineWidth>0){var h=this.lineShader;h.bind(),h.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()}if(this.pointCount>0){var h=this.pointShader;h.bind(),h.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}if(this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0){var h=this.contourShader;h.bind(),h.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind()}},I.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||O,n=t.view||O,i=t.projection||O,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255},l=this.pickShader;if(l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0){var l=this.pointPickShader;l.bind(),l.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}},I.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;ao;++o){for(var s=new Array(r+1),l=0;r>=l;++l)s[l]=t[l][o];i[o]=s}i[r]=new Array(r+1);for(var o=0;r>=o;++o)i[r][o]=1;for(var u=new Array(r+1),o=0;r>o;++o)u[o]=e[o];u[r]=1;var c=a(i,u),f=n(c[r+1]);0===f&&(f=1);for(var h=new Array(r+1),o=0;r>=o;++o)h[o]=n(c[o])/f;return h}e.exports=i;var a=t("robust-linear-solve")},{"robust-linear-solve":255}],255:[function(t,e,r){arguments[4][51][0].apply(r,arguments)},{dup:51,"robust-determinant":261}],256:[function(t,e,r){arguments[4][52][0].apply(r,arguments)},{dup:52}],257:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],258:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":260,"two-sum":257}],259:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],260:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],261:[function(t,e,r){arguments[4][57][0].apply(r,arguments)},{dup:57,"robust-compress":256,"robust-scale":258,"robust-sum":259,"two-product":260}],262:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:0,rgb:[255,255,255,1]}],viridis:[{index:0,rgb:[68,1,84]},{index:.13,rgb:[71,44,122]},{index:.25,rgb:[59,81,139]},{index:.38,rgb:[44,113,142]},{index:.5,rgb:[33,144,141]},{index:.63,rgb:[39,173,129]},{index:.75,rgb:[92,200,99]},{index:.88,rgb:[170,220,50]},{index:1,rgb:[253,231,37]}],inferno:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[31,12,72]},{index:.25,rgb:[85,15,109]},{index:.38,rgb:[136,34,106]},{index:.5,rgb:[186,54,85]},{index:.63,rgb:[227,89,51]},{index:.75,rgb:[249,140,10]},{index:.88,rgb:[249,201,50]},{index:1,rgb:[252,255,164]}],magma:[{index:0,rgb:[0,0,4]},{index:.13,rgb:[28,16,68]},{index:.25,rgb:[79,18,123]},{index:.38,rgb:[129,37,129]},{index:.5,rgb:[181,54,122]},{index:.63,rgb:[229,80,100]},{index:.75,rgb:[251,135,97]},{index:.88,rgb:[254,194,135]},{index:1,rgb:[252,253,191]}],plasma:[{index:0,rgb:[13,8,135]},{index:.13,rgb:[75,3,161]},{index:.25,rgb:[125,3,168]},{index:.38,rgb:[168,34,150]},{index:.5,rgb:[203,70,121]},{index:.63,rgb:[229,107,93]},{index:.75,rgb:[248,148,65]},{index:.88,rgb:[253,195,40]},{index:1,rgb:[240,249,33]}],warm:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[172,0,187]},{index:.25,rgb:[219,0,170]},{index:.38,rgb:[255,0,130]},{index:.5,rgb:[255,63,74]},{index:.63,rgb:[255,123,0]},{index:.75,rgb:[234,176,0]},{index:.88,rgb:[190,228,0]},{index:1,rgb:[147,255,0]}],cool:[{index:0,rgb:[125,0,179]},{index:.13,rgb:[116,0,218]},{index:.25,rgb:[98,74,237]},{index:.38,rgb:[68,146,231]},{index:.5,rgb:[0,204,197]},{index:.63,rgb:[0,247,146]},{index:.75,rgb:[0,255,88]},{index:.88,rgb:[40,255,8]},{index:1,rgb:[147,255,0]}],"rainbow-soft":[{index:0,rgb:[125,0,179]},{index:.1,rgb:[199,0,180]},{index:.2,rgb:[255,0,121]},{index:.3,rgb:[255,108,0]},{index:.4,rgb:[222,194,0]},{index:.5,rgb:[150,255,0]},{index:.6,rgb:[0,255,55]},{index:.7,rgb:[0,246,150]},{index:.8,rgb:[50,167,222]},{index:.9,rgb:[103,51,235]},{index:1,rgb:[124,0,186]}],bathymetry:[{index:0,rgb:[40,26,44]},{index:.13,rgb:[59,49,90]},{index:.25,rgb:[64,76,139]},{index:.38,rgb:[63,110,151]},{index:.5,rgb:[72,142,158]},{index:.63,rgb:[85,174,163]},{index:.75,rgb:[120,206,163]},{index:.88,rgb:[187,230,172]},{index:1,rgb:[253,254,204]}],cdom:[{index:0,rgb:[47,15,62]},{index:.13,rgb:[87,23,86]},{index:.25,rgb:[130,28,99]},{index:.38,rgb:[171,41,96]},{index:.5,rgb:[206,67,86]},{index:.63,rgb:[230,106,84]},{index:.75,rgb:[242,149,103]},{index:.88,rgb:[249,193,135]},{index:1,rgb:[254,237,176]}],chlorophyll:[{index:0,rgb:[18,36,20]},{index:.13,rgb:[25,63,41]},{index:.25,rgb:[24,91,59]},{index:.38,rgb:[13,119,72]},{index:.5,rgb:[18,148,80]},{index:.63,rgb:[80,173,89]},{index:.75,rgb:[132,196,122]},{index:.88,rgb:[175,221,162]},{index:1,rgb:[215,249,208]}],density:[{index:0,rgb:[54,14,36]},{index:.13,rgb:[89,23,80]},{index:.25,rgb:[110,45,132]},{index:.38,rgb:[120,77,178]},{index:.5,rgb:[120,113,213]},{index:.63,rgb:[115,151,228]},{index:.75,rgb:[134,185,227]},{index:.88,rgb:[177,214,227]},{index:1,rgb:[230,241,241]}],"freesurface-blue":[{index:0,rgb:[30,4,110]},{index:.13,rgb:[47,14,176]},{index:.25,rgb:[41,45,236]},{index:.38,rgb:[25,99,212]},{index:.5,rgb:[68,131,200]},{index:.63,rgb:[114,156,197]},{index:.75,rgb:[157,181,203]},{index:.88,rgb:[200,208,216]},{index:1,rgb:[241,237,236]}],"freesurface-red":[{index:0,rgb:[60,9,18]},{index:.13,rgb:[100,17,27]},{index:.25,rgb:[142,20,29]},{index:.38,rgb:[177,43,27]},{index:.5,rgb:[192,87,63]},{index:.63,rgb:[205,125,105]},{index:.75,rgb:[216,162,148]},{index:.88,rgb:[227,199,193]},{index:1,rgb:[241,237,236]}],oxygen:[{index:0,rgb:[64,5,5]},{index:.13,rgb:[106,6,15]},{index:.25,rgb:[144,26,7]},{index:.38,rgb:[168,64,3]},{index:.5,rgb:[188,100,4]},{index:.63,rgb:[206,136,11]},{index:.75,rgb:[220,174,25]},{index:.88,rgb:[231,215,44]},{index:1,rgb:[248,254,105]}],par:[{index:0,rgb:[51,20,24]},{index:.13,rgb:[90,32,35]},{index:.25,rgb:[129,44,34]},{index:.38,rgb:[159,68,25]},{index:.5,rgb:[182,99,19]},{index:.63,rgb:[199,134,22]},{index:.75,rgb:[212,171,35]},{index:.88,rgb:[221,210,54]},{index:1,rgb:[225,253,75]}],phase:[{index:0,rgb:[145,105,18]},{index:.13,rgb:[184,71,38]},{index:.25,rgb:[186,58,115]},{index:.38,rgb:[160,71,185]},{index:.5,rgb:[110,97,218]},{index:.63,rgb:[50,123,164]},{index:.75,rgb:[31,131,110]},{index:.88,rgb:[77,129,34]},{index:1,rgb:[145,105,18]}],salinity:[{index:0,rgb:[42,24,108]},{index:.13,rgb:[33,50,162]},{index:.25,rgb:[15,90,145]},{index:.38,rgb:[40,118,137]},{index:.5,rgb:[59,146,135]},{index:.63,rgb:[79,175,126]},{index:.75,rgb:[120,203,104]},{index:.88,rgb:[193,221,100]},{index:1,rgb:[253,239,154]}],temperature:[{index:0,rgb:[4,35,51]},{index:.13,rgb:[23,51,122]},{index:.25,rgb:[85,59,157]},{index:.38,rgb:[129,79,143]},{index:.5,rgb:[175,95,130]},{index:.63,rgb:[222,112,101]},{index:.75,rgb:[249,146,66]},{index:.88,rgb:[249,196,65]},{index:1,rgb:[232,250,91]}],turbidity:[{index:0,rgb:[34,31,27]},{index:.13, -rgb:[65,50,41]},{index:.25,rgb:[98,69,52]},{index:.38,rgb:[131,89,57]},{index:.5,rgb:[161,112,59]},{index:.63,rgb:[185,140,66]},{index:.75,rgb:[202,174,88]},{index:.88,rgb:[216,209,126]},{index:1,rgb:[233,246,171]}],"velocity-blue":[{index:0,rgb:[17,32,64]},{index:.13,rgb:[35,52,116]},{index:.25,rgb:[29,81,156]},{index:.38,rgb:[31,113,162]},{index:.5,rgb:[50,144,169]},{index:.63,rgb:[87,173,176]},{index:.75,rgb:[149,196,189]},{index:.88,rgb:[203,221,211]},{index:1,rgb:[254,251,230]}],"velocity-green":[{index:0,rgb:[23,35,19]},{index:.13,rgb:[24,64,38]},{index:.25,rgb:[11,95,45]},{index:.38,rgb:[39,123,35]},{index:.5,rgb:[95,146,12]},{index:.63,rgb:[152,165,18]},{index:.75,rgb:[201,186,69]},{index:.88,rgb:[233,216,137]},{index:1,rgb:[255,253,205]}],cubehelix:[{index:0,rgb:[0,0,0]},{index:.07,rgb:[22,5,59]},{index:.13,rgb:[60,4,105]},{index:.2,rgb:[109,1,135]},{index:.27,rgb:[161,0,147]},{index:.33,rgb:[210,2,142]},{index:.4,rgb:[251,11,123]},{index:.47,rgb:[255,29,97]},{index:.53,rgb:[255,54,69]},{index:.6,rgb:[255,85,46]},{index:.67,rgb:[255,120,34]},{index:.73,rgb:[255,157,37]},{index:.8,rgb:[241,191,57]},{index:.87,rgb:[224,220,93]},{index:.93,rgb:[218,241,142]},{index:1,rgb:[227,253,198]}]}},{}],263:[function(t,e,r){"use strict";function n(t){var e,r,n,u,c,f,h,p,d,g,v,m,y,b=[],x=[],_=[],w=[];if(o.isPlainObject(t)||(t={}),d=t.nshades||72,p=t.format||"hex",h=t.colormap,h||(h="jet"),"string"==typeof h){if(h=h.toLowerCase(),!l[h])throw Error(h+" not a supported colorscale");f=s(l[h])}else{if(!Array.isArray(h))throw Error("unsupported colormap option",h);f=s(h)}if(f.length>d)throw new Error(h+" map requires nshades to be at least size "+f.length);for(v=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:s(t.alpha):"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1],e=f.map(function(t){return Math.round(t.index*d)}),v[0]<0&&(v[0]=0),v[1]<0&&(v[0]=0),v[0]>1&&(v[0]=1),v[1]>1&&(v[0]=1),y=0;y=0&&r[3]<=1||(r[3]=v[0]+(v[1]-v[0])*m);for(y=0;yn;++n)e=t[n],e=e.toString(16),r+=("00"+e).substr(e.length);return r}function a(t){return"rgba("+t.join(",")+")"}var o=t("arraytools"),s=t("clone"),l=t("./colorScales");e.exports=n},{"./colorScales":262,arraytools:64,clone:264}],264:[function(t,e,r){(function(t){var r=function(){"use strict";function e(r,n,i,a){function s(r,i){if(null===r)return null;if(0==i)return r;var l,h;if("object"!=typeof r)return r;if(e.__isArray(r))l=[];else if(e.__isRegExp(r))l=new RegExp(r.source,o(r)),r.lastIndex&&(l.lastIndex=r.lastIndex);else if(e.__isDate(r))l=new Date(r.getTime());else{if(f&&t.isBuffer(r))return l=new t(r.length),r.copy(l),l;"undefined"==typeof a?(h=Object.getPrototypeOf(r),l=Object.create(h)):(l=Object.create(a),h=a)}if(n){var p=u.indexOf(r);if(-1!=p)return c[p];u.push(r),c.push(l)}for(var d in r){var g;h&&(g=Object.getOwnPropertyDescriptor(h,d)),g&&null==g.set||(l[d]=s(r[d],i-1))}return l}var l;"object"==typeof n&&(i=n.depth,a=n.prototype,l=n.filter,n=n.circular);var u=[],c=[],f="undefined"!=typeof t;return"undefined"==typeof n&&(n=!0),"undefined"==typeof i&&(i=1/0),s(r,i)}function r(t){return Object.prototype.toString.call(t)}function n(t){return"object"==typeof t&&"[object Date]"===r(t)}function i(t){return"object"==typeof t&&"[object Array]"===r(t)}function a(t){return"object"==typeof t&&"[object RegExp]"===r(t)}function o(t){var e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),e}return e.clonePrototype=function(t){if(null===t)return null;var e=function(){};return e.prototype=t,new e},e.__objToStr=r,e.__isDate=n,e.__isArray=i,e.__isRegExp=a,e.__getRegExpFlags=o,e}();"object"==typeof e&&e.exports&&(e.exports=r)}).call(this,t("buffer").Buffer)},{buffer:65}],265:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":306}],266:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":267,"./lib/create-attributes":268,"./lib/create-uniforms":269,"./lib/reflect":270,"./lib/runtime-reflect":271,"./lib/shader-cache":272,dup:94}],267:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],268:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":267,dup:96}],269:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":267,"./reflect":270,dup:97}],270:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],271:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],272:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":267,dup:100,"gl-format-compiler-error":273,"weakmap-shim":291}],273:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":274,dup:101,"gl-constants/lookup":278,"glsl-shader-name":279,"sprintf-js":288}],274:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":275}],275:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":276}],276:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],277:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],278:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":277,dup:106}],279:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":280,dup:107,"glsl-tokenizer":287}],280:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],281:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":283,"./lib/builtins-300es":282,"./lib/literals":285,"./lib/literals-300es":284,"./lib/operators":286,dup:109}],282:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":283,dup:110}],283:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],284:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":285,dup:112}],285:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],286:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],287:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":281,dup:115}],288:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],289:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":290,dup:117}],290:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],291:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":289,dup:119}],292:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":306}],293:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],294:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":293,dup:155}],295:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":293,dup:156}],296:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":294,"./lib/vao-native.js":295,dup:157}],297:[function(t,e,r){var n=1e-6,i=1e-6;r.vertexNormals=function(t,e,r){for(var i=e.length,a=new Array(i),o=void 0===r?n:r,s=0;i>s;++s)a[s]=[0,0,0];for(var s=0;sx;++x)v[x]=p[x]-d[x],m+=v[x]*v[x],y[x]=g[x]-d[x],b+=y[x]*y[x];if(m*b>o)for(var _=a[c],w=1/Math.sqrt(m*b),x=0;3>x;++x){var k=(x+1)%3,A=(x+2)%3;_[x]+=w*(y[k]*v[A]-y[A]*v[k])}}for(var s=0;i>s;++s){for(var _=a[s],M=0,x=0;3>x;++x)M+=_[x]*_[x];if(M>o)for(var w=1/Math.sqrt(M),x=0;3>x;++x)_[x]*=w;else for(var x=0;3>x;++x)_[x]=0}return a},r.faceNormals=function(t,e,r){for(var n=t.length,a=new Array(n),o=void 0===r?i:r,s=0;n>s;++s){for(var l=t[s],u=new Array(3),c=0;3>c;++c)u[c]=e[l[c]];for(var f=new Array(3),h=new Array(3),c=0;3>c;++c)f[c]=u[1][c]-u[0][c],h[c]=u[2][c]-u[0][c];for(var p=new Array(3),d=0,c=0;3>c;++c){var g=(c+1)%3,v=(c+2)%3;p[c]=f[g]*h[v]-f[v]*h[g],d+=p[c]*p[c]}d=d>o?1/Math.sqrt(d):0;for(var c=0;3>c;++c)p[c]*=d;a[s]=p}return a}},{}],298:[function(t,e,r){"use strict";function n(t,e,r,n,s){i.length=x+_)if(0>x)0>_&&0>h?(_=0,-h>=u?(x=1,y=u+2*h+d):(x=-h/u,y=h*x+d)):(x=0,p>=0?(_=0,y=d):-p>=f?(_=1,y=f+2*p+d):(_=-p/f,y=p*_+d));else if(0>_)_=0,h>=0?(x=0,y=d):-h>=u?(x=1,y=u+2*h+d):(x=-h/u,y=h*x+d);else{var w=1/b;x*=w,_*=w,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d}else{var k,A,M,T;0>x?(k=c+h,A=f+p,A>k?(M=A-k,T=u-2*c+f,M>=T?(x=1,_=0,y=u+2*h+d):(x=M/T,_=1-x,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d)):(x=0,0>=A?(_=1,y=f+2*p+d):p>=0?(_=0,y=d):(_=-p/f,y=p*_+d))):0>_?(k=c+p,A=u+h,A>k?(M=A-k,T=u-2*c+f,M>=T?(_=1,x=0,y=f+2*p+d):(_=M/T,x=1-_,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d)):(_=0,0>=A?(x=1,y=u+2*h+d):h>=0?(x=0,y=d):(x=-h/u,y=h*x+d))):(M=f+p-c-h,0>=M?(x=0,_=1,y=f+2*p+d):(T=u-2*c+f,M>=T?(x=1,_=0,y=u+2*h+d):(x=M/T,_=1-x,y=x*(u*x+c*_+2*h)+_*(c*x+f*_+2*p)+d)))}for(var E=1-x-_,l=0;ly?0:y}var i=new Float64Array(4),a=new Float64Array(4),o=new Float64Array(4);e.exports=n},{}],299:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r=0|Math.max(r,t[n].length);return r-1}function i(t,e){for(var r=t.length,n=f.mallocUint8(r),i=0;r>i;++i)n[i]=t[i]o;++o)for(var s=t[o],e=s.length,l=0;e>l;++l)for(var u=0;l>u;++u){var p=s[u],d=s[l];i[a++]=0|Math.min(p,d),i[a++]=0|Math.max(p,d)}var g=a/2|0;h(c(i,[g,2]));for(var v=2,o=2;a>o;o+=2)i[o-2]===i[o]&&i[o-1]===i[o+1]||(i[v++]=i[o],i[v++]=i[o+1]);return c(i,[v/2|0,2])}function o(t,e,r,n){for(var i=t.data,a=t.shape[0],o=f.mallocDouble(a),s=0,l=0;a>l;++l){var u=i[2*l],h=i[2*l+1];if(r[u]!==r[h]){var p=e[u],d=e[h];i[2*s]=u,i[2*s+1]=h,o[s++]=(d-n)/(d-p)}}return t.shape[0]=s,c(o,[s])}function s(t,e){var r=f.mallocInt32(2*e),n=t.shape[0],i=t.data;r[0]=0;for(var a=0,o=0;n>o;++o){var s=i[2*o];if(s!==a){for(r[2*a+1]=o;++ai;++i)n[i]=[r[2*i],r[2*i+1]];return n}function u(t,e,r,u){r=r||0,"undefined"==typeof u&&(u=n(t));var c=t.length;if(0===c||1>u)return{cells:[],vertexIds:[],vertexWeights:[]};var h=i(e,+r),d=a(t,u),g=o(d,e,h,+r),v=s(d,0|e.length),m=p(u)(t,d.data,v,h),y=l(d),b=[].slice.call(g.data,0,g.shape[0]);return f.free(h),f.free(d.data),f.free(g.data),f.free(v),{cells:m,vertexIds:y,vertexWeights:b}}e.exports=u;var c=t("ndarray"),f=t("typedarray-pool"),h=t("ndarray-sort"),p=t("./lib/codegen")},{"./lib/codegen":300,ndarray:1031,"ndarray-sort":303,"typedarray-pool":306}],300:[function(t,e,r){"use strict";function n(t){function e(t){if(!(t.length<=0)){u.push("R.push(");for(var e=0;e0&&u.push(","),u.push("[");for(var n=0;n0&&u.push(","),u.push("B(C,E,c[",i[0],"],c[",i[1],"])")}u.push("]")}u.push(");")}}var r=0,n=new Array(t+1);n[0]=[[]];for(var i=1;t>=i;++i)for(var s=n[i]=o(i),l=0;l>1,v=E[2*m+1];","if(v===b){return m}","if(b1;--i){t+1>i&&u.push("else "),u.push("if(l===",i,"){");for(var c=[],l=0;i>l;++l)c.push("(S[c["+l+"]]<<"+l+")");u.push("var M=",c.join("+"),";if(M===0||M===",(1<i;++i)n[i]=0,i===e&&(n[i]+=.5),i===r&&(n[i]+=.5);return n}function i(t,e){if(0===e||e===(1<=a;++a)if(e&1<=s;++s)~e&1<n;++n)r[n]=i(t,n);return r}e.exports=a;var o=t("convex-hull")},{"convex-hull":71}],302:[function(t,e,r){"use strict";function n(t){switch(t){case"uint8":return[l.mallocUint8,l.freeUint8];case"uint16":return[l.mallocUint16,l.freeUint16];case"uint32":return[l.mallocUint32,l.freeUint32];case"int8":return[l.mallocInt8,l.freeInt8];case"int16":return[l.mallocInt16,l.freeInt16];case"int32":return[l.mallocInt32,l.freeInt32];case"float32":return[l.mallocFloat,l.freeFloat];case"float64":return[l.mallocDouble,l.freeDouble];default:return null}}function i(t){for(var e=[],r=0;t>r;++r)e.push("s"+r);for(var r=0;t>r;++r)e.push("n"+r);for(var r=1;t>r;++r)e.push("d"+r);for(var r=1;t>r;++r)e.push("e"+r);for(var r=1;t>r;++r)e.push("f"+r);return e}function a(t,e){function r(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function a(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}var o=["'use strict'"],s=["ndarrayInsertionSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(i(t.length)),u=n(e),c=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var f=[],h=1;h1){o.push("dptr=0;sptr=ptr");for(var h=t.length-1;h>=0;--h){var p=t[h];0!==p&&o.push(["for(i",p,"=0;i",p,"left){","dptr=0","sptr=cptr-s0");for(var h=1;hb){break __l}"].join(""));for(var h=t.length-1;h>=1;--h)o.push("sptr+=e"+h,"dptr+=f"+h,"}");o.push("dptr=cptr;sptr=cptr-s0");for(var h=t.length-1;h>=0;--h){var p=t[h];0!==p&&o.push(["for(i",p,"=0;i",p,"=0;--h){var p=t[h];0!==p&&o.push(["for(i",p,"=0;i",p,"left)&&("+r("cptr-s0")+">scratch)){",a("cptr",r("cptr-s0")),"cptr-=s0","}",a("cptr","scratch"));if(o.push("}"),t.length>1&&u&&o.push("free(scratch)"),o.push("} return "+s),u){var d=new Function("malloc","free",o.join("\n"));return d(u[0],u[1])}var d=new Function(o.join("\n"));return d()}function o(t,e,r){function a(t){return["(offset+",t,"*s0)"].join("")}function o(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function s(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}function l(e,r,n){if(1===e.length)_.push("ptr0="+a(e[0]));else for(var i=0;i=0;--i){var o=t[i];0!==o&&_.push(["for(i",o,"=0;i",o,"1)for(var i=0;i1?_.push("ptr_shift+=d"+o):_.push("ptr0+=d"+o),_.push("}"))}}function c(e,r,n,i){if(1===r.length)_.push("ptr0="+a(r[0]));else{for(var o=0;o1)for(var o=0;o=1;--o)n&&_.push("pivot_ptr+=f"+o),r.length>1?_.push("ptr_shift+=e"+o):_.push("ptr0+=e"+o),_.push("}")}function f(){t.length>1&&A&&_.push("free(pivot1)","free(pivot2)")}function h(e,r){var n="el"+e,i="el"+r;if(t.length>1){var s="__l"+ ++M;c(s,[n,i],!1,["comp=",o("ptr0"),"-",o("ptr1"),"\n","if(comp>0){tmp0=",n,";",n,"=",i,";",i,"=tmp0;break ",s,"}\n","if(comp<0){break ",s,"}"].join(""))}else _.push(["if(",o(a(n)),">",o(a(i)),"){tmp0=",n,";",n,"=",i,";",i,"=tmp0}"].join(""))}function p(e,r){t.length>1?l([e,r],!1,s("ptr0",o("ptr1"))):_.push(s(a(e),o(a(r))))}function d(e,r,n){if(t.length>1){var i="__l"+ ++M;c(i,[r],!0,[e,"=",o("ptr0"),"-pivot",n,"[pivot_ptr]\n","if(",e,"!==0){break ",i,"}"].join(""))}else _.push([e,"=",o(a(r)),"-pivot",n].join(""))}function g(e,r){t.length>1?l([e,r],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join("")):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join(""))}function v(e,r,n){t.length>1?(l([e,r,n],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join("")),_.push("++"+r,"--"+n)):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","ptr2=",a(n),"\n","++",r,"\n","--",n,"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join(""))}function m(t,e){g(t,e),_.push("--"+e)}function y(e,r,n){t.length>1?l([e,r],!0,[s("ptr0",o("ptr1")),"\n",s("ptr1",["pivot",n,"[pivot_ptr]"].join(""))].join("")):_.push(s(a(e),o(a(r))),s(a(r),"pivot"+n))}function b(e,r){_.push(["if((",r,"-",e,")<=",u,"){\n","insertionSort(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}else{\n",w,"(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}"].join(""))}function x(e,r,n){t.length>1?(_.push(["__l",++M,":while(true){"].join("")),l([e],!0,["if(",o("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",M,"}"].join("")),_.push(n,"}")):_.push(["while(",o(a(e)),"===pivot",r,"){",n,"}"].join(""))}var _=["'use strict'"],w=["ndarrayQuickSort",t.join("d"),e].join(""),k=["left","right","data","offset"].concat(i(t.length)),A=n(e),M=0;_.push(["function ",w,"(",k.join(","),"){"].join(""));var T=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var E=[],L=1;LL;++L)T.push("b_ptr"+L);T.push("ptr3","ptr4","ptr5","ptr6","ptr7","pivot_ptr","ptr_shift","elementSize="+E.join("*")),A?T.push("pivot1=malloc(elementSize)","pivot2=malloc(elementSize)"):T.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")}else T.push("pivot1","pivot2");if(_.push("var "+T.join(",")),h(1,2),h(4,5),h(1,3),h(2,3),h(1,4),h(3,4),h(2,5),h(2,3),h(4,5),t.length>1?l(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",o("ptr1"),"\n","pivot2[pivot_ptr]=",o("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",o("ptr0"),"\n","y=",o("ptr2"),"\n","z=",o("ptr4"),"\n",s("ptr5","x"),"\n",s("ptr6","y"),"\n",s("ptr7","z")].join("")):_.push(["pivot1=",o(a("el2")),"\n","pivot2=",o(a("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",o(a("el1")),"\n","y=",o(a("el3")),"\n","z=",o(a("el5")),"\n",s(a("index1"),"x"),"\n",s(a("index3"),"y"),"\n",s(a("index5"),"z")].join("")),p("index2","left"),p("index4","right"),_.push("if(pivots_are_equal){"),_.push("for(k=less;k<=great;++k){"),d("comp","k",1),_.push("if(comp===0){continue}"),_.push("if(comp<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),_.push("while(true){"),d("comp","great",1),_.push("if(comp>0){"),_.push("great--"),_.push("}else if(comp<0){"),v("k","less","great"),_.push("break"),_.push("}else{"),m("k","great"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}else{"),_.push("for(k=less;k<=great;++k){"),d("comp_pivot1","k",1),_.push("if(comp_pivot1<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),d("comp_pivot2","k",2),_.push("if(comp_pivot2>0){"),_.push("while(true){"),d("comp","great",2),_.push("if(comp>0){"),_.push("if(--greatindex5){"),x("less",1,"++less"),x("great",2,"--great"),_.push("for(k=less;k<=great;++k){"),d("comp_pivot1","k",1),_.push("if(comp_pivot1===0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),d("comp_pivot2","k",2),_.push("if(comp_pivot2===0){"),_.push("while(true){"),d("comp","great",2),_.push("if(comp===0){"),_.push("if(--great1&&A){var S=new Function("insertionSort","malloc","free",_.join("\n"));return S(r,A[0],A[1])}var S=new Function("insertionSort",_.join("\n"));return S(r)}function s(t,e){var r=["'use strict'"],n=["ndarraySortWrapper",t.join("d"),e].join(""),s=["array"];r.push(["function ",n,"(",s.join(","),"){"].join(""));for(var l=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"],c=0;c0?l.push(["d",v,"=s",v,"-d",d,"*n",d].join("")):l.push(["d",v,"=s",v].join("")),d=v);var p=t.length-1-c;0!==p&&(g>0?l.push(["e",p,"=s",p,"-e",g,"*n",g,",f",p,"=",f[p],"-f",g,"*n",g].join("")):l.push(["e",p,"=s",p,",f",p,"=",f[p]].join("")),g=p)}r.push("var "+l.join(","));var m=["0","n0-1","data","offset"].concat(i(t.length));r.push(["if(n0<=",u,"){","insertionSort(",m.join(","),")}else{","quickSort(",m.join(","),")}"].join("")),r.push("}return "+n);var y=new Function("insertionSort","quickSort",r.join("\n")),b=a(t,e),x=o(t,e,b);return y(b,x)}var l=t("typedarray-pool"),u=32;e.exports=s},{"typedarray-pool":306}],303:[function(t,e,r){"use strict";function n(t){var e=t.order,r=t.dtype,n=[e,r],o=n.join(":"),s=a[o];return s||(a[o]=s=i(e,r)),s(t),t}var i=t("./lib/compile_sort.js"),a={};e.exports=n},{"./lib/compile_sort.js":302}],304:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],305:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],306:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":304,buffer:65,dup:122}],307:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[0,0,0,1,1,0,1,1]),i=o(e,s.boxVert,s.lineFrag);return new n(t,r,i)}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawBox=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o){var s=this.plot,l=this.shader,u=s.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,l.uniforms.lo=t,l.uniforms.hi=e,l.uniforms.color=o,u.drawArrays(u.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":310,"gl-buffer":313,"gl-shader":328}],308:[function(t,e,r){"use strict";function n(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function i(t,e){return t-e}function a(t){var e=t.gl,r=o(e),i=s(e,u.gridVert,u.gridFrag),a=s(e,u.tickVert,u.gridFrag),l=new n(t,r,i,a);return l}e.exports=a;var o=t("gl-buffer"),s=t("gl-shader"),l=t("binary-search-bounds"),u=t("./shaders"),c=n.prototype;c.draw=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){for(var n=this.plot,i=this.vbo,a=this.shader,o=this.ticks,s=n.gl,l=n._tickBounds,u=n.dataBox,c=n.viewBox,f=n.gridLineWidth,h=n.gridLineColor,p=n.gridLineEnable,d=n.pixelRatio,g=0;2>g;++g){var v=l[g],m=l[g+2],y=m-v,b=.5*(u[g+2]+u[g]),x=u[g+2]-u[g];e[g]=2*y/x,t[g]=2*(v-b)/x}a.bind(),i.bind(),a.attributes.dataCoord.pointer(),a.uniforms.dataShift=t,a.uniforms.dataScale=e;for(var _=0,g=0;2>g;++g){r[0]=r[1]=0,r[g]=1,a.uniforms.dataAxis=r,a.uniforms.lineWidth=f[g]/(c[g+2]-c[g])*d,a.uniforms.color=h[g];var w=6*o[g].length;p[g]&&w&&s.drawArrays(s.TRIANGLES,_,w),_+=w}}}(),c.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],o=[0,0];return function(){for(var s=this.plot,u=this.vbo,c=this.tickShader,f=this.ticks,h=s.gl,p=s._tickBounds,d=s.dataBox,g=s.viewBox,v=s.pixelRatio,m=s.screenBox,y=m[2]-m[0],b=m[3]-m[1],x=g[2]-g[0],_=g[3]-g[1],w=0;2>w;++w){var k=p[w],A=p[w+2],M=A-k,T=.5*(d[w+2]+d[w]),E=d[w+2]-d[w];e[w]=2*M/E,t[w]=2*(k-T)/E}e[0]*=x/y,t[0]*=x/y,e[1]*=_/b,t[1]*=_/b,c.bind(),u.bind(),c.attributes.dataCoord.pointer();var L=c.uniforms;L.dataShift=t,L.dataScale=e;var S=s.tickMarkLength,C=s.tickMarkWidth,z=s.tickMarkColor,P=0,R=6*f[0].length,j=Math.min(l.ge(f[0],(d[0]-p[0])/(p[2]-p[0]),i),f[0].length),O=Math.min(l.gt(f[0],(d[2]-p[0])/(p[2]-p[0]),i),f[0].length),I=P+6*j,N=6*Math.max(0,O-j),F=Math.min(l.ge(f[1],(d[1]-p[1])/(p[3]-p[1]),i),f[1].length),D=Math.min(l.gt(f[1],(d[3]-p[1])/(p[3]-p[1]),i),f[1].length),B=R+6*F,U=6*Math.max(0,D-F);a[0]=2*(g[0]-S[1])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[1]*v/y,o[1]=C[1]*v/b,U&&(L.color=z[1],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[1]-S[0])/b-1,o[0]=C[0]*v/y,o[1]=S[0]*v/b,N&&(L.color=z[0],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,I,N)),a[0]=2*(g[2]+S[3])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[3]*v/y,o[1]=C[3]*v/b,U&&(L.color=z[3],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[3]+S[2])/b-1,o[0]=C[2]*v/y,o[1]=S[2]*v/b,N&&(L.color=z[2],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,I,N))}}(),c.update=function(){var t=[1,1,-1,-1,1,-1],e=[1,-1,1,1,-1,-1];return function(r){for(var n=r.ticks,i=r.bounds,a=new Float32Array(18*(n[0].length+n[1].length)),o=(this.plot.zeroLineEnable,0),s=[[],[]],l=0;2>l;++l)for(var u=s[l],c=n[l],f=i[l],h=i[l+2],p=0;pg;++g)a[o++]=d,a[o++]=t[g],a[o++]=e[g]}this.ticks=s,this.vbo.update(a)}}(),c.dispose=function(){this.vbo.dispose(),this.shader.dispose(),this.tickShader.dispose()}},{"./shaders":310,"binary-search-bounds":312,"gl-buffer":313,"gl-shader":328}],309:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[-1,-1,-1,1,1,-1,1,1]),i=o(e,s.lineVert,s.lineFrag),l=new n(t,r,i);return l}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawLine=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o,s){var l=this.plot,u=this.shader,c=l.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,u.uniforms.start=t,u.uniforms.end=e,u.uniforms.width=o*l.pixelRatio,u.uniforms.color=s,c.drawArrays(c.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":310,"gl-buffer":313,"gl-shader":328}],310:[function(t,e,r){"use strict";var n="precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n";e.exports={lineVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n",lineFrag:n,textVert:"#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n",textFrag:n,gridVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n",gridFrag:n,boxVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n",tickVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"}},{}],311:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r,this.tickOffset=[[],[]],this.tickX=[[],[]],this.labelOffset=[0,0],this.labelCount=[0,0]}function i(t){var e=t.gl,r=a(e),i=o(e,u.textVert,u.textFrag),s=new n(t,r,i);return s}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("text-cache"),l=t("binary-search-bounds"),u=t("./shaders"),c=n.prototype;c.drawTicks=function(){var t=[0,0],e=[0,0],r=[0,0];return function(n){var i=this.plot,a=this.shader,o=this.tickX[n],s=this.tickOffset[n],u=i.gl,c=i.viewBox,f=i.dataBox,h=i.screenBox,p=i.pixelRatio,d=i.tickEnable,g=i.tickPad,v=i.tickColor,m=i.tickAngle,y=(i.tickMarkLength, -i.labelEnable),b=i.labelPad,x=i.labelColor,_=i.labelAngle,w=this.labelOffset[n],k=this.labelCount[n],A=l.lt(o,f[n]),M=l.le(o,f[n+2]);t[0]=t[1]=0,t[n]=1,e[n]=(c[2+n]+c[n])/(h[2+n]-h[n])-1;var T=2/h[2+(1^n)]-h[1^n];e[1^n]=T*c[1^n]-1,d[n]&&(e[1^n]-=T*p*g[n],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n],a.uniforms.angle=m[n],u.drawArrays(u.TRIANGLES,s[A],s[M]-s[A]))),y[n]&&k&&(e[1^n]-=T*p*b[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=_[n],u.drawArrays(u.TRIANGLES,w,k)),e[1^n]=T*c[2+(1^n)]-1,d[n+2]&&(e[1^n]+=T*p*g[n+2],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n+2],a.uniforms.angle=m[n+2],u.drawArrays(u.TRIANGLES,s[A],s[M]-s[A]))),y[n+2]&&k&&(e[1^n]+=T*p*b[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=_[n+2],u.drawArrays(u.TRIANGLES,w,k))}}(),c.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,o=r.titleCenter,u=r.pixelRatio;if(this.titleCount){for(var c=0;2>c;++c)e[c]=2*(o[c]*u-a[c])/(a[2+c]-a[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),c.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var u=0;2>u;++u){var c=a[u],f=a[u+2],h=f-c,p=.5*(o[u+2]+o[u]),d=o[u+2]-o[u],g=l[u],v=l[u+2],m=v-g,y=s[u],b=s[u+2],x=b-y;e[u]=2*h/d*m/x,t[u]=2*(c-p)/d*m/x}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),c.update=function(t){for(var e=[],r=t.ticks,n=t.bounds,i=0;2>i;++i){for(var a=[Math.floor(e.length/3)],o=[-(1/0)],l=r[i],u=0;ui;++i){this.labelOffset[i]=Math.floor(e.length/3);for(var g=s(t.labelFont[i],t.labels[i]).data,d=t.labelSize[i],u=0;u>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],313:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":316}],314:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],315:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],316:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":314,buffer:65,dup:122}],317:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],318:[function(t,e,r){e.exports=t("cwise-compiler")},{"cwise-compiler":319}],319:[function(t,e,r){"use strict";function n(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function i(t){var e=new n;e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var i=0;i0)throw new Error("cwise: pre() block may not reference array args");if(i0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if("index"===o){if(e.indexArgs.push(i),i0)throw new Error("cwise: pre() block may not reference array index");if(i0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(e.shapeArgs.push(i),ir.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,a(e)}var a=t("./lib/thunk.js");e.exports=i},{"./lib/thunk.js":321}],320:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],u=[],c=0,f=0;for(n=0;a>n;++n)u.push(["i",n,"=0"].join(""));for(i=0;o>i;++i)for(n=0;a>n;++n)f=c,c=t[n],0===n?u.push(["d",i,"s",n,"=t",i,"p",c].join("")):u.push(["d",i,"s",n,"=(t",i,"p",c,"-s",f,"*t",i,"p",f,")"].join(""));for(l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"n;++n){for(f=c,c=t[n],i=0;o>i;++i)l.push(["p",i,"+=d",i,"s",n].join(""));s&&(n>0&&l.push(["index[",f,"]-=s",f].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function i(t,e,r,i){for(var a=e.length,o=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,u=[],c=0;o>c;++c)u.push(["var offset",c,"=p",c].join(""));for(var c=t;a>c;++c)u.push(["for(var j"+c+"=SS[",e[c],"]|0;j",c,">0;){"].join("")),u.push(["if(j",c,"<",s,"){"].join("")),u.push(["s",e[c],"=j",c].join("")),u.push(["j",c,"=0"].join("")),u.push(["}else{s",e[c],"=",s].join("")),u.push(["j",c,"-=",s,"}"].join("")),l&&u.push(["index[",e[c],"]=j",c].join(""));for(var c=0;o>c;++c){for(var f=["offset"+c],h=t;a>h;++h)f.push(["j",h,"*t",c,"p",e[h]].join(""));u.push(["p",c,"=(",f.join("+"),")"].join(""))}u.push(n(e,r,i));for(var c=t;a>c;++c)u.push("}");return u.join("\n")}function a(t){for(var e=0,r=t[0].length;r>e;){for(var n=1;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}function l(t,e){for(var r=e[1].length-Math.abs(t.arrayBlockIndices[0])|0,l=new Array(t.arrayArgs.length),c=new Array(t.arrayArgs.length),f=0;fy;++y)_.push(["s",y,"=SS[",y,"]"].join(""));for(var f=0;fy;++y)_.push(["t",f,"p",y,"=t",f,"[",d[f]+y,"]"].join(""));for(var y=0;y0&&_.push("shape=SS.slice(0)"),t.indexArgs.length>0){for(var w=new Array(r),f=0;r>f;++f)w[f]="0";_.push(["index=[",w.join(","),"]"].join(""))}for(var f=0;f3&&x.push(o(t.pre,t,c));var T=o(t.body,t,c),E=a(v);r>E?x.push(i(E,v[0],t,T)):x.push(n(v[0],t,T)),t.post.body.length>3&&x.push(o(t.post,t,c)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+x.join("\n")+"\n----------");var L=[t.funcName||"unnamed","_cwise_loop_",l[0].join("s"),"m",E,s(c)].join(""),S=new Function(["function ",L,"(",b.join(","),"){",x.join("\n"),"} return ",L].join(""));return S()}var u=t("uniq");e.exports=l},{uniq:322}],321:[function(t,e,r){"use strict";function n(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],u=[],c=0;c0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[c]))),u.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[c])+"]"))}t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),e.push("if (!("+u.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}"));for(var c=0;c=n;++n){for(var i=new Array(r),a=0;n>a;++a)i[a]=t.COLOR_ATTACHMENT0+a;for(var a=n;r>a;++a)i[a]=t.NONE;y[n]=i}}function o(t){switch(t){case d:throw new Error("gl-fbo: Framebuffer unsupported");case g:throw new Error("gl-fbo: Framebuffer incomplete attachment");case v:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case m:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function s(t,e,r,n,i,a){if(!n)return null;var o=p(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function l(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function u(t){var e=n(t.gl),r=t.gl,a=t.handle=r.createFramebuffer(),u=t._shape[0],c=t._shape[1],f=t.color.length,h=t._ext,p=t._useStencil,d=t._useDepth,g=t._colorType;r.bindFramebuffer(r.FRAMEBUFFER,a);for(var v=0;f>v;++v)t.color[v]=s(r,u,c,g,r.RGBA,r.COLOR_ATTACHMENT0+v);0===f?(t._color_rb=l(r,u,c,r.RGBA4,r.COLOR_ATTACHMENT0),h&&h.drawBuffersWEBGL(y[0])):f>1&&h.drawBuffersWEBGL(y[f]);var m=r.getExtension("WEBGL_depth_texture");m?p?t.depth=s(r,u,c,m.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):d&&(t.depth=s(r,u,c,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):d&&p?t._depth_rb=l(r,u,c,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):d?t._depth_rb=l(r,u,c,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):p&&(t._depth_rb=l(r,u,c,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var b=r.checkFramebufferStatus(r.FRAMEBUFFER);if(b!==r.FRAMEBUFFER_COMPLETE){t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null);for(var v=0;vl;++l)this.color[l]=null;this._color_rb=null,this.depth=null,this._depth_rb=null,this._colorType=n,this._useDepth=a,this._useStencil=o;var c=this,f=[0|e,0|r];Object.defineProperties(f,{0:{get:function(){return c._shape[0]},set:function(t){return c.width=t}},1:{get:function(){return c._shape[1]},set:function(t){return c.height=t}}}),this._shapeVector=f,u(this)}function f(t,e,r){if(t._destroyed)throw new Error("gl-fbo: Can't resize destroyed FBO");if(t._shape[0]!==e||t._shape[1]!==r){var a=t.gl,s=a.getParameter(a.MAX_RENDERBUFFER_SIZE);if(0>e||e>s||0>r||r>s)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var l=n(a),u=0;ue||e>o||0>r||r>o)throw new Error("gl-fbo: Parameters are too large for FBO");n=n||{};var s=1;if("color"in n){if(s=Math.max(0|n.color,0),0>s)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(s>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(s>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+s+" draw buffers")}}var l=t.UNSIGNED_BYTE,u=t.getExtension("OES_texture_float");if(n.float&&s>0){if(!u)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&s>0&&u&&(l=t.FLOAT);var f=!0;"depth"in n&&(f=!!n.depth);var h=!1;return"stencil"in n&&(h=!!n.stencil),new c(t,e,r,l,s,f,h,i)}var p=t("gl-texture2d");e.exports=h;var d,g,v,m,y=null,b=c.prototype;Object.defineProperties(b,{shape:{get:function(){return this._destroyed?[0,0]:this._shapeVector},set:function(t){if(Array.isArray(t)||(t=[0|t,0|t]),2!==t.length)throw new Error("gl-fbo: Shape vector must be length 2");var e=0|t[0],r=0|t[1];return f(this,e,r),[e,r]},enumerable:!1},width:{get:function(){return this._destroyed?0:this._shape[0]},set:function(t){return t=0|t,f(this,t,this._shape[1]),t},enumerable:!1},height:{get:function(){return this._destroyed?0:this._shape[1]},set:function(t){return t=0|t,f(this,this._shape[0],t),t},enumerable:!1}}),b.bind=function(){if(!this._destroyed){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.handle),t.viewport(0,0,this._shape[0],this._shape[1])}},b.dispose=function(){if(!this._destroyed){this._destroyed=!0;var t=this.gl;t.deleteFramebuffer(this.handle),this.handle=null,this.depth&&(this.depth.dispose(),this.depth=null),this._depth_rb&&(t.deleteRenderbuffer(this._depth_rb),this._depth_rb=null);for(var e=0;e_inline_1_arg0_||255>_inline_1_arg1_||255>_inline_1_arg2_||255>_inline_1_arg3_){var _inline_1_l=_inline_1_arg4_-_inline_1_arg6_[0],_inline_1_a=_inline_1_arg5_-_inline_1_arg6_[1],_inline_1_f=_inline_1_l*_inline_1_l+_inline_1_a*_inline_1_a;_inline_1_fthis.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(u(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),f.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},f.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},f.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),u=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=u)return null;var f=[o-a,u-s],h=l(this.buffer,[f[0],f[1],4],[4,4*i[0],1],4*(a+i[0]*s)),p=c(h.hi(f[0],f[1],1),r,r),d=p[0],g=p[1];if(0>d||Math.pow(this.radius,2)l;++l)for(var u=t[l],c=0;2>c;++c)a[c]=0|Math.min(a[c],u[c]),o[c]=0|Math.max(o[c],u[c]);var f=0;switch(n){case"center":f=-.5*(a[0]+o[0]);break;case"right":case"end":f=-o[0];break;case"left":case"start":f=-a[0];break;default:throw new Error("vectorize-text: Unrecognized textAlign: '"+n+"'")}var h=0;switch(i){case"hanging":case"top":h=-a[1];break;case"middle":h=-.5*(a[1]+o[1]);break;case"alphabetic":case"ideographic":h=-3*r;break;case"bottom":h=-o[1];break;default:throw new Error("vectorize-text: Unrecoginized textBaseline: '"+i+"'")}var p=1/r;return"lineHeight"in e?p*=+e.lineHeight:"width"in e?p=e.width/(o[0]-a[0]):"height"in e&&(p=e.height/(o[1]-a[1])),t.map(function(t){return[p*(t[0]+f),p*(t[1]+h)]})}function i(t,e,r,n){var i=0|Math.ceil(e.measureText(r).width+2*n);if(i>8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.heights)){if(n>i){var l=n;n=i,i=l,l=o,o=s,s=l}e.isConstraint(n,i)||a(t[n],t[i],t[o],t[s])<0&&r.push(n,i)}}function i(t,e){for(var r=[],i=t.length,o=e.stars,s=0;i>s;++s)for(var l=o[s],u=1;uc||e.isConstraint(s,c))){for(var f=l[u-1],h=-1,p=1;ph||a(t[s],t[c],t[f],t[h])<0&&r.push(s,c)}}for(;r.length>0;){for(var c=r.pop(),s=r.pop(),f=-1,h=-1,l=o[s],d=1;df||0>h||a(t[s],t[c],t[f],t[h])>=0||(e.flip(s,c),n(t,e,r,f,s,h),n(t,e,r,s,h,f),n(t,e,r,h,c,f),n(t,e,r,c,f,h))}}var a=t("robust-in-sphere")[4];t("binary-search-bounds");e.exports=i},{"binary-search-bounds":312,"robust-in-sphere":361}],358:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function i(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}function a(t,e){for(var r=t.cells(),a=r.length,o=0;a>o;++o){var s=r[o],l=s[0],u=s[1],c=s[2];c>u?l>u&&(s[0]=u,s[1]=c,s[2]=l):l>c&&(s[0]=c,s[1]=l,s[2]=u)}r.sort(i);for(var f=new Array(a),o=0;oo;++o)for(var s=r[o],y=0;3>y;++y){var l=s[y],u=s[(y+1)%3],b=d[3*o+y]=m.locate(u,l,t.opposite(u,l)),x=g[3*o+y]=t.isConstraint(l,u);0>b&&(x?p.push(o):(h.push(o),f[o]=1),e&&v.push([u,l,-1]))}return m}function o(t,e,r){for(var n=0,i=0;i0||l.length>0;){for(;s.length>0;){var p=s.pop();if(u[p]!==-i){u[p]=i;for(var d=(c[p],0);3>d;++d){var g=h[3*p+d];g>=0&&0===u[g]&&(f[3*p+d]?l.push(g):(s.push(g),u[g]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var m=o(c,u,e);return r?m.concat(n.boundary):m}var l=t("binary-search-bounds");e.exports=s;var u=n.prototype;u.locate=function(){var t=[0,0,0];return function(e,r,n){var a=e,o=r,s=n;return n>r?e>r&&(a=r,o=n,s=e):e>n&&(a=n,o=e,s=r), -0>a?-1:(t[0]=a,t[1]=o,t[2]=s,l.eq(this.cells,t,i))}}()},{"binary-search-bounds":312}],359:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.a=t,this.b=e,this.idx=r,this.lowerIds=n,this.upperIds=i}function i(t,e,r,n){this.a=t,this.b=e,this.type=r,this.idx=n}function a(t,e){var r=t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.type-e.type;return r?r:t.type!==d&&(r=p(t.a,t.b,e.b))?r:t.idx-e.idx}function o(t,e){return p(t.a,t.b,e)}function s(t,e,r,n,i){for(var a=h.lt(e,n,o),s=h.gt(e,n,o),l=a;s>l;++l){for(var u=e[l],c=u.lowerIds,f=c.length;f>1&&p(r[c[f-2]],r[c[f-1]],n)>0;)t.push([c[f-1],c[f-2],i]),f-=1;c.length=f,c.push(i);for(var d=u.upperIds,f=d.length;f>1&&p(r[d[f-2]],r[d[f-1]],n)<0;)t.push([d[f-2],d[f-1],i]),f-=1;d.length=f,d.push(i)}}function l(t,e){var r;return(r=t.a[0]f;++f)l.push(new i(t[f],null,d,f));for(var f=0;o>f;++f){var h=e[f],p=t[h[0]],m=t[h[1]];p[0]m[0]&&l.push(new i(m,p,v,f),new i(p,m,g,f))}l.sort(a);for(var y=l[0].a[0]-(1+Math.abs(l[0].a[0]))*Math.pow(2,-52),b=[new n([y,1],[y,0],-1,[],[],[],[])],x=[],f=0,_=l.length;_>f;++f){var w=l[f],k=w.type;k===d?s(x,b,t,w.a,w.idx):k===v?u(b,t,w):c(b,t,w)}return x}var h=t("binary-search-bounds"),p=t("robust-orientation")[3],d=0,g=1,v=2;e.exports=f},{"binary-search-bounds":312,"robust-orientation":1040}],360:[function(t,e,r){"use strict";function n(t,e){this.stars=t,this.edges=e}function i(t,e,r){for(var n=1,i=t.length;i>n;n+=2)if(t[n-1]===e&&t[n]===r)return t[n-1]=t[i-2],t[n]=t[i-1],void(t.length=i-2)}function a(t,e){for(var r=new Array(t),i=0;t>i;++i)r[i]=[];return new n(r,e)}var o=t("binary-search-bounds");e.exports=a;var s=n.prototype;s.isConstraint=function(){function t(t,e){return t[0]-e[0]||t[1]-e[1]}var e=[0,0];return function(r,n){return e[0]=Math.min(r,n),e[1]=Math.max(r,n),o.eq(this.edges,e,t)>=0}}(),s.removeTriangle=function(t,e,r){var n=this.stars;i(n[t],e,r),i(n[e],r,t),i(n[r],t,e)},s.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},s.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;i>n;n+=2)if(r[n]===t)return r[n-1];return-1},s.flip=function(t,e){var r=this.opposite(t,e),n=this.opposite(e,t);this.removeTriangle(t,e,r),this.removeTriangle(e,t,n),this.addTriangle(t,n,r),this.addTriangle(e,r,n)},s.edges=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2)e.push([i[a],i[a+1]]);return e},s.cells=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2){var s=i[a],l=i[a+1];rr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-2,"]"].join("")}return e}function a(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",a(t.slice(0,e)),",",a(t.slice(e)),")"].join("")}function o(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return o(e,t)}function s(t){return t&!0?"-":""}function l(t){if(2===t.length)return[["diff(",o(t[0][0],t[1][1]),",",o(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;rn;++n)r.push(["prod(m",t,"[",n,"],m",t,"[",n,"])"].join(""));return a(r)}function c(t){for(var e=[],r=[],o=i(t),s=0;t>s;++s)o[0][s]="1",o[t-1][s]="w"+s;for(var s=0;t>s;++s)0===(1&s)?e.push.apply(e,l(n(o,s))):r.push.apply(r,l(n(o,s)));for(var c=a(e),f=a(r),h="exactInSphere"+t,p=[],s=0;t>s;++s)p.push("m"+s);for(var d=["function ",h,"(",p.join(),"){"],s=0;t>s;++s){d.push("var w",s,"=",u(s,t),";");for(var g=0;t>g;++g)g!==s&&d.push("var w",s,"m",g,"=scale(w",s,",m",g,"[0]);")}d.push("var p=",c,",n=",f,",d=diff(p,n);return d[d.length-1];}return ",h);var x=new Function("sum","diff","prod","scale",d.join(""));return x(m,y,v,b)}function f(){return 0}function h(){return 0}function p(){return 0}function d(t){var e=_[t.length];return e||(e=_[t.length]=c(t.length)),e.apply(void 0,t)}function g(){for(;_.length<=x;)_.push(c(_.length));for(var t=[],r=["slow"],n=0;x>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function testInSphere(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;x>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var v=t("two-product"),m=t("robust-sum"),y=t("robust-subtract"),b=t("robust-scale"),x=6,_=[f,h,p];g()},{"robust-scale":363,"robust-subtract":364,"robust-sum":365,"two-product":366}],362:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],363:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":366,"two-sum":362}],364:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],-e[0]);var a,o,s=r+i,l=new Array(s),u=0,c=0,f=0,h=Math.abs,p=t[c],d=h(p),g=-e[f],v=h(g);v>d?(o=p,c+=1,r>c&&(p=t[c],d=h(p))):(o=g,f+=1,i>f&&(g=-e[f],v=h(g))),r>c&&v>d||f>=i?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>c&&i>f;)v>d?(a=p,c+=1,r>c&&(p=t[c],d=h(p))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>c;)a=p,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,c+=1,r>c&&(p=t[c]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[u++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=-e[f]);return M&&(l[u++]=M),T&&(l[u++]=T),u||(l[u++]=0),l.length=u,l}e.exports=i},{}],365:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],366:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],367:[function(t,e,r){"use strict";function n(t){var e=x(t),r=b(y(e),t);return 0>r?[e,w(e,1/0)]:r>0?[w(e,-(1/0)),e]:[e,e]}function i(t,e){for(var r=new Array(e.length),n=0;n=t.length)return o[e-t.length];var r=t[e];return[y(r[0]),y(r[1])]}for(var o=[],s=0;s=0;--s){var g=n[s],u=g[0],v=e[u],m=v[0],x=v[1],w=t[m],A=t[x];if((w[0]-A[0]||w[1]-A[1])<0){var M=m;m=x,x=M}v[0]=m;var T,E=v[1]=g[1];for(i&&(T=v[2]);s>0&&n[s-1][0]===u;){var g=n[--s],L=g[1];i?e.push([E,L,T]):e.push([E,L]),E=L}i?e.push([E,x,T]):e.push([E,x])}return o}function u(t,e,r){for(var i=t.length+e.length,a=new g(i),o=r,s=0;ss;++s){var d=a.find(s);d===s?(p[s]=f,t[f++]=t[s]):(h=!1,p[s]=-1)}if(t.length=f,h)return null;for(var s=0;i>s;++s)p[s]<0&&(p[s]=p[a.find(s)]);return p}function c(t,e){return t[0]-e[0]||t[1]-e[1]}function f(t,e){var r=t[0]-e[0]||t[1]-e[1];return r?r:t[2]e[2]?1:0}function h(t,e,r){if(0!==t.length){if(e)for(var n=0;n0||p.length>0}function d(t,e,r){var n,i=!1;if(r){n=e;for(var a=new Array(e.length),o=0;o0?r=r.shln(f):0>f&&(c=c.shln(-f)),l(r,c)}var i=t("./is-rat"),a=t("./lib/is-bn"),o=t("./lib/num-to-bn"),s=t("./lib/str-to-bn"),l=t("./lib/rationalize"),u=t("./div");e.exports=n},{"./div":371,"./is-rat":373,"./lib/is-bn":377,"./lib/num-to-bn":378,"./lib/rationalize":379,"./lib/str-to-bn":380}],373:[function(t,e,r){"use strict";function n(t){return Array.isArray(t)&&2===t.length&&i(t[0])&&i(t[1])}var i=t("./lib/is-bn");e.exports=n},{"./lib/is-bn":377}],374:[function(t,e,r){"use strict";function n(t){return t.cmp(new i(0))}var i=t("bn.js");e.exports=n},{"bn.js":383}],375:[function(t,e,r){"use strict";function n(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var n=0,i=0;e>i;i++){var a=r[i];n+=a*Math.pow(67108864,i)}return t.sign?-n:n}e.exports=n},{}],376:[function(t,e,r){"use strict";function n(t){var e=a(i.lo(t));if(32>e)return e;var r=a(i.hi(t));return r>20?52:r+32}var i=t("double-bits"),a=t("bit-twiddle").countTrailingZeros;e.exports=n},{"bit-twiddle":382,"double-bits":384}],377:[function(t,e,r){"use strict";function n(t){return t&&"object"==typeof t&&Boolean(t.words)}t("bn.js");e.exports=n},{"bn.js":383}],378:[function(t,e,r){"use strict";function n(t){var e=a.exponent(t);return 52>e?new i(t):new i(t*Math.pow(2,52-e)).shln(e-52)}var i=t("bn.js"),a=t("double-bits");e.exports=n},{"bn.js":383,"double-bits":384}],379:[function(t,e,r){"use strict";function n(t,e){var r=a(t),n=a(e);if(0===r)return[i(0),i(1)];if(0===n)return[i(0),i(0)];0>n&&(t=t.neg(),e=e.neg());var o=t.gcd(e);return o.cmpn(1)?[t.div(o),e.div(o)]:[t,e]}var i=t("./num-to-bn"),a=t("./bn-sign");e.exports=n},{"./bn-sign":374,"./num-to-bn":378}],380:[function(t,e,r){"use strict";function n(t){return new i(t)}var i=t("bn.js");e.exports=n},{"bn.js":383}],381:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[0]),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":379}],382:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],383:[function(t,e,r){!function(t,e){"use strict";function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){return null!==t&&"object"==typeof t&&Array.isArray(t.words)?t:(this.sign=!1,this.words=null,this.length=0,this.red=null,"le"!==e&&"be"!==e||(r=e,e=10),void(null!==t&&this._init(t||0,e||10,r||"be")))}function a(t,e,r){for(var n=0,i=Math.min(t.length,r),a=e;i>a;a++){var o=t.charCodeAt(a)-48;n<<=4,n|=o>=49&&54>=o?o-49+10:o>=17&&22>=o?o-17+10:15&o}return n}function o(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;a>o;o++){var s=t.charCodeAt(o)-48;i*=n,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}function s(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).ishln(this.n).isub(this.p),this.tmp=this._tmp()}function l(){s.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function u(){s.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function c(){s.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function f(){s.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function h(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else this.m=t,this.prime=null}function p(t){h.call(this,t),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).ishln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv.sign=!0,this.minv=this.minv.mod(this.r)}"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26,i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&36>=e),t=t.toString().replace(/\s+/g,"");var i=0;"-"===t[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.sign=!0),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){0>t&&(this.sign=!0,t=-t),67108864>t?(this.words=[67108863&t],this.length=1):4503599627370496>t?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(9007199254740992>t),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3){var s=t[i]|t[i-1]<<8|t[i-2]<<16;this.words[o]|=s<>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}else if("le"===n)for(var i=0,o=0;i>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6){var o=a(t,r,r+6);this.words[i]|=o<>>26-n&4194303,n+=24,n>=26&&(n-=26,i++)}if(r+6!==e){var o=a(t,e,r+6);this.words[i]|=o<>>26-n&4194303}this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;67108863>=i;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,s=a%n,l=Math.min(a,a-s)+r,u=0,c=r;l>c;c+=n)u=o(t,c,c+n,e),this.imuln(i),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u);if(0!==s){for(var f=1,u=o(t,c,t.length,e),c=0;s>c;c++)f*=e;this.imuln(f),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u)}},i.prototype.copy=function(t){t.words=new Array(this.length);for(var e=0;e1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.sign=!1),this},i.prototype.inspect=function(){return(this.red?""};var d=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],v=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(t,e){if(t=t||10,16===t||"hex"===t){for(var n="",i=0,e=0|e||1,a=0,o=0;o>>24-i&16777215,n=0!==a||o!==this.length-1?d[6-l.length]+l+n:l+n,i+=2,i>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!==0;)n="0"+n;return this.sign&&(n="-"+n),n}if(t===(0|t)&&t>=2&&36>=t){var u=g[t],c=v[t],n="",f=this.clone();for(f.sign=!1;0!==f.cmpn(0);){var h=f.modn(c).toString(t);f=f.idivn(c),n=0!==f.cmpn(0)?d[u-h.length]+h+n:h+n}return 0===this.cmpn(0)&&(n="0"+n),this.sign&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toArray=function(t){this.strip();var e=new Array(this.byteLength());e[0]=0;var r=this.clone();if("le"!==t)for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[e.length-n-1]=i}else for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[n]=i}return e},Math.clz32?i.prototype._countBits=function(t){return 32-Math.clz32(t)}:i.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0===(8191&e)&&(r+=13,e>>>=13),0===(127&e)&&(r+=7,e>>>=7),0===(15&e)&&(r+=4,e>>>=4),0===(3&e)&&(r+=2,e>>>=2),0===(1&e)&&r++,r},i.prototype.bitLength=function(){var t=0,e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(0===this.cmpn(0))return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.iand=function(t){this.sign=this.sign&&t.sign;var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.ixor=function(t){this.sign=this.sign||t.sign;var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);for(var n=t/26|0,i=t%26;this.length<=n;)this.words[this.length++]=0;return e?this.words[n]=this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26}for(;0!==i&&a>>26}if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(t.sign){t.sign=!1;var e=this.iadd(t);return t.sign=!0,e._normSign()}if(this.sign)return this.sign=!1,this.iadd(t),this.sign=!0,this._normSign();var r=this.cmp(t);if(0===r)return this.sign=!1,this.length=1,this.words[0]=0,this;var n,i;r>0?(n=this,i=t):(n=t,i=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e}for(;0!==a&&o>26,this.words[o]=67108863&e}if(0===a&&o>>26,a=67108863&r,o=Math.min(n,t.length-1),s=Math.max(0,n-this.length+1);o>=s;s++){var l=n-s,u=0|this.words[l],c=0|t.words[s],f=u*c,h=67108863&f;i=i+(f/67108864|0)|0,h=h+a|0,a=67108863&h,i=i+(h>>>26)|0}e.words[n]=a,r=i}return 0!==r?e.words[n]=r:e.length--,e.strip()},i.prototype._bigMulTo=function(t,e){e.sign=t.sign!==this.sign,e.length=this.length+t.length;for(var r=0,n=0,i=0;i=l;l++){var u=i-l,c=0|this.words[u],f=0|t.words[l],h=c*f,p=67108863&h;a=a+(h/67108864|0)|0,p=p+o|0,o=67108863&p,a=a+(p>>>26)|0,n+=a>>>26,a&=67108863}e.words[i]=o,r=a,a=n}return 0!==r?e.words[i]=r:e.length--,e.strip()},i.prototype.mulTo=function(t,e){var r;return r=this.length+t.length<63?this._smallMulTo(t,e):this._bigMulTo(t,e)},i.prototype.mul=function(t){var e=new i(null);return e.words=new Array(this.length+t.length),this.mulTo(t,e)},i.prototype.imul=function(t){if(0===this.cmpn(0)||0===t.cmpn(0))return this.words[0]=0,this.length=1,this;var e=this.length,r=t.length;this.sign=t.sign!==this.sign,this.length=this.length+t.length,this.words[this.length-1]=0;for(var n=this.length-2;n>=0;n--){for(var i=0,a=0,o=Math.min(n,r-1),s=Math.max(0,n-e+1);o>=s;s++){var l=n-s,u=this.words[l],c=t.words[s],f=u*c,h=67108863&f;i+=f/67108864|0,h+=a,a=67108863&h,i+=h>>>26}this.words[n]=a,this.words[n+1]+=i,i=0}for(var i=0,l=1;l>>26}return this.strip()},i.prototype.imuln=function(t){r("number"==typeof t);for(var e=0,n=0;n>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.mul(this)},i.prototype.ishln=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=67108863>>>26-e<<26-e;if(0!==e){for(var a=0,o=0;o>>26-e}a&&(this.words[o]=a,this.length++)}if(0!==n){for(var o=this.length-1;o>=0;o--)this.words[o+n]=this.words[o];for(var o=0;n>o;o++)this.words[o]=0;this.length+=n}return this.strip()},i.prototype.ishrn=function(t,e,n){r("number"==typeof t&&t>=0);var i;i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<u;u++)l.words[u]=this.words[u];l.length=o}if(0===o);else if(this.length>o){this.length-=o;for(var u=0;u=0&&(0!==c||u>=i);u--){var f=this.words[u];this.words[u]=c<<26-a|f>>>a,c=f&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip(),this},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(!this.sign,"imaskn works only with positive numbers"),0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<t?this.isubn(-t):this.sign?1===this.length&&this.words[0]=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),0>t)return this.iaddn(-t);if(this.sign)return this.sign=!1,this.iaddn(t),this.sign=!0,this;this.words[0]-=t;for(var e=0;e>26)-(u/67108864|0),this.words[i+n]=67108863&l}for(;i>26,this.words[i+n]=67108863&l}if(0===s)return this.strip();r(-1===s),s=0;for(var i=0;i>26,this.words[i]=67108863&l}return this.sign=!0,this.strip()},i.prototype._wordDiv=function(t,e){var r=this.length-t.length,n=this.clone(),a=t,o=a.words[a.length-1],s=this._countBits(o);r=26-s,0!==r&&(a=a.shln(r),n.ishln(r),o=a.words[a.length-1]);var l,u=n.length-a.length;if("mod"!==e){l=new i(null),l.length=u+1,l.words=new Array(l.length);for(var c=0;c=0;h--){var p=67108864*n.words[a.length+h]+n.words[a.length+h-1];for(p=Math.min(p/o|0,67108863),n._ishlnsubmul(a,p,h);n.sign;)p--,n.sign=!1,n._ishlnsubmul(a,1,h),0!==n.cmpn(0)&&(n.sign=!n.sign);l&&(l.words[h]=p)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.ishrn(r),{div:l?l:null,mod:n}},i.prototype.divmod=function(t,e){if(r(0!==t.cmpn(0)),this.sign&&!t.sign){var n,a,o=this.neg().divmod(t,e);return"mod"!==e&&(n=o.div.neg()),"div"!==e&&(a=0===o.mod.cmpn(0)?o.mod:t.sub(o.mod)),{div:n,mod:a}}if(!this.sign&&t.sign){var n,o=this.divmod(t.neg(),e);return"mod"!==e&&(n=o.div.neg()),{div:n,mod:o.mod}}return this.sign&&t.sign?this.neg().divmod(t.neg(),e):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e)},i.prototype.div=function(t){return this.divmod(t,"div").div},i.prototype.mod=function(t){return this.divmod(t,"mod").mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(0===e.mod.cmpn(0))return e.div;var r=e.div.sign?e.mod.isub(t):e.mod,n=t.shrn(1),i=t.andln(1),a=r.cmp(n);return 0>a||1===i&&0===a?e.div:e.div.sign?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(67108863>=t);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+this.words[i])%t;return n},i.prototype.idivn=function(t){r(67108863>=t);for(var e=0,n=this.length-1;n>=0;n--){var i=this.words[n]+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.ishrn(1),n.ishrn(1),++u;for(var c=n.clone(),f=e.clone();0!==e.cmpn(0);){for(;e.isEven();)e.ishrn(1),a.isEven()&&o.isEven()?(a.ishrn(1),o.ishrn(1)):(a.iadd(c).ishrn(1),o.isub(f).ishrn(1));for(;n.isEven();)n.ishrn(1),s.isEven()&&l.isEven()?(s.ishrn(1),l.ishrn(1)):(s.iadd(c).ishrn(1),l.isub(f).ishrn(1));e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.ishln(u)}},i.prototype._invmp=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(;e.isEven();)e.ishrn(1),a.isEven()?a.ishrn(1):a.iadd(s).ishrn(1);for(;n.isEven();)n.ishrn(1),o.isEven()?o.ishrn(1):o.iadd(s).ishrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(o)):(n.isub(e),o.isub(a))}return 0===e.cmpn(1)?a:o},i.prototype.gcd=function(t){if(0===this.cmpn(0))return t.clone();if(0===t.cmpn(0))return this.clone();var e=this.clone(),r=t.clone();e.sign=!1,r.sign=!1;for(var n=0;e.isEven()&&r.isEven();n++)e.ishrn(1),r.ishrn(1);for(;;){for(;e.isEven();)e.ishrn(1);for(;r.isEven();)r.ishrn(1);var i=e.cmp(r);if(0>i){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.ishln(n)},i.prototype.invm=function(t){return this.egcd(t).a.mod(t)},i.prototype.isEven=function(){return 0===(1&this.words[0])},i.prototype.isOdd=function(){ -return 1===(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<a;a++)this.words[a]=0;return this.words[n]|=i,this.length=n+1,this}for(var o=i,a=n;0!==o&&a>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},i.prototype.cmpn=function(t){var e=0>t;if(e&&(t=-t),this.sign&&!e)return-1;if(!this.sign&&e)return 1;t&=67108863,this.strip();var r;if(this.length>1)r=1;else{var n=this.words[0];r=n===t?0:t>n?-1:1}return this.sign&&(r=-r),r},i.prototype.cmp=function(t){if(this.sign&&!t.sign)return-1;if(!this.sign&&t.sign)return 1;var e=this.ucmp(t);return this.sign?-e:e},i.prototype.ucmp=function(t){if(this.length>t.length)return 1;if(this.length=0;r--){var n=this.words[r],i=t.words[r];if(n!==i){i>n?e=-1:n>i&&(e=1);break}}return e},i.red=function(t){return new h(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(!this.sign,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};s.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},s.prototype.ireduce=function(t){var e,r=t;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength();while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},s.prototype.split=function(t,e){t.ishrn(this.n,0,e)},s.prototype.imulK=function(t){return t.imul(this.k)},n(l,s),l.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;n>i;i++)e.words[i]=t.words[i];if(e.length=n,t.length<=9)return t.words[0]=0,void(t.length=1);var a=t.words[9];e.words[e.length++]=a&r;for(var i=10;i>>22,a=o}t.words[i-10]=a>>>22,t.length-=9},l.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e,r=0,n=0;n>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function y(t){if(m[t])return m[t];var y;if("k256"===t)y=new l;else if("p224"===t)y=new u;else if("p192"===t)y=new c;else{if("p25519"!==t)throw new Error("Unknown prime "+t);y=new f}return m[t]=y,y},h.prototype._verify1=function(t){r(!t.sign,"red works only with positives"),r(t.red,"red works only with red numbers")},h.prototype._verify2=function(t,e){r(!t.sign&&!e.sign,"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},h.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.mod(this.m)._forceRed(this)},h.prototype.neg=function(t){var e=t.clone();return e.sign=!e.sign,e.iadd(this.m)._forceRed(this)},h.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},h.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},h.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},h.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},h.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.shln(e))},h.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},h.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},h.prototype.isqr=function(t){return this.imul(t,t)},h.prototype.sqr=function(t){return this.mul(t,t)},h.prototype.sqrt=function(t){if(0===t.cmpn(0))return t.clone();var e=this.m.andln(3);if(r(e%2===1),3===e){var n=this.m.add(new i(1)).ishrn(2),a=this.pow(t,n);return a}for(var o=this.m.subn(1),s=0;0!==o.cmpn(0)&&0===o.andln(1);)s++,o.ishrn(1);r(0!==o.cmpn(0));var l=new i(1).toRed(this),u=l.redNeg(),c=this.m.subn(1).ishrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,c).cmp(u);)f.redIAdd(u);for(var h=this.pow(f,o),a=this.pow(t,o.addn(1).ishrn(1)),p=this.pow(t,o),d=s;0!==p.cmp(l);){for(var g=p,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(d>v);var m=this.pow(h,new i(1).ishln(d-v-1));a=a.redMul(m),h=m.redSqr(),p=p.redMul(h),d=v}return a},h.prototype.invm=function(t){var e=t._invmp(this.m);return e.sign?(e.sign=!1,this.imod(e).redNeg()):this.imod(e)},h.prototype.pow=function(t,e){var r=[];if(0===e.cmpn(0))return new i(1);for(var n=e.clone();0!==n.cmpn(0);)r.push(n.andln(1)),n.ishrn(1);for(var a=t,o=0;o=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},p.prototype.mul=function(t,e){if(0===t.cmpn(0)||0===e.cmpn(0))return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).ishrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},p.prototype.invm=function(t){var e=this.imod(t._invmp(this.m).mul(this.r2));return e._forceRed(this)}}("undefined"==typeof e||e,this)},{}],384:[function(t,e,r){(function(t){function r(t,e){return p[0]=t,p[1]=e,h[0]}function n(t){return h[0]=t,p[0]}function i(t){return h[0]=t,p[1]}function a(t,e){return p[1]=t,p[0]=e,h[0]}function o(t){return h[0]=t,p[1]}function s(t){return h[0]=t,p[0]}function l(t,e){return d.writeUInt32LE(t,0,!0),d.writeUInt32LE(e,4,!0),d.readDoubleLE(0,!0)}function u(t){return d.writeDoubleLE(t,0,!0),d.readUInt32LE(0,!0)}function c(t){return d.writeDoubleLE(t,0,!0),d.readUInt32LE(4,!0)}var f=!1;if("undefined"!=typeof Float64Array){var h=new Float64Array(1),p=new Uint32Array(h.buffer);h[0]=1,f=!0,1072693248===p[1]?(e.exports=function(t){return h[0]=t,[p[0],p[1]]},e.exports.pack=r,e.exports.lo=n,e.exports.hi=i):1072693248===p[0]?(e.exports=function(t){return h[0]=t,[p[1],p[0]]},e.exports.pack=a,e.exports.lo=o,e.exports.hi=s):f=!1}if(!f){var d=new t(8);e.exports=function(t){return d.writeDoubleLE(t,0,!0),[d.readUInt32LE(0,!0),d.readUInt32LE(4,!0)]},e.exports.pack=l,e.exports.lo=u,e.exports.hi=c}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){var r=e.exports.hi(t);return(r<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){var r=e.exports.hi(t);return!(2146435072&r)}}).call(this,t("buffer").Buffer)},{buffer:65}],385:[function(t,e,r){"use strict";function n(t){return i(t[0])*i(t[1])}var i=t("./lib/bn-sign");e.exports=n},{"./lib/bn-sign":374}],386:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":379}],387:[function(t,e,r){"use strict";function n(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.divmod(r),o=n.div,s=i(o),l=n.mod;if(0===l.cmpn(0))return s;if(s){var u=a(s)+4,c=i(l.shln(u).divRound(r));return 0>s&&(c=-c),s+c*Math.pow(2,-u)}var f=r.bitLength()-l.bitLength()+53,c=i(l.shln(f).divRound(r));return 1023>f?c*Math.pow(2,-f):(c*=Math.pow(2,-1023),c*Math.pow(2,1023-f))}var i=t("./lib/bn-to-num"),a=t("./lib/ctz");e.exports=n},{"./lib/bn-to-num":375,"./lib/ctz":376}],388:[function(t,e,r){"use strict";function n(t,e){for(var r=0;t>r;++r)if(!(e[r]<=e[r+t]))return!0;return!1}function i(t,e,r,i){for(var a=0,o=0,s=0,l=t.length;l>s;++s){var u=t[s];if(!n(e,u)){for(var c=0;2*e>c;++c)r[a++]=u[c];i[o++]=s}}return o}function a(t,e,r,n){var a=t.length,o=e.length;if(!(0>=a||0>=o)){var s=t[0].length>>>1;if(!(0>=s)){var l,u=f.mallocDouble(2*s*a),c=f.mallocInt32(a);if(a=i(t,s,u,c),a>0){if(1===s&&n)h.init(a),l=h.sweepComplete(s,r,0,a,u,c,0,a,u,c);else{var d=f.mallocDouble(2*s*o),g=f.mallocInt32(o);o=i(e,s,d,g),o>0&&(h.init(a+o),l=1===s?h.sweepBipartite(s,r,0,a,u,c,0,o,d,g):p(s,r,n,a,u,c,o,d,g),f.free(d),f.free(g))}f.free(u),f.free(c)}return l}}}function o(t,e){c.push([t,e])}function s(t){return c=[],a(t,t,o,!0),c}function l(t,e){return c=[],a(t,e,o,!1),c}function u(t,e,r){switch(arguments.length){case 1:return s(t);case 2:return"function"==typeof e?a(t,t,e,!0):l(t,e);case 3:return a(t,e,r,!1);default:throw new Error("box-intersect: Invalid arguments")}}e.exports=u;var c,f=t("typedarray-pool"),h=t("./lib/sweep"),p=t("./lib/intersect")},{"./lib/intersect":390,"./lib/sweep":394,"typedarray-pool":397}],389:[function(t,e,r){"use strict";function n(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",w.join(),"){","var ",u,"=2*",a,";"],l="for(var i="+c+","+d+"="+u+"*"+c+";i<"+f+";++i,"+d+"+="+u+"){var x0="+h+"["+o+"+"+d+"],x1="+h+"["+o+"+"+d+"+"+a+"],xi="+p+"[i];",k="for(var j="+g+","+b+"="+u+"*"+g+";j<"+v+";++j,"+b+"+="+u+"){var y0="+m+"["+o+"+"+b+"],"+(r?"y1="+m+"["+o+"+"+b+"+"+a+"],":"")+"yi="+y+"[j];";return t?i.push(l,_,":",k):i.push(k,_,":",l),r?i.push("if(y1"+v+"-"+g+"){"),t?(e(!0,!1),o.push("}else{"),e(!1,!1)):(o.push("if("+l+"){"),e(!0,!0),o.push("}else{"),e(!0,!1),o.push("}}else{if("+l+"){"),e(!1,!0),o.push("}else{"),e(!1,!1),o.push("}")),o.push("}}return "+r);var s=i.join("")+o.join(""),u=new Function(s);return u()}var a="d",o="ax",s="vv",l="fp",u="es",c="rs",f="re",h="rb",p="ri",d="rp",g="bs",v="be",m="bb",y="bi",b="bp",x="rv",_="Q",w=[a,o,s,c,f,h,p,g,v,m,y];r.partial=i(!1),r.full=i(!0)},{}],390:[function(t,e,r){"use strict";function n(t,e){var r=8*u.log2(e+1)*(t+1)|0,n=u.nextPow2(M*r);L.lengthS&&(l.free(S),S=l.mallocDouble(i))}function i(t,e,r,n,i,a,o,s,l){var u=M*t;L[u]=e,L[u+1]=r,L[u+2]=n,L[u+3]=i,L[u+4]=a,L[u+5]=o;var c=T*t;S[c]=s,S[c+1]=l}function a(t,e,r,n,i,a,o,s,l,u,c){var f=2*t,h=l*f,p=u[h+e];t:for(var d=i,g=i*f;a>d;++d,g+=f){var v=o[g+e],m=o[g+e+t];if(!(v>p||p>m||n&&p===v)){for(var y=s[d],b=e+1;t>b;++b){var v=o[g+b],m=o[g+b+t],x=u[h+b],_=u[h+b+t];if(x>m||v>_)continue t}var w;if(w=n?r(c,y):r(y,c),void 0!==w)return w}}}function o(t,e,r,n,i,a,o,s,l,u){var c=2*t,f=s*c,h=l[f+e];t:for(var p=n,d=n*c;i>p;++p,d+=c){var g=o[p];if(g!==u){var v=a[d+e],m=a[d+e+t];if(!(v>h||h>m)){for(var y=e+1;t>y;++y){var v=a[d+y],m=a[d+y+t],b=l[f+y],x=l[f+y+t];if(b>m||v>x)continue t}var _=r(g,u);if(void 0!==_)return _}}}}function s(t,e,r,s,l,u,c,g,E){n(t,s+c);var C,z=0,P=2*t;for(i(z++,0,0,s,0,c,r?16:0,-(1/0),1/0),r||i(z++,0,0,c,0,s,1,-(1/0),1/0);z>0;){z-=1;var R=z*M,j=L[R],O=L[R+1],I=L[R+2],N=L[R+3],F=L[R+4],D=L[R+5],B=z*T,U=S[B],V=S[B+1],q=1&D,G=!!(16&D),H=l,Y=u,X=g,W=E;if(q&&(H=g,Y=E,X=l,W=u),!(2&D&&(I=_(t,j,O,I,H,Y,V),O>=I)||4&D&&(O=w(t,j,O,I,H,Y,U),O>=I))){var Z=I-O,K=F-N;if(G){if(y>t*Z*(Z+K)){if(C=p.scanComplete(t,j,e,O,I,H,Y,N,F,X,W),void 0!==C)return C;continue}}else{if(t*Math.min(Z,K)t*Z*K){if(C=p.scanBipartite(t,j,e,q,O,I,H,Y,N,F,X,W),void 0!==C)return C;continue}}var $=b(t,j,O,I,H,Y,U,V);if($>O)if(v>t*($-O)){if(C=h(t,j+1,e,O,$,H,Y,N,F,X,W),void 0!==C)return C}else if(j===t-2){if(C=q?p.sweepBipartite(t,e,N,F,X,W,O,$,H,Y):p.sweepBipartite(t,e,O,$,H,Y,N,F,X,W),void 0!==C)return C}else i(z++,j+1,O,$,N,F,q,-(1/0),1/0),i(z++,j+1,N,F,O,$,1^q,-(1/0),1/0);if(I>$){var Q=d(t,j,N,F,X,W),J=X[P*Q+j],tt=x(t,j,Q,F,X,W,J);if(F>tt&&i(z++,j,$,I,tt,F,(4|q)+(G?16:0),J,V),Q>N&&i(z++,j,$,I,N,Q,(2|q)+(G?16:0),U,J),Q+1===tt){if(C=G?o(t,j,e,$,I,H,Y,Q,X,W[Q]):a(t,j,e,q,$,I,H,Y,Q,X,W[Q]),void 0!==C)return C}else if(tt>Q){var et;if(G){if(et=k(t,j,$,I,H,Y,J),et>$){var rt=x(t,j,$,et,H,Y,J);if(j===t-2){if(rt>$&&(C=p.sweepComplete(t,e,$,rt,H,Y,Q,tt,X,W),void 0!==C))return C;if(et>rt&&(C=p.sweepBipartite(t,e,rt,et,H,Y,Q,tt,X,W),void 0!==C))return C}else rt>$&&i(z++,j+1,$,rt,Q,tt,16,-(1/0),1/0),et>rt&&(i(z++,j+1,rt,et,Q,tt,0,-(1/0),1/0),i(z++,j+1,Q,tt,rt,et,1,-(1/0),1/0))}}else et=q?A(t,j,$,I,H,Y,J):k(t,j,$,I,H,Y,J),et>$&&(j===t-2?C=q?p.sweepBipartite(t,e,Q,tt,X,W,$,et,H,Y):p.sweepBipartite(t,e,$,et,H,Y,Q,tt,X,W):(i(z++,j+1,$,et,Q,tt,q,-(1/0),1/0),i(z++,j+1,Q,tt,$,et,1^q,-(1/0),1/0)))}}}}}e.exports=s;var l=t("typedarray-pool"),u=t("bit-twiddle"),c=t("./brute"),f=c.partial,h=c.full,p=t("./sweep"),d=t("./median"),g=t("./partition"),v=128,m=1<<22,y=1<<22,b=g("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]),x=g("lo===p0",["p0"]),_=g("lol;++l,s+=o)for(var u=i[s],c=l,f=o*(l-1);c>r&&i[f+e]>u;--c,f-=o){for(var h=f,p=f+o,d=0;o>d;++d,++h,++p){var g=i[h];i[h]=i[p],i[p]=g}var v=a[c];a[c]=a[c-1],a[c-1]=v}}function i(t,e,r,i,a,l){if(r+1>=i)return r;for(var u=r,c=i,f=i+r>>>1,h=2*t,p=f,d=a[h*f+e];c>u;){if(s>c-u){n(t,e,u,c,a,l),d=a[h*f+e];break}var g=c-u,v=Math.random()*g+u|0,m=a[h*v+e],y=Math.random()*g+u|0,b=a[h*y+e],x=Math.random()*g+u|0,_=a[h*x+e];b>=m?_>=b?(p=y,d=b):m>=_?(p=v,d=m):(p=x,d=_):b>=_?(p=y,d=b):_>=m?(p=v,d=m):(p=x,d=_);for(var w=h*(c-1),k=h*p,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[c-1];l[c-1]=l[p],l[p]=T,p=o(t,e,u,c-1,a,l,d);for(var w=h*(c-1),k=h*p,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[c-1];if(l[c-1]=l[p],l[p]=T,p>f){for(c=p-1;c>u&&a[h*(c-1)+e]===d;)c-=1;c+=1}else{if(!(f>p))break;for(u=p+1;c>u&&a[h*u+e]===d;)u+=1}}return o(t,e,r,f,a,l,a[h*f+e])}e.exports=i;var a=t("./partition"),o=a("lo=0&&n.push("lo=e[k+n]"),t.indexOf("hi")>=0&&n.push("hi=e[k+o]"),r.push(i.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)}e.exports=n;var i="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],393:[function(t,e,r){"use strict";function n(t,e){4*h>=e?i(0,e-1,t):f(0,e-1,t)}function i(t,e,r){for(var n=2*(t+1),i=t+1;e>=i;++i){for(var a=r[n++],o=r[n++],s=i,l=n-2;s-- >t;){var u=r[l-2],c=r[l-1];if(a>u)break;if(u===a&&o>c)break;r[l]=u,r[l+1]=c,l-=2}r[l]=a,r[l+1]=o}}function a(t,e,r){t*=2,e*=2;var n=r[t],i=r[t+1];r[t]=r[e],r[t+1]=r[e+1],r[e]=n,r[e+1]=i}function o(t,e,r){t*=2,e*=2,r[t]=r[e],r[t+1]=r[e+1]}function s(t,e,r,n){t*=2,e*=2,r*=2;var i=n[t],a=n[t+1];n[t]=n[e],n[t+1]=n[e+1],n[e]=n[r],n[e+1]=n[r+1],n[r]=i,n[r+1]=a}function l(t,e,r,n,i){t*=2,e*=2,i[t]=i[e],i[e]=r,i[t+1]=i[e+1],i[e+1]=n}function u(t,e,r){t*=2,e*=2;var n=r[t],i=r[e];return i>n?!1:n===i?r[t+1]>r[e+1]:!0}function c(t,e,r,n){t*=2;var i=n[t];return e>i?!0:i===e?n[t+1]>1,v=g-n,m=g+n,y=p,b=v,x=g,_=m,w=d,k=t+1,A=e-1,M=0;u(y,b,r)&&(M=y,y=b,b=M),u(_,w,r)&&(M=_,_=w,w=M),u(y,x,r)&&(M=y,y=x,x=M),u(b,x,r)&&(M=b,b=x,x=M),u(y,_,r)&&(M=y,y=_,_=M),u(x,_,r)&&(M=x,x=_,_=M),u(b,w,r)&&(M=b,b=w,w=M),u(b,x,r)&&(M=b,b=x,x=M),u(_,w,r)&&(M=_,_=w,w=M);for(var T=r[2*b],E=r[2*b+1],L=r[2*_],S=r[2*_+1],C=2*y,z=2*x,P=2*w,R=2*p,j=2*g,O=2*d,I=0;2>I;++I){var N=r[C+I],F=r[z+I],D=r[P+I];r[R+I]=N,r[j+I]=F,r[O+I]=D}o(v,t,r),o(m,e,r);for(var B=k;A>=B;++B)if(c(B,T,E,r))B!==k&&a(B,k,r),++k;else if(!c(B,L,S,r))for(;;){if(c(A,L,S,r)){c(A,T,E,r)?(s(B,k,A,r),++k,--A):(a(B,A,r),--A);break}if(--A=k-2-t?i(t,k-2,r):f(t,k-2,r),h>=e-(A+2)?i(A+2,e,r):f(A+2,e,r),h>=A-k?i(k,A,r):f(k,A,r)}e.exports=n;var h=32},{}],394:[function(t,e,r){"use strict";function n(t){var e=f.nextPow2(t);g.lengthk;++k){var A=s[k],M=b*k;_[d++]=o[M+x],_[d++]=-(A+1),_[d++]=o[M+w],_[d++]=A}for(var k=l;u>k;++k){var A=f[k]+p,T=b*k;_[d++]=c[T+x],_[d++]=-A,_[d++]=c[T+w],_[d++]=A}var E=d>>>1;h(_,E);for(var L=0,S=0,k=0;E>k;++k){var C=0|_[2*k+1];if(C>=p)C=C-p|0,i(m,y,S--,C);else if(C>=0)i(g,v,L--,C);else if(-p>=C){C=-C-p|0;for(var z=0;L>z;++z){var P=e(g[z],C);if(void 0!==P)return P}a(m,y,S++,C)}else{C=-C-1|0;for(var z=0;S>z;++z){var P=e(C,m[z]);if(void 0!==P)return P}a(g,v,L++,C)}}}function s(t,e,r,n,o,s,l,u,c,f){for(var p=0,d=2*t,w=t-1,k=d-1,A=r;n>A;++A){var M=s[A]+1<<1,T=d*A;_[p++]=o[T+w],_[p++]=-M,_[p++]=o[T+k],_[p++]=M}for(var A=l;u>A;++A){var M=f[A]+1<<1,E=d*A;_[p++]=c[E+w],_[p++]=1|-M,_[p++]=c[E+k],_[p++]=1|M}var L=p>>>1;h(_,L);for(var S=0,C=0,z=0,A=0;L>A;++A){var P=0|_[2*A+1],R=1&P;if(L-1>A&&P>>1===_[2*A+3]>>1&&(R=2,A+=1),0>P){for(var j=-(P>>1)-1,O=0;z>O;++O){var I=e(b[O],j);if(void 0!==I)return I}if(0!==R)for(var O=0;S>O;++O){var I=e(g[O],j);if(void 0!==I)return I}if(1!==R)for(var O=0;C>O;++O){var I=e(m[O],j);if(void 0!==I)return I}0===R?a(g,v,S++,j):1===R?a(m,y,C++,j):2===R&&a(b,x,z++,j)}else{var j=(P>>1)-1;0===R?i(g,v,S--,j):1===R?i(m,y,C--,j):2===R&&i(b,x,z--,j)}}}function l(t,e,r,n,o,s,l,u,c,f,d,m){var y=0,b=2*t,x=e,w=e+t,k=1,A=1;n?A=p:k=p;for(var M=o;s>M;++M){var T=M+k,E=b*M;_[y++]=l[E+x],_[y++]=-T,_[y++]=l[E+w],_[y++]=T}for(var M=c;f>M;++M){var T=M+A,L=b*M;_[y++]=d[L+x],_[y++]=-T}var S=y>>>1;h(_,S);for(var C=0,M=0;S>M;++M){var z=0|_[2*M+1];if(0>z){var T=-z,P=!1;if(T>=p?(P=!n,T-=p):(P=!!n,T-=1),P)a(g,v,C++,T);else{var R=m[T],j=b*T,O=d[j+e+1],I=d[j+e+1+t];t:for(var N=0;C>N;++N){var F=g[N],D=b*F;if(!(IB;++B)if(d[j+B+t]y;++y){var b=y+p,x=d*y;_[f++]=a[x+v],_[f++]=-b,_[f++]=a[x+m],_[f++]=b}for(var y=s;l>y;++y){var b=y+1,w=d*y;_[f++]=u[w+v],_[f++]=-b}var k=f>>>1;h(_,k);for(var A=0,y=0;k>y;++y){var M=0|_[2*y+1];if(0>M){var b=-M;if(b>=p)g[A++]=b-p;else{b-=1;var T=c[b],E=d*b,L=u[E+e+1],S=u[E+e+1+t];t:for(var C=0;A>C;++C){var z=g[C],P=o[z];if(P===T)break;var R=d*z;if(!(Sj;++j)if(u[E+j+t]=0;--C)if(g[C]===b){for(var j=C+1;A>j;++j)g[j-1]=g[j];break}--A}}}e.exports={init:n,sweepBipartite:o,sweepComplete:s,scanBipartite:l,scanComplete:u};var c=t("typedarray-pool"),f=t("bit-twiddle"),h=t("./sort"),p=1<<28,d=1024,g=c.mallocInt32(d),v=c.mallocInt32(d),m=c.mallocInt32(d),y=c.mallocInt32(d),b=c.mallocInt32(d),x=c.mallocInt32(d),_=c.mallocDouble(8*d)},{"./sort":393,"bit-twiddle":395,"typedarray-pool":397}],395:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],396:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],397:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":395,buffer:65,dup:122}],398:[function(t,e,r){arguments[4][61][0].apply(r,arguments)},{dup:61}],399:[function(t,e,r){"use strict";function n(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return 0>e?-a:a;var r=i.hi(t),n=i.lo(t);return e>t==t>0?n===o?(r+=1,n=0):n+=1:0===n?(n=o,r-=1):n-=1,i.pack(n,r)}var i=t("double-bits"),a=Math.pow(2,-1074),o=-1>>>0;e.exports=n},{"double-bits":400}],400:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],401:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/add");e.exports=n},{"big-rat/add":369}],402:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t.length),r=0;rs;++s)o[s]=a(t[s],r);return o}var i=t("big-rat"),a=t("big-rat/mul");e.exports=n},{"big-rat":372,"big-rat/mul":381}],404:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/sub");e.exports=n},{"big-rat/sub":386}],405:[function(t,e,r){"use strict";function n(t,e,r,n){for(var i=0;2>i;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],f=Math.min(u,c),h=Math.max(u,c);if(s>h||f>l)return!1}return!0}function i(t,e,r,i){var o=a(t,r,i),s=a(e,r,i);if(o>0&&s>0||0>o&&0>s)return!1;var l=a(r,t,e),u=a(i,t,e);return l>0&&u>0||0>l&&0>u?!1:0===o&&0===s&&0===l&&0===u?n(t,e,r,i):!0}e.exports=i;var a=t("robust-orientation")[3]},{"robust-orientation":1040}],406:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],407:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t,e.length),n=new Array(e.length),a=new Array(e.length),o=[],s=0;s=l&&o.push(s)}for(;o.length>0;){var u=o.pop();n[u]=!1;for(var c=r[u],s=0;sn;++n){var a=t[n];e=Math.max(e,a[0],a[1])}e=(0|e)+1}e=0|e;for(var o=new Array(e),n=0;e>n;++n)o[n]=[];for(var n=0;r>n;++n){var a=t[n];o[a[0]].push(a[1]),o[a[1]].push(a[0])}for(var s=0;e>s;++s)i(o[s],function(t,e){return t-e});return o}e.exports=n;var i=t("uniq")},{uniq:423}],409:[function(t,e,r){"use strict";function n(t,e){function r(t,e){var r=u[e][t[e]];r.splice(r.indexOf(t),1)}function n(t,n,a){for(var o,s,l,c=0;2>c;++c)if(u[c][n].length>0){o=u[c][n][0],l=c;break}s=o[1^l];for(var f=0;2>f;++f)for(var h=u[f][n],p=0;p0&&(o=d,s=g,l=f)}return a?s:(o&&r(o,l),s)}function a(t,a){var o=u[a][t][0],s=[t];r(o,a);for(var l=o[1^a];;){for(;l!==t;)s.push(l),l=n(s[s.length-2],l,!1);if(u[0][t].length+u[1][t].length===0)break;var c=s[s.length-1],f=t,h=s[1],p=n(c,f,!0);if(i(e[c],e[f],e[h],e[p])<0)break;s.push(t),l=n(c,f)}return s}function o(t,e){return e[1]===e[e.length-1]}for(var s=0|e.length,l=t.length,u=[new Array(s),new Array(s)],c=0;s>c;++c)u[0][c]=[],u[1][c]=[];for(var c=0;l>c;++c){var f=t[c];u[0][f[0]].push(f),u[1][f[1]].push(f)}for(var h=[],c=0;s>c;++c)u[0][c].length+u[1][c].length===0&&h.push([c]);for(var c=0;s>c;++c)for(var p=0;2>p;++p){for(var d=[];u[p][c].length>0;){var g=(u[0][c].length,a(c,p));o(d,g)?d.push.apply(d,g):(d.length>0&&h.push(d),d=g)}d.length>0&&h.push(d)}return h}e.exports=n;var i=t("compare-angle")},{"compare-angle":410}],410:[function(t,e,r){"use strict";function n(t,e,r){var n=s(t[0],-e[0]),i=s(t[1],-e[1]),a=s(r[0],-e[0]),o=s(r[1],-e[1]),c=u(l(n,a),l(i,o));return c[c.length-1]>=0}function i(t,e,r,i){var s=a(e,r,i);if(0===s){var l=o(a(t,e,r)),u=o(a(t,e,i));if(l===u){if(0===l){var c=n(t,e,r),f=n(t,e,i);return c===f?0:c?1:-1}return 0}return 0===u?l>0?-1:n(t,e,i)?-1:1:0===l?u>0?1:n(t,e,r)?1:-1:o(u-l)}var h=a(t,e,r);if(h>0)return s>0&&a(t,e,i)>0?1:-1;if(0>h)return s>0||a(t,e,i)>0?1:-1;var p=a(t,e,i);return p>0?1:n(t,e,r)?1:-1}e.exports=i;var a=t("robust-orientation"),o=t("signum"),s=t("two-sum"),l=t("robust-product"),u=t("robust-sum")},{"robust-orientation":1040,"robust-product":412,"robust-sum":421,signum:413,"two-sum":414}],411:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":422,"two-sum":414}],412:[function(t,e,r){"use strict";function n(t,e){if(1===t.length)return a(e,t[0]);if(1===e.length)return a(t,e[0]);if(0===t.length||0===e.length)return[0];var r=[0];if(t.lengtht?-1:t>0?1:0}},{}],414:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],415:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],416:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}function i(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function a(t,e){var r=d(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function o(t,e){var r=t.intervals([]);r.push(e),a(t,r)}function s(t,e){var r=t.intervals([]),n=r.indexOf(e);return 0>n?y:(r.splice(n,1),a(t,r),b)}function l(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function c(t,e){for(var r=0;r>1],a=[],o=[],s=[],r=0;r3*(e+1)?o(this,t):this.left.insert(t):this.left=d([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?o(this,t):this.right.insert(t):this.right=d([t]);else{var r=m.ge(this.leftPoints,t,h),n=m.ge(this.rightPoints,t,p);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1))return s(this,t);var n=this.left.remove(t);return n===x?(this.left=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(t[0]>this.mid){if(!this.right)return y;var a=this.left?this.left.count:0;if(4*a>3*(e-1))return s(this,t);var n=this.right.remove(t);return n===x?(this.right=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(1===this.count)return this.leftPoints[0]===t?x:y;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var o=this,l=this.left;l.right;)o=l,l=l.right;if(o===this)l.right=this.right;else{var u=this.left,n=this.right;o.count-=l.count,o.right=l.left,l.left=u,l.right=n}i(this,l),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?i(this,this.left):i(this,this.right);return b}for(var u=m.ge(this.leftPoints,t,h);uthis.mid){if(this.right){var r=this.right.queryPoint(t,e);if(r)return r}return u(this.rightPoints,t,e)}return c(this.leftPoints,e)},_.queryInterval=function(t,e,r){if(tthis.mid&&this.right){var n=this.right.queryInterval(t,e,r);if(n)return n}return ethis.mid?u(this.rightPoints,t,r):c(this.leftPoints,r)};var w=g.prototype;w.insert=function(t){this.root?this.root.insert(t):this.root=new n(t[0],null,null,[t],[t])},w.remove=function(t){if(this.root){var e=this.root.remove(t);return e===x&&(this.root=null),e!==y}return!1},w.queryPoint=function(t,e){return this.root?this.root.queryPoint(t,e):void 0; -},w.queryInterval=function(t,e,r){return e>=t&&this.root?this.root.queryInterval(t,e,r):void 0},Object.defineProperty(w,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(w,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":415}],417:[function(t,e,r){"use strict";function n(t,e){var r,n;if(e[0][0]e[1][0])){var i=Math.min(t[0][1],t[1][1]),o=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),l=Math.max(e[0][1],e[1][1]);return s>o?o-s:i>l?i-l:o-l}r=e[1],n=e[0]}var u,c;t[0][1]e[1][0]))return n(e,t);r=e[1],i=e[0]}var o,s;if(t[0][0]t[1][0]))return-n(t,e);o=t[1],s=t[0]}var l=a(r,i,s),u=a(r,i,o);if(0>l){if(0>=u)return l}else if(l>0){if(u>=0)return l}else if(u)return u;if(l=a(s,o,i),u=a(s,o,r),0>l){if(0>=u)return l}else if(l>0){if(u>=0)return l}else if(u)return u;return i[0]-s[0]}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":1040}],418:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function i(t){return new n(t._color,t.key,t.value,t.left,t.right,t._count)}function a(t,e){return new n(t,e.key,e.value,e.left,e.right,e._count)}function o(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function s(t,e){this._compare=t,this.root=e}function l(t,e){if(e.left){var r=l(t,e.left);if(r)return r}var r=t(e.key,e.value);return r?r:e.right?l(t,e.right):void 0}function u(t,e,r,n){var i=e(t,n.key);if(0>=i){if(n.left){var a=u(t,e,r,n.left);if(a)return a}var a=r(n.key,n.value);if(a)return a}return n.right?u(t,e,r,n.right):void 0}function c(t,e,r,n,i){var a,o=r(t,i.key),s=r(e,i.key);if(0>=o){if(i.left&&(a=c(t,e,r,n,i.left)))return a;if(s>0&&(a=n(i.key,i.value)))return a}return s>0&&i.right?c(t,e,r,n,i.right):void 0}function f(t,e){this.tree=t,this._stack=e}function h(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function p(t){for(var e,r,n,s,l=t.length-1;l>=0;--l){if(e=t[l],0===l)return void(e._color=m);if(r=t[l-1],r.left===e){if(n=r.right,n.right&&n.right._color===v){if(n=r.right=i(n),s=n.right=i(n.right),r.right=n.left,n.left=r,n.right=s,n._color=r._color,e._color=m,r._color=m,s._color=m,o(r),o(n),l>1){var u=t[l-2];u.left===r?u.left=n:u.right=n}return void(t[l-1]=n)}if(n.left&&n.left._color===v){if(n=r.right=i(n),s=n.left=i(n.left),r.right=s.left,n.left=s.right,s.left=r,s.right=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var u=t[l-2];u.left===r?u.left=s:u.right=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.right=a(v,n));r.right=a(v,n);continue}if(n=i(n),r.right=n.left,n.left=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var u=t[l-2];u.left===r?u.left=n:u.right=n}t[l-1]=n,t[l]=r,l+11){var u=t[l-2];u.right===r?u.right=n:u.left=n}return void(t[l-1]=n)}if(n.right&&n.right._color===v){if(n=r.left=i(n),s=n.right=i(n.right),r.left=s.right,n.right=s.left,s.right=r,s.left=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var u=t[l-2];u.right===r?u.right=s:u.left=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.left=a(v,n));r.left=a(v,n);continue}if(n=i(n),r.left=n.right,n.right=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var u=t[l-2];u.right===r?u.right=n:u.left=n}t[l-1]=n,t[l]=r,l+1t?-1:t>e?1:0}function g(t){return new s(t||d,null)}e.exports=g;var v=0,m=1,y=s.prototype;Object.defineProperty(y,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(y,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(y,"length",{get:function(){return this.root?this.root._count:0}}),y.insert=function(t,e){for(var r=this._compare,i=this.root,l=[],u=[];i;){var c=r(t,i.key);l.push(i),u.push(c),i=0>=c?i.left:i.right}l.push(new n(v,t,e,null,null,1));for(var f=l.length-2;f>=0;--f){var i=l[f];u[f]<=0?l[f]=new n(i._color,i.key,i.value,l[f+1],i.right,i._count+1):l[f]=new n(i._color,i.key,i.value,i.left,l[f+1],i._count+1)}for(var f=l.length-1;f>1;--f){var h=l[f-1],i=l[f];if(h._color===m||i._color===m)break;var p=l[f-2];if(p.left===h)if(h.left===i){var d=p.right;if(!d||d._color!==v){if(p._color=v,p.left=h.right,h._color=m,h.right=p,l[f-2]=h,l[f-1]=i,o(p),o(h),f>=3){var g=l[f-3];g.left===p?g.left=h:g.right=h}break}h._color=m,p.right=a(m,d),p._color=v,f-=1}else{var d=p.right;if(!d||d._color!==v){if(h.right=i.left,p._color=v,p.left=i.right,i._color=m,i.left=h,i.right=p,l[f-2]=i,l[f-1]=h,o(p),o(h),o(i),f>=3){var g=l[f-3];g.left===p?g.left=i:g.right=i}break}h._color=m,p.right=a(m,d),p._color=v,f-=1}else if(h.right===i){var d=p.left;if(!d||d._color!==v){if(p._color=v,p.right=h.left,h._color=m,h.left=p,l[f-2]=h,l[f-1]=i,o(p),o(h),f>=3){var g=l[f-3];g.right===p?g.right=h:g.left=h}break}h._color=m,p.left=a(m,d),p._color=v,f-=1}else{var d=p.left;if(!d||d._color!==v){if(h.left=i.right,p._color=v,p.right=i.left,i._color=m,i.right=h,i.left=p,l[f-2]=i,l[f-1]=h,o(p),o(h),o(i),f>=3){var g=l[f-3];g.right===p?g.right=i:g.left=i}break}h._color=m,p.left=a(m,d),p._color=v,f-=1}}return l[0]._color=m,new s(r,l[0])},y.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return l(t,this.root);case 2:return u(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return c(e,r,this._compare,t,this.root)}},Object.defineProperty(y,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new f(this,t)}}),Object.defineProperty(y,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new f(this,t)}}),y.at=function(t){if(0>t)return new f(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new f(this,[])},y.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>=a&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>a&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new f(this,n);r=0>=i?r.left:r.right}return new f(this,[])},y.remove=function(t){var e=this.find(t);return e?e.remove():this},y.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=0>=n?r.left:r.right}};var b=f.prototype;Object.defineProperty(b,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(b,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),b.clone=function(){return new f(this.tree,this._stack.slice())},b.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new n(r._color,r.key,r.value,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i){var r=t[i];r.left===t[i+1]?e[i]=new n(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count)}if(r=e[e.length-1],r.left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var o=e[a-1];e.push(new n(r._color,o.key,o.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(var i=e.length-2;i>=a;--i)r=e[i],e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count);e[a-1].left=e[a]}if(r=e[e.length-1],r._color===v){var l=e[e.length-2];l.left===r?l.left=null:l.right===r&&(l.right=null),e.pop();for(var i=0;i0?this._stack[this._stack.length-1].key:void 0},enumerable:!0}),Object.defineProperty(b,"value",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1].value:void 0},enumerable:!0}),Object.defineProperty(b,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),b.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),b.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),i=e[e.length-1];r[r.length-1]=new n(i._color,i.key,t,i.left,i.right,i._count);for(var a=e.length-2;a>=0;--a)i=e[a],i.left===e[a+1]?r[a]=new n(i._color,i.key,i.value,r[a+1],i.right,i._count):r[a]=new n(i._color,i.key,i.value,i.left,r[a+1],i._count);return new s(this.tree._compare,r[0])},b.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],419:[function(t,e,r){"use strict";function n(t,e,r){this.slabs=t,this.coordinates=e,this.horizontal=r}function i(t,e){return t.y-e}function a(t,e){for(var r=null;t;){var n,i,o=t.key;o[0][0]s)t=t.left;else if(s>0)if(e[0]!==o[1][0])r=t,t=t.right;else{var l=a(t.right,e);if(l)return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l=a(t.right,e);if(l)return l;t=t.left}}return r}function o(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function s(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}function l(t){for(var e=t.length,r=2*e,i=new Array(r),a=0;e>a;++a){var l=t[a],u=l[0][0]a;){for(var v=i[a].x,m=[];r>a;){var y=i[a];if(y.x!==v)break;a+=1,y.segment[0][0]===y.x&&y.segment[1][0]===y.x?y.create&&(y.segment[0][1]e)return-1;var r=(this.slabs[e],a(this.slabs[e],t)),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var o=null;if(r&&(o=r.key),e>0){var s=a(this.slabs[e-1],t);s&&(o?h(s.key,o)>0&&(o=s.key,n=s.value):(n=s.value,o=s.key))}var l=this.horizontal[e];if(l.length>0){var c=u.ge(l,t[1],i);if(c=l.length)return n;p=l[c]}}if(p.start)if(o){var d=f(o[0],o[1],[t[0],p.y]);o[0][0]>o[1][0]&&(d=-d),d>0&&(n=p.index)}else n=p.index;else p.y!==t[1]&&(n=p.index)}}}return n}},{"./lib/order-segments":417,"binary-search-bounds":415,"functional-red-black-tree":418,"robust-orientation":1040}],420:[function(t,e,r){function n(){return!0}function i(t){return function(e,r){var i=t[e];return i?!!i.queryPoint(r,n):!1}}function a(t){for(var e={},r=0;rn)return 1;var i=t[n];if(!i){if(!(n>0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=f(r,o[0],o[1]);if(o[0][0]s)i=i.left;else{if(!(s>0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(0>s))return 0;a=1,i=i.right}}return a}}function s(t){return 1}function l(t){return function(e){return t(e[0],e[1])?0:1}}function u(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}function c(t){for(var e=t.length,r=[],n=[],i=0;e>i;++i)for(var c=t[i],f=c.length,p=f-1,d=0;f>d;p=d++){var g=c[p],v=c[d];g[0]===v[0]?n.push([g,v]):r.push([g,v])}if(0===r.length)return 0===n.length?s:l(a(n));var m=h(r),y=o(m.slabs,m.coordinates);return 0===n.length?y:u(a(n),y)}e.exports=c;var f=t("robust-orientation")[3],h=t("slab-decomposition"),p=t("interval-tree-1d"),d=t("binary-search-bounds")},{"binary-search-bounds":415,"interval-tree-1d":416,"robust-orientation":1040,"slab-decomposition":419}],421:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],422:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],423:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],424:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function i(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=[];return e}function a(t,e){function r(t){for(var r=t.length,n=[0],i=0;r>i;++i){var a=e[t[i]],o=e[t[(i+1)%r]],s=u(-a[0],a[1]),l=u(-a[0],o[1]),f=u(o[0],a[1]),h=u(o[0],o[1]);n=c(n,c(c(s,l),c(f,h)))}return n[n.length-1]>0}function a(t){for(var e=t.length,r=0;e>r;++r)if(!j[t[r]])return!1;return!0}var p=h(t,e);t=p[0],e=p[1];for(var d=e.length,g=(t.length,o(t,e.length)),v=0;d>v;++v)if(g[v].length%2===1)throw new Error("planar-graph-to-polyline: graph must be manifold");var m=s(t,e);m=m.filter(r);for(var y=m.length,b=new Array(y),x=new Array(y),v=0;y>v;++v){b[v]=v;var _=new Array(y),w=m[v].map(function(t){return e[t]}),k=l([w]),A=0;t:for(var M=0;y>M;++M)if(_[M]=0,v!==M){for(var T=m[M],E=T.length,L=0;E>L;++L){var S=k(e[T[L]]);if(0!==S){0>S&&(_[M]=1,A+=1);continue t}}_[M]=1,A+=1}x[v]=[A,v,_]}x.sort(function(t,e){return e[0]-t[0]});for(var v=0;y>v;++v)for(var _=x[v],C=_[1],z=_[2],M=0;y>M;++M)z[M]&&(b[M]=C);for(var P=i(y),v=0;y>v;++v)P[v].push(b[v]),P[b[v]].push(v);for(var R={},j=n(d,!1),v=0;y>v;++v)for(var T=m[v],E=T.length,M=0;E>M;++M){var O=T[M],I=T[(M+1)%E],N=Math.min(O,I)+":"+Math.max(O,I);if(N in R){var F=R[N];P[F].push(v),P[v].push(F),j[O]=j[I]=!0}else R[N]=v}for(var D=[],B=n(y,-1),v=0;y>v;++v)b[v]!==v||a(m[v])?B[v]=-1:(D.push(v),B[v]=0);for(var p=[];D.length>0;){var U=D.pop(),V=P[U];f(V,function(t,e){return t-e});var q,G=V.length,H=B[U];if(0===H){var T=m[U];q=[T]}for(var v=0;G>v;++v){var Y=V[v];if(!(B[Y]>=0)&&(B[Y]=1^H,D.push(Y),0===H)){var T=m[Y];a(T)||(T.reverse(),q.push(T))}}0===H&&p.push(q)}return p}e.exports=a;var o=t("edges-to-adjacency-list"),s=t("planar-dual"),l=t("point-in-big-polygon"),u=t("two-product"),c=t("robust-sum"),f=t("uniq"),h=t("./lib/trim-leaves")},{"./lib/trim-leaves":407,"edges-to-adjacency-list":408,"planar-dual":409,"point-in-big-polygon":420,"robust-sum":421,"two-product":422,uniq:423}],425:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],426:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n,n.prototype.length=function(){return this.roots.length},n.prototype.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},n.prototype.find=function(t){for(var e=this.roots;e[t]!==t;){var r=e[t];e[t]=e[r],t=r}return t},n.prototype.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],427:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":425,dup:79,"union-find":426}],428:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.abs(a(t,e,r)),i=Math.sqrt(Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2));return n/i}function i(t,e,r){function i(t){if(x[t])return 1/0;var r=m[t],i=y[t];return 0>r||0>i?1/0:n(e[t],e[r],e[i])}function a(t,e){var r=M[t],n=M[e];M[t]=n,M[e]=r,T[r]=e,T[n]=t}function s(t){return b[M[t]]}function l(t){return 1&t?t-1>>1:(t>>1)-1}function u(t){for(var e=s(t);;){var r=e,n=2*t+1,i=2*(t+1),o=t;if(L>n){var l=s(n);r>l&&(o=n,r=l)}if(L>i){var u=s(i);r>u&&(o=i)}if(o===t)return t;a(t,o),t=o}}function c(t){for(var e=s(t);t>0;){var r=l(t);if(r>=0){var n=s(r);if(n>e){a(t,r),t=r;continue}}return t}}function f(){if(L>0){var t=M[0];return a(0,L-1),L-=1,u(0),t}return-1}function h(t,e){var r=M[t];return b[r]===e?t:(b[r]=-(1/0),c(t),f(),b[r]=e,L+=1,c(L-1))}function p(t){if(!x[t]){x[t]=!0;var e=m[t],r=y[t];m[r]>=0&&(m[r]=e),y[e]>=0&&(y[e]=r),T[e]>=0&&h(T[e],i(e)),T[r]>=0&&h(T[r],i(r))}}function d(t,e){if(t[e]<0)return e;var r=e,n=e;do{var i=t[n];if(!x[n]||0>i||i===n)break;if(n=i,i=t[n],!x[n]||0>i||i===n)break;n=i,r=t[r]}while(r!==n);for(var a=e;a!==n;a=t[a])t[a]=n;return n}for(var g=e.length,v=t.length,m=new Array(g),y=new Array(g),b=new Array(g),x=new Array(g),_=0;g>_;++_)m[_]=y[_]=-1,b[_]=1/0,x[_]=!1;for(var _=0;v>_;++_){var w=t[_];if(2!==w.length)throw new Error("Input must be a graph");var k=w[1],A=w[0];-1!==y[A]?y[A]=-2:y[A]=k,-1!==m[k]?m[k]=-2:m[k]=A}for(var M=[],T=new Array(g),_=0;g>_;++_){var E=b[_]=i(_);1/0>E?(T[_]=M.length,M.push(_)):T[_]=-1}for(var L=M.length,_=L>>1;_>=0;--_)u(_);for(;;){var S=f();if(0>S||b[S]>r)break;p(S)}for(var C=[],_=0;g>_;++_)x[_]||(T[_]=C.length,C.push(e[_].slice()));var z=(C.length,[]);return t.forEach(function(t){var e=d(m,t[0]),r=d(y,t[1]);if(e>=0&&r>=0&&e!==r){var n=T[e],i=T[r];n!==i&&z.push([n,i])}}),o.unique(o.normalize(z)),{positions:C,edges:z}}e.exports=i;var a=t("robust-orientation"),o=t("simplicial-complex")},{"robust-orientation":1040,"simplicial-complex":427}],429:[function(t,e,r){"use strict";function n(t){return"a"+t}function i(t){return"d"+t}function a(t,e){return"c"+t+"_"+e}function o(t){return"s"+t}function s(t,e){return"t"+t+"_"+e}function l(t){return"o"+t}function u(t){return"x"+t}function c(t){return"p"+t}function f(t,e){return"d"+t+"_"+e}function h(t){return"i"+t}function p(t,e){return"u"+t+"_"+e}function d(t){return"b"+t}function g(t){return"y"+t}function v(t){return"e"+t}function m(t){return"v"+t}function y(t,e,r){for(var n=0,i=0;t>i;++i)e&1<e;++e)F.push(c(e),"+=",p(e,x[t]),";");F.push("}")}function z(t){for(var e=t-1;e>=0;--e)S(e,0);for(var r=[],e=0;O>e;++e)L[e]?r.push(i(e)+".get("+c(e)+")"):r.push(i(e)+"["+c(e)+"]");for(var e=0;b>e;++e)r.push(u(e));F.push(k,"[",T,"++]=phase(",r.join(),");");for(var e=0;t>e;++e)C(e);for(var n=0;O>n;++n)F.push(c(n),"+=",p(n,x[t]),";")}function P(t){for(var e=0;O>e;++e)L[e]?F.push(a(e,0),"=",i(e),".get(",c(e),");"):F.push(a(e,0),"=",i(e),"[",c(e),"];");for(var r=[],e=0;O>e;++e)r.push(a(e,0));for(var e=0;b>e;++e)r.push(u(e));F.push(d(0),"=",k,"[",T,"]=phase(",r.join(),");");for(var n=1;1<n;++n)F.push(d(n),"=",k,"[",T,"+",v(n),"];");for(var o=[],n=1;1<n;++n)o.push("("+d(0)+"!=="+d(n)+")");F.push("if(",o.join("||"),"){");for(var s=[],e=0;I>e;++e)s.push(h(e));for(var e=0;O>e;++e){s.push(a(e,0));for(var n=1;1<n;++n)L[e]?F.push(a(e,n),"=",i(e),".get(",c(e),"+",f(e,n),");"):F.push(a(e,n),"=",i(e),"[",c(e),"+",f(e,n),"];"),s.push(a(e,n))}for(var e=0;1<e;++e)s.push(d(e));for(var e=0;b>e;++e)s.push(u(e));F.push("vertex(",s.join(),");",m(0),"=",w,"[",T,"]=",A,"++;");for(var l=(1<n;++n)if(0===(t&~(1<0;_=_-1&g)x.push(w+"["+T+"+"+v(_)+"]");x.push(m(0));for(var _=0;O>_;++_)1&n?x.push(a(_,l),a(_,g)):x.push(a(_,g),a(_,l));1&n?x.push(p,y):x.push(y,p);for(var _=0;b>_;++_)x.push(u(_));F.push("if(",p,"!==",y,"){","face(",x.join(),")}")}F.push("}",T,"+=1;")}function R(){for(var t=1;1<t;++t)F.push(E,"=",v(t),";",v(t),"=",g(t),";",g(t),"=",E,";")}function j(t,e){if(0>t)return void P(e);z(t),F.push("if(",o(x[t]),">0){",h(x[t]),"=1;"),j(t-1,e|1<r;++r)F.push(c(r),"+=",p(r,x[t]),";");t===I-1&&(F.push(T,"=0;"),R()),S(t,2),j(t-1,e),t===I-1&&(F.push("if(",h(x[I-1]),"&1){",T,"=0;}"),R()),C(t),F.push("}")}var O=L.length,I=x.length;if(2>I)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var N="extractContour"+x.join("_"),F=[],D=[],B=[],U=0;O>U;++U)B.push(n(U));for(var U=0;b>U;++U)B.push(u(U));for(var U=0;I>U;++U)D.push(o(U)+"="+n(0)+".shape["+U+"]|0");for(var U=0;O>U;++U){D.push(i(U)+"="+n(U)+".data",l(U)+"="+n(U)+".offset|0");for(var V=0;I>V;++V)D.push(s(U,V)+"="+n(U)+".stride["+V+"]|0")}for(var U=0;O>U;++U){D.push(c(U)+"="+l(U)),D.push(a(U,0));for(var V=1;1<V;++V){for(var q=[],G=0;I>G;++G)V&1<U;++U)for(var V=0;I>V;++V){var H=[s(U,x[V])];V>0&&H.push(s(U,x[V-1])+"*"+o(x[V-1])),D.push(p(U,x[V])+"=("+H.join("-")+")|0")}for(var U=0;I>U;++U)D.push(h(U)+"=0");D.push(A+"=0");for(var Y=["2"],U=I-2;U>=0;--U)Y.push(o(x[U]));D.push(M+"=("+Y.join("*")+")|0",k+"=mallocUint32("+M+")",w+"=mallocUint32("+M+")",T+"=0"),D.push(d(0)+"=0");for(var V=1;1<V;++V){for(var X=[],W=[],G=0;I>G;++G)V&1<n&&e("Must have at least one array argument");var i=t.scalarArguments||0;0>i&&e("Scalar arg count must be > 0"),"function"!=typeof t.vertex&&e("Must specify vertex creation function"),"function"!=typeof t.cell&&e("Must specify cell creation function"),"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;n>s;++s)a.indexOf(s)>=0?o[s]=!0:o[s]=!1;return b(t.vertex,t.cell,t.phase,i,r,o)}var _=t("typedarray-pool");e.exports=x;var w="V",k="P",A="N",M="Q",T="X",E="T"},{"typedarray-pool":432}],430:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],431:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],432:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":430,buffer:65,dup:122}],433:[function(t,e,r){function n(t){if(0>t)return Number("0/0");for(var e=s[0],r=s.length-1;r>0;--r)e+=s[r]/(t+r);var n=t+o+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}var i=7,a=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],o=607/128,s=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];e.exports=function l(t){if(.5>t)return Math.PI/(Math.sin(Math.PI*t)*l(1-t));if(t>100)return Math.exp(n(t));t-=1;for(var e=a[0],r=1;i+2>r;r++)e+=a[r]/(t+r);var o=t+i+.5;return Math.sqrt(2*Math.PI)*Math.pow(o,t+.5)*Math.exp(-o)*e},e.exports.log=n},{}],434:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],435:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],436:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":434,buffer:65,dup:122}],437:[function(t,e,r){"use strict";function n(t){var e=t.length;if(i>e){for(var r=1,n=0;e>n;++n)for(var o=0;n>o;++o)if(t[n]n;++n)s[n]=0;for(var r=1,n=0;e>n;++n)if(!s[n]){var l=1;s[n]=1;for(var o=t[n];o!==n;o=t[o]){if(s[o])return a.freeUint8(s),0;l+=1,s[o]=1}1&l||(r=-r)}return a.freeUint8(s),r}e.exports=n;var i=32,a=t("typedarray-pool")},{"typedarray-pool":436}],438:[function(t,e,r){"use strict";function n(t){var e=t.length;switch(e){case 0:case 1:return 0;case 2:return t[1]}var r,n,i,s=a.mallocUint32(e),l=a.mallocUint32(e),u=0;for(o(t,l),i=0;e>i;++i)s[i]=t[i];for(i=e-1;i>0;--i)n=l[i],r=s[i],s[i]=s[n],s[n]=r,l[i]=l[r],l[r]=n,u=(u+r)*i;return a.freeUint32(l),a.freeUint32(s),u}function i(t,e,r){switch(t){case 0:return r?r:[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}r=r||new Array(t);var n,i,a,o=1;for(r[0]=0,a=1;t>a;++a)r[a]=a,o=o*a|0;for(a=t-1;a>0;--a)n=e/o|0,e=e-n*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}var a=t("typedarray-pool"),o=t("invert-permutation");r.rank=n,r.unrank=i},{"invert-permutation":439,"typedarray-pool":442}],439:[function(t,e,r){"use strict";function n(t,e){e=e||new Array(t.length);for(var r=0;rt)return[];if(0===t)return[[0]];for(var e=0|Math.round(o(t+1)),r=[],n=0;e>n;++n){for(var s=i.unrank(t,n),l=[0],u=0,c=0;c= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":445}],445:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":447,dup:319}],446:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:448}],447:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":446,dup:321}],448:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],449:[function(t,e,r){"use strict";function n(t,e){var r=[];return e=+e||0,i(t.hi(t.shape[0]-1),r,e),r}e.exports=n;var i=t("./lib/zc-core")},{"./lib/zc-core":444}],450:[function(t,e,r){"use strict";function n(t,e){var r=t.length,n=["'use strict';"],i="surfaceNets"+t.join("_")+"d"+e;n.push("var contour=genContour({","order:[",t.join(),"],","scalarArguments: 3,","phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],l=[],u=0;r>u;++u)a.push("d"+u),l.push("d"+u);for(var u=0;1<u;++u)a.push("v"+u),l.push("v"+u);for(var u=0;1<u;++u)a.push("p"+u),l.push("p"+u);a.push("a","b","c"),l.push("a","c"),n.push("vertex:function vertexFunc(",a.join(),"){");for(var c=[],u=0;1<u;++u)c.push("(p"+u+"<<"+u+")");n.push("var m=(",c.join("+"),")|0;if(m===0||m===",(1<<(1<=1<<(1<>>7){");for(var u=0;1<<(1<u;++u){if(1<<(1<128&&u%128===0){f.length>0&&h.push("}}");var p="vExtra"+f.length;n.push("case ",u>>>7,":",p,"(m&0x7f,",l.join(),");break;"),h=["function ",p,"(m,",l.join(),"){switch(m){"],f.push(h)}h.push("case ",127&u,":");for(var d=new Array(r),g=new Array(r),v=new Array(r),m=new Array(r),y=0,b=0;r>b;++b)d[b]=[],g[b]=[],v[b]=0,m[b]=0;for(var b=0;1<b;++b)for(var x=0;r>x;++x){var _=b^1<b)&&!(u&1<<_)!=!(u&1<w?(d[x].push("-v"+b+"-v"+_),v[x]+=2):(d[x].push("v"+b+"+v"+_),v[x]-=2),y+=1;for(var k=0;r>k;++k)k!==x&&(_&1<x;++x)if(0===d[x].length)A.push("d"+x+"-0.5");else{var M="";v[x]<0?M=v[x]+"*c":v[x]>0&&(M="+"+v[x]+"*c");var T=.5*(d[x].length/y),E=.5+.5*(m[x]/y);A.push("d"+x+"-"+E+"-"+T+"*("+d[x].join("+")+M+")/("+g[x].join("+")+")")}h.push("a.push([",A.join(),"]);","break;")}n.push("}},"),f.length>0&&h.push("}}");for(var L=[],u=0;1<u;++u)L.push("v"+u);L.push("c0","c1","p0","p1","a","b","c"),n.push("cell:function cellFunc(",L.join(),"){");var S=s(r-1);n.push("if(p0){b.push(",S.map(function(t){return"["+t.map(function(t){return"v"+t})+"]"}).join(),")}else{b.push(",S.map(function(t){var e=t.slice();return e.reverse(),"["+e.map(function(t){return"v"+t})+"]"}).join(),")}}});function ",i,"(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ",i,";");for(var u=0;uo;++o)i[o]=[r[o]],a[o]=[o];return{positions:i,cells:a}}function a(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return i(t,e);var r=t.order.join()+"-"+t.dtype,a=u[r],e=+e||0;return a||(a=u[r]=n(t.order,t.dtype)),a(t,e)}e.exports=a;var o=t("ndarray-extract-contour"),s=t("triangulate-hypercube"),l=t("zero-crossings"),u={}},{"ndarray-extract-contour":429,"triangulate-hypercube":443,"zero-crossings":449}],451:[function(t,e,r){(function(r){"use strict";function n(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;ol;++l){var u=r[s[l]];n[i++]=u[0],n[i++]=u[1]+1.4, -a=Math.max(u[0],a)}return{data:n,shape:a}}function i(t,e){var r=s[t];r||(r=s[t]={" ":{data:new Float32Array(0),shape:.2}});var o=r[e];if(!o)if(e.length<=1||!/\d/.test(e))o=r[e]=n(a(e,{triangles:!0,font:t,textAlign:"left",textBaseline:"alphabetic"}));else{for(var l=e.split(/(\d|\s)/),u=new Array(l.length),c=0,f=0,h=0;h0&&(f+=.02);for(var p=new Float32Array(c),d=0,g=-.5*f,h=0;hd;++d)if(f[d]&&n[d]<=0&&n[d+2]>=0){var g=e[d]-n[d]*(e[d+2]-e[d])/(n[d+2]-n[d]);0===d?o.drawLine(g,e[1],g,e[3],p[d],h[d]):o.drawLine(e[0],g,e[2],g,p[d],h[d])}}for(var d=0;dd;++d)s.drawTicks(d);this.titleEnable&&s.drawTitle();for(var b=this.overlays,d=0;du;++u){var c=s[u].slice(0);0!==c.length&&(c.sort(a),l[u]=Math.min(l[u],c[0].x),l[u+2]=Math.max(l[u+2],c[c.length-1].x))}this.grid.update({bounds:l,ticks:s}),this.text.update({bounds:l,ticks:s,labels:t.labels||["x","y"],labelSize:t.labelSize||[12,12],labelFont:t.labelFont||["sans-serif","sans-serif"],title:t.title||"",titleSize:t.titleSize||18,titleFont:t.titleFont||"sans-serif"}),this.setDirty()},h.dispose=function(){this.box.dispose(),this.grid.dispose(),this.text.dispose(),this.line.dispose();for(var t=this.objects.length-1;t>=0;--t)this.objects[t].dispose();this.objects.length=0;for(var t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},h.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},h.removeObject=function(t){for(var e=this.objects,r=0;rh;++h)o=o&&l[h]===s[h],l[h]=s[h];var p=t.clientWidth===c&&t.clientHeight===f;return c=t.clientWidth,f=t.clientHeight,o?!p:(u=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){return n.setMode(t),n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return u},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var p=0,d=0;return o(t,function(e,r,a,o){var s=1/t.clientHeight,l=s*(r-p),c=s*(a-d),f=h.flipX?1:-1,g=h.flipY?1:-1,v=Math.PI*h.rotateSpeed,m=i();if(1&e)o.shift?n.rotate(m,0,0,-l*v):n.rotate(m,f*v*l,-g*v*c,0);else if(2&e)n.pan(m,-h.translateSpeed*l*u,h.translateSpeed*c*u,0);else if(4&e){var y=h.zoomSpeed*c/window.innerHeight*(m-n.lastT())*50;n.pan(m,0,0,u*(Math.exp(y)-1))}p=r,d=a}),s(t,function(t,e,r){var a=h.flipX?1:-1,o=h.flipY?1:-1,s=i();if(Math.abs(t)>Math.abs(e))n.rotate(s,0,0,-t*a*Math.PI*h.rotateSpeed/window.innerWidth);else{var l=h.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,u*(Math.exp(l)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],455:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":458}],456:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],457:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],458:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":456,buffer:65,dup:122}],459:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],460:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":459,dup:155}],461:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":459,dup:156}],462:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":460,"./lib/vao-native.js":461,dup:157}],463:[function(t,e,r){!function(){"use strict";function t(e){e.permitHostObjects___&&e.permitHostObjects___(t)}function r(t){return!(t.substr(0,p.length)==p&&"___"===t.substr(t.length-3))}function n(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[d];if(e&&e.key===t)return e;if(h(t)){e={key:t};try{return f(t,d,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(r){return}}}function i(t){return t.prototype=null,Object.freeze(t)}function a(){y||"undefined"==typeof console||(y=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}if("undefined"==typeof ses||!ses.ok||ses.ok()){"undefined"!=typeof ses&&(ses.weakMapPermitHostObjects=t);var o=!1;if("function"==typeof WeakMap){var s=WeakMap;if("undefined"!=typeof navigator&&/Firefox/.test(navigator.userAgent));else{var l=new s,u=Object.freeze({});if(l.set(u,1),1===l.get(u))return void(e.exports=WeakMap);o=!0}}var c=(Object.prototype.hasOwnProperty,Object.getOwnPropertyNames),f=Object.defineProperty,h=Object.isExtensible,p="weakmap:",d=p+"ident:"+Math.random()+"___";if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof ArrayBuffer&&"function"==typeof Uint8Array){var g=new ArrayBuffer(25),v=new Uint8Array(g);crypto.getRandomValues(v),d=p+"rand:"+Array.prototype.map.call(v,function(t){return(t%36).toString(36)}).join("")+"___"}if(f(Object,"getOwnPropertyNames",{value:function(t){return c(t).filter(r)}}),"getPropertyNames"in Object){var m=Object.getPropertyNames;f(Object,"getPropertyNames",{value:function(t){return m(t).filter(r)}})}!function(){var t=Object.freeze;f(Object,"freeze",{value:function(e){return n(e),t(e)}});var e=Object.seal;f(Object,"seal",{value:function(t){return n(t),e(t)}});var r=Object.preventExtensions;f(Object,"preventExtensions",{value:function(t){return n(t),r(t)}})}();var y=!1,b=0,x=function(){function t(t,e){var r,i=n(t);return i?u in i?i[u]:e:(r=s.indexOf(t),r>=0?l[r]:e)}function e(t){var e=n(t);return e?u in e:s.indexOf(t)>=0}function r(t,e){var r,i=n(t);return i?i[u]=e:(r=s.indexOf(t),r>=0?l[r]=e:(r=s.length,l[r]=e,s[r]=t)),this}function o(t){var e,r,i=n(t);return i?u in i&&delete i[u]:(e=s.indexOf(t),0>e?!1:(r=s.length-1,s[e]=void 0,l[e]=l[r],s[e]=s[r],s.length=r,l.length=r,!0))}this instanceof x||a();var s=[],l=[],u=b++;return Object.create(x.prototype,{get___:{value:i(t)},has___:{value:i(e)},set___:{value:i(r)},delete___:{value:i(o)}})};x.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},"delete":{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof s?!function(){function r(){function e(t,e){return c?u.has(t)?u.get(t):c.get___(t,e):u.get(t,e)}function r(t){return u.has(t)||(c?c.has___(t):!1)}function n(t){var e=!!u.delete(t);return c?c.delete___(t)||e:e}this instanceof x||a();var l,u=new s,c=void 0,f=!1;return l=o?function(t,e){return u.set(t,e),u.has(t)||(c||(c=new x),c.set(t,e)),this}:function(t,e){if(f)try{u.set(t,e)}catch(r){c||(c=new x),c.set___(t,e)}else u.set(t,e);return this},Object.create(x.prototype,{get___:{value:i(e)},has___:{value:i(r)},set___:{value:i(l)},delete___:{value:i(n)},permitHostObjects___:{value:i(function(e){if(e!==t)throw new Error("bogus call to permitHostObjects___");f=!0})}})}o&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=x.prototype,e.exports=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=x)}}()},{}],464:[function(t,e,r){"use strict";function n(t){var e=s.get(t);if(!e||!t.isBuffer(e._triangleBuffer.buffer)){var r=a(t,new Float32Array([-1,-1,-1,4,4,-1]));e=o(t,[{buffer:r,type:t.FLOAT,size:2}]),e._triangleBuffer=r,s.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}var i="undefined"==typeof WeakMap?t("weak-map"):WeakMap,a=t("gl-buffer"),o=t("gl-vao"),s=new i;e.exports=n},{"gl-buffer":455,"gl-vao":462,"weak-map":463}],465:[function(t,e,r){"use strict";function n(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function i(t){this.gl=t,this.pixelRatio=1,this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.autoTicks=!0,this.tickSpacing=[1,1,1],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[10,10,10],this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]},this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont="sans-serif",this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[10,10,10],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[0,0,0],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!1,!1,!1],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._firstInit=!0,this._text=null,this._lines=null,this._background=c(t)}function a(){this.primalOffset=[0,0,0],this.primalMinor=[0,0,0],this.mirrorOffset=[0,0,0],this.mirrorMinor=[0,0,0]}function o(t,e,r,n,i){for(var a=t.primalOffset,o=t.primalMinor,s=t.mirrorOffset,l=t.mirrorMinor,u=n[e],c=0;3>c;++c)if(e!==c){var f=a,h=s,p=o,d=l;u&1<0?(p[c]=-1,d[c]=0):(p[c]=0,d[c]=1)}}function s(t,e){var r=new i(t);return r.update(e),r}e.exports=s;var l=t("./lib/text.js"),u=t("./lib/lines.js"),c=t("./lib/background.js"),f=t("./lib/cube.js"),h=t("./lib/ticks.js"),p=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),d=i.prototype;d.update=function(t){function e(e,r,n){if(n in t){var i,a=t[n],o=this[n];(e?Array.isArray(a)&&Array.isArray(a[0]):Array.isArray(a))?this[n]=i=[r(a[0]),r(a[1]),r(a[2])]:this[n]=i=[r(a),r(a),r(a)];for(var s=0;3>s;++s)if(i[s]!==o[s])return!0}return!1}t=t||{};var r,n=e.bind(this,!1,Number),i=e.bind(this,!1,Boolean),a=e.bind(this,!1,String),o=e.bind(this,!0,function(t){if(Array.isArray(t)){if(3===t.length)return[+t[0],+t[1],+t[2],1];if(4===t.length)return[+t[0],+t[1],+t[2],+t[3]]}return[0,0,0,1]}),s=!1,c=!1;if("bounds"in t)for(var f=t.bounds,p=0;2>p;++p)for(var d=0;3>d;++d)f[p][d]!==this.bounds[p][d]&&(c=!0),this.bounds[p][d]=f[p][d];if("ticks"in t){r=t.ticks,s=!0,this.autoTicks=!1;for(var p=0;3>p;++p)this.tickSpacing[p]=0}else n("tickSpacing")&&(this.autoTicks=!0,c=!0);if(this._firstInit&&("ticks"in t||"tickSpacing"in t||(this.autoTicks=!0),c=!0,s=!0,this._firstInit=!1),c&&this.autoTicks&&(r=h.create(this.bounds,this.tickSpacing),s=!0),s){for(var p=0;3>p;++p)r[p].sort(function(t,e){return t.x-e.x});h.equal(r,this.ticks)?s=!1:this.ticks=r}i("tickEnable"),a("tickFont")&&(s=!0),n("tickSize"),n("tickAngle"),n("tickPad"),o("tickColor");var g=a("labels");a("labelFont")&&(g=!0),i("labelEnable"),n("labelSize"),n("labelPad"),o("labelColor"),i("lineEnable"),i("lineMirror"),n("lineWidth"),o("lineColor"),i("lineTickEnable"),i("lineTickMirror"),n("lineTickLength"),n("lineTickWidth"),o("lineTickColor"),i("gridEnable"),n("gridWidth"),o("gridColor"),i("zeroEnable"),o("zeroLineColor"),n("zeroLineWidth"),i("backgroundEnable"),o("backgroundColor"),this._text?this._text&&(g||s)&&this._text.update(this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont):this._text=l(this.gl,this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont),this._lines&&s&&(this._lines.dispose(),this._lines=null),this._lines||(this._lines=u(this.gl,this.bounds,this.ticks))};var g=[new a,new a,new a],v=[0,0,0],m={model:p,view:p,projection:p};d.isOpaque=function(){return!0},d.isTransparent=function(){return!1},d.drawTransparent=function(t){};var y=[0,0,0],b=[0,0,0],x=[0,0,0];d.draw=function(t){t=t||m;for(var e=this.gl,r=t.model||p,i=t.view||p,a=t.projection||p,s=this.bounds,l=f(r,i,a,s),u=l.cubeEdges,c=l.axis,h=i[12],d=i[13],_=i[14],w=i[15],k=this.pixelRatio*(a[3]*h+a[7]*d+a[11]*_+a[15]*w)/e.drawingBufferHeight,A=0;3>A;++A)this.lastCubeProps.cubeEdges[A]=u[A],this.lastCubeProps.axis[A]=c[A];for(var M=g,A=0;3>A;++A)o(g[A],A,this.bounds,u,c);for(var e=this.gl,T=v,A=0;3>A;++A)this.backgroundEnable[A]?T[A]=c[A]:T[A]=0;this._background.draw(r,i,a,s,T,this.backgroundColor),this._lines.bind(r,i,a,this);for(var A=0;3>A;++A){var E=[0,0,0];c[A]>0?E[A]=s[1][A]:E[A]=s[0][A];for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.gridEnable[S]&&this._lines.drawGrid(S,C,this.bounds,E,this.gridColor[S],this.gridWidth[S]*this.pixelRatio)}for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.zeroEnable[C]&&s[0][C]<=0&&s[1][C]>=0&&this._lines.drawZero(S,C,this.bounds,E,this.zeroLineColor[C],this.zeroLineWidth[C]*this.pixelRatio)}}for(var A=0;3>A;++A){this.lineEnable[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].primalOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio),this.lineMirror[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].mirrorOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio);for(var z=n(y,M[A].primalMinor),P=n(b,M[A].mirrorMinor),R=this.lineTickLength,L=0;3>L;++L){var j=k/r[5*L];z[L]*=R[L]*j,P[L]*=R[L]*j}this.lineTickEnable[A]&&this._lines.drawAxisTicks(A,M[A].primalOffset,z,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio),this.lineTickMirror[A]&&this._lines.drawAxisTicks(A,M[A].mirrorOffset,P,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio)}this._text.bind(r,i,a,this.pixelRatio);for(var A=0;3>A;++A){for(var O=M[A].primalMinor,I=n(x,M[A].primalOffset),L=0;3>L;++L)this.lineTickEnable[A]&&(I[L]+=k*O[L]*Math.max(this.lineTickLength[L],0)/r[5*L]);if(this.tickEnable[A]){for(var L=0;3>L;++L)I[L]+=k*O[L]*this.tickPad[L]/r[5*L];this._text.drawTicks(A,this.tickSize[A],this.tickAngle[A],I,this.tickColor[A])}if(this.labelEnable[A]){for(var L=0;3>L;++L)I[L]+=k*O[L]*this.labelPad[L]/r[5*L];I[A]+=.5*(s[0][A]+s[1][A]),this._text.drawLabel(A,this.labelSize[A],this.labelAngle[A],I,this.labelColor[A])}}},d.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":466,"./lib/cube.js":467,"./lib/lines.js":468,"./lib/text.js":470,"./lib/ticks.js":471}],466:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}function i(t){for(var e=[],r=[],i=0,l=0;3>l;++l)for(var u=(l+1)%3,c=(l+2)%3,f=[0,0,0],h=[0,0,0],p=-1;1>=p;p+=2){r.push(i,i+2,i+1,i+1,i+2,i+3),f[l]=p,h[l]=p;for(var d=-1;1>=d;d+=2){f[u]=d;for(var g=-1;1>=g;g+=2)f[c]=g,e.push(f[0],f[1],f[2],h[0],h[1],h[2]),i+=1}var v=u;u=c,c=v}var m=a(t,new Float32Array(e)),y=a(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),b=o(t,[{buffer:m,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:m,type:t.FLOAT,size:3,offset:12,stride:24}],y),x=s(t);return x.attributes.position.location=0,x.attributes.normal.location=1,new n(t,m,b,x)}e.exports=i;var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders").bg,l=n.prototype;l.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;3>s;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),l.disable(l.POLYGON_OFFSET_FILL)}},l.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":469,"gl-buffer":475,"gl-vao":480}],467:[function(t,e,r){"use strict";function n(t,e,r){for(var n=0;4>n;++n){t[n]=r[12+n];for(var i=0;3>i;++i)t[n]+=e[i]*r[4*i+n]}}function i(t){for(var e=0;eg;++g){p[2]=a[g][2];for(var b=0;2>b;++b){p[1]=a[b][1];for(var x=0;2>x;++x)p[0]=a[x][0],n(f[l],p,c),l+=1}}for(var _=-1,g=0;8>g;++g){for(var w=f[g][3],k=0;3>k;++k)h[g][k]=f[g][k]/w;0>w&&(0>_?_=g:h[g][2]_){_=0;for(var A=0;3>A;++A){for(var M=(A+2)%3,T=(A+1)%3,E=-1,L=-1,S=0;2>S;++S){var C=S<E||0>L)L>E&&(_|=1<S;++S){var C=S<E&&(_|=1<g;++g)g!==_&&g!==j&&(0>O?O=g:h[O][1]>h[g][1]&&(O=g));for(var I=-1,g=0;3>g;++g){var N=O^1<I&&(I=N);var T=h[N];T[0]g;++g){var N=O^1<F&&(F=N);var T=h[N];T[0]>h[F][0]&&(F=N)}}var D=v;D[0]=D[1]=D[2]=0,D[o.log2(I^O)]=O&I,D[o.log2(O^F)]=O&F;var B=7^F;B===_||B===j?(B=7^I,D[o.log2(F^B)]=B&F):D[o.log2(I^B)]=B&I;for(var U=m,V=_,A=0;3>A;++A)V&1<t;++t)f[t]=[1,1,1,1],h[t]=[1,1,1]}();var g=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]],v=[1,1,1],m=[0,0,0],y={cubeEdges:v,axis:m}},{"bit-twiddle":472,"gl-mat4/invert":240,"gl-mat4/multiply":242,"robust-orientation":1040,"split-polygon":482}],468:[function(t,e,r){"use strict";function n(t){return t[0]=t[1]=t[2]=0,t}function i(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function a(t,e,r,n,i,a,o,s){this.gl=t,this.vertBuffer=e,this.vao=r,this.shader=n,this.tickCount=i,this.tickOffset=a,this.gridCount=o,this.gridOffset=s}function o(t,e,r){var n=[],i=[0,0,0],o=[0,0,0],c=[0,0,0],f=[0,0,0];n.push(0,0,1,0,1,1,0,0,-1,0,0,-1,0,1,1,0,1,-1);for(var h=0;3>h;++h){for(var p=n.length/3|0,d=0;dh;++h)for(var d=c[h],g=2;g>=0;--g){var v=u[d[g]];s.push(l*v[0],-l*v[1],t)}}for(var s=(this.gl,[]),l=[0,0,0],u=[0,0,0],c=[0,0,0],p=[0,0,0],d=0;3>d;++d){c[d]=s.length/h|0,o(.5*(t[0][d]+t[1][d]),e[d],r),p[d]=(s.length/h|0)-c[d],l[d]=s.length/h|0;for(var g=0;g=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;0>o?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u=0|u);var c=""+l;if(0>o&&(c="-"+c),i){for(var f=""+u;f.lengthi;++i){for(var a=[],o=(.5*(t[0][i]+t[1][i]),0);o*e[i]<=t[1][i];++o)a.push({x:o*e[i],text:n(e[i],o)});for(var o=-1;o*e[i]>=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r}function a(t,e){for(var r=0;3>r;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;na?a=0:a>1&&(a=1);for(var o=1-a,s=t.length,l=new Array(s),u=0;s>u;++u)l[u]=a*t[u]+o*r[u];return l}function a(t,e){for(var r=[],a=[],o=n(t[t.length-1],e),s=t[t.length-1],l=t[0],u=0;uo&&c>0||o>0&&0>c){var f=i(s,c,l,o);r.push(f),a.push(f.slice())}0>c?a.push(l.slice()):c>0?r.push(l.slice()):(r.push(l.slice()),a.push(l.slice())),o=c}return{positive:r,negative:a}}function o(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&u>0||a>0&&0>u)&&r.push(i(o,u,s,a)),u>=0&&r.push(s.slice()),a=u}return r}function s(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&u>0||a>0&&0>u)&&r.push(i(o,u,s,a)),0>=u&&r.push(s.slice()),a=u}return r}var l=t("robust-dot-product"),u=t("robust-sum");e.exports=a,e.exports.positive=o,e.exports.negative=s},{"robust-dot-product":483,"robust-sum":485}],483:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t[0],e[0]),n=1;na;++a){for(var o=d,s=g,l=0;3>l;++l)s[l]=o[l]=r[l];s[3]=o[3]=1,s[a]+=1,f(s,s,e),s[3]<0&&(t[a]=1/0),o[a]-=1,f(o,o,e),o[3]<0&&(t[a]=1/0);var u=(o[0]/o[3]-s[0]/s[3])*n,c=(o[1]/o[3]-s[1]/s[3])*i;t[a]=.25*Math.sqrt(u*u+c*c)}return t}function a(t,e,r,n,a){var f=e.model||h,d=e.view||h,g=e.projection||h,y=t.bounds,a=a||l(f,d,g,y),b=a.axis;a.edges;u(p,d,f),u(p,g,p);for(var x=v,_=0;3>_;++_)x[_].lo=1/0,x[_].hi=-(1/0),x[_].pixelsPerDataUnit=1/0;var w=o(c(p,p));c(p,p);for(var k=0;3>k;++k){var A=(k+1)%3,M=(k+2)%3,T=m;t:for(var _=0;2>_;++_){var E=[];if(b[k]<0!=!!_){T[k]=y[_][k];for(var L=0;2>L;++L){T[A]=y[L^_][A];for(var S=0;2>S;++S)T[M]=y[S^L^_][M],E.push(T.slice())}for(var L=0;LS;++S)x[S].lo=Math.min(x[S].lo,M[S]),x[S].hi=Math.max(x[S].hi,M[S]),S!==k&&(x[S].pixelsPerDataUnit=Math.min(x[S].pixelsPerDataUnit,Math.abs(C[S])))}}}return x}e.exports=a;var o=t("extract-frustum-planes"),s=t("split-polygon"),l=t("./lib/cube.js"),u=t("gl-mat4/multiply"),c=t("gl-mat4/transpose"),f=t("gl-vec4/transformMat4"),h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),p=new Float32Array(16),d=[0,0,0,1],g=[0,0,0,1],v=[new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0)],m=[0,0,0]},{"./lib/cube.js":467,"extract-frustum-planes":474,"gl-mat4/multiply":242,"gl-mat4/transpose":250,"gl-vec4/transformMat4":481,"split-polygon":482}],576:[function(t,e,r){arguments[4][323][0].apply(r,arguments)},{dup:323,"gl-texture2d":580}],577:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],578:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],579:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":577,buffer:65,dup:122}],580:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":579}],581:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],582:[function(t,e,r){arguments[4][318][0].apply(r,arguments)},{"cwise-compiler":583,dup:318}],583:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":585,dup:319}],584:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:586}],585:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":584,dup:321}],586:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],587:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],588:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":581,buffer:65,dup:122}],589:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.coord=[t,e],this.id=r,this.value=n,this.distance=i}function i(t,e,r){this.gl=t,this.fbo=e,this.buffer=r,this._readTimeout=null;var n=this;this._readCallback=function(){n.gl&&(e.bind(),t.readPixels(0,0,e.shape[0],e.shape[1],t.RGBA,t.UNSIGNED_BYTE,n.buffer),n._readTimeout=null)}}function a(t,e){var r=o(t,e),n=s.mallocUint8(e[0]*e[1]*4);return new i(t,r,n)}e.exports=a;var o=t("gl-fbo"),s=t("typedarray-pool"),l=t("ndarray"),u=t("bit-twiddle").nextPow2,c=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(255>_inline_4_arg0_||255>_inline_4_arg1_||255>_inline_4_arg2_||255>_inline_4_arg3_){var _inline_4_l=_inline_4_arg4_-_inline_4_arg6_[0],_inline_4_a=_inline_4_arg5_-_inline_4_arg6_[1],_inline_4_f=_inline_4_l*_inline_4_l+_inline_4_a*_inline_4_a;_inline_4_fthis.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(u(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),f.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},f.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},f.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),u=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=u)return null;var f=[o-a,u-s],h=l(this.buffer,[f[0],f[1],4],[4,4*i[0],1],4*(a+i[0]*s)),p=c(h.hi(f[0],f[1],1),r,r),d=p[0],g=p[1];if(0>d||Math.pow(this.radius,2)d;++d)i&&i[d]<0?(u[d]=this.bounds[0][d],p[d]=this.bounds[1][d]):(u[d]=this.bounds[1][d],p[d]=this.bounds[0][d]);h[0]=e.drawingBufferWidth,h[1]=e.drawingBufferHeight,n.uniforms.model=a,n.uniforms.view=o,n.uniforms.projection=s,n.uniforms.coordinates=[this.position,u,p],n.uniforms.colors=this.colors,n.uniforms.screenShape=h;for(var d=0;3>d;++d)n.uniforms.lineWidth=this.lineWidth[d]*this.pixelRatio,this.enabled[d]&&(r.draw(e.TRIANGLES,6,6*d),this.drawSides[d]&&r.draw(e.TRIANGLES,12,18+12*d));r.unbind()},u.update=function(t){t&&("bounds"in t&&(this.bounds=t.bounds),"position"in t&&(this.position=t.position),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"colors"in t&&(this.colors=t.colors),"enabled"in t&&(this.enabled=t.enabled),"drawSides"in t&&(this.drawSides=t.drawSides))},u.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders/index":624,"gl-buffer":616,"gl-vao":623}],626:[function(t,e,r){"use strict";function n(){this.mouse=[-1,-1],this.screen=null,this.distance=1/0,this.index=null,this.dataCoordinate=null,this.dataPosition=null,this.object=null,this.data=null}function i(t,e){var r=null;try{r=t.getContext("webgl",e),r||(r=t.getContext("experimental-webgl",e))}catch(n){return null}return r}function a(t){var e=Math.round(Math.log(Math.abs(t))/Math.log(10));if(0>e){var r=Math.round(Math.pow(10,-e));return Math.ceil(t*r)/r}if(e>0){var r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function o(t){return"boolean"==typeof t?t:!0}function s(t){function e(){if(!_&&G.autoResize){var t=w.parentNode,e=1,r=1;t&&t!==document.body?(e=t.clientWidth,r=t.clientHeight):(e=window.innerWidth,r=window.innerHeight);var n=0|Math.ceil(e*G.pixelRatio),i=0|Math.ceil(r*G.pixelRatio);if(n!==w.width||i!==w.height){w.width=n,w.height=i;var a=w.style;a.position=a.position||"absolute",a.left="0px",a.top="0px",a.width=e+"px",a.height=r+"px",F=!0}}}function r(){for(var t=j.length,e=N.length,r=0;e>r;++r)I[r]=0;t:for(var r=0;t>r;++r){var n=j[r],i=n.pickSlots;if(i){for(var a=0;e>a;++a)if(I[a]+i<255){O[r]=a,n.setPickBase(I[a]+1),I[a]+=i;continue t}var o=h(A,q);O[r]=e,N.push(o),I.push(i),n.setPickBase(1),e+=1}else O[r]=-1}for(;e>0&&0===I[e-1];)I.pop(),N.pop().dispose()}function s(){return G.contextLost?!0:void(A.isContextLost()&&(G.contextLost=!0,G.mouseListener.enabled=!1,G.selection.object=null,G.oncontextloss&&G.oncontextloss()))}function y(){if(!s()){A.colorMask(!0,!0,!0,!0),A.depthMask(!0),A.disable(A.BLEND),A.enable(A.DEPTH_TEST);for(var t=j.length,e=N.length,r=0;e>r;++r){var n=N[r];n.shape=H,n.begin();for(var i=0;t>i;++i)if(O[i]===r){var a=j[i];a.drawPick&&(a.pixelRatio=1,a.drawPick(V))}n.end()}}}function b(){if(!s()){e();var t=G.camera.tick();V.view=G.camera.matrix,F=F||t,D=D||t,z.pixelRatio=G.pixelRatio,R.pixelRatio=G.pixelRatio;var r=j.length,n=W[0],i=W[1];n[0]=n[1]=n[2]=1/0,i[0]=i[1]=i[2]=-(1/0);for(var o=0;r>o;++o){var l=j[o];l.pixelRatio=G.pixelRatio,l.axes=G.axes,F=F||!!l.dirty,D=D||!!l.dirty;var u=l.bounds;if(u)for(var f=u[0],h=u[1],p=0;3>p;++p)n[p]=Math.min(n[p],f[p]),i[p]=Math.max(i[p],h[p])}var g=G.bounds;if(G.autoBounds)for(var p=0;3>p;++p){if(i[p]p;++p)b=b||Z[0][p]!==g[0][p]||Z[1][p]!==g[1][p],Z[0][p]=g[0][p],Z[1][p]=g[1][p];if(b){for(var x=[0,0,0],o=0;3>o;++o)x[o]=a((g[1][o]-g[0][o])/10);z.autoTicks?z.update({bounds:g,tickSpacing:x}):z.update({bounds:g})}D=D||b,F=F||b;var _=A.drawingBufferWidth,w=A.drawingBufferHeight;q[0]=_,q[1]=w,H[0]=0|Math.max(_/G.pixelRatio,1),H[1]=0|Math.max(w/G.pixelRatio,1),v(B,G.fovy,_/w,G.zNear,G.zFar);for(var o=0;16>o;++o)U[o]=0;U[15]=1;for(var k=0,o=0;3>o;++o)k=Math.max(k,g[1][o]-g[0][o]);for(var o=0;3>o;++o)G.autoScale?U[5*o]=G.aspect[o]/(g[1][o]-g[0][o]):U[5*o]=1/k,G.autoCenter&&(U[12+o]=.5*-U[5*o]*(g[0][o]+g[1][o])); -for(var o=0;r>o;++o){var l=j[o];l.axesBounds=g,G.clipToBounds&&(l.clipBounds=g)}if(T.object&&(G.snapToData?R.position=T.dataCoordinate:R.position=T.dataPosition,R.bounds=g),D&&(D=!1,y()),F){G.axesPixels=c(G.axes,V,_,w),G.onrender&&G.onrender(),A.bindFramebuffer(A.FRAMEBUFFER,null),A.viewport(0,0,_,w);var M=G.clearColor;A.clearColor(M[0],M[1],M[2],M[3]),A.clear(A.COLOR_BUFFER_BIT|A.DEPTH_BUFFER_BIT),A.depthMask(!0),A.colorMask(!0,!0,!0,!0),A.enable(A.DEPTH_TEST),A.depthFunc(A.LEQUAL),A.disable(A.BLEND),A.disable(A.CULL_FACE);var S=!1;z.enable&&(S=S||z.isTransparent(),z.draw(V)),R.axes=z,T.object&&R.draw(V),A.disable(A.CULL_FACE);for(var o=0;r>o;++o){var l=j[o];l.axes=z,l.pixelRatio=G.pixelRatio,l.isOpaque&&l.isOpaque()&&l.draw(V),l.isTransparent&&l.isTransparent()&&(S=!0)}if(S){E.shape=q,E.bind(),A.clear(A.DEPTH_BUFFER_BIT),A.colorMask(!1,!1,!1,!1),A.depthMask(!0),A.depthFunc(A.LESS),z.enable&&z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=j[o];l.isOpaque&&l.isOpaque()&&l.draw(V)}A.enable(A.BLEND),A.blendEquation(A.FUNC_ADD),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.colorMask(!0,!0,!0,!0),A.depthMask(!1),A.clearColor(0,0,0,0),A.clear(A.COLOR_BUFFER_BIT),z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=j[o];l.isTransparent&&l.isTransparent()&&l.drawTransparent(V)}A.bindFramebuffer(A.FRAMEBUFFER,null),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.disable(A.DEPTH_TEST),L.bind(),E.color[0].bind(0),L.uniforms.accumBuffer=0,d(A),A.disable(A.BLEND)}F=!1;for(var o=0;r>o;++o)j[o].dirty=!1}}}function x(){_||G.contextLost||(requestAnimationFrame(x),b())}t=t||{};var _=!1,w=(t.pixelRatio||parseFloat(window.devicePixelRatio),t.canvas);if(!w)if(w=document.createElement("canvas"),t.container){var k=t.container;k.appendChild(w)}else document.body.appendChild(w);var A=t.gl;if(A||(A=i(w,t.glOptions||{premultipliedAlpha:!0,antialias:!0})),!A)throw new Error("webgl not supported");var M=t.bounds||[[-10,-10,-10],[10,10,10]],T=new n,E=p(A,[A.drawingBufferWidth,A.drawingBufferHeight],{preferFloat:!0}),L=m(A),S=t.camera||{eye:[2,0,0],center:[0,0,0],up:[0,1,0],zoomMin:.1,zoomMax:100,mode:"turntable"},C=t.axes||{},z=u(A,C);z.enable=!C.disable;var P=t.spikes||{},R=f(A,P),j=[],O=[],I=[],N=[],F=!0,D=!0,B=new Array(16),U=new Array(16),V={view:null,projection:B,model:U},D=!0,q=[A.drawingBufferWidth,A.drawingBufferHeight],G={gl:A,contextLost:!1,pixelRatio:t.pixelRatio||parseFloat(window.devicePixelRatio),canvas:w,selection:T,camera:l(w,S),axes:z,axesPixels:null,spikes:R,bounds:M,objects:j,shape:q,aspect:t.aspectRatio||[1,1,1],pickRadius:t.pickRadius||10,zNear:t.zNear||.01,zFar:t.zFar||1e3,fovy:t.fovy||Math.PI/4,clearColor:t.clearColor||[0,0,0,0],autoResize:o(t.autoResize),autoBounds:o(t.autoBounds),autoScale:!!t.autoScale,autoCenter:o(t.autoCenter),clipToBounds:o(t.clipToBounds),snapToData:!!t.snapToData,onselect:t.onselect||null,onrender:t.onrender||null,onclick:t.onclick||null,cameraParams:V,oncontextloss:null,mouseListener:null},H=[A.drawingBufferWidth/G.pixelRatio|0,A.drawingBufferHeight/G.pixelRatio|0];G.autoResize&&e(),window.addEventListener("resize",e),G.update=function(t){_||(t=t||{},F=!0,D=!0)},G.add=function(t){_||(t.axes=z,j.push(t),O.push(-1),F=!0,D=!0,r())},G.remove=function(t){if(!_){var e=j.indexOf(t);0>e||(j.splice(e,1),O.pop(),F=!0,D=!0,r())}},G.dispose=function(){if(!_&&(_=!0,window.removeEventListener("resize",e),w.removeEventListener("webglcontextlost",s),G.mouseListener.enabled=!1,!G.contextLost)){z.dispose(),R.dispose();for(var t=0;ts;++s){var l=N[s].query(e,H[1]-r-1,G.pickRadius);if(l){if(l.distance>T.distance)continue;for(var u=0;i>u;++u){var c=j[u];if(O[u]===s){var f=c.pick(l);f&&(T.buttons=t,T.screen=l.coord,T.distance=l.distance,T.object=c,T.index=f.distance,T.dataPosition=f.position,T.dataCoordinate=f.dataCoordinate,T.data=f,o=!0)}}}}}a&&a!==T.object&&(a.highlight&&a.highlight(null),F=!0),T.object&&(T.object.highlight&&T.object.highlight(T.data),F=!0),o=o||T.object!==a,o&&G.onselect&&G.onselect(T),1&t&&!(1&X)&&G.onclick&&G.onclick(T),X=t}}),w.addEventListener("webglcontextlost",s);var W=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],Z=[W[0].slice(),W[1].slice()];return x(),G.redraw=function(){_||(F=!0,b())},G}e.exports=s;var l=t("3d-view-controls"),u=t("gl-axes3d"),c=t("gl-axes3d/properties"),f=t("gl-spikes3d"),h=t("gl-select-static"),p=t("gl-fbo"),d=t("a-big-triangle"),g=t("mouse-change"),v=t("gl-mat4/perspective"),m=t("./lib/shader")},{"./lib/shader":453,"3d-view-controls":454,"a-big-triangle":464,"gl-axes3d":465,"gl-axes3d/properties":575,"gl-fbo":576,"gl-mat4/perspective":243,"gl-select-static":589,"gl-spikes3d":625,"mouse-change":1004}],627:[function(t,e,r){"use strict";e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",fragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n",pickVertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",pickFragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n"}},{}],628:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":658}],629:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":630,"./lib/create-attributes":631,"./lib/create-uniforms":632,"./lib/reflect":633,"./lib/runtime-reflect":634,"./lib/shader-cache":635,dup:94}],630:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],631:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":630,dup:96}],632:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":630,"./reflect":633,dup:97}],633:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],634:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],635:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":630,dup:100,"gl-format-compiler-error":636,"weakmap-shim":654}],636:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":637,dup:101,"gl-constants/lookup":641,"glsl-shader-name":642,"sprintf-js":651}],637:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":638}],638:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":639}],639:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],640:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],641:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":640,dup:106}],642:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":643,dup:107,"glsl-tokenizer":650}],643:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],644:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":646,"./lib/builtins-300es":645,"./lib/literals":648,"./lib/literals-300es":647,"./lib/operators":649,dup:109}],645:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":646,dup:110}],646:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],647:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":648,dup:112}],648:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],649:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],650:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":644,dup:115}],651:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],652:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":653,dup:117}],653:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],654:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":652,dup:119}],655:[function(t,e,r){arguments[4][451][0].apply(r,arguments)},{_process:70,dup:451,"vectorize-text":659}],656:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],657:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],658:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":656,buffer:65,dup:122}],659:[function(t,e,r){arguments[4][354][0].apply(r,arguments)},{"./lib/vtext":660,dup:354}],660:[function(t,e,r){arguments[4][355][0].apply(r,arguments)},{cdt2d:661,"clean-pslg":673,dup:355,ndarray:1031,"planar-graph-to-polyline":728,"simplify-planar-graph":732,"surface-nets":745}],661:[function(t,e,r){arguments[4][356][0].apply(r,arguments)},{"./lib/delaunay":662,"./lib/filter":663,"./lib/monotone":664,"./lib/triangulation":665,dup:356}],662:[function(t,e,r){arguments[4][357][0].apply(r,arguments)},{"binary-search-bounds":666,dup:357,"robust-in-sphere":667}],663:[function(t,e,r){arguments[4][358][0].apply(r,arguments)},{"binary-search-bounds":666,dup:358}],664:[function(t,e,r){arguments[4][359][0].apply(r,arguments)},{"binary-search-bounds":666,dup:359,"robust-orientation":1040}],665:[function(t,e,r){arguments[4][360][0].apply(r,arguments)},{"binary-search-bounds":666,dup:360}],666:[function(t,e,r){arguments[4][312][0].apply(r,arguments)},{dup:312}],667:[function(t,e,r){arguments[4][361][0].apply(r,arguments)},{dup:361,"robust-scale":669,"robust-subtract":670,"robust-sum":671,"two-product":672}],668:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],669:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":672,"two-sum":668}],670:[function(t,e,r){arguments[4][364][0].apply(r,arguments)},{dup:364}],671:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],672:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],673:[function(t,e,r){arguments[4][367][0].apply(r,arguments)},{"./lib/rat-seg-intersect":674,"big-rat":678,"big-rat/cmp":676,"big-rat/to-float":693,"box-intersect":694,"compare-cell":702,dup:367,nextafter:703,"rat-vec":706,"robust-segment-intersect":709,"union-find":710}],674:[function(t,e,r){arguments[4][368][0].apply(r,arguments)},{"big-rat/div":677,"big-rat/mul":687,"big-rat/sign":691,"big-rat/sub":692,"big-rat/to-float":693,dup:368,"rat-vec/add":705,"rat-vec/muls":707,"rat-vec/sub":708}],675:[function(t,e,r){arguments[4][369][0].apply(r,arguments)},{"./lib/rationalize":685,dup:369}],676:[function(t,e,r){arguments[4][370][0].apply(r,arguments)},{dup:370}],677:[function(t,e,r){arguments[4][371][0].apply(r,arguments)},{"./lib/rationalize":685,dup:371}],678:[function(t,e,r){arguments[4][372][0].apply(r,arguments)},{"./div":677,"./is-rat":679,"./lib/is-bn":683,"./lib/num-to-bn":684,"./lib/rationalize":685,"./lib/str-to-bn":686,dup:372}],679:[function(t,e,r){arguments[4][373][0].apply(r,arguments)},{"./lib/is-bn":683,dup:373}],680:[function(t,e,r){arguments[4][374][0].apply(r,arguments)},{"bn.js":689,dup:374}],681:[function(t,e,r){arguments[4][375][0].apply(r,arguments)},{dup:375}],682:[function(t,e,r){arguments[4][376][0].apply(r,arguments)},{"bit-twiddle":688,"double-bits":690,dup:376}],683:[function(t,e,r){arguments[4][377][0].apply(r,arguments)},{"bn.js":689,dup:377}],684:[function(t,e,r){arguments[4][378][0].apply(r,arguments)},{"bn.js":689,"double-bits":690,dup:378}],685:[function(t,e,r){arguments[4][379][0].apply(r,arguments)},{"./bn-sign":680,"./num-to-bn":684,dup:379}],686:[function(t,e,r){arguments[4][380][0].apply(r,arguments)},{"bn.js":689,dup:380}],687:[function(t,e,r){arguments[4][381][0].apply(r,arguments)},{"./lib/rationalize":685,dup:381}],688:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],689:[function(t,e,r){arguments[4][383][0].apply(r,arguments)},{dup:383}],690:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],691:[function(t,e,r){arguments[4][385][0].apply(r,arguments)},{"./lib/bn-sign":680,dup:385}],692:[function(t,e,r){arguments[4][386][0].apply(r,arguments)},{"./lib/rationalize":685,dup:386}],693:[function(t,e,r){arguments[4][387][0].apply(r,arguments)},{"./lib/bn-to-num":681,"./lib/ctz":682,dup:387}],694:[function(t,e,r){arguments[4][388][0].apply(r,arguments)},{"./lib/intersect":696,"./lib/sweep":700,dup:388,"typedarray-pool":658}],695:[function(t,e,r){arguments[4][389][0].apply(r,arguments)},{dup:389}],696:[function(t,e,r){arguments[4][390][0].apply(r,arguments)},{"./brute":695,"./median":697,"./partition":698,"./sweep":700,"bit-twiddle":701,dup:390,"typedarray-pool":658}],697:[function(t,e,r){arguments[4][391][0].apply(r,arguments)},{"./partition":698,dup:391}],698:[function(t,e,r){arguments[4][392][0].apply(r,arguments)},{dup:392}],699:[function(t,e,r){arguments[4][393][0].apply(r,arguments)},{dup:393}],700:[function(t,e,r){arguments[4][394][0].apply(r,arguments)},{"./sort":699,"bit-twiddle":701,dup:394,"typedarray-pool":658}],701:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],702:[function(t,e,r){arguments[4][61][0].apply(r,arguments)},{dup:61}],703:[function(t,e,r){arguments[4][399][0].apply(r,arguments)},{"double-bits":704,dup:399}],704:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],705:[function(t,e,r){arguments[4][401][0].apply(r,arguments)},{"big-rat/add":675,dup:401}],706:[function(t,e,r){arguments[4][402][0].apply(r,arguments)},{"big-rat":678,dup:402}],707:[function(t,e,r){arguments[4][403][0].apply(r,arguments)},{"big-rat":678,"big-rat/mul":687,dup:403}],708:[function(t,e,r){arguments[4][404][0].apply(r,arguments)},{"big-rat/sub":692,dup:404}],709:[function(t,e,r){arguments[4][405][0].apply(r,arguments)},{dup:405,"robust-orientation":1040}],710:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],711:[function(t,e,r){arguments[4][407][0].apply(r,arguments)},{dup:407,"edges-to-adjacency-list":712}],712:[function(t,e,r){arguments[4][408][0].apply(r,arguments)},{dup:408,uniq:727}],713:[function(t,e,r){arguments[4][409][0].apply(r,arguments)},{"compare-angle":714,dup:409}],714:[function(t,e,r){arguments[4][410][0].apply(r,arguments)},{dup:410,"robust-orientation":1040,"robust-product":716,"robust-sum":725,signum:717,"two-sum":718}],715:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":726,"two-sum":718}],716:[function(t,e,r){arguments[4][412][0].apply(r,arguments)},{dup:412,"robust-scale":715,"robust-sum":725}],717:[function(t,e,r){arguments[4][413][0].apply(r,arguments)},{dup:413}],718:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],719:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],720:[function(t,e,r){arguments[4][416][0].apply(r,arguments)},{"binary-search-bounds":719,dup:416}],721:[function(t,e,r){arguments[4][417][0].apply(r,arguments)},{dup:417,"robust-orientation":1040}],722:[function(t,e,r){arguments[4][418][0].apply(r,arguments)},{dup:418}],723:[function(t,e,r){arguments[4][419][0].apply(r,arguments)},{"./lib/order-segments":721,"binary-search-bounds":719,dup:419,"functional-red-black-tree":722,"robust-orientation":1040}],724:[function(t,e,r){arguments[4][420][0].apply(r,arguments)},{"binary-search-bounds":719,dup:420,"interval-tree-1d":720,"robust-orientation":1040,"slab-decomposition":723}],725:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],726:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],727:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],728:[function(t,e,r){arguments[4][424][0].apply(r,arguments)},{"./lib/trim-leaves":711,dup:424,"edges-to-adjacency-list":712,"planar-dual":713,"point-in-big-polygon":724,"robust-sum":725,"two-product":726,uniq:727}],729:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],730:[function(t,e,r){arguments[4][426][0].apply(r,arguments)},{dup:426}],731:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":729,dup:79,"union-find":730}],732:[function(t,e,r){arguments[4][428][0].apply(r,arguments)},{dup:428,"robust-orientation":1040,"simplicial-complex":731}],733:[function(t,e,r){arguments[4][429][0].apply(r,arguments)},{dup:429,"typedarray-pool":658}],734:[function(t,e,r){arguments[4][433][0].apply(r,arguments)},{dup:433}],735:[function(t,e,r){arguments[4][437][0].apply(r,arguments)},{dup:437,"typedarray-pool":658}],736:[function(t,e,r){arguments[4][438][0].apply(r,arguments)},{dup:438,"invert-permutation":737,"typedarray-pool":658}],737:[function(t,e,r){arguments[4][439][0].apply(r,arguments)},{dup:439}],738:[function(t,e,r){arguments[4][443][0].apply(r,arguments)},{dup:443,gamma:734,"permutation-parity":735,"permutation-rank":736}],739:[function(t,e,r){arguments[4][444][0].apply(r,arguments)},{"cwise-compiler":740,dup:444}],740:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":742,dup:319}],741:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:743}],742:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":741,dup:321}],743:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],744:[function(t,e,r){arguments[4][449][0].apply(r,arguments)},{"./lib/zc-core":739,dup:449}],745:[function(t,e,r){arguments[4][450][0].apply(r,arguments)},{dup:450,"ndarray-extract-contour":733,"triangulate-hypercube":738,"zero-crossings":744}],746:[function(t,e,r){"use strict";function n(t){if(t in h)return h[t];var e=c(t,{polygons:!0,font:"sans-serif",textAlign:"left",textBaseline:"alphabetic"}),r=[],n=[];e.forEach(function(t){t.forEach(function(t){for(var e=0;eo;++o)i[o]=Math.min(i[o],r[a+o]),i[2+o]=Math.max(i[2+o],r[a+o]);return h[t]={coords:r,normals:n,bounds:i}}function i(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.offsetBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.numVertices=0,this.pickOffset=0,this.points=null}function a(t,e){var r=t.gl,n=o(r,f.vertex,f.fragment),a=o(r,f.pickVertex,f.pickFragment),l=s(r),u=s(r),c=s(r),h=s(r),p=new i(t,n,a,l,u,c,h);return p.update(e),t.addObject(p),p}e.exports=a;var o=t("gl-shader"),s=t("gl-buffer"),l=t("text-cache"),u=t("typedarray-pool"),c=t("vectorize-text"),f=t("./lib/shaders"),h={},p=i.prototype;!function(){function t(){var t=this.plot,n=this.bounds,i=t.viewBox,a=t.dataBox,o=t.pixelRatio,s=n[2]-n[0],l=n[3]-n[1],u=a[2]-a[0],c=a[3]-a[1];e[0]=2*s/u,e[4]=2*l/c,e[6]=2*(n[0]-a[0])/u-1,e[7]=2*(n[1]-a[1])/c-1;var f=i[2]-i[0],h=i[3]-i[1];r[0]=2*o/f,r[1]=2*o/h}var e=[1,0,0,0,1,0,0,0,1],r=[1,1];p.draw=function(){var n=this.plot,i=this.shader,a=this.numVertices;if(a){var o=n.gl;t.call(this),i.bind(),i.uniforms.pixelScale=r,i.uniforms.viewTransform=e,this.positionBuffer.bind(),i.attributes.position.pointer(),this.offsetBuffer.bind(),i.attributes.offset.pointer(),this.colorBuffer.bind(),i.attributes.color.pointer(o.UNSIGNED_BYTE,!0),o.drawArrays(o.TRIANGLES,0,a)}};var n=[0,0,0,0];p.drawPick=function(i){var a=this.plot,o=this.pickShader,s=this.numVertices,l=a.gl;if(this.pickOffset=i,!s)return i;for(var u=0;4>u;++u)n[u]=i>>8*u&255;return t.call(this),o.bind(),o.uniforms.pixelScale=r,o.uniforms.viewTransform=e,o.uniforms.pickOffset=n,this.positionBuffer.bind(),o.attributes.position.pointer(),this.offsetBuffer.bind(),o.attributes.offset.pointer(),this.idBuffer.bind(),o.attributes.id.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,s),i+this.numPoints}}(),p.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},p.update=function(t){t=t||{};var e=t.positions||[],r=t.colors||[],i=t.glyphs||[],a=t.sizes||[],o=t.borderWidths||[],s=t.borderColors||[];this.points=e;for(var c=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=0,h=0;h>1;for(var p=0;2>p;++p)c[p]=Math.min(c[p],e[2*h+p]),c[2+p]=Math.max(c[2+p],e[2*h+p])}c[0]===c[2]&&(c[2]+=1),c[3]===c[1]&&(c[3]+=1);for(var d=1/(c[2]-c[0]),g=1/(c[3]-c[1]),v=c[0],m=c[1],y=u.mallocFloat32(2*f),b=u.mallocFloat32(2*f),x=u.mallocUint8(4*f),_=u.mallocUint32(f),w=0,h=0;h=a?i(0,a-1,t,e,r,n):f(0,a-1,t,e,r,n)}function i(t,e,r,n,i,a){for(var o=t+1;e>=o;++o){for(var s=r[o],l=n[2*o],u=n[2*o+1],c=i[o],f=a[o],h=o;h>t;){var p=r[h-1],d=n[2*(h-1)];if((p-s||l-d)>=0)break;r[h]=p,n[2*h]=d,n[2*h+1]=n[2*h-1],i[h]=i[h-1],a[h]=a[h-1],h-=1}r[h]=s,n[2*h]=l,n[2*h+1]=u,i[h]=c,a[h]=f}}function a(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],u=i[t],c=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=u,a[e]=c}function o(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function s(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],u=i[2*t+1],c=a[t],f=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=u,a[r]=c,o[r]=f}function l(t,e,r,n,i,a,o,s,l,u,c){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],u[t]=u[e],c[t]=c[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,u[e]=a,c[e]=o}function u(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function c(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}function f(t,e,r,n,p,d){var g=(e-t+1)/6|0,v=t+g,m=e-g,y=t+e>>1,b=y-g,x=y+g,_=v,w=b,k=y,A=x,M=m,T=t+1,E=e-1,L=0;u(_,w,r,n,p,d)&&(L=_,_=w,w=L),u(A,M,r,n,p,d)&&(L=A,A=M,M=L),u(_,k,r,n,p,d)&&(L=_,_=k,k=L),u(w,k,r,n,p,d)&&(L=w,w=k,k=L),u(_,A,r,n,p,d)&&(L=_,_=A,A=L),u(k,A,r,n,p,d)&&(L=k,k=A,A=L),u(w,M,r,n,p,d)&&(L=w,w=M,M=L),u(w,k,r,n,p,d)&&(L=w,w=k,k=L),u(A,M,r,n,p,d)&&(L=A,A=M,M=L);var S=r[w],C=n[2*w],z=n[2*w+1],P=p[w],R=d[w],j=r[A],O=n[2*A],I=n[2*A+1],N=p[A],F=d[A],D=_,B=k,U=M,V=v,q=y,G=m,H=r[D],Y=r[B],X=r[U];r[V]=H,r[q]=Y,r[G]=X;for(var W=0;2>W;++W){var Z=n[2*D+W],K=n[2*B+W],$=n[2*U+W];n[2*V+W]=Z,n[2*q+W]=K,n[2*G+W]=$}var Q=p[D],J=p[B],tt=p[U];p[V]=Q,p[q]=J,p[G]=tt;var et=d[D],rt=d[B],nt=d[U];d[V]=et,d[q]=rt,d[G]=nt,o(b,t,r,n,p,d),o(x,e,r,n,p,d);for(var it=T;E>=it;++it)if(c(it,S,C,z,P,r,n,p))it!==T&&a(it,T,r,n,p,d),++T;else if(!c(it,j,O,I,N,r,n,p))for(;;){if(c(E,j,O,I,N,r,n,p)){c(E,S,C,z,P,r,n,p)?(s(it,T,E,r,n,p,d),++T,--E):(a(it,E,r,n,p,d),--E);break}if(--E=T-2-t?i(t,T-2,r,n,p,d):f(t,T-2,r,n,p,d),h>=e-(E+2)?i(E+2,e,r,n,p,d):f(E+2,e,r,n,p,d),h>=E-T?i(T,E,r,n,p,d):f(T,E,r,n,p,d)}e.exports=n;var h=32},{}],777:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s){for(var l=r,u=r;n>u;++u){var c=t[2*u],f=t[2*u+1],h=e[u];c>=i&&o>=c&&f>=a&&s>=f&&(u===l?l+=1:(t[2*u]=t[2*l],t[2*u+1]=t[2*l+1],e[u]=e[l],t[2*l]=c,t[2*l+1]=f,e[l]=h,l+=1))}return l}function i(t,e,r){this.pixelSize=t,this.offset=e,this.count=r}function a(t,e,r,a){function l(i,a,o,s,u,c){var f=.5*o,h=s+1,p=u-s;r[_]=p,x[_++]=c;for(var d=0;2>d;++d)for(var g=0;2>g;++g){var v=i+d*f,m=a+g*f,y=n(t,e,h,u,v,m,v+f,m+f);if(y!==h){if(y-h>=Math.max(.9*p,32)){var b=u+s>>>1;l(v,m,f,h,b,c+1),h=b}l(v,m,f,h,y,c+1),h=y}}}var u=t.length>>>1;if(1>u)return[];for(var c=1/0,f=1/0,h=-(1/0),p=-(1/0),d=0;u>d;++d){var g=t[2*d],v=t[2*d+1];c=Math.min(c,g),h=Math.max(h,g),f=Math.min(f,v),p=Math.max(p,v),e[d]=d}c===h&&(h+=1+Math.abs(h)),f===p&&(p+=1+Math.abs(h));var m=1/(h-c),y=1/(p-f),b=Math.max(h-c,p-f);a=a||[0,0,0,0],a[0]=c,a[1]=f,a[2]=h,a[3]=p;var x=o.mallocInt32(u),_=0;l(c,f,b,0,u,0),s(x,t,e,r,u);for(var w=[],k=0,A=u,_=u-1;_>=0;--_){t[2*_]=(t[2*_]-c)*m,t[2*_+1]=(t[2*_+1]-f)*y;var M=x[_];M!==k&&(w.push(new i(b*Math.pow(.5,M),_+1,A-(_+1))),A=_+1,k=M)}return w.push(new i(b*Math.pow(.5,M+1),0,A)),o.free(x),w}var o=t("typedarray-pool"),s=t("./lib/sort");e.exports=a},{"./lib/sort":776,"typedarray-pool":780}],778:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],779:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],780:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":778,buffer:65,dup:122}],781:[function(t,e,r){"use strict"; -function n(t,e,r,n,i,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.weightBuffer=n,this.shader=i,this.pickShader=a,this.scales=[],this.size=12,this.borderSize=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.pickOffset=0,this.points=null,this.xCoords=null}function i(t,e){var r=t.gl,i=o(r),s=o(r),l=o(r),u=a(r,c.pointVertex,c.pointFragment),f=a(r,c.pickVertex,c.pickFragment),h=new n(t,i,s,l,u,f);return h.update(e),t.addObject(h),h}var a=t("gl-shader"),o=t("gl-buffer"),s=t("binary-search-bounds"),l=t("snap-points-2d"),u=t("typedarray-pool"),c=t("./lib/shader");e.exports=i;var f=n.prototype;f.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.xCoords&&u.free(this.xCoords),this.plot.removeObject(this)},f.update=function(t){function e(e,r){return e in t?t[e]:r}t=t||{},this.size=e("size",12),this.color=e("color",[1,0,0,1]).slice(),this.borderSize=e("borderSize",1),this.borderColor=e("borderColor",[0,0,0,1]).slice(),this.xCoords&&u.free(this.xCoords);var r=t.positions,n=u.mallocFloat32(r.length),i=u.mallocInt32(r.length>>>1);n.set(r);var a=u.mallocFloat32(r.length);this.points=r,this.scales=l(n,i,a,this.bounds),this.offsetBuffer.update(n),this.pickBuffer.update(i),this.weightBuffer.update(a);for(var o=u.mallocFloat32(r.length>>>1),s=0,c=0;s>>1,this.pickOffset=0},f.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.scales,o=this.offsetBuffer,l=this.pickBuffer,u=this.bounds,c=this.size,f=this.borderSize,h=n.gl,p=n.pickPixelRatio,d=n.viewBox,g=n.dataBox;if(0===this.pointCount)return r;var v=u[2]-u[0],m=u[3]-u[1],y=g[2]-g[0],b=g[3]-g[1],x=(d[2]-d[0])*p/n.pixelRatio,_=(d[3]-d[1])*p/n.pixelRatio,w=Math.min(y/x,b/_);t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(u[0]-g[0])/y-1,t[7]=2*(u[1]-g[1])/b-1,this.pickOffset=r,e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,i.bind(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointSize=p*(c+f),i.uniforms.pickOffset=e,0===this.borderSize?i.uniforms.centerFraction=2:i.uniforms.centerFraction=c/(c+f+1.25),o.bind(),i.attributes.position.pointer(),l.bind(),i.attributes.pickId.pointer(h.UNSIGNED_BYTE);for(var k=this.xCoords,A=(g[0]-u[0]-w*c*p)/v,M=(g[2]-u[0]+w*c*p)/v,T=a.length-1;T>=0;--T){var E=a[T];if(!(E.pixelSize1)){var L=E.offset,S=E.count+L,C=s.ge(k,A,L,S-1),z=s.lt(k,M,C,S-1)+1;z>C&&h.drawArrays(h.POINTS,C,z-C)}}return r+this.pointCount}}(),f.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.scales,i=this.offsetBuffer,a=this.bounds,o=this.size,l=this.borderSize,u=e.gl,c=e.pixelRatio,f=e.viewBox,h=e.dataBox;if(0!==this.pointCount){var p=a[2]-a[0],d=a[3]-a[1],g=h[2]-h[0],v=h[3]-h[1],m=f[2]-f[0],y=f[3]-f[1],b=Math.min(g/m,v/y);t[0]=2*p/g,t[4]=2*d/v,t[6]=2*(a[0]-h[0])/g-1,t[7]=2*(a[1]-h[1])/v-1,r.bind(),r.uniforms.matrix=t,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointSize=c*(o+l),r.uniforms.useWeight=1,0===this.borderSize?r.uniforms.centerFraction=2:r.uniforms.centerFraction=o/(o+l+1.25),i.bind(),r.attributes.position.pointer(),this.weightBuffer.bind(),r.attributes.weight.pointer();for(var x=this.xCoords,_=(h[0]-a[0]-b*o*c)/p,w=(h[2]-a[0]+b*o*c)/p,k=!0,A=n.length-1;A>=0;--A){var M=n[A];if(!(M.pixelSize1)){var T=M.offset,E=M.count+T,L=s.ge(x,_,T,E-1),S=s.lt(x,w,L,E-1)+1;S>L&&u.drawArrays(u.POINTS,L,S-L),k&&(k=!1,r.uniforms.useWeight=0)}}}}}(),f.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":747,"binary-search-bounds":748,"gl-buffer":749,"gl-shader":750,"snap-points-2d":777,"typedarray-pool":780}],782:[function(t,e,r){"use strict";function n(t,e){var r=a[e];if(r||(r=a[e]={}),t in r)return r[t];for(var n=i(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),o=i(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),s=[[1/0,1/0],[-(1/0),-(1/0)]],l=0;lc;++c)s[0][c]=Math.min(s[0][c],u[c]),s[1][c]=Math.max(s[1][c],u[c]);return r[t]=[o,n,s]}var i=t("vectorize-text");e.exports=n;var a={}},{"vectorize-text":818}],783:[function(t,e,r){function n(t,e){var r=i(t,e),n=r.attributes;return n.position.location=0,n.color.location=1,n.glyph.location=2,n.id.location=3,r}var i=t("gl-shader"),a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n \n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n \n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * view * model * vec4(position, 1);\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n",u="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}",c=[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"glyph",type:"vec2"},{name:"id",type:"vec4"}],f={vertex:a,fragment:l,attributes:c},h={vertex:o,fragment:l,attributes:c},p={vertex:s,fragment:l,attributes:c},d={vertex:a,fragment:u,attributes:c},g={vertex:o,fragment:u,attributes:c},v={vertex:s,fragment:u,attributes:c};r.createPerspective=function(t){return n(t,f)},r.createOrtho=function(t){return n(t,h)},r.createProject=function(t){return n(t,p)},r.createPickPerspective=function(t){return n(t,d)},r.createPickOrtho=function(t){return n(t,g)},r.createPickProject=function(t){return n(t,v)}},{"gl-shader":785}],784:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":817}],785:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":786,"./lib/create-attributes":787,"./lib/create-uniforms":788,"./lib/reflect":789,"./lib/runtime-reflect":790,"./lib/shader-cache":791,dup:94}],786:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],787:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":786,dup:96}],788:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":786,"./reflect":789,dup:97}],789:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],790:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],791:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":786,dup:100,"gl-format-compiler-error":792,"weakmap-shim":810}],792:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":793,dup:101,"gl-constants/lookup":797,"glsl-shader-name":798,"sprintf-js":807}],793:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":794}],794:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":795}],795:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],796:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],797:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":796,dup:106}],798:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":799,dup:107,"glsl-tokenizer":806}],799:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],800:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":802,"./lib/builtins-300es":801,"./lib/literals":804,"./lib/literals-300es":803,"./lib/operators":805,dup:109}],801:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":802,dup:110}],802:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],803:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":804,dup:112}],804:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],805:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],806:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":800,dup:115}],807:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],808:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":809,dup:117}],809:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],810:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":808,dup:119}],811:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],812:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":811,dup:155}],813:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":811,dup:156}],814:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":812,"./lib/vao-native.js":813,dup:157}],815:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],816:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],817:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":815,buffer:65,dup:122}],818:[function(t,e,r){arguments[4][354][0].apply(r,arguments)},{"./lib/vtext":819,dup:354}],819:[function(t,e,r){arguments[4][355][0].apply(r,arguments)},{cdt2d:820,"clean-pslg":832,dup:355,ndarray:1031,"planar-graph-to-polyline":887,"simplify-planar-graph":891,"surface-nets":904}],820:[function(t,e,r){arguments[4][356][0].apply(r,arguments)},{"./lib/delaunay":821,"./lib/filter":822,"./lib/monotone":823,"./lib/triangulation":824,dup:356}],821:[function(t,e,r){arguments[4][357][0].apply(r,arguments)},{"binary-search-bounds":825,dup:357,"robust-in-sphere":826}],822:[function(t,e,r){arguments[4][358][0].apply(r,arguments)},{"binary-search-bounds":825,dup:358}],823:[function(t,e,r){arguments[4][359][0].apply(r,arguments)},{"binary-search-bounds":825,dup:359,"robust-orientation":1040}],824:[function(t,e,r){arguments[4][360][0].apply(r,arguments)},{"binary-search-bounds":825,dup:360}],825:[function(t,e,r){arguments[4][312][0].apply(r,arguments)},{dup:312}],826:[function(t,e,r){arguments[4][361][0].apply(r,arguments)},{dup:361,"robust-scale":828,"robust-subtract":829,"robust-sum":830,"two-product":831}],827:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],828:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":831,"two-sum":827}],829:[function(t,e,r){arguments[4][364][0].apply(r,arguments)},{dup:364}],830:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],831:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],832:[function(t,e,r){arguments[4][367][0].apply(r,arguments)},{"./lib/rat-seg-intersect":833,"big-rat":837,"big-rat/cmp":835,"big-rat/to-float":852,"box-intersect":853,"compare-cell":861,dup:367,nextafter:862,"rat-vec":865,"robust-segment-intersect":868,"union-find":869}],833:[function(t,e,r){arguments[4][368][0].apply(r,arguments)},{"big-rat/div":836,"big-rat/mul":846,"big-rat/sign":850,"big-rat/sub":851,"big-rat/to-float":852,dup:368,"rat-vec/add":864,"rat-vec/muls":866,"rat-vec/sub":867}],834:[function(t,e,r){arguments[4][369][0].apply(r,arguments)},{"./lib/rationalize":844,dup:369}],835:[function(t,e,r){arguments[4][370][0].apply(r,arguments)},{dup:370}],836:[function(t,e,r){arguments[4][371][0].apply(r,arguments)},{"./lib/rationalize":844,dup:371}],837:[function(t,e,r){arguments[4][372][0].apply(r,arguments)},{"./div":836,"./is-rat":838,"./lib/is-bn":842,"./lib/num-to-bn":843,"./lib/rationalize":844,"./lib/str-to-bn":845,dup:372}],838:[function(t,e,r){arguments[4][373][0].apply(r,arguments)},{"./lib/is-bn":842,dup:373}],839:[function(t,e,r){arguments[4][374][0].apply(r,arguments)},{"bn.js":848,dup:374}],840:[function(t,e,r){arguments[4][375][0].apply(r,arguments)},{dup:375}],841:[function(t,e,r){arguments[4][376][0].apply(r,arguments)},{"bit-twiddle":847,"double-bits":849,dup:376}],842:[function(t,e,r){arguments[4][377][0].apply(r,arguments)},{"bn.js":848,dup:377}],843:[function(t,e,r){arguments[4][378][0].apply(r,arguments)},{"bn.js":848,"double-bits":849,dup:378}],844:[function(t,e,r){arguments[4][379][0].apply(r,arguments)},{"./bn-sign":839,"./num-to-bn":843,dup:379}],845:[function(t,e,r){arguments[4][380][0].apply(r,arguments)},{"bn.js":848,dup:380}],846:[function(t,e,r){arguments[4][381][0].apply(r,arguments)},{"./lib/rationalize":844,dup:381}],847:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],848:[function(t,e,r){arguments[4][383][0].apply(r,arguments)},{dup:383}],849:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],850:[function(t,e,r){arguments[4][385][0].apply(r,arguments)},{"./lib/bn-sign":839,dup:385}],851:[function(t,e,r){arguments[4][386][0].apply(r,arguments)},{"./lib/rationalize":844,dup:386}],852:[function(t,e,r){arguments[4][387][0].apply(r,arguments)},{"./lib/bn-to-num":840,"./lib/ctz":841,dup:387}],853:[function(t,e,r){arguments[4][388][0].apply(r,arguments)},{"./lib/intersect":855,"./lib/sweep":859,dup:388,"typedarray-pool":817}],854:[function(t,e,r){arguments[4][389][0].apply(r,arguments)},{dup:389}],855:[function(t,e,r){arguments[4][390][0].apply(r,arguments)},{"./brute":854,"./median":856,"./partition":857,"./sweep":859,"bit-twiddle":860,dup:390,"typedarray-pool":817}],856:[function(t,e,r){arguments[4][391][0].apply(r,arguments)},{"./partition":857,dup:391}],857:[function(t,e,r){arguments[4][392][0].apply(r,arguments)},{dup:392}],858:[function(t,e,r){arguments[4][393][0].apply(r,arguments)},{dup:393}],859:[function(t,e,r){arguments[4][394][0].apply(r,arguments)},{"./sort":858,"bit-twiddle":860,dup:394,"typedarray-pool":817}],860:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],861:[function(t,e,r){arguments[4][61][0].apply(r,arguments)},{dup:61}],862:[function(t,e,r){arguments[4][399][0].apply(r,arguments)},{"double-bits":863,dup:399}],863:[function(t,e,r){arguments[4][384][0].apply(r,arguments)},{buffer:65,dup:384}],864:[function(t,e,r){arguments[4][401][0].apply(r,arguments)},{"big-rat/add":834,dup:401}],865:[function(t,e,r){arguments[4][402][0].apply(r,arguments)},{"big-rat":837,dup:402}],866:[function(t,e,r){arguments[4][403][0].apply(r,arguments)},{"big-rat":837,"big-rat/mul":846,dup:403}],867:[function(t,e,r){arguments[4][404][0].apply(r,arguments)},{"big-rat/sub":851,dup:404}],868:[function(t,e,r){arguments[4][405][0].apply(r,arguments)},{dup:405,"robust-orientation":1040}],869:[function(t,e,r){arguments[4][78][0].apply(r,arguments)},{dup:78}],870:[function(t,e,r){arguments[4][407][0].apply(r,arguments)},{dup:407,"edges-to-adjacency-list":871}],871:[function(t,e,r){arguments[4][408][0].apply(r,arguments)},{dup:408,uniq:886}],872:[function(t,e,r){arguments[4][409][0].apply(r,arguments)},{"compare-angle":873,dup:409}],873:[function(t,e,r){arguments[4][410][0].apply(r,arguments)},{dup:410,"robust-orientation":1040,"robust-product":875,"robust-sum":884,signum:876,"two-sum":877}],874:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":885,"two-sum":877}],875:[function(t,e,r){arguments[4][412][0].apply(r,arguments)},{dup:412,"robust-scale":874,"robust-sum":884}],876:[function(t,e,r){arguments[4][413][0].apply(r,arguments)},{dup:413}],877:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],878:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],879:[function(t,e,r){arguments[4][416][0].apply(r,arguments)},{"binary-search-bounds":878,dup:416}],880:[function(t,e,r){arguments[4][417][0].apply(r,arguments)},{dup:417,"robust-orientation":1040}],881:[function(t,e,r){arguments[4][418][0].apply(r,arguments)},{dup:418}],882:[function(t,e,r){arguments[4][419][0].apply(r,arguments)},{"./lib/order-segments":880,"binary-search-bounds":878,dup:419,"functional-red-black-tree":881,"robust-orientation":1040}],883:[function(t,e,r){arguments[4][420][0].apply(r,arguments)},{"binary-search-bounds":878,dup:420,"interval-tree-1d":879,"robust-orientation":1040,"slab-decomposition":882}],884:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],885:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],886:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],887:[function(t,e,r){arguments[4][424][0].apply(r,arguments)},{"./lib/trim-leaves":870,dup:424,"edges-to-adjacency-list":871,"planar-dual":872,"point-in-big-polygon":883,"robust-sum":884,"two-product":885,uniq:886}],888:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],889:[function(t,e,r){arguments[4][426][0].apply(r,arguments)},{dup:426}],890:[function(t,e,r){arguments[4][79][0].apply(r,arguments)},{"bit-twiddle":888,dup:79,"union-find":889}],891:[function(t,e,r){arguments[4][428][0].apply(r,arguments)},{dup:428,"robust-orientation":1040,"simplicial-complex":890}],892:[function(t,e,r){arguments[4][429][0].apply(r,arguments)},{dup:429,"typedarray-pool":817}],893:[function(t,e,r){arguments[4][433][0].apply(r,arguments)},{dup:433}],894:[function(t,e,r){arguments[4][437][0].apply(r,arguments)},{dup:437,"typedarray-pool":817}],895:[function(t,e,r){arguments[4][438][0].apply(r,arguments)},{dup:438,"invert-permutation":896,"typedarray-pool":817}],896:[function(t,e,r){arguments[4][439][0].apply(r,arguments)},{dup:439}],897:[function(t,e,r){arguments[4][443][0].apply(r,arguments)},{dup:443,gamma:893,"permutation-parity":894,"permutation-rank":895}],898:[function(t,e,r){arguments[4][444][0].apply(r,arguments)},{"cwise-compiler":899,dup:444}],899:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":901,dup:319}],900:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:902}],901:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":900,dup:321}],902:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],903:[function(t,e,r){arguments[4][449][0].apply(r,arguments)},{"./lib/zc-core":898,dup:449}],904:[function(t,e,r){arguments[4][450][0].apply(r,arguments)},{dup:450,"ndarray-extract-contour":892,"triangulate-hypercube":897,"zero-crossings":903}],905:[function(t,e,r){"use strict";function n(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];return t[0]=e[0]*r+e[4]*n+e[8]*i+e[12]*a,t[1]=e[1]*r+e[5]*n+e[9]*i+e[13]*a,t[2]=e[2]*r+e[6]*n+e[10]*i+e[14]*a,t[3]=e[3]*r+e[7]*n+e[11]*i+e[15]*a,t}function i(t,e,r,i){return n(i,i,r),n(i,i,e),n(i,i,t)}function a(t,e){this.index=t,this.dataCoordinate=this.position=e}function o(t,e,r,n,i,o,s,l,u,c,f,h){this.gl=t,this.pixelRatio=1,this.shader=e,this.orthoShader=r,this.projectShader=n,this.pointBuffer=i,this.colorBuffer=o,this.glyphBuffer=s,this.idBuffer=l,this.vao=u,this.vertexCount=0,this.lineVertexCount=0,this.opacity=1,this.lineWidth=0,this.projectScale=[2/3,2/3,2/3],this.projectOpacity=[1,1,1],this.pickId=0,this.pickPerspectiveShader=c,this.pickOrthoShader=f,this.pickProjectShader=h,this.points=[],this._selectResult=new a(0,[0,0,0]),this.useOrtho=!0,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.axesProject=[!0,!0,!0],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.highlightId=[1,1,1,1],this.highlightScale=2,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.dirty=!0}function s(t){return t[0]=t[1]=t[2]=0,t}function l(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function u(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function c(t){for(var e=S,r=0;2>r;++r)for(var n=0;3>n;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}function f(t,e,r,n,a){var o,f=e.axesProject,h=e.gl,p=t.uniforms,d=r.model||x,g=r.view||x,v=r.projection||x,y=e.axesBounds,b=c(e.clipBounds);o=e.axes?e.axes.lastCubeProps.axis:[1,1,1],w[0]=2/h.drawingBufferWidth,w[1]=2/h.drawingBufferHeight,t.bind(),p.view=g,p.projection=v,p.screenSize=w,p.highlightId=e.highlightId,p.highlightScale=e.highlightScale,p.clipBounds=b,p.pickGroup=e.pickId/255,p.pixelRatio=e.pixelRatio;for(var _=0;3>_;++_)if(f[_]&&e.projectOpacity[_]<1===n){p.scale=e.projectScale[_],p.opacity=e.projectOpacity[_];for(var S=E,C=0;16>C;++C)S[C]=0;for(var C=0;4>C;++C)S[5*C]=1;S[5*_]=0,o[_]<0?S[12+_]=y[0][_]:S[12+_]=y[1][_],m(S,d,S),p.model=S;var z=(_+1)%3,P=(_+2)%3,R=s(k),j=s(A);R[z]=1,j[P]=1;var O=i(v,g,d,l(M,R)),I=i(v,g,d,l(T,j));if(Math.abs(O[1])>Math.abs(I[1])){var N=O;O=I,I=N,N=R,R=j,j=N;var F=z;z=P,P=F}O[0]<0&&(R[z]=-1),I[1]>0&&(j[P]=-1);for(var D=0,B=0,C=0;4>C;++C)D+=Math.pow(d[4*z+C],2),B+=Math.pow(d[4*P+C],2);R[z]/=Math.sqrt(D),j[P]/=Math.sqrt(B),p.axes[0]=R,p.axes[1]=j,p.fragClipBounds[0]=u(L,b[0],_,-1e8),p.fragClipBounds[1]=u(L,b[1],_,1e8),e.vao.draw(h.TRIANGLES,e.vertexCount),e.lineWidth>0&&(h.lineWidth(e.lineWidth),e.vao.draw(h.LINES,e.lineVertexCount,e.vertexCount))}}function h(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||x,s.view=n.view||x,s.projection=n.projection||x,w[0]=2/o.drawingBufferWidth,w[1]=2/o.drawingBufferHeight,s.screenSize=w,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=P,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}f(e,r,n,i,a),r.vao.unbind()}function p(t){var e=t.gl,r=y.createPerspective(e),n=y.createOrtho(e),i=y.createProject(e),a=y.createPickPerspective(e),s=y.createPickOrtho(e),l=y.createPickProject(e),u=d(e),c=d(e),f=d(e),h=d(e),p=g(e,[{buffer:u,size:3,type:e.FLOAT},{buffer:c,size:4,type:e.FLOAT},{buffer:f,size:2,type:e.FLOAT},{buffer:h,size:4,type:e.UNSIGNED_BYTE,normalized:!0}]),v=new o(e,r,n,i,u,c,f,h,p,a,s,l);return v.update(t),v}var d=t("gl-buffer"),g=t("gl-vao"),v=t("typedarray-pool"),m=t("gl-mat4/multiply"),y=t("./lib/shaders"),b=t("./lib/glyphs"),x=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];e.exports=p;var _=o.prototype;_.pickSlots=1,_.setPickBase=function(t){this.pickId=t},_.isTransparent=function(){if(this.opacity<1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]<1)return!0;return!1},_.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var w=[0,0],k=[0,0,0],A=[0,0,0],M=[0,0,0,1],T=[0,0,0,1],E=x.slice(),L=[0,0,0],S=[[0,0,0],[0,0,0]],C=[-1e8,-1e8,-1e8],z=[1e8,1e8,1e8],P=[C,z];_.draw=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!1,!1)},_.drawTransparent=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!0,!1)},_.drawPick=function(t){var e=this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader;h(e,this.pickProjectShader,this,t,!1,!0)},_.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||0>e)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;3>i;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},_.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},_.update=function(t){if(t=t||{},"perspective"in t&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{var r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-(1/0),-(1/0),-(1/0)],l=t.glyph,u=t.color,c=t.size,f=t.angle,h=t.lineColor,p=0,d=0,g=0,m=n.length;t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_)if(isNaN(x[_])||!isFinite(x[_]))continue t;var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];d+=3*k.cells.length,g+=2*A.edges.length}var T=d+g,E=v.mallocFloat(3*T),L=v.mallocFloat(4*T),S=v.mallocFloat(2*T),C=v.mallocUint32(T),z=[0,a[1]],P=0,R=d,j=[0,0,0,1],O=[0,0,0,1],I=Array.isArray(u)&&Array.isArray(u[0]),N=Array.isArray(h)&&Array.isArray(h[0]);t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_){if(isNaN(x[_])||!isFinite(x[_])){p+=1;continue t}s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_])}var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];if(Array.isArray(u)){var F;if(F=I?u[y]:u,3===F.length){for(var _=0;3>_;++_)j[_]=F[_];j[3]=1}else if(4===F.length)for(var _=0;4>_;++_)j[_]=F[_]}else j[0]=j[1]=j[2]=0,j[3]=1;if(Array.isArray(h)){var F;if(F=N?h[y]:h,3===F.length){for(var _=0;3>_;++_)O[_]=F[_];O[_]=1}else if(4===F.length)for(var _=0;4>_;++_)O[_]=F[_]}else O[0]=O[1]=O[2]=0,O[3]=1;var D=.5;Array.isArray(c)?D=+c[y]:c?D=+c:this.useOrtho&&(D=12);var B=0;Array.isArray(f)?B=+f[y]:f&&(B=+f);for(var U=Math.cos(B),V=Math.sin(B),x=n[y],_=0;3>_;++_)s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_]);a[0]<0?z[0]=a[0]*(1+M[1][0]):a[0]>0&&(z[0]=-a[0]*(1+M[0][0]));for(var q=k.cells,G=k.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*P+X]=x[X];for(var X=0;4>X;++X)L[4*P+X]=j[X];C[P]=p;var W=G[H[Y]];S[2*P]=D*(U*W[0]-V*W[1]+z[0]),S[2*P+1]=D*(V*W[0]+U*W[1]+z[1]),P+=1}for(var q=A.edges,G=A.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*R+X]=x[X];for(var X=0;4>X;++X)L[4*R+X]=O[X];C[R]=p;var W=G[H[Y]];S[2*R]=D*(U*W[0]-V*W[1]+z[0]),S[2*R+1]=D*(V*W[0]+U*W[1]+z[1]),R+=1}p+=1}this.vertexCount=d,this.lineVertexCount=g,this.pointBuffer.update(E),this.colorBuffer.update(L),this.glyphBuffer.update(S),this.idBuffer.update(new Uint32Array(C)),v.free(E),v.free(L),v.free(S),v.free(C),this.bounds=[o,s],this.points=n,this.pointCount=n.length}},_.dispose=function(){this.shader.dispose(),this.orthoShader.dispose(),this.pickPerspectiveShader.dispose(),this.pickOrthoShader.dispose(),this.vao.dispose(),this.pointBuffer.dispose(),this.colorBuffer.dispose(),this.glyphBuffer.dispose(),this.idBuffer.dispose()}},{"./lib/glyphs":782,"./lib/shaders":783,"gl-buffer":784,"gl-mat4/multiply":242,"gl-vao":814,"typedarray-pool":817}],906:[function(t,e,r){"use strict";r.boxVertex="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n",r.boxFragment="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n"},{}],907:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":910}],908:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],909:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],910:[function(t,e,r){arguments[4][122][0].apply(r,arguments)},{"bit-twiddle":908,buffer:65,dup:122}],911:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":912,"./lib/create-attributes":913,"./lib/create-uniforms":914,"./lib/reflect":915,"./lib/runtime-reflect":916,"./lib/shader-cache":917,dup:94}],912:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],913:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":912,dup:96}],914:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":912,"./reflect":915,dup:97}],915:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],916:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],917:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":912,dup:100,"gl-format-compiler-error":918,"weakmap-shim":936}],918:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":919,dup:101,"gl-constants/lookup":923,"glsl-shader-name":924,"sprintf-js":933}],919:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":920}],920:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":921}],921:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],922:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],923:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":922,dup:106}],924:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":925,dup:107,"glsl-tokenizer":932}],925:[function(t,e,r){arguments[4][108][0].apply(r,arguments); -},{dup:108}],926:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":928,"./lib/builtins-300es":927,"./lib/literals":930,"./lib/literals-300es":929,"./lib/operators":931,dup:109}],927:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":928,dup:110}],928:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],929:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":930,dup:112}],930:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],931:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],932:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":926,dup:115}],933:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],934:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":935,dup:117}],935:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],936:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":934,dup:119}],937:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.boxBuffer=e,this.boxShader=r,this.enabled=!0,this.selectBox=[1/0,1/0,-(1/0),-(1/0)],this.borderColor=[0,0,0,1],this.innerFill=!1,this.innerColor=[0,0,0,.25],this.outerFill=!0,this.outerColor=[0,0,0,.5],this.borderWidth=10}function i(t,e){var r=t.gl,i=o(r,[0,0,0,1,1,0,1,1]),l=a(r,s.boxVertex,s.boxFragment),u=new n(t,i,l);return u.update(e),t.addOverlay(u),u}var a=t("gl-shader"),o=t("gl-buffer"),s=t("./lib/shaders");e.exports=i;var l=n.prototype;l.draw=function(){if(this.enabled){var t=this.plot,e=this.selectBox,r=this.borderWidth,n=(this.innerFill,this.innerColor),i=(this.outerFill,this.outerColor),a=this.borderColor,o=t.box,s=t.screenBox,l=t.dataBox,u=t.viewBox,c=t.pixelRatio,f=(e[0]-l[0])*(u[2]-u[0])/(l[2]-l[0])+u[0],h=(e[1]-l[1])*(u[3]-u[1])/(l[3]-l[1])+u[1],p=(e[2]-l[0])*(u[2]-u[0])/(l[2]-l[0])+u[0],d=(e[3]-l[1])*(u[3]-u[1])/(l[3]-l[1])+u[1];if(f=Math.max(f,u[0]),h=Math.max(h,u[1]),p=Math.min(p,u[2]),d=Math.min(d,u[3]),!(f>p||h>d)){o.bind();var g=s[2]-s[0],v=s[3]-s[1];if(this.outerFill&&(o.drawBox(0,0,g,h,i),o.drawBox(0,h,f,d,i),o.drawBox(0,d,g,v,i),o.drawBox(p,h,g,d,i)),this.innerFill&&o.drawBox(f,h,p,d,n),r>0){var m=r*c;o.drawBox(f-m,h-m,p+m,h+m,a),o.drawBox(f-m,d-m,p+m,d+m,a),o.drawBox(f-m,h-m,f+m,d+m,a),o.drawBox(p-m,h-m,p+m,d+m,a)}}}},l.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},l.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":906,"gl-buffer":907,"gl-shader":911}],938:[function(t,e,r){"use strict";function n(t){this.plot=t,this.enable=[!0,!0,!1,!1],this.width=[1,1,1,1],this.color=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.center=[1/0,1/0]}function i(t,e){var r=new n(t);return r.update(e),t.addOverlay(r),r}e.exports=i;var a=n.prototype;a.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},a.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),u=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,u,s[0],u,e[0],r[0]),t[1]&&a.drawLine(l,u,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,u,s[2],u,e[2],r[2]),t[3]&&a.drawLine(l,u,l,s[3],e[3],r[3])}},a.dispose=function(){this.plot.removeOverlay(this)}},{}],939:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n",s="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n";r.createShader=function(t){var e=n(t,i,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,i,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,o,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},r.createPickContourShader=function(t){var e=n(t,o,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e}},{"gl-shader":947}],940:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],941:[function(t,e,r){arguments[4][77][0].apply(r,arguments)},{dup:77}],942:[function(t,e,r){arguments[4][262][0].apply(r,arguments)},{dup:262}],943:[function(t,e,r){arguments[4][263][0].apply(r,arguments)},{"./colorScales":942,arraytools:64,clone:944,dup:263}],944:[function(t,e,r){arguments[4][264][0].apply(r,arguments)},{buffer:65,dup:264}],945:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],946:[function(t,e,r){arguments[4][93][0].apply(r,arguments)},{dup:93,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":1002}],947:[function(t,e,r){arguments[4][94][0].apply(r,arguments)},{"./lib/GLError":948,"./lib/create-attributes":949,"./lib/create-uniforms":950,"./lib/reflect":951,"./lib/runtime-reflect":952,"./lib/shader-cache":953,dup:94}],948:[function(t,e,r){arguments[4][95][0].apply(r,arguments)},{dup:95}],949:[function(t,e,r){arguments[4][96][0].apply(r,arguments)},{"./GLError":948,dup:96}],950:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{"./GLError":948,"./reflect":951,dup:97}],951:[function(t,e,r){arguments[4][98][0].apply(r,arguments)},{dup:98}],952:[function(t,e,r){arguments[4][99][0].apply(r,arguments)},{dup:99}],953:[function(t,e,r){arguments[4][100][0].apply(r,arguments)},{"./GLError":948,dup:100,"gl-format-compiler-error":954,"weakmap-shim":972}],954:[function(t,e,r){arguments[4][101][0].apply(r,arguments)},{"add-line-numbers":955,dup:101,"gl-constants/lookup":959,"glsl-shader-name":960,"sprintf-js":969}],955:[function(t,e,r){arguments[4][102][0].apply(r,arguments)},{dup:102,"pad-left":956}],956:[function(t,e,r){arguments[4][103][0].apply(r,arguments)},{dup:103,"repeat-string":957}],957:[function(t,e,r){arguments[4][104][0].apply(r,arguments)},{dup:104}],958:[function(t,e,r){arguments[4][105][0].apply(r,arguments)},{dup:105}],959:[function(t,e,r){arguments[4][106][0].apply(r,arguments)},{"./1.0/numbers":958,dup:106}],960:[function(t,e,r){arguments[4][107][0].apply(r,arguments)},{"atob-lite":961,dup:107,"glsl-tokenizer":968}],961:[function(t,e,r){arguments[4][108][0].apply(r,arguments)},{dup:108}],962:[function(t,e,r){arguments[4][109][0].apply(r,arguments)},{"./lib/builtins":964,"./lib/builtins-300es":963,"./lib/literals":966,"./lib/literals-300es":965,"./lib/operators":967,dup:109}],963:[function(t,e,r){arguments[4][110][0].apply(r,arguments)},{"./builtins":964,dup:110}],964:[function(t,e,r){arguments[4][111][0].apply(r,arguments)},{dup:111}],965:[function(t,e,r){arguments[4][112][0].apply(r,arguments)},{"./literals":966,dup:112}],966:[function(t,e,r){arguments[4][113][0].apply(r,arguments)},{dup:113}],967:[function(t,e,r){arguments[4][114][0].apply(r,arguments)},{dup:114}],968:[function(t,e,r){arguments[4][115][0].apply(r,arguments)},{"./index":962,dup:115}],969:[function(t,e,r){arguments[4][116][0].apply(r,arguments)},{dup:116}],970:[function(t,e,r){arguments[4][117][0].apply(r,arguments)},{"./hidden-store.js":971,dup:117}],971:[function(t,e,r){arguments[4][118][0].apply(r,arguments)},{dup:118}],972:[function(t,e,r){arguments[4][119][0].apply(r,arguments)},{"./create-store.js":970,dup:119}],973:[function(t,e,r){arguments[4][188][0].apply(r,arguments)},{dup:188,ndarray:1031,"ndarray-ops":1026,"typedarray-pool":1002}],974:[function(t,e,r){arguments[4][154][0].apply(r,arguments)},{dup:154}],975:[function(t,e,r){arguments[4][155][0].apply(r,arguments)},{"./do-bind.js":974,dup:155}],976:[function(t,e,r){arguments[4][156][0].apply(r,arguments)},{"./do-bind.js":974,dup:156}],977:[function(t,e,r){arguments[4][157][0].apply(r,arguments)},{"./lib/vao-emulated.js":975,"./lib/vao-native.js":976,dup:157}],978:[function(t,e,r){"use strict";function n(t){if(t in l)return l[t];for(var e=[],r=0;t>r;++r)e.push("out",r,"s=0.5*(inp",r,"l-inp",r,"r);");for(var n=["array"],i=["junk"],r=0;t>r;++r){n.push("array"),i.push("out"+r+"s");var a=o(t);a[r]=-1,n.push({array:0,offset:a.slice()}),a[r]=1,n.push({array:0,offset:a.slice()}),i.push("inp"+r+"l","inp"+r+"r")}return l[t]=s({args:n,pre:c,post:c,body:{body:e.join(""),args:i.map(function(t){return{name:t,lvalue:0===t.indexOf("out"),rvalue:0===t.indexOf("inp"),count:"junk"!==t|0}}),thisVars:[],localVars:[]},funcName:"fdTemplate"+t})}function i(t){function e(e){for(var r=a-e.length,n=[],i=[],s=[],l=0;a>l;++l)e.indexOf(l+1)>=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),n.push("1"),i.push("s["+l+"]-2"));var u=".lo("+n.join()+").hi("+i.join()+")";if(0===n.length&&(u=""),r>0){o.push("if(1");for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push("&&s[",l,"]>2");o.push("){grad",r,"(src.pick(",s.join(),")",u);for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push(",dst.pick(",s.join(),",",l,")",u);o.push(");")}for(var l=0;l1){dst.set(",s.join(),",",c,",0.5*(src.get(",h.join(),")-src.get(",p.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):o.push("if(s[",c,"]>1){diff(",f,",src.pick(",h.join(),")",u,",src.pick(",p.join(),")",u,");}else{zero(",f,");};");break;case"mirror":0===r?o.push("dst.set(",s.join(),",",c,",0);"):o.push("zero(",f,");");break;case"wrap":var d=s.slice(),g=s.slice();e[l]<0?(d[c]="s["+c+"]-2",g[c]="0"):(d[c]="s["+c+"]-1",g[c]="1"),0===r?o.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",d.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):o.push("if(s[",c,"]>2){diff(",f,",src.pick(",d.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",f,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}r>0&&o.push("};")}var r=t.join(),i=u[r];if(i)return i;for(var a=t.length,o=["function gradient(dst,src){var s=src.shape.slice();"],s=0;1<s;++s){for(var c=[],p=0;a>p;++p)s&1<=s;++s)v.push("grad"+s),m.push(n(s));v.push(o.join(""));var y=Function.apply(void 0,v),i=y.apply(void 0,m);return l[r]=i,i}function a(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r="string"==typeof r?o(e.dimension,r):o(e.dimension,"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;nr;++r)for(o=o||e.surfaceProject[r],n=0;3>n;++n)s=s||e.contourProject[r][n];for(r=0;3>r;++r){var l=D.projections[r];for(n=0;16>n;++n)l[n]=0;for(n=0;4>n;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],k(l,t.model,l);var u=D.clipBounds[r];for(i=0;2>i;++i)for(n=0;3>n;++n)u[i][n]=t.clipBounds[i][n];u[0][r]=-1e8,u[1][r]=1e8}return D.showSurface=o,D.showContour=s,D}function s(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=B;n.model=t.model||R,n.view=t.view||R,n.projection=t.projection||R,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=A(n.inverseModel,n.model);for(var i=0;2>i;++i)for(var a=n.clipBounds[i],s=0;3>s;++s)a[s]=Math.min(Math.max(this.clipBounds[i][s],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=V;var l=U;for(k(l,n.view,n.model),k(l,n.projection,l),A(l,l),i=0;3>i;++i)n.eyePosition[i]=l[12+i]/l[15];var u=l[15];for(i=0;3>i;++i)u+=this.lightPosition[i]*l[4*i+3];for(i=0;3>i;++i){var c=l[12+i];for(s=0;3>s;++s)c+=l[4*s+i]*this.lightPosition[s];n.lightPosition[i]=c/u}var f=o(n,this);if(f.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;3>i;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=f.projections[i],this._shader.uniforms.clipBounds=f.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(f.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var p=this._contourVAO;for(p.bind(),i=0;3>i;++i)for(h.uniforms.permutation=O[i],r.lineWidth(this.contourWidth[i]),s=0;si;++i)for(h.uniforms.model=f.projections[i],h.uniforms.clipBounds=f.clipBounds[i],s=0;3>s;++s)if(this.contourProject[i][s]){h.uniforms.permutation=O[s],r.lineWidth(this.contourWidth[s]);for(var d=0;di;++i)if(0!==this._dynamicCounts[i])for(h.uniforms.model=n.model,h.uniforms.clipBounds=n.clipBounds,h.uniforms.permutation=O[i],r.lineWidth(this.dynamicWidth[i]),h.uniforms.contourColor=this.dynamicColor[i],h.uniforms.contourTint=this.dynamicTint[i],h.uniforms.height=this.dynamicLevel[i],p.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]),s=0;3>s;++s)this.contourProject[s][i]&&(h.uniforms.model=f.projections[s],h.uniforms.clipBounds=f.clipBounds[s],p.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]));p.unbind()}}function l(t,e){var r=e.shape.slice(),n=t.shape.slice();b.assign(t.lo(1,1).hi(r[0],r[1]),e),b.assign(t.lo(1).hi(r[0],1),e.hi(r[0],1)),b.assign(t.lo(1,n[1]-1).hi(r[0],1),e.lo(0,r[1]-1).hi(r[0],1)),b.assign(t.lo(0,1).hi(1,r[1]),e.hi(1)),b.assign(t.lo(n[0]-1,1).hi(1,r[1]),e.lo(r[0]-1)),t.set(0,0,e.get(0,0)),t.set(0,n[1]-1,e.get(0,r[1]-1)),t.set(n[0]-1,0,e.get(r[0]-1,0)),t.set(n[0]-1,n[1]-1,e.get(r[0]-1,r[1]-1))}function u(t,e){return Array.isArray(t)?[e(t[0]),e(t[1]),e(t[2])]:[e(t),e(t),e(t)]}function c(t){return Array.isArray(t)?3===t.length?[t[0],t[1],t[2],1]:[t[0],t[1],t[2],t[3]]:[0,0,0,1]}function f(t){if(Array.isArray(t)){if(Array.isArray(t))return[c(t[0]),c(t[1]),c(t[2])];var e=c(t);return[e.slice(),e.slice(),e.slice()]}}function h(t){var e=t.gl,r=L(e),n=C(e),i=S(e),o=z(e),s=d(e),l=g(e,[{buffer:s,size:4,stride:P,offset:0},{buffer:s,size:3,stride:P,offset:16},{buffer:s,size:3,stride:P,offset:28}]),u=d(e),c=g(e,[{buffer:u,size:4,stride:20,offset:0},{buffer:u,size:1,stride:20,offset:16}]),f=d(e),h=g(e,[{buffer:f,size:2,type:e.FLOAT}]),p=v(e,1,I,e.RGBA,e.UNSIGNED_BYTE);p.minFilter=e.LINEAR,p.magFilter=e.LINEAR;var m=new a(e,[0,0],[[0,0,0],[0,0,0]],r,n,s,l,p,i,o,u,c,f,h),y={levels:[[],[],[]]};for(var b in t)y[b]=t[b];return y.colormap=y.colormap||"jet",m.update(y),m}e.exports=h;var p=t("bit-twiddle"),d=t("gl-buffer"),g=t("gl-vao"),v=t("gl-texture2d"),m=t("typedarray-pool"),y=t("colormap"),b=t("ndarray-ops"),x=t("ndarray-pack"),_=t("ndarray"),w=t("surface-nets"),k=t("gl-mat4/multiply"),A=t("gl-mat4/invert"),M=t("binary-search-bounds"),T=t("ndarray-gradient"),E=t("./lib/shaders"),L=E.createShader,S=E.createContourShader,C=E.createPickShader,z=E.createPickContourShader,P=40,R=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],j=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],O=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];!function(){for(var t=0;3>t;++t){var e=O[t],r=(t+1)%3,n=(t+2)%3;e[r+0]=1,e[n+3]=1,e[t+6]=1}}();var I=265,N=a.prototype;N.isTransparent=function(){return this.opacity<1},N.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},N.pickSlots=1,N.setPickBase=function(t){this.pickId=t};var F=[0,0,0],D={showSurface:!1,showContour:!1,projections:[R.slice(),R.slice(),R.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]},B={model:R,view:R,projection:R,inverseModel:R.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1},U=R.slice(),V=[1,0,0,0,1,0,0,0,1];N.draw=function(t){return s.call(this,t,!1)},N.drawTransparent=function(t){return s.call(this,t,!0)};var q={model:R,view:R,projection:R,inverseModel:R,clipBounds:[[0,0,0],[0,0,0]],height:0,shape:[0,0],pickId:0,lowerBound:[0,0,0],upperBound:[0,0,0],zOffset:0,permutation:[1,0,0,0,1,0,0,0,1],lightPosition:[0,0,0],eyePosition:[0,0,0]};N.drawPick=function(t){t=t||{};var e=this.gl;e.disable(e.CULL_FACE);var r=q;r.model=t.model||R,r.view=t.view||R,r.projection=t.projection||R,r.shape=this._field[2].shape,r.pickId=this.pickId/255,r.lowerBound=this.bounds[0],r.upperBound=this.bounds[1],r.permutation=V;for(var n=0;2>n;++n)for(var i=r.clipBounds[n],a=0;3>a;++a)i[a]=Math.min(Math.max(this.clipBounds[n][a],-1e8),1e8);var s=o(r,this);if(s.showSurface){for(this._pickShader.bind(),this._pickShader.uniforms=r,this._vao.bind(),this._vao.draw(e.TRIANGLES,this._vertexCount),n=0;3>n;++n)this.surfaceProject[n]&&(this._pickShader.uniforms.model=s.projections[n],this._pickShader.uniforms.clipBounds=s.clipBounds[n],this._vao.draw(e.TRIANGLES,this._vertexCount));this._vao.unbind()}if(s.showContour){var l=this._contourPickShader;l.bind(),l.uniforms=r;var u=this._contourVAO;for(u.bind(),a=0;3>a;++a)for(e.lineWidth(this.contourWidth[a]),l.uniforms.permutation=O[a],n=0;nn;++n)for(l.uniforms.model=s.projections[n],l.uniforms.clipBounds=s.clipBounds[n],a=0;3>a;++a)if(this.contourProject[n][a]){l.uniforms.permutation=O[a],e.lineWidth(this.contourWidth[a]);for(var c=0;c>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;2>c;++c)for(var f=c?a:1-a,h=0;2>h;++h)for(var p=h?l:1-l,d=i+c,g=s+h,v=f*p,m=0;3>m;++m)u[m]+=this._field[m].get(d,g)*v;for(var y=this._pickResult.level,b=0;3>b;++b)if(y[b]=M.le(this.contourLevels[b],u[b]),y[b]<0)this.contourLevels[b].length>0&&(y[b]=0);else if(y[b]Math.abs(_-u[b])&&(y[b]+=1)}for(r.index[0]=.5>a?i:i+1,r.index[1]=.5>l?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],m=0;3>m;++m)r.dataCoordinate[m]=this._field[m].get(r.index[0],r.index[1]);return r},N.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=u(t.contourWidth,Number)),"showContour"in t&&(this.showContour=u(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=u(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=f(t.contourColor)),"contourProject"in t&&(this.contourProject=u(t.contourProject,function(t){return u(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=f(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=u(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=u(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(m.freeFloat(this._field[2].data),this._field[2].data=m.mallocFloat(p.nextPow2(n))),this._field[2]=_(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),l(this._field[2],e),this.shape=e.shape.slice();for(var a=this.shape,o=0;2>o;++o)this._field[2].size>this._field[o].data.length&&(m.freeFloat(this._field[o].data),this._field[o].data=m.mallocFloat(this._field[2].size)),this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2]);if(t.coords){var s=t.coords;if(!Array.isArray(s)||3!==s.length)throw new Error("gl-surface: invalid coordinates for x/y"); -for(o=0;2>o;++o){var c=s[o];for(y=0;2>y;++y)if(c.shape[y]!==a[y])throw new Error("gl-surface: coords have incorrect shape");l(this._field[o],c)}}else if(t.ticks){var h=t.ticks;if(!Array.isArray(h)||2!==h.length)throw new Error("gl-surface: invalid ticks");for(o=0;2>o;++o){var d=h[o];if((Array.isArray(d)||d.length)&&(d=_(d)),d.shape[0]!==a[o])throw new Error("gl-surface: invalid tick length");var g=_(d.data,a);g.stride[o]=d.stride[0],g.stride[1^o]=0,l(this._field[o],g)}}else{for(o=0;2>o;++o){var v=[0,0];v[o]=1,this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2],v,0)}this._field[0].set(0,0,0);for(var y=0;yo;++o)T(x.pick(o),b[o],"mirror");var k=_(m.mallocFloat(3*b[2].size),[a[0]+2,a[1]+2,3]);for(o=0;oO?(O=Math.max(Math.abs(z),Math.abs(P),Math.abs(R)),1e-8>O?(R=1,P=z=0,O=1):O=1/O):O=1/Math.sqrt(O),k.set(o,y,0,z*O),k.set(o,y,1,P*O),k.set(o,y,2,R*O)}m.free(x.data);var I=[1/0,1/0,1/0],N=[-(1/0),-(1/0),-(1/0)],F=1/0,D=-(1/0),B=(a[0]-1)*(a[1]-1)*6,U=m.mallocFloat(p.nextPow2(10*B)),V=0,q=0;for(o=0;oG;++G)for(var H=0;2>H;++H)for(var Y=0;3>Y;++Y){var X=this._field[Y].get(1+o+G,1+y+H);if(isNaN(X)||!isFinite(X))continue t}for(Y=0;6>Y;++Y){var W=o+j[Y][0],Z=y+j[Y][1],K=this._field[0].get(W+1,Z+1),$=this._field[1].get(W+1,Z+1);X=this._field[2].get(W+1,Z+1);var Q=X;z=k.get(W+1,Z+1,0),P=k.get(W+1,Z+1,1),R=k.get(W+1,Z+1,2),t.intensity&&(Q=t.intensity.get(W,Z)),U[V++]=W,U[V++]=Z,U[V++]=K,U[V++]=$,U[V++]=X,U[V++]=0,U[V++]=Q,U[V++]=z,U[V++]=P,U[V++]=R,I[0]=Math.min(I[0],K),I[1]=Math.min(I[1],$),I[2]=Math.min(I[2],X),F=Math.min(F,Q),N[0]=Math.max(N[0],K),N[1]=Math.max(N[1],$),N[2]=Math.max(N[2],X),D=Math.max(D,Q),q+=1}}for(t.intensityBounds&&(F=+t.intensityBounds[0],D=+t.intensityBounds[1]),o=6;V>o;o+=10)U[o]=(U[o]-F)/(D-F);this._vertexCount=q,this._coordinateBuffer.update(U.subarray(0,V)),m.freeFloat(U),m.free(k.data),this.bounds=[I,N],this.intensity=t.intensity||this._field[2],this.intensityBounds[0]===F&&this.intensityBounds[1]===D||(r=!0),this.intensityBounds=[F,D]}if("levels"in t){var J=t.levels;for(J=Array.isArray(J[0])?J.slice():[[],[],J],o=0;3>o;++o)J[o]=J[o].slice(),J.sort(function(t,e){return t-e});t:for(o=0;3>o;++o){if(J[o].length!==this.contourLevels[o].length){r=!0;break}for(y=0;yet;++et){J=this.contourLevels[et];var rt=[],nt=[],it=[0,0,0];for(o=0;oY;++Y){var st=at.positions[ot[Y]],lt=st[0],ut=0|Math.floor(lt),ct=lt-ut,ft=st[1],ht=0|Math.floor(ft),pt=ft-ht,dt=!1;e:for(var gt=0;3>gt;++gt){it[gt]=0;var vt=(et+gt+1)%3;for(G=0;2>G;++G){var mt=G?ct:1-ct;for(W=0|Math.min(Math.max(ut+G,0),a[0]),H=0;2>H;++H){var yt=H?pt:1-pt;if(Z=0|Math.min(Math.max(ht+H,0),a[1]),X=2>gt?this._field[vt].get(W,Z):(this.intensity.get(W,Z)-this.intensityBounds[0])/(this.intensityBounds[1]-this.intensityBounds[0]),!isFinite(X)||isNaN(X)){dt=!0;break e}var bt=mt*yt;it[gt]+=bt*X}}}if(dt){if(Y>0){for(var xt=0;5>xt;++xt)tt.pop();q-=1}continue t}tt.push(it[0],it[1],st[0],st[1],it[2]),q+=1}}nt.push(q)}this._contourOffsets[et]=rt,this._contourCounts[et]=nt}var _t=m.mallocFloat(tt.length);for(o=0;ot;++t)m.freeFloat(this._field[t].data)},N.highlight=function(t){if(!t)return this._dynamicCounts=[0,0,0],this.dyanamicLevel=[NaN,NaN,NaN],void(this.highlightLevel=[-1,-1,-1]);for(var e=0;3>e;++e)this.enableHighlight[e]?this.highlightLevel[e]=t.level[e]:this.highlightLevel[e]=-1;var r;if(r=this.snapToData?t.dataCoordinate:t.position,this.enableDynamic[0]&&r[0]!==this.dynamicLevel[0]||this.enableDynamic[1]&&r[1]!==this.dynamicLevel[1]||this.enableDynamic[2]&&r[2]!==this.dynamicLevel[2]){for(var n=0,i=this.shape,a=m.mallocFloat(12*i[0]*i[1]),o=0;3>o;++o)if(this.enableDynamic[o]){this.dynamicLevel[o]=r[o];var s=(o+1)%3,l=(o+2)%3,u=this._field[o],c=this._field[s],f=this._field[l],h=(this.intensity,w(u,r[o])),p=h.cells,d=h.positions;for(this._dynamicOffsets[o]=n,e=0;ev;++v){var y=d[g[v]],b=+y[0],x=0|b,_=0|Math.min(x+1,i[0]),k=b-x,A=1-k,M=+y[1],T=0|M,E=0|Math.min(T+1,i[1]),L=M-T,S=1-L,C=A*S,z=A*L,P=k*S,R=k*L,j=C*c.get(x,T)+z*c.get(x,E)+P*c.get(_,T)+R*c.get(_,E),O=C*f.get(x,T)+z*f.get(x,E)+P*f.get(_,T)+R*f.get(_,E);if(isNaN(j)||isNaN(O)){v&&(n-=1);break}a[2*n+0]=j,a[2*n+1]=O,n+=1}this._dynamicCounts[o]=n-this._dynamicOffsets[o]}else this.dynamicLevel[o]=NaN,this._dynamicCounts[o]=0;this._dynamicBuffer.update(a.subarray(0,2*n)),m.freeFloat(a)}}},{"./lib/shaders":939,"binary-search-bounds":940,"bit-twiddle":941,colormap:943,"gl-buffer":946,"gl-mat4/invert":240,"gl-mat4/multiply":242,"gl-texture2d":973,"gl-vao":977,ndarray:1031,"ndarray-gradient":978,"ndarray-ops":1026,"ndarray-pack":983,"surface-nets":1001,"typedarray-pool":1002}],1004:[function(t,e,r){"use strict";function n(t,e){function r(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==g.alt,g.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==g.shift,g.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==g.control,g.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==g.meta,g.meta=!!t.metaKey),e}function n(t,n){var a=i.x(n),o=i.y(n);"buttons"in n&&(t=0|n.buttons),(t!==h||a!==p||o!==d||r(n))&&(h=0|t,p=a||0,d=o||0,e&&e(h,p,d,g))}function a(t){n(0,t)}function o(){(h||p||d||g.shift||g.alt||g.meta||g.control)&&(p=d=0,h=0,g.shift=g.alt=g.control=g.meta=!1,e&&e(0,0,0,g))}function s(t){r(t)&&e&&e(h,p,d,g)}function l(t){0===i.buttons(t)?n(0,t):n(h,t)}function u(t){n(h|i.buttons(t),t)}function c(t){n(h&~i.buttons(t),t)}function f(){v||(v=!0,t.addEventListener("mousemove",l),t.addEventListener("mousedown",u),t.addEventListener("mouseup",c),t.addEventListener("mouseleave",a),t.addEventListener("mouseenter",a),t.addEventListener("mouseout",a),t.addEventListener("mouseover",a),t.addEventListener("blur",o),t.addEventListener("keyup",s),t.addEventListener("keydown",s),t.addEventListener("keypress",s),t!==window&&(window.addEventListener("blur",o),window.addEventListener("keyup",s),window.addEventListener("keydown",s),window.addEventListener("keypress",s)))}e||(e=t,t=window);var h=0,p=0,d=0,g={shift:!1,alt:!1,control:!1,meta:!1},v=!1;f();var m={element:t};return Object.defineProperties(m,{enabled:{get:function(){return v},set:function(t){t&&f()},enumerable:!0},buttons:{get:function(){return h},enumerable:!0},x:{get:function(){return p},enumerable:!0},y:{get:function(){return d},enumerable:!0},mods:{get:function(){return g},enumerable:!0}}),m}e.exports=n;var i=t("mouse-event")},{"mouse-event":1005}],1005:[function(t,e,r){"use strict";function n(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){var e=t.which;if(2===e)return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1<=0&&r=0&&r+1=0&&n=0&&n+1=0&&s=0&&s+1=0&&i=0&&i+1=0&&l=0&&l+1=0&&h=0&&h+1e;++e)r=+arguments[e+1],i[e]=Math.floor(r),a[e]=r-i[e],o[e]=0<=i[e]&&i[e]e;++e){for(u=1,c=t.offset,l=0;n>l;++l)if(e&1<r;++r){t[r]=o[(n+1)*n+r];for(var i=0;n>i;++i)t[r]+=o[(n+1)*i+r]*e[i]}for(var a=o[(n+1)*(n+1)-1],i=0;n>i;++i)a+=o[(n+1)*i+n]*e[i];for(var s=1/a,r=0;n>r;++r)t[r]*=s;return t}),t}var i=t("ndarray-warp"),a=t("gl-matrix-invert");e.exports=n},{"gl-matrix-invert":1015,"ndarray-warp":1024}],1026:[function(t,e,r){"use strict";function n(t){if(!t)return s;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in l){var e=l[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var u={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in u){var e=u[t];r[t]=a({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=a({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in c){var e=c[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var f=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=o({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=o({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=a({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=a({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=a({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=o({args:["array","array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":1027}],1027:[function(t,e,r){arguments[4][319][0].apply(r,arguments)},{"./lib/thunk.js":1029,dup:319}],1028:[function(t,e,r){arguments[4][320][0].apply(r,arguments)},{dup:320,uniq:1030}],1029:[function(t,e,r){arguments[4][321][0].apply(r,arguments)},{"./compile.js":1028,dup:321}],1030:[function(t,e,r){arguments[4][87][0].apply(r,arguments)},{dup:87}],1031:[function(t,e,r){function n(t,e){return t[0]-e[0]}function i(){var t,e=this.stride,r=new Array(e.length);for(t=0;te&&(r="View_Nil"+t);var n="generic"===t;if(-1===e){var a="function "+r+"(a){this.data=a;};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+r+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+r+"(a){return new "+r+"(a);}",o=new Function(a);return o()}if(0===e){var a="function "+r+"(a,d) {this.data = a;this.offset = d};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+r+"_copy() {return new "+r+"(this.data,this.offset)};proto.pick=function "+r+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+r+"_get(){return "+(n?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+r+"_set(v){return "+(n?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+r+"(a,b,c,d){return new "+r+"(a,d)}",o=new Function("TrivialArray",a);return o(f[t][0])}var a=["'use strict'"],s=l(e),u=s.map(function(t){return"i"+t}),c="this.offset+"+s.map(function(t){return"this.stride["+t+"]*i"+t}).join("+"),h=s.map(function(t){return"b"+t}).join(","),p=s.map(function(t){return"c"+t}).join(",");a.push("function "+r+"(a,"+h+","+p+",d){this.data=a","this.shape=["+h+"]","this.stride=["+p+"]","this.offset=d|0}","var proto="+r+".prototype","proto.dtype='"+t+"'","proto.dimension="+e),a.push("Object.defineProperty(proto,'size',{get:function "+r+"_size(){return "+s.map(function(t){return"this.shape["+t+"]"}).join("*"),"}})"),1===e?a.push("proto.order=[0]"):(a.push("Object.defineProperty(proto,'order',{get:"),4>e?(a.push("function "+r+"_order(){"),2===e?a.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+u.join(",")+",v){"),n?a.push("return this.data.set("+c+",v)}"):a.push("return this.data["+c+"]=v}"),a.push("proto.get=function "+r+"_get("+u.join(",")+"){"),n?a.push("return this.data.get("+c+")}"):a.push("return this.data["+c+"]}"),a.push("proto.index=function "+r+"_index(",u.join(),"){return "+c+"}"),a.push("proto.hi=function "+r+"_hi("+u.join(",")+"){return new "+r+"(this.data,"+s.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+s.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var d=s.map(function(t){return"a"+t+"=this.shape["+t+"]"}),g=s.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+u.join(",")+"){var b=this.offset,d=0,"+d.join(",")+","+g.join(","));for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){d=i"+v+"|0;b+=c"+v+"*d;a"+v+"-=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+u.join(",")+"){var "+s.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+s.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'){d=i"+v+"|0;if(d<0){c+=b"+v+"*(a"+v+"-1);a"+v+"=ceil(-a"+v+"/d)}else{a"+v+"=ceil(a"+v+"/d)}b"+v+"*=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"b"+t}).join(",")+",c)}");for(var m=new Array(e),y=new Array(e),v=0;e>v;++v)m[v]="a[i"+v+"]",y[v]="b[i"+v+"]";a.push("proto.transpose=function "+r+"_transpose("+u+"){"+u.map(function(t,e){return t+"=("+t+"===undefined?"+e+":"+t+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+r+"(this.data,"+m.join(",")+","+y.join(",")+",this.offset)}"),a.push("proto.pick=function "+r+"_pick("+u+"){var a=[],b=[],c=this.offset");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){c=(c+this.stride["+v+"]*i"+v+")|0}else{a.push(this.shape["+v+"]);b.push(this.stride["+v+"])}");a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+s.map(function(t){return"shape["+t+"]"; -}).join(",")+","+s.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}");var o=new Function("CTOR_LIST","ORDER",a.join("\n"));return o(f[t],i)}function o(t){if(u(t))return"buffer";if(c)switch(Object.prototype.toString.call(t)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(t)?"array":"generic"}function s(t,e,r,n){if(void 0===t){var i=f.array[0];return i([])}"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var s=e.length;if(void 0===r){r=new Array(s);for(var l=s-1,u=1;l>=0;--l)r[l]=u,u*=e[l]}if(void 0===n){n=0;for(var l=0;s>l;++l)r[l]<0&&(n-=(e[l]-1)*r[l])}for(var c=o(t),h=f[c];h.length<=s+1;)h.push(a(c,h.length-1));var i=h[s+1];return i(t,e,r,n)}var l=t("iota-array"),u=t("is-buffer"),c="undefined"!=typeof Float64Array,f={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=s},{"iota-array":1032,"is-buffer":1033}],1032:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=r;return e}e.exports=n},{}],1033:[function(t,e,r){e.exports=function(t){return!(null==t||!(t._isBuffer||t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)))}},{}],1034:[function(t,e,r){(function(t){e.exports=t.performance&&t.performance.now?function(){return performance.now()}:Date.now||function(){return+new Date}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],1035:[function(t,e,r){arguments[4][53][0].apply(r,arguments)},{dup:53}],1036:[function(t,e,r){arguments[4][54][0].apply(r,arguments)},{dup:54,"two-product":1039,"two-sum":1035}],1037:[function(t,e,r){arguments[4][364][0].apply(r,arguments)},{dup:364}],1038:[function(t,e,r){arguments[4][55][0].apply(r,arguments)},{dup:55}],1039:[function(t,e,r){arguments[4][56][0].apply(r,arguments)},{dup:56}],1040:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-1,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;ru;++u)0===(1&u)?e.push.apply(e,s(n(a,u))):r.push.apply(r,s(n(a,u))),l.push("m"+u);var c=o(e),g=o(r),v="orientation"+t+"Exact",m=["function ",v,"(",l.join(),"){var p=",c,",n=",g,",d=sub(p,n);return d[d.length-1];};return ",v].join(""),y=new Function("sum","prod","scale","sub",m);return y(h,f,p,d)}function u(t){var e=_[t.length];return e||(e=_[t.length]=l(t.length)),e.apply(void 0,t)}function c(){for(;_.length<=g;)_.push(l(_.length));for(var t=[],r=["slow"],n=0;g>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;g>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var f=t("two-product"),h=t("robust-sum"),p=t("robust-scale"),d=t("robust-subtract"),g=5,v=1.1102230246251565e-16,m=(3+16*v)*v,y=(7+56*v)*v,b=l(3),x=l(4),_=[function(){return 0},function(){return 0},function(t,e){return e[0]-t[0]},function(t,e,r){var n,i=(t[1]-r[1])*(e[0]-r[0]),a=(t[0]-r[0])*(e[1]-r[1]),o=i-a;if(i>0){if(0>=a)return o;n=i+a}else{if(!(0>i))return o;if(a>=0)return o;n=-(i+a)}var s=m*n;return o>=s||-s>=o?o:b(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],p=a*u,d=o*l,g=o*s,v=i*u,m=i*l,b=a*s,_=c*(p-d)+f*(g-v)+h*(m-b),w=(Math.abs(p)+Math.abs(d))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(f)+(Math.abs(m)+Math.abs(b))*Math.abs(h),k=y*w;return _>k||-_>k?_:x(t,e,r,n)}];c()},{"robust-scale":1036,"robust-subtract":1037,"robust-sum":1038,"two-product":1039}],1041:[function(t,e,r){"use strict";function n(t){return t.split("").map(function(t){return t in i?i[t]:""}).join("")}e.exports=n;var i={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"}},{}],1042:[function(e,r,n){!function(){function e(t,r){if(t=t?t:"",r=r||{},t instanceof e)return t;if(!(this instanceof e))return new e(t,r);var i=n(t);this._originalInput=t,this._r=i.r,this._g=i.g,this._b=i.b,this._a=i.a,this._roundA=U(100*this._a)/100,this._format=r.format||i.format,this._gradientType=r.gradientType,this._r<1&&(this._r=U(this._r)),this._g<1&&(this._g=U(this._g)),this._b<1&&(this._b=U(this._b)),this._ok=i.ok,this._tc_id=D++}function n(t){var e={r:0,g:0,b:0},r=1,n=!1,a=!1;return"string"==typeof t&&(t=O(t)),"object"==typeof t&&(t.hasOwnProperty("r")&&t.hasOwnProperty("g")&&t.hasOwnProperty("b")?(e=i(t.r,t.g,t.b),n=!0,a="%"===String(t.r).substr(-1)?"prgb":"rgb"):t.hasOwnProperty("h")&&t.hasOwnProperty("s")&&t.hasOwnProperty("v")?(t.s=P(t.s),t.v=P(t.v),e=l(t.h,t.s,t.v),n=!0,a="hsv"):t.hasOwnProperty("h")&&t.hasOwnProperty("s")&&t.hasOwnProperty("l")&&(t.s=P(t.s),t.l=P(t.l),e=o(t.h,t.s,t.l),n=!0,a="hsl"),t.hasOwnProperty("a")&&(r=t.a)),r=M(r),{ok:n,format:t.format||a,r:V(255,q(e.r,0)),g:V(255,q(e.g,0)),b:V(255,q(e.b,0)),a:r}}function i(t,e,r){return{r:255*T(t,255),g:255*T(e,255),b:255*T(r,255)}}function a(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=(a+o)/2;if(a==o)n=i=0;else{var l=a-o;switch(i=s>.5?l/(2-a-o):l/(a+o),a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,l:s}}function o(t,e,r){function n(t,e,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?t+6*(e-t)*r:.5>r?e:2/3>r?t+(e-t)*(2/3-r)*6:t}var i,a,o;if(t=T(t,360),e=T(e,100),r=T(r,100),0===e)i=a=o=r;else{var s=.5>r?r*(1+e):r+e-r*e,l=2*r-s;i=n(l,s,t+1/3),a=n(l,s,t),o=n(l,s,t-1/3)}return{r:255*i,g:255*a,b:255*o}}function s(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=a,l=a-o;if(i=0===a?0:l/a,a==o)n=0;else{switch(a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,v:s}}function l(t,e,r){t=6*T(t,360),e=T(e,100),r=T(r,100);var n=B.floor(t),i=t-n,a=r*(1-e),o=r*(1-i*e),s=r*(1-(1-i)*e),l=n%6,u=[r,o,a,a,s,r][l],c=[s,r,r,o,a,a][l],f=[a,a,s,r,r,o][l];return{r:255*u,g:255*c,b:255*f}}function u(t,e,r,n){var i=[z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function c(t,e,r,n){var i=[z(R(n)),z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return i.join("")}function f(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s-=r/100,n.s=E(n.s),e(n)}function h(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s+=r/100,n.s=E(n.s),e(n)}function p(t){return e(t).desaturate(100)}function d(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l+=r/100,n.l=E(n.l),e(n)}function g(t,r){r=0===r?0:r||10;var n=e(t).toRgb();return n.r=q(0,V(255,n.r-U(255*-(r/100)))),n.g=q(0,V(255,n.g-U(255*-(r/100)))),n.b=q(0,V(255,n.b-U(255*-(r/100)))),e(n)}function v(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l-=r/100,n.l=E(n.l),e(n)}function m(t,r){var n=e(t).toHsl(),i=(U(n.h)+r)%360;return n.h=0>i?360+i:i,e(n)}function y(t){var r=e(t).toHsl();return r.h=(r.h+180)%360,e(r)}function b(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+120)%360,s:r.s,l:r.l}),e({h:(n+240)%360,s:r.s,l:r.l})]}function x(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+90)%360,s:r.s,l:r.l}),e({h:(n+180)%360,s:r.s,l:r.l}),e({h:(n+270)%360,s:r.s,l:r.l})]}function _(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+72)%360,s:r.s,l:r.l}),e({h:(n+216)%360,s:r.s,l:r.l})]}function w(t,r,n){r=r||6,n=n||30;var i=e(t).toHsl(),a=360/n,o=[e(t)];for(i.h=(i.h-(a*r>>1)+720)%360;--r;)i.h=(i.h+a)%360,o.push(e(i));return o}function k(t,r){r=r||6;for(var n=e(t).toHsv(),i=n.h,a=n.s,o=n.v,s=[],l=1/r;r--;)s.push(e({h:i,s:a,v:o})),o=(o+l)%1;return s}function A(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}function M(t){return t=parseFloat(t),(isNaN(t)||0>t||t>1)&&(t=1),t}function T(t,e){S(t)&&(t="100%");var r=C(t);return t=V(e,q(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),B.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function E(t){return V(1,q(0,t))}function L(t){return parseInt(t,16)}function S(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)}function C(t){return"string"==typeof t&&-1!=t.indexOf("%")}function z(t){return 1==t.length?"0"+t:""+t}function P(t){return 1>=t&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function j(t){return L(t)/255}function O(t){t=t.replace(N,"").replace(F,"").toLowerCase();var e=!1;if(H[t])t=H[t],e=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};var r;return(r=X.rgb.exec(t))?{r:r[1],g:r[2],b:r[3]}:(r=X.rgba.exec(t))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=X.hsl.exec(t))?{h:r[1],s:r[2],l:r[3]}:(r=X.hsla.exec(t))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=X.hsv.exec(t))?{h:r[1],s:r[2],v:r[3]}:(r=X.hsva.exec(t))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=X.hex8.exec(t))?{a:j(r[1]),r:L(r[2]),g:L(r[3]),b:L(r[4]),format:e?"name":"hex8"}:(r=X.hex6.exec(t))?{r:L(r[1]),g:L(r[2]),b:L(r[3]),format:e?"name":"hex"}:(r=X.hex3.exec(t))?{r:L(r[1]+""+r[1]),g:L(r[2]+""+r[2]),b:L(r[3]+""+r[3]),format:e?"name":"hex"}:!1}function I(t){var e,r;return t=t||{level:"AA",size:"small"},e=(t.level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA"),"small"!==r&&"large"!==r&&(r="small"),{level:e,size:r}}var N=/^\s+/,F=/\s+$/,D=0,B=Math,U=B.round,V=B.min,q=B.max,G=B.random;e.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n,i,a,o=this.toRgb();return t=o.r/255,e=o.g/255,r=o.b/255,n=.03928>=t?t/12.92:Math.pow((t+.055)/1.055,2.4),i=.03928>=e?e/12.92:Math.pow((e+.055)/1.055,2.4),a=.03928>=r?r/12.92:Math.pow((r+.055)/1.055,2.4),.2126*n+.7152*i+.0722*a},setAlpha:function(t){return this._a=M(t),this._roundA=U(100*this._a)/100,this},toHsv:function(){var t=s(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=s(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return u(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(){return c(this._r,this._g,this._b,this._a)},toHex8String:function(){return"#"+this.toHex8()},toRgb:function(){return{r:U(this._r),g:U(this._g),b:U(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+U(this._r)+", "+U(this._g)+", "+U(this._b)+")":"rgba("+U(this._r)+", "+U(this._g)+", "+U(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:U(100*T(this._r,255))+"%",g:U(100*T(this._g,255))+"%",b:U(100*T(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%)":"rgba("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":this._a<1?!1:Y[u(this._r,this._g,this._b,!0)]||!1},toFilter:function(t){var r="#"+c(this._r,this._g,this._b,this._a),n=r,i=this._gradientType?"GradientType = 1, ":"";if(t){var a=e(t);n=a.toHex8String()}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+r+",endColorstr="+n+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0,i=!e&&n&&("hex"===t||"hex6"===t||"hex3"===t||"name"===t);return i?"name"===t&&0===this._a?this.toName():this.toRgbString():("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString())},clone:function(){return e(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(d,arguments)},brighten:function(){return this._applyModification(g,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(f,arguments)},saturate:function(){return this._applyModification(h,arguments)},greyscale:function(){return this._applyModification(p,arguments)},spin:function(){return this._applyModification(m,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(w,arguments)},complement:function(){return this._applyCombination(y,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(b,arguments)},tetrad:function(){return this._applyCombination(x,arguments)}},e.fromRatio=function(t,r){if("object"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&("a"===i?n[i]=t[i]:n[i]=P(t[i]));t=n}return e(t,r)},e.equals=function(t,r){return t&&r?e(t).toRgbString()==e(r).toRgbString():!1},e.random=function(){return e.fromRatio({r:G(),g:G(),b:G()})},e.mix=function(t,r,n){n=0===n?0:n||50;var i,a=e(t).toRgb(),o=e(r).toRgb(),s=n/100,l=2*s-1,u=o.a-a.a;i=l*u==-1?l:(l+u)/(1+l*u),i=(i+1)/2;var c=1-i,f={r:o.r*i+a.r*c,g:o.g*i+a.g*c,b:o.b*i+a.b*c,a:o.a*s+a.a*(1-s)};return e(f)},e.readability=function(t,r){var n=e(t),i=e(r);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},e.isReadable=function(t,r,n){var i,a,o=e.readability(t,r);switch(a=!1,i=I(n),i.level+i.size){case"AAsmall":case"AAAlarge":a=o>=4.5;break;case"AAlarge":a=o>=3;break;case"AAAsmall":a=o>=7}return a},e.mostReadable=function(t,r,n){var i,a,o,s,l=null,u=0;n=n||{},a=n.includeFallbackColors,o=n.level,s=n.size;for(var c=0;cu&&(u=i,l=e(r[c]));return e.isReadable(t,l,{level:o,size:s})||!a?l:(n.includeFallbackColors=!1,e.mostReadable(t,["#fff","#000"],n))};var H=e.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Y=e.hexNames=A(H),X=function(){var t="[-\\+]?\\d+%?",e="[-\\+]?\\d*\\.\\d+%?",r="(?:"+e+")|(?:"+t+")",n="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?",i="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?";return{rgb:new RegExp("rgb"+n),rgba:new RegExp("rgba"+i),hsl:new RegExp("hsl"+n),hsla:new RegExp("hsla"+i),hsv:new RegExp("hsv"+n),hsva:new RegExp("hsva"+i),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();"undefined"!=typeof r&&r.exports?r.exports=e:"function"==typeof t&&t.amd?t(function(){return e}):window.tinycolor=e}()},{}],1043:[function(e,r,n){!function(e,i){"object"==typeof n&&"undefined"!=typeof r?i(n):"function"==typeof t&&t.amd?t(["exports"],i):i(e.topojson=e.topojson||{})}(this,function(t){"use strict";function e(){}function r(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0),t[0]=(r+=t[0])*i+o,t[1]=(n+=t[1])*a+s}}function n(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0);var l=Math.round((t[0]-o)/i),u=Math.round((t[1]-s)/a);t[0]=l-r,t[1]=u-n,r=l,n=u}}function i(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r}function a(t,e){for(var r=0,n=t.length;n>r;){var i=r+n>>>1;t[i]t?~t:t],a=0,o=n.length;o>a;++a)e.push(r=n[a].slice()),c(r,a);0>t&&i(e,o)}function a(t){return t=t.slice(),c(t,0),t}function o(t){for(var e=[],r=0,i=t.length;i>r;++r)n(t[r],e);return e.length<2&&e.push(e[0].slice()),e}function s(t){for(var e=o(t);e.length<4;)e.push(e[0].slice());return e}function l(t){return t.map(s)}function u(t){var e=t.type;return"GeometryCollection"===e?{type:e,geometries:t.geometries.map(u)}:e in h?{type:e,coordinates:h[e](t)}:null}var c=r(t.transform),f=t.arcs,h={Point:function(t){return a(t.coordinates)},MultiPoint:function(t){return t.coordinates.map(a)},LineString:function(t){return o(t.arcs)},MultiLineString:function(t){return t.arcs.map(o)},Polygon:function(t){return l(t.arcs)},MultiPolygon:function(t){return t.arcs.map(l)}};return u(e)}function u(t,e){function r(e){var r,n=t.arcs[0>e?~e:e],i=n[0];return t.transform?(r=[0,0],n.forEach(function(t){r[0]+=t[0],r[1]+=t[1]})):r=n[n.length-1],0>e?[r,i]:[i,r]}function n(t,e){for(var r in t){var n=t[r];delete e[n.start],delete n.start,delete n.end,n.forEach(function(t){i[0>t?~t:t]=1}),s.push(n)}}var i={},a={},o={},s=[],l=-1;return e.forEach(function(r,n){var i,a=t.arcs[0>r?~r:r];a.length<3&&!a[1][0]&&!a[1][1]&&(i=e[++l],e[l]=r,e[n]=i)}),e.forEach(function(t){var e,n,i=r(t),s=i[0],l=i[1];if(e=o[s])if(delete o[e.end],e.push(t),e.end=l,n=a[l]){delete a[n.start];var u=n===e?e:e.concat(n);a[u.start=e.start]=o[u.end=n.end]=u}else a[e.start]=o[e.end]=e;else if(e=a[l])if(delete a[e.start],e.unshift(t),e.start=s,n=o[s]){delete o[n.end];var c=n===e?e:n.concat(e);a[c.start=n.start]=o[c.end=e.end]=c}else a[e.start]=o[e.end]=e;else e=[t],a[e.start=s]=o[e.end=l]=e}),n(o,a),n(a,o),e.forEach(function(t){i[0>t?~t:t]||s.push([t])}),s}function c(t){return l(t,f.apply(this,arguments))}function f(t,e,r){function n(t){var e=0>t?~t:t;(c[e]||(c[e]=[])).push({i:t,g:l})}function i(t){t.forEach(n)}function a(t){t.forEach(i)}function o(t){"GeometryCollection"===t.type?t.geometries.forEach(o):t.type in f&&(l=t,f[t.type](t.arcs))}var s=[];if(arguments.length>1){var l,c=[],f={LineString:i,MultiLineString:a,Polygon:a,MultiPolygon:function(t){t.forEach(a)}};o(e),c.forEach(arguments.length<3?function(t){s.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&s.push(t[0].i)})}else for(var h=0,p=t.arcs.length;p>h;++h)s.push(h);return{type:"MultiLineString",arcs:u(t,s)}}function h(t){var e=t[0],r=t[1],n=t[2];return Math.abs((e[0]-n[0])*(r[1]-e[1])-(e[0]-r[0])*(n[1]-e[1]))}function p(t){for(var e,r=-1,n=t.length,i=t[n-1],a=0;++re?~e:e]||(i[e]=[])).push(t)})}),a.push(t)}function n(e){return Math.abs(p(l(t,{type:"Polygon",arcs:[e]}).coordinates[0]))}var i={},a=[],o=[];return e.forEach(function(t){"Polygon"===t.type?r(t.arcs):"MultiPolygon"===t.type&&t.arcs.forEach(r)}),a.forEach(function(t){if(!t._){var e=[],r=[t];for(t._=1,o.push(e);t=r.pop();)e.push(t),t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].forEach(function(t){t._||(t._=1,r.push(t))})})})}}),a.forEach(function(t){delete t._}),{type:"MultiPolygon",arcs:o.map(function(e){var r,a=[];if(e.forEach(function(t){t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].length<2&&a.push(t)})})}),a=u(t,a),(r=a.length)>1)for(var o,s,l=1,c=n(a[0]);r>l;++l)(o=n(a[l]))>c&&(s=a[0],a[0]=a[l],a[l]=s,c=o);return a})}}function v(t){function e(t,e){t.forEach(function(t){0>t&&(t=~t);var r=i[t];r?r.push(e):i[t]=[e]})}function r(t,r){t.forEach(function(t){e(t,r)})}function n(t,e){"GeometryCollection"===t.type?t.geometries.forEach(function(t){n(t,e)}):t.type in s&&s[t.type](t.arcs,e)}var i={},o=t.map(function(){return[]}),s={LineString:e,MultiLineString:r,Polygon:r,MultiPolygon:function(t,e){t.forEach(function(t){r(t,e)})}};t.forEach(n);for(var l in i)for(var u=i[l],c=u.length,f=0;c>f;++f)for(var h=f+1;c>h;++h){var p,d=u[f],g=u[h];(p=o[d])[l=a(p,g)]!==g&&p.splice(l,0,g),(p=o[g])[l=a(p,d)]!==d&&p.splice(l,0,d)}return o}function m(t,e){return t[1][2]-e[1][2]}function y(){function t(t,e){for(;e>0;){var r=(e+1>>1)-1,i=n[r];if(m(t,i)>=0)break;n[i._=e]=i,n[t._=e=r]=t}}function e(t,e){for(;;){var r=e+1<<1,a=r-1,o=e,s=n[o];if(i>a&&m(n[a],s)<0&&(s=n[o=a]),i>r&&m(n[r],s)<0&&(s=n[o=r]),o===e)break;n[s._=e]=s,n[t._=e=o]=t}}var r={},n=[],i=0;return r.push=function(e){return t(n[e._=i]=e,i++),i},r.pop=function(){if(!(0>=i)){var t,r=n[0];return--i>0&&(t=n[i],e(n[t._=0]=t,0)),r}},r.remove=function(r){var a,o=r._;if(n[o]===r)return o!==--i&&(a=n[i],(m(a,r)<0?t:e)(n[a._=o]=a,o)),o},r}function b(t,e){function i(t){s.remove(t),t[1][2]=e(t),s.push(t)}var a=r(t.transform),o=n(t.transform),s=y();return e||(e=h),t.arcs.forEach(function(t){var r,n,l,u,c=[],f=0;for(n=0,l=t.length;l>n;++n)u=t[n],a(t[n]=[u[0],u[1],1/0],n);for(n=1,l=t.length-1;l>n;++n)r=t.slice(n-1,n+2),r[1][2]=e(r),c.push(r),s.push(r);for(n=0,l=c.length;l>n;++n)r=c[n],r.previous=c[n-1],r.next=c[n+1];for(;r=s.pop();){var h=r.previous,p=r.next;r[1][2]h;h++){var p=l[h],d={_fullLayout:e},g=c.coerceRef(t,n,d,p),m=.5;if("paper"!==g){var y=c.getFromId(d,g);if(m=y.range[0]+m*(y.range[1]-y.range[0]),-1!==["date","category"].indexOf(y.type)&&"string"==typeof t[p]){var b;"date"===y.type?(b=u.dateTime2ms(t[p]),b!==!1&&(t[p]=b)):(y._categories||[]).length&&(b=y._categories.indexOf(t[p]),-1!==b&&(t[p]=b))}}r(p,m),s||r(p+"anchor")}return u.noneOrAll(t,n,["x","y"]),n}function i(t){var e=t._fullLayout;e.annotations.forEach(function(e){var r=c.getFromId(t,e.xref),n=c.getFromId(t,e.yref);if(r||n){var i=(e._xsize||0)/2,a=e._xshift||0,o=(e._ysize||0)/2,s=e._yshift||0,l=i-a,u=i+a,f=o-s,h=o+s;if(e.showarrow){var p=3*e.arrowsize*e.arrowwidth;l=Math.max(l,p),u=Math.max(u,p),f=Math.max(f,p),h=Math.max(h,p)}r&&r.autorange&&c.expand(r,[r.l2c(e.x)],{ppadplus:u,ppadminus:l}),n&&n.autorange&&c.expand(n,[n.l2c(e.y)],{ppadplus:h,ppadminus:f})}})}function a(t,e,r,n,i,a,o,s){var l=r-t,u=i-t,c=o-i,f=n-e,h=a-e,p=s-a,d=l*p-c*f;if(0===d)return null;var g=(u*p-c*h)/d,v=(u*f-l*h)/d;return 0>v||v>1||0>g||g>1?null:{x:t+l*g,y:e+f*g}}var o=t("d3"),s=t("fast-isnumeric"),l=t("../../plotly"),u=t("../../lib"),c=t("../../plots/cartesian/axes"),f=t("../color"),h=t("../drawing"),p=t("../../lib/svg_text_utils"),d=t("../../lib/setcursor"),g=t("../dragelement"),v=e.exports={};v.ARROWPATHS=t("./arrow_paths"),v.layoutAttributes=t("./attributes"),v.supplyLayoutDefaults=function(t,e){for(var r=t.annotations||[],i=e.annotations=[],a=0;at?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}tt.selectAll("tspan.line").attr({y:0,x:0});var n=W.select(".annotation-math-group"),i=!n.empty(),s=h.bBox((i?n:tt).node()),p=s.width,m=s.height,y=Math.round(p+2*$),b=Math.round(m+2*$);U._w=p,U._h=m;var x=!1;if(["x","y"].forEach(function(e){var n,i=c.getFromId(t,U[e+"ref"]||e),a=(H+("x"===e?0:90))*Math.PI/180,o=y*Math.abs(Math.cos(a))+b*Math.abs(Math.sin(a)),s=U[e+"anchor"];if(i){if(!i.autorange&&(U[e]-i.range[0])*(U[e]-i.range[1])>0)return void(x=!0);G[e]=i._offset+i.l2p(U[e]),n=.5}else n=U[e],"y"===e&&(n=1-n),G[e]="x"===e?S.l+S.w*n:S.t+S.h*n;var l=0;l=U.showarrow?U["a"+e]:o*r(n,s),G[e]+=l,U["_"+e+"type"]=i&&i.type,U["_"+e+"size"]=o,U["_"+e+"shift"]=l}),x)return void W.remove();var w,k;U.showarrow&&(w=u.constrain(G.x-U.ax,1,_.width-1),k=u.constrain(G.y-U.ay,1,_.height-1)),G.x=u.constrain(G.x,1,_.width-1),G.y=u.constrain(G.y,1,_.height-1);var A=$-s.top,M=$-s.left;i?n.select("svg").attr({x:$-1,y:$}):(tt.attr({x:M,y:A}),tt.selectAll("tspan.line").attr({y:A,x:M})),Q.call(h.setRect,Z/2,Z/2,y-Z,b-Z);var T=Math.round(G.x-y/2),E=Math.round(G.y-b/2);W.call(u.setTranslate,T,E);var L="annotations["+e+"]",C=function(r,n){o.select(t).selectAll('.annotation-arrow-g[data-index="'+e+'"]').remove();var i=G.x+r,s=G.y+n,c=u.rotationXYMatrix(H,i,s),h=u.apply2DTransform(c),p=u.apply2DTransform2(c),d=Q.attr("width")/2,m=Q.attr("height")/2,y=[[i-d,s-m,i-d,s+m],[i-d,s+m,i+d,s+m],[i+d,s+m,i+d,s-m],[i+d,s-m,i-d,s-m]].map(p);if(!y.reduce(function(t,e){return t^!!a(w,k,w+1e6,k+1e6,e[0],e[1],e[2],e[3])},!1)){y.forEach(function(t){var e=a(i,s,w,k,t[0],t[1],t[2],t[3]);e&&(i=e.x,s=e.y)});var b=U.arrowwidth,x=U.arrowcolor,_=Y.append("g").style({opacity:f.opacity(x) -}).classed("annotation-arrow-g",!0).attr("data-index",String(e)),A=_.append("path").attr("d","M"+i+","+s+"L"+w+","+k).style("stroke-width",b+"px").call(f.stroke,f.rgb(x));v.arrowhead(A,U.arrowhead,"end",U.arrowsize);var M=_.append("path").classed("annotation",!0).classed("anndrag",!0).attr({"data-index":String(e),d:"M3,3H-3V-3H3ZM0,0L"+(i-w)+","+(s-k),transform:"translate("+w+","+k+")"}).style("stroke-width",b+6+"px").call(f.stroke,"rgba(0,0,0,0)").call(f.fill,"rgba(0,0,0,0)");if(t._context.editable){var T,E,C;g.init({element:M.node(),prepFn:function(){var t=u.getTranslate(W);E=t.x,C=t.y,T={},V&&V.autorange&&(T[V._name+".autorange"]=!0),q&&q.autorange&&(T[q._name+".autorange"]=!0)},moveFn:function(t,e){_.attr("transform","translate("+t+","+e+")");var r=h(E,C),n=r[0]+t,i=r[1]+e;W.call(u.setTranslate,n,i),T[L+".x"]=V?U.x+t/V._m:(w+t-S.l)/S.w,T[L+".y"]=q?U.y+e/q._m:1-(k+e-S.t)/S.h,X.attr({transform:"rotate("+H+","+n+","+i+")"})},doneFn:function(e){if(e){l.relayout(t,T);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}};U.showarrow&&C(0,0);var z=u.rotationXYMatrix(H,G.x,G.y),P=u.apply2DTransform(z);if(t._context.editable){var R,j,O;g.init({element:W.node(),prepFn:function(){var t=u.getTranslate(W);R=t.x,j=t.y,O={}},moveFn:function(t,e){W.call(u.setTranslate,R+t,j+e);var r="pointer";if(U.showarrow)O[L+".ax"]=U.ax+t,O[L+".ay"]=U.ay+e,C(t,e);else{if(V)O[L+".x"]=U.x+t/V._m;else{var n=U._xsize/S.w,i=U.x+U._xshift/S.w-n/2;O[L+".x"]=g.align(i+t/S.w,n,0,1,U.xanchor)}if(q)O[L+".y"]=U.y+e/q._m;else{var a=U._ysize/S.h,o=U.y-U._yshift/S.h-a/2;O[L+".y"]=g.align(o-e/S.h,a,0,1,U.yanchor)}V&&q||(r=g.getCursor(V?.5:O[L+".x"],q?.5:O[L+".y"],U.xanchor,U.yanchor))}var s=P(R,j),l=s[0]+t,c=s[1]+e;W.call(u.setTranslate,R+t,j+e),X.attr({transform:"rotate("+H+","+l+","+c+")"}),d(W,r)},doneFn:function(e){if(d(W),e){l.relayout(t,O);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}var b,x=t.layout,_=t._fullLayout;if(!s(e)||-1===e){if(!e&&Array.isArray(i))return x.annotations=i,v.supplyLayoutDefaults(x,_),void v.drawAll(t);if("remove"===i)return delete x.annotations,_.annotations=[],void v.drawAll(t);if(r&&"add"!==i){for(b=0;b<_.annotations.length;b++)v.draw(t,b,r,i);return}e=_.annotations.length,_.annotations.push({})}if(!r&&i){if("remove"===i){for(_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove(),_.annotations.splice(e,1),x.annotations.splice(e,1),b=e;b<_.annotations.length;b++)_._infolayer.selectAll('.annotation[data-index="'+(b+1)+'"]').attr("data-index",String(b)),v.draw(t,b);return}if("add"===i||u.isPlainObject(i)){_.annotations.splice(e,0,{});var w=u.isPlainObject(i)?u.extendFlat({},i):{text:"New text"};for(x.annotations?x.annotations.splice(e,0,w):x.annotations=[w],b=_.annotations.length-1;b>e;b--)_._infolayer.selectAll('.annotation[data-index="'+(b-1)+'"]').attr("data-index",String(b)),v.draw(t,b)}}_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove();var k=x.annotations[e],A=_.annotations[e];if(k){var M={xref:k.xref,yref:k.yref},T={};"string"==typeof r&&r?T[r]=i:u.isPlainObject(r)&&(T=r);var E=Object.keys(T);for(b=0;bb;b++){var z=C[b];if(void 0===T[z]&&void 0!==k[z]){var P=c.getFromId(t,c.coerceRef(M,{},t,z)),R=c.getFromId(t,c.coerceRef(k,{},t,z)),j=k[z],O=A["_"+z+"type"];if(void 0!==T[z+"ref"]){var I="auto"===k[z+"anchor"],N="x"===z?S.w:S.h,F=(A["_"+z+"size"]||0)/(2*N);if(P&&R)j=(j-P.range[0])/(P.range[1]-P.range[0]),j=R.range[0]+j*(R.range[1]-R.range[0]);else if(P){if(j=(j-P.range[0])/(P.range[1]-P.range[0]),j=P.domain[0]+j*(P.domain[1]-P.domain[0]),I){var D=j+F,B=j-F;2/3>j+B?j=B:j+D>4/3&&(j=D)}}else R&&(I&&(1/3>j?j+=F:j>2/3&&(j-=F)),j=(j-R.domain[0])/(R.domain[1]-R.domain[0]),j=R.range[0]+j*(R.range[1]-R.range[0]))}R&&R===P&&O&&("log"===O&&"log"!==R.type?j=Math.pow(10,j):"log"!==O&&"log"===R.type&&(j=j>0?Math.log(j)/Math.LN10:void 0)),k[z]=j}}var U=n(k,_);_.annotations[e]=U;var V=c.getFromId(t,U.xref),q=c.getFromId(t,U.yref),G={x:0,y:0},H=+U.textangle||0,Y=_._infolayer.append("g").classed("annotation",!0).attr("data-index",String(e)).style("opacity",U.opacity).on("click",function(){t._dragging=!1,t.emit("plotly_clickannotation",{index:e,annotation:k,fullAnnotation:U})}),X=Y.append("g").classed("annotation-text-g",!0).attr("data-index",String(e)),W=X.append("g"),Z=U.borderwidth,K=U.borderpad,$=Z+K,Q=W.append("rect").attr("class","bg").style("stroke-width",Z+"px").call(f.stroke,U.bordercolor).call(f.fill,U.bgcolor),J=U.font,tt=W.append("text").classed("annotation",!0).attr("data-unformatted",U.text).text(U.text);t._context.editable?tt.call(p.makeEditable,W).call(m).on("edit",function(r){U.text=r,this.attr({"data-unformatted":U.text}),this.call(m);var n={};n["annotations["+e+"].text"]=U.text,V&&V.autorange&&(n[V._name+".autorange"]=!0),q&&q.autorange&&(n[q._name+".autorange"]=!0),l.relayout(t,n)}):tt.call(m),X.attr({transform:"rotate("+H+","+G.x+","+G.y+")"}).call(h.setPosition,G.x,G.y)}},v.arrowhead=function(t,e,r,n){s(n)||(n=1);var i=t.node(),a=v.ARROWPATHS[e||0];if(a){"string"==typeof r&&r||(r="end");var l,u,c,p,d=(h.getPx(t,"stroke-width")||1)*n,g=t.style("stroke")||f.defaultLine,m=t.style("stroke-opacity")||1,y=r.indexOf("start")>=0,b=r.indexOf("end")>=0,x=a.backoff*d;if("line"===i.nodeName){if(l={x:+t.attr("x1"),y:+t.attr("y1")},u={x:+t.attr("x2"),y:+t.attr("y2")},c=Math.atan2(l.y-u.y,l.x-u.x),p=c+Math.PI,x){var _=x*Math.cos(c),w=x*Math.sin(c);y&&(l.x-=_,l.y-=w,t.attr({x1:l.x,y1:l.y})),b&&(u.x+=_,u.y+=w,t.attr({x2:u.x,y2:u.y}))}}else if("path"===i.nodeName){var k=i.getTotalLength(),A="";if(y){var M=i.getPointAtLength(0),T=i.getPointAtLength(.1);c=Math.atan2(M.y-T.y,M.x-T.x),l=i.getPointAtLength(Math.min(x,k)),x&&(A="0px,"+x+"px,")}if(b){var E=i.getPointAtLength(k),L=i.getPointAtLength(k-.1);if(p=Math.atan2(E.y-L.y,E.x-L.x),u=i.getPointAtLength(Math.max(0,k-x)),x){var S=A?2*x:x;A+=k-S+"px,"+k+"px"}}else A&&(A+=k+"px");A&&t.style("stroke-dasharray",A)}var C=function(r,n){e>5&&(n=0),o.select(i.parentElement).append("path").attr({"class":t.attr("class"),d:a.path,transform:"translate("+r.x+","+r.y+")rotate("+180*n/Math.PI+")scale("+d+")"}).style({fill:g,opacity:m,"stroke-width":0})};y&&C(l,c),b&&C(u,p)}},v.calcAutorange=function(t){var e=t._fullLayout,r=e.annotations;if(r.length&&t._fullData.length){var n={};r.forEach(function(t){n[t.xref]=!0,n[t.yref]=!0});var a=c.list(t).filter(function(t){return t.autorange&&n[t._id]});if(a.length)return u.syncOrAsync([v.drawAll,i],t)}}},{"../../lib":1127,"../../lib/setcursor":1136,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/cartesian/axes":1150,"../color":1048,"../dragelement":1069,"../drawing":1071,"./arrow_paths":1044,"./attributes":1045,d3:82,"fast-isnumeric":90}],1047:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.lightFraction=1e3/11},{}],1048:[function(t,e,r){"use strict";function n(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}var i=t("tinycolor2"),a=t("fast-isnumeric"),o=e.exports={},s=t("./attributes");o.defaults=s.defaults,o.defaultLine=s.defaultLine,o.lightLine=s.lightLine,o.background=s.background,o.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},o.rgb=function(t){return o.tinyRGB(i(t))},o.opacity=function(t){return t?i(t).getAlpha():0},o.addOpacity=function(t,e){var r=i(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},o.combine=function(t,e){var r=i(t).toRgb();if(1===r.a)return i(t).toRgbString();var n=i(e||o.background).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},s={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return i(s).toRgbString()},o.stroke=function(t,e){var r=i(e);t.style({stroke:o.tinyRGB(r),"stroke-opacity":r.getAlpha()})},o.fill=function(t,e){var r=i(e);t.style({fill:o.tinyRGB(r),"fill-opacity":r.getAlpha()})},o.clean=function(t){if(t&&"object"==typeof t){var e,r,i,a,s=Object.keys(t);for(e=0;el&&(a[1]-=(ot-l)/2)):r.node()&&!r.classed("js-placeholder")&&(ot=h.bBox(e.node()).height),ot){if(ot+=5,"top"===x.titleside)Q.domain[1]-=ot/M.h,a[1]*=-1;else{Q.domain[0]+=ot/M.h;var c=Math.max(1,r.selectAll("tspan.line").size());a[1]+=(1-c)*l}e.attr("transform","translate("+a+")"),Q.setScale()}}it.selectAll(".cbfills,.cblines,.cbaxis").attr("transform","translate(0,"+Math.round(M.h*(1-Q.domain[1]))+")");var f=it.select(".cbfills").selectAll("rect.cbfill").data(S);f.enter().append("rect").classed("cbfill",!0).style("stroke","none"),f.exit().remove(),f.each(function(t,e){var r=[0===e?E[0]:(S[e]+S[e-1])/2,e===S.length-1?E[1]:(S[e]+S[e+1])/2].map(Q.c2p).map(Math.round);e!==S.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=z(t).replace("e-",""),o=i(a).toHexString();n.select(this).attr({x:Y,width:Math.max(D,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var p=it.select(".cblines").selectAll("path.cbline").data(x.line.color&&x.line.width?L:[]);return p.enter().append("path").classed("cbline",!0),p.exit().remove(),p.each(function(t){n.select(this).attr("d","M"+Y+","+(Math.round(Q.c2p(t))+x.line.width/2%1)+"h"+D).call(h.lineGroupStyle,x.line.width,C(t),x.line.dash)}),Q._axislayer.selectAll("g."+Q._id+"tick,path").remove(),Q._pos=Y+D+(x.outlinewidth||0)/2-("outside"===x.ticks?1:0),Q.side="right",u.syncOrAsync([function(){return s.doTicks(t,Q,!0)},function(){if(-1===["top","bottom"].indexOf(x.titleside)){var e=Q.titlefont.size,r=Q._offset+Q._length/2,i=M.l+(Q.position||0)*M.w+("right"===Q.side?10+e*(Q.showticklabels?1:.5):-10-e*(Q.showticklabels?.5:0));w("h"+Q._id+"title",{avoid:{selection:n.select(t).selectAll("g."+Q._id+"tick"),side:x.titleside,offsetLeft:M.l,offsetTop:M.t,maxShift:A.width},attributes:{x:i,y:r,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])}function w(e,r){var n,i=b();n=o.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var a={propContainer:Q,propName:n,traceIndex:i.index,dfltName:"colorscale",containerGroup:it.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;it.selectAll("."+s+",."+s+"-math-group").remove(),d.draw(t,e,c(a,r||{}))}function k(){var r=D+x.outlinewidth/2+h.bBox(Q._axislayer.node()).width;if(I=at.select("text"),I.node()&&!I.classed("js-placeholder")){var n,i=at.select(".h"+Q._id+"title-math-group").node();n=i&&-1!==["top","bottom"].indexOf(x.titleside)?h.bBox(i).width:h.bBox(at.node()).right-Y-M.l,r=Math.max(r,n)}var a=2*x.xpad+r+x.borderwidth+x.outlinewidth/2,s=Z-K;it.select(".cbbg").attr({x:Y-x.xpad-(x.borderwidth+x.outlinewidth)/2,y:K-G,width:Math.max(a,2),height:Math.max(s+2*G,2)}).call(p.fill,x.bgcolor).call(p.stroke,x.bordercolor).style({"stroke-width":x.borderwidth}),it.selectAll(".cboutline").attr({x:Y,y:K+x.ypad+("top"===x.titleside?ot:0),width:Math.max(D,2),height:Math.max(s-2*x.ypad-ot,2)}).call(p.stroke,x.outlinecolor).style({fill:"None","stroke-width":x.outlinewidth});var l=({center:.5,right:1}[x.xanchor]||0)*a;it.attr("transform","translate("+(M.l-l)+","+M.t+")"),o.autoMargin(t,e,{x:x.x,y:x.y,l:a*({right:1,center:.5}[x.xanchor]||0),r:a*({left:1,center:.5}[x.xanchor]||0),t:s*({bottom:1,middle:.5}[x.yanchor]||0),b:s*({top:1,middle:.5}[x.yanchor]||0)})}var A=t._fullLayout,M=A._size;if("function"!=typeof x.fillcolor&&"function"!=typeof x.line.color)return void A._infolayer.selectAll("g."+e).remove();var T,E=n.extent(("function"==typeof x.fillcolor?x.fillcolor:x.line.color).domain()),L=[],S=[],C="function"==typeof x.line.color?x.line.color:function(){return x.line.color},z="function"==typeof x.fillcolor?x.fillcolor:function(){return x.fillcolor},P=x.levels.end+x.levels.size/100,R=x.levels.size,j=1.001*E[0]-.001*E[1],O=1.001*E[1]-.001*E[0];for(T=x.levels.start;0>(T-P)*R;T+=R)T>j&&O>T&&L.push(T);if("function"==typeof x.fillcolor)if(x.filllevels)for(P=x.filllevels.end+x.filllevels.size/100,R=x.filllevels.size,T=x.filllevels.start;0>(T-P)*R;T+=R)T>E[0]&&T1){var nt=Math.pow(10,Math.floor(Math.log(rt)/Math.LN10));tt*=nt*u.roundUp(rt/nt,[2,5,10]),(Math.abs(x.levels.start)/x.levels.size+1e-6)%1<2e-6&&(Q.tick0=0)}Q.dtick=tt}Q.domain=[W+H,W+V-H],Q.setScale();var it=A._infolayer.selectAll("g."+e).data([0]);it.enter().append("g").classed(e,!0).each(function(){var t=n.select(this);t.append("rect").classed("cbbg",!0),t.append("g").classed("cbfills",!0),t.append("g").classed("cblines",!0),t.append("g").classed("cbaxis",!0).classed("crisp",!0),t.append("g").classed("cbtitleunshift",!0).append("g").classed("cbtitle",!0),t.append("rect").classed("cboutline",!0),t.select(".cbtitle").datum(0)}),it.attr("transform","translate("+Math.round(M.l)+","+Math.round(M.t)+")");var at=it.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(M.l)+",-"+Math.round(M.t)+")");Q._axislayer=it.select(".cbaxis");var ot=0;if(-1!==["top","bottom"].indexOf(x.titleside)){var st,lt=M.l+(x.x+q)*M.w,ut=Q.titlefont.size;st="top"===x.titleside?(1-(W+V-H))*M.h+M.t+3+.75*ut:(1-(W+H))*M.h+M.t-3-.25*ut,w(Q._id+"title",{attributes:{x:lt,y:st,"text-anchor":"start"}})}var ct=u.syncOrAsync([o.previousPromises,_,o.previousPromises,k],t);if(ct&&ct.then&&(t._promises||[]).push(ct),t._context.editable){var ft,ht,pt;l.init({element:it.node(),prepFn:function(){ft=it.attr("transform"),f(it)},moveFn:function(t,e){it.attr("transform",ft+" translate("+t+","+e+")"),ht=l.align(X+t/M.w,B,0,1,x.xanchor),pt=l.align(W-e/M.h,V,0,1,x.yanchor);var r=l.getCursor(ht,pt,x.xanchor,x.yanchor);f(it,r)},doneFn:function(e){f(it),e&&void 0!==ht&&void 0!==pt&&a.restyle(t,{"colorbar.x":ht,"colorbar.y":pt},b().index)}})}return ct}function b(){var r,n,i=e.substr(2);for(r=0;rc*f?i.RdBu:c>=0?i.Reds:i.Blues,l.colorscale=h,s.reversescale&&(h=a(h)),s.colorscale=h)}},{"../../lib":1127,"./flip_scale":1059,"./scales":1066}],1056:[function(t,e,r){"use strict";var n=t("./attributes"),i=t("../../lib/extend").extendDeep;e.exports=function(t){return{color:{valType:"color",arrayOk:!0},colorscale:i({},n.colorscale,{}),cauto:i({},n.zauto,{}),cmax:i({},n.zmax,{}),cmin:i({},n.zmin,{}),autocolorscale:i({},n.autocolorscale,{}),reversescale:i({},n.reversescale,{})}}},{"../../lib/extend":1122,"./attributes":1054}],1057:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":1066}],1058:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./is_valid_scale"),l=t("./flip_scale");e.exports=function(t,e,r,u,c){var f=c.prefix,h=c.cLetter,p=f.slice(0,f.length-1),d=f?i.nestedProperty(t,p).get()||{}:t,g=f?i.nestedProperty(e,p).get()||{}:e,v=d[h+"min"],m=d[h+"max"],y=d.colorscale,b=n(v)&&n(m)&&m>v;u(f+h+"auto",!b),u(f+h+"min"),u(f+h+"max");var x;void 0!==y&&(x=!s(y)),u(f+"autocolorscale",x);var _=u(f+"colorscale"),w=u(f+"reversescale");if(w&&(g.colorscale=l(_)),"marker.line."!==f){var k;f&&(k=a(d));var A=u(f+"showscale",k);A&&o(d,g,r)}}},{"../../lib":1127,"../colorbar/defaults":1050,"../colorbar/has_colorbar":1052,"./flip_scale":1059,"./is_valid_scale":1063,"fast-isnumeric":90}],1059:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n}},{}],1060:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./default_scale"),a=t("./is_valid_scale_array");e.exports=function(t,e){function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return e||(e=i),t?("string"==typeof t&&(r(),"string"==typeof t&&r()),a(t)?t:e):e}},{"./default_scale":1057,"./is_valid_scale_array":1064,"./scales":1066}],1061:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("./is_valid_scale");e.exports=function(t,e){var r=e?i.nestedProperty(t,e).get()||{}:t,o=r.color,s=!1;if(Array.isArray(o))for(var l=0;lh;h++)l=t[h],c[h]=e+l[0]*(r-e),f[h]=i(l[1]).toRgb();var p=n.scale.linear().domain(c).interpolate(n.interpolateObject).range(f);return function(t){if(a(t)){var n=o.constrain(t,e,r),l=p(n);return i(l).toRgbString()}return i(t).isValid()?t:s.defaultLine}}},{"../../lib":1127,"../color":1048,d3:82,"fast-isnumeric":90,tinycolor2:1042}],1066:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]]}},{}],1067:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=(t-r)/(n-r),o=a+e/(n-r),s=(a+o)/2;return"left"===i||"bottom"===i?a:"center"===i||"middle"===i?s:"right"===i||"top"===i?o:2/3-s>a?a:o>4/3-s?o:s}},{}],1068:[function(t,e,r){"use strict";var n=t("../../lib"),i=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,a){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===a?0:"middle"===a?1:"top"===a?2:n.constrain(Math.floor(3*e),0,2),i[e][t]}},{"../../lib":1127}],1069:[function(t,e,r){"use strict";function n(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function i(t){t._dragging=!1,t._replotPending&&a.plot(t)}var a=t("../../plotly"),o=t("../../lib"),s=t("../../plots/cartesian/constants"),l=e.exports={};l.align=t("./align"),l.getCursor=t("./cursor");var u=t("./unhover");l.unhover=u.wrapped,l.unhoverRaw=u.raw,l.init=function(t){function e(e){return d._dragged=!1,d._dragging=!0,u=e.clientX,c=e.clientY,p=e.target,f=(new Date).getTime(),f-d._mouseDownTimev&&(g=Math.max(g-1,1)),t.doneFn&&t.doneFn(d._dragged,g),!d._dragged){var r=document.createEvent("MouseEvents");r.initEvent("click",!0,!0),p.dispatchEvent(r)}return i(d),d._dragged=!1,o.pauseEvent(e)}var u,c,f,h,p,d=o.getPlotDiv(t.element)||{},g=1,v=s.DBLCLICKDELAY;d._mouseDownTime||(d._mouseDownTime=0),t.element.onmousedown=e,t.element.style.pointerEvents="all"}},{"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/constants":1155,"./align":1067,"./cursor":1068,"./unhover":1070}],1070:[function(t,e,r){"use strict";var n=t("../../lib/events"),i=e.exports={};i.wrapped=function(t,e,r){"string"==typeof t&&(t=document.getElementById(t)),t._hoverTimer&&(clearTimeout(t._hoverTimer),t._hoverTimer=void 0),i.raw(t,e,r)},i.raw=function(t,e){var r=t._fullLayout;e||(e={}),e.target&&n.triggerHandler(t,"plotly_beforehover",e)===!1||(r._hoverlayer.selectAll("g").remove(),e.target&&t._hoverdata&&t.emit("plotly_unhover",{points:t._hoverdata}),t._hoverdata=void 0)}},{"../../lib/events":1121}],1071:[function(t,e,r){"use strict";function n(t,e,r,n){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],u=Math.pow(a*a+o*o,x/2),c=Math.pow(s*s+l*l,x/2),f=(c*c*a-u*u*s)*n,h=(c*c*o-u*u*l)*n,p=3*c*(u+c),d=3*u*(u+c);return[[i.round(e[0]+(p&&f/p),2),i.round(e[1]+(p&&h/p),2)],[i.round(e[0]-(d&&f/d),2),i.round(e[1]-(d&&h/d),2)]]}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../plots/plots"),s=t("../color"),l=t("../colorscale"),u=t("../../lib"),c=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),h=t("../../traces/scatter/subtypes"),p=t("../../traces/scatter/make_bubble_size_func"),d=e.exports={}; -d.font=function(t,e,r,n){e&&e.family&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(s.fill,n)},d.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},d.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},d.setRect=function(t,e,r,n,i){t.call(d.setPosition,e,r).call(d.setSize,n,i)},d.translatePoints=function(t,e,r,n,o,s){var l=o&&(o||{}).duration>0;if(l)var u=t.size();t.each(function(t,c){var f=t.xp||e.c2p(t.x),h=t.yp||r.c2p(t.y),p=i.select(this);if(a(f)&&a(h))if("text"===this.nodeName)p.attr("x",f).attr("y",h);else if(l){var g;s?-1===s?g=p.style("opacity",1).transition().duration(o.duration).ease(o.easing).style("opacity",0).remove():1===s&&(g=p.attr("transform","translate("+f+","+h+")"),n&&g.call(d.pointStyle,n),g.style("opacity",0).transition().duration(o.duration).ease(o.easing).style("opacity",1)):(g=p.transition().delay(o.delay+o.cascade/u*c).duration(o.duration).ease(o.easing).attr("transform","translate("+f+","+h+")"),n&&g.call(d.pointStyle,n))}else p.attr("transform","translate("+f+","+h+")");else p.remove()})},d.getPx=function(t,e){return Number(t.style(e).replace(/px$/,""))},d.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:1>e?1:Math.round(e):r||0},d.lineGroupStyle=function(t,e,r,n){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,l=n||a.dash||"";i.select(this).call(s.stroke,r||a.color).call(d.dashLine,l,o)})},d.dashLine=function(t,e,r){var n=Math.max(r,3);"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},d.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=i.select(this);try{r.call(s.fill,e[0].trace.fillcolor)}catch(n){u.error(n,t),r.remove()}})};var g=t("./symbol_defs");d.symbolNames=[],d.symbolFuncs=[],d.symbolNeedLines={},d.symbolNoDot={},d.symbolList=[],Object.keys(g).forEach(function(t){var e=g[t];d.symbolList=d.symbolList.concat([e.n,t,e.n+100,t+"-open"]),d.symbolNames[e.n]=t,d.symbolFuncs[e.n]=e.f,e.needLine&&(d.symbolNeedLines[e.n]=!0),e.noDot?d.symbolNoDot[e.n]=!0:d.symbolList=d.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"])});var v=d.symbolNames.length,m="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";d.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),t=d.symbolNames.indexOf(t),t>=0&&(t+=e)}return t%100>=v||t>=400?0:Math.floor(Math.max(t,0))},d.pointStyle=function(t,e){if(t.size()){var r=e.marker,n=r.line;if(o.traceIs(e,"symbols")){var a=p(e);t.attr("d",function(t){var n;n="various"===t.ms||"various"===r.size?3:h.isBubble(e)?a(t.ms):(r.size||6)/2,t.mrc=n;var i=d.symbolNumber(t.mx||r.symbol)||0,o=i%100;return t.om=i%200>=100,d.symbolFuncs[o](n)+(i>=200?m:"")}).style("opacity",function(t){return(t.mo+1||r.opacity+1)-1})}var l=(e._input||{}).marker||{},u=d.tryColorscale(r,l,""),c=d.tryColorscale(r,l,"line.");t.each(function(t,e){var a,o,l;t.so?(l=n.outlierwidth,o=n.outliercolor,a=r.outliercolor):(l=(t.mlw+1||n.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,o="mlc"in t?t.mlcc=c(t.mlc):Array.isArray(n.color)?r.color[e]:n.color,a="mc"in t?t.mcc=u(t.mc):Array.isArray(r.color)?r.color[e]:r.color||"rgba(0,0,0,0)");var f=i.select(this);t.om?f.call(s.stroke,a).style({"stroke-width":(l||1)+"px",fill:"none"}):(f.style("stroke-width",l+"px").call(s.fill,a),l&&f.call(s.stroke,o))})}},d.tryColorscale=function(t,e,r){var n=u.nestedProperty(t,r+"color").get(),i=u.nestedProperty(t,r+"colorscale").get(),o=u.nestedProperty(t,r+"cauto").get(),s=u.nestedProperty(t,r+"cmin"),c=u.nestedProperty(t,r+"cmax"),f=s.get(),h=c.get();return i&&Array.isArray(n)?(!o&&a(f)&&a(h)||(f=1/0,h=-(1/0),n.forEach(function(t){a(t)&&(f>t&&(f=+t),t>h&&(h=+t))}),f>h&&(f=0,h=1),s.set(f),c.set(h),u.nestedProperty(e,r+"cmin").set(f),u.nestedProperty(e,r+"cmax").set(h)),l.makeScaleFunction(i,f,h)):u.identity};var y={start:1,end:-1,middle:0,bottom:1,top:-1},b=1.3;d.textPointStyle=function(t,e){t.each(function(t){var r=i.select(this),n=t.tx||e.text;if(!n||Array.isArray(n))return void r.remove();var o=t.tp||e.textposition,s=-1!==o.indexOf("top")?"top":-1!==o.indexOf("bottom")?"bottom":"middle",l=-1!==o.indexOf("left")?"end":-1!==o.indexOf("right")?"start":"middle",u=t.ts||e.textfont.size,f=t.mrc?t.mrc/.8+1:0;u=a(u)&&u>0?u:0,r.call(d.font,t.tf||e.textfont.family,u,t.tc||e.textfont.color).attr("text-anchor",l).text(n).call(c.convertToTspans);var h=i.select(this.parentNode),p=r.selectAll("tspan.line"),g=((p[0].length||1)-1)*b+1,v=y[l]*f,m=.75*u+y[s]*f+(y[s]-1)*g*u/2;h.attr("transform","translate("+v+","+m+")"),g>1&&p.attr({x:r.attr("x"),y:r.attr("y")})})};var x=.5;d.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,i="M"+t[0],a=[];for(r=1;rr;r++)o.push(n(t[r-1],t[r],t[r+1],e));for(o.push(n(t[a-1],t[a],t[0],e)),r=1;a>=r;r++)i+="C"+o[r-1][1]+" "+o[r][0]+" "+t[r];return i+="C"+o[a][1]+" "+o[0][0]+" "+t[0]+"Z"};var _={hv:function(t,e){return"H"+i.round(e[0],2)+"V"+i.round(e[1],2)},vh:function(t,e){return"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},hvh:function(t,e){return"H"+i.round((t[0]+e[0])/2,2)+"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},vhv:function(t,e){return"V"+i.round((t[1]+e[1])/2,2)+"H"+i.round(e[0],2)+"V"+i.round(e[1],2)}},w=function(t,e){return"L"+i.round(e[0],2)+","+i.round(e[1],2)};d.steps=function(t){var e=_[t]||w;return function(t){for(var r="M"+i.round(t[0][0],2)+","+i.round(t[0][1],2),n=1;n=A&&(i.selectAll("[data-bb]").attr("data-bb",null),k=[]),t.setAttribute("data-bb",k.length),k.push(l),u.extendFlat({},l)},d.setClipUrl=function(t,e){if(!e)return void t.attr("clip-path",null);var r="#"+e,n=i.select("base");n.size()&&n.attr("href")&&(r=window.location.href+r),t.attr("clip-path","url("+r+")")}},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plots/plots":1199,"../../traces/scatter/make_bubble_size_func":1315,"../../traces/scatter/subtypes":1322,"../color":1048,"../colorscale":1062,"./symbol_defs":1072,d3:82,"fast-isnumeric":90}],1072:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+","+r+"H"+e+"L0,-"+i+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+",-"+r+"H"+e+"L0,"+i+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M"+r+",-"+e+"V"+e+"L-"+i+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+r+",-"+e+"V"+e+"L"+i+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(t*-.309,2),o=n.round(.809*t,2);return"M"+e+","+a+"L"+r+","+o+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(e*-.309,2),u=n.round(.118*e,2),c=n.round(.809*e,2),f=n.round(.382*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+u+"L"+o+","+c+"L0,"+f+"L-"+o+","+c+"L-"+a+","+u+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0}}},{d3:82}],1073:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"]},symmetric:{valType:"boolean"},array:{valType:"data_array"},arrayminus:{valType:"data_array"},value:{valType:"number",min:0,dflt:10},valueminus:{valType:"number",min:0,dflt:10},traceref:{valType:"integer",min:0,dflt:0},tracerefminus:{valType:"integer",min:0,dflt:0},copy_ystyle:{valType:"boolean"},copy_zstyle:{valType:"boolean"},color:{valType:"color"},thickness:{valType:"number",min:0,dflt:2},width:{valType:"number",min:0},_deprecated:{opacity:{valType:"number"}}}},{}],1074:[function(t,e,r){"use strict";function n(t,e,r,n){var a=e["error_"+n]||{},l=a.visible&&-1!==["linear","log"].indexOf(r.type),u=[];if(l){for(var c=s(a),f=0;fs;s++)o[s]={x:r[s],y:i[s]};return o[0].trace=t,n.calc({calcdata:[o],_fullLayout:e}),o},n.plot=t("./plot"),n.style=t("./style"),n.hoverInfo=function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys)),(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}},{"./attributes":1073,"./calc":1074,"./defaults":1076,"./plot":1078,"./style":1079}],1078:[function(t,e,r){"use strict";function n(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../lib"),s=t("../../traces/scatter/subtypes");e.exports=function(t,e){var r=e.x(),l=e.y();t.each(function(t){var e=t[0].trace,u=e.error_x||{},c=e.error_y||{},f=s.hasMarkers(e)&&e.marker.maxdisplayed>0;if(c.visible||u.visible){var h=i.select(this).selectAll("g.errorbar").data(o.identity);h.enter().append("g").classed("errorbar",!0),h.each(function(t){var e=i.select(this),o=n(t,r,l);if(!f||t.vis){var s;if(c.visible&&a(o.x)&&a(o.yh)&&a(o.ys)){var h=c.width;s="M"+(o.x-h)+","+o.yh+"h"+2*h+"m-"+h+",0V"+o.ys,o.noYS||(s+="m-"+h+",0h"+2*h),e.append("path").classed("yerror",!0).attr("d",s)}if(u.visible&&a(o.y)&&a(o.xh)&&a(o.xs)){var p=(u.copy_ystyle?c:u).width;s="M"+o.xh+","+(o.y-p)+"v"+2*p+"m0,-"+p+"H"+o.xs,o.noXS||(s+="m0,-"+p+"v"+2*p),e.append("path").classed("xerror",!0).attr("d",s)}}})}})}},{"../../lib":1127,"../../traces/scatter/subtypes":1322,d3:82,"fast-isnumeric":90}],1079:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(i.stroke,r.color),a.copy_ystyle&&(a=r),o.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(i.stroke,a.color)})}},{"../color":1048,d3:82}],1080:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants");e.exports={_isLinkedToArray:!0,source:{valType:"string"},layer:{valType:"enumerated",values:["below","above"],dflt:"above"},sizex:{valType:"number",dflt:0},sizey:{valType:"number",dflt:0},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain"},opacity:{valType:"number",min:0,max:1,dflt:1},x:{valType:"number",dflt:0},y:{valType:"number",dflt:0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper"}}},{"../../plots/cartesian/constants":1155}],1081:[function(t,e,r){"use strict";function n(t,e,r){function n(r,n){return a.coerce(t,e,o,r,n)}e=e||{},n("source"),n("layer"),n("x"),n("y"),n("xanchor"),n("yanchor"),n("sizex"),n("sizey"),n("sizing"),n("opacity");for(var s=0;2>s;s++){var l={_fullLayout:r},u=["x","y"][s];i.coerceRef(t,e,l,u,"paper")}return e}var i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./attributes");e.exports=function(t,e){if(t.images&&Array.isArray(t.images))for(var r=t.images,i=e.images=[],a=0;a=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],1085:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat;e.exports={bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.defaultLine},borderwidth:{valType:"number",min:0,dflt:0},font:a({},n,{}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"]},tracegroupgap:{valType:"number",min:0,dflt:10},x:{valType:"number",min:-2,max:3,dflt:1.02},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"}}},{"../../lib/extend":1122,"../../plots/font_attributes":1168,"../color/attributes":1047}],1086:[function(t,e,r){"use strict";e.exports={scrollBarWidth:4,scrollBarHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],1087:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/plots"),a=t("./attributes"),o=t("./helpers");e.exports=function(t,e,r){function s(t,e){return n.coerce(h,p,a,t,e)}for(var l,u,c,f,h=t.legend||{},p=e.legend={},d=0,g="normal",v=0;v1);if(y!==!1){if(s("bgcolor",e.paper_bgcolor),s("bordercolor"),s("borderwidth"),n.coerceFont(s,"font",e.font),s("orientation"),"h"===p.orientation){var b=t.xaxis;b&&b.rangeslider&&b.rangeslider.visible?(l=0,c="left",u=1.1,f="bottom"):(l=0,c="left",u=-.1,f="top")}s("traceorder",g),o.isGrouped(e.legend)&&s("tracegroupgap"),s("x",l),s("xanchor",c),s("y",u),s("yanchor",f),n.noneOrAll(h,p,["x","y"])}}},{"../../lib":1127,"../../plots/plots":1199,"./attributes":1085,"./helpers":1090}],1088:[function(t,e,r){"use strict";function n(t,e){function r(r){c.util.convertToTspans(r,function(){r.selectAll("tspan.line").attr({x:r.attr("x")}),t.call(a,e)})}var n=t.data()[0][0],i=e._fullLayout,o=n.trace,s=h.traceIs(o,"pie"),l=o.index,u=s?n.label:o.name,f=t.selectAll("text.legendtext").data([0]);f.enter().append("text").classed("legendtext",!0),f.attr({x:40,y:0,"data-unformatted":u}).style("text-anchor","start").classed("user-select-none",!0).call(d.font,i.legend.font).text(u),e._context.editable&&!s?f.call(c.util.makeEditable).call(r).on("edit",function(t){this.attr({"data-unformatted":t}),this.text(t).call(r),this.text()||(t=" "),c.restyle(e,"name",t,l)}):f.call(r)}function i(t,e){var r=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(g.fill,"rgba(0,0,0,0)"),n.on("click",function(){if(!e._dragged){var n,i,a=t.data()[0][0],o=e._fullData,s=a.trace,l=s.legendgroup,u=[];if(h.traceIs(s,"pie")){var f=a.label,p=r.indexOf(f);-1===p?r.push(f):r.splice(p,1),c.relayout(e,"hiddenlabels",r)}else{if(""===l)u=[s.index];else for(var d=0;dtspan"),p=h[0].length||1;r=l*p,n=c.node()&&d.bBox(c.node()).width;var g=l*(.3+(1-p)/2);c.attr("y",g),h.attr("y",g)}r=Math.max(r,16)+3,a.attr({x:0,y:-r/2,height:r}),i.height=r,i.width=n}function o(t,e,r){var n=t._fullLayout,i=n.legend,a=i.borderwidth,o=b.isGrouped(i);if(b.isVertical(i))o&&e.each(function(t,e){f.setTranslate(this,0,e*i.tracegroupgap)}),i.width=0,i.height=0,r.each(function(t){var e=t[0],r=e.height,n=e.width;f.setTranslate(this,a,5+a+i.height+r/2),i.height+=r,i.width=Math.max(i.width,n)}),i.width+=45+2*a,i.height+=10+2*a,o&&(i.height+=(i._lgroupsLength-1)*i.tracegroupgap),r.selectAll(".legendtoggle").attr("width",(t._context.editable?0:i.width)+40),i.width=Math.ceil(i.width),i.height=Math.ceil(i.height);else if(o){i.width=0,i.height=0;for(var s=[i.width],l=e.data(),c=0,h=l.length;h>c;c++){var p=l[c].map(function(t){return t[0].width}),d=40+Math.max.apply(null,p);i.width+=i.tracegroupgap+d,s.push(i.width)}e.each(function(t,e){f.setTranslate(this,s[e],0)}),e.each(function(){var t=u.select(this),e=t.selectAll("g.traces"),r=0;e.each(function(t){var e=t[0],n=e.height;f.setTranslate(this,0,5+a+r+n/2),r+=n}),i.height=Math.max(i.height,r)}),i.height+=10+2*a,i.width+=2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}else i.width=0,i.height=0,r.each(function(t){var e=t[0],r=40+e.width,n=i.tracegroupgap||5;f.setTranslate(this,a+i.width,5+a+e.height/2),i.width+=n+r,i.height=Math.max(i.height,e.height)}),i.width+=2*a,i.height+=10+2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}function s(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center");var i="top";x.isBottomAnchor(r)?i="bottom":x.isMiddleAnchor(r)&&(i="middle"),h.autoMargin(t,"legend",{x:r.x,y:r.y,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:r.height*({top:1,middle:.5}[i]||0),t:r.height*({bottom:1,middle:.5}[i]||0)})}function l(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center"),h.autoMargin(t,"legend",{x:r.x,y:.5,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:0,t:0})}var u=t("d3"),c=t("../../plotly"),f=t("../../lib"),h=t("../../plots/plots"),p=t("../dragelement"),d=t("../drawing"),g=t("../color"),v=t("./constants"),m=t("./get_legend_data"),y=t("./style"),b=t("./helpers"),x=t("./anchor_utils");e.exports=function(t){function e(t,e){T.attr("data-scroll",e).call(f.setTranslate,0,e),E.call(d.setRect,F,t,v.scrollBarWidth,v.scrollBarHeight),A.select("rect").attr({y:b.borderwidth-e})}var r=t._fullLayout,a="legend"+r._uid;if(r._infolayer&&t.calcdata){var b=r.legend,_=r.showlegend&&m(t.calcdata,b),w=r.hiddenlabels||[];if(!r.showlegend||!_.length)return r._infolayer.selectAll(".legend").remove(),r._topdefs.select("#"+a).remove(),void h.autoMargin(t,"legend");var k=r._infolayer.selectAll("g.legend").data([0]);k.enter().append("g").attr({"class":"legend","pointer-events":"all"});var A=r._topdefs.selectAll("#"+a).data([0]);A.enter().append("clipPath").attr("id",a).append("rect");var M=k.selectAll("rect.bg").data([0]);M.enter().append("rect").attr({"class":"bg","shape-rendering":"crispEdges"}).call(g.stroke,b.bordercolor).call(g.fill,b.bgcolor).style("stroke-width",b.borderwidth+"px");var T=k.selectAll("g.scrollbox").data([0]);T.enter().append("g").attr("class","scrollbox");var E=k.selectAll("rect.scrollbar").data([0]);E.enter().append("rect").attr({"class":"scrollbar",rx:20,ry:2,width:0,height:0}).call(g.fill,"#808BA4");var L=T.selectAll("g.groups").data(_);L.enter().append("g").attr("class","groups"),L.exit().remove();var S=L.selectAll("g.traces").data(f.identity);S.enter().append("g").attr("class","traces"),S.exit().remove(),S.call(y).style("opacity",function(t){var e=t[0].trace;return h.traceIs(e,"pie")?-1!==w.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){u.select(this).call(n,t).call(i,t)});var C=0!==k.enter().size();C&&(o(t,L,S),s(t));var z=0,P=r.width,R=0,j=r.height;o(t,L,S),b.height>j?l(t):s(t);var O=r._size,I=O.l+O.w*b.x,N=O.t+O.h*(1-b.y);x.isRightAnchor(b)?I-=b.width:x.isCenterAnchor(b)&&(I-=b.width/2),x.isBottomAnchor(b)?N-=b.height:x.isMiddleAnchor(b)&&(N-=b.height/2);var F=b.width,D=O.w;F>D?(I=O.l,F=D):(I+F>P&&(I=P-F),z>I&&(I=z),F=Math.min(P-I,b.width));var B=b.height,U=O.h;B>U?(N=O.t,B=U):(N+B>j&&(N=j-B),R>N&&(N=R),B=Math.min(j-N,b.height)),f.setTranslate(k,I,N);var V,q,G=B-v.scrollBarHeight-2*v.scrollBarMargin,H=b.height-B;if(b.height<=B||t._context.staticPlot)M.attr({ -width:F-b.borderwidth,height:B-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2}),f.setTranslate(T,0,0),A.select("rect").attr({width:F-2*b.borderwidth,height:B-2*b.borderwidth,x:b.borderwidth,y:b.borderwidth}),T.call(d.setClipUrl,a);else{V=v.scrollBarMargin,q=T.attr("data-scroll")||0,M.attr({width:F-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin,height:B-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2}),A.select("rect").attr({width:F-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin,height:B-2*b.borderwidth,x:b.borderwidth,y:b.borderwidth-q}),T.call(d.setClipUrl,a),C&&e(V,q),k.on("wheel",null),k.on("wheel",function(){q=f.constrain(T.attr("data-scroll")-u.event.deltaY/G*H,-H,0),V=v.scrollBarMargin-q/H*G,e(V,q),u.event.preventDefault()}),E.on(".drag",null),T.on(".drag",null);var Y=u.behavior.drag().on("drag",function(){V=f.constrain(u.event.y-v.scrollBarHeight/2,v.scrollBarMargin,v.scrollBarMargin+G),q=-(V-v.scrollBarMargin)/G*H,e(V,q)});E.call(Y),T.call(Y)}if(t._context.editable){var X,W,Z,K;k.classed("cursor-move",!0),p.init({element:k.node(),prepFn:function(){var t=f.getTranslate(k);Z=t.x,K=t.y},moveFn:function(t,e){var r=Z+t,n=K+e;f.setTranslate(k,r,n),X=p.align(r,0,O.l,O.l+O.w,b.xanchor),W=p.align(n,0,O.t+O.h,O.t,b.yanchor)},doneFn:function(e){e&&void 0!==X&&void 0!==W&&c.relayout(t,{"legend.x":X,"legend.y":W})}})}}}},{"../../lib":1127,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../dragelement":1069,"../drawing":1071,"./anchor_utils":1084,"./constants":1086,"./get_legend_data":1089,"./helpers":1090,"./style":1092,d3:82}],1089:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("./helpers");e.exports=function(t,e){function r(t,r){if(""!==t&&i.isGrouped(e))-1===l.indexOf(t)?(l.push(t),u=!0,s[t]=[[r]]):s[t].push([r]);else{var n="~~i"+f;l.push(n),s[n]=[[r]],f++}}var a,o,s={},l=[],u=!1,c={},f=0;for(a=0;aa;a++)m=s[l[a]],y[a]=i.isReversed(e)?m.reverse():m;else{for(y=[new Array(b)],a=0;b>a;a++)m=s[l[a]][0],y[0][i.isReversed(e)?b-a-1:a]=m;b=1}return e._lgroupsLength=b,y}},{"../../plots/plots":1199,"./helpers":1090}],1090:[function(t,e,r){"use strict";var n=t("../../plots/plots");r.legendGetsTrace=function(t){return t.visible&&n.traceIs(t,"showLegend")},r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{"../../plots/plots":1199}],1091:[function(t,e,r){"use strict";var n=e.exports={};n.layoutAttributes=t("./attributes"),n.supplyLayoutDefaults=t("./defaults"),n.draw=t("./draw"),n.style=t("./style")},{"./attributes":1085,"./defaults":1087,"./draw":1088,"./style":1092}],1092:[function(t,e,r){"use strict";function n(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,n=p.hasLines(e),i=l.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);i.enter().append("path").classed("js-fill",!0),i.exit().remove(),i.attr("d","M5,0h30v6h-30z").call(f.fillGroupStyle);var a=l.select(this).select(".legendlines").selectAll("path").data(n?[t]:[]);a.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),a.exit().remove(),a.call(f.lineGroupStyle)}function i(t){function e(t,e,r){var n=u.nestedProperty(o,t).get(),i=Array.isArray(n)&&e?e(n):n;if(r){if(ir[1])return r[1]}return i}function r(t){return t[0]}var n,i,a=t[0],o=a.trace,s=p.hasMarkers(o),c=p.hasText(o),h=p.hasLines(o);if(s||c||h){var d={},g={};s&&(d.mc=e("marker.color",r),d.mo=e("marker.opacity",u.mean,[.2,1]),d.ms=e("marker.size",u.mean,[2,16]),d.mlc=e("marker.line.color",r),d.mlw=e("marker.line.width",u.mean,[0,5]),g.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),h&&(g.line={width:e("line.width",r,[0,10])}),c&&(d.tx="Aa",d.tp=e("textposition",r),d.ts=10,d.tc=e("textfont.color",r),d.tf=e("textfont.family",r)),n=[u.minExtend(a,d)],i=u.minExtend(o,g)}var v=l.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(s?n:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(f.pointStyle,i),s&&(n[0].mrc=3);var y=v.selectAll("g.pointtext").data(c?n:[]);y.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),y.exit().remove(),y.selectAll("text").call(f.textPointStyle,i)}function a(t){var e=t[0].trace,r=e.marker||{},n=r.line||{},i=l.select(this).select("g.legendpoints").selectAll("path.legendbar").data(c.traceIs(e,"bar")?[t]:[]);i.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),i.exit().remove(),i.each(function(t){var e=(t.mlw+1||n.width+1)-1,i=l.select(this);i.style("stroke-width",e+"px").call(h.fill,t.mc||r.color),e&&i.call(h.stroke,t.mlc||n.color)})}function o(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendbox").data(c.traceIs(e,"box")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(t){var r=(t.lw+1||e.line.width+1)-1,n=l.select(this);n.style("stroke-width",r+"px").call(h.fill,t.fc||e.fillcolor),r&&n.call(h.stroke,t.lc||e.line.color)})}function s(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendpie").data(c.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(d,t[0],e)}var l=t("d3"),u=t("../../lib"),c=t("../../plots/plots"),f=t("../drawing"),h=t("../color"),p=t("../../traces/scatter/subtypes"),d=t("../../traces/pie/style_one");e.exports=function(t){t.each(function(t){var e=l.select(this),r=e.selectAll("g.legendfill").data([t]);r.enter().append("g").classed("legendfill",!0);var n=e.selectAll("g.legendlines").data([t]);n.enter().append("g").classed("legendlines",!0);var i=e.selectAll("g.legendsymbols").data([t]);i.enter().append("g").classed("legendsymbols",!0),i.style("opacity",t[0].trace.opacity),i.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(a).each(o).each(s).each(n).each(i)}},{"../../lib":1127,"../../plots/plots":1199,"../../traces/pie/style_one":1299,"../../traces/scatter/subtypes":1322,"../color":1048,"../drawing":1071,d3:82}],1093:[function(t,e,r){"use strict";function n(t,e){var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o={};if("zoom"===n){for(var s,l,c="in"===i?.5:2,h=(1+c)/2,p=(1-c)/2,d=u.Axes.list(t,null,!0),v=0;vy;y++){var b=s[y];h=m[b]={};for(var x=0;x1)return n(["resetViews","toggleHover"]),o(v,r);c&&(n(["zoom3d","pan3d","orbitRotation","tableRotation"]),n(["resetCameraDefault3d","resetCameraLastSave3d"]),n(["hoverClosest3d"])),h&&(n(["zoomInGeo","zoomOutGeo","resetGeo"]),n(["hoverClosestGeo"]));var m=i(s),y=[];return((u||d)&&!m||g)&&(y=["zoom2d","pan2d"]),(u||g)&&a(l)&&(y.push("select2d"),y.push("lasso2d")),y.length&&n(y),!u&&!d||m||g||n(["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]),u&&p?n(["toggleHover"]):d?n(["hoverClosestGl2d"]):u?n(["hoverClosestCartesian","hoverCompareCartesian"]):p&&n(["hoverClosestPie"]),o(v,r)}function i(t){for(var e=l.Axes.list({_fullLayout:t},null,!0),r=!0,n=0;n0);if(h){var p=i(e,r,s);l("x",p[0]),l("y",p[1]),a.noneOrAll(t,e,["x","y"]),l("xanchor"),l("yanchor"),a.coerceFont(l,"font",r.font),l("bgcolor"),l("bordercolor"),l("borderwidth")}}},{"../../lib":1127,"./attributes":1096,"./button_attributes":1097,"./constants":1098}],1100:[function(t,e,r){"use strict";function n(t){for(var e=m.list(t,"x",!0),r=[],n=0;ne){var r=e;e=t,t=r}s.setAttributes(w,{"data-min":t,"data-max":e}),s.setAttributes(R,{x:t,width:e-t}),s.setAttributes(M,{width:t}),s.setAttributes(T,{x:e,width:d-e}),s.setAttributes(E,{transform:"translate("+(t-v-1)+")"}),s.setAttributes(C,{transform:"translate("+e+")"})}var f=t._fullLayout,h=f._infolayer.selectAll("g.range-slider"),p=f.xaxis.rangeslider,d=f._size.w,g=(f.height-f.margin.b-f.margin.t)*p.thickness,v=2,m=Math.floor(p.borderwidth/2),y=f.margin.l,b=f.height-g-f.margin.b,x=0,_=d,w=document.createElementNS(o,"g");s.setAttributes(w,{"class":"range-slider","data-min":x,"data-max":_,"pointer-events":"all",transform:"translate("+y+","+b+")"});var k=document.createElementNS(o,"rect"),A=p.borderwidth%2===0?p.borderwidth:p.borderwidth-1;s.setAttributes(k,{fill:p.bgcolor,stroke:p.bordercolor,"stroke-width":p.borderwidth,height:g+A,width:d+A,transform:"translate(-"+m+", -"+m+")","shape-rendering":"crispEdges"});var M=document.createElementNS(o,"rect");s.setAttributes(M,{x:0,width:x,height:g,fill:"rgba(0,0,0,0.4)"});var T=document.createElementNS(o,"rect");s.setAttributes(T,{x:_,width:d-_,height:g,fill:"rgba(0,0,0,0.4)"});var E=document.createElementNS(o,"g"),L=document.createElementNS(o,"rect"),S=document.createElementNS(o,"rect");s.setAttributes(E,{transform:"translate("+(x-v-1)+")"}),s.setAttributes(L,{width:10,height:g,x:-6,fill:"transparent",cursor:"col-resize"}),s.setAttributes(S,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(E,[S,L]);var C=document.createElementNS(o,"g"),z=document.createElementNS(o,"rect"),P=document.createElementNS(o,"rect");s.setAttributes(C,{transform:"translate("+_+")"}),s.setAttributes(z,{width:10,height:g,x:-2,fill:"transparent",cursor:"col-resize"}),s.setAttributes(P,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(C,[P,z]);var R=document.createElementNS(o,"rect");s.setAttributes(R,{x:x,width:_-x,height:g,cursor:"ew-resize",fill:"transparent"}),w.addEventListener("mousedown",function(t){function r(t){var r,n,f=+t.clientX-a;switch(i){case R:w.style.cursor="ew-resize",r=+s+f,n=+l+f,c(r,n),u(e(r),e(n));break;case L:w.style.cursor="col-resize",r=+s+f,n=+l,c(r,n),u(e(r),e(n));break;case z:w.style.cursor="col-resize",r=+s,n=+l+f,c(r,n),u(e(r),e(n));break;default:w.style.cursor="ew-resize",r=o,n=o+f,c(r,n),u(e(r),e(n))}}function n(){window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n),w.style.cursor="auto"}var i=t.target,a=t.clientX,o=a-w.getBoundingClientRect().left,s=w.getAttribute("data-min"),l=w.getAttribute("data-max");window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)}),p.range||(p.range=i.getAutoRange(f.xaxis));var j=l(t,d,g);s.appendChildren(w,[k,j,M,T,R,E,C]),r(f.xaxis.range[0],f.xaxis.range[1]),h.data([0]).enter().append(function(){return p.setRange=r,w})}},{"../../constants/xmlns_namespaces":1115,"../../lib":1127,"../../plotly":1147,"../../plots/cartesian/axes":1150,"./helpers":1106,"./range_plot":1108}],1105:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(t,e){return n.coerce(s,l,i,t,e)}if(t[r].rangeslider){var s="object"==typeof t[r].rangeslider?t[r].rangeslider:{},l=e[r].rangeslider={};if(o("bgcolor"),o("bordercolor"),o("borderwidth"),o("thickness"),o("visible"),o("range"),l.range&&!e[r].autorange){var u=l.range,c=e[r].range;u[0]=Math.min(u[0],c[0]),u[1]=Math.max(u[1],c[1])}else e[r]._needsExpand=!0;l.visible&&a.forEach(function(t){var r=e[t]||{};r.fixedrange=!0,e[t]=r})}}},{"../../lib":1127,"./attributes":1103}],1106:[function(t,e,r){"use strict";r.setAttributes=function(t,e){for(var r in e)t.setAttribute(r,e[r])},r.appendChildren=function(t,e){for(var r=0;rl;l++){var u=s[l],c={_fullLayout:e},f=x.coerceRef(t,n,c,u);if("path"!==o){var h=.25,p=.75;if("paper"!==f){var d=x.getFromId(c,f),g=a(d);h=g(d.range[0]+h*(d.range[1]-d.range[0])),p=g(d.range[0]+p*(d.range[1]-d.range[0]))}r(u+"0",h),r(u+"1",p)}}return"path"===o?r("path"):b.noneOrAll(t,n,["x0","x1","y0","y1"]),n}function i(t){return"category"===t.type?t.c2l:t.d2l}function a(t){return"category"===t.type?t.l2c:t.l2d}function o(t,e){t.layout.shapes=e,k.supplyLayoutDefaults(t.layout,t._fullLayout),k.drawAll(t)}function s(t){delete t.layout.shapes,t._fullLayout.shapes=[],k.drawAll(t)}function l(t,e,r){for(var n=0;ne;i--)h(t,i).selectAll('[data-index="'+(i-1)+'"]').attr("data-index",i),k.draw(t,i)}function f(t,e,r,o){function s(e){var r=e.append("path").attr(z).style("opacity",S.opacity).call(_.stroke,P).call(_.fill,S.fillcolor).call(w.dashLine,S.line.dash,S.line.width);C&&r.call(w.setClipUrl,"clip"+t._fullLayout._uid+C)}var l,u;h(t,e).selectAll('[data-index="'+e+'"]').remove();var c=t.layout.shapes[e];if(c){var f={xref:c.xref,yref:c.yref},d={};"string"==typeof r&&r?d[r]=o:b.isPlainObject(r)&&(d=r);var v=Object.keys(d);for(l=0;ll;l++){var k=y[l];if(void 0===d[k]&&void 0!==c[k]){var A,M=k.charAt(0),T=x.getFromId(t,x.coerceRef(f,{},t,M)),E=x.getFromId(t,x.coerceRef(c,{},t,M)),L=c[k];void 0!==d[M+"ref"]&&(T?(A=i(T)(L),L=(A-T.range[0])/(T.range[1]-T.range[0])):L=(L-E.domain[0])/(E.domain[1]-E.domain[0]),E?(A=E.range[0]+L*(E.range[1]-E.range[0]),L=a(E)(A)):L=T.domain[0]+L*(T.domain[1]-T.domain[0])),c[k]=L}}var S=n(c,t._fullLayout);t._fullLayout.shapes[e]=S;var C,z={"data-index":e,"fill-rule":"evenodd",d:g(t,S)},P=S.line.width?S.line.color:"rgba(0,0,0,0)";if("below"!==S.layer)C=(S.xref+S.yref).replace(/paper/g,""),s(t._fullLayout._shapeUpperLayer);else if("paper"===S.xref&&"paper"===S.yref)C="",s(t._fullLayout._shapeLowerLayer);else{var R,j=t._fullLayout._plots||{},O=Object.keys(j);for(l=0,u=O.length;u>l;l++)R=j[O[l]],C=O[l],p(t,S,R)&&s(R.shapelayer)}}}function h(t,e){var r=t._fullLayout.shapes[e],n=t._fullLayout._shapeUpperLayer;return r?"below"===r.layer&&(n="paper"===r.xref&&"paper"===r.yref?t._fullLayout._shapeLowerLayer:t._fullLayout._shapeSubplotLayer):b.log("getShapeLayer: undefined shape: index",e),n}function p(t,e,r){var n=y.Axes.getFromId(t,r.id,"x")._id,i=y.Axes.getFromId(t,r.id,"y")._id,a="below"===e.layer,o=n===e.xref||i===e.yref,s=!!r.shapelayer;return a&&o&&s}function d(t){return function(e){return t(e.replace("_"," "))}}function g(t,e){var r,n,a,o,s=e.type,l=x.getFromId(t,e.xref),u=x.getFromId(t,e.yref),c=t._fullLayout._size;if(l?(r=i(l),n=function(t){return l._offset+l.l2p(r(t,!0))}):n=function(t){return c.l+c.w*t},u?(a=i(u),o=function(t){return u._offset+u.l2p(a(t,!0))}):o=function(t){return c.t+c.h*(1-t)},"path"===s)return l&&"date"===l.type&&(n=d(n)),u&&"date"===u.type&&(o=d(o)),k.convertPath(e.path,n,o);var f=n(e.x0),h=n(e.x1),p=o(e.y0),g=o(e.y1);if("line"===s)return"M"+f+","+p+"L"+h+","+g;if("rect"===s)return"M"+f+","+p+"H"+h+"V"+g+"H"+f+"Z";var v=(f+h)/2,m=(p+g)/2,y=Math.abs(v-f),b=Math.abs(m-p),_="A"+y+","+b,w=v+y+","+m,A=v+","+(m-b);return"M"+w+_+" 0 1,1 "+A+_+" 0 0,1 "+w+"Z"}function v(t,e,r,n,i){var a="category"===t.type?Number:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var o,s,l,u,c,f=1/0,h=-(1/0),p=n.match(A);for("date"===t.type&&(a=d(a)),o=0;oc&&(f=c),c>h&&(h=c)));return h>=f?[f,h]:void 0}}var m=t("fast-isnumeric"),y=t("../../plotly"),b=t("../../lib"),x=t("../../plots/cartesian/axes"),_=t("../color"),w=t("../drawing"),k=e.exports={};k.layoutAttributes=t("./attributes"),k.supplyLayoutDefaults=function(t,e){for(var r=t.shapes||[],i=e.shapes=[],a=0;as&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),b.log("Ignoring extra params in segment "+t)),i+l})},k.calcAutorange=function(t){var e,r,n,i,a,o=t._fullLayout,s=o.shapes;if(s.length&&t._fullData.length)for(e=0;eh?r=h:(c.left-=b.offsetLeft,c.right-=b.offsetLeft,c.top-=b.offsetTop,c.bottom-=b.offsetTop,b.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(c,t,u)&&(r=Math.max(r,o*(t[b.side]-c[a])+u))}),r=Math.min(h,r)),r>0||0>h){var p={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[b.side];e.attr("transform","translate("+p+")")}}}function d(){E=0,L=!0,S=z,k._infolayer.select("."+e).attr({"data-unformatted":S}).text(S).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)})}var g=r.propContainer,v=r.propName,m=r.traceIndex,y=r.dfltName,b=r.avoid||{},x=r.attributes,_=r.transform,w=r.containerGroup,k=t._fullLayout,A=g.titlefont.family,M=g.titlefont.size,T=g.titlefont.color,E=1,L=!1,S=g.title.trim();""===S&&(E=0),S.match(/Click to enter .+ title/)&&(E=.2,L=!0),w||(w=k._infolayer.selectAll(".g-"+e).data([0]),w.enter().append("g").classed("g-"+e,!0));var C=w.selectAll("text").data([0]);C.enter().append("text"),C.text(S).attr("class",e),C.attr({"data-unformatted":S}).call(f);var z="Click to enter "+y+" title";t._context.editable?(S||d(),C.call(c.makeEditable).on("edit",function(e){void 0!==m?a.restyle(t,v,e,m):a.relayout(t,v,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(f)}).on("input",function(t){this.text(t||" ").attr(x).selectAll("tspan.line").attr(x)})):S&&!S.match(/Click to enter .+ title/)||C.remove(),C.classed("js-placeholder",L)}},{"../../lib":1127,"../../lib/svg_text_utils":1140,"../../plotly":1147,"../../plots/plots":1199,"../color":1048,"../drawing":1071,d3:82,"fast-isnumeric":90}],1112:[function(t,e,r){"use strict";e.exports={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}},{}],1113:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],1114:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],1115:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],1116:[function(t,e,r){"use strict";var n=t("./plotly");r.version="1.13.0",r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.animate=n.animate,r.relayout=n.relayout,r.redraw=n.redraw,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.setPlotConfig=t("./plot_api/set_plot_config"),r.register=n.register,r.toImage=t("./plot_api/to_image"),r.downloadImage=t("./snapshot/download"),r.Icons=t("../build/ploticon"),r.Plots=n.Plots,r.Fx=n.Fx,r.Snapshot=n.Snapshot,r.PlotSchema=n.PlotSchema,r.Queue=n.Queue,r.d3=t("d3")},{"../build/ploticon":2,"./plot_api/set_plot_config":1145,"./plot_api/to_image":1146,"./plotly":1147,"./snapshot/download":1214,d3:82}],1117:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],1118:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){Array.isArray(t)&&(e[r]=t[n])}},{}],1119:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("./nested_property"),o=t("../components/colorscale/get_scale"),s=(Object.keys(t("../components/colorscale/scales")),/^([2-9]|[1-9][0-9]+)$/);r.valObjects={data_array:{coerceFunction:function(t,e,r){Array.isArray(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)}},"boolean":{coerceFunction:function(t,e,r){t===!0||t===!1?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,i){!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if(n.strict===!0&&"string"!=typeof t)return void e.set(r);var i=String(t);void 0===t||n.noBlank===!0&&!i?e.set(r):e.set(i)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?(Math.abs(t)>180&&(t-=360*Math.round(t/360)),e.set(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r){var n=r.length;return"string"==typeof t&&t.substr(0,n)===r&&s.test(t.substr(n))?void e.set(t):void e.set(r)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"!=typeof t)return void e.set(r);if(-1!==n.extras.indexOf(t))return void e.set(t);for(var i=t.split("+"),a=0;a2)return!1;var l=o[0].split("-");if(l.length>3||3!==l.length&&o[1])return!1;if(4===l[0].length)r=Number(l[0]);else{if(2!==l[0].length)return!1;var u=(new Date).getFullYear();r=((Number(l[0])-u+70)%100+200)%100+u-70}return s(r)?1===l.length?new Date(r,0,1).getTime():(n=Number(l[1])-1,l[1].length>2||!(n>=0&&11>=n)?!1:2===l.length?new Date(r,n,1).getTime():(i=Number(l[2]),l[2].length>2||!(i>=1&&31>=i)?!1:(i=new Date(r,n,i).getTime(),o[1]?(l=o[1].split(":"),l.length>3?!1:(a=Number(l[0]),l[0].length>2||!(a>=0&&23>=a)?!1:(i+=36e5*a,1===l.length?i:(n=Number(l[1]),l[1].length>2||!(n>=0&&59>=n)?!1:(i+=6e4*n,2===l.length?i:(t=Number(l[2]),t>=0&&60>t?i+1e3*t:!1)))))):i))):!1},r.isDateTime=function(t){return r.dateTime2ms(t)!==!1},r.ms2DateTime=function(t,e){if("undefined"==typeof o)return void l.error("d3 is not defined.");e||(e=0);var r=new Date(t),i=o.time.format("%Y-%m-%d")(r);return 7776e6>e?(i+=" "+n(r.getHours(),2),432e6>e&&(i+=":"+n(r.getMinutes(),2),108e5>e&&(i+=":"+n(r.getSeconds(),2),3e5>e&&(i+="."+n(r.getMilliseconds(),3)))),i.replace(/([:\s]00)*\.?[0]*$/,"")):i};var u={H:["%H:%M:%S~%L","%H:%M:%S","%H:%M"],I:["%I:%M:%S~%L%p","%I:%M:%S%p","%I:%M%p"],D:["%H","%I%p","%Hh"]},c={Y:["%Y~%m~%d","%Y%m%d","%y%m%d","%m~%d~%Y","%d~%m~%Y"],Yb:["%b~%d~%Y","%d~%b~%Y","%Y~%d~%b","%Y~%b~%d"],y:["%m~%d~%y","%d~%m~%y","%y~%m~%d"],yb:["%b~%d~%y","%d~%b~%y","%y~%d~%b","%y~%b~%d"]},f=o.time.format.utc,h={Y:{H:["%Y~%m~%dT%H:%M:%S","%Y~%m~%dT%H:%M:%S~%L"].map(f),I:[],D:["%Y%m%d%H%M%S","%Y~%m","%m~%Y"].map(f)},Yb:{H:[],I:[],D:["%Y~%b","%b~%Y"].map(f)},y:{H:[],I:[],D:[]},yb:{H:[],I:[],D:[]}};["Y","Yb","y","yb"].forEach(function(t){c[t].forEach(function(e){h[t].D.push(f(e)),["H","I","D"].forEach(function(r){u[r].forEach(function(n){var i=h[t][r];i.push(f(e+"~"+n)),i.push(f(n+"~"+e))})})})});var p=/[a-z]*/g,d=function(t){return t.substr(0,3)},g=/(mon|tue|wed|thu|fri|sat|sun|the|of|st|nd|rd|th)/g,v=/[\s,\/\-\.\(\)]+/g,m=/~?([ap])~?m(~|$)/,y=function(t,e){return e+"m "},b=/\d\d\d\d/,x=/(^|~)[a-z]{3}/,_=/[ap]m/,w=/:/,k=/q([1-4])/,A=["31~mar","30~jun","30~sep","31~dec"],M=function(t,e){return A[e-1]},T=/ ?([+\-]\d\d:?\d\d|Z)$/;r.parseDate=function(t){if(t.getTime)return t;if("string"!=typeof t)return!1;t=t.toLowerCase().replace(p,d).replace(g,"").replace(v,"~").replace(m,y).replace(k,M).trim().replace(T,"");var e,r,n=null,o=i(t),s=a(t);e=h[o][s],r=e.length;for(var l=0;r>l&&!(n=e[l].parse(t));l++);if(!(n instanceof Date))return!1;var u=n.getTimezoneOffset();return n.setTime(n.getTime()+60*u*1e3),n}},{"../lib":1127,d3:82,"fast-isnumeric":90}],1121:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i={init:function(t){if(t._ev instanceof n)return t;var e=new n;return t._ev=e,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t.emit=function(r,n){"undefined"!=typeof jQuery&&jQuery(t).trigger(r,n),e.emit(r,n)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;ld;d++){o=t[d];for(s in o)l=h[s],u=o[s],e&&u&&(i(u)||(c=a(u)))?(c?(c=!1,f=l&&a(l)?l:[]):f=l&&i(l)?l:{},h[s]=n([f,u],e,r)):("undefined"!=typeof u||r)&&(h[s]=u)}return h}var i=t("./is_plain_object.js"),a=Array.isArray;r.extendFlat=function(){return n(arguments,!1,!1)},r.extendDeep=function(){return n(arguments,!0,!1)},r.extendDeepAll=function(){return n(arguments,!0,!0)}},{"./is_plain_object.js":1128}],1123:[function(t,e,r){"use strict";e.exports=function(t){for(var e=[],r=0;ry;y++)f=s(d,y),p=l(e,y),m[y]=n(f,p);else m=n(d,e);return m}var s=t("tinycolor2"),l=t("fast-isnumeric"),u=t("../components/colorscale/make_scale_function"),c=t("../components/color/attributes").defaultLine,f=t("./str2rgbarray"),h=1;e.exports=o},{"../components/color/attributes":1047,"../components/colorscale/make_scale_function":1065,"./str2rgbarray":1139,"fast-isnumeric":90,tinycolor2:1042}],1126:[function(t,e,r){"use strict";function n(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(e>r)break;t=t.slice(0,e)+l(t.slice(e+5,r))+t.slice(r+6)}return t}function i(t){return t.replace(/\/g,"\n")}function a(t){return t.replace(/\<.*\>/g,"")}function o(t){for(var e=0;(e=t.indexOf("&",e))>=0;){var r=t.indexOf(";",e);if(e>r)e+=1;else{var n=u[t.slice(e+1,r)];t=n?t.slice(0,e)+n+t.slice(r+1):t.slice(0,e)+t.slice(r+1)}}return t}function s(t){return""+o(a(n(i(t))))}var l=t("superscript-text"),u={mu:"\u03bc",amp:"&",lt:"<",gt:">"};e.exports=s},{"superscript-text":1041}],1127:[function(t,e,r){"use strict";var n=t("d3"),i=e.exports={};i.nestedProperty=t("./nested_property"),i.isPlainObject=t("./is_plain_object");var a=t("./coerce");i.valObjects=a.valObjects,i.coerce=a.coerce,i.coerce2=a.coerce2,i.coerceFont=a.coerceFont;var o=t("./dates");i.dateTime2ms=o.dateTime2ms,i.isDateTime=o.isDateTime,i.ms2DateTime=o.ms2DateTime,i.parseDate=o.parseDate;var s=t("./search");i.findBin=s.findBin,i.sorterAsc=s.sorterAsc,i.sorterDes=s.sorterDes,i.distinctVals=s.distinctVals,i.roundUp=s.roundUp;var l=t("./stats");i.aggNums=l.aggNums,i.len=l.len,i.mean=l.mean,i.variance=l.variance,i.stdev=l.stdev,i.interp=l.interp;var u=t("./matrix");i.init2dArray=u.init2dArray,i.transposeRagged=u.transposeRagged,i.dot=u.dot,i.translationMatrix=u.translationMatrix,i.rotationMatrix=u.rotationMatrix,i.rotationXYMatrix=u.rotationXYMatrix,i.apply2DTransform=u.apply2DTransform,i.apply2DTransform2=u.apply2DTransform2;var c=t("./extend");i.extendFlat=c.extendFlat,i.extendDeep=c.extendDeep,i.extendDeepAll=c.extendDeepAll;var f=t("./loggers");i.log=f.log,i.warn=f.warn,i.error=f.error,i.notifier=t("./notifier"),i.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},i.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},i.identity=function(t){return t},i.randstr=function h(t,e,r){if(r||(r=16),void 0===e&&(e=24),0>=e)return"0";var n,i,a,o=Math.log(Math.pow(2,e))/Math.log(r),s="";for(n=2;o===1/0;n*=2)o=Math.log(Math.pow(2,e/n))/Math.log(r)*n;var l=o-Math.floor(o);for(n=0;n-1||u!==1/0&&u>=Math.pow(2,e)?h(t,e,r):s},i.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={};return r.optionList=[],r._newoption=function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)},r["_"+e]=t,r},i.smooth=function(t,e){if(e=Math.round(e)||0,2>e)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;l>r;r++)u[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;o>r;r++){for(a=0,n=0;l>n;n++)i=r+n+1-e,-o>i?i-=s*Math.round(i/s):i>=s&&(i-=s*Math.floor(i/s)),0>i?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},i.syncOrAsync=function(t,e,r){function n(){return i.syncOrAsync(t,e,r)}for(var a,o;t.length;)if(o=t.splice(0,1)[0],a=o(e),a&&a.then)return a.then(n).then(void 0,i.promiseError);return r&&r(e)},i.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},i.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;ni;i++)e[i][r]=t[i]},i.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,o,s=3,l=Object.keys(t);for(n=0;n1?n+a[1]:"";if(i&&(a.length>1||o.length>4))for(;r.test(o);)o=o.replace(r,"$1"+i+"$2");return o+s},i.deepClone=function p(t,e,r){var n,i,a="__getDeepCircularCopy__";if(t!==Object(t))return t;var o,s=a in t,l=t[a];if(s&&"function"==typeof l)return l();if(t[a]=function(){return o},t instanceof Array){o=[];for(var u=0;u1){for(var t=["LOG:"],e=0;e0){for(var t=["WARN:"],e=0;e0){for(var t=["ERROR:"],e=0;en;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,i=t.length;for(e=0;i>e;e++)n=Math.max(n,t[e].length);var a=new Array(n);for(e=0;n>e;e++)for(a[e]=new Array(i),r=0;i>r;r++)a[e][r]=t[r][e];return a},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,i,a=t.length;if(t[0].length)for(n=new Array(a),i=0;a>i;i++)n[i]=r.dot(t[i],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),i=0;ii;i++)n+=t[i]*e[i];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],1131:[function(t,e,r){"use strict";function n(t,e){return function(){var r,i,a,o,s,l=t;for(o=0;o=0;e--){ -if(n=t[e],o=!1,Array.isArray(n))for(r=n.length-1;r>=0;r--)u(n[r])?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)u(n[a[r]])&&!i(n[a[r]],a[r])?delete n[a[r]]:o=!0;if(o)return}}function u(t){return void 0===t||null===t?!0:"object"!=typeof t?!1:Array.isArray(t)?!t.length:!Object.keys(t).length}function c(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}var f=t("fast-isnumeric");e.exports=function(t,e){if(f(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,l=e.split(".");sr||r>a||o>n||n>s?!1:!e||!u(t)}function r(t,e){var r=t[0],l=t[1];if(i>r||r>a||o>l||l>s)return!1;var u,c,f,h,p,d=n.length,g=n[0][0],v=n[0][1],m=0;for(u=1;d>u;u++)if(c=g,f=v,g=n[u][0],v=n[u][1],h=Math.min(c,g),!(h>r||r>Math.max(c,g)||l>Math.max(f,v)))if(l=l&&r!==h&&m++}return m%2===1}var n=t.slice(),i=n[0][0],a=i,o=n[0][1],s=o;n.push(n[0]);for(var l=1;la;a++)if(o=[t[a][0]-l[0],t[a][1]-l[1]],s=n(o,u),0>s||s>c||Math.abs(n(o,h))>i)return!0;return!1};i.filter=function(t,e){function r(r){t.push(r);var s=n.length,l=i;n.splice(o+1);for(var u=l+1;u1){var s=t.pop();r(s)}return{addPt:r,raw:t,filtered:n}}},{"./matrix":1130}],1134:[function(t,e,r){"use strict";function n(t,e){for(var r,n=[],a=0;a=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;rt}function i(t,e){return e>=t}function a(t,e){return t>e}function o(t,e){return t>=e}var s=t("fast-isnumeric"),l=t("../lib");r.findBin=function(t,e,r){if(s(e.start))return r?Math.ceil((t-e.start)/e.size)-1:Math.floor((t-e.start)/e.size);var u,c,f=0,h=e.length,p=0;for(c=e[e.length-1]>=e[0]?r?n:i:r?o:a;h>f&&p++<100;)u=Math.floor((f+h)/2),c(e[u],t)?f=u+1:h=u;return p>90&&l.log("Long binary search..."),f-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;n>s;s++)e[s+1]>e[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;a>i&&o++<100;)n=u((i+a)/2),e[n]<=t?i=n+s:a=n-l;return e[i]}},{"../lib":1127,"fast-isnumeric":90}],1136:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],1137:[function(t,e,r){"use strict";var n=t("../components/color"),i=function(){};e.exports=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=i);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=n.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1}},{"../components/color":1048}],1138:[function(t,e,r){"use strict";var n=t("fast-isnumeric");r.aggNums=function(t,e,i,a){var o,s;if(a||(a=i.length),n(e)||(e=!1),Array.isArray(i[0])){for(s=new Array(a),o=0;a>o;o++)s[o]=r.aggNums(t,e,i[o]);i=s}for(o=0;a>o;o++)n(e)?n(i[o])&&(e=t(+e,+i[o])):e=i[o];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.variance=function(t,e,i){return e||(e=r.len(t)),n(i)||(i=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-i,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if(e=e*t.length-.5,0>e)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"fast-isnumeric":90}],1139:[function(t,e,r){"use strict";function n(t){return t=i(t),a.str2RgbaArray(t.toRgbString())}var i=t("tinycolor2"),a=t("arraytools");e.exports=n},{arraytools:64,tinycolor2:1042}],1140:[function(t,e,r){"use strict";function n(t,e){return t.node().getBoundingClientRect()[e]}function i(t){return t.replace(/(<|<|<)/g,"\\lt ").replace(/(>|>|>)/g,"\\gt ")}function a(t,e,r){var n="math-output-"+l.Lib.randstr([],64),a=u.select("body").append("div").attr({id:n}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text(i(t));MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var e=u.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())c.log("There was an error in the tex syntax.",t),r();else{var n=a.select("svg").node().getBoundingClientRect();r(a.select(".MathJax_SVG"),e,n)}a.remove()})}function o(t){for(var e=l.util.html_entity_decode(t),r=e.split(/(<[^<>]*>)/).map(function(t){var e=t.match(/<(\/?)([^ >]*)\s*(.*)>/i),r=e&&e[2].toLowerCase(),n=p[r];if(void 0!==n){var i=e[1],a=e[3],o=a.match(/^style\s*=\s*"([^"]+)"\s*/i);if("a"===r){if(i)return"";if("href"!==a.substr(0,4).toLowerCase())return"";var s=document.createElement("a");return s.href=a.substr(4).replace(/["'=]/g,""),-1===d.indexOf(s.protocol)?"":'"}if("br"===r)return"
";if(i)return"sup"===r?'':"sub"===r?'':"";var u=""}return l.util.xml_entity_encode(t).replace(/");i>0;i=r.indexOf("
",i+1))n.push(i);var a=0;n.forEach(function(t){for(var e=t+a,n=r.slice(0,e),i="",o=n.length-1;o>=0;o--){var s=n[o].match(/<(\/?).*>/i);if(s&&"
"!==n[o]){s[1]||(i=n[o]);break}}i&&(r.splice(e+1,0,i),r.splice(e,0,""),a+=2)});var o=r.join(""),s=o.split(/
/gi);return s.length>1&&(r=s.map(function(t,e){return''+t+""})),r.join("")}function s(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}var l=t("../plotly"),u=t("d3"),c=t("../lib"),f=t("../constants/xmlns_namespaces"),h=e.exports={};u.selection.prototype.appendSVG=function(t){for(var e=['',t,""].join(""),r=(new DOMParser).parseFromString(e,"application/xml"),n=r.documentElement.firstChild;n;)this.node().appendChild(this.node().ownerDocument.importNode(n,!0)),n=n.nextSibling;return r.querySelector("parsererror")?(c.log(r.querySelector("parsererror div").textContent),null):u.select(this.node().lastChild)},h.html_entity_decode=function(t){var e=u.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"<"===t?"<":"&rt;"===t?">":e.html(t).text()});return e.remove(),r},h.xml_entity_encode=function(t){return t.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")},h.convertToTspans=function(t,e){function r(){p.empty()||(d=c.attr("class")+"-math",p.select("svg."+d).remove()),t.text("").style({visibility:"visible","white-space":"pre"}),h=t.appendSVG(s),h||t.text(i),t.select("a").size()&&t.style("pointer-events","all"),e&&e.call(c)}var i=t.text(),s=o(i),c=t,f=!c.attr("data-notex")&&s.match(/([^$]*)([$]+[^$]*[$]+)([^$]*)/),h=i,p=u.select(c.node().parentNode);if(!p.empty()){var d=c.attr("class")?c.attr("class").split(" ")[0]:"text";d+="-math",p.selectAll("svg."+d).remove(),p.selectAll("g."+d+"-group").remove(),t.style({visibility:null});for(var g=t.node();g&&g.removeAttribute;g=g.parentNode)g.removeAttribute("data-bb");if(f){var v=l.Lib.getPlotDiv(c.node());(v&&v._promises||[]).push(new Promise(function(t){c.style({visibility:"hidden"});var i={fontSize:parseInt(c.style("font-size"),10)};a(f[2],i,function(i,a,o){p.selectAll("svg."+d).remove(),p.selectAll("g."+d+"-group").remove();var s=i&&i.select("svg");if(!s||!s.node())return r(),void t();var l=p.append("g").classed(d+"-group",!0).attr({"pointer-events":"none"});l.node().appendChild(s.node()),a&&a.node()&&s.node().insertBefore(a.node().cloneNode(!0),s.node().firstChild),s.attr({"class":d,height:o.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var u=c.style("fill")||"black";s.select("g").attr({fill:u,stroke:u});var f=n(s,"width"),h=n(s,"height"),g=+c.attr("x")-f*{start:0,middle:.5,end:1}[c.attr("text-anchor")||"start"],v=parseInt(c.style("font-size"),10)||n(c,"height"),m=-v/4;"y"===d[0]?(l.attr({transform:"rotate("+[-90,+c.attr("x"),+c.attr("y")]+") translate("+[-f/2,m-h/2]+")"}),s.attr({x:+c.attr("x"),y:+c.attr("y")})):"l"===d[0]?s.attr({x:c.attr("x"),y:m-h/2}):"a"===d[0]?s.attr({x:0,y:m}):s.attr({x:g,y:+c.attr("y")+m-h/2}),e&&e.call(c,l),t(l)})}))}else r();return t}};var p={sup:'font-size:70%" dy="-0.6em',sub:'font-size:70%" dy="0.3em',b:"font-weight:bold",i:"font-style:italic",a:"",span:"",br:"",em:"font-style:italic;font-weight:bold"},d=["http:","https:","mailto:"],g=new RegExp("]*)?/?>","g");h.plainText=function(t){return(t||"").replace(g," ")},h.makeEditable=function(t,e,r){function n(){a(),o.style({opacity:0});var t,e=h.attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&u.select(o.node().parentNode).select(t).style({opacity:0})}function i(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}function a(){var t=u.select(l.Lib.getPlotDiv(o.node())),e=t.select(".svg-container"),n=e.append("div");n.classed("plugin-editable editable",!0).style({position:"absolute","font-family":o.style("font-family")||"Arial","font-size":o.style("font-size")||12,color:r.fill||o.style("fill")||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-parseFloat(o.style("font-size"))/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||o.attr("data-unformatted")).call(s(o,e,r)).on("blur",function(){o.text(this.textContent).style({opacity:1});var t,e=u.select(this).attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&u.select(o.node().parentNode).select(t).style({opacity:0});var r=this.textContent;u.select(this).transition().duration(0).remove(),u.select(document).on("mouseup",null),c.edit.call(o,r)}).on("focus",function(){var t=this;u.select(document).on("mouseup",function(){return u.event.target===t?!1:void(document.activeElement===n.node()&&n.node().blur())})}).on("keyup",function(){27===u.event.which?(o.style({opacity:1}),u.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),c.cancel.call(o,this.textContent)):(c.input.call(o,this.textContent),u.select(this).call(s(o,e,r)))}).on("keydown",function(){13===u.event.which&&this.blur()}).call(i)}r||(r={});var o=this,c=u.dispatch("edit","input","cancel"),f=u.select(this.node()).style({"pointer-events":"all"}),h=e||f;return e&&f.style({"pointer-events":"none"}),r.immediate?n():h.on("click",n),u.rebind(this,c,"on")}},{"../constants/xmlns_namespaces":1115,"../lib":1127,"../plotly":1147,d3:82}],1141:[function(t,e,r){"use strict";var n=e.exports={},i=t("../plots/geo/constants").locationmodeToLayer,a=t("topojson").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../plots/geo/constants":1169,topojson:1043}],1142:[function(t,e,r){"use strict";function n(t){var e;if("string"==typeof t){if(e=document.getElementById(t),null===e)throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t}function i(t,e){t._fullLayout._paperdiv.style("background","white"),R.defaultConfig.setBackground(t,e)}function a(t,e){t._context||(t._context=j.extendFlat({},R.defaultConfig));var r=t._context;e&&(Object.keys(e).forEach(function(t){t in r&&("setBackground"===t&&"opaque"===e[t]?r[t]=i:r[t]=e[t])}),e.plot3dPixelRatio&&!r.plotGlPixelRatio&&(r.plotGlPixelRatio=r.plot3dPixelRatio)),r.staticPlot&&(r.editable=!1,r.autosizable=!1,r.scrollZoom=!1,r.doubleClick=!1,r.showTips=!1,r.showLink=!1,r.displayModeBar=!1)}function o(t,e,r){var n=C.select(t).selectAll(".plot-container").data([0]);n.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=n.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e),r&&(t.layout=r),R.micropolar.manager.fillLayout(t),"initial"===t._fullLayout.autosize&&t._context.autosizable&&(w(t,{}),t._fullLayout.autosize=r.autosize=!0),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=R.micropolar.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var a=t.framework.svg(),o=1,s=t._fullLayout.title;""!==s&&s||(o=0);var l="Click to enter title",u=function(){this.call(R.util.convertToTspans)},c=a.select(".title-group text").call(u);if(t._context.editable){c.attr({"data-unformatted":s}),s&&s!==l||(o=.2,c.attr({"data-unformatted":l}).text(l).style({opacity:o}).on("mouseover.opacity",function(){C.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){C.select(this).transition().duration(1e3).style("opacity",0)}));var f=function(){this.call(R.util.makeEditable).on("edit",function(e){t.framework({layout:{title:e}}),this.attr({"data-unformatted":e}).text(e).call(u),this.call(f)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(u)})};c.call(f)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),N.addLinks(t),Promise.resolve()}function s(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1);var n=R.Axes.list({_fullLayout:t});for(e=0;ee;e++){var o=t.annotations[e];o.ref&&("paper"===o.ref?(o.xref="paper",o.yref="paper"):"data"===o.ref&&(o.xref="x",o.yref="y"),delete o.ref),l(o,"xref"),l(o,"yref")}void 0===t.shapes||Array.isArray(t.shapes)||(j.warn("Shapes must be an array."),delete t.shapes);var s=(t.shapes||[]).length;for(e=0;s>e;e++){var u=t.shapes[e];l(u,"xref"),l(u,"yref")}var c=t.legend;c&&(c.x>3?(c.x=1.02,c.xanchor="left"):c.x<-2&&(c.x=-.02,c.xanchor="right"),c.y>3?(c.y=1.02,c.yanchor="bottom"):c.y<-2&&(c.y=-.02,c.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var h=N.getSubplotIds(t,"gl3d");for(e=0;er;++r)b[r]=v[e]+m*y[2+4*r];p.camera={eye:{x:b[0],y:b[1],z:b[2]},center:{x:v[0],y:v[1],z:v[2]},up:{x:y[1],y:y[5],z:y[9]}},delete p.cameraposition}}return D.clean(t),t}function l(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=R.Axes.cleanId(r,n))}function u(t,e){for(var r=[],n=(t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid})),i=0;ia&&(s=j.randstr(n),-1!==r.indexOf(s));a++);o.uid=j.randstr(n),n.push(o.uid)}if(r.push(o.uid),"histogramy"===o.type&&"xbins"in o&&!("ybins"in o)&&(o.ybins=o.xbins,delete o.xbins),o.error_y&&"opacity"in o.error_y){var l=D.defaults,u=o.error_y.color||(N.traceIs(o,"bar")?D.defaultLine:l[i%l.length]);o.error_y.color=D.addOpacity(D.rgb(u),D.opacity(u)*o.error_y.opacity),delete o.error_y.opacity}if("bardir"in o&&("h"!==o.bardir||!N.traceIs(o,"bar")&&"histogram"!==o.type.substr(0,9)||(o.orientation="h",x(o)),delete o.bardir),"histogramy"===o.type&&x(o),"histogramx"!==o.type&&"histogramy"!==o.type||(o.type="histogram"),"scl"in o&&(o.colorscale=o.scl,delete o.scl),"reversescl"in o&&(o.reversescale=o.reversescl,delete o.reversescl),o.xaxis&&(o.xaxis=R.Axes.cleanId(o.xaxis,"x")),o.yaxis&&(o.yaxis=R.Axes.cleanId(o.yaxis,"y")),N.traceIs(o,"gl3d")&&o.scene&&(o.scene=N.subplotsRegistry.gl3d.cleanId(o.scene)),N.traceIs(o,"pie")||(Array.isArray(o.textposition)?o.textposition=o.textposition.map(c):o.textposition&&(o.textposition=c(o.textposition))),N.traceIs(o,"2dMap")&&("YIGnBu"===o.colorscale&&(o.colorscale="YlGnBu"),"YIOrRd"===o.colorscale&&(o.colorscale="YlOrRd")),N.traceIs(o,"markerColorscale")&&o.marker){var h=o.marker;"YIGnBu"===h.colorscale&&(h.colorscale="YlGnBu"),"YIOrRd"===h.colorscale&&(h.colorscale="YlOrRd")}if("surface"===o.type&&j.isPlainObject(o.contours)){var p=["x","y","z"];for(a=0;an?a.push(i+n):a.push(n);return a}function d(t,e,r){var n,i;for(n=0;n=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||0>i&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function g(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),d(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&d(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function v(t,e,r){var n,i;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n=0&&l0){var s=_(t._boundingBoxMargins),l=s.left+s.right,u=s.bottom+s.top,c=a._container.node().getBoundingClientRect(),f=1-2*o.frameMargins;i=Math.round(f*(c.width-l)),n=Math.round(f*(c.height-u))}else r=window.getComputedStyle(t),n=parseFloat(r.height)||a.height,i=parseFloat(r.width)||a.width;return Math.abs(a.width-i)>1||Math.abs(a.height-n)>1?(a.height=t.layout.height=n,a.width=t.layout.width=i):"initial"!==a.autosize&&(delete e.autosize,a.autosize=t.layout.autosize=!0),N.sanitizeMargins(a),e}function k(t){var e=C.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),"initial"===r.autosize&&(w(t,{}),r.autosize=!0,t.layout.autosize=!0),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([0]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._geocontainer=r._paperdiv.selectAll(".geo-container").data([0]),r._geocontainer.enter().append("div").classed("geo-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var n=[];C.selectAll("defs").each(function(){this.id&&n.push(this.id.split("-")[1])}),r._uid=j.randstr(n)}r._paperdiv.selectAll(".main-svg").attr(Z.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=i.append("g").classed("imagelayer",!0),r._shapeLowerLayer=i.append("g").classed("shapelayer",!0);var a=R.Axes.getSubplots(t);a.join("")!==Object.keys(t._fullLayout._plots||{}).join("")&&A(t,a),r._has("cartesian")&&M(t,a),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0);var o=r._paper.selectAll(".layer-subplot");r._imageSubplotLayer=o.selectAll(".imagelayer"),r._shapeSubplotLayer=o.selectAll(".shapelayer");var s=r._paper.append("g").classed("layer-above",!0);r._imageUpperLayer=s.append("g").classed("imagelayer",!0),r._shapeUpperLayer=s.append("g").classed("shapelayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0),r._geoimages=r._paper.append("g").classed("geoimages",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework");var l=j.syncOrAsync([T,function(){return R.Axes.doTicks(t,"redraw")},F.init],t);return l&&l.then&&t._promises.push(l),l}function A(t,e){function r(e,r){return function(){return R.Axes.getFromId(t,e,r)}}for(var n,i,a=t._fullLayout._plots={},o=0;o=0;e--)t.data[e][i]||(r=t._fullData[e].type,n=R.PlotSchema.get().traces[r],t.data[e]=j.deepCloneTrace(t.data[e],n),t.data[e][i]=!0)}var C=t("d3"),z=t("gl-mat4/fromQuat"),P=t("fast-isnumeric"),R=t("../plotly"),j=t("../lib"),O=t("../lib/events"),I=t("../lib/queue"),N=t("../plots/plots"),F=t("../plots/cartesian/graph_interact"),D=t("../components/color"),B=t("../components/drawing"),U=t("../components/errorbars"),V=t("../components/images"),q=t("../components/legend"),G=t("../components/rangeslider"),H=t("../components/rangeselector"),Y=t("../components/shapes"),X=t("../components/titles"),W=t("../components/modebar/manage"),Z=t("../constants/xmlns_namespaces");R.plot=function(t,e,r,i){function l(){var e,r,n,i=t.calcdata;for(q.draw(t),H.draw(t),e=0;e0,_=R.Axes.getSubplots(t).join(""),w=Object.keys(t._fullLayout._plots||{}).join(""),A=w===_;x?t.framework===k&&!b&&A||(t.framework=k,k(t)):A?b&&k(t):(t.framework=k,k(t)),b&&R.Axes.saveRangeInitial(t);var M=t._fullLayout,E=!t.calcdata||t.calcdata.length!==(t.data||[]).length;E&&h(t);for(var L=0;LY.range[0]?[1,2]:[2,1]);else{var X=Y.range[0],Z=Y.range[1];"log"===P?(0>=X&&0>=Z&&i(U+".autorange",!0),0>=X?X=Z/1e6:0>=Z&&(Z=X/1e6),i(U+".range[0]",Math.log(X)/Math.LN10),i(U+".range[1]",Math.log(Z)/Math.LN10)):(i(U+".range[0]",Math.pow(10,X)),i(U+".range[1]",Math.pow(10,Z)))}else i(U+".autorange",!0)}if("reverse"===D)G.range?G.range.reverse():(i(U+".autorange",!0),G.range=[1,0]),H.autorange?_=!0:x=!0;else if("annotations"===z.parts[0]||"shapes"===z.parts[0]){var K=z.parts[1],$=z.parts[0],Q=d[$]||[],J=R[j.titleCase($)],tt=Q[K]||{};2===z.parts.length&&("add"===v[C]||j.isPlainObject(v[C])?E[C]="remove":"remove"===v[C]?-1===K?(E[$]=Q,delete E[C]):E[C]=tt:j.log("???",v)),!a(tt,"x")&&!a(tt,"y")||j.containsAny(C,["color","opacity","align","dash"])||(_=!0),J.draw(t,K,z.parts.slice(2).join("."),v[C]),delete v[C]}else if("images"===z.parts[0]){var et=j.objectFromPath(C,P);j.extendDeepAll(t.layout,et),V.supplyLayoutDefaults(t.layout,t._fullLayout),V.draw(t)}else if("mapbox"===z.parts[0]&&"layers"===z.parts[1]){j.extendDeepAll(t.layout,j.objectFromPath(C,P));var nt=(t._fullLayout.mapbox||{}).layers||[],it=z.parts[2]+1-nt.length;for(p=0;it>p;p++)nt.push({});x=!0}else 0===z.parts[0].indexOf("scene")?x=!0:0===z.parts[0].indexOf("geo")?x=!0:0===z.parts[0].indexOf("ternary")?x=!0:!g._has("gl2d")||-1===C.indexOf("axis")&&"plot_bgcolor"!==z.parts[0]?"hiddenlabels"===C?_=!0:-1!==z.parts[0].indexOf("legend")?m=!0:-1!==C.indexOf("title")?y=!0:-1!==z.parts[0].indexOf("bgcolor")?b=!0:z.parts.length>1&&j.containsAny(z.parts[1],["tick","exponent","grid","zeroline"])?y=!0:-1!==C.indexOf(".linewidth")&&-1!==C.indexOf("axis")?y=b=!0:z.parts.length>1&&-1!==z.parts[1].indexOf("line")?b=!0:z.parts.length>1&&"mirror"===z.parts[1]?y=b=!0:"margin.pad"===C?y=b=!0:"margin"===z.parts[0]||"autorange"===z.parts[1]||"rangemode"===z.parts[1]||"type"===z.parts[1]||"domain"===z.parts[1]||C.match(/^(bar|box|font)/)?_=!0:-1!==["hovermode","dragmode"].indexOf(C)?k=!0:-1===["hovermode","dragmode","height","width","autosize"].indexOf(C)&&(x=!0):x=!0,z.set(P)}I&&I.add(t,rt,[t,E],rt,[t,M]),v.autosize&&(v=w(t,v)),(v.height||v.width||v.autosize)&&(_=!0);var at=Object.keys(v),ot=[N.previousPromises];if(x||_)ot.push(function(){return t.layout=void 0,_&&(t.calcdata=void 0),R.plot(t,"",d)});else if(at.length&&(N.supplyDefaults(t),g=t._fullLayout,m&&ot.push(function(){return q.draw(t),N.previousPromises(t)}),b&&ot.push(T),y&&ot.push(function(){return R.Axes.doTicks(t,"redraw"),L(t),N.previousPromises(t)}),k)){var st;for(W(t),st=N.getSubplotIds(g,"gl3d"),p=0;p1)};u(r.width)&&u(r.height)||s(new Error("Height and width should be pixel values."));var c=n.clone(e,{format:"png",height:r.height,width:r.width}),f=c.td;f.style.position="absolute",f.style.left="-5000px",document.body.appendChild(f);var h=n.getRedrawFunc(f);a.plot(f,c.data,c.layout,c.config).then(h).then(l).then(function(e){t(e)}).catch(function(t){s(t)})});return s}var i=t("fast-isnumeric"),a=t("../plotly"),o=t("../lib");e.exports=n},{"../lib":1127,"../plotly":1147,"../snapshot":1216,"fast-isnumeric":90}],1147:[function(t,e,r){"use strict";t("es6-promise").polyfill(),r.Lib=t("./lib"),r.util=t("./lib/svg_text_utils"),r.Queue=t("./lib/queue"),t("../build/plotcss"),r.MathJaxConfig=t("./fonts/mathjax_config"),r.defaultConfig=t("./plot_api/plot_config");var n=r.Plots=t("./plots/plots");r.Axes=t("./plots/cartesian/axes"),r.Fx=t("./plots/cartesian/graph_interact"),r.micropolar=t("./plots/polar/micropolar"),r.Color=t("./components/color"),r.Drawing=t("./components/drawing"),r.Colorscale=t("./components/colorscale"),r.Colorbar=t("./components/colorbar"),r.ErrorBars=t("./components/errorbars"),r.Annotations=t("./components/annotations"),r.Shapes=t("./components/shapes"),r.Legend=t("./components/legend"),r.Images=t("./components/images"),r.ModeBar=t("./components/modebar"),r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;eu&&c>e&&(void 0===i[r]?a[f]=T.tickText(t,e):a[f]=s(t,e,String(i[r])),f++);return f=864e5?t._tickround="d":r>=36e5?t._tickround="H":r>=6e4?t._tickround="M":r>=1e3?t._tickround="S":t._tickround=3-Math.round(Math.log(r/2)/Math.LN10);else{b(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01),e="log"===t.type?Math.pow(10,Math.max(t.range[0],t.range[1])):Math.max(Math.abs(t.range[0]),Math.abs(t.range[1]));var n=Math.floor(Math.log(e)/Math.LN10+.01);Math.abs(n)>3&&("SI"===t.exponentformat||"B"===t.exponentformat?t._tickexponent=3*Math.round((n-1)/3):t._tickexponent=n); -}else"M"===r.charAt(0)?t._tickround=2===r.length?"m":"y":t._tickround=null}function o(t,e){var r=t.match(U),n=new Date(e);if(r){var i=Math.min(+r[1]||6,6),a=String(e/1e3%1+2.0000005).substr(2,i).replace(/0+$/,"")||"0";return y.time.format(t.replace(U,a))(n)}return y.time.format(t)(n)}function s(t,e,r){var n=t.tickfont||t._gd._fullLayout.font;return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}function l(t,e,r,n){var i,a=e.x,s=t._tickround,l=new Date(a),u="";r&&t.hoverformat?i=o(t.hoverformat,a):t.tickformat?i=o(t.tickformat,a):(n&&(b(s)?s+=2:s={y:"m",m:"d",d:"H",H:"M",M:"S",S:2}[s]),"y"===s?i=O(l):"m"===s?i=I(l):(a!==t._tmin||r||(u="
"+O(l)),"d"===s?i=N(l):"H"===s?i=F(l):(a!==t._tmin||r||(u="
"+N(l)+", "+O(l)),i=D(l),"M"!==s&&(i+=B(l),"S"!==s&&(i+=h(m(a/1e3,1),t,"none",r).substr(1)))))),e.text=i+u}function u(t,e,r,n,i){var a=t.dtick,o=e.x;if(!n||"string"==typeof a&&"L"===a.charAt(0)||(a="L3"),t.tickformat||"string"==typeof a&&"L"===a.charAt(0))e.text=h(Math.pow(10,o),t,i,n);else if(b(a)||"D"===a.charAt(0)&&m(o+.01,1)<.1)if(-1!==["e","E","power"].indexOf(t.exponentformat)){var s=Math.round(o);0===s?e.text=1:1===s?e.text="10":s>1?e.text="10"+s+"":e.text="10\u2212"+-s+"",e.fontSize*=1.25}else e.text=h(Math.pow(10,o),t,"","fakehover"),"D1"===a&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6);else{if("D"!==a.charAt(0))throw"unrecognized dtick "+String(a);e.text=String(Math.round(Math.pow(10,m(o,1)))),e.fontSize*=.75}if("D1"===t.dtick){var l=String(e.text).charAt(0);"0"!==l&&"1"!==l||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(0>o?.5:.25)))}}function c(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r=""),e.text=String(r)}function f(t,e,r,n,i){"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide"),e.text=h(e.x,t,i,n)}function h(t,e,r,n){var i=0>t,o=e._tickround,s=r||e.exponentformat||"B",l=e._tickexponent,u=e.tickformat;if(n){var c={exponentformat:e.exponentformat,dtick:"none"===e.showexponent?e.dtick:b(t)?Math.abs(t)||1:1,range:"none"===e.showexponent?e.range:[0,t||1]};a(c),o=(Number(c._tickround)||0)+4,l=c._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return y.format(u)(t).replace(/-/g,"\u2212");var f=Math.pow(10,-o)/2;if("none"===s&&(l=0),t=Math.abs(t),f>t)t="0",i=!1;else{if(t+=f,l&&(t*=Math.pow(10,-l),o+=l),0===o)t=String(Math.floor(t));else if(0>o){t=String(Math.round(t)),t=t.substr(0,t.length+o);for(var h=o;0>h;h++)t+="0"}else{t=String(t);var p=t.indexOf(".")+1;p&&(t=t.substr(0,p+o).replace(/\.?0+$/,""))}t=_.numSeparate(t,e._gd._fullLayout.separators)}if(l&&"hide"!==s){var d;d=0>l?"\u2212"+-l:"power"!==s?"+"+l:String(l),"e"===s||("SI"===s||"B"===s)&&(l>12||-15>l)?t+="e"+d:"E"===s?t+="E"+d:"power"===s?t+="×10"+d+"":"B"===s&&9===l?t+="B":"SI"!==s&&"B"!==s||(t+=V[l/3+5])}return i?"\u2212"+t:t}function p(t,e){var r,n,i=[];for(r=0;r1)for(n=1;n2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},T.getAutoRange=function(t){var e,r=[],n=t._min[0].val,i=t._max[0].val;for(e=1;e0&&c>0&&f/c>h&&(l=o,u=s,h=f/c);return n===i?r=p?[n+1,"normal"!==t.rangemode?0:n-1]:["normal"!==t.rangemode?0:n-1,n+1]:h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode&&l.val>=0?l={val:0,pad:0}:"nonnegative"===t.rangemode&&(l.val-h*l.pad<0&&(l={val:0,pad:0}),u.val<0&&(u={val:1,pad:0})),h=(u.val-l.val)/(t._length-l.pad-u.pad)),r=[l.val-h*l.pad,u.val+h*u.pad],r[0]===r[1]&&(r=[r[0]-1,r[0]+1]),p&&r.reverse()),r},T.doAutoRange=function(t){t._length||t.setScale();var e=t._min&&t._max&&t._min.length&&t._max.length;if(t.autorange&&e){t.range=T.getAutoRange(t);var r=t._gd.layout[t._name];r||(t._gd.layout[t._name]=r={}),r!==t&&(r.range=t.range.slice(),r.autorange=t.autorange)}},T.saveRangeInitial=function(t,e){for(var r=T.list(t,"",!0),n=!1,i=0;id&&(d=g/10),u=t.c2l(d),c=t.c2l(g),y&&(u=Math.min(0,u),c=Math.max(0,c)),n(u)){for(p=!0,o=0;o=h?p=!1:s.val>=u&&s.pad<=h&&(t._min.splice(o,1),o--);p&&t._min.push({val:u,pad:y&&0===u?0:h})}if(n(c)){for(p=!0,o=0;o=c&&s.pad>=f?p=!1:s.val<=c&&s.pad<=f&&(t._max.splice(o,1),o--);p&&t._max.push({val:c,pad:y&&0===c?0:f})}}}if((t.autorange||t._needsExpand)&&e){t._min||(t._min=[]),t._max||(t._max=[]),r||(r={}),t._m||t.setScale();var a,o,s,l,u,c,f,h,p,d,g,v=e.length,m=r.padded?.05*t._length:0,y=r.tozero&&("linear"===t.type||"-"===t.type),x=n((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),_=n((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),w=n(r.vpadplus||r.vpad),k=n(r.vpadminus||r.vpad);for(a=0;6>a;a++)i(a);for(a=v-1;a>5;a--)i(a)}},T.autoBin=function(t,e,r,n){function i(t){return(1+100*(t-p)/f.dtick)%100<2}var a=_.aggNums(Math.min,null,t),o=_.aggNums(Math.max,null,t);if("category"===e.type)return{start:a-.5,end:o+.5,size:1};var s;if(r)s=(o-a)/r;else{var l=_.distinctVals(t),u=Math.pow(10,Math.floor(Math.log(l.minDiff)/Math.LN10)),c=u*_.roundUp(l.minDiff/u,[.9,1.9,4.9,9.9],!0);s=Math.max(c,2*_.stdev(t)/Math.pow(t.length,n?.25:.4))}var f={type:"log"===e.type?"linear":e.type,range:[a,o]};T.autoTicks(f,s);var h,p=T.tickIncrement(T.tickFirst(f),f.dtick,"reverse");if("number"==typeof f.dtick){for(var d=0,g=0,v=0,m=0,y=0;yg&&(d>.3*x||i(a)||i(o))){var w=f.dtick/2;p+=a>p+w?w:-w}var k=1+Math.floor((o-p)/f.dtick);h=p+k*f.dtick}else for(h=p;o>=h;)h=T.tickIncrement(h,f.dtick);return{start:p,end:h,size:f.dtick}},T.calcTicks=function(t){if("array"===t.tickmode)return n(t);if("auto"===t.tickmode||!t.dtick){var e,r=t.nticks;r||("category"===t.type?(e=t.tickfont?1.2*(t.tickfont.size||12):15,r=t._length/e):(e="y"===t._id.charAt(0)?40:80,r=_.constrain(t._length/e,4,9)+1)),T.autoTicks(t,Math.abs(t.range[1]-t.range[0])/r),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t._forceTick0)}t.tick0||(t.tick0="date"===t.type?new Date(2e3,0,1).getTime():0),a(t),t._tmin=T.tickFirst(t);var i=t.range[1]=s:s>=l)&&(o.push(l),!(o.length>1e3));l=T.tickIncrement(l,t.dtick,i));t._tmax=o[o.length-1];for(var u=new Array(o.length),c=0;c157788e5?(e/=315576e5,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="M"+12*i(e,r,S)):e>12096e5?(e/=26298e5,t.dtick="M"+i(e,1,C)):e>432e5?(t.dtick=i(e,864e5,P),t.tick0=new Date(2e3,0,2).getTime()):e>18e5?t.dtick=i(e,36e5,C):e>3e4?t.dtick=i(e,6e4,z):e>500?t.dtick=i(e,1e3,z):(r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));else if("log"===t.type)if(t.tick0=0,e>.7)t.dtick=Math.ceil(e);else if(Math.abs(t.range[1]-t.range[0])<1){var n=1.5*Math.abs((t.range[1]-t.range[0])/e);e=Math.abs(Math.pow(10,t.range[1])-Math.pow(10,t.range[0]))/n,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="L"+i(e,r,S)}else t.dtick=e>.3?"D2":"D1";else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):(t.tick0=0,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));if(0===t.dtick&&(t.dtick=1),!b(t.dtick)&&"string"!=typeof t.dtick){var a=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(a)}},T.tickIncrement=function(t,e,r){var n=r?-1:1;if(b(e))return t+n*e;var i=e.charAt(0),a=n*Number(e.substr(1));if("M"===i){var o=new Date(t);return o.setMonth(o.getMonth()+a)}if("L"===i)return Math.log(Math.pow(10,t)+a)/Math.LN10;if("D"===i){var s="D2"===e?j:R,l=t+.01*n,u=_.roundUp(m(l,1),s,r);return Math.floor(l)+Math.log(y.round(Math.pow(10,u),1))/Math.LN10}throw"unrecognized dtick "+String(e)},T.tickFirst=function(t){var e=t.range[1]n:n>u;)u=T.tickIncrement(u,i,e);return u}if("L"===c)return Math.log(r((Math.pow(10,n)-a)/f)*f+a)/Math.LN10;if("D"===c){var h="D2"===i?j:R,p=_.roundUp(m(n,1),h,e);return Math.floor(n)+Math.log(y.round(Math.pow(10,p),1))/Math.LN10}throw"unrecognized dtick "+String(i)};var O=y.time.format("%Y"),I=y.time.format("%b %Y"),N=y.time.format("%b %-d"),F=y.time.format("%b %-d %Hh"),D=y.time.format("%H:%M"),B=y.time.format(":%S"),U=/%(\d?)f/g;T.tickText=function(t,e,r){function n(n){var i;return void 0===n?!0:r?"none"===n:(i={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==i)}var i,a,o=s(t,e),h="array"===t.tickmode,p=r||h;if(h&&Array.isArray(t.ticktext)){var d=Math.abs(t.range[1]-t.range[0])/1e4;for(a=0;a1&&er&&(A=90),i(c,A)}u._lastangle=A}return o(e),e+" done"}function l(){u._boundingBox=r.node().getBoundingClientRect()}var c=r.selectAll("g."+C).data(L,S);if(!u.showticklabels||!b(n))return c.remove(),void o(e);var f,h,d,m,x;"x"===v?(x="bottom"===B?1:-1,f=function(t){return t.dx+O*x},m=n+(j+R)*x,h=function(t){return t.dy+m+t.fontSize*("bottom"===B?1:-.5)},d=function(t){return b(t)&&0!==t&&180!==t?0>t*x?"end":"start":"middle"}):(x="right"===B?1:-1,h=function(t){return t.dy+t.fontSize/2-O*x},f=function(t){return t.dx+n+(j+R+(90===Math.abs(u.tickangle)?t.fontSize/2:0))*x},d=function(t){return b(t)&&90===Math.abs(t)?"middle":"right"===B?"start":"end"});var k=0,A=0,T=[];c.enter().append("g").classed(C,1).append("text").attr("text-anchor","middle").each(function(e){var r=y.select(this),n=t._promises.length;r.call(M.setPosition,f(e),h(e)).call(M.font,e.font,e.fontSize,e.fontColor).text(e.text).call(w.convertToTspans),n=t._promises[n],n?T.push(t._promises.pop().then(function(){i(r,u.tickangle)})):i(r,u.tickangle)}),c.exit().remove(),c.each(function(t){k=Math.max(k,t.fontSize)}),i(c,u._lastangle||u.tickangle);var E=_.syncOrAsync([a,s,l]);return E&&E.then&&t._promises.push(E),E}function o(e){if(!r){var n,i,a,o,s=E.getFromId(t,e),l=y.select(t).selectAll("g."+e+"tick"),u={selection:l,side:s.side},f=e.charAt(0),h=t._fullLayout._size,p=1.5,d=s.titlefont.size;if(l.size()){var g=y.select(l.node().parentNode).attr("transform").match(/translate\(([-\.\d]+),([-\.\d]+)\)/);g&&(u.offsetLeft=+g[1],u.offsetTop=+g[2])}"x"===f?(i="free"===s.anchor?{_offset:h.t+(1-(s.position||0))*h.h,_length:0}:E.getFromId(t,s.anchor),a=s._offset+s._length/2,o=i._offset+("top"===s.side?-10-d*(p+(s.showticklabels?1:0)):i._length+10+d*(p+(s.showticklabels?1.5:.5))),s.rangeslider&&s.rangeslider.visible&&s._boundingBox&&(o+=(c.height-c.margin.b-c.margin.t)*s.rangeslider.thickness+s._boundingBox.height),u.side||(u.side="bottom")):(i="free"===s.anchor?{_offset:h.l+(s.position||0)*h.w,_length:0}:E.getFromId(t,s.anchor),o=s._offset+s._length/2,a=i._offset+("right"===s.side?i._length+10+d*(p+(s.showticklabels?1:.5)):-10-d*(p+(s.showticklabels?.5:0))),n={rotate:"-90",offset:0},u.side||(u.side="left")),k.draw(t,e+"title",{propContainer:s,propName:s._name+".title",dfltName:f.toUpperCase()+" axis",avoid:u,transform:n,attributes:{x:a,y:o,"text-anchor":"middle"}})}}function s(t,e){return t.visible!==!0||t.xaxis+t.yaxis!==e?!1:x.Plots.traceIs(t,"bar")&&t.orientation==={x:"h",y:"v"}[v]?!0:t.fill&&t.fill.charAt(t.fill.length-1)===v}function l(e,r,i){var a=e.gridlayer,o=e.zerolinelayer,l=e["hidegrid"+v]?[]:V,c=u._gridpath||"M0,0"+("x"===v?"v":"h")+r._length,f=a.selectAll("path."+z).data(u.showgrid===!1?[]:l,S);if(f.enter().append("path").classed(z,1).classed("crisp",1).attr("d",c).each(function(t){u.zeroline&&("linear"===u.type||"-"===u.type)&&Math.abs(t.x)g;g++){var y=u.mirrors[o._id+h[g]];"ticks"!==y&&"labels"!==y||(f[g]=!0)}return void 0!==n[2]&&(f[2]=!0),f.forEach(function(t,e){var r=n[e],i=U[e];t&&b(r)&&(p+=d(r+R*i,i*u.ticklen))}),i(r,p),l(e,o,t),a(r,n[3])}}).filter(function(t){return t&&t.then});return G.length?Promise.all(G):0},T.swap=function(t,e){for(var r=p(t,e),n=0;n2*n}function c(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}var f=t("fast-isnumeric"),h=t("tinycolor2").mix,p=t("../../lib"),d=t("../plots"),g=t("../../components/color/attributes").lightFraction,v=t("./layout_attributes"),m=t("./tick_value_defaults"),y=t("./tick_mark_defaults"),b=t("./tick_label_defaults"),x=t("./category_order_defaults"),_=t("./set_convert"),w=t("./ordered_categories"),k=t("./clean_datum"),A=t("./axis_ids");e.exports=function(t,e,r,i){function a(r,n){return p.coerce2(t,e,v,r,n)}var o=i.letter,s=i.font||{},l="Click to enter "+(i.title||o.toUpperCase()+" axis")+" title";i.name&&(e._name=i.name,e._id=A.name2id(i.name));var u=r("type");"-"===u&&(n(e,i.data),"-"===e.type?e.type="linear":u=t.type=e.type),_(e);var c=r("color"),d=c===t.color?c:s.color;r("title",l),p.coerceFont(r,"titlefont",{family:s.family,size:Math.round(1.2*s.size),color:d});var k=2===(t.range||[]).length&&f(t.range[0])&&f(t.range[1]),M=r("autorange",!k);M&&r("rangemode");var T=r("range",[-1,"x"===o?6:4]);T[0]===T[1]&&(e.range=[T[0]-1,T[0]+1]),p.noneOrAll(t.range,e.range,[0,1]),r("fixedrange"),m(t,e,r,u),b(t,e,r,u,i),y(t,e,r,i),x(t,e,r);var E=a("linecolor",c),L=a("linewidth"),S=r("showline",!!E||!!L);S||(delete e.linecolor,delete e.linewidth),(S||e.ticks)&&r("mirror");var C=a("gridcolor",h(c,i.bgColor,g).toRgbString()),z=a("gridwidth"),P=r("showgrid",i.showGrid||!!C||!!z);P||(delete e.gridcolor,delete e.gridwidth);var R=a("zerolinecolor",c),j=a("zerolinewidth"),O=r("zeroline",i.showGrid||!!R||!!j);return O||(delete e.zerolinecolor,delete e.zerolinewidth),e._initialCategories="category"===u?w(o,e.categoryorder,e.categoryarray,i.data):[],e}},{"../../components/color/attributes":1047,"../../lib":1127,"../plots":1199,"./axis_ids":1152,"./category_order_defaults":1153,"./clean_datum":1154,"./layout_attributes":1159,"./ordered_categories":1161,"./set_convert":1164,"./tick_label_defaults":1165,"./tick_mark_defaults":1166,"./tick_value_defaults":1167,"fast-isnumeric":90,tinycolor2:1042}],1152:[function(t,e,r){"use strict";function n(t,e,r){function n(t,r){for(var n=Object.keys(t),i=/^[xyz]axis[0-9]*/,a=[],o=0;o0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}},{}],1154:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t){try{if("object"==typeof t&&null!==t&&t.getTime)return i.ms2DateTime(t);if("string"!=typeof t&&!n(t))return"";t=t.toString().replace(/['"%,$# ]/g,"")}catch(e){i.error(e,t)}return t}},{"../../lib":1127,"fast-isnumeric":90}],1155:[function(t,e,r){"use strict";e.exports={idRegex:{x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},attrRegex:{x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},BADNUM:void 0,xAxisMatch:/^xaxis[0-9]*$/,yAxisMatch:/^yaxis[0-9]*$/,AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,DBLCLICKDELAY:300,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,MAXDIST:20,YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,BENDPX:1.5,REDRAWDELAY:50}},{}],1156:[function(t,e,r){"use strict";function n(t,e){var r,n=t.range[e],i=Math.abs(n-t.range[1-e]);return"date"===t.type?u.ms2DateTime(n,i):"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,o.format("."+r+"g")(Math.pow(10,n))):(r=Math.floor(Math.log(Math.abs(n))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,o.format("."+String(r)+"g")(n))}function i(t,e){return t?"nsew"===t?"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}function a(t){o.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var o=t("d3"),s=t("tinycolor2"),l=t("../../plotly"),u=t("../../lib"),c=t("../../lib/svg_text_utils"),f=t("../../components/color"),h=t("../../components/drawing"),p=t("../../lib/setcursor"),d=t("../../components/dragelement"),g=t("./axes"),v=t("./select"),m=t("./constants"),y=!0;e.exports=function(t,e,r,o,b,x,_,w){function k(t,e){for(var r=0;r.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+ht+", "+pt+")").attr("d",ot+"Z"),ct=ft.append("path").attr("class","zoombox-corners").style({fill:f.background,stroke:f.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+ht+", "+pt+")").attr("d","M0,0Z"),T();for(var a=0;ai?(lt="",it.r=it.l,it.t=it.b,ct.attr("d","M0,0Z")):(it.t=0,it.b=V,lt="x",ct.attr("d","M"+(it.l-.5)+","+(nt-G-.5)+"h-3v"+(2*G+1)+"h3ZM"+(it.r+.5)+","+(nt-G-.5)+"h3v"+(2*G+1)+"h-3Z")):!Z||i.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),ct.transition().style("opacity",1).duration(200),st=!0)}function L(t,e,r){var n,i,a;for(n=0;nzoom back out","long"),y=!1)))}function C(e,r){var i=1===(_+w).length;if(e)O();else if(2!==r||i){if(1===r&&i){var a=_?B[0]:D[0],o="s"===_||"w"===w?0:1,s=a._name+".range["+o+"]",u=n(a,o),f="left",h="middle"; -if(a.fixedrange)return;_?(h="n"===_?"top":"bottom","right"===a.side&&(f="right")):"e"===w&&(f="right"),J.call(c.makeEditable,null,{immediate:!0,background:N.paper_bgcolor,text:String(u),fill:a.tickfont?a.tickfont.color:"#444",horizontalAlign:f,verticalAlign:h}).on("edit",function(e){var r="category"===a.type?a.c2l(e):a.d2l(e);void 0!==r&&l.relayout(t,s,r)})}}else j()}function z(e){function r(t,e,r){if(!t.fixedrange){A(t.range);var n=t.range,i=n[0]+(n[1]-n[0])*e;t.range=[i+(n[0]-i)*r,i+(n[1]-i)*r]}}if(t._context.scrollZoom||N._enablescrollzoom){var n=t.querySelector(".plotly");if(!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(gt);var i=-e.deltaY;if(isFinite(i)||(i=e.wheelDelta/10),!isFinite(i))return void u.log("Did not find wheel motion attributes: ",e);var a,o=Math.exp(-Math.min(Math.max(i,-20),20)/100),s=mt.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(e.clientX-s.left)/s.width,c=dt[0]+dt[2]*l,f=(s.bottom-e.clientY)/s.height,h=dt[1]+dt[3]*(1-f);if(w){for(a=0;a=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function i(t,e,r){for(var i=1-e,a=0,o=0;o0;n--)r.push(e);return r}function i(t,e){for(var r=[],n=0;nT;T++){var E=a[T],L=p[E];if(L)A[T]=w.getFromId(t,L.xaxis._id),M[T]=w.getFromId(t,L.yaxis._id);else{var S=o[E]._subplot;A[T]=S.xaxis,M[T]=S.yaxis}}var C=e.hovermode||o.hovermode;if(-1===["x","y","closest"].indexOf(C)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return _.unhoverRaw(t,e);var z,P,R,j,O,I,N,F,D,B,U,V,q=[],G=[];if(Array.isArray(e))for(C="array",R=0;RH||H>X.width||0>Y||Y>X.height)return _.unhoverRaw(t,e)}else H="xpx"in e?e.xpx:A[0]._length/2,Y="ypx"in e?e.ypx:M[0]._length/2;if(z="xval"in e?n(a,e.xval):i(A,H),P="yval"in e?n(a,e.yval):i(M,Y),!g(z[0])||!g(P[0]))return v.warn("Plotly.Fx.hover failed",e,t),_.unhoverRaw(t,e)}var W=1/0;for(j=0;j1||-1!==I.hoverinfo.indexOf("name")?I.name:void 0,index:!1,distance:Math.min(W,k.MAXDIST),color:b.defaultLine,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},V=q.length,"array"===F){var Z=e[j];"pointNumber"in Z?(U.index=Z.pointNumber,F="closest"):(F="","xval"in Z&&(D=Z.xval,F="x"),"yval"in Z&&(B=Z.yval,F=F?"closest":"y"))}else D=z[N],B=P[N];if(I._module&&I._module.hoverPoints){var K=I._module.hoverPoints(U,D,B,F);if(K)for(var $,Q=0;QV&&(q.splice(0,V),W=q[0].distance)}if(0===q.length)return _.unhoverRaw(t,e);var J="y"===C&&G.length>1;q.sort(function(t,e){return t.distance-e.distance});var tt=b.combine(o.plot_bgcolor||b.background,o.paper_bgcolor),et={hovermode:C,rotateLabels:J,bgColor:tt,container:o._hoverlayer,outerContainer:o._paperdiv},rt=u(q,et);c(q,J?"xa":"ya"),f(rt,J);var nt=t._hoverdata,it=[];for(R=0;R128?"#000":b.background;if(t.name&&void 0===t.zLabelVal){var c=document.createElement("p");c.innerHTML=t.name,r=c.textContent||"",r.length>15&&(r=r.substr(0,12)+"...")}void 0!==t.extraText&&(n+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(n+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(n+="y: "+t.yLabel+"
"),n+=(n?"z: ":"")+t.zLabel):M&&t[i+"Label"]===g?n=t[("x"===i?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(n=t.yLabel):n=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(n+=(n?"
":"")+t.text),""===n&&(""===r&&e.remove(),n=r);var f=e.select("text.nums").style("fill",u).call(x.setPosition,0,0).text(n).attr("data-notex",1).call(y.convertToTspans);f.selectAll("tspan.line").call(x.setPosition,0,0);var h=e.select("text.name"),v=0;r&&r!==n?(h.style("fill",l).text(r).call(x.setPosition,0,0).attr("data-notex",1).call(y.convertToTspans),h.selectAll("tspan.line").call(x.setPosition,0,0),v=h.node().getBoundingClientRect().width+2*P):(h.remove(),e.select("rect").remove()),e.select("path").style({fill:l,stroke:u});var m,k,E=f.node().getBoundingClientRect(),L=t.xa._offset+(t.x0+t.x1)/2,S=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),R=Math.abs(t.y1-t.y0),j=E.width+z+P+v;t.ty0=_-E.top,t.bx=E.width+2*P,t.by=E.height+2*P,t.anchor="start",t.txwidth=E.width,t.tx2width=v,t.offset=0,a?(t.pos=L,m=A>=S+R/2+j,k=S-R/2-j>=0,"top"!==t.idealAlign&&m||!k?m?(S+=R/2,t.anchor="start"):t.anchor="middle":(S-=R/2,t.anchor="end")):(t.pos=S,m=w>=L+C/2+j,k=L-C/2-j>=0,"left"!==t.idealAlign&&m||!k?m?(L+=C/2,t.anchor="start"):t.anchor="middle":(L-=C/2,t.anchor="end")),f.attr("text-anchor",t.anchor),v&&h.attr("text-anchor",t.anchor),e.attr("transform","translate("+L+","+S+")"+(a?"rotate("+T+")":""))}),S}function c(t,e){function r(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(.01>a)){if(-.01>i){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;oe.pmax&&u++;for(o=t.length-1;o>=0&&!(0>=u);o--)l=t[o],l.pos>e.pmax-1&&(l.del=!0,u--);for(o=0;o=u);o++)if(l=t[o],l.pos=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(0>=u);o--)l=t[o],l.pos+l.dp+l.size>e.pmax&&(l.del=!0,u--)}}}for(var n,i,a,o,s,l,u,c=0,f=t.map(function(t,r){var n=t[e];return[{i:r,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===n._id.charAt(0)?L:1)/2,pmin:n._offset,pmax:n._offset+n._length}]}).sort(function(t,e){return t[0].posref-e[0].posref});!n&&c<=t.length;){for(c++,n=!0,o=0;o.01&&d.pmin===g.pmin&&d.pmax===g.pmax){for(s=p.length-1;s>=0;s--)p[s].dp+=i;for(h.push.apply(h,p),f.splice(o+1,1),u=0,s=h.length-1;s>=0;s--)u+=h[s].dp;for(a=u/h.length,s=h.length-1;s>=0;s--)h[s].dp-=a;n=!1}else o++}f.forEach(r)}for(o=f.length-1;o>=0;o--){var v=f[o];for(s=v.length-1;s>=0;s--){var m=v[s],y=t[m.i];y.offset=m.dp,y.del=m.del}}}function f(t,e){t.each(function(t){var r=p.select(this);if(t.del)return void r.remove();var n="end"===t.anchor?-1:1,i=r.select("text.nums"),a={start:1,end:-1,middle:0}[t.anchor],o=a*(z+P),s=o+a*(t.txwidth+P),l=0,u=t.offset;"middle"===t.anchor&&(o-=t.tx2width/2,s-=t.tx2width/2),e&&(u*=-C,l=t.offset*S),r.select("path").attr("d","middle"===t.anchor?"M-"+t.bx/2+",-"+t.by/2+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(n*z+l)+","+(z+u)+"v"+(t.by/2-z)+"h"+n*t.bx+"v-"+t.by+"H"+(n*z+l)+"V"+(u-z)+"Z"),i.call(x.setPosition,o+l,u+t.ty0-t.by/2+P).selectAll("tspan.line").attr({x:i.attr("x"),y:i.attr("y")}),t.tx2width&&(r.select("text.name, text.name tspan.line").call(x.setPosition,s+a*P+l,u+t.ty0-t.by/2+P),r.select("rect").call(x.setRect,s+(a-1)*t.tx2width/2+l,u-t.by/2-1,t.tx2width,t.by+2))})}function h(t,e,r){if(!e.target)return!1;if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}var p=t("d3"),d=t("tinycolor2"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../lib/events"),y=t("../../lib/svg_text_utils"),b=t("../../components/color"),x=t("../../components/drawing"),_=t("../../components/dragelement"),w=t("./axes"),k=t("./constants"),A=t("./dragbox"),M=e.exports={};M.unhover=_.unhover,M.layoutAttributes={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom"},hovermode:{valType:"enumerated",values:["x","y","closest",!1]}},M.supplyLayoutDefaults=function(t,e,r){function n(r,n){return v.coerce(t,e,M.layoutAttributes,r,n)}n("dragmode");var i;if(e._has("cartesian")){var a=e._isHoriz=M.isHoriz(r);i=a?"y":"x"}else i="closest";n("hovermode",i)},M.isHoriz=function(t){for(var e=!0,r=0;rt._lastHoverTime+k.HOVERMINTIME?(o(t,e,r),void(t._lastHoverTime=Date.now())):void(t._hoverTimer=setTimeout(function(){o(t,e,r),t._lastHoverTime=Date.now(),t._hoverTimer=void 0},k.HOVERMINTIME))},M.getDistanceFunction=function(t,e,r,n){return"closest"===t?n||a(e,r):"x"===t?e:r},M.getClosest=function(t,e,r){if(r.index!==!1)r.index>=0&&r.indext*e||0===t?k.MAXDIST*(.6-.3/Math.max(3,Math.abs(t-e))):1/0}},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../lib":1127,"../../lib/events":1121,"../../lib/svg_text_utils":1140,"./axes":1150,"./constants":1155,"./dragbox":1156,d3:82,"fast-isnumeric":90,tinycolor2:1042}],1158:[function(t,e,r){"use strict";var n=t("../plots"),i=(t("d3"),t("./constants"));r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=i.idRegex,r.attrRegex=i.attrRegex,r.attributes=t("./attributes"),r.plot=function(t,e,r){function i(t,e){for(var r=[],n=0;nf[1]-.01&&(e.domain=[0,1]),i.noneOrAll(t.domain,e.domain,[0,1])}return e}},{"../../lib":1127,"fast-isnumeric":90}],1163:[function(t,e,r){"use strict";function n(t){return t._id}var i=t("../../lib/polygon"),a=t("../../components/color"),o=t("./axes"),s=t("./constants"),l=i.filter,u=i.tester,c=s.MINSELECT;e.exports=function(t,e,r,i,f){function h(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function p(t,e){return t-e}var d,g=i.gd._fullLayout._zoomlayer,v=i.element.getBoundingClientRect(),m=i.plotinfo.x()._offset,y=i.plotinfo.y()._offset,b=e-v.left,x=r-v.top,_=b,w=x,k="M"+b+","+x,A=i.xaxes[0]._length,M=i.yaxes[0]._length,T=i.xaxes.map(n),E=i.yaxes.map(n),L=i.xaxes.concat(i.yaxes);"lasso"===f&&(d=l([[b,x]],s.BENDPX));var S=g.selectAll("path.select-outline").data([1,2]);S.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t}).attr("transform","translate("+m+", "+y+")").attr("d",k+"Z");var C,z,P,R,j,O=g.append("path").attr("class","zoombox-corners").style({fill:a.background,stroke:a.defaultLine,"stroke-width":1}).attr("transform","translate("+m+", "+y+")").attr("d","M0,0Z"),I=[],N=i.gd,F=[];for(C=0;C0)return Math.log(e)/Math.LN10;if(0>=e&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*c*Math.abs(n-i))}return o.BADNUM}function r(t){return Math.pow(10,t)}function u(t){return i(t)?Number(t):o.BADNUM}var c=10;if(t.c2l="log"===t.type?e:u,t.l2c="log"===t.type?r:u,t.l2d=function(e){return t.c2d(t.l2c(e))},t.p2d=function(e){return t.l2d(t.p2l(e))},t.setScale=function(){var e,r=t._gd._fullLayout._size;if(t._categories||(t._categories=[]),t.overlaying){var n=l.getFromId(t._gd,t.overlaying);t.domain=n.domain}for(t.range&&2===t.range.length&&t.range[0]!==t.range[1]||(t.range=[-1,1]),e=0;2>e;e++)i(t.range[e])||(t.range[e]=i(t.range[1-e])?t.range[1-e]*(e?10:.1):e?1:-1),t.range[e]<-(Number.MAX_VALUE/2)?t.range[e]=-(Number.MAX_VALUE/2):t.range[e]>Number.MAX_VALUE/2&&(t.range[e]=Number.MAX_VALUE/2);if("y"===t._id.charAt(0)?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[0]-t.range[1]),t._b=-t._m*t.range[1]):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[1]-t.range[0]),t._b=-t._m*t.range[0]),!isFinite(t._m)||!isFinite(t._b))throw a.notifier("Something went wrong with axis scaling","long"),t._gd._replotting=!1, -new Error("axis scaling")},t.l2p=function(e){return i(e)?n.round(t._b+t._m*e,2):o.BADNUM},t.p2l=function(e){return(e-t._b)/t._m},t.c2p=function(e,r){return t.l2p(t.c2l(e,r))},t.p2c=function(e){return t.l2c(t.p2l(e))},-1!==["linear","log","-"].indexOf(t.type))t.c2d=u,t.d2c=function(t){return t=s(t),i(t)?Number(t):o.BADNUM},t.d2l=function(e,r){return"log"===t.type?t.c2l(t.d2c(e),r):t.d2c(e)};else if("date"===t.type){if(t.c2d=function(t){return i(t)?a.ms2DateTime(t):o.BADNUM},t.d2c=function(t){return i(t)?Number(t):a.dateTime2ms(t)},t.d2l=t.d2c,t.range&&t.range.length>1)try{var f=t.range.map(a.dateTime2ms);!i(t.range[0])&&i(f[0])&&(t.range[0]=f[0]),!i(t.range[1])&&i(f[1])&&(t.range[1]=f[1])}catch(h){a.error(h,t.range)}}else"category"===t.type&&(t.c2d=function(e){return t._categories[Math.round(e)]},t.d2c=function(e){null!==e&&void 0!==e&&-1===t._categories.indexOf(e)&&t._categories.push(e);var r=t._categories.indexOf(e);return-1===r?o.BADNUM:r},t.d2l=t.d2c);t.makeCalcdata=function(e,r){var n,i,a;if(r in e)for(n=e[r],i=new Array(n.length),a=0;an?"0":"1.0"}var r=this.framework,n=r.select("g.choroplethlayer"),i=r.select("g.scattergeolayer"),a=this.projection,o=this.path,s=this.clipAngle;r.selectAll("path.basepath").attr("d",o),r.selectAll("path.graticulepath").attr("d",o),n.selectAll("path.choroplethlocation").attr("d",o),n.selectAll("path.basepath").attr("d",o),i.selectAll("path.js-line").attr("d",o),null!==s?(i.selectAll("path.point").style("opacity",e).attr("transform",t),i.selectAll("text").style("opacity",e).attr("transform",t)):(i.selectAll("path.point").attr("transform",t),i.selectAll("text").attr("transform",t))}},{"../../components/color":1048,"../../components/drawing":1071,"../../constants/xmlns_namespaces":1115,"../../lib/filter_visible":1123,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"./constants":1169,"./projections":1177,"./set_scale":1178,"./zoom":1179,"./zoom_reset":1180,d3:82,topojson:1043}],1171:[function(t,e,r){"use strict";var n=t("./geo"),i=t("../../plots/plots");r.name="geo",r.attr="geo",r.idRoot="geo",r.idRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"geo");void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var o=0;o=n}function a(t,e){for(var r=e[0],n=e[1],i=!1,a=0,o=t.length,s=o-1;o>a;s=a++){var l=t[a],u=l[0],c=l[1],f=t[s],h=f[0],p=f[1];c>n^p>n&&(h-u)*(n-c)/(p-c)+u>r&&(i=!i)}return i}function o(t){return t?t/Math.sin(t):1}function s(t){return t>1?P:-1>t?-P:Math.asin(t)}function l(t){return t>1?0:-1>t?z:Math.acos(t)}function u(t,e){var r=(2+P)*Math.sin(e);e/=2;for(var n=0,i=1/0;10>n&&Math.abs(i)>S;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(z*(4+z))*t*(1+Math.cos(e)),2*Math.sqrt(z/(4+z))*Math.sin(e)]}function c(t,e){function r(r,n){var i=N(r/e,n);return i[0]*=t,i}return arguments.length<2&&(e=t),1===e?N:e===1/0?h:(r.invert=function(r,n){var i=N.invert(r/t,n);return i[0]*=e,i},r)}function f(){var t=2,e=I(c),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}function h(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function p(t,e){return[3*t/(2*z)*Math.sqrt(z*z/3-e*e),e]}function d(t,e){return[t,1.25*Math.log(Math.tan(z/4+.4*e))]}function g(t){return function(e){var r,n=t*Math.sin(e),i=30;do e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e));while(Math.abs(r)>S&&--i>0);return e/2}}function v(t,e,r){function n(r,n){return[t*r*Math.cos(n=i(n)),e*Math.sin(n)]}var i=g(r);return n.invert=function(n,i){var a=s(i/e);return[n/(t*Math.cos(a)),s((2*a+Math.sin(2*a))/r)]},n}function m(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(-.013791+n*(.003971*r-.001529*n))),e*(1.007226+r*(.015085+n*(-.044475+.028874*r-.005916*n)))]}function y(t,e){var r,n=Math.min(18,36*Math.abs(e)/z),i=Math.floor(n),a=n-i,o=(r=D[i])[0],s=r[1],l=(r=D[++i])[0],u=r[1],c=(r=D[Math.min(19,++i)])[0],f=r[1];return[t*(l+a*(c-o)/2+a*a*(c-2*l+o)/2),(e>0?P:-P)*(u+a*(f-s)/2+a*a*(f-2*u+s)/2)]}function b(t,e){return[t*Math.cos(e),e]}function x(t,e){var r=Math.cos(e),n=o(l(r*Math.cos(t/=2)));return[2*r*Math.sin(t)*n,Math.sin(e)*n]}function _(t,e){var r=x(t,e);return[(r[0]+t/P)/2,(r[1]+e)/2]}t.geo.project=function(t,e){var n=e.stream;if(!n)throw new Error("not yet supported");return(t&&w.hasOwnProperty(t.type)?w[t.type]:r)(t,n)};var w={Feature:e,FeatureCollection:function(t,r){return{type:"FeatureCollection",features:t.features.map(function(t){return e(t,r)})}}},k=[],A=[],M={point:function(t,e){k.push([t,e])},result:function(){var t=k.length?k.length<2?{type:"Point",coordinates:k[0]}:{type:"MultiPoint",coordinates:k}:null;return k=[],t}},T={lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){k.length&&(A.push(k),k=[])},result:function(){var t=A.length?A.length<2?{type:"LineString",coordinates:A[0]}:{type:"MultiLineString",coordinates:A}:null;return A=[],t}},E={polygonStart:n,lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){var t=k.length;if(t){do k.push(k[0].slice());while(++t<4);A.push(k),k=[]}},polygonEnd:n,result:function(){if(!A.length)return null;var t=[],e=[];return A.forEach(function(r){i(r)?t.push([r]):e.push(r)}),e.forEach(function(e){var r=e[0];t.some(function(t){return a(t[0],r)?(t.push(e),!0):void 0})||t.push([e])}),A=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},L={Point:M,MultiPoint:M,LineString:T,MultiLineString:T,Polygon:E,MultiPolygon:E,Sphere:E},S=1e-6,C=S*S,z=Math.PI,P=z/2,R=(Math.sqrt(z),z/180),j=180/z,O=t.geo.projection,I=t.geo.projectionMutator;t.geo.interrupt=function(e){function r(t,r){for(var n=0>r?-1:1,i=l[+(0>r)],a=0,o=i.length-1;o>a&&t>i[a][2][0];++a);var s=e(t-i[a][1][0],r);return s[0]+=e(i[a][1][0],n*r>n*i[a][0][1]?i[a][0][1]:r)[0],s}function n(){s=l.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})})}function i(){for(var e=1e-6,r=[],n=0,i=l[0].length;i>n;++n){var o=l[0][n],s=180*o[0][0]/z,u=180*o[0][1]/z,c=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[s+e,u+e],[s+e,c-e],[f-e,c-e],[f-e,h+e]],30))}for(var n=l[1].length-1;n>=0;--n){var o=l[1][n],s=180*o[0][0]/z,u=180*o[0][1]/z,c=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[f-e,h-e],[f-e,c+e],[s+e,c+e],[s+e,u-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}function a(t,e){for(var r,n,i,a=-1,o=t.length,s=t[0],l=[];++au;++u)l.push([s[0]+u*n,s[1]+u*i]);s=r}return l.push(r),l}function o(t,e){return Math.abs(t[0]-e[0])n)],a=l[+(0>n)],u=0,c=i.length;c>u;++u){var f=i[u];if(f[0][0]<=t&&tS&&--i>0);return[t/(.8707+(a=n*n)*(-.131979+a*(-.013791+a*a*a*(.003971-.001529*a)))),n]},(t.geo.naturalEarth=function(){return O(m)}).raw=m;var D=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];D.forEach(function(t){t[1]*=1.0144}),y.invert=function(t,e){var r=e/P,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],u=l-o,c=l-2*s+o,f=2*(Math.abs(r)-s)/u,h=c/u,p=f*(1-h*f*(1-2*h*f));if(p>=0||1===a){n=(e>=0?5:-5)*(p+i);var d,g=50;do i=Math.min(18,Math.abs(n)/5),a=Math.floor(i),p=i-a,o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],n-=(d=(e>=0?P:-P)*(s+p*(l-o)/2+p*p*(l-2*s+o)/2)-e)*j;while(Math.abs(d)>C&&--g>0);break}}while(--a>=0);var v=D[a][0],m=D[a+1][0],y=D[Math.min(19,a+2)][0];return[t/(m+p*(y-v)/2+p*p*(y-2*m+v)/2),n*R]},(t.geo.robinson=function(){return O(y)}).raw=y,b.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return O(b)}).raw=b,x.invert=function(t,e){if(!(t*t+4*e*e>z*z+S)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),u=Math.cos(r/2),c=Math.sin(n),f=Math.cos(n),h=Math.sin(2*n),p=c*c,d=f*f,g=s*s,v=1-d*u*u,m=v?l(f*u)*Math.sqrt(a=1/v):a=0,y=2*m*f*s-t,b=m*c-e,x=a*(d*g+m*f*u*p),_=a*(.5*o*h-2*m*c*s),w=.25*a*(h*s-m*c*d*o),k=a*(p*u+m*g*f),A=_*w-k*x;if(!A)break;var M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return O(x)}).raw=x,_.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),u=Math.sin(2*n),c=s*s,f=o*o,h=Math.sin(r),p=Math.cos(r/2),d=Math.sin(r/2),g=d*d,v=1-f*p*p,m=v?l(o*p)*Math.sqrt(a=1/v):a=0,y=.5*(2*m*o*d+r/P)-t,b=.5*(m*s+n)-e,x=.5*a*(f*g+m*o*p*c)+.5/P,_=a*(h*u/4-m*s*d),w=.125*a*(u*d-m*s*f*h),k=.5*a*(c*p+m*g*o)+.5,A=_*w-k*x,M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return O(_)}).raw=_}e.exports=n},{}],1178:[function(t,e,r){"use strict";function n(t,e){var r=t.projection,n=t.lonaxis,o=t.lataxis,l=t.domain,u=t.framewidth||0,c=e.w*(l.x[1]-l.x[0]),f=e.h*(l.y[1]-l.y[0]),h=n.range[0]+s,p=n.range[1]-s,d=o.range[0]+s,g=o.range[1]-s,v=n._fullRange[0]+s,m=n._fullRange[1]-s,y=o._fullRange[0]+s,b=o._fullRange[1]-s;r._translate0=[e.l+c/2,e.t+f/2];var x=p-h,_=g-d,w=[h+x/2,d+_/2],k=r._rotate;r._center=[w[0]+k[0],w[1]+k[1]];var A=function(e){function n(t){return Math.min(_*c/(t[1][0]-t[0][0]),_*f/(t[1][1]-t[0][1]))}var o,s,l,x,_=e.scale(),w=r._translate0,k=i(h,d,p,g),A=i(v,y,m,b);l=a(e,k),o=n(l),x=a(e,A),r._fullScale=n(x),e.scale(o),l=a(e,k),s=[w[0]-l[0][0]+u,w[1]-l[0][1]+u],r._translate=s,e.translate(s),l=a(e,k),t._isAlbersUsa||e.clipExtent(l),o=r.scale*o,r._scale=o,t._width=Math.round(l[1][0])+u,t._height=Math.round(l[1][1])+u,t._marginX=(c-Math.round(l[1][0]))/2,t._marginY=(f-Math.round(l[1][1]))/2};return A}function i(t,e,r,n){var i=(r-t)/4;return{type:"Polygon",coordinates:[[[t,e],[t,n],[t+i,n],[t+2*i,n],[t+3*i,n],[r,n],[r,e],[r-i,e],[r-2*i,e],[r-3*i,e],[t,e]]]}}function a(t,e){return o.geo.path().projection(t).bounds(e)}var o=t("d3"),s=t("./constants").clipPad;e.exports=n},{"./constants":1169,d3:82}],1179:[function(t,e,r){"use strict";function n(t,e){var r;return(r=e._isScoped?a:e._clipAngle?s:o)(t,e.projection)}function i(t,e){var r=e._fullScale;return _.behavior.zoom().translate(t.translate()).scale(t.scale()).scaleExtent([.5*r,100*r])}function a(t,e){function r(){_.select(this).style(A)}function n(){o.scale(_.event.scale).translate(_.event.translate),t.render()}function a(){_.select(this).style(M)}var o=t.projection,s=i(o,e);return s.on("zoomstart",r).on("zoom",n).on("zoomend",a),s}function o(t,e){function r(t){return v.invert(t)}function n(t){var e=v(r(t));return Math.abs(e[0]-t[0])>y||Math.abs(e[1]-t[1])>y}function a(){_.select(this).style(A),l=_.mouse(this),u=v.rotate(),c=v.translate(),f=u,h=r(l)}function o(){return p=_.mouse(this),n(l)?(m.scale(v.scale()),void m.translate(v.translate())):(v.scale(_.event.scale),v.translate([c[0],_.event.translate[1]]),h?r(p)&&(g=r(p),d=[f[0]+(g[0]-h[0]),u[1],u[2]],v.rotate(d),f=d):(l=p,h=r(l)),void t.render())}function s(){_.select(this).style(M)}var l,u,c,f,h,p,d,g,v=t.projection,m=i(v,e),y=2;return m.on("zoomstart",a).on("zoom",o).on("zoomend",s),m}function s(t,e){function r(t){m++||t({type:"zoomstart"})}function n(t){t({type:"zoom"})}function a(t){--m||t({type:"zoomend"})}var o,s=t.projection,p={r:s.rotate(),k:s.scale()},d=i(s,e),g=x(d,"zoomstart","zoom","zoomend"),m=0,y=d.on;return d.on("zoomstart",function(){_.select(this).style(A);var t=_.mouse(this),e=s.rotate(),i=e,a=s.translate(),m=u(e);o=l(s,t),y.call(d,"zoom",function(){var r=_.mouse(this);if(s.scale(p.k=_.event.scale),o){if(l(s,r)){s.rotate(e).translate(a);var u=l(s,r),d=f(o,u),y=v(c(m,d)),b=p.r=h(y,o,i);isFinite(b[0])&&isFinite(b[1])&&isFinite(b[2])||(b=i),s.rotate(b),i=b}}else t=r,o=l(s,t);n(g.of(this,arguments))}),r(g.of(this,arguments))}).on("zoomend",function(){_.select(this).style(M),y.call(d,"zoom",null),a(g.of(this,arguments))}).on("zoom.redraw",function(){t.render()}),_.rebind(d,g,"on")}function l(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&m(r)}function u(t){var e=.5*t[0]*w,r=.5*t[1]*w,n=.5*t[2]*w,i=Math.sin(e),a=Math.cos(e),o=Math.sin(r),s=Math.cos(r),l=Math.sin(n),u=Math.cos(n);return[a*s*u+i*o*l,i*s*u-a*o*l,a*o*u+i*s*l,a*s*l-i*o*u]}function c(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],l=e[2],u=e[3];return[r*o-n*s-i*l-a*u,r*s+n*o+i*u-a*l,r*l-n*u+i*o+a*s,r*u+n*l-i*s+a*o]}function f(t,e){if(t&&e){var r=b(t,e),n=Math.sqrt(y(r,r)),i=.5*Math.acos(Math.max(-1,Math.min(1,y(t,e)))),a=Math.sin(i)/n;return n&&[Math.cos(i),r[2]*a,-r[1]*a,r[0]*a]}}function h(t,e,r){var n=g(e,2,t[0]);n=g(n,1,t[1]),n=g(n,0,t[2]-r[2]);var i,a,o=e[0],s=e[1],l=e[2],u=n[0],c=n[1],f=n[2],h=Math.atan2(s,o)*k,d=Math.sqrt(o*o+s*s);Math.abs(c)>d?(a=(c>0?90:-90)-h,i=0):(a=Math.asin(c/d)*k-h,i=Math.sqrt(d*d-c*c));var v=180-a-2*h,m=(Math.atan2(f,u)-Math.atan2(l,i))*k,y=(Math.atan2(f,u)-Math.atan2(l,-i))*k,b=p(r[0],r[1],a,m),x=p(r[0],r[1],v,y);return x>=b?[a,m,r[2]]:[v,y,r[2]]}function p(t,e,r,n){var i=d(r-t),a=d(n-e);return Math.sqrt(i*i+a*a)}function d(t){return(t%360+540)%360-180}function g(t,e,r){var n=r*w,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function v(t){return[Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),1-2*(t[1]*t[1]+t[2]*t[2]))*k,Math.asin(Math.max(-1,Math.min(1,2*(t[0]*t[2]-t[3]*t[1]))))*k,Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),1-2*(t[2]*t[2]+t[3]*t[3]))*k]}function m(t){var e=t[0]*w,r=t[1]*w,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function y(t,e){for(var r=0,n=0,i=t.length;i>n;++n)r+=t[n]*e[n];return r}function b(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function x(t){for(var e=0,r=arguments.length,n=[];++ep;++p){for(e=u[p],r=t[this.scene[e]._name],n=/Click to enter .+ title/.test(r.title)?"":r.title,d=0;2>=d;d+=2)this.labelEnable[p+d]=!1,this.labels[p+d]=o(n),this.labelColor[p+d]=s(r.titlefont.color),this.labelFont[p+d]=r.titlefont.family,this.labelSize[p+d]=r.titlefont.size,this.labelPad[p+d]=this.getLabelPad(e,r),this.tickEnable[p+d]=!1,this.tickColor[p+d]=s((r.tickfont||{}).color),this.tickAngle[p+d]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[p+d]=this.getTickPad(r),this.tickMarkLength[p+d]=0,this.tickMarkWidth[p+d]=r.tickwidth||0,this.tickMarkColor[p+d]=s(r.tickcolor),this.borderLineEnable[p+d]=!1,this.borderLineColor[p+d]=s(r.linecolor),this.borderLineWidth[p+d]=r.linewidth||0;c=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!c,l=this.hasAxisInAltrPos(e,r)&&!c,i=r.mirror||!1,f=c?-1!==String(i).indexOf("all"):!!i,h=c?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[p]=!0:l&&(this.labelEnable[p+2]=!0),a?this.tickEnable[p]=r.showticklabels:l&&(this.tickEnable[p+2]=r.showticklabels),(a||f)&&(this.borderLineEnable[p]=r.showline),(l||f)&&(this.borderLineEnable[p+2]=r.showline),(a||h)&&(this.tickMarkLength[p]=this.getTickMarkLength(r)),(l||h)&&(this.tickMarkLength[p+2]=this.getTickMarkLength(r)),this.gridLineEnable[p]=r.showgrid,this.gridLineColor[p]=s(r.gridcolor),this.gridLineWidth[p]=r.gridwidth,this.zeroLineEnable[p]=r.zeroline,this.zeroLineColor[p]=s(r.zerolinecolor),this.zeroLineWidth[p]=r.zerolinewidth}},l.hasSharedAxis=function(t){var e=this.scene,r=a.Plots.getSubplotIds(e.fullLayout,"gl2d"),n=a.Axes.findSubplotsWithAxis(r,t);return 0!==n.indexOf(e.id)},l.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},l.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},l.getLabelPad=function(t,e){var r=1.5,n=e.titlefont.size,i=e.showticklabels;return"xaxis"===t?"top"===e.side?-10+n*(r+(i?1:0)):-10+n*(r+(i?.5:0)):"yaxis"===t?"right"===e.side?10+n*(r+(i?1:.5)):10+n*(r+(i?.5:0)):void 0},l.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},l.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e},e.exports=i},{"../../lib/html2unicode":1126,"../../lib/str2rgbarray":1139,"../../plotly":1147}],1183:[function(t,e,r){"use strict";var n=t("./scene2d"),i=t("../plots"),a=t("../../constants/xmlns_namespaces");r.name="gl2d",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex={x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},r.attrRegex={x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},r.attributes=t("../cartesian/attributes"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"gl2d"),o=0;or;++r){var n=t[r],i=e[r];if(n.length!==i.length)return!0;for(var a=0;ao;++o,--s)for(var l=0;r>l;++l)for(var u=0;4>u;++u){var c=i[4*(r*o+l)+u];i[4*(r*o+l)+u]=i[4*(r*s+l)+u],i[4*(r*s+l)+u]=c}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),p=h.createImageData(r,n);p.data.set(i),h.putImageData(p,0,0);var d;switch(t){case"jpeg":d=f.toDataURL("image/jpeg");break;case"webp":d=f.toDataURL("image/webp");break;default:d=f.toDataURL("image/png")}return this.staticPlot&&this.container.removeChild(a),d},m.computeTickMarks=function(){this.xaxis._length=this.glplot.viewBox[2]-this.glplot.viewBox[0],this.yaxis._length=this.glplot.viewBox[3]-this.glplot.viewBox[1];for(var t=[s.calcTicks(this.xaxis),s.calcTicks(this.yaxis)],e=0;2>e;++e)for(var r=0;rk;++k)w[k]=Math.min(w[k],a.bounds[k]),w[k+2]=Math.max(w[k+2],a.bounds[k+2])}var A;for(n=0;2>n;++n)w[n]>w[n+2]&&(w[n]=-1,w[n+2]=1),A=this[v[n]],A._length=y.viewBox[n+2]-y.viewBox[n],s.doAutoRange(A);y.ticks=this.computeTickMarks();var M=this.xaxis.range,T=this.yaxis.range;y.dataBox=[M[0],T[0],M[1],T[1]],y.merge(r),o.update(y),this.glplot.draw()},m.draw=function(){if(!this.stopped){requestAnimationFrame(this.redraw);var t=this.glplot,e=this.camera,r=e.mouseListener,n=this.fullLayout;this.cameraChanged();var i=r.x*t.pixelRatio,a=this.canvas.height-t.pixelRatio*r.y;if(e.boxEnabled&&"zoom"===n.dragmode)this.selectBox.enabled=!0,this.selectBox.selectBox=[Math.min(e.boxStart[0],e.boxEnd[0]),Math.min(e.boxStart[1],e.boxEnd[1]),Math.max(e.boxStart[0],e.boxEnd[0]),Math.max(e.boxStart[1],e.boxEnd[1])],t.setDirty();else{this.selectBox.enabled=!1;var o=n._size,s=this.xaxis.domain,u=this.yaxis.domain,c=t.pick(i/t.pixelRatio+o.l+s[0]*o.w,a/t.pixelRatio-(o.t+(1-u[1])*o.h));if(c&&n.hovermode){var f=c.object._trace.handlePick(c);if(f&&(!this.lastPickResult||this.lastPickResult.trace!==f.trace||this.lastPickResult.dataCoord[0]!==f.dataCoord[0]||this.lastPickResult.dataCoord[1]!==f.dataCoord[1])){var h=this.lastPickResult=f;this.spikes.update({center:c.dataCoord}),h.screenCoord=[((t.viewBox[2]-t.viewBox[0])*(c.dataCoord[0]-t.dataBox[0])/(t.dataBox[2]-t.dataBox[0])+t.viewBox[0])/t.pixelRatio,(this.canvas.height-(t.viewBox[3]-t.viewBox[1])*(c.dataCoord[1]-t.dataBox[1])/(t.dataBox[3]-t.dataBox[1])-t.viewBox[1])/t.pixelRatio];var p=h.hoverinfo;if("all"!==p){var d=p.split("+");-1===d.indexOf("x")&&(h.traceCoord[0]=void 0),-1===d.indexOf("y")&&(h.traceCoord[1]=void 0),-1===d.indexOf("z")&&(h.traceCoord[2]=void 0),-1===d.indexOf("text")&&(h.textLabel=void 0),-1===d.indexOf("name")&&(h.name=void 0)}l.loneHover({x:h.screenCoord[0],y:h.screenCoord[1],xLabel:this.hoverFormatter("xaxis",h.traceCoord[0]),yLabel:this.hoverFormatter("yaxis",h.traceCoord[1]),zLabel:h.traceCoord[2],text:h.textLabel,name:h.name,color:h.color},{container:this.svgContainer}),this.lastPickResult={dataCoord:c.dataCoord}}}else!c&&this.lastPickResult&&(this.spikes.update({}),this.lastPickResult=null,l.loneUnhover(this.svgContainer))}t.draw()}},m.hoverFormatter=function(t,e){if(void 0!==e){var r=this[t];return s.tickText(r,r.c2l(e),"hover").text}}},{"../../lib/html2unicode":1126,"../../lib/show_no_webgl_msg":1137,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"./camera":1181,"./convert":1182,"gl-plot2d":452,"gl-select-box":937,"gl-spikes2d":938}],1185:[function(t,e,r){"use strict";function n(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]),"zoomMin"in e&&(r[0]=e.zoomMin),"zoomMax"in e&&(r[1]=e.zoomMax);var n=a({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],u=0,c=t.clientWidth,f=t.clientHeight,h={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=i(),r=this.delay,a=e-2*r;n.idle(e-r),n.recalcMatrix(a),n.flush(e-(100+2*r));for(var o=!0,s=n.computedMatrix,h=0;16>h;++h)o=o&&l[h]===s[h],l[h]=s[h];var p=t.clientWidth===c&&t.clientHeight===f;return c=t.clientWidth,f=t.clientHeight,o?!p:(u=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),a=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var o=i();n._active.lookAt(o,r,a,e),n._active.lookAt(o+500,r,a,[0,0,1]),n._active.flush(o)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return u},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var p=0,d=0;return o(t,function(e,r,a,o){var s="rotate"===h.keyBindingMode,l="pan"===h.keyBindingMode,c="zoom"===h.keyBindingMode,f=!!o.control,g=!!o.alt,v=!!o.shift,m=!!(1&e),y=!!(2&e),b=!!(4&e),x=1/t.clientHeight,_=x*(r-p),w=x*(a-d),k=h.flipX?1:-1,A=h.flipY?1:-1,M=i(),T=Math.PI*h.rotateSpeed;if((s&&m&&!f&&!g&&!v||m&&!f&&!g&&v)&&n.rotate(M,k*T*_,-A*T*w,0),(l&&m&&!f&&!g&&!v||y||m&&f&&!g&&!v)&&n.pan(M,-h.translateSpeed*_*u,h.translateSpeed*w*u,0),c&&m&&!f&&!g&&!v||b||m&&!f&&g&&!v){var E=-h.zoomSpeed*w/window.innerHeight*(M-n.lastT())*100;n.pan(M,0,0,u*(Math.exp(E)-1))}return p=r,d=a,!0}),s(t,function(t,e){var r=h.flipX?1:-1,a=h.flipY?1:-1,o=i();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*h.rotateSpeed/window.innerWidth);else{var s=-h.zoomSpeed*a*e/window.innerHeight*(o-n.lastT())/100;n.pan(o,0,0,u*(Math.exp(s)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":45,"mouse-change":1004,"mouse-wheel":1008,"right-now":1034}],1186:[function(t,e,r){"use strict";function n(t,e){for(var r=0;3>r;++r){var n=s[r];e[n]._gd=t}}var i=t("./scene"),a=t("../plots"),o=t("../../constants/xmlns_namespaces"),s=["xaxis","yaxis","zaxis"];r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,o=a.getSubplotIds(e,"gl3d");e._paperdiv.style({width:e.width+"px",height:e.height+"px"}),t._context.setBackground(t,e.paper_bgcolor);for(var s=0;sr;++r){var n=t[u[r]];e.labels[r]=o(n.title),"titlefont"in n&&(n.titlefont.color&&(e.labelColor[r]=s(n.titlefont.color)),n.titlefont.family&&(e.labelFont[r]=n.titlefont.family),n.titlefont.size&&(e.labelSize[r]=n.titlefont.size)),"showline"in n&&(e.lineEnable[r]=n.showline),"linecolor"in n&&(e.lineColor[r]=s(n.linecolor)),"linewidth"in n&&(e.lineWidth[r]=n.linewidth),"showgrid"in n&&(e.gridEnable[r]=n.showgrid),"gridcolor"in n&&(e.gridColor[r]=s(n.gridcolor)),"gridwidth"in n&&(e.gridWidth[r]=n.gridwidth),"log"===n.type?e.zeroEnable[r]=!1:"zeroline"in n&&(e.zeroEnable[r]=n.zeroline),"zerolinecolor"in n&&(e.zeroLineColor[r]=s(n.zerolinecolor)),"zerolinewidth"in n&&(e.zeroLineWidth[r]=n.zerolinewidth),"ticks"in n&&n.ticks?e.lineTickEnable[r]=!0:e.lineTickEnable[r]=!1,"ticklen"in n&&(e.lineTickLength[r]=e._defaultLineTickLength[r]=n.ticklen),"tickcolor"in n&&(e.lineTickColor[r]=s(n.tickcolor)),"tickwidth"in n&&(e.lineTickWidth[r]=n.tickwidth),"tickangle"in n&&(e.tickAngle[r]="auto"===n.tickangle?0:Math.PI*-n.tickangle/180),"showticklabels"in n&&(e.tickEnable[r]=n.showticklabels),"tickfont"in n&&(n.tickfont.color&&(e.tickColor[r]=s(n.tickfont.color)),n.tickfont.family&&(e.tickFont[r]=n.tickfont.family),n.tickfont.size&&(e.tickSize[r]=n.tickfont.size)),"mirror"in n?-1!==["ticks","all","allticks"].indexOf(n.mirror)?(e.lineTickMirror[r]=!0,e.lineMirror[r]=!0):n.mirror===!0?(e.lineTickMirror[r]=!1,e.lineMirror[r]=!0):(e.lineTickMirror[r]=!1,e.lineMirror[r]=!1):e.lineMirror[r]=!1,"showbackground"in n&&n.showbackground!==!1?(e.backgroundEnable[r]=!0,e.backgroundColor[r]=s(n.backgroundcolor)):e.backgroundEnable[r]=!1}},e.exports=i},{"../../../lib/html2unicode":1126,"../../../lib/str2rgbarray":1139,arraytools:64}],1191:[function(t,e,r){"use strict";function n(t,e,r,n){for(var a=r("bgcolor"),l=i.combine(a,n.paper_bgcolor),u=Object.keys(o.camera),c=0;ce;++e){var r=t[o[e]];this.enabled[e]=r.showspikes,this.colors[e]=a(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness}},e.exports=i},{"../../../lib/str2rgbarray":1139}],1194:[function(t,e,r){"use strict";function n(t){for(var e=new Array(3),r=0;3>r;++r){for(var n=t[r],i=new Array(n.length),a=0;ac;++c){var f=i[s[c]];if(f._length=(r[c].hi-r[c].lo)*r[c].pixelsPerDataUnit/t.dataScale[c],Math.abs(f._length)===1/0)u[c]=[];else{f.range[0]=r[c].lo/t.dataScale[c],f.range[1]=r[c].hi/t.dataScale[c],f._m=1/(t.dataScale[c]*r[c].pixelsPerDataUnit),f.range[0]===f.range[1]&&(f.range[0]-=1,f.range[1]+=1);var h=f.tickmode;if("auto"===f.tickmode){f.tickmode="linear";var p=f.nticks||a.Lib.constrain(f._length/40,4,9);a.Axes.autoTicks(f,Math.abs(f.range[1]-f.range[0])/p)}for(var d=a.Axes.calcTicks(f),g=0;gc;++c){l[c]=.5*(t.glplot.bounds[0][c]+t.glplot.bounds[1][c]);for(var g=0;2>g;++g)e.bounds[g][c]=t.glplot.bounds[g][c]}t.contourLevels=n(u)}e.exports=i;var a=t("../../../plotly"),o=t("../../../lib/html2unicode"),s=["xaxis","yaxis","zaxis"],l=[0,0,0]},{"../../../lib/html2unicode":1126,"../../../plotly":1147}],1195:[function(t,e,r){"use strict";function n(t,e){var r,n,i=[0,0,0,0];for(r=0;4>r;++r)for(n=0;4>n;++n)i[n]+=t[4*r+n]*e[r];return i}function i(t,e){var r=n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])));return r}e.exports=i},{}],1196:[function(t,e,r){"use strict";function n(t){function e(e,r){if("string"==typeof r)return r;var n=t.fullSceneLayout[e];return g.tickText(n,n.c2l(r),"hover").text}var r,n=t.svgContainer,i=t.container.getBoundingClientRect(),a=i.width,o=i.height;n.setAttributeNS(null,"viewBox","0 0 "+a+" "+o),n.setAttributeNS(null,"width",a),n.setAttributeNS(null,"height",o),A(t),t.glplot.axes.update(t.axesOptions);for(var s=Object.keys(t.traces),l=null,u=t.glplot.selection,c=0;ca;++a)l=c[T[a]],_(l);t?Array.isArray(t)||(t=[t]):t=[];var h=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]];for(a=0;ao;++o)h[0][o]>h[1][o]?p[o]=1:h[1][o]===h[0][o]?p[o]=1:p[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=p,a=0;aa;++a){if(l=c[T[a]],u=l.type,u in x?(x[u].acc*=p[a],x[u].count+=1):x[u]={acc:p[a],count:1},l.autorange){for(y[0][a]=1/0,y[1][a]=-(1/0),o=0;oy[1][a])y[0][a]=-1,y[1][a]=1;else{var k=y[1][a]-y[0][a];y[0][a]-=k/32,y[1][a]+=k/32}}else{var A=c[T[a]].range;y[0][a]=A[0],y[1][a]=A[1]}y[0][a]===y[1][a]&&(y[0][a]-=1,y[1][a]+=1),b[a]=y[1][a]-y[0][a],this.glplot.bounds[0][a]=y[0][a]*p[a],this.glplot.bounds[1][a]=y[1][a]*p[a]}var M=[1,1,1];for(a=0;3>a;++a){l=c[T[a]],u=l.type;var E=x[u];M[a]=Math.pow(E.acc,1/E.count)/p[a]}var L,S=4;if("auto"===c.aspectmode)L=Math.max.apply(null,M)/Math.min.apply(null,M)<=S?M:[1,1,1];else if("cube"===c.aspectmode)L=[1,1,1];else if("data"===c.aspectmode)L=M;else{if("manual"!==c.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var C=c.aspectratio;L=[C.x,C.y,C.z]}c.aspectratio.x=f.aspectratio.x=L[0],c.aspectratio.y=f.aspectratio.y=L[1],c.aspectratio.z=f.aspectratio.z=L[2],this.glplot.aspect=L;var z=c.domain||null,P=e._size||null;if(z&&P){var R=this.container.style;R.position="absolute",R.left=P.l+z.x[0]*P.w+"px",R.top=P.t+(1-z.y[1])*P.h+"px",R.width=P.w*(z.x[1]-z.x[0])+"px",R.height=P.h*(z.y[1]-z.y[0])+"px"}this.glplot.redraw()}},M.destroy=function(){this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null},M.setCameraToDefault=function(){this.setCamera({eye:{x:1.25,y:1.25,z:1.25},center:{x:0,y:0,z:0},up:{x:0,y:0,z:1}})},M.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),u(this.glplot.camera)},M.setCamera=function(t){var e={};e[this.id]=t,this.glplot.camera.lookAt.apply(this,l(t)),this.graphDiv.emit("plotly_relayout",e)},M.saveCamera=function(t){function e(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}var r=this.getCamera(),n=p.nestedProperty(t,this.id+".camera"),i=n.get(),a=!1;if(void 0===i)a=!0;else for(var o=0;3>o;o++)for(var s=0;3>s;s++)if(!e(r,i,o,s)){a=!0;break}return a&&n.set(r),a},M.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},M.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(c),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;o>a;++a,--o)for(var s=0;r>s;++s)for(var l=0;4>l;++l){var u=i[4*(r*a+s)+l];i[4*(r*a+s)+l]=i[4*(r*o+s)+l],i[4*(r*o+s)+l]=u}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),p=h.createImageData(r,n);p.data.set(i),h.putImageData(p,0,0);var d;switch(t){case"jpeg":d=f.toDataURL("image/jpeg");break;case"webp":d=f.toDataURL("image/webp");break;default:d=f.toDataURL("image/png")}return this.staticMode&&this.container.removeChild(c),d},e.exports=a},{"../../lib":1127,"../../lib/show_no_webgl_msg":1137,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../../plots/plots":1199,"./camera":1185,"./layout/convert":1190,"./layout/spikes":1193,"./layout/tick_marks":1194,"./project":1195,"./set_convert":1197,"gl-plot3d":626}],1197:[function(t,e,r){"use strict";var n=t("../cartesian/axes"),i=function(){};e.exports=function(t){n.setConvert(t),t.setScale=i}},{"../cartesian/axes":1150}],1198:[function(t,e,r){"use strict";var n=t("../plotly"),i=t("./font_attributes"),a=t("../components/color/attributes"),o=n.Lib.extendFlat;e.exports={font:{family:o({},i.family,{dflt:'"Open Sans", verdana, arial, sans-serif'}),size:o({},i.size,{dflt:12}),color:o({},i.color,{dflt:a.defaultLine})},title:{valType:"string",dflt:"Click to enter Plot title"},titlefont:o({},i,{}),autosize:{valType:"enumerated",values:[!0,!1,"initial"]},width:{valType:"number",min:10,dflt:700},height:{valType:"number",min:10,dflt:450},margin:{l:{valType:"number",min:0,dflt:80},r:{valType:"number",min:0,dflt:80},t:{valType:"number",min:0,dflt:100},b:{valType:"number",min:0,dflt:80},pad:{valType:"number",min:0,dflt:0},autoexpand:{valType:"boolean",dflt:!0}},paper_bgcolor:{valType:"color",dflt:a.background},plot_bgcolor:{valType:"color",dflt:a.background},separators:{valType:"string",dflt:".,"},hidesources:{valType:"boolean",dflt:!1},smith:{valType:"enumerated",values:[!1],dflt:!1},showlegend:{valType:"boolean"},_composedModules:{"*":"Fx"},_nestedModules:{xaxis:"Axes",yaxis:"Axes",scene:"gl3d",geo:"geo",legend:"Legend",annotations:"Annotations",shapes:"Shapes",images:"Images",ternary:"ternary",mapbox:"mapbox"}}},{"../components/color/attributes":1047,"../plotly":1147,"./font_attributes":1168}],1199:[function(t,e,r){"use strict";function n(t){return"object"==typeof t&&(t=t.type),t}function i(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#","class":"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){f.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}function a(t,e){for(var r,n=Object.keys(e),i=0;i=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var s=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),u=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&i(t,s),l.text(s.text()&&u.text()?" - ":"")},f.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=o.select(t).append("div").attr("id","hiddenform").style("display","none"),n=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"}),i=n.append("input").attr({type:"text",name:"data"});return i.node().value=f.graphJson(t,!1,"keepdata"),n.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1},f.supplyDefaults=function(t){var e,r,n=t._fullLayout||{},i=t._fullLayout={},o=t.layout||{},s=t._fullData||[],c=t._fullData=[],h=t.data||[],p=i._modules=[],d=i._basePlotModules=[];for(f.supplyLayoutGlobalDefaults(o,i),i._dataLength=h.length,e=0;ea&&(e=(r-1)/(i.l+i.r),i.l=Math.floor(e*i.l),i.r=Math.floor(e*i.r)),0>o&&(e=(n-1)/(i.t+i.b),i.t=Math.floor(e*i.t),i.b=Math.floor(e*i.b))}},f.autoMargin=function(t,e,r){var n=t._fullLayout;if(n._pushmargin||(n._pushmargin={}),n.margin.autoexpand!==!1){if(r){var i=void 0===r.pad?12:r.pad;r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];t._replotting||f.doAutoMargin(t)}},f.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),a=Math.max(e.margin.r||0,0),o=Math.max(e.margin.t||0,0),u=Math.max(e.margin.b||0,0),c=e._pushmargin;return e.margin.autoexpand!==!1&&(c.base={l:{val:0,size:i},r:{val:1,size:a},t:{val:1,size:o},b:{val:0,size:u}},Object.keys(c).forEach(function(t){var r=c[t].l||{},n=c[t].b||{},l=r.val,f=r.size,h=n.val,p=n.size;Object.keys(c).forEach(function(t){if(s(f)&&c[t].r){var r=c[t].r.val,n=c[t].r.size;if(r>l){var d=(f*r+(n-e.width)*l)/(r-l),g=(n*(1-l)+(f-e.width)*(1-r))/(r-l);d>=0&&g>=0&&d+g>i+a&&(i=d,a=g)}}if(s(p)&&c[t].t){var v=c[t].t.val,m=c[t].t.size;if(v>h){var y=(p*v+(m-e.height)*h)/(v-h),b=(m*(1-h)+(p-e.height)*(1-v))/(v-h);y>=0&&b>=0&&y+b>u+o&&(u=y,o=b)}}})})),r.l=Math.round(i),r.r=Math.round(a),r.t=Math.round(o),r.b=Math.round(u),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,t._replotting||"{}"===n||n===JSON.stringify(e._size)?void 0:l.plot(t)},f.graphJson=function(t,e,r,n,i){function a(t){if("function"==typeof t)return null;if(u.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0&&!u.isPlainObject(t.stream))continue}else if("keepall"!==r&&(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0))continue;i[e]=a(t[e])}return i}return Array.isArray(t)?t.map(a):t&&t.getTime?u.ms2DateTime(t):t}(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&f.supplyDefaults(t);var o=i?t._fullData:t.data,s=i?t._fullLayout:t.layout,l={data:(o||[]).map(function(t){var r=a(t);return e&&delete r.fit,r})};return e||(l.layout=a(s)),t.framework&&t.framework.isPolar&&(l=t.framework.getConfig()),"object"===n?l:JSON.stringify(l)}},{"../components/color":1048,"../lib":1127,"../plotly":1147,"./attributes":1148,"./font_attributes":1168,"./layout_attributes":1198,d3:82,"fast-isnumeric":90}],1200:[function(t,e,r){"use strict";var n=t("../../traces/scatter/attributes"),i=n.marker;e.exports={r:n.r,t:n.t,marker:{color:i.color,size:i.size,symbol:i.symbol,opacity:i.opacity}}},{"../../traces/scatter/attributes":1301}],1201:[function(t,e,r){"use strict";function n(t,e){var r={showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}};return a({},e,r)}var i=t("../cartesian/layout_attributes"),a=t("../../lib/extend").extendFlat,o=a({},i.domain,{});e.exports={radialaxis:n("radial",{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:n("angular",{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}}},{"../../lib/extend":1122,"../cartesian/layout_attributes":1159}],1202:[function(t,e,r){var n=t("../../plotly"),i=t("d3"),a=e.exports={version:"0.2.2",manager:t("./micropolar_manager")},o=n.Lib.extendDeepAll;a.Axis=function(){function t(t){r=t||r;var u=l.data,f=l.layout;return("string"==typeof r||r.nodeName)&&(r=i.select(r)),r.datum(u).each(function(t,r){function l(t,e){return s(t)%360+f.orientation}var u=t.slice();c={data:a.util.cloneJson(u),layout:a.util.cloneJson(f)};var h=0;u.forEach(function(t,e){t.color||(t.color=f.defaultColorRange[h],h=(h+1)%f.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:i.rgb(t.color).darker().toString()),c.data[e].color=t.color,c.data[e].strokeColor=t.strokeColor,c.data[e].strokeDash=t.strokeDash,c.data[e].strokeSize=t.strokeSize});var p=u.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||r===!0}),d=!1,g=p.map(function(t,e){return d=d||"undefined"!=typeof t.groupId,t});if(d){var v=i.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),m=[],y=v.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],m.push(r),r=a.util.sumArrays(t.r,r)}),t.values});p=i.merge(y)}p.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var b=Math.min(f.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2;b=Math.max(10,b);var x,_=[f.margin.left+b,f.margin.top+b];if(d){var w=i.max(a.util.sumArrays(a.util.arrayLast(p).r[0],a.util.arrayLast(m)));x=[0,w]}else x=i.extent(a.util.flattenArray(p.map(function(t,e){return t.r})));f.radialAxis.domain!=a.DATAEXTENT&&(x[0]=0),n=i.scale.linear().domain(f.radialAxis.domain!=a.DATAEXTENT&&f.radialAxis.domain?f.radialAxis.domain:x).range([0,b]),c.layout.radialAxis.domain=n.domain();var k,A=a.util.flattenArray(p.map(function(t,e){return t.t})),M="string"==typeof A[0];M&&(A=a.util.deduplicate(A),k=A.slice(),A=i.range(A.length),p=p.map(function(t,e){var r=t;return t.t=[A],d&&(r.yStack=t.yStack),r}));var T=p.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===p.length,E=null===f.needsEndSpacing?M||!T:f.needsEndSpacing,L=f.angularAxis.domain&&f.angularAxis.domain!=a.DATAEXTENT&&!M&&f.angularAxis.domain[0]>=0,S=L?f.angularAxis.domain:i.extent(A),C=Math.abs(A[1]-A[0]);T&&!M&&(C=0);var z=S.slice();E&&M&&(z[1]+=C);var P=f.angularAxis.ticksCount||4;P>8&&(P=P/(P/8)+P%8),f.angularAxis.ticksStep&&(P=(z[1]-z[0])/P);var R=f.angularAxis.ticksStep||(z[1]-z[0])/(P*(f.minorTicks+1));k&&(R=Math.max(Math.round(R),1)),z[2]||(z[2]=R);var j=i.range.apply(this,z);if(j=j.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=i.scale.linear().domain(z.slice(0,2)).range("clockwise"===f.direction?[0,360]:[360,0]),c.layout.angularAxis.domain=s.domain(),c.layout.angularAxis.endPadding=E?C:0,e=i.select(this).select("svg.chart-root"),"undefined"==typeof e||e.empty()){var O="' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '",I=(new DOMParser).parseFromString(O,"application/xml"),N=this.appendChild(this.ownerDocument.importNode(I.documentElement,!0));e=i.select(N)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var F,D=e.select(".chart-group"),B={fill:"none",stroke:f.tickColor},U={"font-size":f.font.size,"font-family":f.font.family,fill:f.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+f.font.outlineColor}).join(",")};if(f.showLegend){F=e.select(".legend-group").attr({transform:"translate("+[b,f.margin.top]+")"}).style({display:"block"});var V=p.map(function(t,e){var r=a.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});a.Legend().config({data:p.map(function(t,e){return t.name||"Element"+e}),legendConfig:o({},a.Legend.defaultConfig().legendConfig,{container:F,elements:V,reverseOrder:f.legend.reverseOrder})})();var q=F.node().getBBox();b=Math.min(f.width-q.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2,b=Math.max(10,b),_=[f.margin.left+b,f.margin.top+b],n.range([0,b]),c.layout.radialAxis.domain=n.domain(),F.attr("transform","translate("+[_[0]+b,_[1]-b]+")")}else F=e.select(".legend-group").style({display:"none"});e.attr({width:f.width,height:f.height}).style({opacity:f.opacity}),D.attr("transform","translate("+_+")").style({cursor:"crosshair"});var G=[(f.width-(f.margin.left+f.margin.right+2*b+(q?q.width:0)))/2,(f.height-(f.margin.top+f.margin.bottom+2*b))/2];if(G[0]=Math.max(0,G[0]),G[1]=Math.max(0,G[1]),e.select(".outer-group").attr("transform","translate("+G+")"),f.title){var H=e.select("g.title-group text").style(U).text(f.title),Y=H.node().getBBox();H.attr({x:_[0]-Y.width/2,y:_[1]-b-20})}var X=e.select(".radial.axis-group");if(f.radialAxis.gridLinesVisible){var W=X.selectAll("circle.grid-circle").data(n.ticks(5));W.enter().append("circle").attr({"class":"grid-circle"}).style(B),W.attr("r",n),W.exit().remove()}X.select("circle.outside-circle").attr({r:b}).style(B);var Z=e.select("circle.background-circle").attr({r:b}).style({fill:f.backgroundColor,stroke:f.stroke});if(f.radialAxis.visible){var K=i.svg.axis().scale(n).ticks(5).tickSize(5);X.call(K).attr({transform:"rotate("+f.radialAxis.orientation+")"}),X.selectAll(".domain").style(B),X.selectAll("g>text").text(function(t,e){return this.textContent+f.radialAxis.ticksSuffix}).style(U).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===f.radialAxis.tickOrientation?"rotate("+-f.radialAxis.orientation+") translate("+[0,U["font-size"]]+")":"translate("+[0,U["font-size"]]+")"}}),X.selectAll("g>line").style({stroke:"black"})}var $=e.select(".angular.axis-group").selectAll("g.angular-tick").data(j),Q=$.enter().append("g").classed("angular-tick",!0);$.attr({transform:function(t,e){return"rotate("+l(t,e)+")"}}).style({display:f.angularAxis.visible?"block":"none"}),$.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(f.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(f.minorTicks+1)==0)}).style(B),Q.selectAll(".minor").style({stroke:f.minorTickColor}),$.select("line.grid-line").attr({x1:f.tickLength?b-f.tickLength:0,x2:b}).style({display:f.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(U);var J=$.select("text.axis-text").attr({x:b+f.labelOffset,dy:".35em",transform:function(t,e){var r=l(t,e),n=b+f.labelOffset,i=f.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?270>r&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(180>=r&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:f.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(f.minorTicks+1)!=0?"":k?k[t]+f.angularAxis.ticksSuffix:t+f.angularAxis.ticksSuffix}).style(U);f.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(f.minorTicks+1)!=0?"":f.angularAxis.rewriteTicks(this.textContent,e)});var tt=i.max(D.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));F.attr({transform:"translate("+[b+tt,f.margin.top]+")"});var et=e.select("g.geometry-group").selectAll("g").size()>0,rt=e.select("g.geometry-group").selectAll("g.geometry").data(p);if(rt.enter().append("g").attr({"class":function(t,e){return"geometry geometry"+e}}),rt.exit().remove(),p[0]||et){var nt=[];p.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=s,r.container=rt.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=f.orientation,r.direction=f.direction,r.index=e,nt.push({data:t,geometryConfig:r})});var it=i.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(nt),at=[];it.forEach(function(t,e){"unstacked"===t.key?at=at.concat(t.values.map(function(t,e){return[t]})):at.push(t.values)}),at.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return o(a[r].defaultConfig(),t)});a[r]().config(n)()})}var ot,st,lt=e.select(".guides-group"),ut=e.select(".tooltips-group"),ct=a.tooltipPanel().config({container:ut,fontSize:8})(),ft=a.tooltipPanel().config({container:ut,fontSize:8})(),ht=a.tooltipPanel().config({container:ut,hasTick:!0})();if(!M){var pt=lt.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});D.on("mousemove.angular-guide",function(t,e){var r=a.util.getMousePos(Z).angle;pt.attr({x2:-b,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-f.orientation)%360;ot=s.invert(n);var i=a.util.convertToCartesian(b+12,r+180);ct.text(a.util.round(ot)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){lt.select("line").style({opacity:0})})}var dt=lt.select("circle").style({stroke:"grey",fill:"none"});D.on("mousemove.radial-guide",function(t,e){var r=a.util.getMousePos(Z).radius;dt.attr({r:r}).style({opacity:.5}),st=n.invert(a.util.getMousePos(Z).radius);var i=a.util.convertToCartesian(r,f.radialAxis.orientation);ft.text(a.util.round(st)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){dt.style({opacity:0}),ht.hide(),ct.hide(),ft.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(t,r){var n=i.select(this),o=n.style("fill"),s="black",l=n.style("opacity")||1;if(n.attr({"data-opacity":l}),"none"!=o){n.attr({"data-fill":o}),s=i.hsl(o).darker().toString(),n.style({fill:s,opacity:1});var u={t:a.util.round(t[0]),r:a.util.round(t[1])};M&&(u.t=k[t[0]]);var c="t: "+u.t+", r: "+u.r,f=this.getBoundingClientRect(),h=e.node().getBoundingClientRect(),p=[f.left+f.width/2-G[0]-h.left,f.top+f.height/2-G[1]-h.top];ht.config({color:s}).text(c),ht.move(p)}else o=n.style("stroke"),n.attr({"data-stroke":o}),s=i.hsl(o).darker().toString(),n.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){return 0!=i.event.which?!1:void(i.select(this).attr("data-fill")&&ht.show()); -}).on("mouseout.tooltip",function(t,e){ht.hide();var r=i.select(this),n=r.attr("data-fill");n?r.style({fill:n,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})}),h}var e,r,n,s,l={data:[],layout:{}},u={},c={},f=i.dispatch("hover"),h={};return h.render=function(e){return t(e),this},h.config=function(t){if(!arguments.length)return l;var e=a.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),o(l.data[e],a.Axis.defaultConfig().data[0]),o(l.data[e],t)}),o(l.layout,a.Axis.defaultConfig().layout),o(l.layout,e.layout),this},h.getLiveConfig=function(){return c},h.getinputConfig=function(){return u},h.radialScale=function(t){return n},h.angularScale=function(t){return s},h.svg=function(){return e},i.rebind(h,f,"on"),h},a.Axis.defaultConfig=function(t,e){var r={data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:i.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}};return r},a.util={},a.DATAEXTENT="dataExtent",a.AREA="AreaChart",a.LINE="LinePlot",a.DOT="DotPlot",a.BAR="BarChart",a.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},a.util._extend=function(t,e){for(var r in t)e[r]=t[r]},a.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},a.util.dataFromEquation2=function(t,e){var r=e||6,n=i.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180,i=t(n);return[e,i]});return n},a.util.dataFromEquation=function(t,e,r){var n=e||6,a=[],o=[];i.range(0,360+n,n).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},a.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return i.range(e).map(function(t,e){return r[e]||r[0]})},a.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=a.util.ensureArray(t[e],r)}),t},a.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},a.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},a.util.sumArrays=function(t,e){return i.zip(t,e).map(function(t,e){return i.sum(t)})},a.util.arrayLast=function(t){return t[t.length-1]},a.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},a.util.flattenArray=function(t){for(var e=[];!a.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},a.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},a.util.convertToCartesian=function(t,e){var r=e*Math.PI/180,n=t*Math.cos(r),i=t*Math.sin(r);return[n,i]},a.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},a.util.getMousePos=function(t){var e=i.mouse(t.node()),r=e[0],n=e[1],a={};return a.x=r,a.y=n,a.pos=e,a.angle=180*(Math.atan2(n,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+n*n),a},a.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;a>i;i++)e=t[i],e in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},a.util.duplicates=function(t){return Object.keys(a.util.duplicatesCount(t))},a.util.translator=function(t,e,r,n){if(n){var i=r.slice();r=e,e=i}var a=e.reduce(function(t,e){return"undefined"!=typeof t?t[e]:void 0},t);"undefined"!=typeof a&&(e.reduce(function(t,r,n){return"undefined"!=typeof t?(n===e.length-1&&delete t[r],t[r]):void 0},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=a),t[e]},t))},a.PolyChart=function(){function t(){var t=r[0].geometryConfig,e=t.container;"string"==typeof e&&(e=i.select(e)),e.datum(r).each(function(e,r){function n(e,r){var n=t.radialScale(e[1]),i=(t.angularScale(e[0])+t.orientation)*Math.PI/180;return{r:n,t:i}}function a(t){var e=t.r*Math.cos(t.t),r=t.r*Math.sin(t.t);return{x:e,y:r}}var o=!!e[0].data.yStack,l=e.map(function(t,e){return o?i.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):i.zip(t.data.t[0],t.data.r[0])}),u=t.angularScale,c=t.radialScale.domain()[0],f={};f.bar=function(r,n,a){var o=e[a].data,s=t.radialScale(r[1])-t.radialScale(0),l=t.radialScale(r[2]||0),c=o.barWidth;i.select(this).attr({"class":"mark bar",d:"M"+[[s+l,-c/2],[s+l,c/2],[l,c/2],[l,-c/2]].join("L")+"Z",transform:function(e,r){return"rotate("+(t.orientation+u(e[0]))+")"}})},f.dot=function(t,r,o){var s=t[2]?[t[0],t[1]+t[2]]:t,l=i.svg.symbol().size(e[o].data.dotSize).type(e[o].data.dotType)(t,r);i.select(this).attr({"class":"mark dot",d:l,transform:function(t,e){var r=a(n(s));return"translate("+[r.x,r.y]+")"}})};var h=i.svg.line.radial().interpolate(e[0].data.lineInterpolation).radius(function(e){return t.radialScale(e[1])}).angle(function(e){return t.angularScale(e[0])*Math.PI/180});f.line=function(r,n,a){var o=r[2]?l[a].map(function(t,e){return[t[0],t[1]+t[2]]}):l[a];if(i.select(this).each(f.dot).style({opacity:function(t,r){return+e[a].data.dotVisible},fill:v.stroke(r,n,a)}).attr({"class":"mark dot"}),!(n>0)){var s=i.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({"class":"line",d:h(o),transform:function(e,r){return"rotate("+(t.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return v.fill(r,n,a)},"fill-opacity":0,stroke:function(t,e){return v.stroke(r,n,a)},"stroke-width":function(t,e){return v["stroke-width"](r,n,a)},"stroke-dasharray":function(t,e){return v["stroke-dasharray"](r,n,a)},opacity:function(t,e){return v.opacity(r,n,a)},display:function(t,e){return v.display(r,n,a)}})}};var p=t.angularScale.range(),d=Math.abs(p[1]-p[0])/l[0].length*Math.PI/180,g=i.svg.arc().startAngle(function(t){return-d/2}).endAngle(function(t){return d/2}).innerRadius(function(e){return t.radialScale(c+(e[2]||0))}).outerRadius(function(e){return t.radialScale(c+(e[2]||0))+t.radialScale(e[1])});f.arc=function(e,r,n){i.select(this).attr({"class":"mark arc",d:g,transform:function(e,r){return"rotate("+(t.orientation+u(e[0])+90)+")"}})};var v={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,n){return s[e[n].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return"undefined"==typeof e[n].data.visible||e[n].data.visible?"block":"none"}},m=i.select(this).selectAll("g.layer").data(l);m.enter().append("g").attr({"class":"layer"});var y=m.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({"class":"mark"}),y.style(v).each(f[t.geometryType]),y.exit().remove(),m.exit().remove()})}var e,r=[a.PolyChart.defaultConfig()],n=i.dispatch("hover"),s={solid:"none",dash:[5,2],dot:[2,5]};return t.config=function(t){return arguments.length?(t.forEach(function(t,e){r[e]||(r[e]={}),o(r[e],a.PolyChart.defaultConfig()),o(r[e],t)}),this):r},t.getColorScale=function(){return e},i.rebind(t,n,"on"),t},a.PolyChart.defaultConfig=function(){var t={data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:i.scale.category20()}};return t},a.BarChart=function(){return a.PolyChart()},a.BarChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"bar"}};return t},a.AreaChart=function(){return a.PolyChart()},a.AreaChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"arc"}};return t},a.DotPlot=function(){return a.PolyChart()},a.DotPlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"dot",dotType:"circle"}};return t},a.LinePlot=function(){return a.PolyChart()},a.LinePlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"line"}};return t},a.Legend=function(){function t(){var r=e.legendConfig,n=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=o({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=i.merge(n);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||"undefined"==typeof r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var s=r.container;("string"==typeof s||s.nodeName)&&(s=i.select(s));var l=a.map(function(t,e){return t.color}),u=r.fontSize,c=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,f=c?r.height:u*a.length,h=s.classed("legend-group",!0),p=h.selectAll("svg").data([0]),d=p.enter().append("svg").attr({width:300,height:f+u,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});d.append("g").classed("legend-axis",!0),d.append("g").classed("legend-marks",!0);var g=i.range(a.length),v=i.scale[c?"linear":"ordinal"]().domain(g).range(l),m=i.scale[c?"linear":"ordinal"]().domain(g)[c?"range":"rangePoints"]([0,f]),y=function(t,e){var r=3*e;return"line"===t?"M"+[[-e/2,-e/12],[e/2,-e/12],[e/2,e/12],[-e/2,e/12]]+"Z":-1!=i.svg.symbolTypes.indexOf(t)?i.svg.symbol().type(t).size(r)():i.svg.symbol().type("square").size(r)()};if(c){var b=p.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);b.enter().append("stop"),b.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),p.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var x=p.select(".legend-marks").selectAll("path.legend-mark").data(a);x.enter().append("path").classed("legend-mark",!0),x.attr({transform:function(t,e){return"translate("+[u/2,m(e)+u/2]+")"},d:function(t,e){var r=t.symbol;return y(r,u)},fill:function(t,e){return v(e)}}),x.exit().remove()}var _=i.svg.axis().scale(m).orient("right"),w=p.select("g.legend-axis").attr({transform:"translate("+[c?r.colorBandWidth:u,u/2]+")"}).call(_);return w.selectAll(".domain").style({fill:"none",stroke:"none"}),w.selectAll("line").style({fill:"none",stroke:c?r.textColor:"none"}),w.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),t}var e=a.Legend.defaultConfig(),r=i.dispatch("hover");return t.config=function(t){return arguments.length?(o(e,t),this):e},i.rebind(t,r,"on"),t},a.Legend.defaultConfig=function(t,e){var r={data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}};return r},a.tooltipPanel=function(){var t,e,r,n={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+a.tooltipPanel.uid++,l=10,u=function(){t=n.container.selectAll("g."+s).data([0]);var i=t.enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=i.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=i.append("text").attr({dx:n.padding+l,dy:.3*+n.fontSize}),u};return u.text=function(a){var o=i.hsl(n.color).l,s=o>=.5?"#aaa":"white",c=o>=.5?"black":"white",f=a||"";e.style({fill:c,"font-size":n.fontSize+"px"}).text(f);var h=n.padding,p=e.node().getBBox(),d={fill:n.color,stroke:s,"stroke-width":"2px"},g=p.width+2*h+l,v=p.height+2*h;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[n.hasTick?0:l,0],[l,v/4],[l,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(d),t.attr({transform:"translate("+[l,-v/2+2*h]+")"}),t.style({display:"block"}),u},u.move=function(e){return t?(t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),u):void 0},u.hide=function(){return t?(t.style({display:"none"}),u):void 0},u.show=function(){return t?(t.style({display:"block"}),u):void 0},u.config=function(t){return o(n,t),u},u},a.tooltipPanel.uid=1,a.adapter={},a.adapter.plotly=function(){var t={};return t.convert=function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=o({},t),i=[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]];return i.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",n.dotVisible===!0?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var n=a.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var i=n.indexOf(t.geometry);-1!=i&&(r.data[e].groupId=i)})}if(t.layout){var s=o({},t.layout),l=[[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]];if(l.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&"undefined"!=typeof s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&"undefined"!=typeof s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&"undefined"!=typeof s.margin.t){var u=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],f={};i.entries(s.margin).forEach(function(t,e){f[c[u.indexOf(t.key)]]=t.value}),s.margin=f}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r},t}},{"../../plotly":1147,"./micropolar_manager":1203,d3:82}],1203:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("d3"),a=t("./undo_manager"),o=e.exports={},s=n.Lib.extendDeepAll;o.framework=function(t){function e(e,a){return a&&(f=a),i.select(i.select(f).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),r=r?s(r,e):e,u||(u=n.micropolar.Axis()),c=n.micropolar.adapter.plotly().convert(r),u.config(c).render(f),t.data=r.data,t.layout=r.layout,o.fillLayout(t),r}var r,l,u,c,f,h=new a;return e.isPolar=!0,e.svg=function(){return u.svg()},e.getConfig=function(){return r},e.getLiveConfig=function(){return n.micropolar.adapter.plotly().convert(u.getLiveConfig(),!0)},e.getLiveScales=function(){return{t:u.angularScale(),r:u.radialScale()}},e.setUndoPoint=function(){var t=this,e=n.micropolar.util.cloneJson(r);!function(e,r){h.add({undo:function(){r&&t(r)},redo:function(){t(e)}})}(e,l),l=n.micropolar.util.cloneJson(e)},e.undo=function(){h.undo()},e.redo=function(){h.redo()},e},o.fillLayout=function(t){var e=i.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:n.Color.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../plotly":1147,"./undo_manager":1204,d3:82}],1204:[function(t,e,r){"use strict";e.exports=function(){function t(t,e){return t?(i=!0,t[e](),i=!1,this):this}var e,r=[],n=-1,i=!1;return{add:function(t){return i?this:(r.splice(n+1,r.length-n),r.push(t),n=r.length-1,this)},setCallback:function(t){e=t},undo:function(){var i=r[n];return i?(t(i,"undo"),n-=1,e&&e(i.undo),this):this},redo:function(){var i=r[n+1];return i?(t(i,"redo"),n+=1,e&&e(i.redo),this):this},clear:function(){r=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return ng;g++){var v=p[g];s=t[v]?t[v]:t[v]={},e[v]=l={},o("domain."+h,[g/d,(g+1)/d]),o("domain."+{x:"y",y:"x"}[h]),a.id=v,f(s,l,o,a)}}},{"../lib":1127,"./plots":1199}],1206:[function(t,e,r){"use strict";var n=t("./ternary"),i=t("../../plots/plots");r.name="ternary",r.attr="subplot",r.idRoot="ternary",r.idRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"ternary"),o=0;o=o&&(p.min=0,d.min=0,g.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}var i=t("../../../components/color"),a=t("../../subplot_defaults"),o=t("./layout_attributes"),s=t("./axis_defaults"),l=["aaxis","baxis","caxis"];e.exports=function(t,e,r){a(t,e,r,{type:"ternary",attributes:o,handleDefaults:n,font:e.font,paper_bgcolor:e.paper_bgcolor})}},{"../../../components/color":1048,"../../subplot_defaults":1205,"./axis_defaults":1209,"./layout_attributes":1211}],1211:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("./axis_attributes");e.exports={domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},bgcolor:{valType:"color",dflt:n.background},sum:{valType:"number",dflt:1,min:0},aaxis:i,baxis:i,caxis:i}},{"../../../components/color/attributes":1047,"./axis_attributes":1208}],1212:[function(t,e,r){"use strict";function n(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework()}function i(t){a.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var a=t("d3"),o=t("tinycolor2"),s=t("../../plotly"),l=t("../../lib"),u=t("../../components/color"),c=t("../../components/drawing"),f=t("../cartesian/set_convert"),h=t("../../lib/extend").extendFlat,p=t("../cartesian/axes"),d=t("../../lib/filter_visible"),g=t("../../components/dragelement"),v=t("../../components/titles"),m=t("../cartesian/select"),y=t("../cartesian/constants"),b=t("../cartesian/graph_interact");e.exports=n;var x=n.prototype;x.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={}},x.plot=function(t,e){var r,n=this,i=e[n.id],a=e._size;l.getPlotDiv(n.plotContainer.node())!==n.graphDiv&&(n.init(n.graphDiv._fullLayout),n.makeFramework()),n.adjustLayout(i,a);var o=n.traceHash,s={};for(r=0;r_*y?(a=y,i=a*_):(i=m,a=i/_),o=g*i/m,s=v*a/y,r=e.l+e.w*p-i/2,n=e.t+e.h*(1-d)-a/2,l.x0=r,l.y0=n,l.w=i,l.h=a,l.sum=b,l.xaxis={type:"linear",range:[x+2*k-b,b-x-2*w],domain:[p-o/2,p+o/2],_id:"x",_gd:l.graphDiv},f(l.xaxis),l.xaxis.setScale(),l.yaxis={type:"linear",range:[x,b-w-k],domain:[d-s/2,d+s/2],_id:"y",_gd:l.graphDiv},f(l.yaxis),l.yaxis.setScale();var A=l.yaxis.domain[0],M=l.aaxis=h({},t.aaxis,{range:[x,b-w-k],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[A,A+s*_],_axislayer:l.layers.aaxis,_gridlayer:l.layers.agrid,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2});f(M);var T=l.baxis=h({},t.baxis,{range:[b-x-k,w],side:"bottom",_counterangle:30,domain:l.xaxis.domain,_axislayer:l.layers.baxis,_gridlayer:l.layers.bgrid,_counteraxis:l.aaxis,_pos:0,_gd:l.graphDiv,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a});f(T),M._counteraxis=T;var E=l.caxis=h({},t.caxis,{range:[b-x-w,k],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[A,A+s*_],_axislayer:l.layers.caxis,_gridlayer:l.layers.cgrid,_counteraxis:l.baxis,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2});f(E);var L="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDef.select("path").attr("d",L),l.layers.plotbg.select("path").attr("d",L);var S="translate("+r+","+n+")";l.plotContainer.selectAll(".scatterlayer,.maplayer,.zoom").attr("transform",S);var C="translate("+r+","+(n+a)+")";l.layers.baxis.attr("transform",C),l.layers.bgrid.attr("transform",C);var z="translate("+(r+i/2)+","+n+")rotate(30)";l.layers.aaxis.attr("transform",z),l.layers.agrid.attr("transform",z);var P="translate("+(r+i/2)+","+n+")rotate(-30)";l.layers.caxis.attr("transform",P),l.layers.cgrid.attr("transform",P),l.drawAxes(!0),l.plotContainer.selectAll(".crisp").classed("crisp",!1);var R=l.layers.axlines;R.select(".aline").attr("d",M.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(u.stroke,M.linecolor||"#000").style("stroke-width",(M.linewidth||0)+"px"),R.select(".bline").attr("d",T.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(u.stroke,T.linecolor||"#000").style("stroke-width",(T.linewidth||0)+"px"),R.select(".cline").attr("d",E.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(u.stroke,E.linecolor||"#000").style("stroke-width",(E.linewidth||0)+"px")},x.drawAxes=function(t){var e=this,r=e.graphDiv,n=e.id.substr(7)+"title",i=e.aaxis,a=e.baxis,o=e.caxis;if(p.doTicks(r,i,!0),p.doTicks(r,a,!0),p.doTicks(r,o,!0),t){var s=Math.max(i.showticklabels?i.tickfont.size/2:0,(o.showticklabels?.75*o.tickfont.size:0)+("outside"===o.ticks?.87*o.ticklen:0));v.draw(r,"a"+n,{propContainer:i,propName:e.id+".aaxis.title",dfltName:"Component A",attributes:{x:e.x0+e.w/2,y:e.y0-i.titlefont.size/3-s,"text-anchor":"middle"}});var l=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;v.draw(r,"b"+n,{propContainer:a,propName:e.id+".baxis.title",dfltName:"Component B",attributes:{x:e.x0-l,y:e.y0+e.h+.83*a.titlefont.size+l,"text-anchor":"middle"}}),v.draw(r,"c"+n,{propContainer:o,propName:e.id+".caxis.title",dfltName:"Component C",attributes:{x:e.x0+e.w+l,y:e.y0+e.h+.83*o.titlefont.size+l,"text-anchor":"middle"}})}};var w=y.MINZOOM/2+.87,k="m-0.87,.5h"+w+"v3h-"+(w+5.2)+"l"+(w/2+2.6)+",-"+(.87*w+4.5)+"l2.6,1.5l-"+w/2+","+.87*w+"Z",A="m0.87,.5h-"+w+"v3h"+(w+5.2)+"l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-2.6,1.5l"+w/2+","+.87*w+"Z",M="m0,1l"+w/2+","+.87*w+"l2.6,-1.5l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-"+(w/2+2.6)+","+(.87*w+4.5)+"l2.6,1.5l"+w/2+",-"+.87*w+"Z",T="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",E=!0;x.initInteractions=function(){function t(t,e,r){var n=N.getBoundingClientRect();x=e-n.left,w=r-n.top,L={a:I.aaxis.range[0],b:I.baxis.range[1],c:I.caxis.range[1]},C=L,S=I.aaxis.range[1]-L.a,z=o(I.graphDiv._fullLayout[I.id].bgcolor).getLuminance(),P="M0,"+I.h+"L"+I.w/2+", 0L"+I.w+","+I.h+"Z",R=!1,j=D.append("path").attr("class","zoombox").style({fill:z>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",P),O=D.append("path").attr("class","zoombox-corners").style({fill:u.background,stroke:u.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),d()}function e(t,e){return 1-e/I.h}function r(t,e){return 1-(t+(I.h-e)/Math.sqrt(3))/I.w}function n(t,e){return(t-(I.h-e)/Math.sqrt(3))/I.w}function a(t,i){var a=x+t,o=w+i,s=Math.max(0,Math.min(1,e(x,w),e(a,o))),l=Math.max(0,Math.min(1,r(x,w),r(a,o))),u=Math.max(0,Math.min(1,n(x,w),n(a,o))),c=(s/2+u)*I.w,f=(1-s/2-l)*I.w,h=(c+f)/2,p=f-c,d=(1-s)*I.h,g=d-p/_;p.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),O.transition().style("opacity",1).duration(200),R=!0)}function c(t,e){if(C===L)return 2===e&&v(),i(F);i(F);var r={};r[I.id+".aaxis.min"]=C.a,r[I.id+".baxis.min"]=C.b,r[I.id+".caxis.min"]=C.c,s.relayout(F,r),E&&F.data&&F._context.showTips&&(l.notifier("Double-click to
zoom back out","long"),E=!1)}function f(){L={a:I.aaxis.range[0],b:I.baxis.range[1],c:I.caxis.range[1]},C=L}function h(t,e){var r=t/I.xaxis._m,n=e/I.yaxis._m;C={a:L.a-n,b:L.b+(r+n)/2,c:L.c-(r-n)/2};var i=[C.a,C.b,C.c].sort(),a={a:i.indexOf(C.a),b:i.indexOf(C.b),c:i.indexOf(C.c)};i[0]<0&&(i[1]+i[0]/2<0?(i[2]+=i[0]+i[1],i[0]=i[1]=0):(i[2]+=i[0]/2,i[1]+=i[0]/2,i[0]=0),C={a:i[a.a],b:i[a.b],c:i[a.c]},e=(L.a-C.a)*I.yaxis._m,t=(L.c-C.c-L.b+C.b)*I.xaxis._m);var o="translate("+(I.x0+t)+","+(I.y0+e)+")";I.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",o),I.aaxis.range=[C.a,I.sum-C.b-C.c],I.baxis.range=[I.sum-C.a-C.c,C.b], -I.caxis.range=[I.sum-C.a-C.b,C.c],I.drawAxes(!1),I.plotContainer.selectAll(".crisp").classed("crisp",!1)}function p(t,e){if(t){var r={};r[I.id+".aaxis.min"]=C.a,r[I.id+".baxis.min"]=C.b,r[I.id+".caxis.min"]=C.c,s.relayout(F,r)}else 2===e&&v()}function d(){I.plotContainer.selectAll(".select-outline").remove()}function v(){var t={};t[I.id+".aaxis.min"]=0,t[I.id+".baxis.min"]=0,t[I.id+".caxis.min"]=0,F.emit("plotly_doubleclick",null),s.relayout(F,t)}var x,w,L,S,C,z,P,R,j,O,I=this,N=I.layers.plotbg.select("path").node(),F=I.graphDiv,D=I.layers.zoom,B={element:N,gd:F,plotinfo:{plot:D},doubleclick:v,subplot:I.id,prepFn:function(e,r,n){B.xaxes=[I.xaxis],B.yaxes=[I.yaxis];var i=F._fullLayout.dragmode;e.shiftKey&&(i="pan"===i?"zoom":"pan"),"lasso"===i?B.minDrag=1:B.minDrag=void 0,"zoom"===i?(B.moveFn=a,B.doneFn=c,t(e,r,n)):"pan"===i?(B.moveFn=h,B.doneFn=p,f(),d()):"select"!==i&&"lasso"!==i||m(e,r,n,B,i)}};g.init(B),N.onmousemove=function(t){b.hover(F,t,I.id),F._fullLayout._lasthover=N,F._fullLayout._hoversubplot=I.id},N.onmouseout=function(t){F._dragging||g.unhover(F,t)},N.onclick=function(t){b.click(F,t)}}},{"../../components/color":1048,"../../components/dragelement":1069,"../../components/drawing":1071,"../../components/titles":1111,"../../lib":1127,"../../lib/extend":1122,"../../lib/filter_visible":1123,"../../plotly":1147,"../cartesian/axes":1150,"../cartesian/constants":1155,"../cartesian/graph_interact":1157,"../cartesian/select":1163,"../cartesian/set_convert":1164,d3:82,tinycolor2:1042}],1213:[function(t,e,r){"use strict";function n(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}function i(t){var e=["xaxis","yaxis","zaxis"];return e.indexOf(t.slice(0,5))>-1}var a=t("../plotly"),o=a.Lib.extendFlat,s=a.Lib.extendDeep;e.exports=function(t,e){t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var r,l=t.data,u=t.layout,c=s([],l),f=s({},u,n(e.tileClass));if(e.width&&(f.width=e.width),e.height&&(f.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){f.annotations=[];var h=Object.keys(f);for(r=0;rl;l++)n(r[l])&&p.push({p:r[l],s:s[l],b:0});return a(e,"marker")&&o(e,e.marker.color,"marker","c"),a(e,"marker.line")&&o(e,e.marker.line.color,"marker.line","c"),p}},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"../../plots/cartesian/axes":1150,"fast-isnumeric":90}],1223:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../scatter/xy_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,u){function c(r,i){return n.coerce(t,e,l,r,i)}var f=a(t,e,c);return f?(c("orientation",e.x&&!e.y?"h":"v"),c("text"),o(t,e,c,r,u),s(t,e,i.defaultLine,{axis:"y"}),void s(t,e,i.defaultLine,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"../scatter/xy_defaults":1324,"./attributes":1221}],1224:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../components/errorbars"),a=t("../../components/color");e.exports=function(t,e,r,o){var s,l=t.cd,u=l[0].trace,c=l[0].t,f=t.xa,h=t.ya,p="closest"===o?c.barwidth/2:c.dbar*(1-f._gd._fullLayout.bargap)/2;s="closest"!==o?function(t){return t.p}:"h"===u.orientation?function(t){return t.y}:function(t){return t.x};var d,g;"h"===u.orientation?(d=function(t){return n.inbox(t.b-e,t.x-e)+(t.x-e)/(t.x-t.b)},g=function(t){var e=s(t)-r;return n.inbox(e-p,e+p)}):(g=function(t){return n.inbox(t.b-r,t.y-r)+(t.y-r)/(t.y-t.b)},d=function(t){var r=s(t)-e;return n.inbox(r-p,r+p)});var v=n.getDistanceFunction(o,d,g);if(n.getClosest(l,v,t),t.index!==!1){var m=l[t.index],y=m.mcc||u.marker.color,b=m.mlcc||u.marker.line.color,x=m.mlw||u.marker.line.width;return a.opacity(y)?t.color=y:a.opacity(b)&&x&&(t.color=b),"h"===u.orientation?(t.x0=t.x1=f.c2p(m.x,!0),t.xLabelVal=m.s,t.y0=h.c2p(s(m)-p,!0),t.y1=h.c2p(s(m)+p,!0),t.yLabelVal=m.p):(t.y0=t.y1=h.c2p(m.y,!0),t.yLabelVal=m.s,t.x0=f.c2p(s(m)-p,!0),t.x1=f.c2p(s(m)+p,!0),t.xLabelVal=m.p),m.tx&&(t.text=m.tx),i.hoverInfo(m,u,t),[t]}}},{"../../components/color":1048,"../../components/errorbars":1077,"../../plots/cartesian/graph_interact":1157}],1225:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","oriented","markerColorscale","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../scatter/colorbar":1304,"./arrays_to_calcdata":1220,"./attributes":1221,"./calc":1222,"./defaults":1223,"./hover":1224,"./layout_attributes":1226,"./layout_defaults":1227,"./plot":1228,"./set_positions":1229,"./style":1230}],1226:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:""},bargap:{valType:"number",min:0,max:1},bargroupgap:{valType:"number",min:0,max:1,dflt:0}}},{}],1227:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function s(r,n){return a.coerce(t,e,o,r,n)}for(var l=!1,u=!1,c=!1,f={},h=0;h=2?a(t):t>e?Math.ceil(t):Math.floor(t)}var h,p,d,g;if("h"===s.orientation?(d=c.c2p(r.poffset+e.p,!0),g=c.c2p(r.poffset+e.p+r.barwidth,!0),h=u.c2p(e.b,!0),p=u.c2p(e.s+e.b,!0)):(h=u.c2p(r.poffset+e.p,!0),p=u.c2p(r.poffset+e.p+r.barwidth,!0),g=c.c2p(e.s+e.b,!0),d=c.c2p(e.b,!0)),!(i(h)&&i(p)&&i(d)&&i(g)&&h!==p&&d!==g))return void n.select(this).remove();var v=(e.mlw+1||s.marker.line.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,m=n.round(v/2%1,2);if(!t._context.staticPlot){var y=o.opacity(e.mc||s.marker.color),b=1>y||v>.01?a:l;h=b(h,p),p=b(p,h),d=b(d,g),g=b(g,d)}n.select(this).attr("d","M"+h+","+d+"V"+g+"H"+p+"V"+d+"Z")})}),h.call(s.plot,e)}},{"../../components/color":1048,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1220,d3:82,"fast-isnumeric":90}],1229:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axes"),o=t("../../lib");e.exports=function(t,e){var r,s,l=t._fullLayout,u=e.x(),c=e.y();["v","h"].forEach(function(f){function h(e){function r(t){t[d]=t.p+h}var n=[];e.forEach(function(e){t.calcdata[e].forEach(function(t){n.push(t.p)})});var i=o.distinctVals(n),s=i.vals,u=i.minDiff,c=!1,f=[];"group"===l.barmode&&e.forEach(function(e){c||(t.calcdata[e].forEach(function(t){c||f.forEach(function(e){Math.abs(t.p-e)_&&(S=!0,M=_),_>A+R&&(S=!0,A=_))}a.expand(m,[M,A],{tozero:!0,padded:S})}else{var j=function(t){return t[g]=t.s,t.s};for(r=0;r1||0===s.bargap&&0===s.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),e.selectAll("g.points").each(function(t){var e=t[0].trace,r=e.marker,o=r.line,s=(e._input||{}).marker||{},l=a.tryColorscale(r,s,""),u=a.tryColorscale(r,s,"line.");n.select(this).selectAll("path").each(function(t){var e,a,s=(t.mlw+1||o.width+1)-1,c=n.select(this);e="mc"in t?t.mcc=l(t.mc):Array.isArray(r.color)?i.defaultLine:r.color,c.style("stroke-width",s+"px").call(i.fill,e),s&&(a="mlc"in t?t.mlcc=u(t.mlc):Array.isArray(o.color)?i.defaultLine:o.color,c.call(i.stroke,a))})}),e.call(o.style)}},{"../../components/color":1048,"../../components/drawing":1071,"../../components/errorbars":1077,d3:82}],1231:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width")}},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061}],1232:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/color/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=o.line;e.exports={y:{valType:"data_array"},x:{valType:"data_array"},x0:{valType:"any"},y0:{valType:"any"},whiskerwidth:{valType:"number",min:0,max:1,dflt:.5},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1},jitter:{valType:"number",min:0,max:1},pointpos:{valType:"number",min:-2,max:2},orientation:{valType:"enumerated",values:["v","h"]},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)"},symbol:a({},o.symbol,{arrayOk:!1}),opacity:a({},o.opacity,{arrayOk:!1,dflt:1}),size:a({},o.size,{arrayOk:!1}),color:a({},o.color,{arrayOk:!1}),line:{color:a({},s.color,{arrayOk:!1,dflt:i.defaultLine}),width:a({},s.width,{arrayOk:!1,dflt:0}),outliercolor:{valType:"color"},outlierwidth:{valType:"number",min:0,dflt:1}}},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2}},fillcolor:n.fillcolor}},{"../../components/color/attributes":1047,"../../lib/extend":1122,"../scatter/attributes":1301}],1233:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes");e.exports=function(t,e){function r(t,e,r,a,o){var s;return r in e?d=a.makeCalcdata(e,r):(s=r+"0"in e?e[r+"0"]:"name"in e&&("category"===a.type||n(e.name)&&-1!==["linear","log"].indexOf(a.type)||i.isDateTime(e.name)&&"date"===a.type)?e.name:t.numboxes,s=a.d2c(s),d=o.map(function(){return s})),d}function o(t,e,r,a,o){var s,l,u,c,f=a.length,h=e.length,p=[],d=[];for(s=0;f>s;++s)l=a[s],t[s]={pos:l},d[s]=l-o,p[s]=[];for(d.push(a[f-1]+o),s=0;h>s;++s)c=e[s],n(c)&&(u=i.findBin(r[s],d),u>=0&&h>u&&p[u].push(c));return p}function s(t,e){var r,n,a,o;for(o=0;o1,m=r.dPos*(1-h.boxgap)*(1-h.boxgroupgap)/(v?t.numboxes:1),y=v?2*r.dPos*(-.5+(r.boxnum+.5)/t.numboxes)*(1-h.boxgap):0,b=m*g.whiskerwidth;return g.visible!==!0||r.emptybox?void a.select(this).remove():("h"===g.orientation?(l=d,f=p):(l=p,f=d),r.bPos=y,r.bdPos=m,n(),a.select(this).selectAll("path.box").data(o.identity).enter().append("path").attr("class","box").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=l.c2p(t.pos+y-b,!0),s=l.c2p(t.pos+y+b,!0),u=f.c2p(t.q1,!0),c=f.c2p(t.q3,!0),h=o.constrain(f.c2p(t.med,!0),Math.min(u,c)+1,Math.max(u,c)-1),p=f.c2p(g.boxpoints===!1?t.min:t.lf,!0),d=f.c2p(g.boxpoints===!1?t.max:t.uf,!0);"h"===g.orientation?a.select(this).attr("d","M"+h+","+r+"V"+n+"M"+u+","+r+"V"+n+"H"+c+"V"+r+"ZM"+u+","+e+"H"+p+"M"+c+","+e+"H"+d+(0===g.whiskerwidth?"":"M"+p+","+i+"V"+s+"M"+d+","+i+"V"+s)):a.select(this).attr("d","M"+r+","+h+"H"+n+"M"+r+","+u+"H"+n+"V"+c+"H"+r+"ZM"+e+","+u+"V"+p+"M"+e+","+c+"V"+d+(0===g.whiskerwidth?"":"M"+i+","+p+"H"+s+"M"+i+","+d+"H"+s))}),g.boxpoints&&a.select(this).selectAll("g.points").data(function(t){return t.forEach(function(t){t.t=r,t.trace=g}),t}).enter().append("g").attr("class","points").selectAll("path").data(function(t){var e,r,n,a,s,l,f,h="all"===g.boxpoints?t.val:t.val.filter(function(e){return et.uf}),p=(t.q3-t.q1)*c,d=[],v=0;if(g.jitter){for(e=0;et.lo&&(n.so=!0),n})}).enter().append("path").call(s.translatePoints,p,d),void(g.boxmean&&a.select(this).selectAll("path.mean").data(o.identity).enter().append("path").attr("class","mean").style("fill","none").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=f.c2p(t.mean,!0),o=f.c2p(t.mean-t.sd,!0),s=f.c2p(t.mean+t.sd,!0);"h"===g.orientation?a.select(this).attr("d","M"+i+","+r+"V"+n+("sd"!==g.boxmean?"":"m0,0L"+o+","+e+"L"+i+","+r+"L"+s+","+e+"Z")):a.select(this).attr("d","M"+r+","+i+"H"+n+("sd"!==g.boxmean?"":"m0,0L"+e+","+o+"L"+r+","+i+"L"+e+","+s+"Z"))})))})}},{"../../components/drawing":1071,"../../lib":1127,d3:82}],1240:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib");e.exports=function(t,e){var r,o,s,l,u=t._fullLayout,c=e.x(),f=e.y(),h=["v","h"];for(o=0;ol&&(e.z=c.slice(0,l)),s("locationmode"),s("text"),s("marker.line.color"),s("marker.line.width"),i(t,e,o,s,{prefix:"",cLetter:"z"}),void s("hoverinfo",1===o._dataLength?"location+z+text":void 0)):void(e.visible=!1)}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1242}],1245:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./plot").plot,n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":1171,"../heatmap/colorbar":1259,"./attributes":1242,"./calc":1243,"./defaults":1244,"./plot":1246}],1246:[function(t,e,r){"use strict";function n(t,e){function r(e){var r=t.mockAxis;return o.tickText(r,r.c2l(e),"hover").text}var n=e.hoverinfo;if("none"===n)return function(t){delete t.nameLabel, -delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("name"),s=-1!==i.indexOf("location"),l=-1!==i.indexOf("z"),u=-1!==i.indexOf("text"),c=!a&&s;return function(t){var n=[];c?t.nameLabel=t.id:(a&&(t.nameLabel=e.name),s&&n.push(t.id)),l&&n.push(r(t.z)),u&&n.push(t.tx),t.textLabel=n.join("
")}}function i(t){return function(e,r){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:r,location:e.id,z:e.z}]}}}var a=t("d3"),o=t("../../plots/cartesian/axes"),s=t("../../plots/cartesian/graph_interact"),l=t("../../components/color"),u=t("../../components/drawing"),c=t("../../components/colorscale/get_scale"),f=t("../../components/colorscale/make_scale_function"),h=t("../../lib/topojson_utils").getTopojsonFeatures,p=t("../../lib/geo_location_utils").locationToFeature,d=t("../../lib/array_to_calc_item"),g=t("../../plots/geo/constants"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){for(var r,n=[],i=t.locations,a=i.length,o=h(t,e),s=(t.marker||{}).line||{},l=0;a>l;l++)r=p(t.locationmode,i[l],o),void 0!==r&&(r.z=t.z[l],void 0!==t.text&&(r.tx=t.text[l]),d(s.color,r,"mlc",l),d(s.width,r,"mlw",l),n.push(r));return n.length>0&&(n[0].trace=t),n},m.plot=function(t,e,r){var o,l=t.framework,u=l.select("g.choroplethlayer"),c=l.select("g.baselayer"),f=l.select("g.baselayeroverchoropleth"),h=g.baseLayersOverChoropleth,p=u.selectAll("g.trace.choropleth").data(e,function(t){return t.uid});p.enter().append("g").attr("class","trace choropleth"),p.exit().remove(),p.each(function(e){function r(e,r){if(t.showHover){var n=t.projection(e.properties.ct);u(e),s.loneHover({x:n[0],y:n[1],name:e.nameLabel,text:e.textLabel},{container:t.hoverContainer.node()}),f=c(e,r),t.graphDiv.emit("plotly_hover",f)}}function o(e,r){t.graphDiv.emit("plotly_click",c(e,r))}var l=m.calcGeoJSON(e,t.topojson),u=n(t,e),c=i(e),f=null,h=a.select(this).selectAll("path.choroplethlocation").data(l);h.enter().append("path").classed("choroplethlocation",!0).on("mouseover",r).on("click",o).on("mouseout",function(){s.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",f)}).on("mousedown",function(){s.loneUnhover(t.hoverContainer)}).on("mouseup",r),h.exit().remove()}),f.selectAll("*").remove();for(var d=0;dr;r++)e=f[r],p[r]=e[0]*(t.zmax-t.zmin)+t.zmin,d[r]=e[1];var g=n.extent([t.zmin,t.zmax,a.start,a.start+l*(u-1)]),v=g[t.zminr;r++)e=f[r],p[r]=(e[0]*(u+c-1)-c/2)*l+o,d[r]=e[1];var y=n.scale.linear().interpolate(n.interpolateRgb).domain(p).range(d);return y}},{"../../components/colorscale/get_scale":1060,d3:82}],1254:[function(t,e,r){"use strict";function n(t,e,r){var n=r[0].trace,a=r[0].x,s=r[0].y,u=n.contours,c=n.uid,f=e.x(),h=e.y(),v=t._fullLayout,b="contour"+c,x=i(u,e,r[0]);if(n.visible!==!0)return v._paper.selectAll("."+b+",.hm"+c).remove(),void v._infolayer.selectAll(".cb"+c).remove();"heatmap"===u.coloring?(n.zauto&&n.autocontour===!1&&(n._input.zmin=n.zmin=u.start-u.size/2,n._input.zmax=n.zmax=n.zmin+x.length*u.size),k(t,e,[r])):v._paper.selectAll(".hm"+c).remove(),o(x),l(x);var _=f.c2p(a[0],!0),w=f.c2p(a[a.length-1],!0),A=h.c2p(s[0],!0),M=h.c2p(s[s.length-1],!0),T=[[_,M],[w,M],[w,A],[_,A]],E=p(e,r,b);d(E,T,u),g(E,x,T,u),m(E,x,u),y(E,e,r[0],T)}function i(t,e,r){for(var n=t.size||1,i=[],a=t.start;at?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);if(5===r||10===r){var n=(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4;return t>n?5===r?713:1114:5===r?104:208}return 15===r?0:r}function o(t){var e,r,n,i,o,s,l,u,c,f=t[0].z,h=f.length,p=f[0].length,d=2===h||2===p;for(r=0;h-1>r;r++)for(i=[],0===r&&(i=i.concat(A)),r===h-2&&(i=i.concat(M)),e=0;p-1>e;e++)for(n=i.slice(),0===e&&(n=n.concat(T)),e===p-2&&(n=n.concat(E)),o=e+","+r,s=[[f[r][e],f[r][e+1]],[f[r+1][e],f[r+1][e+1]]],c=0;ci;i++){if(s>20?(s=S[s][(l[0]||l[1])<0?0:1],t.crossings[o]=C[s]):delete t.crossings[o],l=L[s],!l){_.log("Found bad marching index:",s,e,t.level);break}if(p.push(h(t,e,l)),e[0]+=l[0],e[1]+=l[1],c(p[p.length-1],p[p.length-2])&&p.pop(),o=e.join(","),o===a&&l.join(",")===d||r&&(l[0]&&(e[0]<0||e[0]>v-2)||l[1]&&(e[1]<0||e[1]>g-2)))break;s=t.crossings[o]}1e4===i&&_.log("Infinite loop in contour?");var m,y,b,x,w,k,A,M=c(p[0],p[p.length-1]),T=0,E=.2*t.smoothing,z=[],P=0;for(i=1;i=P;i--)if(m=z[i],R>m){for(b=0,y=i-1;y>=P&&m+z[y]b&&m+z[b]e;)e++,r=Object.keys(i.crossings)[0].split(",").map(Number),s(i,r);1e4===e&&_.log("Infinite loop in contour?")}}function u(t,e,r){var n=0,i=0;return t>20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==A.indexOf(t)?i=1:-1!==T.indexOf(t)?n=1:-1!==M.indexOf(t)?i=-1:n=-1,[n,i]}function c(t,e){return Math.abs(t[0]-e[0])<.01&&Math.abs(t[1]-e[1])<.01}function f(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}function h(t,e,r){var n=e[0]+Math.max(r[0],0),i=e[1]+Math.max(r[1],0),a=t.z[i][n],o=t.xaxis,s=t.yaxis;if(r[1]){var l=(t.level-a)/(t.z[i][n+1]-a);return[o.c2p((1-l)*t.x[n]+l*t.x[n+1],!0),s.c2p(t.y[i],!0)]}var u=(t.level-a)/(t.z[i+1][n]-a);return[o.c2p(t.x[n],!0),s.c2p((1-u)*t.y[i]+u*t.y[i+1],!0)]}function p(t,e,r){var n=t.plot.select(".maplayer").selectAll("g.contour."+r).data(e);return n.enter().append("g").classed("contour",!0).classed(r,!0),n.exit().remove(),n}function d(t,e,r){var n=t.selectAll("g.contourbg").data([0]);n.enter().append("g").classed("contourbg",!0);var i=n.selectAll("path").data("fill"===r.coloring?[0]:[]);i.enter().append("path"),i.exit().remove(),i.attr("d","M"+e.join("L")+"Z").style("stroke","none")}function g(t,e,r,n){var i=t.selectAll("g.contourfill").data([0]);i.enter().append("g").classed("contourfill",!0);var a=i.selectAll("path").data("fill"===n.coloring?e:[]);a.enter().append("path"),a.exit().remove(),a.each(function(t){var e=v(t,r);e?x.select(this).attr("d",e).style("stroke","none"):x.select(this).remove()})}function v(t,e){function r(t){return Math.abs(t[1]-e[0][1])<.01}function n(t){return Math.abs(t[1]-e[2][1])<.01}function i(t){return Math.abs(t[0]-e[0][0])<.01}function a(t){return Math.abs(t[0]-e[2][0])<.01}for(var o,s,l,u,c,f,h=t.edgepaths.length||t.z[0][0]l;l++){if(!o){_.log("Missing end?",p,t);break}for(r(o)&&!a(o)?s=e[1]:i(o)?s=e[0]:n(o)?s=e[3]:a(o)&&(s=e[2]),c=0;c=0&&(s=v,u=c):Math.abs(o[1]-s[1])<.01?Math.abs(o[1]-v[1])<.01&&(v[0]-o[0])*(s[0]-v[0])>=0&&(s=v,u=c):_.log("endpt to newendpt is not vert. or horz.",o,s,v)}if(o=s,u>=0)break;h+="L"+s}if(u===t.edgepaths.length){_.log("unclosed perimeter path");break}p=u,g=-1===d.indexOf(p),g&&(p=d[0],h+="Z")}for(p=0;pe;e++)s.push(1);for(e=0;a>e;e++)i.push(s.slice());for(e=0;eo;o++)for(n=i(l,o),c[o]=new Array(n),s=0;n>s;s++)c[o][s]=e(a(l,o,s));return c}function i(t,e,r,n,i,a){var o,s,l,u=[],c=h.traceIs(t,"contour"),f=h.traceIs(t,"histogram"),p=h.traceIs(t,"gl2d");if(Array.isArray(e)&&!f&&"category"!==a.type){e=e.map(a.d2c);var d=e.length;if(!(i>=d))return c?e.slice(0,i):e.slice(0,i+1);if(c||p)u=e.slice(0,i);else if(1===i)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],l=1;d>l;l++)u.push(.5*(e[l-1]+e[l]));u.push(1.5*e[d-1]-.5*e[d-2])}if(i>d){var g=u[u.length-1],v=g-u[u.length-2];for(l=d;i>l;l++)g+=v,u.push(g)}}else for(s=n||1,o=void 0===r?0:f||"category"===a.type?r:a.d2c(r),l=c||p?0:-.5;i>l;l++)u.push(o+s*l);return u}function a(t){return.5-.25*Math.min(1,.5*t)}function o(t,e,r){var n,i,o=1;if(Array.isArray(r))for(n=0;nn&&o>y;n++)o=l(t,e,a(o));return o>y&&c.log("interp2d didn't converge quickly",o),t}function s(t){var e,r,n,i,a,o,s,l,u=[],c={},f=[],h=t[0],p=[],d=[0,0,0],g=m(t);for(r=0;rn;n++)void 0===p[n]&&(o=(void 0!==p[n-1]?1:0)+(void 0!==p[n+1]?1:0)+(void 0!==e[n]?1:0)+(void 0!==h[n]?1:0),o?(0===r&&o++,0===n&&o++,r===t.length-1&&o++,n===p.length-1&&o++,4>o&&(c[[r,n]]=[r,n,o]),u.push([r,n,o])):f.push([r,n]));for(;f.length;){for(s={},l=!1,a=f.length-1;a>=0;a--)i=f[a],r=i[0],n=i[1],o=((c[[r-1,n]]||d)[2]+(c[[r+1,n]]||d)[2]+(c[[r,n-1]]||d)[2]+(c[[r,n+1]]||d)[2])/20,o&&(s[i]=[r,n,o],f.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)c[i]=s[i],u.push(s[i])}return u.sort(function(t,e){return e[2]-t[2]})}function l(t,e,r){var n,i,a,o,s,l,u,c,f,h,p,d,g,v=0;for(o=0;os;s++)l=b[s],u=t[i+l[0]],u&&(c=u[a+l[1]],void 0!==c&&(0===h?d=g=c:(d=Math.min(d,c),g=Math.max(g,c)),f++,h+=c));if(0===f)throw"iterateInterp2d order is wrong: no defined neighbors";t[i][a]=h/f,void 0===p?4>f&&(v=1):(t[i][a]=(1+r)*t[i][a]-r*p,g>d&&(v=Math.max(v,Math.abs(t[i][a]-p)/(g-d))))}return v}var u=t("fast-isnumeric"),c=t("../../lib"),f=t("../../plots/cartesian/axes"),h=t("../../plots/plots"),p=t("../histogram2d/calc"),d=t("../../components/colorscale/calc"),g=t("./has_columns"),v=t("./convert_column_xyz"),m=t("./max_row_length");e.exports=function(t,e){function r(t){E=e._input.zsmooth=e.zsmooth=!1,c.notifier("cannot fast-zsmooth: "+t)}var a,l,u,y,b,x,_,w,k=f.getFromId(t,e.xaxis||"x"),A=f.getFromId(t,e.yaxis||"y"),M=h.traceIs(e,"contour"),T=h.traceIs(e,"histogram"),E=M?"best":e.zsmooth;if(k._minDtick=0,A._minDtick=0,T){var L=p(t,e);a=L.x,l=L.x0,u=L.dx,y=L.y,b=L.y0,x=L.dy,_=L.z}else g(e)&&v(e,k,A),a=e.x?k.makeCalcdata(e,"x"):[],y=e.y?A.makeCalcdata(e,"y"):[],l=e.x0||0,u=e.dx||1,b=e.y0||0,x=e.dy||1,_=n(e),(M||e.connectgaps)&&(e._emptypoints=s(_),e._interpz=o(_,e._emptypoints,e._interpz));if("fast"===E)if("log"===k.type||"log"===A.type)r("log axis found");else if(!T){if(a.length){var S=(a[a.length-1]-a[0])/(a.length-1),C=Math.abs(S/100);for(w=0;wC){r("x scale is not linear");break}}if(y.length&&"fast"===E){var z=(y[y.length-1]-y[0])/(y.length-1),P=Math.abs(z/100);for(w=0;wP){r("y scale is not linear");break}}}var R=m(_),j="scaled"===e.xtype?"":e.x,O=i(e,j,l,u,R,k),I="scaled"===e.ytype?"":e.y,N=i(e,I,b,x,_.length,A);f.expand(k,O),f.expand(A,N);var F={x:O,y:N,z:_};if(d(e,_,"","z"),M&&e.contours&&"heatmap"===e.contours.coloring){var D="contour"===e.type?"heatmap":"histogram2d";F.xfill=i(D,j,l,u,R,k),F.yfill=i(D,I,b,x,_.length,A)}return[F]};var y=.01,b=[[-1,0],[1,0],[0,-1],[0,1]]},{"../../components/colorscale/calc":1055,"../../lib":1127,"../../plots/cartesian/axes":1150,"../../plots/plots":1199,"../histogram2d/calc":1278,"./convert_column_xyz":1260,"./has_columns":1262,"./max_row_length":1265,"fast-isnumeric":90}],1259:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,u="cb"+r.uid,c=s(r.colorscale),f=r.zmin,h=r.zmax;if(i(f)||(f=a.aggNums(Math.min,null,r.z)),i(h)||(h=a.aggNums(Math.max,null,r.z)),t._fullLayout._infolayer.selectAll("."+u).remove(),!r.showscale)return void o.autoMargin(t,u);var p=e[0].t.cb=l(t,u);p.fillcolor(n.scale.linear().domain(c.map(function(t){return f+t[0]*(h-f)})).range(c.map(function(t){return t[1]}))).filllevels({start:f,end:h,size:(h-f)/254}).options(r.colorbar)()}},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,d3:82,"fast-isnumeric":90}],1260:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a=t.x.slice(),o=t.y.slice(),s=t.z,l=t.text,u=Math.min(a.length,o.length,s.length),c=void 0!==l&&!Array.isArray(l[0]);for(ui;i++)a[i]=e.d2c(a[i]),o[i]=r.d2c(o[i]);var f,h,p,d=n.distinctVals(a),g=d.vals,v=n.distinctVals(o),m=v.vals,y=n.init2dArray(m.length,g.length);for(c&&(p=n.init2dArray(m.length,g.length)),i=0;u>i;i++)f=n.findBin(a[i]+d.minDiff/2,g),h=n.findBin(o[i]+v.minDiff/2,m),y[h][f]=s[i],c&&(p[h][f]=l[i]);t.x=g,t.y=m,t.z=y,c&&(t.text=p)}},{"../../lib":1127}],1261:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./has_columns"),a=t("./xyz_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function u(r,i){return n.coerce(t,e,s,r,i)}var c=a(t,e,u);return c?(u("text"),u("zsmooth"),u("connectgaps",i(e)&&e.zsmooth!==!1),void o(t,e,l,u,{prefix:"",cLetter:"z"})):void(e.visible=!1)}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1257,"./has_columns":1262,"./xyz_defaults":1268}],1262:[function(t,e,r){"use strict";e.exports=function(t){return!Array.isArray(t.z[0])}},{}],1263:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../lib");e.exports=function(t,e,r,a,o){if(!(t.distanceu||u>=m[0].length||0>c||c>m.length)return}else{if(n.inbox(e-g[0],e-g[g.length-1])>n.MAXDIST||n.inbox(r-v[0],r-v[v.length-1])>n.MAXDIST)return;if(o){var w;for(b=[2*g[0]-g[1]],w=1;w0;)_=v.c2p(C[M]),M--;for(x>_&&(w=_,_=x,x=w,I=!0),M=0;void 0===k&&M0;)A=m.c2p(z[M]),M--;if(k>A&&(w=k,k=A,A=w,N=!0),P&&(C=r[0].xfill,z=r[0].yfill),"fast"!==R){var F="best"===R?0:.5;x=Math.max(-F*v._length,x),_=Math.min((1+F)*v._length,_),k=Math.max(-F*m._length,k),A=Math.min((1+F)*m._length,A)}var D=Math.round(_-x),B=Math.round(A-k);if(!(0>=D||0>=B)){var U,V;"fast"===R?(U=O,V=j):(U=D,V=B);var q=document.createElement("canvas");q.width=U,q.height=V;var G,H,Y=q.getContext("2d"),X=i.scale.linear().domain(S.map(function(t){return t[0]})).range(S.map(function(t){var e=a(t[1]).toRgb();return[e.r,e.g,e.b,e.a]})).clamp(!0);"fast"===R?(G=I?function(t){return O-1-t}:o.identity,H=N?function(t){return j-1-t}:o.identity):(G=function(t){return o.constrain(Math.round(v.c2p(C[t])-x),0,D)},H=function(t){return o.constrain(Math.round(m.c2p(z[t])-k),0,B)});var W,Z,K,$,Q,J,tt=H(0),et=[tt,tt],rt=I?0:1,nt=N?0:1,it=0,at=0,ot=0,st=0;if(R){var lt=0,ut=new Uint8Array(D*B*4);if("best"===R){var ct,ft,ht,pt=new Array(C.length),dt=new Array(z.length),gt=new Array(D);for(M=0;MM;M++)gt[M]=n(M,pt);for(Z=0;B>Z;Z++)for(ct=n(Z,dt),ft=T[ct.bin0],ht=T[ct.bin1],M=0;D>M;M++,lt+=4)J=p(ft,ht,gt[M],ct),h(ut,lt,J)}else for(Z=0;j>Z;Z++)for(Q=T[Z],et=H(Z),M=0;D>M;M++)J=f(Q[M],1),lt=4*(et*D+G(M)),h(ut,lt,J);var vt=Y.createImageData(D,B);vt.data.set(ut),Y.putImageData(vt,0,0)}else for(Z=0;j>Z;Z++)if(Q=T[Z],et.reverse(),et[nt]=H(Z+1),et[0]!==et[1]&&void 0!==et[0]&&void 0!==et[1])for(K=G(0),W=[K,K],M=0;O>M;M++)W.reverse(),W[rt]=G(M+1),W[0]!==W[1]&&void 0!==W[0]&&void 0!==W[1]&&($=Q[M],J=f($,(W[1]-W[0])*(et[1]-et[0])),Y.fillStyle="rgba("+J.join(",")+")",Y.fillRect(W[0],et[0],W[1]-W[0],et[1]-et[0]));at=Math.round(at/it),ot=Math.round(ot/it),st=Math.round(st/it);var mt=a("rgb("+at+","+ot+","+st+")");t._hmpixcount=(t._hmpixcount||0)+it,t._hmlumcount=(t._hmlumcount||0)+it*mt.getLuminance();var yt=e.plot.select(".imagelayer").selectAll("g.hm."+b).data([0]);yt.enter().append("g").classed("hm",!0).classed(b,!0),yt.exit().remove();var bt=yt.selectAll("image").data(r);bt.enter().append("svg:image"),bt.exit().remove(),bt.attr({xmlns:u.svg,"xlink:href":q.toDataURL("image/png"),height:B,width:D,x:x,y:k,preserveAspectRatio:"none"})}}var i=t("d3"),a=t("tinycolor2"),o=t("../../lib"),s=t("../../plots/plots"),l=t("../../components/colorscale/get_scale"),u=t("../../constants/xmlns_namespaces"),c=t("./max_row_length");e.exports=function(t,e,r){for(var i=0;i0&&(n=!0);for(var s=0;si;i++)e[i]?(t[i]/=e[i],n+=t[i]):t[i]=null;return n}},{}],1271:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){var e=r(t+"bins.start"),n=r(t+"bins.end"),i=r("autobin"+t,!(e&&n));r(i?"nbins"+t:t+"bins.size")}),e}},{}],1272:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,i){var a=i[e];return n(a)?(a=Number(a),r[t]+=a,a):0},avg:function(t,e,r,i,a){ -var o=i[e];return n(o)&&(o=Number(o),r[t]+=o,a[t]++),0},min:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]>a)return r[t]=a,a-r[t]}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]r&&u.length<5e3;)g=a.tickIncrement(r,b.size),u.push((r+g)/2),c.push(S),x&&_.push(r),E&&w.push(1/(g-r)),P&&k.push(0),r=g;var R=c.length;for(r=0;r=0&&R>m&&(A+=C(m,r,c,y,k));P&&(A=l(c,k)),z&&z(c,A,w);var j=Math.min(u.length,c.length),O=[],I=0,N=j-1;for(r=0;j>r;r++)if(c[r]){I=r;break}for(r=j-1;r>I;r--)if(c[r]){N=r;break}for(r=I;N>=r;r++)n(u[r])&&n(c[r])&&O.push({p:u[r],s:c[r],b:0});return O}}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./average":1270,"./bin_functions":1272,"./norm_functions":1276,"fast-isnumeric":90}],1274:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("./bin_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,u){function c(r,i){return n.coerce(t,e,l,r,i)}var f=c("x"),h=c("y");c("text");var p=c("orientation",h&&!f?"h":"v"),d=e["v"===p?"x":"y"];if(!d||!d.length)return void(e.visible=!1);var g=e["h"===p?"x":"y"];g&&c("histfunc");var v="h"===p?["y"]:["x"];a(t,e,c,v),o(t,e,c,r,u),s(t,e,i.defaultLine,{axis:"y"}),s(t,e,i.defaultLine,{axis:"x",inherit:"y"})}},{"../../components/color":1048,"../../components/errorbars/defaults":1076,"../../lib":1127,"../bar/style_defaults":1231,"./attributes":1269,"./bin_defaults":1271}],1275:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.style=t("../bar/style"),n.colorbar=t("../scatter/colorbar"),n.hoverPoints=t("../bar/hover"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../bar/hover":1224,"../bar/layout_attributes":1226,"../bar/layout_defaults":1227,"../bar/plot":1228,"../bar/set_positions":1229,"../bar/style":1230,"../scatter/colorbar":1304,"./attributes":1269,"./calc":1273,"./defaults":1274}],1276:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,i=0;r>i;i++)t[i]*=n},probability:function(t,e){for(var r=t.length,n=0;r>n;n++)t[n]/=e},density:function(t,e,r,n){var i=t.length;n=n||1;for(var a=0;i>a;a++)t[a]*=r[a]*n},"probability density":function(t,e,r,n){var i=t.length;n&&(e/=n);for(var a=0;i>a;a++)t[a]*=r[a]/e}}},{}],1277:[function(t,e,r){"use strict";var n=t("../histogram/attributes"),i=t("../heatmap/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports=o({},{x:n.x,y:n.y,z:{valType:"data_array"},marker:{color:{valType:"data_array"}},histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zsmooth:i.zsmooth,_nestedModules:{colorbar:"Colorbar"}},a,{autocolorscale:o({},a.autocolorscale,{dflt:!1})})},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../heatmap/attributes":1257,"../histogram/attributes":1269}],1278:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../histogram/bin_functions"),o=t("../histogram/norm_functions"),s=t("../histogram/average");e.exports=function(t,e){var r,l,u,c,f,h,p=i.getFromId(t,e.xaxis||"x"),d=e.x?p.makeCalcdata(e,"x"):[],g=i.getFromId(t,e.yaxis||"y"),v=e.y?g.makeCalcdata(e,"y"):[],m=Math.min(d.length,v.length);d.length>m&&d.splice(m,d.length-m),v.length>m&&v.splice(m,v.length-m),!e.autobinx&&"xbins"in e||(e.xbins=i.autoBin(d,p,e.nbinsx,"2d"),"histogram2dcontour"===e.type&&(e.xbins.start-=e.xbins.size,e.xbins.end+=e.xbins.size),e._input.xbins=e.xbins),!e.autobiny&&"ybins"in e||(e.ybins=i.autoBin(v,g,e.nbinsy,"2d"),"histogram2dcontour"===e.type&&(e.ybins.start-=e.ybins.size,e.ybins.end+=e.ybins.size),e._input.ybins=e.ybins),f=[];var y,b,x=[],_=[],w="string"==typeof e.xbins.size?[]:e.xbins,k="string"==typeof e.xbins.size?[]:e.ybins,A=0,M=[],T=e.histnorm,E=e.histfunc,L=-1!==T.indexOf("density"),S="max"===E||"min"===E,C=S?null:0,z=a.count,P=o[T],R=!1,j=[],O=[],I="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";I&&"count"!==E&&(R="avg"===E,z=a[E]);var N=e.xbins,F=N.end+(N.start-i.tickIncrement(N.start,N.size))/1e6;for(h=N.start;F>h;h=i.tickIncrement(h,N.size))x.push(C),Array.isArray(w)&&w.push(h),R&&_.push(0);Array.isArray(w)&&w.push(h);var D=x.length;for(r=e.xbins.start,l=(h-r)/D,r+=l/2,N=e.ybins,F=N.end+(N.start-i.tickIncrement(N.start,N.size))/1e6,h=N.start;F>h;h=i.tickIncrement(h,N.size))f.push(x.concat()),Array.isArray(k)&&k.push(h),R&&M.push(_.concat());Array.isArray(k)&&k.push(h);var B=f.length;for(u=e.ybins.start,c=(h-u)/B,u+=c/2,L&&(j=x.map(function(t,e){return Array.isArray(w)?1/(w[e+1]-w[e]):1/l}),O=f.map(function(t,e){return Array.isArray(k)?1/(k[e+1]-k[e]):1/c})),h=0;m>h;h++)y=n.findBin(d[h],w),b=n.findBin(v[h],k),y>=0&&D>y&&b>=0&&B>b&&(A+=z(y,h,f[b],I,M[b]));if(R)for(b=0;B>b;b++)A+=s(f[b],M[b]);if(P)for(b=0;B>b;b++)P(f[b],A,j,O[b]);return{x:d,x0:r,dx:l,y:v,y0:u,dy:c,z:f}}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../histogram/average":1270,"../histogram/bin_functions":1272,"../histogram/norm_functions":1276}],1279:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./sample_defaults"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r){function s(r,i){return n.coerce(t,e,o,r,i)}i(t,e,s),s("zsmooth"),a(t,e,r,s,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1277,"./sample_defaults":1281}],1280:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../heatmap/calc"),n.plot=t("../heatmap/plot"),n.colorbar=t("../heatmap/colorbar"),n.style=t("../heatmap/style"),n.hoverPoints=t("../heatmap/hover"),n.moduleType="trace",n.name="histogram2d",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../heatmap/calc":1258,"../heatmap/colorbar":1259,"../heatmap/hover":1263,"../heatmap/plot":1266,"../heatmap/style":1267,"./attributes":1277,"./defaults":1279}],1281:[function(t,e,r){"use strict";var n=t("../histogram/bin_defaults");e.exports=function(t,e,r){var i=r("x"),a=r("y");if(!(i&&i.length&&a&&a.length))return void(e.visible=!1);var o=r("z")||r("marker.color");o&&r("histfunc");var s=["x","y"];n(t,e,r,s)}},{"../histogram/bin_defaults":1271}],1282:[function(t,e,r){"use strict";var n=t("../histogram2d/attributes"),i=t("../contour/attributes"),a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports=o({},{x:n.x,y:n.y,z:n.z,marker:n.marker,histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,autocontour:i.autocontour,ncontours:i.ncontours,contours:i.contours,line:i.line,_nestedModules:{colorbar:"Colorbar"}},a)},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../contour/attributes":1247,"../histogram2d/attributes":1277}],1283:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../histogram2d/sample_defaults"),a=t("../contour/style_defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}i(t,e,l);var u=n.coerce2(t,e,o,"contours.start"),c=n.coerce2(t,e,o,"contours.end"),f=l("autocontour",!(u&&c));l(f?"ncontours":"contours.size"),a(t,e,l,s)}},{"../../lib":1127,"../contour/style_defaults":1256,"../histogram2d/sample_defaults":1281,"./attributes":1282}],1284:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../contour/calc"),n.plot=t("../contour/plot"),n.style=t("../contour/style"),n.colorbar=t("../contour/colorbar"),n.hoverPoints=t("../contour/hover"),n.moduleType="trace",n.name="histogram2dcontour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","contour","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":1158,"../contour/calc":1248,"../contour/colorbar":1249,"../contour/hover":1251,"../contour/plot":1254,"../contour/style":1255,"./attributes":1282,"./defaults":1283}],1285:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../surface/attributes"),a=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},i:{valType:"data_array"},j:{valType:"data_array"},k:{valType:"data_array"},delaunayaxis:{valType:"enumerated",values:["x","y","z"],dflt:"z"},alphahull:{valType:"number",dflt:-1},intensity:{valType:"data_array"},color:{valType:"color"},vertexcolor:{valType:"data_array"},facecolor:{valType:"data_array"},opacity:a({},i.opacity),flatshading:{valType:"boolean",dflt:!1},contour:{show:a({},i.contours.x.show,{}),color:a({},i.contours.x.color),width:a({},i.contours.x.width)},colorscale:n.colorscale,reversescale:n.reversescale,showscale:n.showscale,lightposition:{x:a({},i.lightposition.x,{dflt:1e5}),y:a({},i.lightposition.y,{dflt:1e5}),z:a({},i.lightposition.z,{dflt:0})},lighting:a({},{vertexnormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-12},facenormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-6}},i.lighting),_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":1054,"../../lib/extend":1122,"../surface/attributes":1348}],1286:[function(t,e,r){"use strict";function n(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.color="#fff",this.data=null,this.showContour=!1}function i(t){return t.map(function(t){var e=t[0],r=u(t[1]),n=r.toRgb();return{index:e,rgb:[n.r,n.g,n.b,1]}})}function a(t){return t.map(p)}function o(t,e,r){for(var n=new Array(t.length),i=0;i0)s=f(t.alphahull,l);else{var u=["x","y","z"].indexOf(t.delaunayaxis);s=c(l.map(function(t){return[t[(u+1)%3],t[(u+2)%3]]}))}var d={positions:l,cells:s,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:p(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",d.vertexIntensity=t.intensity,d.colormap=i(t.colorscale)):t.vertexcolor?(this.color=t.vertexcolors[0],d.vertexColors=a(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],d.cellColors=a(t.facecolor)):(this.color=t.color,d.meshColor=p(t.color)),this.mesh.update(d)},d.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=s},{"../../lib/str2rgbarray":1139,"alpha-shape":46,"convex-hull":71,"delaunay-triangulate":88,"gl-mesh3d":253,tinycolor2:1042}],1287:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorbar/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}function l(t){var e=t.map(function(t){var e=s(t);return e&&Array.isArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var u=l(["x","y","z"]),c=l(["i","j","k"]);return u?(c&&c.forEach(function(t){for(var e=0;el||(u=d[r],void 0!==u&&""!==u||(u=r),u=String(u),void 0===y[u]&&(y[u]=!0,c=a(e.marker.colors[r]),c.isValid()?(c=o.addOpacity(c,c.getAlpha()),m[u]||(m[u]=c)):m[u]?c=m[u]:(c=!1,b=!0),f=-1!==_.indexOf(u),f||(x+=l),g.push({v:l,label:u,color:c,i:r,hidden:f}))));if(e.sort&&g.sort(function(t,e){return e.v-t.v}),b)for(r=0;r")}return g};var l},{"../../components/color":1048,"./helpers":1293,"fast-isnumeric":90,tinycolor2:1042}],1292:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}var s=n.coerceFont,l=o("values");if(!Array.isArray(l)||!l.length)return void(e.visible=!1);var u=o("labels");Array.isArray(u)||(o("label0"),o("dlabel"));var c=o("marker.line.width");c&&o("marker.line.color");var f=o("marker.colors");Array.isArray(f)||(e.marker.colors=[]),o("scalegroup");var h=o("text"),p=o("textinfo",Array.isArray(h)?"text+percent":"percent");if(o("hoverinfo",1===a._dataLength?"label+text+value+percent":void 0),p&&"none"!==p){var d=o("textposition"),g=Array.isArray(d)||"auto"===d,v=g||"inside"===d,m=g||"outside"===d;if(v||m){var y=s(o,"textfont",a.font);v&&s(o,"insidetextfont",y),m&&s(o,"outsidetextfont",y)}}o("domain.x"),o("domain.y"),o("hole"),o("sort"),o("direction"),o("rotation"),o("pull")}},{"../../lib":1127,"./attributes":1289}],1293:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)}},{"../../lib":1127}],1294:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":1289,"./base_plot":1290,"./calc":1291,"./defaults":1292,"./layout_attributes":1295,"./layout_defaults":1296,"./plot":1297,"./style":1298,"./style_one":1299}],1295:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array"}}},{}],1296:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e){function r(r,a){return n.coerce(t,e,i,r,a)}r("hiddenlabels")}},{"../../lib":1127,"./layout_attributes":1295}],1297:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,o=Math.PI*Math.min(e.v/r.vTotal,.5),s=1-r.trace.hole,l=i(e,r),u={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(u.scale>=1)return u;var c=a+1/(2*Math.tan(o)),f=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),s/(Math.sqrt(a*a+s/2)+a)),h={scale:2*f/t.height,rCenter:Math.cos(f/r.r)-f*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},p=1/a,d=p+1/(2*Math.tan(o)),g=r.r*Math.min(1/(Math.sqrt(d*d+.5)+d),s/(Math.sqrt(p*p+s/2)+p)),v={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},m=v.scale>h.scale?v:h;return u.scale<1&&m.scale>u.scale?m:u}function i(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function a(t,e){var r=e.pxmid[0],n=e.pxmid[1],i=t.width/2,a=t.height/2;return 0>r&&(i*=-1),0>n&&(a*=-1),{scale:1,rCenter:1,rotate:0,x:i+Math.abs(a)*(i>0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}function o(t,e){function r(t,e){return t.pxmid[1]-e.pxmid[1]}function n(t,e){return e.pxmid[1]-t.pxmid[1]}function i(t,r){r||(r={});var n,i,a,s,h,p,g=r.labelExtraY+(o?r.yLabelMax:r.yLabelMin),v=o?t.yLabelMin:t.yLabelMax,m=o?t.yLabelMax:t.yLabelMin,y=t.cyFinal+u(t.px0[1],t.px1[1]),b=g-v;if(b*f>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(i=0;i=e.pull[a.i]||((t.pxmid[1]-a.pxmid[1])*f>0?(s=a.cyFinal+u(a.px0[1],a.px1[1]),b=s-v-t.labelExtraY,b*f>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-y)*f>0&&(n=3*c*Math.abs(i-d.indexOf(t)),h=a.cxFinal+l(a.px0[0],a.px1[0]),p=h+n-(t.cxFinal+t.pxmid[0])-t.labelExtraX,p*c>0&&(t.labelExtraX+=p)))}var a,o,s,l,u,c,f,h,p,d,g,v,m;for(o=0;2>o;o++)for(s=o?r:n,u=o?Math.max:Math.min,f=o?1:-1,a=0;2>a;a++){for(l=a?Math.max:Math.min,c=a?1:-1,h=t[o][a],h.sort(s),p=t[1-o][a],d=p.concat(h),v=[],g=0;gc&&(c=s.pull[a]);o.r=Math.min(r/u(s.tilt,Math.sin(l),s.depth),n/u(s.tilt,Math.cos(l),s.depth))/(2+2*c),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===p.indexOf(s.scalegroup)&&p.push(s.scalegroup)}for(a=0;af.vTotal/2?1:0)}function u(t,e,r){if(!t)return 1;var n=Math.sin(t*Math.PI/180);return Math.max(.01,r*n*Math.abs(e)+2*Math.sqrt(1-n*n*e*e))}var c=t("d3"),f=t("../../plots/cartesian/graph_interact"),h=t("../../components/color"),p=t("../../components/drawing"),d=t("../../lib/svg_text_utils"),g=t("./helpers");e.exports=function(t,e){var r=t._fullLayout;s(e,r._size);var u=r._pielayer.selectAll("g.trace").data(e);u.enter().append("g").attr({"stroke-linejoin":"round","class":"trace"}),u.exit().remove(),u.order(),u.each(function(e){var s=c.select(this),u=e[0],v=u.trace,m=0,y=(v.depth||0)*u.r*Math.sin(m)/2,b=v.tiltaxis||0,x=b*Math.PI/180,_=[y*Math.sin(x),y*Math.cos(x)],w=u.r*Math.cos(m),k=s.selectAll("g.part").data(v.tilt?["top","sides"]:["top"]);k.enter().append("g").attr("class",function(t){return t+" part"}),k.exit().remove(),k.order(),l(e),s.selectAll(".top").each(function(){var s=c.select(this).selectAll("g.slice").data(e);s.enter().append("g").classed("slice",!0),s.exit().remove();var l=[[[],[]],[[],[]]],m=!1;s.each(function(o){function s(e){var n=t._fullLayout,a=t._fullData[v.index],s=a.hoverinfo;if("all"===s&&(s="label+text+value+percent+name"),!t._dragging&&n.hovermode!==!1&&"none"!==s&&s){var l=i(o,u),c=k+o.pxmid[0]*(1-l),h=A+o.pxmid[1]*(1-l),p=r.separators,d=[];-1!==s.indexOf("label")&&d.push(o.label),a.text&&a.text[o.i]&&-1!==s.indexOf("text")&&d.push(a.text[o.i]),-1!==s.indexOf("value")&&d.push(g.formatPieValue(o.v,p)),-1!==s.indexOf("percent")&&d.push(g.formatPiePercent(o.v/u.vTotal,p)),f.loneHover({x0:c-l*u.r,x1:c+l*u.r,y:h,text:d.join("
"),name:-1!==s.indexOf("name")?a.name:void 0,color:o.color,idealAlign:o.pxmid[0]<0?"left":"right"},{container:n._hoverlayer.node(),outerContainer:n._paper.node()}),f.hover(t,e,"pie"),E=!0}}function h(e){t.emit("plotly_unhover",{points:[e]}),E&&(f.loneUnhover(r._hoverlayer.node()),E=!1)}function y(){t._hoverdata=[o],t._hoverdata.trace=e.trace,f.click(t,{target:!0})}function x(t,e,r,n){return"a"+n*u.r+","+n*w+" "+b+" "+o.largeArc+(r?" 1 ":" 0 ")+n*(e[0]-t[0])+","+n*(e[1]-t[1])}if(o.hidden)return void c.select(this).selectAll("path,g").remove();l[o.pxmid[1]<0?0:1][o.pxmid[0]<0?0:1].push(o);var k=u.cx+_[0],A=u.cy+_[1],M=c.select(this),T=M.selectAll("path.surface").data([o]),E=!1;if(T.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),M.select("path.textline").remove(),M.on("mouseover",s).on("mouseout",h).on("click",y),v.pull){var L=+(Array.isArray(v.pull)?v.pull[o.i]:v.pull)||0;L>0&&(k+=L*o.pxmid[0],A+=L*o.pxmid[1])}o.cxFinal=k,o.cyFinal=A;var S=v.hole;if(o.v===u.vTotal){var C="M"+(k+o.px0[0])+","+(A+o.px0[1])+x(o.px0,o.pxmid,!0,1)+x(o.pxmid,o.px0,!0,1)+"Z";S?T.attr("d","M"+(k+S*o.px0[0])+","+(A+S*o.px0[1])+x(o.px0,o.pxmid,!1,S)+x(o.pxmid,o.px0,!1,S)+"Z"+C):T.attr("d",C)}else{var z=x(o.px0,o.px1,!0,1);if(S){var P=1-S;T.attr("d","M"+(k+S*o.px1[0])+","+(A+S*o.px1[1])+x(o.px1,o.px0,!1,S)+"l"+P*o.px0[0]+","+P*o.px0[1]+z+"Z")}else T.attr("d","M"+k+","+A+"l"+o.px0[0]+","+o.px0[1]+z+"Z")}var R=Array.isArray(v.textposition)?v.textposition[o.i]:v.textposition,j=M.selectAll("g.slicetext").data(o.text&&"none"!==R?[0]:[]);j.enter().append("g").classed("slicetext",!0),j.exit().remove(),j.each(function(){var t=c.select(this).selectAll("text").data([0]);t.enter().append("text").attr("data-notex",1),t.exit().remove(),t.text(o.text).attr({"class":"slicetext",transform:"","data-bb":"","text-anchor":"middle",x:0,y:0}).call(p.font,"outside"===R?v.outsidetextfont:v.insidetextfont).call(d.convertToTspans),t.selectAll("tspan.line").attr({x:0,y:0});var e,r=p.bBox(t.node());"outside"===R?e=a(r,o):(e=n(r,o,u),"auto"===R&&e.scale<1&&(t.call(p.font,v.outsidetextfont),v.outsidetextfont.family===v.insidetextfont.family&&v.outsidetextfont.size===v.insidetextfont.size||(t.attr({"data-bb":""}),r=p.bBox(t.node())),e=a(r,o)));var i=k+o.pxmid[0]*e.rCenter+(e.x||0),s=A+o.pxmid[1]*e.rCenter+(e.y||0);e.outside&&(o.yLabelMin=s-r.height/2,o.yLabelMid=s,o.yLabelMax=s+r.height/2,o.labelExtraX=0,o.labelExtraY=0,m=!0),t.attr("transform","translate("+i+","+s+")"+(e.scale<1?"scale("+e.scale+")":"")+(e.rotate?"rotate("+e.rotate+")":"")+"translate("+-(r.left+r.right)/2+","+-(r.top+r.bottom)/2+")")})}),m&&o(l,v),s.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=c.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var n=t.cxFinal+t.pxmid[0],i=t.cyFinal+t.pxmid[1],a="M"+n+","+i,o=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],l=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);a+=Math.abs(s)>Math.abs(l)?"l"+l*t.pxmid[0]/t.pxmid[1]+","+l+"H"+(n+t.labelExtraX+o):"l"+t.labelExtraX+","+s+"v"+(l-s)+"h"+o}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+o;e.append("path").classed("textline",!0).call(h.stroke,v.outsidetextfont.color).attr({"stroke-width":Math.min(2,v.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){u.selectAll("tspan").each(function(){var t=c.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/svg_text_utils":1140,"../../plots/cartesian/graph_interact":1157,"./helpers":1293,d3:82}],1298:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0],r=e.trace,a=n.select(this);a.style({opacity:r.opacity}),a.selectAll(".top path.surface").each(function(t){n.select(this).call(i,t,r)})})}},{"./style_one":1299,d3:82}],1299:[function(t,e,r){"use strict";var n=t("../../components/color");e.exports=function(t,e,r){var i=r.marker.line.color;Array.isArray(i)&&(i=i[e.i]||n.defaultLine);var a=r.marker.line.width||0;Array.isArray(a)&&(a=a[e.i]||0),t.style({"stroke-width":a,fill:e.color}).call(n.stroke,i)}},{"../../components/color":1048}],1300:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){var e=t[0].trace,r=e.marker;if(n.mergeArray(e.text,t,"tx"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf")),r&&r.line){var i=r.line;n.mergeArray(r.opacity,t,"mo"),n.mergeArray(r.symbol,t,"mx"),n.mergeArray(r.color,t,"mc"),n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw")}}},{"../../lib":1127}],1301:[function(t,e,r){"use strict";var n=t("../../components/colorscale/color_attributes"),i=t("../../components/drawing"),a=(t("./constants"),t("../../lib/extend").extendFlat);e.exports={x:{valType:"data_array"},x0:{valType:"any",dflt:0},dx:{valType:"number",dflt:1},y:{valType:"data_array"},y0:{valType:"any",dflt:0},dy:{valType:"number",dflt:1},key:{valType:"data_array"},text:{valType:"string",dflt:"",arrayOk:!0},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"]},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear"},smoothing:{valType:"number",min:0,max:1.3,dflt:1},dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid"}},connectgaps:{valType:"boolean",dflt:!1},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none"},fillcolor:{valType:"color"},marker:a({},{symbol:{valType:"enumerated",values:i.symbolList,dflt:"circle",arrayOk:!0},opacity:{valType:"number",min:0,max:1,arrayOk:!0},size:{valType:"number",min:0,dflt:6,arrayOk:!0},maxdisplayed:{valType:"number",min:0,dflt:0},sizeref:{valType:"number",dflt:1},sizemin:{valType:"number",min:0,dflt:0},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter"},showscale:{valType:"boolean",dflt:!1},line:a({},{width:{valType:"number",min:0,arrayOk:!0}},n("marker.line"))},n("marker")),textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0},textfont:{family:{valType:"string",noBlank:!0,strict:!0,arrayOk:!0},size:{valType:"number",min:1,arrayOk:!0},color:{valType:"color",arrayOk:!0}},r:{valType:"data_array"},t:{valType:"data_array"},_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":1056, -"../../components/drawing":1071,"../../lib/extend":1122,"./constants":1305}],1302:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./subtypes"),s=t("./marker_colorscale_calc");e.exports=function(t,e){var r,l,u,c=i.getFromId(t,e.xaxis||"x"),f=i.getFromId(t,e.yaxis||"y"),h=c.makeCalcdata(e,"x"),p=f.makeCalcdata(e,"y"),d=Math.min(h.length,p.length);c._minDtick=0,f._minDtick=0,h.length>d&&h.splice(d,h.length-d),p.length>d&&p.splice(d,p.length-d);var g={padded:!0},v={padded:!0};if(o.hasMarkers(e)){if(r=e.marker,l=r.size,Array.isArray(l)){var m={type:"linear"};i.setConvert(m),l=m.makeCalcdata(e.marker,"size"),l.length>d&&l.splice(d,l.length-d)}var y,b=1.6*(e.marker.sizeref||1);y="area"===e.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/b),3)}:function(t){return Math.max((t||0)/b,3)},g.ppad=v.ppad=Array.isArray(l)?l.map(y):y(l)}s(e),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||h[0]===h[d-1]&&p[0]===p[d-1]?e.error_y.visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(o.hasMarkers(e)||o.hasText(e))||(g.padded=!1,g.ppad=0):g.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||h[0]===h[d-1]&&p[0]===p[d-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(v.padded=!1):v.tozero=!0,i.expand(c,h,g),i.expand(f,p,v);var x=new Array(d);for(u=0;d>u;u++)x[u]=n(h[u])&&n(p[u])?{x:h[u],y:p[u]}:{x:!1,y:!1},e.key&&void 0!==e.key[u]&&(x[u].key=e.key[u]);return void 0!==typeof l&&a.mergeArray(l,x,"ms"),t.firstscatter=!1,x}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"./marker_colorscale_calc":1316,"./subtypes":1322,"fast-isnumeric":90}],1303:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i,a;for(e=0;e=0;i--)if(a=t[i],"scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}},{}],1304:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,u=r.marker,c="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+c).remove(),void 0===u||!u.showscale)return void o.autoMargin(t,c);var f=s(u.colorscale),h=u.color,p=u.cmin,d=u.cmax;i(p)||(p=a.aggNums(Math.min,null,h)),i(d)||(d=a.aggNums(Math.max,null,h));var g=e[0].t.cb=l(t,c);g.fillcolor(n.scale.linear().domain(f.map(function(t){return p+t[0]*(d-p)})).range(f.map(function(t){return t[1]}))).filllevels({start:p,end:d,size:(d-p)/254}).options(u.colorbar)()}},{"../../components/colorbar/draw":1051,"../../components/colorscale/get_scale":1060,"../../lib":1127,"../../plots/plots":1199,d3:82,"fast-isnumeric":90}],1305:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20}},{}],1306:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./constants"),o=t("./subtypes"),s=t("./xy_defaults"),l=t("./marker_defaults"),u=t("./line_defaults"),c=t("./line_shape_defaults"),f=t("./text_defaults"),h=t("./fillcolor_defaults"),p=t("../../components/errorbars/defaults");e.exports=function(t,e,r,d){function g(r,a){return n.coerce(t,e,i,r,a)}var v=s(t,e,g),m=vi(f))break;l=f,y=g[0]*d[0]+g[1]*d[1],y>v?(v=y,u=f,p=!1):m>y&&(m=y,c=f,p=!0)}if(p?(C[z++]=u,l!==c&&(C[z++]=c)):(c!==s&&(C[z++]=c),l!==u&&(C[z++]=u)),C[z++]=l,o>=t.length||!f)break;C[z++]=f,s=f}}else C[z++]=u}E.push(C.slice(0,z))}return E}},{"../../plots/cartesian/axes":1150}],1313:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=r("line.shape");"spline"===n&&r("line.smoothing")}},{}],1314:[function(t,e,r){"use strict";var n=t("../../plots/plots");e.exports=function(t,e,r){var i,a,o,s=(t._fullLayout,e.x()),l=e.y(),u=null;for(i=0;i0?Math.max(e,i):0}}},{"fast-isnumeric":90}],1316:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t){if(a.hasMarkers(t)){var e=t.marker;n(t,"marker")&&i(t,e.color,"marker","c"),n(t,"marker.line")&&i(t,e.line.color,"marker.line","c")}}},{"../../components/colorscale/calc":1055,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1317:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l){var u,c=o.isBubble(t),f=(t.line||{}).color;f&&(r=f),l("marker.symbol"),l("marker.opacity",c?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),u=f&&e.marker.color!==f?f:c?n.background:n.defaultLine,l("marker.line.color",u),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",c?1:0),c&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode"))}},{"../../components/color":1048,"../../components/colorscale/defaults":1058,"../../components/colorscale/has_colorscale":1061,"./subtypes":1322}],1318:[function(t,e,r){"use strict";function n(t){return t[0].trace.uid}function i(t,e,r,n){var i;e.selectAll("g.trace").each(function(t){var e=s.select(this);i=t[0].trace,"tozero"===i.fill.substr(0,6)||"toself"===i.fill||"to"===i.fill.substr(0,2)&&!i._prevtrace?(i._ownFill=e.select(".js-fill.js-tozero"),i._ownFill.size()||(i._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),i._ownFill=null),i._nexttrace?(i._nextFill=e.select(".js-fill.js-tonext"),i._nextFill.size()||(i._nextFill=e.insert("path",":first-child").attr("class","js-fill js-tonext"))):(e.selectAll(".js-fill.js-tonext").remove(),i._nextFill=null)})}function a(t,e,r,n,i){function a(t){return t.transition().duration(i.duration).ease(i.easing)}function d(t){return t.filter(function(t){return t.vis})}function g(t){return t.key}function v(t){return t.key?g:void 0}function m(t){var e=t[0].trace,r=s.select(this),n=f.hasMarkers(e),a=f.hasText(e);if(!n&&!a||e.visible!==!0)r.remove();else{if(n){var o=r.selectAll("path.point").data(e.marker.maxdisplayed?d:l.identity,v(e));o.enter().append("path").classed("point",!0).call(u.pointStyle,e).call(u.translatePoints,y,b,e,i,1),o.transition().call(u.translatePoints,y,b,e,i,0).call(u.pointStyle,e),o.exit().call(u.translatePoints,y,b,e,i,-1)}a&&r.selectAll("g").data(e.marker.maxdisplayed?d:l.identity).enter().append("g").append("text").call(u.translatePoints,y,b,e,i,1)}}o(t,e,r);var y=e.x(),b=e.y(),x=r[0].trace,_=x.line,w=s.select(n);if(w.call(c.plot,e),x.visible===!0){var k,A,M=x.fill.charAt(x.fill.length-1);"x"!==M&&"y"!==M&&(M=""),r[0].node3=w,h(r);var T="",E=x._prevtrace;E&&(T=E._revpath||"",A=E._nextFill);var L,S,C,z,P,R="",j="";if(k=x._ownFill,f.hasLines(x)||"none"!==x.fill){A&&A.datum(r),-1!==["hv","vh","hvh","vhv"].indexOf(_.shape)?(C=u.steps(_.shape),z=u.steps(_.shape.split("").reverse().join(""))):C=z="spline"===_.shape?function(t){var e=t[t.length-1];return t[0][0]===e[0]&&t[0][1]===e[1]?u.smoothclosed(t.slice(1),_.smoothing):u.smoothopen(t,_.smoothing)}:function(t){return"M"+t.join("L")},P=function(t){return z(t.reverse())};var O=p(r,{xaxis:y,yaxis:b,connectGaps:x.connectgaps,baseTolerance:Math.max(_.width||1,3)/4,linear:"linear"===_.shape});if(O.length){for(var I=O[0][0],N=O[O.length-1],F=N[N.length-1],D=0;D1){var U=w.selectAll(".js-line").data([r]);U.enter().append("path").classed("js-line",!0).attr("d",L),a(U).attr("d",L)}}k?I&&F&&(M?("y"===M?I[1]=F[1]=b.c2p(0,!0):"x"===M&&(I[0]=F[0]=y.c2p(0,!0)),a(k).attr("d",R+"L"+F+"L"+I+"Z")):a(k).attr("d",R+"Z")):"tonext"===x.fill.substr(0,6)&&R&&T&&("tonext"===x.fill?a(A).attr("d",R+"Z"+T+"Z"):a(A).attr("d",R+"L"+T.substr(1)+"Z"))}x._revpath=j}var V=w.selectAll(".points").data([r]);V.enter().append("g").classed("points",!0).each(m),V.transition().duration(0).each(m),V.exit().remove()}}function o(t,e,r){var n=e.x(),i=e.y(),a=s.extent(n.range.map(n.l2c)),o=s.extent(i.range.map(i.l2c)),l=0,u=r[0].trace;if(f.hasMarkers(u)){var c=u.marker.maxdisplayed;if(0!==c){var h=r.filter(function(t){return t.x>=a[0]&&t.x<=a[1]&&t.y>=o[0]&&t.y<=o[1]}),p=Math.ceil(h.length/c),d=0;r.forEach(function(t,e){var r=t[0].trace;f.hasMarkers(r)&&r.marker.maxdisplayed>0&&l>e&&d++});var g=Math.round(d*p/3+Math.floor(d/3)*p/7.1);r.forEach(function(t){delete t.vis}),h.forEach(function(t,e){0===Math.round((e+g)%p)&&(t.vis=!0)})}}}var s=t("d3"),l=t("../../lib"),u=t("../../components/drawing"),c=t("../../components/errorbars"),f=t("./subtypes"),h=t("./arrays_to_calcdata"),p=t("./line_points"),d=t("./link_traces");e.exports=function(t,e,r,o,s){var u,c,f,h=l.extendFlat({},s||{});h=l.extendFlat({duration:0,easing:"in-out-cubic",cascade:0,delay:0},h);h.duration>0;if(o)f=!0;else{for(u=0,o=[];un?1:-1})}},{"../../components/drawing":1071,"../../components/errorbars":1077,"../../lib":1127,"./arrays_to_calcdata":1300,"./line_points":1312,"./link_traces":1314,"./subtypes":1322,d3:82}],1319:[function(t,e,r){"use strict";var n=t("./subtypes"),i=.2;e.exports=function(t,e){var r,a,o,s,l=t.cd,u=t.xaxis,c=t.yaxis,f=[],h=l[0].trace,p=h.index,d=h.marker;if(n.hasMarkers(h)||n.hasText(h)){var g=Array.isArray(d.opacity)?1:d.opacity;if(e===!1)for(r=0;rs;s++){for(var l=[[0,0,0],[0,0,0]],u=0;3>u;u++)if(r[u])for(var c=0;2>c;c++)l[c][u]=r[u][s][c];o[s]=l}return o}var o=t("../../components/errorbars/compute_error");e.exports=a},{"../../components/errorbars/compute_error":1075}],1328:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.linePlot=null,this.scatterPlot=null,this.errorBars=null,this.textMarkers=null,this.delaunayMesh=null,this.color=null,this.mode="",this.dataPoints=[],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.textLabels=null,this.data=null}function i(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;ni;i++){var a=t[i];a&&a.copy_zstyle!==!1&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=b(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}function o(t){var e=[0,0];return Array.isArray(t)?[0,-1]:(t.indexOf("bottom")>=0&&(e[1]+=1),t.indexOf("top")>=0&&(e[1]-=1),t.indexOf("left")>=0&&(e[0]-=1),t.indexOf("right")>=0&&(e[0]+=1),e)}function s(t,e){return e(4*t)}function l(t){return k[t]}function u(t,e,r,n,i){var a=null;if(Array.isArray(t)){a=[];for(var o=0;e>o;o++)void 0===t[o]?a[o]=n:a[o]=r(t[o],i)}else a=r(t,y.identity);return a}function c(t,e){var r,n,i,c,f,h,p=[],d=t.fullSceneLayout,g=t.dataScale,v=d.xaxis,m=d.yaxis,w=d.zaxis,k=e.marker,M=e.line,T=e.x||[],E=e.y||[],L=e.z||[],S=T.length;for(n=0;S>n;n++)i=v.d2l(T[n])*g[0],c=m.d2l(E[n])*g[1],f=w.d2l(L[n])*g[2],p[n]=[i,c,f];if(Array.isArray(e.text))h=e.text;else if(void 0!==e.text)for(h=new Array(S),n=0;S>n;n++)h[n]=e.text;if(r={position:p,mode:e.mode,text:h},"line"in e&&(r.lineColor=b(M.color),r.lineWidth=M.width,r.lineDashes=M.dash),"marker"in e){var C=_(e);r.scatterColor=x(k,1,S),r.scatterSize=u(k.size,S,s,20,C),r.scatterMarker=u(k.symbol,S,l,"\u25cf"),r.scatterLineWidth=k.line.width,r.scatterLineColor=x(k.line,1,S),r.scatterAngle=0}"textposition"in e&&(r.textOffset=o(e.textposition),r.textColor=x(e.textfont,1,S),r.textSize=u(e.textfont.size,S,y.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var z=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;3>n;++n){var P=e.projection[z[n]];(r.project[n]=P.show)&&(r.projectOpacity[n]=P.opacity,r.projectScale[n]=P.scale)}r.errorBounds=A(e,g);var R=a([e.error_x,e.error_y,e.error_z]);return r.errorColor=R.color,r.errorLineWidth=R.lineWidth,r.errorCapSize=R.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=b(e.surfacecolor),r}function f(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}function h(t,e){var r=new n(t,e.uid);return r.update(e),r}var p=t("gl-line3d"),d=t("gl-scatter3d"),g=t("gl-error3d"),v=t("gl-mesh3d"),m=t("delaunay-triangulate"),y=t("../../lib"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/make_bubble_size_func"),w=t("../../constants/gl3d_dashes"),k=t("../../constants/gl_markers"),A=t("./calc_errors"),M=n.prototype;M.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels&&void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel="";var e=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},M.update=function(t){var e,r,n,a,o=this.scene.glplot.gl,s=w.solid;this.data=t;var l=c(this.scene,t);"mode"in l&&(this.mode=l.mode),"lineDashes"in l&&l.lineDashes in w&&(s=w[l.lineDashes]),this.color=f(l.scatterColor)||f(l.lineColor),this.dataPoints=l.position,e={gl:o,position:l.position,color:l.lineColor,lineWidth:l.lineWidth||1,dashes:s[0],dashScale:s[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=p(e),this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var u=t.opacity;if(t.marker&&t.marker.opacity&&(u*=t.marker.opacity),r={gl:o,position:l.position,color:l.scatterColor,size:l.scatterSize,glyph:l.scatterMarker,opacity:u,orthographic:!0,lineWidth:l.scatterLineWidth,lineColor:l.scatterLineColor,project:l.project,projectScale:l.projectScale,projectOpacity:l.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=d(r),this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),a={gl:o,position:l.position,glyph:l.text,color:l.textColor,size:l.textSize,angle:l.textAngle,alignment:l.textOffset,font:l.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=l.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(a):(this.textMarkers=d(a),this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:o,position:l.position,color:l.errorColor,error:l.errorBounds,lineWidth:l.errorLineWidth,capSize:l.errorCapSize,opacity:t.opacity},this.errorBars?l.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):l.errorBounds&&(this.errorBars=g(n),this.scene.glplot.add(this.errorBars)),l.delaunayAxis>=0){var h=i(l.position,l.delaunayColor,l.delaunayAxis);h.opacity=t.opacity,this.delaunayMesh?this.delaunayMesh.update(h):(h.gl=o,this.delaunayMesh=v(h),this.scene.glplot.add(this.delaunayMesh))}else this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose(),this.delaunayMesh=null)},M.dispose=function(){this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose()),this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose()),this.errorBars&&(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose()),this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose()),this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose())},e.exports=h},{"../../constants/gl3d_dashes":1113,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../scatter/make_bubble_size_func":1315,"./calc_errors":1327,"delaunay-triangulate":88,"gl-error3d":123,"gl-line3d":193,"gl-mesh3d":253,"gl-scatter3d":905}],1329:[function(t,e,r){"use strict";function n(t,e,r){var n=0,i=r("x"),a=r("y"),o=r("z");return i&&a&&o&&(n=Math.min(i.length,a.length,o.length),n=0&&h("surfacecolor",d||g);for(var v=["x","y","z"],m=0;3>m;++m){var y="projection."+v[m];h(y+".show")&&(h(y+".opacity"),h(y+".scale"))}u(t,e,r,{axis:"z"}),u(t,e,r,{axis:"y",inherit:"z"}),u(t,e,r,{axis:"x",inherit:"z"})}},{"../../components/errorbars/defaults":1076,"../../lib":1127,"../scatter/line_defaults":1311,"../scatter/marker_defaults":1317,"../scatter/subtypes":1322,"../scatter/text_defaults":1323,"./attributes":1325}],1330:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../constants/gl_markers":1114,"../../plots/gl3d":1186,"../scatter/colorbar":1304,"./attributes":1325,"./calc":1326,"./convert":1328,"./defaults":1329}],1331:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../components/colorscale/color_attributes"),o=t("../../lib/extend").extendFlat,s=n.marker,l=n.line,u=s.line;e.exports={lon:{valType:"data_array"},lat:{valType:"data_array"},locations:{valType:"data_array"},locationmode:{valType:"enumerated",values:["ISO-3","USA-states","country names"],dflt:"ISO-3"},mode:o({},n.mode,{dflt:"markers"}),text:o({},n.text,{}),line:{color:l.color,width:l.width,dash:l.dash},marker:o({},{symbol:s.symbol,opacity:s.opacity,size:s.size,sizeref:s.sizeref,sizemin:s.sizemin,sizemode:s.sizemode,showscale:s.showscale,line:o({},{width:u.width},a("marker.line"))},a("marker")),textfont:n.textfont,textposition:n.textposition,hoverinfo:o({},i.hoverinfo,{flags:["lon","lat","location","text","name"]}),_nestedModules:{"marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":1056,"../../lib/extend":1122,"../../plots/attributes":1148,"../scatter/attributes":1301}],1332:[function(t,e,r){"use strict";var n=t("../scatter/marker_colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(e),r}},{"../scatter/marker_colorscale_calc":1316}],1333:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=0,o=r("locations");return o?(r("locationmode"),a=o.length):(n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length),an;n++)r[n]=[t.lon[n],t.lat[n]];return{type:"LineString",coordinates:r,trace:t}}function a(t,e){function r(e){var r=t.mockAxis;return u.tickText(r,r.c2l(e),"hover").text+"\xb0"}var n=e.hoverinfo;if("none"===n)return function(t){delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("location")&&Array.isArray(e.locations),o=-1!==i.indexOf("lon"),s=-1!==i.indexOf("lat"),l=-1!==i.indexOf("text");return function(t){var n=[];a?n.push(t.location):o&&s?n.push("("+r(t.lon)+", "+r(t.lat)+")"):o?n.push("lon: "+r(t.lon)):s&&n.push("lat: "+r(t.lat)),l&&n.push(t.tx||e.text),t.textLabel=n.join("
")}}function o(t){var e=Array.isArray(t.locations);return function(r,n){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:n,lon:r.lon,lat:r.lat,location:e?r.location:null}]}}}var s=t("d3"),l=t("../../plots/cartesian/graph_interact"),u=t("../../plots/cartesian/axes"),c=t("../../lib/topojson_utils").getTopojsonFeatures,f=t("../../lib/geo_location_utils").locationToFeature,h=t("../../lib/array_to_calc_item"),p=t("../../components/color"),d=t("../../components/drawing"),g=t("../scatter/subtypes"),v=t("./attributes"),m=e.exports={}; -m.calcGeoJSON=function(t,e){var r,i,a,o,s=[],l=Array.isArray(t.locations);l?(o=t.locations,r=o.length,i=c(t,e),a=function(t,e){var r=f(t.locationmode,o[e],i);return void 0!==r?r.properties.ct:void 0}):(r=t.lon.length,a=function(t,e){return[t.lon[e],t.lat[e]]});for(var u=0;r>u;u++){var h=a(t,u);if(h){var p={lon:h[0],lat:h[1],location:l?t.locations[u]:null};n(t,p,u),s.push(p)}}return s.length>0&&(s[0].trace=t),s},m.plot=function(t,e){var r=t.framework.select(".scattergeolayer").selectAll("g.trace.scattergeo").data(e,function(t){return t.uid});r.enter().append("g").attr("class","trace scattergeo"),r.exit().remove(),r.selectAll("*").remove(),r.each(function(t){var e=s.select(this);g.hasLines(t)&&e.selectAll("path.js-line").data([i(t)]).enter().append("path").classed("js-line",!0)}),r.each(function(e){function r(r,n){if(t.showHover){var i=t.projection([r.lon,r.lat]);h(r),l.loneHover({x:i[0],y:i[1],name:v?e.name:void 0,text:r.textLabel,color:r.mc||(e.marker||{}).color},{container:t.hoverContainer.node()}),y=p(r,n),t.graphDiv.emit("plotly_hover",y)}}function n(e,r){t.graphDiv.emit("plotly_click",p(e,r))}var i=s.select(this),u=g.hasMarkers(e),c=g.hasText(e);if(u||c){var f=m.calcGeoJSON(e,t.topojson),h=a(t,e),p=o(e),d=e.hoverinfo,v="all"===d||-1!==d.indexOf("name"),y=null;u&&i.selectAll("path.point").data(f).enter().append("path").classed("point",!0).on("mouseover",r).on("click",n).on("mouseout",function(){l.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",y)}).on("mousedown",function(){l.loneUnhover(t.hoverContainer)}).on("mouseup",r),c&&i.selectAll("g").data(f).enter().append("g").append("text")}}),m.style(t)},m.style=function(t){var e=t.framework.selectAll("g.trace.scattergeo");e.style("opacity",function(t){return t.opacity}),e.each(function(t){s.select(this).selectAll("path.point").call(d.pointStyle,t),s.select(this).selectAll("text").call(d.textPointStyle,t)}),e.selectAll("path.js-line").style("fill","none").each(function(t){var e=t.trace,r=e.line||{};s.select(this).call(p.stroke,r.color).call(d.dashLine,r.dash||"",r.width||0)})}},{"../../components/color":1048,"../../components/drawing":1071,"../../lib/array_to_calc_item":1118,"../../lib/geo_location_utils":1124,"../../lib/topojson_utils":1141,"../../plots/cartesian/axes":1150,"../../plots/cartesian/graph_interact":1157,"../scatter/subtypes":1322,"./attributes":1331,d3:82}],1336:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/colorscale/color_attributes"),a=t("../../constants/gl2d_dashes"),o=t("../../constants/gl_markers"),s=t("../../lib/extend").extendFlat,l=t("../../lib/extend").extendDeep,u=n.line,c=n.marker,f=c.line;e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:s({},n.text,{}),mode:{valType:"flaglist",flags:["lines","markers"],extras:["none"]},line:{color:u.color,width:u.width,dash:{valType:"enumerated",values:Object.keys(a),dflt:"solid"}},marker:l({},i("marker"),{symbol:{valType:"enumerated",values:Object.keys(o),dflt:"circle",arrayOk:!0},size:c.size,sizeref:c.sizeref,sizemin:c.sizemin,sizemode:c.sizemode,opacity:c.opacity,showscale:c.showscale,line:l({},i("marker.line"),{width:f.width})}),connectgaps:n.connectgaps,fill:s({},n.fill,{values:["none","tozeroy","tozerox"]}),fillcolor:n.fillcolor,_nestedModules:{error_x:"ErrorBars",error_y:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/colorscale/color_attributes":1056,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib/extend":1122,"../scatter/attributes":1301}],1337:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.connectgaps=!0,this.idToIndex=[],this.bounds=[0,0,0,0],this.hasLines=!1,this.lineOptions={positions:new Float32Array(0),color:[0,0,0,1],width:1,fill:[!1,!1,!1,!1],fillColor:[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],dashes:[1]},this.line=p(t.glplot,this.lineOptions),this.line._trace=this,this.hasErrorX=!1,this.errorXOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorX=d(t.glplot,this.errorXOptions),this.errorX._trace=this,this.hasErrorY=!1,this.errorYOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorY=d(t.glplot,this.errorYOptions),this.errorY._trace=this,this.hasMarkers=!1,this.scatterOptions={positions:new Float32Array(0),sizes:[],colors:[],glyphs:[],borderWidths:[],borderColors:[],size:12,color:[0,0,0,1],borderSize:1,borderColor:[0,0,0,1]},this.scatter=f(t.glplot,this.scatterOptions),this.scatter._trace=this,this.fancyScatter=h(t.glplot,this.scatterOptions),this.fancyScatter._trace=this}function i(t,e,r){return Array.isArray(e)||(e=[e]),a(t,e,r)}function a(t,e,r){for(var n=new Array(r),i=e[0],a=0;r>a;++a)n[a]=t(a>=e.length?i:e[a]);return n}function o(t,e,r){return l(S(t,r),L(e,r),r)}function s(t,e,r,n){var i=x(t,e,n);return i=Array.isArray(i[0])?i:a(v.identity,[i],n),l(i,L(r,n),n)}function l(t,e,r){for(var n=new Array(4*r),i=0;r>i;++i){for(var a=0;3>a;++a)n[4*i+a]=t[i][a];n[4*i+3]=t[i][3]*e[i]}return n}function u(t,e){if(void 0===Float32Array.slice){for(var r=new Float32Array(e),n=0;e>n;n++)r[n]=t[n];return r}return t.slice(0,e)}function c(t,e){var r=new n(t,e.uid);return r.update(e),r}var f=t("gl-scatter2d"),h=t("gl-scatter2d-fancy"),p=t("gl-line2d"),d=t("gl-error2d"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../plots/cartesian/axes"),y=t("../../components/errorbars"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/subtypes"),w=t("../scatter/make_bubble_size_func"),k=t("../scatter/get_trace_color"),A=t("../../constants/gl_markers"),M=t("../../constants/gl2d_dashes"),T=["xaxis","yaxis"],E=n.prototype;E.handlePick=function(t){var e=t.pointId;return(t.object!==this.line||this.connectgaps)&&(e=this.idToIndex[t.pointId]),{trace:this,dataCoord:t.dataCoord,traceCoord:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:Array.isArray(this.color)?this.color[e]:this.color,name:this.name,hoverinfo:this.hoverinfo}},E.isFancy=function(t){if("linear"!==this.scene.xaxis.type)return!0;if("linear"!==this.scene.yaxis.type)return!0;if(!t.x||!t.y)return!0;if(this.hasMarkers){var e=t.marker||{};if(Array.isArray(e.symbol)||"circle"!==e.symbol||Array.isArray(e.size)||Array.isArray(e.color)||Array.isArray(e.line.width)||Array.isArray(e.line.color)||Array.isArray(e.opacity))return!0}return this.hasLines&&!this.connectgaps?!0:this.hasErrorX?!0:!!this.hasErrorY};var L=i.bind(null,function(t){return+t}),S=i.bind(null,b),C=i.bind(null,function(t){return A[t]||"\u25cf"});E.update=function(t){t.visible!==!0?(this.hasLines=!1,this.hasErrorX=!1,this.hasErrorY=!1,this.hasMarkers=!1):(this.hasLines=_.hasLines(t),this.hasErrorX=t.error_x.visible===!0,this.hasErrorY=t.error_y.visible===!0,this.hasMarkers=_.hasMarkers(t)),this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.connectgaps=!!t.connectgaps,this.isFancy(t)?this.updateFancy(t):this.updateFast(t),this.color=k(t,{})},E.updateFast=function(t){for(var e,r,n=this.xData=this.pickXData=t.x,i=this.yData=this.pickYData=t.y,a=n.length,o=new Array(a),s=new Float32Array(2*a),l=this.bounds,c=0,f=0,h=0;a>h;++h)e=n[h],r=i[h],g(e)&&g(r)&&(o[c++]=h,s[f++]=e,s[f++]=r,l[0]=Math.min(l[0],e),l[1]=Math.min(l[1],r),l[2]=Math.max(l[2],e),l[3]=Math.max(l[3],r));s=u(s,f),this.idToIndex=o,this.updateLines(t,s),this.updateError("X",t),this.updateError("Y",t);var p;if(this.hasMarkers){this.scatterOptions.positions=s;var d=b(t.marker.color),v=b(t.marker.line.color),m=t.opacity*t.marker.opacity;d[3]*=m,this.scatterOptions.color=d,v[3]*=m,this.scatterOptions.borderColor=v,p=t.marker.size,this.scatterOptions.size=p,this.scatterOptions.borderSize=t.marker.line.width,this.scatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions),this.expandAxesFast(l,p)},E.updateFancy=function(t){var e=this.scene,r=e.xaxis,n=e.yaxis,a=this.bounds,o=this.pickXData=r.makeCalcdata(t,"x").slice(),l=this.pickYData=n.makeCalcdata(t,"y").slice();this.xData=o.slice(),this.yData=l.slice();var c,f,h,p,d,g,v,m,b=y.calcFromTrace(t,e.fullLayout),x=o.length,_=new Array(x),k=new Float32Array(2*x),A=new Float32Array(4*x),M=new Float32Array(4*x),T=0,E=0,S=0,z=0,P="log"===r.type?function(t){return r.d2l(t)}:function(t){return t},R="log"===n.type?function(t){return n.d2l(t)}:function(t){return t};for(c=0;x>c;++c)this.xData[c]=h=P(o[c]),this.yData[c]=p=R(l[c]),isNaN(h)||isNaN(p)||(_[T++]=c,k[E++]=h,k[E++]=p,d=A[S++]=h-b[c].xs||0,g=A[S++]=b[c].xh-h||0,A[S++]=0,A[S++]=0,M[z++]=0,M[z++]=0,v=M[z++]=p-b[c].ys||0,m=M[z++]=b[c].yh-p||0,a[0]=Math.min(a[0],h-d),a[1]=Math.min(a[1],p-v),a[2]=Math.max(a[2],h+g),a[3]=Math.max(a[3],p+m));k=u(k,E),this.idToIndex=_,this.updateLines(t,k),this.updateError("X",t,k,A),this.updateError("Y",t,k,M);var j;if(this.hasMarkers){this.scatterOptions.positions=k,this.scatterOptions.sizes=new Array(T),this.scatterOptions.glyphs=new Array(T),this.scatterOptions.borderWidths=new Array(T),this.scatterOptions.colors=new Array(4*T),this.scatterOptions.borderColors=new Array(4*T);var O,I=w(t),N=t.marker,F=N.opacity,D=t.opacity,B=s(N,F,D,x),U=C(N.symbol,x),V=L(N.line.width,x),q=s(N.line,F,D,x);for(j=i(I,N.size,x),c=0;T>c;++c)for(O=_[c],this.scatterOptions.sizes[c]=4*j[O],this.scatterOptions.glyphs[c]=U[O],this.scatterOptions.borderWidths[c]=.5*V[O],f=0;4>f;++f)this.scatterOptions.colors[4*c+f]=B[4*O+f],this.scatterOptions.borderColors[4*c+f]=q[4*O+f];this.fancyScatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions),this.expandAxesFancy(o,l,j)},E.updateLines=function(t,e){var r;if(this.hasLines){var n=e;if(!t.connectgaps){var i=0,a=this.xData,s=this.yData;for(n=new Float32Array(2*a.length),r=0;ro;o++)r=this.scene[T[o]],n=r._min,n||(n=[]),n.push({val:t[o],pad:a}),i=r._max,i||(i=[]),i.push({val:t[o+2],pad:a})},E.expandAxesFancy=function(t,e,r){var n=this.scene,i={padded:!0,ppad:r};m.expand(n.xaxis,t,i),m.expand(n.yaxis,e,i)},E.dispose=function(){this.line.dispose(),this.errorX.dispose(),this.errorY.dispose(),this.scatter.dispose(),this.fancyScatter.dispose()},e.exports=c},{"../../components/errorbars":1077,"../../constants/gl2d_dashes":1112,"../../constants/gl_markers":1114,"../../lib":1127,"../../lib/gl_format_color":1125,"../../lib/str2rgbarray":1139,"../../plots/cartesian/axes":1150,"../scatter/get_trace_color":1308,"../scatter/make_bubble_size_func":1315,"../scatter/subtypes":1322,"fast-isnumeric":90,"gl-error2d":91,"gl-line2d":160,"gl-scatter2d":781,"gl-scatter2d-fancy":746}],1338:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/xy_defaults"),s=t("../scatter/marker_defaults"),l=t("../scatter/line_defaults"),u=t("../scatter/fillcolor_defaults"),c=t("../../components/errorbars/defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function p(r,i){return n.coerce(t,e,f,r,i)}var d=o(t,e,p);return d?(p("text"),p("mode",dr;r++)y=e.a[r],b=e.b[r],x=e.c[r],n(y)&&n(b)&&n(x)?(y=+y,b=+b,x=+x,_=v/(y+b+x),1!==_&&(y*=_,b*=_,x*=_),k=y,w=x-b,M[r]={x:w,y:k,a:y,b:b,c:x}):M[r]={x:!1,y:!1};var T,E;if(o.hasMarkers(e)&&(T=e.marker,E=T.size,Array.isArray(E))){var L={type:"linear"};i.setConvert(L),E=L.makeCalcdata(e.marker,"size"),E.length>A&&E.splice(A,E.length-A)}return s(e),void 0!==typeof E&&a.mergeArray(E,M,"ms"),M}},{"../../lib":1127,"../../plots/cartesian/axes":1150,"../scatter/marker_colorscale_calc":1316,"../scatter/subtypes":1322,"fast-isnumeric":90}],1342:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/line_shape_defaults"),u=t("../scatter/text_defaults"),c=t("../scatter/fillcolor_defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function p(r,i){return n.coerce(t,e,f,r,i)}var d,g=p("a"),v=p("b"),m=p("c");if(g?(d=g.length,v?(d=Math.min(d,v.length),m&&(d=Math.min(d,m.length))):d=m?Math.min(d,m.length):0):v&&m&&(d=Math.min(v.length,m.length)),!d)return void(e.visible=!1);g&&d"),s}}},{"../../plots/cartesian/axes":1150,"../scatter/hover":1309}],1344:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scatterternary",n.basePlotModule=t("../../plots/ternary"),n.categories=["ternary","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../plots/ternary":1206,"../scatter/colorbar":1304,"./attributes":1340,"./calc":1341,"./defaults":1342,"./hover":1343,"./plot":1345,"./select":1346,"./style":1347}],1345:[function(t,e,r){"use strict";var n=t("../scatter/plot");e.exports=function(t,e){var r=t.plotContainer;r.select(".scatterlayer").selectAll("*").remove();for(var i={x:function(){return t.xaxis},y:function(){return t.yaxis},plot:r},a=new Array(e.length),o=t.graphDiv.calcdata,s=0;se){for(var r=g/e,n=[0|Math.floor(t[0].shape[0]*r+1),0|Math.floor(t[0].shape[1]*r+1)],i=n[0]*n[1],o=0;or;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},v.update=function(t){var e,r=this.scene,n=r.fullSceneLayout,a=this.surface,s=t.opacity,l=i(t.colorscale,s),c=t.z,h=t.x,p=t.y,g=n.xaxis,v=n.yaxis,m=n.zaxis,y=r.dataScale,b=c[0].length,x=c.length,_=[u(new Float32Array(b*x),[b,x]),u(new Float32Array(b*x),[b,x]),u(new Float32Array(b*x),[b,x])],w=_[0],k=_[1],A=r.contourLevels;this.data=t,f(_[2],function(t,e){return m.d2l(c[e][t])*y[2]}),Array.isArray(h[0])?f(w,function(t,e){return g.d2l(h[e][t])*y[0]}):f(w,function(t){return g.d2l(h[t])*y[0]}),Array.isArray(p[0])?f(k,function(t,e){return v.d2l(p[e][t])*y[1]}):f(k,function(t,e){return v.d2l(p[e])*y[1]});var M={colormap:l,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:1};if(M.intensityBounds=[t.cmin,t.cmax],t.surfacecolor){var T=u(new Float32Array(b*x),[b,x]);f(T,function(e,r){return t.surfacecolor[r][e]}),_.push(T)}else M.intensityBounds[0]*=y[2],M.intensityBounds[1]*=y[2];this.dataScale=o(_),t.surfacecolor&&(M.intensity=_.pop()),"opacity"in t&&t.opacity<1&&(M.opacity=.25*t.opacity);var E=[!0,!0,!0],L=["x","y","z"];for(e=0;3>e;++e){var S=t.contours[L[e]];E[e]=S.highlight,M.showContour[e]=S.show||S.highlight,M.showContour[e]&&(M.contourProject[e]=[S.project.x,S.project.y,S.project.z],S.show?(this.showContour[e]=!0,M.levels[e]=A[e],a.highlightColor[e]=M.contourColor[e]=d(S.color),S.usecolormap?a.highlightTint[e]=M.contourTint[e]=0:a.highlightTint[e]=M.contourTint[e]=1,M.contourWidth[e]=S.width):this.showContour[e]=!1,S.highlight&&(M.dynamicColor[e]=d(S.highlightcolor),M.dynamicWidth[e]=S.highlightwidth))}M.coords=_,a.update(M),a.visible=t.visible,a.enableDynamic=E,a.snapToData=!0,"lighting"in t&&(a.ambientLight=t.lighting.ambient,a.diffuseLight=t.lighting.diffuse,a.specularLight=t.lighting.specular,a.roughness=t.lighting.roughness,a.fresnel=t.lighting.fresnel),"lightposition"in t&&(a.lightPosition=[t.lightposition.x,t.lightposition.y,t.lightposition.z]),s&&1>s&&(a.supportsTransparency=!0)},v.dispose=function(){this.scene.glplot.remove(this.surface),this.surface.dispose()},e.exports=s},{"../../lib/str2rgbarray":1139,"gl-surface3d":1003,ndarray:1031,"ndarray-fill":1009,"ndarray-homography":1025,"ndarray-ops":1026,tinycolor2:1042}],1352:[function(t,e,r){"use strict";function n(t,e,r){e in t&&!(r in t)&&(t[r]=t[e])}var i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}var u,c,f=l("z");if(!f)return void(e.visible=!1);var h=f[0].length,p=f.length;if(l("x"),l("y"),!Array.isArray(e.x))for(e.x=[],u=0;h>u;++u)e.x[u]=u;if(l("text"),!Array.isArray(e.y))for(e.y=[],u=0;p>u;++u)e.y[u]=u;["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lightposition.x","lightposition.y","lightposition.z","hidesurface","opacity"].forEach(function(t){l(t)});var d=l("surfacecolor");l("colorscale");var g=["x","y","z"];for(u=0;3>u;++u){var v="contours."+g[u],m=l(v+".show"),y=l(v+".highlight");if(m||y)for(c=0;3>c;++c)l(v+".project."+g[c]);m&&(l(v+".color"),l(v+".width"),l(v+".usecolormap")),y&&(l(v+".highlightcolor"),l(v+".highlightwidth"))}d||(n(t,"zmin","cmin"),n(t,"zmax","cmax"),n(t,"zauto","cauto")),a(t,e,s,l,{prefix:"",cLetter:"c"})}},{"../../components/colorscale/defaults":1058,"../../lib":1127,"./attributes":1348}],1353:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("./colorbar"),n.calc=t("./calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="surface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","noOpacity"],n.meta={},e.exports=n},{"../../plots/gl3d":1186,"./attributes":1348,"./calc":1349,"./colorbar":1350,"./convert":1351,"./defaults":1352}]},{},[12])(12)}); \ No newline at end of file +!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.Plotly=t()}}(function(){var t;return function e(t,r,n){function i(o,s){if(!r[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[o]={exports:{}};t[o][0].call(u.exports,function(e){var r=t[o][1][e];return i(r?r:e)},u,u.exports,e,t,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;or;++r)e[r]=0;return e}function o(t,e,r){switch(arguments.length){case 0:return new i([0],[0],0);case 1:if("number"==typeof t){var n=a(t);return new i(n,n,0)}return new i(t,a(t.length),0);case 2:if("number"==typeof e){var n=a(t.length);return new i(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new i(t,e,r)}}e.exports=o;var s=t("cubic-hermite"),l=t("binary-search-bounds"),c=i.prototype;c.flush=function(t){var e=l.gt(this._time,t)-1;0>=e||(this._time.splice(0,e),this._state.splice(0,e*this.dimension),this._velocity.splice(0,e*this.dimension))},c.curve=function(t){var e=this._time,r=e.length,i=l.le(e,t),a=this._scratch[0],o=this._state,c=this._velocity,u=this.dimension,f=this.bounds;if(0>i)for(var h=u-1,d=0;u>d;++d,--h)a[d]=o[h];else if(i>=r-1)for(var h=o.length-1,p=t-e[r-1],d=0;u>d;++d,--h)a[d]=o[h]+p*c[h];else{for(var h=u*(i+1)-1,g=e[i],v=e[i+1],m=v-g||1,y=this._scratch[1],b=this._scratch[2],x=this._scratch[3],_=this._scratch[4],w=!0,d=0;u>d;++d,--h)y[d]=o[h],x[d]=c[h]*m,b[d]=o[h+u],_[d]=c[h+u]*m,w=w&&y[d]===b[d]&&x[d]===_[d]&&0===x[d];if(w)for(var d=0;u>d;++d)a[d]=y[d];else s(y,x,b,_,(t-g)/m,a)}for(var k=f[0],A=f[1],d=0;u>d;++d)a[d]=n(k[d],A[d],a[d]);return a},c.dcurve=function(t){var e=this._time,r=e.length,n=l.le(e,t),i=this._scratch[0],a=this._state,o=this._velocity,c=this.dimension;if(n>=r-1)for(var u=a.length-1,f=(t-e[r-1],0);c>f;++f,--u)i[f]=o[u];else{for(var u=c*(n+1)-1,h=e[n],d=e[n+1],p=d-h||1,g=this._scratch[1],v=this._scratch[2],m=this._scratch[3],y=this._scratch[4],b=!0,f=0;c>f;++f,--u)g[f]=a[u],m[f]=o[u]*p,v[f]=a[u+c],y[f]=o[u+c]*p,b=b&&g[f]===v[f]&&m[f]===y[f]&&0===m[f];if(b)for(var f=0;c>f;++f)i[f]=0;else{s.derivative(g,m,v,y,(t-h)/p,i);for(var f=0;c>f;++f)i[f]/=p}}return i},c.lastT=function(){var t=this._time;return t[t.length-1]},c.stable=function(){for(var t=this._velocity,e=t.length,r=this.dimension-1;r>=0;--r)if(t[--e])return!1;return!0},c.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],c=s[1];this._time.push(e,t);for(var u=0;2>u;++u)for(var f=0;r>f;++f)i.push(i[o++]),a.push(0);this._time.push(t);for(var f=r;f>0;--f)i.push(n(l[f-1],c[f-1],arguments[f])),a.push(0)}},c.push=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=t-e,l=this.bounds,c=l[0],u=l[1],f=s>1e-6?1/s:0;this._time.push(t);for(var h=r;h>0;--h){var d=n(c[h-1],u[h-1],arguments[h]);i.push(d),a.push((d-i[o++])*f)}}},c.set=function(t){var e=this.dimension;if(!(t0;--l)r.push(n(o[l-1],s[l-1],arguments[l])),i.push(0)}},c.move=function(t){var e=this.lastT(),r=this.dimension;if(!(e>=t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],c=s[1],u=t-e,f=u>1e-6?1/u:0;this._time.push(t);for(var h=r;h>0;--h){var d=arguments[h];i.push(n(l[h-1],c[h-1],i[o++]+d)),a.push(d*f)}}},c.idle=function(t){var e=this.lastT();if(!(e>t)){var r=this.dimension,i=this._state,a=this._velocity,o=i.length-r,s=this.bounds,l=s[0],c=s[1],u=t-e;this._time.push(t);for(var f=r-1;f>=0;--f)i.push(n(l[f],c[f],i[o]+u*a[o])),a.push(0),o+=1}}},{"binary-search-bounds":21,"cubic-hermite":22}],21:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],22:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,c=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var u=t.length-1;u>=0;--u)a[u]=o*t[u]+s*e[u]+l*r[u]+c*n[u];return a}return o*t+s*e+l*r[u]+c*n}function i(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,c=(1+2*i)*l,u=i*l,f=s*(3-2*i),h=s*o;if(t.length){a||(a=new Array(t.length));for(var d=t.length-1;d>=0;--d)a[d]=c*t[d]+u*e[d]+f*r[d]+h*n[d];return a}return c*t+u*e+f*r+h*n}e.exports=i,e.exports.derivative=n},{}],23:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t}e.exports=n},{}],24:[function(t,e,r){function n(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}e.exports=n},{}],25:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}e.exports=n},{}],26:[function(t,e,r){function n(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}e.exports=n},{}],27:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a),t}e.exports=n},{}],28:[function(t,e,r){"use strict";function n(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-(1/0),1/0]}function i(t){t=t||{};var e=t.matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return new n(e)}var a=t("binary-search-bounds"),o=t("mat4-interpolate"),s=t("gl-mat4/invert"),l=t("gl-mat4/rotateX"),c=t("gl-mat4/rotateY"),u=t("gl-mat4/rotateZ"),f=t("gl-mat4/lookAt"),h=t("gl-mat4/translate"),d=(t("gl-mat4/scale"),t("gl-vec3/normalize")),p=[0,0,0];e.exports=i;var g=n.prototype;g.recalcMatrix=function(t){var e=this._time,r=a.le(e,t),n=this.computedMatrix;if(!(0>r)){var i=this._components;if(r===e.length-1)for(var l=16*r,c=0;16>c;++c)n[c]=i[l++];else{for(var u=e[r+1]-e[r],l=16*r,f=this.prevMatrix,h=!0,c=0;16>c;++c)f[c]=i[l++];for(var p=this.nextMatrix,c=0;16>c;++c)p[c]=i[l++],h=h&&f[c]===p[c];if(1e-6>u||h)for(var c=0;16>c;++c)n[c]=f[c];else o(n,f,p,(t-e[r])/u)}var g=this.computedUp;g[0]=n[1],g[1]=n[5],g[2]=n[6],d(g,g);var v=this.computedInverse;s(v,n);var m=this.computedEye,y=v[15];m[0]=v[12]/y,m[1]=v[13]/y,m[2]=v[14]/y;for(var b=this.computedCenter,x=Math.exp(this.computedRadius[0]),c=0;3>c;++c)b[c]=m[c]-n[2+4*c]*x}},g.idle=function(t){if(!(tn;++n)e.push(e[r++]);this._time.push(t)}},g.flush=function(t){var e=a.gt(this._time,t)-2;0>e||(this._time.slice(0,e),this._components.slice(0,16*e))},g.lastT=function(){return this._time[this._time.length-1]},g.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||p,n=n||this.computedUp,this.setMatrix(t,f(this.computedMatrix,e,r,n));for(var i=0,a=0;3>a;++a)i+=Math.pow(r[a]-e[a],2);i=Math.log(Math.sqrt(i)),this.computedRadius[0]=i},g.rotate=function(t,e,r,n){this.recalcMatrix(t);var i=this.computedInverse;e&&c(i,i,e),r&&l(i,i,r),n&&u(i,i,n),this.setMatrix(t,s(this.computedMatrix,i))};var v=[0,0,0];g.pan=function(t,e,r,n){v[0]=-(e||0),v[1]=-(r||0),v[2]=-(n||0),this.recalcMatrix(t);var i=this.computedInverse;h(i,i,v),this.setMatrix(t,s(i,i))},g.translate=function(t,e,r,n){v[0]=e||0,v[1]=r||0,v[2]=n||0,this.recalcMatrix(t);var i=this.computedMatrix;h(i,i,v),this.setMatrix(t,i)},g.setMatrix=function(t,e){if(!(tr;++r)this._components.push(e[r])}},g.setDistance=function(t,e){this.computedRadius[0]=e},g.setDistanceLimits=function(t,e){var r=this._limits;r[0]=t,r[1]=e},g.getDistanceLimits=function(t){var e=this._limits;return t?(t[0]=e[0],t[1]=e[1],t):e}},{"binary-search-bounds":29,"gl-mat4/invert":137,"gl-mat4/lookAt":138,"gl-mat4/rotateX":142,"gl-mat4/rotateY":143,"gl-mat4/rotateZ":144,"gl-mat4/scale":145,"gl-mat4/translate":146,"gl-vec3/normalize":27,"mat4-interpolate":30}],29:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],30:[function(t,e,r){function n(t,e,r,n){if(0===u(e)||0===u(r))return!1;var i=c(e,h.translate,h.scale,h.skew,h.perspective,h.quaternion),a=c(r,d.translate,d.scale,d.skew,d.perspective,d.quaternion);return i&&a?(s(p.translate,h.translate,d.translate,n),s(p.skew,h.skew,d.skew,n),s(p.scale,h.scale,d.scale,n),s(p.perspective,h.perspective,d.perspective,n),f(p.quaternion,h.quaternion,d.quaternion,n),l(t,p.translate,p.scale,p.skew,p.perspective,p.quaternion),!0):!1}function i(){return{translate:a(),scale:a(1),skew:a(),perspective:o(),quaternion:o()}}function a(t){return[t||0,t||0,t||0]}function o(){return[0,0,0,1]}var s=t("gl-vec3/lerp"),l=t("mat4-recompose"),c=t("mat4-decompose"),u=t("gl-mat4/determinant"),f=t("quat-slerp"),h=i(),d=i(),p=i();e.exports=n},{"gl-mat4/determinant":133,"gl-vec3/lerp":26,"mat4-decompose":31,"mat4-recompose":33,"quat-slerp":34}],31:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function i(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}function a(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var o=t("./normalize"),s=t("gl-mat4/create"),l=t("gl-mat4/clone"),c=t("gl-mat4/determinant"),u=t("gl-mat4/invert"),f=t("gl-mat4/transpose"),h={length:t("gl-vec3/length"),normalize:t("gl-vec3/normalize"),dot:t("gl-vec3/dot"),cross:t("gl-vec3/cross")},d=s(),p=s(),g=[0,0,0,0],v=[[0,0,0],[0,0,0],[0,0,0]],m=[0,0,0];e.exports=function(t,e,r,s,y,b){if(e||(e=[0,0,0]),r||(r=[0,0,0]),s||(s=[0,0,0]),y||(y=[0,0,0,1]),b||(b=[0,0,0,1]),!o(d,t))return!1;if(l(p,d),p[3]=0,p[7]=0,p[11]=0,p[15]=1,Math.abs(c(p)<1e-8))return!1;var x=d[3],_=d[7],w=d[11],k=d[12],A=d[13],M=d[14],T=d[15];if(0!==x||0!==_||0!==w){g[0]=x,g[1]=_,g[2]=w,g[3]=T;var E=u(p,p);if(!E)return!1;f(p,p),n(y,g,p)}else y[0]=y[1]=y[2]=0,y[3]=1;if(e[0]=k,e[1]=A,e[2]=M,i(v,d),r[0]=h.length(v[0]),h.normalize(v[0],v[0]),s[0]=h.dot(v[0],v[1]),a(v[1],v[1],v[0],1,-s[0]),r[1]=h.length(v[1]),h.normalize(v[1],v[1]),s[0]/=r[1],s[1]=h.dot(v[0],v[2]),a(v[2],v[2],v[0],1,-s[1]),s[2]=h.dot(v[1],v[2]),a(v[2],v[2],v[1],1,-s[2]),r[2]=h.length(v[2]),h.normalize(v[2],v[2]),s[1]/=r[2],s[2]/=r[2],h.cross(m,v[1],v[2]),h.dot(v[0],m)<0)for(var L=0;3>L;L++)r[L]*=-1,v[L][0]*=-1,v[L][1]*=-1,v[L][2]*=-1;return b[0]=.5*Math.sqrt(Math.max(1+v[0][0]-v[1][1]-v[2][2],0)),b[1]=.5*Math.sqrt(Math.max(1-v[0][0]+v[1][1]-v[2][2],0)),b[2]=.5*Math.sqrt(Math.max(1-v[0][0]-v[1][1]+v[2][2],0)),b[3]=.5*Math.sqrt(Math.max(1+v[0][0]+v[1][1]+v[2][2],0)),v[2][1]>v[1][2]&&(b[0]=-b[0]),v[0][2]>v[2][0]&&(b[1]=-b[1]),v[1][0]>v[0][1]&&(b[2]=-b[2]),!0}},{"./normalize":32,"gl-mat4/clone":131,"gl-mat4/create":132,"gl-mat4/determinant":133,"gl-mat4/invert":137,"gl-mat4/transpose":147,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/length":25,"gl-vec3/normalize":27}],32:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;16>i;i++)t[i]=e[i]*n;return!0}},{}],33:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":132,"gl-mat4/fromRotationTranslation":135,"gl-mat4/identity":136,"gl-mat4/multiply":139,"gl-mat4/scale":145,"gl-mat4/translate":146}],34:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":35}],35:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,c=e[0],u=e[1],f=e[2],h=e[3],d=r[0],p=r[1],g=r[2],v=r[3];return a=c*d+u*p+f*g+h*v,0>a&&(a=-a,d=-d,p=-p,g=-g,v=-v),1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n),t[0]=s*c+l*d,t[1]=s*u+l*p,t[2]=s*f+l*g,t[3]=s*h+l*v,t}e.exports=n},{}],36:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,c){var u=e+a+c;if(f>0){var f=Math.sqrt(u+1);t[0]=.5*(o-l)/f,t[1]=.5*(s-n)/f,t[2]=.5*(r-a)/f,t[3]=.5*f}else{var h=Math.max(e,a,c),f=Math.sqrt(2*h-u+1);e>=h?(t[0]=.5*f,t[1]=.5*(i+r)/f,t[2]=.5*(s+n)/f,t[3]=.5*(o-l)/f):a>=h?(t[0]=.5*(r+i)/f,t[1]=.5*f,t[2]=.5*(l+o)/f,t[3]=.5*(s-n)/f):(t[0]=.5*(n+s)/f,t[1]=.5*(o+l)/f,t[2]=.5*f,t[3]=.5*(r-i)/f)}return t}e.exports=n},{}],37:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function a(t,e){var r=e[0],n=e[1],a=e[2],o=e[3],s=i(r,n,a,o);s>1e-6?(t[0]=r/s,t[1]=n/s,t[2]=a/s,t[3]=o/s):(t[0]=t[1]=t[2]=0,t[3]=1)}function o(t,e,r){this.radius=l([r]),this.center=l(e),this.rotation=l(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),r=[].slice.call(r,0,4),a(r,r);var i=new o(r,e,Math.log(n));return i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up),i}e.exports=s;var l=t("filtered-vector"),c=t("gl-mat4/lookAt"),u=t("gl-mat4/fromQuat"),f=t("gl-mat4/invert"),h=t("./lib/quatFromFrame"),d=o.prototype;d.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},d.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;a(e,e);var r=this.computedMatrix;u(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;3>l;++l){for(var c=0,f=0;3>f;++f)c+=r[l+4*f]*i[f];r[12+l]=-c}},d.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r},d.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},d.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},d.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=a[1],s=a[5],l=a[9],c=n(o,s,l);o/=c,s/=c,l/=c;var u=a[0],f=a[4],h=a[8],d=u*o+f*s+h*l;u-=o*d,f-=s*d,h-=l*d;var p=n(u,f,h);u/=p,f/=p,h/=p;var g=a[2],v=a[6],m=a[10],y=g*o+v*s+m*l,b=g*u+v*f+m*h;g-=y*o+b*u,v-=y*s+b*f,m-=y*l+b*h;var x=n(g,v,m);g/=x,v/=x,m/=x;var _=u*e+o*r,w=f*e+s*r,k=h*e+l*r;this.center.move(t,_,w,k);var A=Math.exp(this.computedRadius[0]);A=Math.max(1e-4,A+i),this.radius.set(t,Math.log(A))},d.rotate=function(t,e,r,a){this.recalcMatrix(t),e=e||0,r=r||0;var o=this.computedMatrix,s=o[0],l=o[4],c=o[8],u=o[1],f=o[5],h=o[9],d=o[2],p=o[6],g=o[10],v=e*s+r*u,m=e*l+r*f,y=e*c+r*h,b=-(p*y-g*m),x=-(g*v-d*y),_=-(d*m-p*v),w=Math.sqrt(Math.max(0,1-Math.pow(b,2)-Math.pow(x,2)-Math.pow(_,2))),k=i(b,x,_,w);k>1e-6?(b/=k,x/=k,_/=k,w/=k):(b=x=_=0,w=1);var A=this.computedRotation,M=A[0],T=A[1],E=A[2],L=A[3],S=M*w+L*b+T*_-E*x,C=T*w+L*x+E*b-M*_,z=E*w+L*_+M*x-T*b,P=L*w-M*b-T*x-E*_;if(a){b=d,x=p,_=g;var R=Math.sin(a)/n(b,x,_);b*=R,x*=R,_*=R,w=Math.cos(e),S=S*w+P*b+C*_-z*x,C=C*w+P*x+z*b-S*_,z=z*w+P*_+S*x-C*b,P=P*w-S*b-C*x-z*_}var O=i(S,C,z,P);O>1e-6?(S/=O,C/=O,z/=O,P/=O):(S=C=z=0,P=1),this.rotation.set(t,S,C,z,P)},d.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;c(i,e,r,n);var o=this.computedRotation;h(o,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),a(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var s=0,l=0;3>l;++l)s+=Math.pow(r[l]-e[l],2);this.radius.set(t,.5*Math.log(Math.max(s,1e-6))),this.center.set(t,r[0],r[1],r[2])},d.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},d.setMatrix=function(t,e){var r=this.computedRotation;h(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),a(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;f(n,e);var i=n[15];if(Math.abs(i)>1e-6){var o=n[12]/i,s=n[13]/i,l=n[14]/i;this.recalcMatrix(t);var c=Math.exp(this.computedRadius[0]);this.center.set(t,o-n[2]*c,s-n[6]*c,l-n[10]*c),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},d.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},d.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},d.getDistanceLimits=function(t){var e=this.radius.bounds; +return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},d.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},d.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":36,"filtered-vector":20,"gl-mat4/fromQuat":134,"gl-mat4/invert":137,"gl-mat4/lookAt":138}],38:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t){return Math.min(1,Math.max(-1,t))}function a(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;3>s;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(var s=0;3>s;++s)i[s]-=o/a*t[s];return h(i,i),i}function o(t,e,r,n,i,a,o,s){this.center=l(r),this.up=l(n),this.right=l(i),this.radius=l([a]),this.angle=l([o,s]),this.angle.bounds=[[-(1/0),-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var c=0;16>c;++c)this.computedMatrix[c]=.5;this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.up||[0,1,0],i=t.right||a(r),s=t.radius||1,l=t.theta||0,c=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),h(r,r),i=[].slice.call(i,0,3),h(i,i),"eye"in t){var u=t.eye,p=[u[0]-e[0],u[1]-e[1],u[2]-e[2]];f(i,p,r),n(i[0],i[1],i[2])<1e-6?i=a(r):h(i,i),s=n(p[0],p[1],p[2]);var g=d(r,p)/s,v=d(i,p)/s;c=Math.acos(g),l=Math.acos(v)}return s=Math.log(s),new o(t.zoomMin,t.zoomMax,e,r,i,s,l,c)}e.exports=s;var l=t("filtered-vector"),c=t("gl-mat4/invert"),u=t("gl-mat4/rotate"),f=t("gl-vec3/cross"),h=t("gl-vec3/normalize"),d=t("gl-vec3/dot"),p=o.prototype;p.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},p.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},p.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,i=0,a=0,o=0;3>o;++o)a+=e[o]*r[o],i+=e[o]*e[o];for(var s=Math.sqrt(i),l=0,o=0;3>o;++o)r[o]-=e[o]*a/i,l+=r[o]*r[o],e[o]/=s;for(var c=Math.sqrt(l),o=0;3>o;++o)r[o]/=c;var u=this.computedToward;f(u,e,r),h(u,u);for(var d=Math.exp(this.computedRadius[0]),p=this.computedAngle[0],g=this.computedAngle[1],v=Math.cos(p),m=Math.sin(p),y=Math.cos(g),b=Math.sin(g),x=this.computedCenter,_=v*y,w=m*y,k=b,A=-v*b,M=-m*b,T=y,E=this.computedEye,L=this.computedMatrix,o=0;3>o;++o){var S=_*r[o]+w*u[o]+k*e[o];L[4*o+1]=A*r[o]+M*u[o]+T*e[o],L[4*o+2]=S,L[4*o+3]=0}var C=L[1],z=L[5],P=L[9],R=L[2],O=L[6],I=L[10],N=z*I-P*O,j=P*R-C*I,F=C*O-z*R,D=n(N,j,F);N/=D,j/=D,F/=D,L[0]=N,L[4]=j,L[8]=F;for(var o=0;3>o;++o)E[o]=x[o]+L[2+4*o]*d;for(var o=0;3>o;++o){for(var l=0,B=0;3>B;++B)l+=L[o+4*B]*E[B];L[12+o]=-l}L[15]=1},p.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r};var g=[0,0,0];p.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;g[0]=i[2],g[1]=i[6],g[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;3>l;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];u(i,i,n,g);for(var l=0;3>l;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},p.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=(Math.exp(this.computedRadius[0]),a[1]),s=a[5],l=a[9],c=n(o,s,l);o/=c,s/=c,l/=c;var u=a[0],f=a[4],h=a[8],d=u*o+f*s+h*l;u-=o*d,f-=s*d,h-=l*d;var p=n(u,f,h);u/=p,f/=p,h/=p;var g=u*e+o*r,v=f*e+s*r,m=h*e+l*r;this.center.move(t,g,v,m);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+i),this.radius.set(t,Math.log(y))},p.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},p.setMatrix=function(t,e,r,a){var o=1;"number"==typeof r&&(o=0|r),(0>o||o>3)&&(o=1);var s=(o+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var l=e[o],u=e[o+4],f=e[o+8];if(a){var h=Math.abs(l),d=Math.abs(u),p=Math.abs(f),g=Math.max(h,d,p);h===g?(l=0>l?-1:1,u=f=0):p===g?(f=0>f?-1:1,l=u=0):(u=0>u?-1:1,l=f=0)}else{var v=n(l,u,f);l/=v,u/=v,f/=v}var m=e[s],y=e[s+4],b=e[s+8],x=m*l+y*u+b*f;m-=l*x,y-=u*x,b-=f*x;var _=n(m,y,b);m/=_,y/=_,b/=_;var w=u*b-f*y,k=f*m-l*b,A=l*y-u*m,M=n(w,k,A);w/=M,k/=M,A/=M,this.center.jump(t,H,G,Y),this.radius.idle(t),this.up.jump(t,l,u,f),this.right.jump(t,m,y,b);var T,E;if(2===o){var L=e[1],S=e[5],C=e[9],z=L*m+S*y+C*b,P=L*w+S*k+C*A;T=0>N?-Math.PI/2:Math.PI/2,E=Math.atan2(P,z)}else{var R=e[2],O=e[6],I=e[10],N=R*l+O*u+I*f,j=R*m+O*y+I*b,F=R*w+O*k+I*A;T=Math.asin(i(N)),E=Math.atan2(F,j)}this.angle.jump(t,E,T),this.recalcMatrix(t);var D=e[2],B=e[6],U=e[10],V=this.computedMatrix;c(V,e);var q=V[15],H=V[12]/q,G=V[13]/q,Y=V[14]/q,X=Math.exp(this.computedRadius[0]);this.center.jump(t,H-D*X,G-B*X,Y-U*X)},p.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},p.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},p.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},p.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},p.lookAt=function(t,e,r,a){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter,a=a||this.computedUp;var o=a[0],s=a[1],l=a[2],c=n(o,s,l);if(!(1e-6>c)){o/=c,s/=c,l/=c;var u=e[0]-r[0],f=e[1]-r[1],h=e[2]-r[2],d=n(u,f,h);if(!(1e-6>d)){u/=d,f/=d,h/=d;var p=this.computedRight,g=p[0],v=p[1],m=p[2],y=o*g+s*v+l*m;g-=y*o,v-=y*s,m-=y*l;var b=n(g,v,m);if(!(.01>b&&(g=s*h-l*f,v=l*u-o*h,m=o*f-s*u,b=n(g,v,m),1e-6>b))){g/=b,v/=b,m/=b,this.up.set(t,o,s,l),this.right.set(t,g,v,m),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(d));var x=s*m-l*v,_=l*g-o*m,w=o*v-s*g,k=n(x,_,w);x/=k,_/=k,w/=k;var A=o*u+s*f+l*h,M=g*u+v*f+m*h,T=x*u+_*f+w*h,E=Math.asin(i(A)),L=Math.atan2(T,M),S=this.angle._state,C=S[S.length-1],z=S[S.length-2];C%=2*Math.PI;var P=Math.abs(C+2*Math.PI-L),R=Math.abs(C-L),O=Math.abs(C-2*Math.PI-L);R>P&&(C+=2*Math.PI),R>O&&(C-=2*Math.PI),this.angle.jump(this.angle.lastT(),C,z),this.angle.set(t,L,E)}}}}},{"filtered-vector":20,"gl-mat4/invert":137,"gl-mat4/rotate":141,"gl-vec3/cross":23,"gl-vec3/dot":24,"gl-vec3/normalize":27}],39:[function(t,e,r){"use strict";function n(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}function i(t){t=t||{};var e=t.eye||[0,0,1],r=t.center||[0,0,0],i=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],c=t.mode||"turntable",u=a(),f=o(),h=s();return u.setDistanceLimits(l[0],l[1]),u.lookAt(0,e,r,i),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,i),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,i),new n({turntable:u,orbit:f,matrix:h},c)}e.exports=i;var a=t("turntable-camera-controller"),o=t("orbit-camera-controller"),s=t("matrix-camera-controller"),l=n.prototype,c=[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]];c.forEach(function(t){for(var e=t[0],r=[],n=0;ne)){var r=this._active,n=this._controllerList[e],i=Math.max(r.lastT(),n.lastT());r.recalcMatrix(i),n.setMatrix(i,r.computedMatrix),this._active=n,this._mode=t,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}}},l.getMode=function(){return this._mode}},{"matrix-camera-controller":28,"orbit-camera-controller":37,"turntable-camera-controller":38}],40:[function(t,e,r){function n(t,e){return a(i(t,e))}e.exports=n;var i=t("alpha-complex"),a=t("simplicial-complex-boundary")},{"alpha-complex":41,"simplicial-complex-boundary":44}],41:[function(t,e,r){"use strict";function n(t,e){return i(e).filter(function(r){for(var n=new Array(r.length),i=0;ii;++i)r+=t[i]*e[i];return r}function i(t){var e=t.length;if(0===e)return[];var r=(t[0].length,o([t.length+1,t.length+1],1)),i=o([t.length+1],1);r[e][e]=0;for(var a=0;e>a;++a){for(var l=0;a>=l;++l)r[l][a]=r[a][l]=2*n(t[a],t[l]);i[a]=n(t[a],t[a])}for(var c=s(r,i),u=0,f=c[e+1],a=0;aa;++a){for(var f=c[a],d=0,l=0;ls;++s)r[s]+=t[a][s]*n[a];return r}var o=t("dup"),s=t("robust-linear-solve");a.barycenetric=i,e.exports=a},{dup:115,"robust-linear-solve":256}],44:[function(t,e,r){"use strict";function n(t){return a(i(t))}e.exports=n;var i=t("boundary-cells"),a=t("reduce-simplicial-complex")},{"boundary-cells":45,"reduce-simplicial-complex":48}],45:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r+=t[n].length;for(var i=new Array(r),a=0,n=0;e>n;++n)for(var o=t[n],s=o.length,l=0;s>l;++l)for(var c=i[a++]=new Array(s-1),u=1;s>u;++u)c[u-1]=o[(l+u)%s];return i}e.exports=n},{}],46:[function(t,e,r){"use strict";function n(t){for(var e=1,r=1;rn;++n)if(t[r]n;++n){var s=t[n],l=o(s);if(0!==l){if(r>0){var c=t[r-1];if(0===i(s,c)&&o(c)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}var i=t("compare-cell"),a=t("compare-oriented-cell"),o=t("cell-orientation");e.exports=n},{"cell-orientation":46,"compare-cell":101,"compare-oriented-cell":47}],49:[function(t,e,r){"use strict";var n=function(){function t(t){return!Array.isArray(t)&&null!==t&&"object"==typeof t}function e(t,e,r){for(var n=(e-t)/Math.max(r-1,1),i=[],a=0;r>a;a++)i.push(t+a*n);return i}function r(){for(var t=[].slice.call(arguments),e=t.map(function(t){return t.length}),r=Math.min.apply(null,e),n=[],i=0;r>i;i++){n[i]=[];for(var a=0;aa;a++)i.push([t[a],e[a],r[a]]);return i}function i(t){function e(t){for(var n=0;n>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3])),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}function c(t,e){var r,n;if("string"!=typeof t)return t;if(r=[],"#"===t[0]?(t=t.substr(1),3===t.length&&(t+=t),n=parseInt(t,16),r[0]=n>>16&255,r[1]=n>>8&255,r[2]=255&n):f.test(t)&&(n=t.match(h),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3]),n[4]?r[3]=parseFloat(n[4]):r[3]=1),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}var u={},f=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/,h=/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/;return u.isPlainObject=t,u.linspace=e,u.zip3=n,u.sum=i,u.zip=r,u.isEqual=s,u.copy2D=a,u.copy1D=o,u.str2RgbArray=l,u.str2RgbaArray=c,u};e.exports=n()},{}],50:[function(t,e,r){"use strict";"use restrict";function n(t){var e=32;return t&=-t,t&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}var i=32;r.INT_BITS=i,r.INT_MAX=2147483647,r.INT_MIN=-1<0)-(0>t)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(e>t)},r.max=function(t,e){return t^(t^e)&-(e>t)},r.isPow2=function(t){return!(t&t-1||!t)},r.log2=function(t){var e,r;return e=(t>65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var a=new Array(256);!function(t){for(var e=0;256>e;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|a[t>>>16&255]<<8|a[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],51:[function(t,e,r){(function(e){"use strict";function n(){try{var t=new Uint8Array(1);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t){return this instanceof a?(a.TYPED_ARRAY_SUPPORT||(this.length=0,this.parent=void 0),"number"==typeof t?o(this,t):"string"==typeof t?s(this,t,arguments.length>1?arguments[1]:"utf8"):l(this,t)):arguments.length>1?new a(t,arguments[1]):new a(t)}function o(t,e){if(t=g(t,0>e?0:0|v(e)),!a.TYPED_ARRAY_SUPPORT)for(var r=0;e>r;r++)t[r]=0;return t}function s(t,e,r){"string"==typeof r&&""!==r||(r="utf8");var n=0|y(e,r);return t=g(t,n),t.write(e,r),t}function l(t,e){if(a.isBuffer(e))return c(t,e);if(K(e))return u(t,e);if(null==e)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(e.buffer instanceof ArrayBuffer)return f(t,e);if(e instanceof ArrayBuffer)return h(t,e)}return e.length?d(t,e):p(t,e)}function c(t,e){var r=0|v(e.length);return t=g(t,r),e.copy(t,0,0,r),t}function u(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function f(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function h(t,e){return e.byteLength,a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):t=f(t,new Uint8Array(e)),t}function d(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function p(t,e){var r,n=0;"Buffer"===e.type&&K(e.data)&&(r=e.data,n=0|v(r.length)),t=g(t,n);for(var i=0;n>i;i+=1)t[i]=255&r[i];return t}function g(t,e){a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):t.length=e;var r=0!==e&&e<=a.poolSize>>>1;return r&&(t.parent=$),t}function v(t){if(t>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function m(t,e){if(!(this instanceof m))return new m(t,e);var r=new a(t,e);return delete r.parent,r}function y(t,e){"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"binary":case"raw":case"raws":return r;case"utf8":case"utf-8":return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(n)return q(t).length;e=(""+e).toLowerCase(),n=!0}}function b(t,e,r){var n=!1;if(e=0|e,r=void 0===r||r===1/0?this.length:0|r,t||(t="utf8"),0>e&&(e=0),r>this.length&&(r=this.length),e>=r)return"";for(;;)switch(t){case"hex":return z(this,e,r);case"utf8":case"utf-8":return E(this,e,r);case"ascii":return S(this,e,r);case"binary":return C(this,e,r);case"base64":return T(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function x(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var a=e.length;if(a%2!==0)throw new Error("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;n>o;o++){var s=parseInt(e.substr(2*o,2),16);if(isNaN(s))throw new Error("Invalid hex string");t[r+o]=s}return o}function _(t,e,r,n){return X(q(e,t.length-r),t,r,n)}function w(t,e,r,n){return X(H(e),t,r,n)}function k(t,e,r,n){return w(t,e,r,n)}function A(t,e,r,n){return X(Y(e),t,r,n)}function M(t,e,r,n){return X(G(e,t.length-r),t,r,n)}function T(t,e,r){return 0===e&&r===t.length?W.fromByteArray(t):W.fromByteArray(t.slice(e,r))}function E(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;r>i;){var a=t[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(r>=i+s){var l,c,u,f;switch(s){case 1:128>a&&(o=a);break;case 2:l=t[i+1],128===(192&l)&&(f=(31&a)<<6|63&l,f>127&&(o=f));break;case 3:l=t[i+1],c=t[i+2],128===(192&l)&&128===(192&c)&&(f=(15&a)<<12|(63&l)<<6|63&c,f>2047&&(55296>f||f>57343)&&(o=f));break;case 4:l=t[i+1],c=t[i+2],u=t[i+3],128===(192&l)&&128===(192&c)&&128===(192&u)&&(f=(15&a)<<18|(63&l)<<12|(63&c)<<6|63&u,f>65535&&1114112>f&&(o=f))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return L(n)}function L(t){var e=t.length;if(Q>=e)return String.fromCharCode.apply(String,t);for(var r="",n=0;e>n;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Q));return r}function S(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(127&t[i]);return n}function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function z(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",a=e;r>a;a++)i+=V(t[a]);return i}function P(t,e,r){for(var n=t.slice(e,r),i="",a=0;at)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!a.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(e>i||o>e)throw new RangeError("value is out of bounds");if(r+n>t.length)throw new RangeError("index out of range")}function I(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,a=Math.min(t.length-r,2);a>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function N(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,a=Math.min(t.length-r,4);a>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function j(t,e,r,n,i,a){if(r+n>t.length)throw new RangeError("index out of range");if(0>r)throw new RangeError("index out of range")}function F(t,e,r,n,i){return i||j(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(t,e,r,n,23,4),r+4}function D(t,e,r,n,i){return i||j(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(t,e,r,n,52,8),r+8}function B(t){if(t=U(t).replace(J,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function U(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function V(t){return 16>t?"0"+t.toString(16):t.toString(16)}function q(t,e){e=e||1/0;for(var r,n=t.length,i=null,a=[],o=0;n>o;o++){if(r=t.charCodeAt(o),r>55295&&57344>r){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(56320>r){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,128>r){if((e-=1)<0)break;a.push(r)}else if(2048>r){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(65536>r){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(1114112>r))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(t){for(var e=[],r=0;r>8,i=r%256,a.push(i),a.push(n);return a}function Y(t){return W.toByteArray(B(t))}function X(t,e,r,n){for(var i=0;n>i&&!(i+r>=e.length||i>=t.length);i++)e[i+r]=t[i];return i}var W=t("base64-js"),Z=t("ieee754"),K=t("isarray");r.Buffer=a,r.SlowBuffer=m,r.INSPECT_MAX_BYTES=50,a.poolSize=8192;var $={};a.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),a._augment=function(t){return t.__proto__=a.prototype,t},a.TYPED_ARRAY_SUPPORT?(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})):(a.prototype.length=void 0,a.prototype.parent=void 0),a.isBuffer=function(t){return!(null==t||!t._isBuffer)},a.compare=function(t,e){if(!a.isBuffer(t)||!a.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,o=Math.min(r,n);o>i&&t[i]===e[i];)++i;return i!==o&&(r=t[i],n=e[i]),n>r?-1:r>n?1:0},a.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(t,e){if(!K(t))throw new TypeError("list argument must be an Array of Buffers.");if(0===t.length)return new a(0);var r;if(void 0===e)for(e=0,r=0;r0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},a.prototype.compare=function(t){if(!a.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?0:a.compare(this,t)},a.prototype.indexOf=function(t,e){function r(t,e,r){for(var n=-1,i=0;r+i2147483647?e=2147483647:-2147483648>e&&(e=-2147483648),e>>=0,0===this.length)return-1;if(e>=this.length)return-1;if(0>e&&(e=Math.max(this.length+e,0)),"string"==typeof t)return 0===t.length?-1:String.prototype.indexOf.call(this,t,e);if(a.isBuffer(t))return r(this,t,e);if("number"==typeof t)return a.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,e):r(this,[t],e);throw new TypeError("val must be string, number or Buffer")},a.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else if(isFinite(e))e=0|e,isFinite(r)?(r=0|r,void 0===n&&(n="utf8")):(n=r,r=void 0);else{var i=n;n=e,e=0|r,r=i}var a=this.length-e;if((void 0===r||r>a)&&(r=a),t.length>0&&(0>r||0>e)||e>this.length)throw new RangeError("attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return x(this,t,e,r);case"utf8":case"utf-8":return _(this,t,e,r);case"ascii":return w(this,t,e,r);case"binary":return k(this,t,e,r);case"base64":return A(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;a.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(t,e),n.__proto__=a.prototype;else{var i=e-t;n=new a(i,void 0);for(var o=0;i>o;o++)n[o]=this[o+t]}return n.length&&(n.parent=this.parent||this),n},a.prototype.readUIntLE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t],i=1,a=0;++a0&&(i*=256);)n+=this[t+--e]*i;return n},a.prototype.readUInt8=function(t,e){return e||R(t,1,this.length),this[t]},a.prototype.readUInt16LE=function(t,e){return e||R(t,2,this.length),this[t]|this[t+1]<<8},a.prototype.readUInt16BE=function(t,e){return e||R(t,2,this.length),this[t]<<8|this[t+1]},a.prototype.readUInt32LE=function(t,e){return e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},a.prototype.readUInt32BE=function(t,e){return e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},a.prototype.readIntLE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t],i=1,a=0;++a=i&&(n-=Math.pow(2,8*e)),n},a.prototype.readIntBE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*e)),a},a.prototype.readInt8=function(t,e){return e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},a.prototype.readInt16LE=function(t,e){e||R(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(t,e){e||R(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(t,e){return e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},a.prototype.readInt32BE=function(t,e){return e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},a.prototype.readFloatLE=function(t,e){return e||R(t,4,this.length),Z.read(this,t,!0,23,4)},a.prototype.readFloatBE=function(t,e){return e||R(t,4,this.length),Z.read(this,t,!1,23,4)},a.prototype.readDoubleLE=function(t,e){return e||R(t,8,this.length),Z.read(this,t,!0,52,8)},a.prototype.readDoubleBE=function(t,e){return e||R(t,8,this.length),Z.read(this,t,!1,52,8)},a.prototype.writeUIntLE=function(t,e,r,n){t=+t,e=0|e,r=0|r,n||O(this,t,e,r,Math.pow(2,8*r),0);var i=1,a=0;for(this[e]=255&t;++a=0&&(a*=256);)this[e+i]=t/a&255;return e+r},a.prototype.writeUInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,255,0),a.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},a.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},a.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},a.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):N(this,t,e,!0),e+4},a.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},a.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=0,o=1,s=0>t?1:0;for(this[e]=255&t;++a>0)-s&255;return e+r},a.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0>t?1:0;for(this[e+a]=255&t;--a>=0&&(o*=256);)this[e+a]=(t/o>>0)-s&255;return e+r},a.prototype.writeInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,127,-128),a.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=255&t,e+1},a.prototype.writeInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},a.prototype.writeInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},a.prototype.writeInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):N(this,t,e,!0),e+4},a.prototype.writeInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):N(this,t,e,!1),e+4},a.prototype.writeFloatLE=function(t,e,r){return F(this,t,e,!0,r)},a.prototype.writeFloatBE=function(t,e,r){return F(this,t,e,!1,r)},a.prototype.writeDoubleLE=function(t,e,r){return D(this,t,e,!0,r)},a.prototype.writeDoubleBE=function(t,e,r){return D(this,t,e,!1,r)},a.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(0>e)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length), +t.length-er&&n>e)for(i=o-1;i>=0;i--)t[i+e]=this[i+r];else if(1e3>o||!a.TYPED_ARRAY_SUPPORT)for(i=0;o>i;i++)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+o),e);return o},a.prototype.fill=function(t,e,r){if(t||(t=0),e||(e=0),r||(r=this.length),e>r)throw new RangeError("end < start");if(r!==e&&0!==this.length){if(0>e||e>=this.length)throw new RangeError("start out of bounds");if(0>r||r>this.length)throw new RangeError("end out of bounds");var n;if("number"==typeof t)for(n=e;r>n;n++)this[n]=t;else{var i=q(t.toString()),a=i.length;for(n=e;r>n;n++)this[n]=i[n%a]}return this}};var J=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":52,ieee754:53,isarray:54}],52:[function(t,e,r){"use strict";function n(){var t,e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=e.length;for(t=0;r>t;t++)l[t]=e[t];for(t=0;r>t;++t)c[e.charCodeAt(t)]=t;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63}function i(t){var e,r,n,i,a,o,s=t.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");a="="===t[s-2]?2:"="===t[s-1]?1:0,o=new u(3*s/4-a),n=a>0?s-4:s;var l=0;for(e=0,r=0;n>e;e+=4,r+=3)i=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],o[l++]=(16711680&i)>>16,o[l++]=(65280&i)>>8,o[l++]=255&i;return 2===a?(i=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,o[l++]=255&i):1===a&&(i=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,o[l++]=i>>8&255,o[l++]=255&i),o}function a(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function o(t,e,r){for(var n,i=[],o=e;r>o;o+=3)n=(t[o]<<16)+(t[o+1]<<8)+t[o+2],i.push(a(n));return i.join("")}function s(t){for(var e,r=t.length,n=r%3,i="",a=[],s=16383,c=0,u=r-n;u>c;c+=s)a.push(o(t,c,c+s>u?u:c+s));return 1===n?(e=t[r-1],i+=l[e>>2],i+=l[e<<4&63],i+="=="):2===n&&(e=(t[r-2]<<8)+t[r-1],i+=l[e>>10],i+=l[e>>4&63],i+=l[e<<2&63],i+="="),a.push(i),a.join("")}r.toByteArray=i,r.fromByteArray=s;var l=[],c=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array;n()},{}],53:[function(t,e,r){r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<>1,u=-7,f=r?i-1:0,h=r?-1:1,d=t[e+f];for(f+=h,a=d&(1<<-u)-1,d>>=-u,u+=s;u>0;a=256*a+t[e+f],f+=h,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=n;u>0;o=256*o+t[e+f],f+=h,u-=8);if(0===a)a=1-c;else{if(a===l)return o?NaN:(d?-1:1)*(1/0);o+=Math.pow(2,n),a-=c}return(d?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,c=8*a-i-1,u=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:a-1,p=n?1:-1,g=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=u):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),e+=o+f>=1?h/l:h*Math.pow(2,1-f),e*l>=2&&(o++,l/=2),o+f>=u?(s=0,o=u):o+f>=1?(s=(e*l-1)*Math.pow(2,i),o+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&s,d+=p,s/=256,i-=8);for(o=o<0;t[r+d]=255&o,d+=p,o/=256,c-=8);t[r+d-p]|=128*g}},{}],54:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],55:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!a(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,a,l,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(o(r))for(a=Array.prototype.slice.call(arguments,1),c=r.slice(),n=c.length,l=0;n>l;l++)c[l].apply(this,a);return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(r=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],56:[function(t,e,r){function n(){u=!1,s.length?c=s.concat(c):f=-1,c.length&&i()}function i(){if(!u){var t=setTimeout(n);u=!0;for(var e=c.length;e;){for(s=c,c=[];++f1)for(var r=1;rs)){if(n>i){var l=n;n=i,i=l,l=o,o=s,s=l}e.isConstraint(n,i)||a(t[n],t[i],t[o],t[s])<0&&r.push(n,i)}}function i(t,e){for(var r=[],i=t.length,o=e.stars,s=0;i>s;++s)for(var l=o[s],c=1;cu||e.isConstraint(s,u))){for(var f=l[c-1],h=-1,d=1;dh||a(t[s],t[u],t[f],t[h])<0&&r.push(s,u)}}for(;r.length>0;){for(var u=r.pop(),s=r.pop(),f=-1,h=-1,l=o[s],p=1;pf||0>h||a(t[s],t[u],t[f],t[h])>=0||(e.flip(s,u),n(t,e,r,f,s,h),n(t,e,r,s,h,f),n(t,e,r,h,u,f),n(t,e,r,u,f,h))}}var a=t("robust-in-sphere")[4];t("binary-search-bounds");e.exports=i},{"binary-search-bounds":62,"robust-in-sphere":63}],59:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function i(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}function a(t,e){for(var r=t.cells(),a=r.length,o=0;a>o;++o){var s=r[o],l=s[0],c=s[1],u=s[2];u>c?l>c&&(s[0]=c,s[1]=u,s[2]=l):l>u&&(s[0]=u,s[1]=l,s[2]=c)}r.sort(i);for(var f=new Array(a),o=0;oo;++o)for(var s=r[o],y=0;3>y;++y){var l=s[y],c=s[(y+1)%3],b=p[3*o+y]=m.locate(c,l,t.opposite(c,l)),x=g[3*o+y]=t.isConstraint(l,c);0>b&&(x?d.push(o):(h.push(o),f[o]=1),e&&v.push([c,l,-1]))}return m}function o(t,e,r){for(var n=0,i=0;i0||l.length>0;){for(;s.length>0;){var d=s.pop();if(c[d]!==-i){c[d]=i;for(var p=(u[d],0);3>p;++p){var g=h[3*d+p];g>=0&&0===c[g]&&(f[3*d+p]?l.push(g):(s.push(g),c[g]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var m=o(u,c,e);return r?m.concat(n.boundary):m}var l=t("binary-search-bounds");e.exports=s;var c=n.prototype;c.locate=function(){var t=[0,0,0];return function(e,r,n){var a=e,o=r,s=n;return n>r?e>r&&(a=r,o=n,s=e):e>n&&(a=n,o=e,s=r),0>a?-1:(t[0]=a,t[1]=o,t[2]=s,l.eq(this.cells,t,i))}}()},{"binary-search-bounds":62}],60:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.a=t,this.b=e,this.idx=r,this.lowerIds=n,this.upperIds=i}function i(t,e,r,n){this.a=t,this.b=e,this.type=r,this.idx=n}function a(t,e){var r=t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.type-e.type;return r?r:t.type!==p&&(r=d(t.a,t.b,e.b))?r:t.idx-e.idx}function o(t,e){return d(t.a,t.b,e)}function s(t,e,r,n,i){for(var a=h.lt(e,n,o),s=h.gt(e,n,o),l=a;s>l;++l){for(var c=e[l],u=c.lowerIds,f=u.length;f>1&&d(r[u[f-2]],r[u[f-1]],n)>0;)t.push([u[f-1],u[f-2],i]),f-=1;u.length=f,u.push(i);for(var p=c.upperIds,f=p.length;f>1&&d(r[p[f-2]],r[p[f-1]],n)<0;)t.push([p[f-2],p[f-1],i]),f-=1;p.length=f,p.push(i)}}function l(t,e){var r;return(r=t.a[0]f;++f)l.push(new i(t[f],null,p,f));for(var f=0;o>f;++f){var h=e[f],d=t[h[0]],m=t[h[1]];d[0]m[0]&&l.push(new i(m,d,v,f),new i(d,m,g,f))}l.sort(a);for(var y=l[0].a[0]-(1+Math.abs(l[0].a[0]))*Math.pow(2,-52),b=[new n([y,1],[y,0],-1,[],[],[],[])],x=[],f=0,_=l.length;_>f;++f){var w=l[f],k=w.type;k===p?s(x,b,t,w.a,w.idx):k===v?c(b,t,w):u(b,t,w)}return x}var h=t("binary-search-bounds"),d=t("robust-orientation")[3],p=0,g=1,v=2;e.exports=f},{"binary-search-bounds":62,"robust-orientation":259}],61:[function(t,e,r){"use strict";function n(t,e){this.stars=t,this.edges=e}function i(t,e,r){for(var n=1,i=t.length;i>n;n+=2)if(t[n-1]===e&&t[n]===r)return t[n-1]=t[i-2],t[n]=t[i-1],void(t.length=i-2)}function a(t,e){for(var r=new Array(t),i=0;t>i;++i)r[i]=[];return new n(r,e)}var o=t("binary-search-bounds");e.exports=a;var s=n.prototype;s.isConstraint=function(){function t(t,e){return t[0]-e[0]||t[1]-e[1]}var e=[0,0];return function(r,n){return e[0]=Math.min(r,n),e[1]=Math.max(r,n),o.eq(this.edges,e,t)>=0}}(),s.removeTriangle=function(t,e,r){var n=this.stars;i(n[t],e,r),i(n[e],r,t),i(n[r],t,e)},s.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},s.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;i>n;n+=2)if(r[n]===t)return r[n-1];return-1},s.flip=function(t,e){var r=this.opposite(t,e),n=this.opposite(e,t);this.removeTriangle(t,e,r),this.removeTriangle(e,t,n),this.addTriangle(t,n,r),this.addTriangle(e,r,n)},s.edges=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2)e.push([i[a],i[a+1]]);return e},s.cells=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2){var s=i[a],l=i[a+1];r>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],63:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-2,"]"].join("")}return e}function a(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",a(t.slice(0,e)),",",a(t.slice(e)),")"].join("")}function o(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return o(e,t)}function s(t){return t&!0?"-":""}function l(t){if(2===t.length)return[["diff(",o(t[0][0],t[1][1]),",",o(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;rn;++n)r.push(["prod(m",t,"[",n,"],m",t,"[",n,"])"].join(""));return a(r)}function u(t){for(var e=[],r=[],o=i(t),s=0;t>s;++s)o[0][s]="1",o[t-1][s]="w"+s;for(var s=0;t>s;++s)0===(1&s)?e.push.apply(e,l(n(o,s))):r.push.apply(r,l(n(o,s)));for(var u=a(e),f=a(r),h="exactInSphere"+t,d=[],s=0;t>s;++s)d.push("m"+s);for(var p=["function ",h,"(",d.join(),"){"],s=0;t>s;++s){p.push("var w",s,"=",c(s,t),";");for(var g=0;t>g;++g)g!==s&&p.push("var w",s,"m",g,"=scale(w",s,",m",g,"[0]);")}p.push("var p=",u,",n=",f,",d=diff(p,n);return d[d.length-1];}return ",h);var x=new Function("sum","diff","prod","scale",p.join(""));return x(m,y,v,b)}function f(){return 0}function h(){return 0}function d(){return 0}function p(t){var e=_[t.length];return e||(e=_[t.length]=u(t.length)),e.apply(void 0,t)}function g(){for(;_.length<=x;)_.push(u(_.length));for(var t=[],r=["slow"],n=0;x>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function testInSphere(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;x>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var v=t("two-product"),m=t("robust-sum"),y=t("robust-subtract"),b=t("robust-scale"),x=6,_=[f,h,d];g()},{"robust-scale":260,"robust-subtract":261,"robust-sum":262,"two-product":276}],64:[function(t,e,r){"use strict";function n(t){var e=x(t),r=b(y(e),t);return 0>r?[e,w(e,1/0)]:r>0?[w(e,-(1/0)),e]:[e,e]}function i(t,e){for(var r=new Array(e.length),n=0;n=t.length)return o[e-t.length];var r=t[e];return[y(r[0]),y(r[1])]}for(var o=[],s=0;s=0;--s){var g=n[s],c=g[0],v=e[c],m=v[0],x=v[1],w=t[m],A=t[x];if((w[0]-A[0]||w[1]-A[1])<0){var M=m;m=x,x=M}v[0]=m;var T,E=v[1]=g[1];for(i&&(T=v[2]);s>0&&n[s-1][0]===c;){var g=n[--s],L=g[1];i?e.push([E,L,T]):e.push([E,L]),E=L}i?e.push([E,x,T]):e.push([E,x])}return o}function c(t,e,r){for(var i=t.length+e.length,a=new g(i),o=r,s=0;ss;++s){var p=a.find(s);p===s?(d[s]=f,t[f++]=t[s]):(h=!1,d[s]=-1)}if(t.length=f,h)return null;for(var s=0;i>s;++s)d[s]<0&&(d[s]=d[a.find(s)]);return d}function u(t,e){return t[0]-e[0]||t[1]-e[1]}function f(t,e){var r=t[0]-e[0]||t[1]-e[1];return r?r:t[2]e[2]?1:0}function h(t,e,r){if(0!==t.length){if(e)for(var n=0;n0||d.length>0}function p(t,e,r){var n,i=!1;if(r){n=e;for(var a=new Array(e.length),o=0;o0?r=r.shln(f):0>f&&(u=u.shln(-f)),l(r,u)}var i=t("./is-rat"),a=t("./lib/is-bn"),o=t("./lib/num-to-bn"),s=t("./lib/str-to-bn"),l=t("./lib/rationalize"),c=t("./div");e.exports=n},{"./div":68,"./is-rat":70,"./lib/is-bn":74,"./lib/num-to-bn":75,"./lib/rationalize":76,"./lib/str-to-bn":77}],70:[function(t,e,r){"use strict";function n(t){return Array.isArray(t)&&2===t.length&&i(t[0])&&i(t[1])}var i=t("./lib/is-bn");e.exports=n},{"./lib/is-bn":74}],71:[function(t,e,r){"use strict";function n(t){return t.cmp(new i(0))}var i=t("bn.js");e.exports=n},{"bn.js":79}],72:[function(t,e,r){"use strict";function n(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var n=0,i=0;e>i;i++){var a=r[i];n+=a*Math.pow(67108864,i)}return t.sign?-n:n}e.exports=n},{}],73:[function(t,e,r){"use strict";function n(t){var e=a(i.lo(t));if(32>e)return e;var r=a(i.hi(t));return r>20?52:r+32}var i=t("double-bits"),a=t("bit-twiddle").countTrailingZeros;e.exports=n},{"bit-twiddle":50,"double-bits":90}],74:[function(t,e,r){"use strict";function n(t){return t&&"object"==typeof t&&Boolean(t.words)}t("bn.js");e.exports=n},{"bn.js":79}],75:[function(t,e,r){"use strict";function n(t){var e=a.exponent(t);return 52>e?new i(t):new i(t*Math.pow(2,52-e)).shln(e-52)}var i=t("bn.js"),a=t("double-bits");e.exports=n},{"bn.js":79,"double-bits":90}],76:[function(t,e,r){"use strict";function n(t,e){var r=a(t),n=a(e);if(0===r)return[i(0),i(1)];if(0===n)return[i(0),i(0)];0>n&&(t=t.neg(),e=e.neg());var o=t.gcd(e);return o.cmpn(1)?[t.div(o),e.div(o)]:[t,e]}var i=t("./num-to-bn"),a=t("./bn-sign");e.exports=n},{"./bn-sign":71,"./num-to-bn":75}],77:[function(t,e,r){"use strict";function n(t){return new i(t)}var i=t("bn.js");e.exports=n},{"bn.js":79}],78:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[0]),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":76}],79:[function(t,e,r){!function(t,e){"use strict";function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){return null!==t&&"object"==typeof t&&Array.isArray(t.words)?t:(this.sign=!1,this.words=null,this.length=0,this.red=null,"le"!==e&&"be"!==e||(r=e,e=10),void(null!==t&&this._init(t||0,e||10,r||"be")))}function a(t,e,r){for(var n=0,i=Math.min(t.length,r),a=e;i>a;a++){var o=t.charCodeAt(a)-48;n<<=4,n|=o>=49&&54>=o?o-49+10:o>=17&&22>=o?o-17+10:15&o}return n}function o(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;a>o;o++){var s=t.charCodeAt(o)-48;i*=n,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}function s(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).ishln(this.n).isub(this.p),this.tmp=this._tmp()}function l(){s.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function c(){s.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function u(){s.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function f(){s.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function h(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else this.m=t,this.prime=null}function d(t){h.call(this,t),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).ishln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv.sign=!0,this.minv=this.minv.mod(this.r)}"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26,i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&36>=e),t=t.toString().replace(/\s+/g,"");var i=0;"-"===t[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.sign=!0),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){0>t&&(this.sign=!0,t=-t),67108864>t?(this.words=[67108863&t],this.length=1):4503599627370496>t?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(9007199254740992>t),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3){var s=t[i]|t[i-1]<<8|t[i-2]<<16;this.words[o]|=s<>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}else if("le"===n)for(var i=0,o=0;i>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r=e;r-=6){var o=a(t,r,r+6);this.words[i]|=o<>>26-n&4194303,n+=24,n>=26&&(n-=26,i++)}if(r+6!==e){var o=a(t,e,r+6);this.words[i]|=o<>>26-n&4194303}this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;67108863>=i;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,s=a%n,l=Math.min(a,a-s)+r,c=0,u=r;l>u;u+=n)c=o(t,u,u+n,e),this.imuln(i),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c);if(0!==s){for(var f=1,c=o(t,u,t.length,e),u=0;s>u;u++)f*=e;this.imuln(f),this.words[0]+c<67108864?this.words[0]+=c:this._iaddn(c)}},i.prototype.copy=function(t){t.words=new Array(this.length);for(var e=0;e1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.sign=!1),this},i.prototype.inspect=function(){return(this.red?""};var p=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],v=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(t,e){if(t=t||10,16===t||"hex"===t){for(var n="",i=0,e=0|e||1,a=0,o=0;o>>24-i&16777215,n=0!==a||o!==this.length-1?p[6-l.length]+l+n:l+n,i+=2,i>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!==0;)n="0"+n;return this.sign&&(n="-"+n),n}if(t===(0|t)&&t>=2&&36>=t){var c=g[t],u=v[t],n="",f=this.clone();for(f.sign=!1;0!==f.cmpn(0);){var h=f.modn(u).toString(t);f=f.idivn(u),n=0!==f.cmpn(0)?p[c-h.length]+h+n:h+n}return 0===this.cmpn(0)&&(n="0"+n),this.sign&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toArray=function(t){this.strip();var e=new Array(this.byteLength());e[0]=0;var r=this.clone();if("le"!==t)for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[e.length-n-1]=i}else for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[n]=i}return e},Math.clz32?i.prototype._countBits=function(t){return 32-Math.clz32(t)}:i.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0===(8191&e)&&(r+=13,e>>>=13),0===(127&e)&&(r+=7,e>>>=7),0===(15&e)&&(r+=4,e>>>=4),0===(3&e)&&(r+=2,e>>>=2),0===(1&e)&&r++,r},i.prototype.bitLength=function(){var t=0,e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(0===this.cmpn(0))return 0;for(var t=0,e=0;et.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.iand=function(t){this.sign=this.sign&&t.sign;var e;e=this.length>t.length?t:this;for(var r=0;rt.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.ixor=function(t){this.sign=this.sign||t.sign;var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;nt.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);for(var n=t/26|0,i=t%26;this.length<=n;)this.words[this.length++]=0;return e?this.words[n]=this.words[n]|1<t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a>>26}for(;0!==i&&a>>26}if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;at.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(t.sign){t.sign=!1;var e=this.iadd(t);return t.sign=!0,e._normSign()}if(this.sign)return this.sign=!1,this.iadd(t),this.sign=!0,this._normSign();var r=this.cmp(t);if(0===r)return this.sign=!1,this.length=1,this.words[0]=0,this;var n,i;r>0?(n=this,i=t):(n=t,i=this);for(var a=0,o=0;o>26,this.words[o]=67108863&e}for(;0!==a&&o>26,this.words[o]=67108863&e}if(0===a&&o>>26,a=67108863&r,o=Math.min(n,t.length-1),s=Math.max(0,n-this.length+1);o>=s;s++){var l=n-s,c=0|this.words[l],u=0|t.words[s],f=c*u,h=67108863&f;i=i+(f/67108864|0)|0,h=h+a|0,a=67108863&h,i=i+(h>>>26)|0}e.words[n]=a,r=i}return 0!==r?e.words[n]=r:e.length--,e.strip()},i.prototype._bigMulTo=function(t,e){e.sign=t.sign!==this.sign,e.length=this.length+t.length;for(var r=0,n=0,i=0;i=l;l++){var c=i-l,u=0|this.words[c],f=0|t.words[l],h=u*f,d=67108863&h;a=a+(h/67108864|0)|0,d=d+o|0,o=67108863&d,a=a+(d>>>26)|0,n+=a>>>26,a&=67108863}e.words[i]=o,r=a,a=n}return 0!==r?e.words[i]=r:e.length--,e.strip()},i.prototype.mulTo=function(t,e){var r;return r=this.length+t.length<63?this._smallMulTo(t,e):this._bigMulTo(t,e)},i.prototype.mul=function(t){var e=new i(null);return e.words=new Array(this.length+t.length),this.mulTo(t,e)},i.prototype.imul=function(t){if(0===this.cmpn(0)||0===t.cmpn(0))return this.words[0]=0,this.length=1,this;var e=this.length,r=t.length;this.sign=t.sign!==this.sign,this.length=this.length+t.length,this.words[this.length-1]=0;for(var n=this.length-2;n>=0;n--){for(var i=0,a=0,o=Math.min(n,r-1),s=Math.max(0,n-e+1);o>=s;s++){var l=n-s,c=this.words[l],u=t.words[s],f=c*u,h=67108863&f;i+=f/67108864|0,h+=a,a=67108863&h,i+=h>>>26}this.words[n]=a,this.words[n+1]+=i,i=0}for(var i=0,l=1;l>>26}return this.strip()},i.prototype.imuln=function(t){r("number"==typeof t);for(var e=0,n=0;n>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.mul(this)},i.prototype.ishln=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=67108863>>>26-e<<26-e;if(0!==e){for(var a=0,o=0;o>>26-e}a&&(this.words[o]=a,this.length++)}if(0!==n){for(var o=this.length-1;o>=0;o--)this.words[o+n]=this.words[o];for(var o=0;n>o;o++)this.words[o]=0;this.length+=n}return this.strip()},i.prototype.ishrn=function(t,e,n){r("number"==typeof t&&t>=0);var i;i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<c;c++)l.words[c]=this.words[c];l.length=o}if(0===o);else if(this.length>o){this.length-=o;for(var c=0;c=0&&(0!==u||c>=i);c--){var f=this.words[c];this.words[c]=u<<26-a|f>>>a,u=f&s}return l&&0!==u&&(l.words[l.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip(),this},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<=0);var e=t%26,n=(t-e)/26;if(r(!this.sign,"imaskn works only with positive numbers"),0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<t?this.isubn(-t):this.sign?1===this.length&&this.words[0]=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),0>t)return this.iaddn(-t);if(this.sign)return this.sign=!1,this.iaddn(t),this.sign=!0,this;this.words[0]-=t;for(var e=0;e>26)-(c/67108864|0),this.words[i+n]=67108863&l}for(;i>26,this.words[i+n]=67108863&l}if(0===s)return this.strip();r(-1===s),s=0;for(var i=0;i>26,this.words[i]=67108863&l}return this.sign=!0,this.strip()},i.prototype._wordDiv=function(t,e){var r=this.length-t.length,n=this.clone(),a=t,o=a.words[a.length-1],s=this._countBits(o);r=26-s,0!==r&&(a=a.shln(r),n.ishln(r),o=a.words[a.length-1]);var l,c=n.length-a.length;if("mod"!==e){l=new i(null),l.length=c+1,l.words=new Array(l.length);for(var u=0;u=0;h--){var d=67108864*n.words[a.length+h]+n.words[a.length+h-1];for(d=Math.min(d/o|0,67108863),n._ishlnsubmul(a,d,h);n.sign;)d--,n.sign=!1,n._ishlnsubmul(a,1,h),0!==n.cmpn(0)&&(n.sign=!n.sign);l&&(l.words[h]=d)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.ishrn(r),{div:l?l:null,mod:n}},i.prototype.divmod=function(t,e){if(r(0!==t.cmpn(0)),this.sign&&!t.sign){var n,a,o=this.neg().divmod(t,e);return"mod"!==e&&(n=o.div.neg()),"div"!==e&&(a=0===o.mod.cmpn(0)?o.mod:t.sub(o.mod)),{div:n,mod:a}}if(!this.sign&&t.sign){var n,o=this.divmod(t.neg(),e);return"mod"!==e&&(n=o.div.neg()),{div:n,mod:o.mod}}return this.sign&&t.sign?this.neg().divmod(t.neg(),e):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e)},i.prototype.div=function(t){return this.divmod(t,"div").div},i.prototype.mod=function(t){return this.divmod(t,"mod").mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(0===e.mod.cmpn(0))return e.div;var r=e.div.sign?e.mod.isub(t):e.mod,n=t.shrn(1),i=t.andln(1),a=r.cmp(n);return 0>a||1===i&&0===a?e.div:e.div.sign?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(67108863>=t);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+this.words[i])%t;return n},i.prototype.idivn=function(t){r(67108863>=t);for(var e=0,n=this.length-1;n>=0;n--){var i=this.words[n]+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),c=0;e.isEven()&&n.isEven();)e.ishrn(1),n.ishrn(1),++c;for(var u=n.clone(),f=e.clone();0!==e.cmpn(0);){for(;e.isEven();)e.ishrn(1),a.isEven()&&o.isEven()?(a.ishrn(1),o.ishrn(1)):(a.iadd(u).ishrn(1),o.isub(f).ishrn(1));for(;n.isEven();)n.ishrn(1),s.isEven()&&l.isEven()?(s.ishrn(1),l.ishrn(1)):(s.iadd(u).ishrn(1),l.isub(f).ishrn(1));e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.ishln(c)}},i.prototype._invmp=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(;e.isEven();)e.ishrn(1),a.isEven()?a.ishrn(1):a.iadd(s).ishrn(1);for(;n.isEven();)n.ishrn(1),o.isEven()?o.ishrn(1):o.iadd(s).ishrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(o)):(n.isub(e),o.isub(a))}return 0===e.cmpn(1)?a:o},i.prototype.gcd=function(t){if(0===this.cmpn(0))return t.clone();if(0===t.cmpn(0))return this.clone();var e=this.clone(),r=t.clone();e.sign=!1,r.sign=!1;for(var n=0;e.isEven()&&r.isEven();n++)e.ishrn(1),r.ishrn(1);for(;;){for(;e.isEven();)e.ishrn(1);for(;r.isEven();)r.ishrn(1);var i=e.cmp(r);if(0>i){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.ishln(n)},i.prototype.invm=function(t){return this.egcd(t).a.mod(t)},i.prototype.isEven=function(){return 0===(1&this.words[0])},i.prototype.isOdd=function(){return 1===(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<a;a++)this.words[a]=0;return this.words[n]|=i,this.length=n+1,this}for(var o=i,a=n;0!==o&&a>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},i.prototype.cmpn=function(t){var e=0>t;if(e&&(t=-t),this.sign&&!e)return-1;if(!this.sign&&e)return 1;t&=67108863,this.strip();var r;if(this.length>1)r=1;else{var n=this.words[0];r=n===t?0:t>n?-1:1}return this.sign&&(r=-r),r},i.prototype.cmp=function(t){if(this.sign&&!t.sign)return-1;if(!this.sign&&t.sign)return 1;var e=this.ucmp(t);return this.sign?-e:e},i.prototype.ucmp=function(t){if(this.length>t.length)return 1;if(this.length=0;r--){var n=this.words[r],i=t.words[r];if(n!==i){i>n?e=-1:n>i&&(e=1);break}}return e},i.red=function(t){return new h(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(!this.sign,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};s.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},s.prototype.ireduce=function(t){var e,r=t;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength();while(e>this.n);var n=e0?r.isub(this.p):r.strip(),r},s.prototype.split=function(t,e){t.ishrn(this.n,0,e)},s.prototype.imulK=function(t){return t.imul(this.k)},n(l,s),l.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;n>i;i++)e.words[i]=t.words[i];if(e.length=n,t.length<=9)return t.words[0]=0,void(t.length=1);var a=t.words[9];e.words[e.length++]=a&r;for(var i=10;i>>22,a=o}t.words[i-10]=a>>>22,t.length-=9},l.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e,r=0,n=0;n>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function y(t){if(m[t])return m[t];var y;if("k256"===t)y=new l;else if("p224"===t)y=new c;else if("p192"===t)y=new u;else{if("p25519"!==t)throw new Error("Unknown prime "+t);y=new f}return m[t]=y,y},h.prototype._verify1=function(t){r(!t.sign,"red works only with positives"),r(t.red,"red works only with red numbers")},h.prototype._verify2=function(t,e){r(!t.sign&&!e.sign,"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},h.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.mod(this.m)._forceRed(this)},h.prototype.neg=function(t){var e=t.clone();return e.sign=!e.sign,e.iadd(this.m)._forceRed(this)},h.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},h.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},h.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},h.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},h.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.shln(e))},h.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},h.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},h.prototype.isqr=function(t){return this.imul(t,t)},h.prototype.sqr=function(t){return this.mul(t,t)},h.prototype.sqrt=function(t){if(0===t.cmpn(0))return t.clone();var e=this.m.andln(3);if(r(e%2===1),3===e){var n=this.m.add(new i(1)).ishrn(2),a=this.pow(t,n);return a}for(var o=this.m.subn(1),s=0;0!==o.cmpn(0)&&0===o.andln(1);)s++,o.ishrn(1);r(0!==o.cmpn(0));var l=new i(1).toRed(this),c=l.redNeg(),u=this.m.subn(1).ishrn(1),f=this.m.bitLength();for(f=new i(2*f*f).toRed(this);0!==this.pow(f,u).cmp(c);)f.redIAdd(c);for(var h=this.pow(f,o),a=this.pow(t,o.addn(1).ishrn(1)),d=this.pow(t,o),p=s;0!==d.cmp(l);){for(var g=d,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(p>v);var m=this.pow(h,new i(1).ishln(p-v-1));a=a.redMul(m),h=m.redSqr(),d=d.redMul(h),p=v}return a},h.prototype.invm=function(t){var e=t._invmp(this.m);return e.sign?(e.sign=!1,this.imod(e).redNeg()):this.imod(e)},h.prototype.pow=function(t,e){var r=[];if(0===e.cmpn(0))return new i(1);for(var n=e.clone();0!==n.cmpn(0);)r.push(n.andln(1)),n.ishrn(1);for(var a=t,o=0;o=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},d.prototype.mul=function(t,e){if(0===t.cmpn(0)||0===e.cmpn(0))return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).ishrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},d.prototype.invm=function(t){var e=this.imod(t._invmp(this.m).mul(this.r2));return e._forceRed(this)}}("undefined"==typeof e||e,this)},{}],80:[function(t,e,r){"use strict";function n(t){return i(t[0])*i(t[1])}var i=t("./lib/bn-sign");e.exports=n},{"./lib/bn-sign":71}],81:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":76}],82:[function(t,e,r){"use strict";function n(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.divmod(r),o=n.div,s=i(o),l=n.mod;if(0===l.cmpn(0))return s;if(s){var c=a(s)+4,u=i(l.shln(c).divRound(r));return 0>s&&(u=-u),s+u*Math.pow(2,-c)}var f=r.bitLength()-l.bitLength()+53,u=i(l.shln(f).divRound(r));return 1023>f?u*Math.pow(2,-f):(u*=Math.pow(2,-1023),u*Math.pow(2,1023-f))}var i=t("./lib/bn-to-num"),a=t("./lib/ctz");e.exports=n},{"./lib/bn-to-num":72,"./lib/ctz":73}],83:[function(t,e,r){"use strict";function n(t,e){for(var r=0;t>r;++r)if(!(e[r]<=e[r+t]))return!0;return!1}function i(t,e,r,i){for(var a=0,o=0,s=0,l=t.length;l>s;++s){var c=t[s];if(!n(e,c)){for(var u=0;2*e>u;++u)r[a++]=c[u];i[o++]=s}}return o}function a(t,e,r,n){var a=t.length,o=e.length;if(!(0>=a||0>=o)){var s=t[0].length>>>1;if(!(0>=s)){var l,c=f.mallocDouble(2*s*a),u=f.mallocInt32(a);if(a=i(t,s,c,u),a>0){if(1===s&&n)h.init(a),l=h.sweepComplete(s,r,0,a,c,u,0,a,c,u);else{var p=f.mallocDouble(2*s*o),g=f.mallocInt32(o);o=i(e,s,p,g),o>0&&(h.init(a+o),l=1===s?h.sweepBipartite(s,r,0,a,c,u,0,o,p,g):d(s,r,n,a,c,u,o,p,g),f.free(p),f.free(g))}f.free(c),f.free(u)}return l}}}function o(t,e){u.push([t,e])}function s(t){return u=[],a(t,t,o,!0),u}function l(t,e){return u=[],a(t,e,o,!1),u}function c(t,e,r){switch(arguments.length){case 1:return s(t);case 2:return"function"==typeof e?a(t,t,e,!0):l(t,e);case 3:return a(t,e,r,!1);default:throw new Error("box-intersect: Invalid arguments")}}e.exports=c;var u,f=t("typedarray-pool"),h=t("./lib/sweep"),d=t("./lib/intersect")},{"./lib/intersect":85,"./lib/sweep":89,"typedarray-pool":278}],84:[function(t,e,r){"use strict";function n(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",w.join(),"){","var ",c,"=2*",a,";"],l="for(var i="+u+","+p+"="+c+"*"+u+";i<"+f+";++i,"+p+"+="+c+"){var x0="+h+"["+o+"+"+p+"],x1="+h+"["+o+"+"+p+"+"+a+"],xi="+d+"[i];",k="for(var j="+g+","+b+"="+c+"*"+g+";j<"+v+";++j,"+b+"+="+c+"){var y0="+m+"["+o+"+"+b+"],"+(r?"y1="+m+"["+o+"+"+b+"+"+a+"],":"")+"yi="+y+"[j];";return t?i.push(l,_,":",k):i.push(k,_,":",l),r?i.push("if(y1"+v+"-"+g+"){"),t?(e(!0,!1),o.push("}else{"),e(!1,!1)):(o.push("if("+l+"){"),e(!0,!0),o.push("}else{"),e(!0,!1),o.push("}}else{if("+l+"){"),e(!1,!0),o.push("}else{"),e(!1,!1),o.push("}")),o.push("}}return "+r);var s=i.join("")+o.join(""),c=new Function(s);return c()}var a="d",o="ax",s="vv",l="fp",c="es",u="rs",f="re",h="rb",d="ri",p="rp",g="bs",v="be",m="bb",y="bi",b="bp",x="rv",_="Q",w=[a,o,s,u,f,h,d,g,v,m,y];r.partial=i(!1),r.full=i(!0)},{}],85:[function(t,e,r){"use strict";function n(t,e){var r=8*c.log2(e+1)*(t+1)|0,n=c.nextPow2(M*r);L.lengthS&&(l.free(S),S=l.mallocDouble(i))}function i(t,e,r,n,i,a,o,s,l){var c=M*t;L[c]=e,L[c+1]=r,L[c+2]=n,L[c+3]=i,L[c+4]=a,L[c+5]=o;var u=T*t;S[u]=s,S[u+1]=l}function a(t,e,r,n,i,a,o,s,l,c,u){var f=2*t,h=l*f,d=c[h+e];t:for(var p=i,g=i*f;a>p;++p,g+=f){var v=o[g+e],m=o[g+e+t];if(!(v>d||d>m||n&&d===v)){for(var y=s[p],b=e+1;t>b;++b){var v=o[g+b],m=o[g+b+t],x=c[h+b],_=c[h+b+t];if(x>m||v>_)continue t}var w;if(w=n?r(u,y):r(y,u),void 0!==w)return w}}}function o(t,e,r,n,i,a,o,s,l,c){var u=2*t,f=s*u,h=l[f+e];t:for(var d=n,p=n*u;i>d;++d,p+=u){var g=o[d];if(g!==c){var v=a[p+e],m=a[p+e+t];if(!(v>h||h>m)){for(var y=e+1;t>y;++y){var v=a[p+y],m=a[p+y+t],b=l[f+y],x=l[f+y+t];if(b>m||v>x)continue t}var _=r(g,c);if(void 0!==_)return _}}}}function s(t,e,r,s,l,c,u,g,E){n(t,s+u);var C,z=0,P=2*t;for(i(z++,0,0,s,0,u,r?16:0,-(1/0),1/0),r||i(z++,0,0,u,0,s,1,-(1/0),1/0);z>0;){z-=1;var R=z*M,O=L[R],I=L[R+1],N=L[R+2],j=L[R+3],F=L[R+4],D=L[R+5],B=z*T,U=S[B],V=S[B+1],q=1&D,H=!!(16&D),G=l,Y=c,X=g,W=E;if(q&&(G=g,Y=E,X=l,W=c),!(2&D&&(N=_(t,O,I,N,G,Y,V),I>=N)||4&D&&(I=w(t,O,I,N,G,Y,U),I>=N))){var Z=N-I,K=F-j;if(H){if(y>t*Z*(Z+K)){if(C=d.scanComplete(t,O,e,I,N,G,Y,j,F,X,W),void 0!==C)return C;continue}}else{if(t*Math.min(Z,K)t*Z*K){if(C=d.scanBipartite(t,O,e,q,I,N,G,Y,j,F,X,W),void 0!==C)return C;continue}}var $=b(t,O,I,N,G,Y,U,V);if($>I)if(v>t*($-I)){if(C=h(t,O+1,e,I,$,G,Y,j,F,X,W),void 0!==C)return C}else if(O===t-2){if(C=q?d.sweepBipartite(t,e,j,F,X,W,I,$,G,Y):d.sweepBipartite(t,e,I,$,G,Y,j,F,X,W),void 0!==C)return C}else i(z++,O+1,I,$,j,F,q,-(1/0),1/0),i(z++,O+1,j,F,I,$,1^q,-(1/0),1/0);if(N>$){var Q=p(t,O,j,F,X,W),J=X[P*Q+O],tt=x(t,O,Q,F,X,W,J);if(F>tt&&i(z++,O,$,N,tt,F,(4|q)+(H?16:0),J,V),Q>j&&i(z++,O,$,N,j,Q,(2|q)+(H?16:0),U,J),Q+1===tt){if(C=H?o(t,O,e,$,N,G,Y,Q,X,W[Q]):a(t,O,e,q,$,N,G,Y,Q,X,W[Q]),void 0!==C)return C}else if(tt>Q){var et;if(H){if(et=k(t,O,$,N,G,Y,J),et>$){var rt=x(t,O,$,et,G,Y,J);if(O===t-2){if(rt>$&&(C=d.sweepComplete(t,e,$,rt,G,Y,Q,tt,X,W),void 0!==C))return C;if(et>rt&&(C=d.sweepBipartite(t,e,rt,et,G,Y,Q,tt,X,W),void 0!==C))return C}else rt>$&&i(z++,O+1,$,rt,Q,tt,16,-(1/0),1/0),et>rt&&(i(z++,O+1,rt,et,Q,tt,0,-(1/0),1/0),i(z++,O+1,Q,tt,rt,et,1,-(1/0),1/0))}}else et=q?A(t,O,$,N,G,Y,J):k(t,O,$,N,G,Y,J),et>$&&(O===t-2?C=q?d.sweepBipartite(t,e,Q,tt,X,W,$,et,G,Y):d.sweepBipartite(t,e,$,et,G,Y,Q,tt,X,W):(i(z++,O+1,$,et,Q,tt,q,-(1/0),1/0),i(z++,O+1,Q,tt,$,et,1^q,-(1/0),1/0)))}}}}}e.exports=s;var l=t("typedarray-pool"),c=t("bit-twiddle"),u=t("./brute"),f=u.partial,h=u.full,d=t("./sweep"),p=t("./median"),g=t("./partition"),v=128,m=1<<22,y=1<<22,b=g("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]),x=g("lo===p0",["p0"]),_=g("lol;++l,s+=o)for(var c=i[s],u=l,f=o*(l-1);u>r&&i[f+e]>c;--u,f-=o){for(var h=f,d=f+o,p=0;o>p;++p,++h,++d){var g=i[h];i[h]=i[d],i[d]=g}var v=a[u];a[u]=a[u-1],a[u-1]=v}}function i(t,e,r,i,a,l){if(r+1>=i)return r;for(var c=r,u=i,f=i+r>>>1,h=2*t,d=f,p=a[h*f+e];u>c;){if(s>u-c){n(t,e,c,u,a,l),p=a[h*f+e];break}var g=u-c,v=Math.random()*g+c|0,m=a[h*v+e],y=Math.random()*g+c|0,b=a[h*y+e],x=Math.random()*g+c|0,_=a[h*x+e];b>=m?_>=b?(d=y,p=b):m>=_?(d=v,p=m):(d=x,p=_):b>=_?(d=y,p=b):_>=m?(d=v,p=m):(d=x,p=_);for(var w=h*(u-1),k=h*d,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[u-1];l[u-1]=l[d],l[d]=T,d=o(t,e,c,u-1,a,l,p);for(var w=h*(u-1),k=h*d,A=0;h>A;++A,++w,++k){var M=a[w];a[w]=a[k],a[k]=M}var T=l[u-1];if(l[u-1]=l[d],l[d]=T,d>f){for(u=d-1;u>c&&a[h*(u-1)+e]===p;)u-=1;u+=1}else{if(!(f>d))break;for(c=d+1;u>c&&a[h*c+e]===p;)c+=1}}return o(t,e,r,f,a,l,a[h*f+e])}e.exports=i;var a=t("./partition"),o=a("lo=0&&n.push("lo=e[k+n]"),t.indexOf("hi")>=0&&n.push("hi=e[k+o]"),r.push(i.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)}e.exports=n;var i="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],88:[function(t,e,r){"use strict";function n(t,e){4*h>=e?i(0,e-1,t):f(0,e-1,t)}function i(t,e,r){for(var n=2*(t+1),i=t+1;e>=i;++i){for(var a=r[n++],o=r[n++],s=i,l=n-2;s-- >t;){var c=r[l-2],u=r[l-1];if(a>c)break;if(c===a&&o>u)break;r[l]=c,r[l+1]=u,l-=2}r[l]=a,r[l+1]=o}}function a(t,e,r){t*=2,e*=2;var n=r[t],i=r[t+1];r[t]=r[e],r[t+1]=r[e+1],r[e]=n,r[e+1]=i}function o(t,e,r){t*=2,e*=2,r[t]=r[e],r[t+1]=r[e+1]}function s(t,e,r,n){t*=2,e*=2,r*=2;var i=n[t],a=n[t+1];n[t]=n[e],n[t+1]=n[e+1],n[e]=n[r],n[e+1]=n[r+1],n[r]=i,n[r+1]=a}function l(t,e,r,n,i){t*=2,e*=2,i[t]=i[e],i[e]=r,i[t+1]=i[e+1],i[e+1]=n}function c(t,e,r){t*=2,e*=2;var n=r[t],i=r[e];return i>n?!1:n===i?r[t+1]>r[e+1]:!0}function u(t,e,r,n){t*=2;var i=n[t];return e>i?!0:i===e?n[t+1]>1,v=g-n,m=g+n,y=d,b=v,x=g,_=m,w=p,k=t+1,A=e-1,M=0;c(y,b,r)&&(M=y,y=b,b=M),c(_,w,r)&&(M=_,_=w,w=M),c(y,x,r)&&(M=y,y=x,x=M),c(b,x,r)&&(M=b,b=x,x=M),c(y,_,r)&&(M=y,y=_,_=M),c(x,_,r)&&(M=x,x=_,_=M),c(b,w,r)&&(M=b,b=w,w=M),c(b,x,r)&&(M=b,b=x,x=M),c(_,w,r)&&(M=_,_=w,w=M);for(var T=r[2*b],E=r[2*b+1],L=r[2*_],S=r[2*_+1],C=2*y,z=2*x,P=2*w,R=2*d,O=2*g,I=2*p,N=0;2>N;++N){var j=r[C+N],F=r[z+N],D=r[P+N];r[R+N]=j,r[O+N]=F,r[I+N]=D}o(v,t,r),o(m,e,r);for(var B=k;A>=B;++B)if(u(B,T,E,r))B!==k&&a(B,k,r),++k;else if(!u(B,L,S,r))for(;;){if(u(A,L,S,r)){u(A,T,E,r)?(s(B,k,A,r),++k,--A):(a(B,A,r),--A);break}if(--A=k-2-t?i(t,k-2,r):f(t,k-2,r),h>=e-(A+2)?i(A+2,e,r):f(A+2,e,r),h>=A-k?i(k,A,r):f(k,A,r)}e.exports=n;var h=32},{}],89:[function(t,e,r){"use strict";function n(t){var e=f.nextPow2(t);g.lengthk;++k){var A=s[k],M=b*k;_[p++]=o[M+x],_[p++]=-(A+1),_[p++]=o[M+w],_[p++]=A}for(var k=l;c>k;++k){var A=f[k]+d,T=b*k;_[p++]=u[T+x],_[p++]=-A,_[p++]=u[T+w],_[p++]=A}var E=p>>>1;h(_,E);for(var L=0,S=0,k=0;E>k;++k){var C=0|_[2*k+1];if(C>=d)C=C-d|0,i(m,y,S--,C);else if(C>=0)i(g,v,L--,C);else if(-d>=C){C=-C-d|0;for(var z=0;L>z;++z){var P=e(g[z],C);if(void 0!==P)return P}a(m,y,S++,C)}else{C=-C-1|0;for(var z=0;S>z;++z){var P=e(C,m[z]);if(void 0!==P)return P}a(g,v,L++,C)}}}function s(t,e,r,n,o,s,l,c,u,f){for(var d=0,p=2*t,w=t-1,k=p-1,A=r;n>A;++A){var M=s[A]+1<<1,T=p*A;_[d++]=o[T+w],_[d++]=-M,_[d++]=o[T+k],_[d++]=M}for(var A=l;c>A;++A){var M=f[A]+1<<1,E=p*A;_[d++]=u[E+w],_[d++]=1|-M,_[d++]=u[E+k],_[d++]=1|M}var L=d>>>1;h(_,L);for(var S=0,C=0,z=0,A=0;L>A;++A){var P=0|_[2*A+1],R=1&P;if(L-1>A&&P>>1===_[2*A+3]>>1&&(R=2,A+=1),0>P){for(var O=-(P>>1)-1,I=0;z>I;++I){var N=e(b[I],O);if(void 0!==N)return N}if(0!==R)for(var I=0;S>I;++I){var N=e(g[I],O);if(void 0!==N)return N}if(1!==R)for(var I=0;C>I;++I){var N=e(m[I],O);if(void 0!==N)return N}0===R?a(g,v,S++,O):1===R?a(m,y,C++,O):2===R&&a(b,x,z++,O)}else{var O=(P>>1)-1;0===R?i(g,v,S--,O):1===R?i(m,y,C--,O):2===R&&i(b,x,z--,O)}}}function l(t,e,r,n,o,s,l,c,u,f,p,m){var y=0,b=2*t,x=e,w=e+t,k=1,A=1;n?A=d:k=d;for(var M=o;s>M;++M){var T=M+k,E=b*M;_[y++]=l[E+x],_[y++]=-T,_[y++]=l[E+w],_[y++]=T}for(var M=u;f>M;++M){var T=M+A,L=b*M;_[y++]=p[L+x],_[y++]=-T}var S=y>>>1;h(_,S);for(var C=0,M=0;S>M;++M){var z=0|_[2*M+1];if(0>z){var T=-z,P=!1;if(T>=d?(P=!n,T-=d):(P=!!n,T-=1),P)a(g,v,C++,T);else{var R=m[T],O=b*T,I=p[O+e+1],N=p[O+e+1+t];t:for(var j=0;C>j;++j){var F=g[j],D=b*F;if(!(NB;++B)if(p[O+B+t]y;++y){var b=y+d,x=p*y;_[f++]=a[x+v],_[f++]=-b,_[f++]=a[x+m],_[f++]=b}for(var y=s;l>y;++y){var b=y+1,w=p*y;_[f++]=c[w+v],_[f++]=-b}var k=f>>>1;h(_,k);for(var A=0,y=0;k>y;++y){var M=0|_[2*y+1];if(0>M){var b=-M;if(b>=d)g[A++]=b-d;else{b-=1;var T=u[b],E=p*b,L=c[E+e+1],S=c[E+e+1+t];t:for(var C=0;A>C;++C){var z=g[C],P=o[z];if(P===T)break;var R=p*z;if(!(SO;++O)if(c[E+O+t]=0;--C)if(g[C]===b){for(var O=C+1;A>O;++O)g[O-1]=g[O];break}--A}}}e.exports={init:n,sweepBipartite:o,sweepComplete:s,scanBipartite:l,scanComplete:c};var u=t("typedarray-pool"),f=t("bit-twiddle"),h=t("./sort"),d=1<<28,p=1024,g=u.mallocInt32(p),v=u.mallocInt32(p),m=u.mallocInt32(p),y=u.mallocInt32(p),b=u.mallocInt32(p),x=u.mallocInt32(p),_=u.mallocDouble(8*p)},{"./sort":88,"bit-twiddle":50,"typedarray-pool":278}],90:[function(t,e,r){(function(t){function r(t,e){return d[0]=t,d[1]=e,h[0]}function n(t){return h[0]=t,d[0]}function i(t){return h[0]=t,d[1]}function a(t,e){return d[1]=t,d[0]=e,h[0]}function o(t){return h[0]=t,d[1]}function s(t){return h[0]=t,d[0]}function l(t,e){return p.writeUInt32LE(t,0,!0),p.writeUInt32LE(e,4,!0),p.readDoubleLE(0,!0)}function c(t){return p.writeDoubleLE(t,0,!0),p.readUInt32LE(0,!0)}function u(t){return p.writeDoubleLE(t,0,!0),p.readUInt32LE(4,!0)}var f=!1;if("undefined"!=typeof Float64Array){var h=new Float64Array(1),d=new Uint32Array(h.buffer);h[0]=1,f=!0,1072693248===d[1]?(e.exports=function(t){return h[0]=t,[d[0],d[1]]},e.exports.pack=r,e.exports.lo=n,e.exports.hi=i):1072693248===d[0]?(e.exports=function(t){return h[0]=t, +[d[1],d[0]]},e.exports.pack=a,e.exports.lo=o,e.exports.hi=s):f=!1}if(!f){var p=new t(8);e.exports=function(t){return p.writeDoubleLE(t,0,!0),[p.readUInt32LE(0,!0),p.readUInt32LE(4,!0)]},e.exports.pack=l,e.exports.lo=c,e.exports.hi=u}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){var r=e.exports.hi(t);return(r<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){var r=e.exports.hi(t);return!(2146435072&r)}}).call(this,t("buffer").Buffer)},{buffer:51}],91:[function(t,e,r){"use strict";function n(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return 0>e?-a:a;var r=i.hi(t),n=i.lo(t);return e>t==t>0?n===o?(r+=1,n=0):n+=1:0===n?(n=o,r-=1):n-=1,i.pack(n,r)}var i=t("double-bits"),a=Math.pow(2,-1074),o=-1>>>0;e.exports=n},{"double-bits":90}],92:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/add");e.exports=n},{"big-rat/add":66}],93:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t.length),r=0;rs;++s)o[s]=a(t[s],r);return o}var i=t("big-rat"),a=t("big-rat/mul");e.exports=n},{"big-rat":69,"big-rat/mul":78}],95:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/sub");e.exports=n},{"big-rat/sub":81}],96:[function(t,e,r){"use strict";function n(t,e,r,n){for(var i=0;2>i;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),c=r[i],u=n[i],f=Math.min(c,u),h=Math.max(c,u);if(s>h||f>l)return!1}return!0}function i(t,e,r,i){var o=a(t,r,i),s=a(e,r,i);if(o>0&&s>0||0>o&&0>s)return!1;var l=a(r,t,e),c=a(i,t,e);return l>0&&c>0||0>l&&0>c?!1:0===o&&0===s&&0===l&&0===c?n(t,e,r,i):!0}e.exports=i;var a=t("robust-orientation")[3]},{"robust-orientation":259}],97:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n;var i=n.prototype;Object.defineProperty(i,"length",{get:function(){return this.roots.length}}),i.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},i.find=function(t){for(var e=t,r=this.roots;r[t]!==t;)t=r[t];for(;r[e]!==t;){var n=r[e];r[e]=t,e=n}return t},i.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],98:[function(t,e,r){(function(t){var r=function(){"use strict";function e(r,n,i,a){function s(r,i){if(null===r)return null;if(0==i)return r;var l,h;if("object"!=typeof r)return r;if(e.__isArray(r))l=[];else if(e.__isRegExp(r))l=new RegExp(r.source,o(r)),r.lastIndex&&(l.lastIndex=r.lastIndex);else if(e.__isDate(r))l=new Date(r.getTime());else{if(f&&t.isBuffer(r))return l=new t(r.length),r.copy(l),l;"undefined"==typeof a?(h=Object.getPrototypeOf(r),l=Object.create(h)):(l=Object.create(a),h=a)}if(n){var d=c.indexOf(r);if(-1!=d)return u[d];c.push(r),u.push(l)}for(var p in r){var g;h&&(g=Object.getOwnPropertyDescriptor(h,p)),g&&null==g.set||(l[p]=s(r[p],i-1))}return l}var l;"object"==typeof n&&(i=n.depth,a=n.prototype,l=n.filter,n=n.circular);var c=[],u=[],f="undefined"!=typeof t;return"undefined"==typeof n&&(n=!0),"undefined"==typeof i&&(i=1/0),s(r,i)}function r(t){return Object.prototype.toString.call(t)}function n(t){return"object"==typeof t&&"[object Date]"===r(t)}function i(t){return"object"==typeof t&&"[object Array]"===r(t)}function a(t){return"object"==typeof t&&"[object RegExp]"===r(t)}function o(t){var e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),e}return e.clonePrototype=function(t){if(null===t)return null;var e=function(){};return e.prototype=t,new e},e.__objToStr=r,e.__isDate=n,e.__isArray=i,e.__isRegExp=a,e.__getRegExpFlags=o,e}();"object"==typeof e&&e.exports&&(e.exports=r)}).call(this,t("buffer").Buffer)},{buffer:51}],99:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:0,rgb:[255,255,255,1]}]}},{}],100:[function(t,e,r){"use strict";function n(t){for(var e,r="#",n=0;3>n;++n)e=t[n],e=e.toString(16),r+=("00"+e).substr(e.length);return r}function i(t){return"rgba("+t.join(",")+")"}var a=t("arraytools"),o=t("clone"),s=t("./colorScales");e.exports=function(t){var e,r,l,c,u,f,h,d,p,g,v,m,y,b=[],x=[],_=[],w=[];if(a.isPlainObject(t)||(t={}),p=t.nshades||72,d=t.format||"hex",h=t.colormap,h||(h="jet"),"string"==typeof h){if(h=h.toLowerCase(),!s[h])throw Error(h+" not a supported colorscale");f=o(s[h])}else{if(!Array.isArray(h))throw Error("unsupported colormap option",h);f=o(h)}if(f.length>p)throw new Error(h+" map requires nshades to be at least size "+f.length);for(v=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:o(t.alpha):"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1],e=f.map(function(t){return Math.round(t.index*p)}),v[0]<0&&(v[0]=0),v[1]<0&&(v[0]=0),v[0]>1&&(v[0]=1),v[1]>1&&(v[0]=1),y=0;y=0&&r[3]<=1||(r[3]=v[0]+(v[1]-v[0])*m);for(y=0;yx;++x)if(i=y[x]-b[x])return i;return 0}}e.exports=i;var a=Math.min},{}],102:[function(t,e,r){"use strict";function n(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;return 0===r?[]:1===r?i(t):2===r?a(t):o(t,r)}var i=t("./lib/ch1d"),a=t("./lib/ch2d"),o=t("./lib/chnd");e.exports=n},{"./lib/ch1d":103,"./lib/ch2d":104,"./lib/chnd":105}],103:[function(t,e,r){"use strict";function n(t){for(var e=0,r=0,n=1;nt[r][0]&&(r=n);return r>e?[[e],[r]]:e>r?[[r],[e]]:[[e]]}e.exports=n},{}],104:[function(t,e,r){"use strict";function n(t){var e=i(t),r=e.length;if(2>=r)return[];for(var n=new Array(r),a=e[r-1],o=0;r>o;++o){var s=e[o];n[o]=[a,s],a=s}return n}e.exports=n;var i=t("monotone-convex-hull-2d")},{"monotone-convex-hull-2d":107}],105:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),i=0;ii;++i)e.indexOf(i)<0&&(n[a++]=t[i]);return n}function i(t,e){for(var r=t.length,n=e.length,i=0;r>i;++i)for(var a=t[i],o=0;os)a[o]=e[s];else{s-=n;for(var l=0;n>l;++l)s>=e[l]&&(s+=1);a[o]=s}}return t}function a(t,e){try{return o(t,!0)}catch(r){var a=s(t);if(a.length<=e)return[];var l=n(t,a),c=o(l,!0);return i(c,a)}}e.exports=a;var o=t("incremental-convex-hull"),s=t("affine-hull")},{"affine-hull":106,"incremental-convex-hull":235}],106:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(e+1),n=0;n=i;++i){for(var o=new Array(e),s=0;e>s;++s)o[s]=Math.pow(i+1-n,s);r[i]=o}var l=a.apply(void 0,r);if(l)return!0}return!1}function i(t){var e=t.length;if(0===e)return[];if(1===e)return[0];for(var r=t[0].length,i=[t[0]],a=[0],o=1;e>o;++o)if(i.push(t[o]),n(i,r)){if(a.push(o),a.length===r+1)return a}else i.pop();return a}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":259}],107:[function(t,e,r){"use strict";function n(t){var e=t.length;if(3>e){for(var r=new Array(e),n=0;e>n;++n)r[n]=n;return 2===e&&t[0][0]===t[1][0]&&t[0][1]===t[1][1]?[0]:r}for(var a=new Array(e),n=0;e>n;++n)a[n]=n;a.sort(function(e,r){var n=t[e][0]-t[r][0];return n?n:t[e][1]-t[r][1]});for(var o=[a[0],a[1]],s=[a[0],a[1]],n=2;e>n;++n){for(var l=a[n],c=t[l],u=o.length;u>1&&i(t[o[u-2]],t[o[u-1]],c)<=0;)u-=1,o.pop();for(o.push(l),u=s.length;u>1&&i(t[s[u-2]],t[s[u-1]],c)>=0;)u-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),f=0,n=0,h=o.length;h>n;++n)r[f++]=o[n];for(var d=s.length-2;d>0;--d)r[f++]=s[d];return r}e.exports=n;var i=t("robust-orientation")[3]},{"robust-orientation":259}],108:[function(t,e,r){e.exports={AFG:"afghan",ALA:"\\b\\wland",ALB:"albania",DZA:"algeria",ASM:"^(?=.*americ).*samoa",AND:"andorra",AGO:"angola",AIA:"anguill?a",ATA:"antarctica",ATG:"antigua",ARG:"argentin",ARM:"armenia",ABW:"^(?!.*bonaire).*\\baruba",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baustri.*\\bemp",AZE:"azerbaijan",BHS:"bahamas",BHR:"bahrain",BGD:"bangladesh|^(?=.*east).*paki?stan",BRB:"barbados",BLR:"belarus|byelo",BEL:"^(?!.*luxem).*belgium",BLZ:"belize|^(?=.*british).*honduras",BEN:"benin|dahome",BMU:"bermuda",BTN:"bhutan",BOL:"bolivia",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",BIH:"herzegovina|bosnia",BWA:"botswana|bechuana",BVT:"bouvet",BRA:"brazil",IOT:"british.?indian.?ocean",BRN:"brunei",BGR:"bulgaria",BFA:"burkina|\\bfaso|upper.?volta",BDI:"burundi",KHM:"cambodia|kampuchea|khmer",CMR:"cameroon",CAN:"canada",CPV:"verde",CYM:"cayman",CAF:"\\bcentral.african.republic",TCD:"\\bchad",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china",CXR:"christmas",CCK:"\\bcocos|keeling",COL:"colombia",COM:"comoro",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|belgian.?congo|congo.?free.?state|kinshasa|zaire|l.opoldville|drc|droc|rdc",COG:"^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l.opoldville)(?!.*free).*\\bcongo",COK:"\\bcook",CRI:"costa.?rica",CIV:"ivoire|ivory",HRV:"croatia",CUB:"\\bcuba",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",CYP:"cyprus",CZE:"^(?=.*rep).*czech|czechia|bohemia",CSK:"czechoslovakia",DNK:"denmark",DJI:"djibouti",DMA:"dominica(?!n)",DOM:"dominican.rep",ECU:"ecuador",EGY:"egypt",SLV:"el.?salvador",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",ERI:"eritrea",EST:"estonia",ETH:"ethiopia|abyssinia",FLK:"falkland|malvinas",FRO:"faroe|faeroe",FJI:"fiji",FIN:"finland",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",GUF:"^(?=.*french).*guiana",PYF:"french.?polynesia|tahiti",ATF:"french.?southern",GAB:"gabon",GMB:"gambia",GEO:"^(?!.*south).*georgia",DDR:"german.?democratic.?republic|democratic.?republic.*germany|east.germany",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GHA:"ghana|gold.?coast",GIB:"gibraltar",GRC:"greece|hellenic|hellas",GRL:"greenland",GRD:"grenada",GLP:"guadeloupe",GUM:"\\bguam",GTM:"guatemala",GGY:"guernsey",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",GNB:"bissau|^(?=.*portu).*guinea",GUY:"guyana|british.?guiana",HTI:"haiti",HMD:"heard.*mcdonald",VAT:"holy.?see|vatican|papal.?st",HND:"^(?!.*brit).*honduras",HKG:"hong.?kong",HUN:"^(?!.*austr).*hungary",ISL:"iceland",IND:"india(?!.*ocea)",IDN:"indonesia",IRN:"\\biran|persia",IRQ:"\\biraq|mesopotamia",IRL:"ireland",IMN:"^(?=.*isle).*\\bman",ISR:"israel",ITA:"italy",JAM:"jamaica",JPN:"japan",JEY:"jersey",JOR:"jordan",KAZ:"kazak",KEN:"kenya|british.?east.?africa|east.?africa.?prot",KIR:"kiribati",PRK:"^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|dprk",KOR:"^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea",KWT:"kuwait",KGZ:"kyrgyz|kirghiz",LAO:"\\blaos?\\b",LVA:"latvia",LBN:"lebanon",LSO:"lesotho|basuto",LBR:"liberia",LBY:"libya",LIE:"liechtenstein",LTU:"lithuania",LUX:"^(?!.*belg).*luxem",MAC:"maca(o|u)",MKD:"macedonia|fyrom",MDG:"madagascar|malagasy",MWI:"malawi|nyasa",MYS:"malaysia",MDV:"maldive",MLI:"\\bmali\\b",MLT:"\\bmalta",MHL:"marshall",MTQ:"martinique",MRT:"mauritania",MUS:"mauritius",MYT:"\\bmayotte",MEX:"\\bmexic",FSM:"micronesia",MDA:"moldov|b(a|e)ssarabia",MCO:"monaco",MNG:"mongolia",MNE:"^(?!.*serbia).*montenegro",MSR:"montserrat",MAR:"morocco|\\bmaroc",MOZ:"mozambique",MMR:"myanmar|burma",NAM:"namibia",NRU:"nauru",NPL:"nepal",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",ANT:"^(?=.*\\bant).*(nether|dutch)",NCL:"new.?caledonia",NZL:"new.?zealand",NIC:"nicaragua",NER:"\\bniger(?!ia)",NGA:"nigeria",NIU:"niue",NFK:"norfolk",MNP:"mariana",NOR:"norway",OMN:"\\boman|trucial",PAK:"^(?!.*east).*paki?stan",PLW:"palau",PSE:"palestin|\\bgaza|west.?bank",PAN:"panama",PNG:"papua|new.?guinea",PRY:"paraguay",PER:"peru",PHL:"philippines",PCN:"pitcairn",POL:"poland",PRT:"portugal",PRI:"puerto.?rico",QAT:"qatar",REU:"r(e|\xe9)union",ROU:"r(o|u|ou)mania",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",RWA:"rwanda",BLM:"barth(e|\xe9)lemy",SHN:"helena",KNA:"kitts|\\bnevis",LCA:"\\blucia",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",SPM:"miquelon",VCT:"vincent",WSM:"^(?!.*amer).*samoa",SMR:"san.?marino",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SAU:"\\bsa\\w*.?arabia",SEN:"senegal",SRB:"^(?!.*monte).*serbia",SYC:"seychell",SLE:"sierra",SGP:"singapore",SXM:"^(?!.*martin)(?!.*saba).*maarten",SVK:"^(?!.*cze).*slovak",SVN:"slovenia",SLB:"solomon",SOM:"somali",ZAF:"\\bs\\w*.?africa",SGS:"south.?georgia|sandwich",SSD:"\\bs\\w*.?sudan",ESP:"spain",LKA:"sri.?lanka|ceylon",SDN:"^(?!.*\\bs(?!u)).*sudan",SUR:"surinam|dutch.?guiana",SJM:"svalbard",SWZ:"swaziland",SWE:"sweden",CHE:"switz|swiss",SYR:"syria",TWN:"taiwan|taipei|formosa",TJK:"tajik",TZA:"tanzania",THA:"thailand|\\bsiam",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TGO:"togo",TKL:"tokelau",TON:"tonga",TTO:"trinidad|tobago",TUN:"tunisia",TUR:"turkey",TKM:"turkmen",TCA:"turks",TUV:"tuvalu",UGA:"uganda",UKR:"ukrain",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",USA:"united.?states|\\bu\\.?s\\.?a\\.?\\b|\\bu\\.?s\\.?\\b(?!.*islands)",UMI:"minor.?outlying.?is",URY:"uruguay",UZB:"uzbek",VUT:"vanuatu|new.?hebrides",VEN:"venezuela",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",WLF:"futuna|wallis",ESH:"western.sahara",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",YUG:"yugoslavia",ZMB:"zambia|northern.?rhodesia",EAZ:"zanzibar",ZWE:"zimbabwe|^(?!.*northern).*rhodesia"}},{}],109:[function(t,e,r){"use strict";function n(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function i(t){var e=new n;e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var i=0;i0)throw new Error("cwise: pre() block may not reference array args");if(i0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if("index"===o){if(e.indexArgs.push(i),i0)throw new Error("cwise: pre() block may not reference array index");if(i0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(e.shapeArgs.push(i),ir.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,a(e)}var a=t("./lib/thunk.js");e.exports=i},{"./lib/thunk.js":111}],110:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],c=[],u=0,f=0;for(n=0;a>n;++n)c.push(["i",n,"=0"].join(""));for(i=0;o>i;++i)for(n=0;a>n;++n)f=u,u=t[n],0===n?c.push(["d",i,"s",n,"=t",i,"p",u].join("")):c.push(["d",i,"s",n,"=(t",i,"p",u,"-s",f,"*t",i,"p",f,")"].join(""));for(l.push("var "+c.join(",")),n=a-1;n>=0;--n)u=t[n],l.push(["for(i",n,"=0;i",n,"n;++n){for(f=u,u=t[n],i=0;o>i;++i)l.push(["p",i,"+=d",i,"s",n].join(""));s&&(n>0&&l.push(["index[",f,"]-=s",f].join("")),l.push(["++index[",u,"]"].join(""))),l.push("}")}return l.join("\n")}function i(t,e,r,i){for(var a=e.length,o=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,c=[],u=0;o>u;++u)c.push(["var offset",u,"=p",u].join(""));for(var u=t;a>u;++u)c.push(["for(var j"+u+"=SS[",e[u],"]|0;j",u,">0;){"].join("")),c.push(["if(j",u,"<",s,"){"].join("")),c.push(["s",e[u],"=j",u].join("")),c.push(["j",u,"=0"].join("")),c.push(["}else{s",e[u],"=",s].join("")),c.push(["j",u,"-=",s,"}"].join("")),l&&c.push(["index[",e[u],"]=j",u].join(""));for(var u=0;o>u;++u){for(var f=["offset"+u],h=t;a>h;++h)f.push(["j",h,"*t",u,"p",e[h]].join(""));c.push(["p",u,"=(",f.join("+"),")"].join(""))}c.push(n(e,r,i));for(var u=t;a>u;++u)c.push("}");return c.join("\n")}function a(t){for(var e=0,r=t[0].length;r>e;){for(var n=1;n0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}function l(t,e){for(var r=e[1].length-Math.abs(t.arrayBlockIndices[0])|0,l=new Array(t.arrayArgs.length),u=new Array(t.arrayArgs.length),f=0;fy;++y)_.push(["s",y,"=SS[",y,"]"].join(""));for(var f=0;fy;++y)_.push(["t",f,"p",y,"=t",f,"[",p[f]+y,"]"].join(""));for(var y=0;y0&&_.push("shape=SS.slice(0)"),t.indexArgs.length>0){for(var w=new Array(r),f=0;r>f;++f)w[f]="0";_.push(["index=[",w.join(","),"]"].join(""))}for(var f=0;f3&&x.push(o(t.pre,t,u));var T=o(t.body,t,u),E=a(v);r>E?x.push(i(E,v[0],t,T)):x.push(n(v[0],t,T)),t.post.body.length>3&&x.push(o(t.post,t,u)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+x.join("\n")+"\n----------");var L=[t.funcName||"unnamed","_cwise_loop_",l[0].join("s"),"m",E,s(u)].join(""),S=new Function(["function ",L,"(",b.join(","),"){",x.join("\n"),"} return ",L].join(""));return S()}var c=t("uniq");e.exports=l},{uniq:279}],111:[function(t,e,r){"use strict";function n(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],c=[],u=0;u0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+f+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[u]))),c.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+f+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[u])+"]"))}t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),e.push("if (!("+c.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}"));for(var u=0;ut?-1:t>e?1:t>=e?0:NaN}function a(t){return null===t?NaN:+t}function o(t){return!isNaN(t)}function s(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}function l(t){return t.length}function c(t){for(var e=1;t*e%1;)e*=10;return e}function u(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function f(){this._=Object.create(null)}function h(t){return(t+="")===ko||t[0]===Ao?Ao+t:t}function d(t){return(t+="")[0]===Ao?t.slice(1):t}function p(t){return h(t)in this._}function g(t){return(t=h(t))in this._&&delete this._[t]}function v(){var t=[];for(var e in this._)t.push(d(e));return t}function m(){var t=0;for(var e in this._)++t;return t}function y(){for(var t in this._)return!1;return!0}function b(){this._=Object.create(null)}function x(t){return t}function _(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function w(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=Mo.length;n>r;++r){var i=Mo[r]+e;if(i in t)return i}}function k(){}function A(){}function M(t){function e(){for(var e,n=r,i=-1,a=n.length;++ir;r++)for(var i,a=t[r],o=0,s=a.length;s>o;o++)(i=a[o])&&e(i,o,r);return t}function Y(t){return Eo(t,Oo),t}function X(t){var e,r;return function(n,i,a){var o,s=t[a].update,l=s.length;for(a!=r&&(r=a,e=0),i>=e&&(e=i+1);!(o=s[e])&&++e0&&(t=t.slice(0,s));var c=Io.get(t);return c&&(t=c,l=K),s?e?i:n:e?k:a}function Z(t,e){return function(r){var n=co.event;co.event=r,e[0]=this.__data__;try{t.apply(this,e)}finally{co.event=n}}}function K(t,e){var r=Z(t,e);return function(t){var e=this,n=t.relatedTarget;n&&(n===e||8&n.compareDocumentPosition(e))||r.call(e,t)}}function $(t){var r=".dragsuppress-"+ ++jo,i="click"+r,a=co.select(n(t)).on("touchmove"+r,T).on("dragstart"+r,T).on("selectstart"+r,T);if(null==No&&(No="onselectstart"in t?!1:w(t.style,"userSelect")),No){var o=e(t).style,s=o[No];o[No]="none"}return function(t){if(a.on(r,null),No&&(o[No]=s),t){var e=function(){a.on(i,null)};a.on(i,function(){T(),e()},!0),setTimeout(e,0)}}}function Q(t,e){e.changedTouches&&(e=e.changedTouches[0]);var r=t.ownerSVGElement||t;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>Fo){var a=n(t);if(a.scrollX||a.scrollY){r=co.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();Fo=!(o.f||o.e),r.remove()}}return Fo?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}function J(){return co.event.changedTouches[0].identifier}function tt(t){return t>0?1:0>t?-1:0}function et(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function rt(t){return t>1?0:-1>t?Uo:Math.acos(t)}function nt(t){return t>1?Ho:-1>t?-Ho:Math.asin(t)}function it(t){return((t=Math.exp(t))-1/t)/2}function at(t){return((t=Math.exp(t))+1/t)/2}function ot(t){return((t=Math.exp(2*t))-1)/(t+1)}function st(t){return(t=Math.sin(t/2))*t}function lt(){}function ct(t,e,r){return this instanceof ct?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof ct?new ct(t.h,t.s,t.l):kt(""+t,At,ct):new ct(t,e,r)}function ut(t,e,r){function n(t){return t>360?t-=360:0>t&&(t+=360),60>t?a+(o-a)*t/60:180>t?o:240>t?a+(o-a)*(240-t)/60:a}function i(t){return Math.round(255*n(t))}var a,o;return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:0>e?0:e>1?1:e,r=0>r?0:r>1?1:r,o=.5>=r?r*(1+e):r+e-r*e,a=2*r-o,new bt(i(t+120),i(t),i(t-120))}function ft(t,e,r){return this instanceof ft?(this.h=+t,this.c=+e,void(this.l=+r)):arguments.length<2?t instanceof ft?new ft(t.h,t.c,t.l):t instanceof dt?gt(t.l,t.a,t.b):gt((t=Mt((t=co.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ft(t,e,r)}function ht(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new dt(r,Math.cos(t*=Go)*e,Math.sin(t)*e)}function dt(t,e,r){return this instanceof dt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof dt?new dt(t.l,t.a,t.b):t instanceof ft?ht(t.h,t.c,t.l):Mt((t=bt(t)).r,t.g,t.b):new dt(t,e,r)}function pt(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return i=vt(i)*rs,n=vt(n)*ns,a=vt(a)*is,new bt(yt(3.2404542*i-1.5371385*n-.4985314*a),yt(-.969266*i+1.8760108*n+.041556*a),yt(.0556434*i-.2040259*n+1.0572252*a))}function gt(t,e,r){return t>0?new ft(Math.atan2(r,e)*Yo,Math.sqrt(e*e+r*r),t):new ft(NaN,NaN,t)}function vt(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function mt(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function yt(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function bt(t,e,r){return this instanceof bt?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof bt?new bt(t.r,t.g,t.b):kt(""+t,bt,ut):new bt(t,e,r)}function xt(t){return new bt(t>>16,t>>8&255,255&t)}function _t(t){return xt(t)+""}function wt(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function kt(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(Et(i[0]),Et(i[1]),Et(i[2]))}return(a=ss.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o=o>>4|o,s=240&a,s=s>>4|s,l=15&a,l=l<<4|l):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function At(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=.5>l?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(r>e?6:0):e==o?(r-t)/s+2:(t-e)/s+4,n*=60):(n=NaN,i=l>0&&1>l?0:n),new ct(n,i,l)}function Mt(t,e,r){t=Tt(t),e=Tt(e),r=Tt(r);var n=mt((.4124564*t+.3575761*e+.1804375*r)/rs),i=mt((.2126729*t+.7151522*e+.072175*r)/ns),a=mt((.0193339*t+.119192*e+.9503041*r)/is);return dt(116*i-16,500*(n-i),200*(i-a))}function Tt(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Et(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Lt(t){return"function"==typeof t?t:function(){return t}}function St(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),Ct(e,r,t,n)}}function Ct(t,e,r,n){function i(){var t,e=l.status;if(!e&&Pt(l)||e>=200&&300>e||304===e){try{t=r.call(a,l)}catch(n){return void o.error.call(a,n)}o.load.call(a,t)}else o.error.call(a,l)}var a={},o=co.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,c=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(t){var e=co.event;co.event=t;try{o.progress.call(a,l)}finally{co.event=e}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(e=null==t?null:t+"",a):e},a.responseType=function(t){return arguments.length?(c=t,a):c},a.response=function(t){return r=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(fo(arguments)))}}),a.send=function(r,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),l.open(r,t,!0),null==e||"accept"in s||(s.accept=e+",*/*"),l.setRequestHeader)for(var u in s)l.setRequestHeader(u,s[u]);return null!=e&&l.overrideMimeType&&l.overrideMimeType(e),null!=c&&(l.responseType=c),null!=i&&a.on("error",i).on("load",function(t){i(null,t)}),o.beforesend.call(a,l),l.send(null==n?null:n),a},a.abort=function(){return l.abort(),a},co.rebind(a,o,"on"),null==n?a:a.get(zt(n))}function zt(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}function Pt(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function Rt(t,e,r){var n=arguments.length;2>n&&(e=0),3>n&&(r=Date.now());var i=r+e,a={c:t,t:i,n:null};return cs?cs.n=a:ls=a,cs=a,us||(fs=clearTimeout(fs),us=1,hs(Ot)),a}function Ot(){var t=It(),e=Nt()-t;e>24?(isFinite(e)&&(clearTimeout(fs),fs=setTimeout(Ot,e)),us=0):(us=1,hs(Ot))}function It(){for(var t=Date.now(),e=ls;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Nt(){for(var t,e=ls,r=1/0;e;)e.c?(e.t8?function(t){return t/r}:function(t){return t*r},symbol:t}}function Dt(t){var e=t.decimal,r=t.thousands,n=t.grouping,i=t.currency,a=n&&r?function(t,e){for(var i=t.length,a=[],o=0,s=n[0],l=0;i>0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(i-=s,i+s)),!((l+=s+1)>e));)s=n[o=(o+1)%n.length];return a.reverse().join(r)}:x;return function(t){var r=ps.exec(t),n=r[1]||" ",o=r[2]||">",s=r[3]||"-",l=r[4]||"",c=r[5],u=+r[6],f=r[7],h=r[8],d=r[9],p=1,g="",v="",m=!1,y=!0;switch(h&&(h=+h.substring(1)),(c||"0"===n&&"="===o)&&(c=n="0",o="="),d){case"n":f=!0,d="g";break;case"%":p=100,v="%",d="f";break;case"p":p=100,v="%",d="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+d.toLowerCase());case"c":y=!1;case"d":m=!0,h=0;break;case"s":p=-1,d="r"}"$"===l&&(g=i[0],v=i[1]),"r"!=d||h||(d="g"),null!=h&&("g"==d?h=Math.max(1,Math.min(21,h)):"e"!=d&&"f"!=d||(h=Math.max(0,Math.min(20,h)))),d=gs.get(d)||Bt;var b=c&&f;return function(t){var r=v;if(m&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>p){var l=co.formatPrefix(t,h);t=l.scale(t),r=l.symbol+v}else t*=p;t=d(t,h);var x,_,w=t.lastIndexOf(".");if(0>w){var k=y?t.lastIndexOf("e"):-1;0>k?(x=t,_=""):(x=t.substring(0,k),_=t.substring(k))}else x=t.substring(0,w),_=e+t.substring(w+1);!c&&f&&(x=a(x,1/0));var A=g.length+x.length+_.length+(b?0:i.length),M=u>A?new Array(A=u-A+1).join(n):"";return b&&(x=a(M+x,M.length?u-_.length:1/0)),i+=g,t=x+_,("<"===o?i+t+M:">"===o?M+i+t:"^"===o?M.substring(0,A>>=1)+i+t+M.substring(A):i+(b?t:M+t))+r}}}function Bt(t){return t+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Vt(t,e,r){function n(e){var r=t(e),n=a(r,1);return n-e>e-r?r:n}function i(r){return e(r=t(new ms(r-1)),1),r}function a(t,r){return e(t=new ms(+t),r),t}function o(t,n,a){var o=i(t),s=[];if(a>1)for(;n>o;)r(o)%a||s.push(new Date(+o)),e(o,1);else for(;n>o;)s.push(new Date(+o)),e(o,1);return s}function s(t,e,r){try{ms=Ut;var n=new Ut;return n._=t,o(n,e,r)}finally{ms=Date}}t.floor=t,t.round=n,t.ceil=i,t.offset=a,t.range=o;var l=t.utc=qt(t);return l.floor=l,l.round=qt(n),l.ceil=qt(i),l.offset=qt(a),l.range=s,t}function qt(t){return function(e,r){try{ms=Ut;var n=new Ut;return n._=e,t(n,r)._}finally{ms=Date}}}function Ht(t){function e(t){function e(e){for(var r,i,a,o=[],s=-1,l=0;++ss;){if(n>=c)return-1;if(i=e.charCodeAt(s++),37===i){if(o=e.charAt(s++),a=S[o in bs?e.charAt(s++):o],!a||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}function n(t,e,r){w.lastIndex=0;var n=w.exec(e.slice(r));return n?(t.w=k.get(n[0].toLowerCase()),r+n[0].length):-1}function i(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.w=_.get(n[0].toLowerCase()),r+n[0].length):-1}function a(t,e,r){T.lastIndex=0;var n=T.exec(e.slice(r));return n?(t.m=E.get(n[0].toLowerCase()),r+n[0].length):-1}function o(t,e,r){A.lastIndex=0;var n=A.exec(e.slice(r));return n?(t.m=M.get(n[0].toLowerCase()),r+n[0].length):-1}function s(t,e,n){return r(t,L.c.toString(),e,n)}function l(t,e,n){return r(t,L.x.toString(),e,n)}function c(t,e,n){return r(t,L.X.toString(),e,n)}function u(t,e,r){var n=b.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)}var f=t.dateTime,h=t.date,d=t.time,p=t.periods,g=t.days,v=t.shortDays,m=t.months,y=t.shortMonths;e.utc=function(t){function r(t){try{ms=Ut;var e=new ms;return e._=t,n(e)}finally{ms=Date}}var n=e(t);return r.parse=function(t){try{ms=Ut;var e=n.parse(t);return e&&e._}finally{ms=Date}},r.toString=n.toString,r},e.multi=e.utc.multi=ue;var b=co.map(),x=Yt(g),_=Xt(g),w=Yt(v),k=Xt(v),A=Yt(m),M=Xt(m),T=Yt(y),E=Xt(y);p.forEach(function(t,e){b.set(t.toLowerCase(),e)});var L={a:function(t){return v[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:e(f),d:function(t,e){return Gt(t.getDate(),e,2)},e:function(t,e){return Gt(t.getDate(),e,2)},H:function(t,e){return Gt(t.getHours(),e,2)},I:function(t,e){return Gt(t.getHours()%12||12,e,2)},j:function(t,e){return Gt(1+vs.dayOfYear(t),e,3)},L:function(t,e){return Gt(t.getMilliseconds(),e,3)},m:function(t,e){return Gt(t.getMonth()+1,e,2)},M:function(t,e){return Gt(t.getMinutes(),e,2)},p:function(t){return p[+(t.getHours()>=12)]},S:function(t,e){return Gt(t.getSeconds(),e,2)},U:function(t,e){return Gt(vs.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Gt(vs.mondayOfYear(t),e,2)},x:e(h),X:e(d),y:function(t,e){return Gt(t.getFullYear()%100,e,2)},Y:function(t,e){return Gt(t.getFullYear()%1e4,e,4)},Z:le,"%":function(){return"%"}},S={a:n,A:i,b:a,B:o,c:s,d:re,e:re,H:ie,I:ie,j:ne,L:se,m:ee,M:ae,p:u,S:oe,U:Zt,w:Wt,W:Kt,x:l,X:c,y:Qt,Y:$t,Z:Jt,"%":ce};return e}function Gt(t,e,r){var n=0>t?"-":"",i=(n?-t:t)+"",a=i.length;return n+(r>a?new Array(r-a+1).join(e)+i:i)}function Yt(t){return new RegExp("^(?:"+t.map(co.requote).join("|")+")","i")}function Xt(t){for(var e=new f,r=-1,n=t.length;++r68?1900:2e3)}function ee(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function re(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function ne(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function ie(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function ae(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function oe(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function se(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function le(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=wo(e)/60|0,i=wo(e)%60;return r+Gt(n,"0",2)+Gt(i,"0",2)}function ce(t,e,r){_s.lastIndex=0;var n=_s.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function ue(t){for(var e=t.length,r=-1;++r=0?1:-1,s=o*r,l=Math.cos(e),c=Math.sin(e),u=a*c,f=i*l+u*Math.cos(s),h=u*o*Math.sin(s);Es.add(Math.atan2(h,f)),n=t,i=l,a=c}var e,r,n,i,a;Ls.point=function(o,s){Ls.point=t,n=(e=o)*Go,i=Math.cos(s=(r=s)*Go/2+Uo/4),a=Math.sin(s)},Ls.lineEnd=function(){t(e,r)}}function me(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function ye(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function be(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xe(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function _e(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function we(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function ke(t){return[Math.atan2(t[1],t[0]),nt(t[2])]}function Ae(t,e){return wo(t[0]-e[0])s;++s)i.point((r=t[s])[0],r[1]);return void i.lineEnd()}var l=new Oe(r,t,null,!0),c=new Oe(r,null,l,!1);l.o=c,a.push(l),o.push(c),l=new Oe(n,t,null,!1),c=new Oe(n,null,l,!0),l.o=c,a.push(l),o.push(c)}}),o.sort(e),Re(a),Re(o),a.length){for(var s=0,l=r,c=o.length;c>s;++s)o[s].e=l=!l;for(var u,f,h=a[0];;){for(var d=h,p=!0;d.v;)if((d=d.n)===h)return;u=d.z,i.lineStart();do{if(d.v=d.o.v=!0,d.e){if(p)for(var s=0,c=u.length;c>s;++s)i.point((f=u[s])[0],f[1]);else n(d.x,d.n.x,1,i);d=d.n}else{if(p){u=d.p.z;for(var s=u.length-1;s>=0;--s)i.point((f=u[s])[0],f[1])}else n(d.x,d.p.x,-1,i);d=d.p}d=d.o,u=d.z,p=!p}while(!d.v);i.lineEnd()}}}function Re(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n0){for(_||(a.polygonStart(),_=!0),a.lineStart();++o1&&2&e&&r.push(r.pop().concat(r.shift())),d.push(r.filter(Ne))}var d,p,g,v=e(a),m=i.invert(n[0],n[1]),y={point:o,lineStart:l,lineEnd:c,polygonStart:function(){y.point=u,y.lineStart=f,y.lineEnd=h,d=[],p=[]},polygonEnd:function(){y.point=o,y.lineStart=l,y.lineEnd=c,d=co.merge(d);var t=Ve(m,p);d.length?(_||(a.polygonStart(),_=!0),Pe(d,Fe,t,r,a)):t&&(_||(a.polygonStart(),_=!0),a.lineStart(),r(null,null,1,a),a.lineEnd()),_&&(a.polygonEnd(),_=!1),d=p=null},sphere:function(){a.polygonStart(),a.lineStart(),r(null,null,1,a),a.lineEnd(),a.polygonEnd()}},b=je(),x=e(b),_=!1;return y}}function Ne(t){return t.length>1}function je(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:k,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Fe(t,e){return((t=t.x)[0]<0?t[1]-Ho-Do:Ho-t[1])-((e=e.x)[0]<0?e[1]-Ho-Do:Ho-e[1])}function De(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Uo:-Uo,l=wo(a-r);wo(l-Uo)0?Ho:-Ho),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Uo&&(wo(r-i)Do?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}function Ue(t,e,r,n){var i;if(null==t)i=r*Ho,n.point(-Uo,i),n.point(0,i),n.point(Uo,i),n.point(Uo,0),n.point(Uo,-i),n.point(0,-i),n.point(-Uo,-i),n.point(-Uo,0),n.point(-Uo,i);else if(wo(t[0]-e[0])>Do){var a=t[0]s;++s){var c=e[s],u=c.length;if(u)for(var f=c[0],h=f[0],d=f[1]/2+Uo/4,p=Math.sin(d),g=Math.cos(d),v=1;;){v===u&&(v=0),t=c[v];var m=t[0],y=t[1]/2+Uo/4,b=Math.sin(y),x=Math.cos(y),_=m-h,w=_>=0?1:-1,k=w*_,A=k>Uo,M=p*b;if(Es.add(Math.atan2(M*w*Math.sin(k),g*x+M*Math.cos(k))),a+=A?_+w*Vo:_,A^h>=r^m>=r){var T=be(me(f),me(t));we(T);var E=be(i,T);we(E);var L=(A^_>=0?-1:1)*nt(E[2]);(n>L||n===L&&(T[0]||T[1]))&&(o+=A^_>=0?1:-1)}if(!v++)break;h=m,p=b,g=x,f=t}}return(-Do>a||Do>a&&0>Es)^1&o}function qe(t){function e(t,e){return Math.cos(t)*Math.cos(e)>a}function r(t){var r,a,l,c,u;return{lineStart:function(){c=l=!1,u=1},point:function(f,h){var d,p=[f,h],g=e(f,h),v=o?g?0:i(f,h):g?i(f+(0>f?Uo:-Uo),h):0;if(!r&&(c=l=g)&&t.lineStart(),g!==l&&(d=n(r,p),(Ae(r,d)||Ae(p,d))&&(p[0]+=Do,p[1]+=Do,g=e(p[0],p[1]))),g!==l)u=0,g?(t.lineStart(),d=n(p,r),t.point(d[0],d[1])):(d=n(r,p),t.point(d[0],d[1]),t.lineEnd()),r=d;else if(s&&r&&o^g){var m;v&a||!(m=n(p,r,!0))||(u=0,o?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||r&&Ae(r,p)||t.point(p[0],p[1]),r=p,l=g,a=v},lineEnd:function(){l&&t.lineEnd(),r=null},clean:function(){return u|(c&&l)<<1}}}function n(t,e,r){var n=me(t),i=me(e),o=[1,0,0],s=be(n,i),l=ye(s,s),c=s[0],u=l-c*c;if(!u)return!r&&t;var f=a*l/u,h=-a*c/u,d=be(o,s),p=_e(o,f),g=_e(s,h);xe(p,g);var v=d,m=ye(p,v),y=ye(v,v),b=m*m-y*(ye(p,p)-1);if(!(0>b)){var x=Math.sqrt(b),_=_e(v,(-m-x)/y);if(xe(_,p),_=ke(_),!r)return _;var w,k=t[0],A=e[0],M=t[1],T=e[1];k>A&&(w=k,k=A,A=w);var E=A-k,L=wo(E-Uo)E;if(!L&&M>T&&(w=M,M=T,T=w),S?L?M+T>0^_[1]<(wo(_[0]-k)Uo^(k<=_[0]&&_[0]<=A)){var C=_e(v,(-m+x)/y);return xe(C,p),[_,ke(C)]}}}function i(e,r){var n=o?t:Uo-t,i=0;return-n>e?i|=1:e>n&&(i|=2),-n>r?i|=4:r>n&&(i|=8),i}var a=Math.cos(t),o=a>0,s=wo(a)>Do,l=vr(t,6*Go);return Ie(e,r,l,o?[0,-t]:[-Uo,t-Uo])}function He(t,e,r,n){return function(i){var a,o=i.a,s=i.b,l=o.x,c=o.y,u=s.x,f=s.y,h=0,d=1,p=u-l,g=f-c;if(a=t-l,p||!(a>0)){if(a/=p,0>p){if(h>a)return;d>a&&(d=a)}else if(p>0){if(a>d)return;a>h&&(h=a)}if(a=r-l,p||!(0>a)){if(a/=p,0>p){if(a>d)return;a>h&&(h=a)}else if(p>0){if(h>a)return;d>a&&(d=a)}if(a=e-c,g||!(a>0)){if(a/=g,0>g){if(h>a)return;d>a&&(d=a)}else if(g>0){if(a>d)return;a>h&&(h=a)}if(a=n-c,g||!(0>a)){if(a/=g,0>g){if(a>d)return;a>h&&(h=a)}else if(g>0){if(h>a)return;d>a&&(d=a)}return h>0&&(i.a={x:l+h*p,y:c+h*g}),1>d&&(i.b={x:l+d*p,y:c+d*g}),i}}}}}}function Ge(t,e,r,n){function i(n,i){return wo(n[0]-t)0?0:3:wo(n[0]-r)0?2:1:wo(n[1]-e)0?1:0:i>0?3:2}function a(t,e){return o(t.x,e.x)}function o(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,r=v.length,n=t[1],i=0;r>i;++i)for(var a,o=1,s=v[i],l=s.length,c=s[0];l>o;++o)a=s[o],c[1]<=n?a[1]>n&&et(c,a,t)>0&&++e:a[1]<=n&&et(c,a,t)<0&&--e,c=a;return 0!==e}function c(a,s,l,c){var u=0,f=0;if(null==a||(u=i(a,l))!==(f=i(s,l))||o(a,s)<0^l>0){do c.point(0===u||3===u?t:r,u>1?n:e);while((u=(u+l+4)%4)!==f)}else c.point(s[0],s[1])}function u(i,a){return i>=t&&r>=i&&a>=e&&n>=a}function f(t,e){u(t,e)&&s.point(t,e)}function h(){S.point=p,v&&v.push(m=[]),A=!0,k=!1,_=w=NaN}function d(){g&&(p(y,b),x&&k&&E.rejoin(),g.push(E.buffer())),S.point=f,k&&s.lineEnd()}function p(t,e){t=Math.max(-Vs,Math.min(Vs,t)),e=Math.max(-Vs,Math.min(Vs,e));var r=u(t,e);if(v&&m.push([t,e]),A)y=t,b=e,x=r,A=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&k)s.point(t,e);else{var n={a:{x:_,y:w},b:{x:t,y:e}};L(n)?(k||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),M=!1):r&&(s.lineStart(),s.point(t,e),M=!1)}_=t,w=e,k=r}var g,v,m,y,b,x,_,w,k,A,M,T=s,E=je(),L=He(t,e,r,n),S={point:f,lineStart:h,lineEnd:d,polygonStart:function(){s=E,g=[],v=[],M=!0},polygonEnd:function(){s=T,g=co.merge(g);var e=l([t,n]),r=M&&e,i=g.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),c(null,null,1,s),s.lineEnd()),i&&Pe(g,a,e,c,s),s.polygonEnd()),g=v=m=null}};return S}}function Ye(t){var e=0,r=Uo/3,n=lr(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Uo/180,r=t[1]*Uo/180):[e/Uo*180,r/Uo*180]},i}function Xe(t,e){function r(t,e){var r=Math.sqrt(a-2*i*Math.sin(e))/i;return[r*Math.sin(t*=i),o-r*Math.cos(t)]}var n=Math.sin(t),i=(n+Math.sin(e))/2,a=1+n*(2*i-n),o=Math.sqrt(a)/i;return r.invert=function(t,e){var r=o-e;return[Math.atan2(t,r)/i,nt((a-(t*t+r*r)*i*i)/(2*i))]},r}function We(){function t(t,e){Hs+=i*t-n*e,n=t,i=e}var e,r,n,i;Zs.point=function(a,o){Zs.point=t,e=n=a,r=i=o},Zs.lineEnd=function(){t(e,r)}}function Ze(t,e){Gs>t&&(Gs=t),t>Xs&&(Xs=t),Ys>e&&(Ys=e),e>Ws&&(Ws=e)}function Ke(){function t(t,e){o.push("M",t,",",e,a)}function e(t,e){o.push("M",t,",",e),s.point=r}function r(t,e){o.push("L",t,",",e)}function n(){s.point=t}function i(){o.push("Z")}var a=$e(4.5),o=[],s={point:t,lineStart:function(){s.point=e},lineEnd:n,polygonStart:function(){s.lineEnd=i},polygonEnd:function(){s.lineEnd=n,s.point=t},pointRadius:function(t){return a=$e(t),s},result:function(){if(o.length){var t=o.join("");return o=[],t}}};return s}function $e(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Qe(t,e){zs+=t,Ps+=e,++Rs}function Je(){function t(t,n){var i=t-e,a=n-r,o=Math.sqrt(i*i+a*a);Os+=o*(e+t)/2,Is+=o*(r+n)/2,Ns+=o,Qe(e=t,r=n)}var e,r;$s.point=function(n,i){$s.point=t,Qe(e=n,r=i)}}function tr(){$s.point=Qe}function er(){function t(t,e){var r=t-n,a=e-i,o=Math.sqrt(r*r+a*a);Os+=o*(n+t)/2,Is+=o*(i+e)/2,Ns+=o,o=i*t-n*e,js+=o*(n+t),Fs+=o*(i+e),Ds+=3*o,Qe(n=t,i=e)}var e,r,n,i;$s.point=function(a,o){$s.point=t,Qe(e=n=a,r=i=o)},$s.lineEnd=function(){t(e,r)}}function rr(t){function e(e,r){t.moveTo(e+o,r),t.arc(e,r,o,0,Vo)}function r(e,r){t.moveTo(e,r),s.point=n}function n(e,r){t.lineTo(e,r)}function i(){s.point=e}function a(){t.closePath()}var o=4.5,s={point:e,lineStart:function(){s.point=r},lineEnd:i,polygonStart:function(){s.lineEnd=a},polygonEnd:function(){s.lineEnd=i,s.point=e},pointRadius:function(t){return o=t,s},result:k};return s}function nr(t){function e(t){return(s?n:r)(t)}function r(e){return or(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})}function n(e){function r(r,n){r=t(r,n),e.point(r[0],r[1])}function n(){b=NaN,A.point=a,e.lineStart()}function a(r,n){var a=me([r,n]),o=t(r,n);i(b,x,y,_,w,k,b=o[0],x=o[1],y=r,_=a[0],w=a[1],k=a[2],s,e),e.point(b,x)}function o(){A.point=r,e.lineEnd()}function l(){n(),A.point=c,A.lineEnd=u}function c(t,e){a(f=t,h=e),d=b,p=x,g=_,v=w,m=k,A.point=a}function u(){i(b,x,y,_,w,k,d,p,f,g,v,m,s,e),A.lineEnd=o,o()}var f,h,d,p,g,v,m,y,b,x,_,w,k,A={point:r,lineStart:n,lineEnd:o,polygonStart:function(){e.polygonStart(),A.lineStart=l},polygonEnd:function(){e.polygonEnd(),A.lineStart=n}};return A}function i(e,r,n,s,l,c,u,f,h,d,p,g,v,m){var y=u-e,b=f-r,x=y*y+b*b;if(x>4*a&&v--){var _=s+d,w=l+p,k=c+g,A=Math.sqrt(_*_+w*w+k*k),M=Math.asin(k/=A),T=wo(wo(k)-1)a||wo((y*C+b*z)/x-.5)>.3||o>s*d+l*p+c*g)&&(i(e,r,n,s,l,c,L,S,T,_/=A,w/=A,k,v,m),m.point(L,S),i(L,S,T,_,w,k,u,f,h,d,p,g,v,m))}}var a=.5,o=Math.cos(30*Go),s=16;return e.precision=function(t){return arguments.length?(s=(a=t*t)>0&&16,e):Math.sqrt(a)},e}function ir(t){var e=nr(function(e,r){return t([e*Yo,r*Yo])});return function(t){return cr(e(t))}}function ar(t){this.stream=t}function or(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){return t=s(t[0]*Go,t[1]*Go),[t[0]*h+l,c-t[1]*h]}function r(t){return t=s.invert((t[0]-l)/h,(c-t[1])/h),t&&[t[0]*Yo,t[1]*Yo]}function n(){s=Ce(o=hr(m,y,b),a);var t=a(g,v);return l=d-t[0]*h,c=p+t[1]*h,i()}function i(){return u&&(u.valid=!1,u=null),e}var a,o,s,l,c,u,f=nr(function(t,e){return t=a(t,e),[t[0]*h+l,c-t[1]*h]}),h=150,d=480,p=250,g=0,v=0,m=0,y=0,b=0,_=Us,w=x,k=null,A=null;return e.stream=function(t){return u&&(u.valid=!1),u=cr(_(o,f(w(t)))),u.valid=!0,u},e.clipAngle=function(t){return arguments.length?(_=null==t?(k=t,Us):qe((k=+t)*Go),i()):k},e.clipExtent=function(t){return arguments.length?(A=t,w=t?Ge(t[0][0],t[0][1],t[1][0],t[1][1]):x,i()):A},e.scale=function(t){return arguments.length?(h=+t,n()):h},e.translate=function(t){return arguments.length?(d=+t[0],p=+t[1],n()):[d,p]},e.center=function(t){return arguments.length?(g=t[0]%360*Go,v=t[1]%360*Go,n()):[g*Yo,v*Yo]},e.rotate=function(t){return arguments.length?(m=t[0]%360*Go,y=t[1]%360*Go,b=t.length>2?t[2]%360*Go:0,n()):[m*Yo,y*Yo,b*Yo]},co.rebind(e,f,"precision"),function(){return a=t.apply(this,arguments),e.invert=a.invert&&r,n()}}function cr(t){return or(t,function(e,r){t.point(e*Go,r*Go)})}function ur(t,e){return[t,e]}function fr(t,e){return[t>Uo?t-Vo:-Uo>t?t+Vo:t,e]}function hr(t,e,r){return t?e||r?Ce(pr(t),gr(e,r)):pr(t):e||r?gr(e,r):fr}function dr(t){return function(e,r){return e+=t,[e>Uo?e-Vo:-Uo>e?e+Vo:e,r]}}function pr(t){var e=dr(t);return e.invert=dr(-t),e}function gr(t,e){function r(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,c=Math.sin(e),u=c*n+s*i;return[Math.atan2(l*a-u*o,s*n-c*i),nt(u*a+l*o)]}var n=Math.cos(t),i=Math.sin(t),a=Math.cos(e),o=Math.sin(e);return r.invert=function(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,c=Math.sin(e),u=c*a-l*o;return[Math.atan2(l*a+c*o,s*n+u*i),nt(u*n-s*i)]},r}function vr(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=mr(r,i),a=mr(r,a),(o>0?a>i:i>a)&&(i+=o*Vo)):(i=t+o*Vo,a=t-.5*l);for(var c,u=i;o>0?u>a:a>u;u-=l)s.point((c=ke([r,-n*Math.cos(u),-n*Math.sin(u)]))[0],c[1])}}function mr(t,e){var r=me(e);r[0]-=t,we(r);var n=rt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-Do)%(2*Math.PI)}function yr(t,e,r){var n=co.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[t,e]})}}function br(t,e,r){var n=co.range(t,e-Do,r).concat(e);return function(t){return n.map(function(e){return[e,t]})}}function xr(t){return t.source}function _r(t){return t.target}function wr(t,e,r,n){var i=Math.cos(e),a=Math.sin(e),o=Math.cos(n),s=Math.sin(n),l=i*Math.cos(t),c=i*Math.sin(t),u=o*Math.cos(r),f=o*Math.sin(r),h=2*Math.asin(Math.sqrt(st(n-e)+i*o*st(r-t))),d=1/Math.sin(h),p=h?function(t){var e=Math.sin(t*=h)*d,r=Math.sin(h-t)*d,n=r*l+e*u,i=r*c+e*f,o=r*a+e*s;return[Math.atan2(i,n)*Yo,Math.atan2(o,Math.sqrt(n*n+i*i))*Yo]}:function(){return[t*Yo,e*Yo]};return p.distance=h,p}function kr(){function t(t,i){var a=Math.sin(i*=Go),o=Math.cos(i),s=wo((t*=Go)-e),l=Math.cos(s); +Qs+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=n*a-r*o*l)*s),r*a+n*o*l),e=t,r=a,n=o}var e,r,n;Js.point=function(i,a){e=i*Go,r=Math.sin(a*=Go),n=Math.cos(a),Js.point=t},Js.lineEnd=function(){Js.point=Js.lineEnd=k}}function Ar(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}function Mr(t,e){function r(t,e){o>0?-Ho+Do>e&&(e=-Ho+Do):e>Ho-Do&&(e=Ho-Do);var r=o/Math.pow(i(e),a);return[r*Math.sin(a*t),o-r*Math.cos(a*t)]}var n=Math.cos(t),i=function(t){return Math.tan(Uo/4+t/2)},a=t===e?Math.sin(t):Math.log(n/Math.cos(e))/Math.log(i(e)/i(t)),o=n*Math.pow(i(t),a)/a;return a?(r.invert=function(t,e){var r=o-e,n=tt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(o/n,1/a))-Ho]},r):Er}function Tr(t,e){function r(t,e){var r=a-e;return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}var n=Math.cos(t),i=t===e?Math.sin(t):(n-Math.cos(e))/(e-t),a=n/i+t;return wo(i)i;i++){for(;n>1&&et(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function Rr(t,e){return t[0]-e[0]||t[1]-e[1]}function Or(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function Ir(t,e,r,n){var i=t[0],a=r[0],o=e[0]-i,s=n[0]-a,l=t[1],c=r[1],u=e[1]-l,f=n[1]-c,h=(s*(l-c)-f*(i-a))/(f*o-s*u);return[i+h*o,l+h*u]}function Nr(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}function jr(){an(this),this.edge=this.site=this.circle=null}function Fr(t){var e=fl.pop()||new jr;return e.site=t,e}function Dr(t){Zr(t),ll.remove(t),fl.push(t),an(t)}function Br(t){var e=t.circle,r=e.x,n=e.cy,i={x:r,y:n},a=t.P,o=t.N,s=[t];Dr(t);for(var l=a;l.circle&&wo(r-l.circle.x)u;++u)c=s[u],l=s[u-1],en(c.edge,l.site,c.site,i);l=s[0],c=s[f-1],c.edge=Jr(l.site,c.site,null,i),Wr(l),Wr(c)}function Ur(t){for(var e,r,n,i,a=t.x,o=t.y,s=ll._;s;)if(n=Vr(s,o)-a,n>Do)s=s.L;else{if(i=a-qr(s,o),!(i>Do)){n>-Do?(e=s.P,r=s):i>-Do?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=Fr(t);if(ll.insert(e,l),e||r){if(e===r)return Zr(e),r=Fr(e.site),ll.insert(l,r),l.edge=r.edge=Jr(e.site,l.site),Wr(e),void Wr(r);if(!r)return void(l.edge=Jr(e.site,l.site));Zr(e),Zr(r);var c=e.site,u=c.x,f=c.y,h=t.x-u,d=t.y-f,p=r.site,g=p.x-u,v=p.y-f,m=2*(h*v-d*g),y=h*h+d*d,b=g*g+v*v,x={x:(v*y-d*b)/m+u,y:(h*b-g*y)/m+f};en(r.edge,c,p,x),l.edge=Jr(c,t,null,x),r.edge=Jr(t,p,null,x),Wr(e),Wr(r)}}function Vr(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-(1/0);r=o.site;var s=r.x,l=r.y,c=l-e;if(!c)return s;var u=s-n,f=1/a-1/c,h=u/c;return f?(-h+Math.sqrt(h*h-2*f*(u*u/(-2*c)-l+c/2+i-a/2)))/f+n:(n+s)/2}function qr(t,e){var r=t.N;if(r)return Vr(r,e);var n=t.site;return n.y===e?n.x:1/0}function Hr(t){this.site=t,this.edges=[]}function Gr(t){for(var e,r,n,i,a,o,s,l,c,u,f=t[0][0],h=t[1][0],d=t[0][1],p=t[1][1],g=sl,v=g.length;v--;)if(a=g[v],a&&a.prepare())for(s=a.edges,l=s.length,o=0;l>o;)u=s[o].end(),n=u.x,i=u.y,c=s[++o%l].start(),e=c.x,r=c.y,(wo(n-e)>Do||wo(i-r)>Do)&&(s.splice(o,0,new rn(tn(a.site,u,wo(n-f)Do?{x:f,y:wo(e-f)Do?{x:wo(r-p)Do?{x:h,y:wo(e-h)Do?{x:wo(r-d)=-Bo)){var d=l*l+c*c,p=u*u+f*f,g=(f*d-c*p)/h,v=(l*p-u*d)/h,f=v+s,m=hl.pop()||new Xr;m.arc=t,m.site=i,m.x=g+o,m.y=f+Math.sqrt(g*g+v*v),m.cy=f,t.circle=m;for(var y=null,b=ul._;b;)if(m.yv||v>=s)return;if(h>p){if(a){if(a.y>=c)return}else a={x:v,y:l};r={x:v,y:c}}else{if(a){if(a.yn||n>1)if(h>p){if(a){if(a.y>=c)return}else a={x:(l-i)/n,y:l};r={x:(c-i)/n,y:c}}else{if(a){if(a.yd){if(a){if(a.x>=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.xa||f>o||n>h||i>d)){if(p=t.point){var p,g=e-t.x,v=r-t.y,m=g*g+v*v;if(l>m){var y=Math.sqrt(l=m);n=e-y,i=r-y,a=e+y,o=r+y,s=p}}for(var b=t.nodes,x=.5*(u+h),_=.5*(f+d),w=e>=x,k=r>=_,A=k<<1|w,M=A+4;M>A;++A)if(t=b[3&A])switch(3&A){case 0:c(t,u,f,x,_);break;case 1:c(t,x,f,h,_);break;case 2:c(t,u,_,x,d);break;case 3:c(t,x,_,h,d)}}}(t,n,i,a,o),s}function mn(t,e){t=co.rgb(t),e=co.rgb(e);var r=t.r,n=t.g,i=t.b,a=e.r-r,o=e.g-n,s=e.b-i;return function(t){return"#"+wt(Math.round(r+a*t))+wt(Math.round(n+o*t))+wt(Math.round(i+s*t))}}function yn(t,e){var r,n={},i={};for(r in t)r in e?n[r]=_n(t[r],e[r]):i[r]=t[r];for(r in e)r in t||(i[r]=e[r]);return function(t){for(r in n)i[r]=n[r](t);return i}}function bn(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function xn(t,e){var r,n,i,a=pl.lastIndex=gl.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=pl.exec(t))&&(n=gl.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:bn(r,n)})),a=gl.lastIndex;return an;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}function _n(t,e){for(var r,n=co.interpolators.length;--n>=0&&!(r=co.interpolators[n](t,e)););return r}function wn(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;s>r;++r)n.push(_n(t[r],e[r]));for(;a>r;++r)i[r]=t[r];for(;o>r;++r)i[r]=e[r];return function(t){for(r=0;s>r;++r)i[r]=n[r](t);return i}}function kn(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function An(t){return function(e){return 1-t(1-e)}}function Mn(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Tn(t){return t*t}function En(t){return t*t*t}function Ln(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(.5>t?r:3*(t-e)+r-.75)}function Sn(t){return function(e){return Math.pow(e,t)}}function Cn(t){return 1-Math.cos(t*Ho)}function zn(t){return Math.pow(2,10*(t-1))}function Pn(t){return 1-Math.sqrt(1-t*t)}function Rn(t,e){var r;return arguments.length<2&&(e=.45),arguments.length?r=e/Vo*Math.asin(1/t):(t=1,r=e/4),function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*Vo/e)}}function On(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}}function In(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function Nn(t,e){t=co.hcl(t),e=co.hcl(e);var r=t.h,n=t.c,i=t.l,a=e.h-r,o=e.c-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.c:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ht(r+a*t,n+o*t,i+s*t)+""}}function jn(t,e){t=co.hsl(t),e=co.hsl(e);var r=t.h,n=t.s,i=t.l,a=e.h-r,o=e.s-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.s:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ut(r+a*t,n+o*t,i+s*t)+""}}function Fn(t,e){t=co.lab(t),e=co.lab(e);var r=t.l,n=t.a,i=t.b,a=e.l-r,o=e.a-n,s=e.b-i;return function(t){return pt(r+a*t,n+o*t,i+s*t)+""}}function Dn(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function Bn(t){var e=[t.a,t.b],r=[t.c,t.d],n=Vn(e),i=Un(e,r),a=Vn(qn(r,e,-i))||0;e[0]*r[1]180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(Hn(r)+"rotate(",null,")")-2,x:bn(t,e)})):e&&r.push(Hn(r)+"rotate("+e+")")}function Xn(t,e,r,n){t!==e?n.push({i:r.push(Hn(r)+"skewX(",null,")")-2,x:bn(t,e)}):e&&r.push(Hn(r)+"skewX("+e+")")}function Wn(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(Hn(r)+"scale(",null,",",null,")");n.push({i:i-4,x:bn(t[0],e[0])},{i:i-2,x:bn(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(Hn(r)+"scale("+e+")")}function Zn(t,e){var r=[],n=[];return t=co.transform(t),e=co.transform(e),Gn(t.translate,e.translate,r,n),Yn(t.rotate,e.rotate,r,n),Xn(t.skew,e.skew,r,n),Wn(t.scale,e.scale,r,n),t=e=null,function(t){for(var e,i=-1,a=n.length;++i=0;)r.push(i[n])}function li(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++or;++r)(e=t[r][1])>i&&(n=r,i=e);return n}function bi(t){return t.reduce(xi,0)}function xi(t,e){return t+e[1]}function _i(t,e){return wi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function wi(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function ki(t){return[co.min(t),co.max(t)]}function Ai(t,e){return t.value-e.value}function Mi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ti(t,e){t._pack_next=e,e._pack_prev=t}function Ei(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Li(t){function e(t){u=Math.min(t.x-t.r,u),f=Math.max(t.x+t.r,f),h=Math.min(t.y-t.r,h),d=Math.max(t.y+t.r,d)}if((r=t.children)&&(c=r.length)){var r,n,i,a,o,s,l,c,u=1/0,f=-(1/0),h=1/0,d=-(1/0);if(r.forEach(Si),n=r[0],n.x=-n.r,n.y=0,e(n),c>1&&(i=r[1],i.x=i.r,i.y=0,e(i),c>2))for(a=r[2],Pi(n,i,a),e(a),Mi(n,a),n._pack_prev=a,Mi(a,i),i=n._pack_next,o=3;c>o;o++){Pi(n,i,a=r[o]);var p=0,g=1,v=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(Ei(s,a)){p=1;break}if(1==p)for(l=n._pack_prev;l!==s._pack_prev&&!Ei(l,a);l=l._pack_prev,v++);p?(v>g||g==v&&i.ro;o++)a=r[o],a.x-=m,a.y-=y,b=Math.max(b,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=b,r.forEach(Ci)}}function Si(t){t._pack_next=t._pack_prev=t}function Ci(t){delete t._pack_next,delete t._pack_prev}function zi(t,e,r,n){var i=t.children;if(t.x=e+=n*t.x,t.y=r+=n*t.y,t.r*=n,i)for(var a=-1,o=i.length;++a=0;)e=i[a],e.z+=r,e.m+=r,r+=e.s+(n+=e.c)}function Fi(t,e,r){return t.a.parent===e.parent?t.a:r}function Di(t){return 1+co.max(t,function(t){return t.y})}function Bi(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Ui(t){var e=t.children;return e&&e.length?Ui(e[0]):t}function Vi(t){var e,r=t.children;return r&&(e=r.length)?Vi(r[e-1]):t}function qi(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Hi(t,e){var r=t.x+e[3],n=t.y+e[0],i=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return 0>i&&(r+=i/2,i=0),0>a&&(n+=a/2,a=0),{x:r,y:n,dx:i,dy:a}}function Gi(t){var e=t[0],r=t[t.length-1];return r>e?[e,r]:[r,e]}function Yi(t){return t.rangeExtent?t.rangeExtent():Gi(t.range())}function Xi(t,e,r,n){var i=r(t[0],t[1]),a=n(e[0],e[1]);return function(t){return a(i(t))}}function Wi(t,e){var r,n=0,i=t.length-1,a=t[n],o=t[i];return a>o&&(r=n,n=i,i=r,r=a,a=o,o=r),t[n]=e.floor(a),t[i]=e.ceil(o),t}function Zi(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:Tl}function Ki(t,e,r,n){var i=[],a=[],o=0,s=Math.min(t.length,e.length)-1;for(t[s]2?Ki:Xi,l=n?$n:Kn;return o=i(t,e,l,r),s=i(e,t,l,_n),a}function a(t){return o(t)}var o,s;return a.invert=function(t){return s(t)},a.domain=function(e){return arguments.length?(t=e.map(Number),i()):t},a.range=function(t){return arguments.length?(e=t,i()):e},a.rangeRound=function(t){return a.range(t).interpolate(Dn)},a.clamp=function(t){return arguments.length?(n=t,i()):n},a.interpolate=function(t){return arguments.length?(r=t,i()):r},a.ticks=function(e){return ea(t,e)},a.tickFormat=function(e,r){return ra(t,e,r)},a.nice=function(e){return Ji(t,e),i()},a.copy=function(){return $i(t,e,r,n)},i()}function Qi(t,e){return co.rebind(t,e,"range","rangeRound","interpolate","clamp")}function Ji(t,e){return Wi(t,Zi(ta(t,e)[2])),Wi(t,Zi(ta(t,e)[2])),t}function ta(t,e){null==e&&(e=10);var r=Gi(t),n=r[1]-r[0],i=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),a=e/n*i;return.15>=a?i*=10:.35>=a?i*=5:.75>=a&&(i*=2),r[0]=Math.ceil(r[0]/i)*i,r[1]=Math.floor(r[1]/i)*i+.5*i,r[2]=i,r}function ea(t,e){return co.range.apply(co,ta(t,e))}function ra(t,e,r){var n=ta(t,e);if(r){var i=ps.exec(r);if(i.shift(),"s"===i[8]){var a=co.formatPrefix(Math.max(wo(n[0]),wo(n[1])));return i[7]||(i[7]="."+na(a.scale(n[2]))),i[8]="f",r=co.format(i.join("")),function(t){return r(a.scale(t))+a.symbol}}i[7]||(i[7]="."+ia(i[8],n)),r=i.join("")}else r=",."+na(n[2])+"f";return co.format(r)}function na(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function ia(t,e){var r=na(e[2]);return t in El?Math.abs(r-na(Math.max(wo(e[0]),wo(e[1]))))+ +("e"!==t):r-2*("%"===t)}function aa(t,e,r,n){function i(t){return(r?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function a(t){return r?Math.pow(e,t):-Math.pow(e,-t)}function o(e){return t(i(e))}return o.invert=function(e){return a(t.invert(e))},o.domain=function(e){return arguments.length?(r=e[0]>=0,t.domain((n=e.map(Number)).map(i)),o):n},o.base=function(r){return arguments.length?(e=+r,t.domain(n.map(i)),o):e},o.nice=function(){var e=Wi(n.map(i),r?Math:Sl);return t.domain(e),n=e.map(a),o},o.ticks=function(){var t=Gi(n),o=[],s=t[0],l=t[1],c=Math.floor(i(s)),u=Math.ceil(i(l)),f=e%1?2:e;if(isFinite(u-c)){if(r){for(;u>c;c++)for(var h=1;f>h;h++)o.push(a(c)*h);o.push(a(c))}else for(o.push(a(c));c++0;h--)o.push(a(c)*h);for(c=0;o[c]l;u--);o=o.slice(c,u)}return o},o.tickFormat=function(t,r){if(!arguments.length)return Ll;arguments.length<2?r=Ll:"function"!=typeof r&&(r=co.format(r));var n=Math.max(1,e*t/o.ticks().length);return function(t){var o=t/a(Math.round(i(t)));return e-.5>o*e&&(o*=e),n>=o?r(t):""}},o.copy=function(){return aa(t.copy(),e,r,n)},Qi(o,t)}function oa(t,e,r){function n(e){return t(i(e))}var i=sa(e),a=sa(1/e);return n.invert=function(e){return a(t.invert(e))},n.domain=function(e){return arguments.length?(t.domain((r=e.map(Number)).map(i)),n):r},n.ticks=function(t){return ea(r,t)},n.tickFormat=function(t,e){return ra(r,t,e)},n.nice=function(t){return n.domain(Ji(r,t))},n.exponent=function(o){return arguments.length?(i=sa(e=o),a=sa(1/e),t.domain(r.map(i)),n):e},n.copy=function(){return oa(t.copy(),e,r)},Qi(n,t)}function sa(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function la(t,e){function r(r){return a[((i.get(r)||("range"===e.t?i.set(r,t.push(r)):NaN))-1)%a.length]}function n(e,r){return co.range(t.length).map(function(t){return e+r*t})}var i,a,o;return r.domain=function(n){if(!arguments.length)return t;t=[],i=new f;for(var a,o=-1,s=n.length;++or?[NaN,NaN]:[r>0?s[r-1]:t[0],re?NaN:e/a+t,[e,e+1/a]},n.copy=function(){return ua(t,e,r)},i()}function fa(t,e){function r(r){return r>=r?e[co.bisect(t,r)]:void 0}return r.domain=function(e){return arguments.length?(t=e,r):t},r.range=function(t){return arguments.length?(e=t,r):e},r.invertExtent=function(r){return r=e.indexOf(r),[t[r-1],t[r]]},r.copy=function(){return fa(t,e)},r}function ha(t){function e(t){return+t}return e.invert=e,e.domain=e.range=function(r){return arguments.length?(t=r.map(e),e):t},e.ticks=function(e){return ea(t,e)},e.tickFormat=function(e,r){return ra(t,e,r)},e.copy=function(){return ha(t)},e}function da(){return 0}function pa(t){return t.innerRadius}function ga(t){return t.outerRadius}function va(t){return t.startAngle}function ma(t){return t.endAngle}function ya(t){return t&&t.padAngle}function ba(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function xa(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,c=-s*a,u=t[0]+l,f=t[1]+c,h=e[0]+l,d=e[1]+c,p=(u+h)/2,g=(f+d)/2,v=h-u,m=d-f,y=v*v+m*m,b=r-n,x=u*d-h*f,_=(0>m?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,k=(-x*v-m*_)/y,A=(x*m+v*_)/y,M=(-x*v+m*_)/y,T=w-p,E=k-g,L=A-p,S=M-g;return T*T+E*E>L*L+S*S&&(w=A,k=M),[[w-l,k-c],[w*r/b,k*r/b]]}function _a(t){function e(e){function o(){c.push("M",a(t(u),s))}for(var l,c=[],u=[],f=-1,h=e.length,d=Lt(r),p=Lt(n);++f1?t.join("L"):t+"Z"}function ka(t){return t.join("L")+"Z"}function Aa(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1&&i.push("H",n[0]),i.join("")}function Ma(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var c=2;c9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));for(s=-1;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}function Ua(t){return t.length<3?wa(t):t[0]+Ca(t,Ba(t))}function Va(t){for(var e,r,n,i=-1,a=t.length;++i=e?o(t-e):void(c.c=o)}function o(r){var i=p.active,a=p[i];a&&(a.timer.c=null,a.timer.t=NaN,--p.count,delete p[i],a.event&&a.event.interrupt.call(t,t.__data__,a.index));for(var o in p)if(n>+o){var f=p[o];f.timer.c=null,f.timer.t=NaN,--p.count,delete p[o]}c.c=s,Rt(function(){return c.c&&s(r||1)&&(c.c=null,c.t=NaN),1},0,l),p.active=n,g.event&&g.event.start.call(t,t.__data__,e),d=[],g.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&d.push(n)}),h=g.ease,u=g.duration}function s(i){for(var a=i/u,o=h(a),s=d.length;s>0;)d[--s].call(t,o);return a>=1?(g.event&&g.event.end.call(t,t.__data__,e),--p.count?delete p[n]:delete t[r],1):void 0}var l,c,u,h,d,p=t[r]||(t[r]={active:0,count:0}),g=p[n];g||(l=i.time,c=Rt(a,0,l),g=p[n]={tween:new f,time:l,timer:c,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++p.count)}function ro(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function no(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}function io(t){return t.toISOString()}function ao(t,e,r){function n(e){return t(e)}function i(t,r){var n=t[1]-t[0],i=n/r,a=co.bisect(tc,i);return a==tc.length?[e.year,ta(t.map(function(t){return t/31536e6}),r)[2]]:a?e[i/tc[a-1]1?{floor:function(e){for(;r(e=t.floor(e));)e=oo(e-1);return e},ceil:function(e){for(;r(e=t.ceil(e));)e=oo(+e+1);return e}}:t))},n.ticks=function(t,e){var r=Gi(n.domain()),a=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return a&&(t=a[0],e=a[1]),t.range(r[0],oo(+r[1]+1),1>e?1:e)},n.tickFormat=function(){return r},n.copy=function(){return ao(t.copy(),e,r)},Qi(n,t)}function oo(t){return new Date(t)}function so(t){return JSON.parse(t.responseText)}function lo(t){var e=ho.createRange();return e.selectNode(ho.body),e.createContextualFragment(t.responseText)}var co={version:"3.5.16"},uo=[].slice,fo=function(t){return uo.call(t); +},ho=this.document;if(ho)try{fo(ho.documentElement.childNodes)[0].nodeType}catch(po){fo=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),ho)try{ho.createElement("DIV").style.setProperty("opacity",0,"")}catch(go){var vo=this.Element.prototype,mo=vo.setAttribute,yo=vo.setAttributeNS,bo=this.CSSStyleDeclaration.prototype,xo=bo.setProperty;vo.setAttribute=function(t,e){mo.call(this,t,e+"")},vo.setAttributeNS=function(t,e,r){yo.call(this,t,e,r+"")},bo.setProperty=function(t,e,r){xo.call(this,t,e+"",r)}}co.ascending=i,co.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:NaN},co.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++in&&(r=n)}else{for(;++i=n){r=n;break}for(;++in&&(r=n)}return r},co.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i=n){r=n;break}for(;++ir&&(r=n)}else{for(;++i=n){r=n;break}for(;++ir&&(r=n)}return r},co.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}else{for(;++a=n){r=i=n;break}for(;++an&&(r=n),n>i&&(i=n))}return[r,i]},co.sum=function(t,e){var r,n=0,i=t.length,a=-1;if(1===arguments.length)for(;++a1?l/(u-1):void 0},co.deviation=function(){var t=co.variance.apply(this,arguments);return t?Math.sqrt(t):t};var _o=s(i);co.bisectLeft=_o.left,co.bisect=co.bisectRight=_o.right,co.bisector=function(t){return s(1===t.length?function(e,r){return i(t(e),r)}:t)},co.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,2>a&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},co.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},co.pairs=function(t){for(var e,r=0,n=t.length-1,i=t[0],a=new Array(0>n?0:n);n>r;)a[r]=[e=i,i=t[++r]];return a},co.transpose=function(t){if(!(i=t.length))return[];for(var e=-1,r=co.min(t,l),n=new Array(r);++e=0;)for(n=t[i],e=n.length;--e>=0;)r[--o]=n[e];return r};var wo=Math.abs;co.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r===1/0)throw new Error("infinite range");var n,i=[],a=c(wo(r)),o=-1;if(t*=a,e*=a,r*=a,0>r)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)=a.length)return n?n.call(i,o):r?o.sort(r):o;for(var l,c,u,h,d=-1,p=o.length,g=a[s++],v=new f;++d=a.length)return t;var n=[],i=o[r++];return t.forEach(function(t,i){n.push({key:t,values:e(i,r)})}),i?n.sort(function(t,e){return i(t.key,e.key)}):n}var r,n,i={},a=[],o=[];return i.map=function(e,r){return t(r,e,0)},i.entries=function(r){return e(t(co.map,r,0),0)},i.key=function(t){return a.push(t),i},i.sortKeys=function(t){return o[a.length-1]=t,i},i.sortValues=function(t){return r=t,i},i.rollup=function(t){return n=t,i},i},co.set=function(t){var e=new b;if(t)for(var r=0,n=t.length;n>r;++r)e.add(t[r]);return e},u(b,{has:p,add:function(t){return this._[h(t+="")]=!0,t},remove:g,values:v,size:m,empty:y,forEach:function(t){for(var e in this._)t.call(this,d(e))}}),co.behavior={},co.rebind=function(t,e){for(var r,n=1,i=arguments.length;++n=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},co.event=null,co.requote=function(t){return t.replace(To,"\\$&")};var To=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Eo={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]},Lo=function(t,e){return e.querySelector(t)},So=function(t,e){return e.querySelectorAll(t)},Co=function(t,e){var r=t.matches||t[w(t,"matchesSelector")];return(Co=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(Lo=function(t,e){return Sizzle(t,e)[0]||null},So=Sizzle,Co=Sizzle.matchesSelector),co.selection=function(){return co.select(ho.documentElement)};var zo=co.selection.prototype=[];zo.select=function(t){var e,r,n,i,a=[];t=C(t);for(var o=-1,s=this.length;++o=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),Ro.hasOwnProperty(r)?{space:Ro[r],local:t}:t}},zo.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node();return t=co.ns.qualify(t),t.local?r.getAttributeNS(t.space,t.local):r.getAttribute(t)}for(e in t)this.each(P(e,t[e]));return this}return this.each(P(t,e))},zo.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=I(t)).length,i=-1;if(e=r.classList){for(;++ii){if("string"!=typeof t){2>i&&(e="");for(r in t)this.each(F(r,t[r],e));return this}if(2>i){var a=this.node();return n(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(F(t,e,r))},zo.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(D(e,t[e]));return this}return this.each(D(t,e))},zo.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},zo.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},zo.append=function(t){return t=B(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},zo.insert=function(t,e){return t=B(t),e=C(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},zo.remove=function(){return this.each(U)},zo.data=function(t,e){function r(t,r){var n,i,a,o=t.length,u=r.length,h=Math.min(o,u),d=new Array(u),p=new Array(u),g=new Array(o);if(e){var v,m=new f,y=new Array(o);for(n=-1;++nn;++n)p[n]=V(r[n]);for(;o>n;++n)g[n]=t[n]}p.update=d,p.parentNode=d.parentNode=g.parentNode=t.parentNode,s.push(p),l.push(d),c.push(g)}var n,i,a=-1,o=this.length;if(!arguments.length){for(t=new Array(o=(n=this[0]).length);++aa;a++){i.push(e=[]),e.parentNode=(r=this[a]).parentNode;for(var s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return S(i)},zo.order=function(){for(var t=-1,e=this.length;++t=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},zo.sort=function(t){t=H.apply(this,arguments);for(var e=-1,r=this.length;++et;t++)for(var r=this[t],n=0,i=r.length;i>n;n++){var a=r[n];if(a)return a}return null},zo.size=function(){var t=0;return G(this,function(){++t}),t};var Oo=[];co.selection.enter=Y,co.selection.enter.prototype=Oo,Oo.append=zo.append,Oo.empty=zo.empty,Oo.node=zo.node,Oo.call=zo.call,Oo.size=zo.size,Oo.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++sn){if("string"!=typeof t){2>n&&(e=!1);for(r in t)this.each(W(r,t[r],e));return this}if(2>n)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(W(t,e,r))};var Io=co.map({mouseenter:"mouseover",mouseleave:"mouseout"});ho&&Io.forEach(function(t){"on"+t in ho&&Io.remove(t)});var No,jo=0;co.mouse=function(t){return Q(t,E())};var Fo=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;co.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=E().changedTouches),e)for(var n,i=0,a=e.length;a>i;++i)if((n=e[i]).identifier===r)return Q(t,n)},co.behavior.drag=function(){function t(){this.on("mousedown.drag",a).on("touchstart.drag",o)}function e(t,e,n,a,o){return function(){function s(){var t,r,n=e(h,g);n&&(t=n[0]-b[0],r=n[1]-b[1],p|=t|r,b=n,d({type:"drag",x:n[0]+c[0],y:n[1]+c[1],dx:t,dy:r}))}function l(){e(h,g)&&(m.on(a+v,null).on(o+v,null),y(p),d({type:"dragend"}))}var c,u=this,f=co.event.target.correspondingElement||co.event.target,h=u.parentNode,d=r.of(u,arguments),p=0,g=t(),v=".drag"+(null==g?"":"-"+g),m=co.select(n(f)).on(a+v,s).on(o+v,l),y=$(f),b=e(h,g);i?(c=i.apply(u,arguments),c=[c.x-b[0],c.y-b[1]]):c=[0,0],d({type:"dragstart"})}}var r=L(t,"drag","dragstart","dragend"),i=null,a=e(k,co.mouse,n,"mousemove","mouseup"),o=e(J,co.touch,x,"touchmove","touchend");return t.origin=function(e){return arguments.length?(i=e,t):i},co.rebind(t,r,"on")},co.touches=function(t,e){return arguments.length<2&&(e=E().touches),e?fo(e).map(function(e){var r=Q(t,e);return r.identifier=e.identifier,r}):[]};var Do=1e-6,Bo=Do*Do,Uo=Math.PI,Vo=2*Uo,qo=Vo-Do,Ho=Uo/2,Go=Uo/180,Yo=180/Uo,Xo=Math.SQRT2,Wo=2,Zo=4;co.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],c=e[2],u=s-i,f=l-a,h=u*u+f*f;if(Bo>h)n=Math.log(c/o)/Xo,r=function(t){return[i+t*u,a+t*f,o*Math.exp(Xo*t*n)]};else{var d=Math.sqrt(h),p=(c*c-o*o+Zo*h)/(2*o*Wo*d),g=(c*c-o*o-Zo*h)/(2*c*Wo*d),v=Math.log(Math.sqrt(p*p+1)-p),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/Xo,r=function(t){var e=t*n,r=at(v),s=o/(Wo*d)*(r*ot(Xo*e+v)-it(v));return[i+s*u,a+s*f,o*r/at(Xo*e+v)]}}return r.duration=1e3*n,r},co.behavior.zoom=function(){function t(t){t.on(z,f).on($o+".zoom",d).on("dblclick.zoom",p).on(O,h)}function e(t){return[(t[0]-A.x)/A.k,(t[1]-A.y)/A.k]}function r(t){return[t[0]*A.k+A.x,t[1]*A.k+A.y]}function i(t){A.k=Math.max(E[0],Math.min(E[1],t))}function a(t,e){e=r(e),A.x+=t[0]-e[0],A.y+=t[1]-e[1]}function o(e,r,n,o){e.__chart__={x:A.x,y:A.y,k:A.k},i(Math.pow(2,o)),a(v=r,n),e=co.select(e),S>0&&(e=e.transition().duration(S)),e.call(t.event)}function s(){_&&_.domain(x.range().map(function(t){return(t-A.x)/A.k}).map(x.invert)),k&&k.domain(w.range().map(function(t){return(t-A.y)/A.k}).map(w.invert))}function l(t){C++||t({type:"zoomstart"})}function c(t){s(),t({type:"zoom",scale:A.k,translate:[A.x,A.y]})}function u(t){--C||(t({type:"zoomend"}),v=null)}function f(){function t(){s=1,a(co.mouse(i),h),c(o)}function r(){f.on(P,null).on(R,null),d(s),u(o)}var i=this,o=I.of(i,arguments),s=0,f=co.select(n(i)).on(P,t).on(R,r),h=e(co.mouse(i)),d=$(i);Hl.call(i),l(o)}function h(){function t(){var t=co.touches(p);return d=A.k,t.forEach(function(t){t.identifier in v&&(v[t.identifier]=e(t))}),t}function r(){var e=co.event.target;co.select(e).on(x,n).on(_,s),w.push(e);for(var r=co.event.changedTouches,i=0,a=r.length;a>i;++i)v[r[i].identifier]=null;var l=t(),c=Date.now();if(1===l.length){if(500>c-b){var u=l[0];o(p,u,v[u.identifier],Math.floor(Math.log(A.k)/Math.LN2)+1),T()}b=c}else if(l.length>1){var u=l[0],f=l[1],h=u[0]-f[0],d=u[1]-f[1];m=h*h+d*d}}function n(){var t,e,r,n,o=co.touches(p);Hl.call(p);for(var s=0,l=o.length;l>s;++s,n=null)if(r=o[s],n=v[r.identifier]){if(e)break;t=r,e=n}if(n){var u=(u=r[0]-t[0])*u+(u=r[1]-t[1])*u,f=m&&Math.sqrt(u/m);t=[(t[0]+r[0])/2,(t[1]+r[1])/2],e=[(e[0]+n[0])/2,(e[1]+n[1])/2],i(f*d)}b=null,a(t,e),c(g)}function s(){if(co.event.touches.length){for(var e=co.event.changedTouches,r=0,n=e.length;n>r;++r)delete v[e[r].identifier];for(var i in v)return void t()}co.selectAll(w).on(y,null),k.on(z,f).on(O,h),M(),u(g)}var d,p=this,g=I.of(p,arguments),v={},m=0,y=".zoom-"+co.event.changedTouches[0].identifier,x="touchmove"+y,_="touchend"+y,w=[],k=co.select(p),M=$(p);r(),l(g),k.on(z,null).on(O,r)}function d(){var t=I.of(this,arguments);y?clearTimeout(y):(Hl.call(this),g=e(v=m||co.mouse(this)),l(t)),y=setTimeout(function(){y=null,u(t)},50),T(),i(Math.pow(2,.002*Ko())*A.k),a(v,g),c(t)}function p(){var t=co.mouse(this),r=Math.log(A.k)/Math.LN2;o(this,t,e(t),co.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}var g,v,m,y,b,x,_,w,k,A={x:0,y:0,k:1},M=[960,500],E=Qo,S=250,C=0,z="mousedown.zoom",P="mousemove.zoom",R="mouseup.zoom",O="touchstart.zoom",I=L(t,"zoomstart","zoom","zoomend");return $o||($o="onwheel"in ho?(Ko=function(){return-co.event.deltaY*(co.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ho?(Ko=function(){return co.event.wheelDelta},"mousewheel"):(Ko=function(){return-co.event.detail},"MozMousePixelScroll")),t.event=function(t){t.each(function(){var t=I.of(this,arguments),e=A;Vl?co.select(this).transition().each("start.zoom",function(){A=this.__chart__||{x:0,y:0,k:1},l(t)}).tween("zoom:zoom",function(){var r=M[0],n=M[1],i=v?v[0]:r/2,a=v?v[1]:n/2,o=co.interpolateZoom([(i-A.x)/A.k,(a-A.y)/A.k,r/A.k],[(i-e.x)/e.k,(a-e.y)/e.k,r/e.k]);return function(e){var n=o(e),s=r/n[2];this.__chart__=A={x:i-n[0]*s,y:a-n[1]*s,k:s},c(t)}}).each("interrupt.zoom",function(){u(t)}).each("end.zoom",function(){u(t)}):(this.__chart__=A,l(t),c(t),u(t))})},t.translate=function(e){return arguments.length?(A={x:+e[0],y:+e[1],k:A.k},s(),t):[A.x,A.y]},t.scale=function(e){return arguments.length?(A={x:A.x,y:A.y,k:null},i(+e),s(),t):A.k},t.scaleExtent=function(e){return arguments.length?(E=null==e?Qo:[+e[0],+e[1]],t):E},t.center=function(e){return arguments.length?(m=e&&[+e[0],+e[1]],t):m},t.size=function(e){return arguments.length?(M=e&&[+e[0],+e[1]],t):M},t.duration=function(e){return arguments.length?(S=+e,t):S},t.x=function(e){return arguments.length?(_=e,x=e.copy(),A={x:0,y:0,k:1},t):_},t.y=function(e){return arguments.length?(k=e,w=e.copy(),A={x:0,y:0,k:1},t):k},co.rebind(t,I,"on")};var Ko,$o,Qo=[0,1/0];co.color=lt,lt.prototype.toString=function(){return this.rgb()+""},co.hsl=ct;var Jo=ct.prototype=new lt;Jo.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new ct(this.h,this.s,this.l/t)},Jo.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new ct(this.h,this.s,t*this.l)},Jo.rgb=function(){return ut(this.h,this.s,this.l)},co.hcl=ft;var ts=ft.prototype=new lt;ts.brighter=function(t){return new ft(this.h,this.c,Math.min(100,this.l+es*(arguments.length?t:1)))},ts.darker=function(t){return new ft(this.h,this.c,Math.max(0,this.l-es*(arguments.length?t:1)))},ts.rgb=function(){return ht(this.h,this.c,this.l).rgb()},co.lab=dt;var es=18,rs=.95047,ns=1,is=1.08883,as=dt.prototype=new lt;as.brighter=function(t){return new dt(Math.min(100,this.l+es*(arguments.length?t:1)),this.a,this.b)},as.darker=function(t){return new dt(Math.max(0,this.l-es*(arguments.length?t:1)),this.a,this.b)},as.rgb=function(){return pt(this.l,this.a,this.b)},co.rgb=bt;var os=bt.prototype=new lt;os.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&i>e&&(e=i),r&&i>r&&(r=i),n&&i>n&&(n=i),new bt(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new bt(i,i,i)},os.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new bt(t*this.r,t*this.g,t*this.b)},os.hsl=function(){return At(this.r,this.g,this.b)},os.toString=function(){return"#"+wt(this.r)+wt(this.g)+wt(this.b)};var ss=co.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});ss.forEach(function(t,e){ss.set(t,xt(e))}),co.functor=Lt,co.xhr=St(x),co.dsv=function(t,e){function r(t,r,a){arguments.length<3&&(a=r,r=null);var o=Ct(t,e,null==r?n:i(r),a);return o.row=function(t){return arguments.length?o.response(null==(r=t)?n:i(t)):r},o}function n(t){return r.parse(t.responseText)}function i(t){return function(e){return r.parse(e.responseText,t)}}function a(e){return e.map(o).join(t)}function o(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);return r.parse=function(t,e){var n;return r.parseRows(t,function(t,r){if(n)return n(t,r-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");n=e?function(t,r){return e(i(t),r)}:i})},r.parseRows=function(t,e){function r(){if(u>=c)return o;if(i)return i=!1,a;var e=u;if(34===t.charCodeAt(e)){for(var r=e;r++u;){var n=t.charCodeAt(u++),s=1;if(10===n)i=!0;else if(13===n)i=!0,10===t.charCodeAt(u)&&(++u,++s);else if(n!==l)continue;return t.slice(e,u-s)}return t.slice(e)}for(var n,i,a={},o={},s=[],c=t.length,u=0,f=0;(n=r())!==o;){for(var h=[];n!==a&&n!==o;)h.push(n),n=r();e&&null==(h=e(h,f++))||s.push(h)}return s},r.format=function(e){if(Array.isArray(e[0]))return r.formatRows(e);var n=new b,i=[];return e.forEach(function(t){for(var e in t)n.has(e)||i.push(n.add(e))}),[i.map(o).join(t)].concat(e.map(function(e){return i.map(function(t){return o(e[t])}).join(t)})).join("\n")},r.formatRows=function(t){return t.map(a).join("\n")},r},co.csv=co.dsv(",","text/csv"),co.tsv=co.dsv(" ","text/tab-separated-values");var ls,cs,us,fs,hs=this[w(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};co.timer=function(){Rt.apply(this,arguments)},co.timer.flush=function(){It(),Nt()},co.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var ds=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Ft);co.formatPrefix=function(t,e){var r=0;return(t=+t)&&(0>t&&(t*=-1),e&&(t=co.round(t,jt(t,e))),r=1+Math.floor(1e-12+Math.log(t)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),ds[8+r/3]};var ps=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,gs=co.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=co.round(t,jt(t,e))).toFixed(Math.max(0,Math.min(20,jt(t*(1+1e-15),e))))}}),vs=co.time={},ms=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ys.setUTCDate.apply(this._,arguments)},setDay:function(){ys.setUTCDay.apply(this._,arguments)},setFullYear:function(){ys.setUTCFullYear.apply(this._,arguments)},setHours:function(){ys.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ys.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ys.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ys.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ys.setUTCSeconds.apply(this._,arguments)},setTime:function(){ys.setTime.apply(this._,arguments)}};var ys=Date.prototype;vs.year=Vt(function(t){return t=vs.day(t),t.setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),vs.years=vs.year.range,vs.years.utc=vs.year.utc.range,vs.day=Vt(function(t){var e=new ms(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),vs.days=vs.day.range,vs.days.utc=vs.day.utc.range,vs.dayOfYear=function(t){var e=vs.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=vs[t]=Vt(function(t){return(t=vs.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});vs[t+"s"]=r.range,vs[t+"s"].utc=r.utc.range,vs[t+"OfYear"]=function(t){var r=vs.year(t).getDay();return Math.floor((vs.dayOfYear(t)+(r+e)%7)/7)}}),vs.week=vs.sunday,vs.weeks=vs.sunday.range,vs.weeks.utc=vs.sunday.utc.range,vs.weekOfYear=vs.sundayOfYear;var bs={"-":"",_:" ",0:"0"},xs=/^\s*\d+/,_s=/^%/;co.locale=function(t){return{numberFormat:Dt(t),timeFormat:Ht(t)}};var ws=co.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});co.format=ws.numberFormat,co.geo={},fe.prototype={s:0,t:0,add:function(t){he(t,this.t,ks),he(ks.s,this.s,this),this.s?this.t+=ks.t:this.s=ks.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ks=new fe;co.geo.stream=function(t,e){t&&As.hasOwnProperty(t.type)?As[t.type](t,e):de(t,e)};var As={Feature:function(t,e){de(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++nt?4*Uo+t:t,Ls.lineStart=Ls.lineEnd=Ls.point=k}};co.geo.bounds=function(){function t(t,e){b.push(x=[u=t,h=t]),f>e&&(f=e),e>d&&(d=e)}function e(e,r){var n=me([e*Go,r*Go]);if(m){var i=be(m,n),a=[i[1],-i[0],0],o=be(a,i);we(o),o=ke(o);var l=e-p,c=l>0?1:-1,g=o[0]*Yo*c,v=wo(l)>180;if(v^(g>c*p&&c*e>g)){var y=o[1]*Yo;y>d&&(d=y)}else if(g=(g+360)%360-180,v^(g>c*p&&c*e>g)){var y=-o[1]*Yo;f>y&&(f=y)}else f>r&&(f=r),r>d&&(d=r);v?p>e?s(u,e)>s(u,h)&&(h=e):s(e,h)>s(u,h)&&(u=e):h>=u?(u>e&&(u=e),e>h&&(h=e)):e>p?s(u,e)>s(u,h)&&(h=e):s(e,h)>s(u,h)&&(u=e)}else t(e,r);m=n,p=e}function r(){_.point=e}function n(){x[0]=u,x[1]=h,_.point=t,m=null}function i(t,r){if(m){var n=t-p;y+=wo(n)>180?n+(n>0?360:-360):n}else g=t,v=r;Ls.point(t,r),e(t,r)}function a(){Ls.lineStart()}function o(){i(g,v),Ls.lineEnd(),wo(y)>Do&&(u=-(h=180)),x[0]=u,x[1]=h,m=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function c(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:tEs?(u=-(h=180),f=-(d=90)):y>Do?d=90:-Do>y&&(f=-90),x[0]=u,x[1]=h}};return function(t){d=h=-(u=f=1/0),b=[],co.geo.stream(t,_);var e=b.length;if(e){b.sort(l);for(var r,n=1,i=b[0],a=[i];e>n;++n)r=b[n],c(r[0],i)||c(r[1],i)?(s(i[0],r[1])>s(i[0],i[1])&&(i[1]=r[1]),s(r[0],i[1])>s(i[0],i[1])&&(i[0]=r[0])):a.push(i=r);for(var o,r,p=-(1/0),e=a.length-1,n=0,i=a[e];e>=n;i=r,++n)r=a[n],(o=s(i[1],r[0]))>p&&(p=o,u=r[0],h=i[1])}return b=x=null,u===1/0||f===1/0?[[NaN,NaN],[NaN,NaN]]:[[u,f],[h,d]]}}(),co.geo.centroid=function(t){Ss=Cs=zs=Ps=Rs=Os=Is=Ns=js=Fs=Ds=0,co.geo.stream(t,Bs);var e=js,r=Fs,n=Ds,i=e*e+r*r+n*n;return Bo>i&&(e=Os,r=Is,n=Ns,Do>Cs&&(e=zs,r=Ps,n=Rs),i=e*e+r*r+n*n,Bo>i)?[NaN,NaN]:[Math.atan2(r,e)*Yo,nt(n/Math.sqrt(i))*Yo]};var Ss,Cs,zs,Ps,Rs,Os,Is,Ns,js,Fs,Ds,Bs={sphere:k,point:Me,lineStart:Ee,lineEnd:Le,polygonStart:function(){Bs.lineStart=Se},polygonEnd:function(){Bs.lineStart=Ee}},Us=Ie(ze,De,Ue,[-Uo,-Uo/2]),Vs=1e9;co.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),i=a(t),i.valid=!0,i},extent:function(s){return arguments.length?(a=Ge(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(co.geo.conicEqualArea=function(){return Ye(Xe)}).raw=Xe,co.geo.albers=function(){return co.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},co.geo.albersUsa=function(){ +function t(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}var e,r,n,i,a=co.geo.albers(),o=co.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=co.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};return t.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&.234>i&&n>=-.425&&-.214>n?o:i>=.166&&.234>i&&n>=-.214&&-.115>n?s:a).invert(t)},t.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},t.precision=function(e){return arguments.length?(a.precision(e),o.precision(e),s.precision(e),t):a.precision()},t.scale=function(e){return arguments.length?(a.scale(e),o.scale(.35*e),s.scale(e),t.translate(a.translate())):a.scale()},t.translate=function(e){if(!arguments.length)return a.translate();var c=a.scale(),u=+e[0],f=+e[1];return r=a.translate(e).clipExtent([[u-.455*c,f-.238*c],[u+.455*c,f+.238*c]]).stream(l).point,n=o.translate([u-.307*c,f+.201*c]).clipExtent([[u-.425*c+Do,f+.12*c+Do],[u-.214*c-Do,f+.234*c-Do]]).stream(l).point,i=s.translate([u-.205*c,f+.212*c]).clipExtent([[u-.214*c+Do,f+.166*c+Do],[u-.115*c-Do,f+.234*c-Do]]).stream(l).point,t},t.scale(1070)};var qs,Hs,Gs,Ys,Xs,Ws,Zs={point:k,lineStart:k,lineEnd:k,polygonStart:function(){Hs=0,Zs.lineStart=We},polygonEnd:function(){Zs.lineStart=Zs.lineEnd=Zs.point=k,qs+=wo(Hs/2)}},Ks={point:Ze,lineStart:k,lineEnd:k,polygonStart:k,polygonEnd:k},$s={point:Qe,lineStart:Je,lineEnd:tr,polygonStart:function(){$s.lineStart=er},polygonEnd:function(){$s.point=Qe,$s.lineStart=Je,$s.lineEnd=tr}};co.geo.path=function(){function t(t){return t&&("function"==typeof s&&a.pointRadius(+s.apply(this,arguments)),o&&o.valid||(o=i(a)),co.geo.stream(t,o)),a.result()}function e(){return o=null,t}var r,n,i,a,o,s=4.5;return t.area=function(t){return qs=0,co.geo.stream(t,i(Zs)),qs},t.centroid=function(t){return zs=Ps=Rs=Os=Is=Ns=js=Fs=Ds=0,co.geo.stream(t,i($s)),Ds?[js/Ds,Fs/Ds]:Ns?[Os/Ns,Is/Ns]:Rs?[zs/Rs,Ps/Rs]:[NaN,NaN]},t.bounds=function(t){return Xs=Ws=-(Gs=Ys=1/0),co.geo.stream(t,i(Ks)),[[Gs,Ys],[Xs,Ws]]},t.projection=function(t){return arguments.length?(i=(r=t)?t.stream||ir(t):x,e()):r},t.context=function(t){return arguments.length?(a=null==(n=t)?new Ke:new rr(t),"function"!=typeof s&&a.pointRadius(s),e()):n},t.pointRadius=function(e){return arguments.length?(s="function"==typeof e?e:(a.pointRadius(+e),+e),t):s},t.projection(co.geo.albersUsa()).context(null)},co.geo.transform=function(t){return{stream:function(e){var r=new ar(e);for(var n in t)r[n]=t[n];return r}}},ar.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},co.geo.projection=sr,co.geo.projectionMutator=lr,(co.geo.equirectangular=function(){return sr(ur)}).raw=ur.invert=ur,co.geo.rotation=function(t){function e(e){return e=t(e[0]*Go,e[1]*Go),e[0]*=Yo,e[1]*=Yo,e}return t=hr(t[0]%360*Go,t[1]*Go,t.length>2?t[2]*Go:0),e.invert=function(e){return e=t.invert(e[0]*Go,e[1]*Go),e[0]*=Yo,e[1]*=Yo,e},e},fr.invert=ur,co.geo.circle=function(){function t(){var t="function"==typeof n?n.apply(this,arguments):n,e=hr(-t[0]*Go,-t[1]*Go,0).invert,i=[];return r(null,null,1,{point:function(t,r){i.push(t=e(t,r)),t[0]*=Yo,t[1]*=Yo}}),{type:"Polygon",coordinates:[i]}}var e,r,n=[0,0],i=6;return t.origin=function(e){return arguments.length?(n=e,t):n},t.angle=function(n){return arguments.length?(r=vr((e=+n)*Go,i*Go),t):e},t.precision=function(n){return arguments.length?(r=vr(e*Go,(i=+n)*Go),t):i},t.angle(90)},co.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Go,i=t[1]*Go,a=e[1]*Go,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),c=Math.cos(i),u=Math.sin(a),f=Math.cos(a);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-l*f*s)*r),l*u+c*f*s)},co.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return co.range(Math.ceil(a/v)*v,i,v).map(h).concat(co.range(Math.ceil(c/m)*m,l,m).map(d)).concat(co.range(Math.ceil(n/p)*p,r,p).filter(function(t){return wo(t%v)>Do}).map(u)).concat(co.range(Math.ceil(s/g)*g,o,g).filter(function(t){return wo(t%m)>Do}).map(f))}var r,n,i,a,o,s,l,c,u,f,h,d,p=10,g=p,v=90,m=360,y=2.5;return t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})},t.outline=function(){return{type:"Polygon",coordinates:[h(a).concat(d(l).slice(1),h(i).reverse().slice(1),d(c).reverse().slice(1))]}},t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()},t.majorExtent=function(e){return arguments.length?(a=+e[0][0],i=+e[1][0],c=+e[0][1],l=+e[1][1],a>i&&(e=a,a=i,i=e),c>l&&(e=c,c=l,l=e),t.precision(y)):[[a,c],[i,l]]},t.minorExtent=function(e){return arguments.length?(n=+e[0][0],r=+e[1][0],s=+e[0][1],o=+e[1][1],n>r&&(e=n,n=r,r=e),s>o&&(e=s,s=o,o=e),t.precision(y)):[[n,s],[r,o]]},t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()},t.majorStep=function(e){return arguments.length?(v=+e[0],m=+e[1],t):[v,m]},t.minorStep=function(e){return arguments.length?(p=+e[0],g=+e[1],t):[p,g]},t.precision=function(e){return arguments.length?(y=+e,u=yr(s,o,90),f=br(n,r,y),h=yr(c,l,90),d=br(a,i,y),t):y},t.majorExtent([[-180,-90+Do],[180,90-Do]]).minorExtent([[-180,-80-Do],[180,80+Do]])},co.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}var e,r,n=xr,i=_r;return t.distance=function(){return co.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},t.source=function(r){return arguments.length?(n=r,e="function"==typeof r?null:r,t):n},t.target=function(e){return arguments.length?(i=e,r="function"==typeof e?null:e,t):i},t.precision=function(){return arguments.length?t:0},t},co.geo.interpolate=function(t,e){return wr(t[0]*Go,t[1]*Go,e[0]*Go,e[1]*Go)},co.geo.length=function(t){return Qs=0,co.geo.stream(t,Js),Qs};var Qs,Js={sphere:k,point:k,lineStart:kr,lineEnd:k,polygonStart:k,polygonEnd:k},tl=Ar(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(co.geo.azimuthalEqualArea=function(){return sr(tl)}).raw=tl;var el=Ar(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},x);(co.geo.azimuthalEquidistant=function(){return sr(el)}).raw=el,(co.geo.conicConformal=function(){return Ye(Mr)}).raw=Mr,(co.geo.conicEquidistant=function(){return Ye(Tr)}).raw=Tr;var rl=Ar(function(t){return 1/t},Math.atan);(co.geo.gnomonic=function(){return sr(rl)}).raw=rl,Er.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Ho]},(co.geo.mercator=function(){return Lr(Er)}).raw=Er;var nl=Ar(function(){return 1},Math.asin);(co.geo.orthographic=function(){return sr(nl)}).raw=nl;var il=Ar(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(co.geo.stereographic=function(){return sr(il)}).raw=il,Sr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ho]},(co.geo.transverseMercator=function(){var t=Lr(Sr),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):(t=r(),[t[0],t[1],t[2]-90])},r([0,0,90])}).raw=Sr,co.geom={},co.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Lt(r),a=Lt(n),o=t.length,s=[],l=[];for(e=0;o>e;e++)s.push([+i.call(this,t[e],e),+a.call(this,t[e],e),e]);for(s.sort(Rr),e=0;o>e;e++)l.push([s[e][0],-s[e][1]]);var c=Pr(s),u=Pr(l),f=u[0]===c[0],h=u[u.length-1]===c[c.length-1],d=[];for(e=c.length-1;e>=0;--e)d.push(t[s[c[e]][2]]);for(e=+f;e=n&&c.x<=a&&c.y>=i&&c.y<=o?[[n,o],[a,o],[a,i],[n,i]]:[];u.point=t[s]}),e}function r(t){return t.map(function(t,e){return{x:Math.round(a(t,e)/Do)*Do,y:Math.round(o(t,e)/Do)*Do,i:e}})}var n=Cr,i=zr,a=n,o=i,s=dl;return t?e(t):(e.links=function(t){return cn(r(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},e.triangles=function(t){var e=[];return cn(r(t)).cells.forEach(function(r,n){for(var i,a,o=r.site,s=r.edges.sort(Yr),l=-1,c=s.length,u=s[c-1].edge,f=u.l===o?u.r:u.l;++l=c,h=n>=u,d=h<<1|f;t.leaf=!1,t=t.nodes[d]||(t.nodes[d]=pn()),f?i=c:s=c,h?o=u:l=u,a(t,e,r,n,i,o,s,l)}var u,f,h,d,p,g,v,m,y,b=Lt(s),x=Lt(l);if(null!=e)g=e,v=r,m=n,y=i;else if(m=y=-(g=v=1/0),f=[],h=[],p=t.length,o)for(d=0;p>d;++d)u=t[d],u.xm&&(m=u.x),u.y>y&&(y=u.y),f.push(u.x),h.push(u.y);else for(d=0;p>d;++d){var _=+b(u=t[d],d),w=+x(u,d);g>_&&(g=_),v>w&&(v=w),_>m&&(m=_),w>y&&(y=w),f.push(_),h.push(w)}var k=m-g,A=y-v;k>A?y=v+k:m=g+A;var M=pn();if(M.add=function(t){a(M,t,+b(t,++d),+x(t,d),g,v,m,y)},M.visit=function(t){gn(t,M,g,v,m,y)},M.find=function(t){return vn(M,t[0],t[1],g,v,m,y)},d=-1,null==e){for(;++d=0?t.slice(0,e):t,n=e>=0?t.slice(e+1):"in";return r=ml.get(r)||vl,n=yl.get(n)||x,kn(n(r.apply(null,uo.call(arguments,1))))},co.interpolateHcl=Nn,co.interpolateHsl=jn,co.interpolateLab=Fn,co.interpolateRound=Dn,co.transform=function(t){var e=ho.createElementNS(co.ns.prefix.svg,"g");return(co.transform=function(t){if(null!=t){e.setAttribute("transform",t);var r=e.transform.baseVal.consolidate()}return new Bn(r?r.matrix:bl)})(t)},Bn.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var bl={a:1,b:0,c:0,d:1,e:0,f:0};co.interpolateTransform=Zn,co.layout={},co.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++rs*s/m){if(g>l){var c=e.charge/l;t.px-=a*c,t.py-=o*c}return!0}if(e.point&&l&&g>l){var c=e.pointCharge/l;t.px-=a*c,t.py-=o*c}}return!e.charge}}function e(t){t.px=co.event.x,t.py=co.event.y,l.resume()}var r,n,i,a,o,s,l={},c=co.dispatch("start","tick","end"),u=[1,1],f=.9,h=xl,d=_l,p=-30,g=wl,v=.1,m=.64,y=[],b=[];return l.tick=function(){if((i*=.99)<.005)return r=null,c.end({type:"end",alpha:i=0}),!0;var e,n,l,h,d,g,m,x,_,w=y.length,k=b.length;for(n=0;k>n;++n)l=b[n],h=l.source,d=l.target,x=d.x-h.x,_=d.y-h.y,(g=x*x+_*_)&&(g=i*o[n]*((g=Math.sqrt(g))-a[n])/g,x*=g,_*=g,d.x-=x*(m=h.weight+d.weight?h.weight/(h.weight+d.weight):.5),d.y-=_*m,h.x+=x*(m=1-m),h.y+=_*m);if((m=i*v)&&(x=u[0]/2,_=u[1]/2,n=-1,m))for(;++n0?i=t:(r.c=null,r.t=NaN,r=null,c.end({type:"end",alpha:i=0})):t>0&&(c.start({type:"start",alpha:i=t}),r=Rt(l.tick)),l):i},l.start=function(){function t(t,n){if(!r){for(r=new Array(i),l=0;i>l;++l)r[l]=[];for(l=0;c>l;++l){var a=b[l];r[a.source.index].push(a.target),r[a.target.index].push(a.source)}}for(var o,s=r[e],l=-1,u=s.length;++le;++e)(n=y[e]).index=e,n.weight=0;for(e=0;c>e;++e)n=b[e],"number"==typeof n.source&&(n.source=y[n.source]),"number"==typeof n.target&&(n.target=y[n.target]),++n.source.weight,++n.target.weight;for(e=0;i>e;++e)n=y[e],isNaN(n.x)&&(n.x=t("x",f)),isNaN(n.y)&&(n.y=t("y",g)),isNaN(n.px)&&(n.px=n.x),isNaN(n.py)&&(n.py=n.y);if(a=[],"function"==typeof h)for(e=0;c>e;++e)a[e]=+h.call(this,b[e],e);else for(e=0;c>e;++e)a[e]=h;if(o=[],"function"==typeof d)for(e=0;c>e;++e)o[e]=+d.call(this,b[e],e);else for(e=0;c>e;++e)o[e]=d;if(s=[],"function"==typeof p)for(e=0;i>e;++e)s[e]=+p.call(this,y[e],e);else for(e=0;i>e;++e)s[e]=p;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return n||(n=co.behavior.drag().origin(x).on("dragstart.force",ei).on("drag.force",e).on("dragend.force",ri)),arguments.length?void this.on("mouseover.force",ni).on("mouseout.force",ii).call(n):n},co.rebind(l,c,"on")};var xl=20,_l=1,wl=1/0;co.layout.hierarchy=function(){function t(i){var a,o=[i],s=[];for(i.depth=0;null!=(a=o.pop());)if(s.push(a),(c=r.call(t,a,a.depth))&&(l=c.length)){for(var l,c,u;--l>=0;)o.push(u=c[l]),u.parent=a,u.depth=a.depth+1;n&&(a.value=0),a.children=c}else n&&(a.value=+n.call(t,a,a.depth)||0),delete a.children;return li(i,function(t){var r,i;e&&(r=t.children)&&r.sort(e),n&&(i=t.parent)&&(i.value+=t.value)}),s}var e=fi,r=ci,n=ui;return t.sort=function(r){return arguments.length?(e=r,t):e},t.children=function(e){return arguments.length?(r=e,t):r},t.value=function(e){return arguments.length?(n=e,t):n},t.revalue=function(e){return n&&(si(e,function(t){t.children&&(t.value=0)}),li(e,function(e){var r;e.children||(e.value=+n.call(t,e,e.depth)||0),(r=e.parent)&&(r.value+=e.value)})),e},t},co.layout.partition=function(){function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,c=-1;for(n=e.value?n/e.value:0;++cf?-1:1),p=co.sum(c),g=p?(f-l*d)/p:0,v=co.range(l),m=[];return null!=r&&v.sort(r===kl?function(t,e){return c[e]-c[t]}:function(t,e){return r(o[t],o[e])}),v.forEach(function(t){m[t]={data:o[t],value:s=c[t],startAngle:u,endAngle:u+=s*g+d,padAngle:h}}),m}var e=Number,r=kl,n=0,i=Vo,a=0;return t.value=function(r){return arguments.length?(e=r,t):e},t.sort=function(e){return arguments.length?(r=e,t):r},t.startAngle=function(e){return arguments.length?(n=e,t):n},t.endAngle=function(e){return arguments.length?(i=e,t):i},t.padAngle=function(e){return arguments.length?(a=e,t):a},t};var kl={};co.layout.stack=function(){function t(s,l){if(!(h=s.length))return s;var c=s.map(function(r,n){return e.call(t,r,n)}),u=c.map(function(e){return e.map(function(e,r){return[a.call(t,e,r),o.call(t,e,r)]})}),f=r.call(t,u,l);c=co.permute(c,f),u=co.permute(u,f);var h,d,p,g,v=n.call(t,u,l),m=c[0].length;for(p=0;m>p;++p)for(i.call(t,c[0][p],g=v[p],u[0][p][1]),d=1;h>d;++d)i.call(t,c[d][p],g+=u[d-1][p][1],u[d][p][1]);return s}var e=x,r=vi,n=mi,i=gi,a=di,o=pi;return t.values=function(r){return arguments.length?(e=r,t):e},t.order=function(e){return arguments.length?(r="function"==typeof e?e:Al.get(e)||vi,t):r},t.offset=function(e){return arguments.length?(n="function"==typeof e?e:Ml.get(e)||mi,t):n},t.x=function(e){return arguments.length?(a=e,t):a},t.y=function(e){return arguments.length?(o=e,t):o},t.out=function(e){return arguments.length?(i=e,t):i},t};var Al=co.map({"inside-out":function(t){var e,r,n=t.length,i=t.map(yi),a=t.map(bi),o=co.range(n).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,c=[],u=[];for(e=0;n>e;++e)r=o[e],l>s?(s+=a[r],c.push(r)):(l+=a[r],u.push(r));return u.reverse().concat(c)},reverse:function(t){return co.range(t.length).reverse()},"default":vi}),Ml=co.map({silhouette:function(t){var e,r,n,i=t.length,a=t[0].length,o=[],s=0,l=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];n>s&&(s=n),o.push(n)}for(r=0;a>r;++r)l[r]=(s-o[r])/2;return l},wiggle:function(t){var e,r,n,i,a,o,s,l,c,u=t.length,f=t[0],h=f.length,d=[];for(d[0]=l=c=0,r=1;h>r;++r){for(e=0,i=0;u>e;++e)i+=t[e][r][1];for(e=0,a=0,s=f[r][0]-f[r-1][0];u>e;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*s);e>n;++n)o+=(t[n][r][1]-t[n][r-1][1])/s;a+=o*t[e][r][1]}d[r]=l-=i?a/i*s:0,c>l&&(c=l)}for(r=0;h>r;++r)d[r]-=c;return d},expand:function(t){var e,r,n,i=t.length,a=t[0].length,o=1/i,s=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];if(n)for(e=0;i>e;e++)t[e][r][1]/=n;else for(e=0;i>e;e++)t[e][r][1]=o}for(r=0;a>r;++r)s[r]=0;return s},zero:mi});co.layout.histogram=function(){function t(t,a){for(var o,s,l=[],c=t.map(r,this),u=n.call(this,c,a),f=i.call(this,u,c,a),a=-1,h=c.length,d=f.length-1,p=e?1:1/h;++a0)for(a=-1;++a=u[0]&&s<=u[1]&&(o=l[co.bisect(f,s,1,d)-1],o.y+=p,o.push(t[a]));return l}var e=!0,r=Number,n=ki,i=_i;return t.value=function(e){return arguments.length?(r=e,t):r},t.range=function(e){return arguments.length?(n=Lt(e),t):n},t.bins=function(e){return arguments.length?(i="number"==typeof e?function(t){return wi(t,e)}:Lt(e),t):i},t.frequency=function(r){return arguments.length?(e=!!r,t):e},t},co.layout.pack=function(){function t(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],c=i[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,li(s,function(t){t.r=+u(t.value)}),li(s,Li),n){var f=n*(e?1:Math.max(2*s.r/l,2*s.r/c))/2;li(s,function(t){t.r+=f}),li(s,Li),li(s,function(t){t.r-=f})}return zi(s,l/2,c/2,e?1:1/Math.max(2*s.r/l,2*s.r/c)),o}var e,r=co.layout.hierarchy().sort(Ai),n=0,i=[1,1];return t.size=function(e){return arguments.length?(i=e,t):i},t.radius=function(r){return arguments.length?(e=null==r||"function"==typeof r?r:+r,t):e},t.padding=function(e){return arguments.length?(n=+e,t):n},oi(t,r)},co.layout.tree=function(){function t(t,i){var u=o.call(this,t,i),f=u[0],h=e(f);if(li(h,r),h.parent.m=-h.z,si(h,n),c)si(f,a);else{var d=f,p=f,g=f;si(f,function(t){t.xp.x&&(p=t),t.depth>g.depth&&(g=t)});var v=s(d,p)/2-d.x,m=l[0]/(p.x+s(p,d)/2+v),y=l[1]/(g.depth||1);si(f,function(t){t.x=(t.x+v)*m,t.y=t.depth*y})}return u}function e(t){for(var e,r={A:null,children:[t]},n=[r];null!=(e=n.pop());)for(var i,a=e.children,o=0,s=a.length;s>o;++o)n.push((a[o]=i={_:a[o],parent:e,children:(i=a[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return r.children[0]}function r(t){var e=t.children,r=t.parent.children,n=t.i?r[t.i-1]:null;if(e.length){ji(t);var a=(e[0].z+e[e.length-1].z)/2;n?(t.z=n.z+s(t._,n._),t.m=t.z-a):t.z=a}else n&&(t.z=n.z+s(t._,n._));t.parent.A=i(t,n,t.parent.A||r[0])}function n(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function i(t,e,r){if(e){for(var n,i=t,a=t,o=e,l=i.parent.children[0],c=i.m,u=a.m,f=o.m,h=l.m;o=Ii(o),i=Oi(i),o&&i;)l=Oi(l),a=Ii(a),a.a=t,n=o.z+f-i.z-c+s(o._,i._),n>0&&(Ni(Fi(o,t,r),t,n),c+=n,u+=n),f+=o.m,c+=i.m,h+=l.m,u+=a.m;o&&!Ii(a)&&(a.t=o,a.m+=f-u),i&&!Oi(l)&&(l.t=i,l.m+=c-h,r=t)}return r}function a(t){t.x*=l[0],t.y=t.depth*l[1]}var o=co.layout.hierarchy().sort(null).value(null),s=Ri,l=[1,1],c=null;return t.separation=function(e){return arguments.length?(s=e,t):s},t.size=function(e){return arguments.length?(c=null==(l=e)?a:null,t):c?null:l},t.nodeSize=function(e){return arguments.length?(c=null==(l=e)?null:a,t):c?l:null},oi(t,o)},co.layout.cluster=function(){function t(t,a){var o,s=e.call(this,t,a),l=s[0],c=0;li(l,function(t){var e=t.children;e&&e.length?(t.x=Bi(e),t.y=Di(e)):(t.x=o?c+=r(t,o):0,t.y=0,o=t)});var u=Ui(l),f=Vi(l),h=u.x-r(u,f)/2,d=f.x+r(f,u)/2;return li(l,i?function(t){t.x=(t.x-l.x)*n[0],t.y=(l.y-t.y)*n[1]}:function(t){t.x=(t.x-h)/(d-h)*n[0],t.y=(1-(l.y?t.y/l.y:1))*n[1]}),s}var e=co.layout.hierarchy().sort(null).value(null),r=Ri,n=[1,1],i=!1;return t.separation=function(e){return arguments.length?(r=e,t):r},t.size=function(e){return arguments.length?(i=null==(n=e),t):i?null:n},t.nodeSize=function(e){return arguments.length?(i=null!=(n=e),t):i?n:null},oi(t,e)},co.layout.treemap=function(){function t(t,e){for(var r,n,i=-1,a=t.length;++ie?0:e),r.area=isNaN(n)||0>=n?0:n}function e(r){var a=r.children;if(a&&a.length){var o,s,l,c=f(r),u=[],h=a.slice(),p=1/0,g="slice"===d?c.dx:"dice"===d?c.dy:"slice-dice"===d?1&r.depth?c.dy:c.dx:Math.min(c.dx,c.dy);for(t(h,c.dx*c.dy/r.value),u.area=0;(l=h.length)>0;)u.push(o=h[l-1]),u.area+=o.area,"squarify"!==d||(s=n(u,g))<=p?(h.pop(),p=s):(u.area-=u.pop().area,i(u,g,c,!1),g=Math.min(c.dx,c.dy),u.length=u.area=0,p=1/0);u.length&&(i(u,g,c,!0),u.length=u.area=0),a.forEach(e)}}function r(e){var n=e.children;if(n&&n.length){var a,o=f(e),s=n.slice(),l=[];for(t(s,o.dx*o.dy/e.value),l.area=0;a=s.pop();)l.push(a),l.area+=a.area,null!=a.z&&(i(l,a.z?o.dx:o.dy,o,!s.length),l.length=l.area=0);n.forEach(r)}}function n(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++or&&(a=r),r>i&&(i=r));return n*=n,e*=e,n?Math.max(e*i*p/n,n/(e*a*p)):1/0}function i(t,e,r,n){var i,a=-1,o=t.length,s=r.x,c=r.y,u=e?l(t.area/e):0;if(e==r.dx){for((n||u>r.dy)&&(u=r.dy);++ar.dx)&&(u=r.dx);++ar&&(e=1),1>r&&(t=0),function(){var r,n,i;do r=2*Math.random()-1,n=2*Math.random()-1,i=r*r+n*n;while(!i||i>1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=co.random.normal.apply(co,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=co.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;t>r;r++)e+=Math.random();return e}}},co.scale={};var Tl={floor:x,ceil:x};co.scale.linear=function(){return $i([0,1],[0,1],_n,!1)};var El={s:1,g:1,p:1,r:1,e:1};co.scale.log=function(){return aa(co.scale.linear().domain([0,1]),10,!0,[1,10])};var Ll=co.format(".0e"),Sl={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};co.scale.pow=function(){return oa(co.scale.linear(),1,[0,1])},co.scale.sqrt=function(){return co.scale.pow().exponent(.5)},co.scale.ordinal=function(){return la([],{t:"range",a:[[]]})},co.scale.category10=function(){return co.scale.ordinal().range(Cl)},co.scale.category20=function(){return co.scale.ordinal().range(zl)},co.scale.category20b=function(){return co.scale.ordinal().range(Pl)},co.scale.category20c=function(){return co.scale.ordinal().range(Rl)};var Cl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(_t),zl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(_t),Pl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(_t),Rl=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(_t);co.scale.quantile=function(){return ca([],[])},co.scale.quantize=function(){return ua(0,1,[0,1])},co.scale.threshold=function(){return fa([.5],[0,1])},co.scale.identity=function(){return ha([0,1])},co.svg={},co.svg.arc=function(){function t(){var t=Math.max(0,+r.apply(this,arguments)),c=Math.max(0,+n.apply(this,arguments)),u=o.apply(this,arguments)-Ho,f=s.apply(this,arguments)-Ho,h=Math.abs(f-u),d=u>f?0:1;if(t>c&&(p=c,c=t,t=p),h>=qo)return e(c,d)+(t?e(t,1-d):"")+"Z";var p,g,v,m,y,b,x,_,w,k,A,M,T=0,E=0,L=[];if((m=(+l.apply(this,arguments)||0)/2)&&(v=a===Ol?Math.sqrt(t*t+c*c):+a.apply(this,arguments),d||(E*=-1),c&&(E=nt(v/c*Math.sin(m))),t&&(T=nt(v/t*Math.sin(m)))),c){y=c*Math.cos(u+E),b=c*Math.sin(u+E),x=c*Math.cos(f-E),_=c*Math.sin(f-E);var S=Math.abs(f-u-2*E)<=Uo?0:1;if(E&&ba(y,b,x,_)===d^S){var C=(u+f)/2;y=c*Math.cos(C),b=c*Math.sin(C),x=_=null}}else y=b=0;if(t){w=t*Math.cos(f-T),k=t*Math.sin(f-T),A=t*Math.cos(u+T),M=t*Math.sin(u+T);var z=Math.abs(u-f+2*T)<=Uo?0:1;if(T&&ba(w,k,A,M)===1-d^z){ +var P=(u+f)/2;w=t*Math.cos(P),k=t*Math.sin(P),A=M=null}}else w=k=0;if(h>Do&&(p=Math.min(Math.abs(c-t)/2,+i.apply(this,arguments)))>.001){g=c>t^d?0:1;var R=p,O=p;if(Uo>h){var I=null==A?[w,k]:null==x?[y,b]:Ir([y,b],[A,M],[x,_],[w,k]),N=y-I[0],j=b-I[1],F=x-I[0],D=_-I[1],B=1/Math.sin(Math.acos((N*F+j*D)/(Math.sqrt(N*N+j*j)*Math.sqrt(F*F+D*D)))/2),U=Math.sqrt(I[0]*I[0]+I[1]*I[1]);O=Math.min(p,(t-U)/(B-1)),R=Math.min(p,(c-U)/(B+1))}if(null!=x){var V=xa(null==A?[w,k]:[A,M],[y,b],c,R,d),q=xa([x,_],[w,k],c,R,d);p===R?L.push("M",V[0],"A",R,",",R," 0 0,",g," ",V[1],"A",c,",",c," 0 ",1-d^ba(V[1][0],V[1][1],q[1][0],q[1][1]),",",d," ",q[1],"A",R,",",R," 0 0,",g," ",q[0]):L.push("M",V[0],"A",R,",",R," 0 1,",g," ",q[0])}else L.push("M",y,",",b);if(null!=A){var H=xa([y,b],[A,M],t,-O,d),G=xa([w,k],null==x?[y,b]:[x,_],t,-O,d);p===O?L.push("L",G[0],"A",O,",",O," 0 0,",g," ",G[1],"A",t,",",t," 0 ",d^ba(G[1][0],G[1][1],H[1][0],H[1][1]),",",1-d," ",H[1],"A",O,",",O," 0 0,",g," ",H[0]):L.push("L",G[0],"A",O,",",O," 0 0,",g," ",H[0])}else L.push("L",w,",",k)}else L.push("M",y,",",b),null!=x&&L.push("A",c,",",c," 0 ",S,",",d," ",x,",",_),L.push("L",w,",",k),null!=A&&L.push("A",t,",",t," 0 ",z,",",1-d," ",A,",",M);return L.push("Z"),L.join("")}function e(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}var r=pa,n=ga,i=da,a=Ol,o=va,s=ma,l=ya;return t.innerRadius=function(e){return arguments.length?(r=Lt(e),t):r},t.outerRadius=function(e){return arguments.length?(n=Lt(e),t):n},t.cornerRadius=function(e){return arguments.length?(i=Lt(e),t):i},t.padRadius=function(e){return arguments.length?(a=e==Ol?Ol:Lt(e),t):a},t.startAngle=function(e){return arguments.length?(o=Lt(e),t):o},t.endAngle=function(e){return arguments.length?(s=Lt(e),t):s},t.padAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.centroid=function(){var t=(+r.apply(this,arguments)+ +n.apply(this,arguments))/2,e=(+o.apply(this,arguments)+ +s.apply(this,arguments))/2-Ho;return[Math.cos(e)*t,Math.sin(e)*t]},t};var Ol="auto";co.svg.line=function(){return _a(x)};var Il=co.map({linear:wa,"linear-closed":ka,step:Aa,"step-before":Ma,"step-after":Ta,basis:Pa,"basis-open":Ra,"basis-closed":Oa,bundle:Ia,cardinal:Sa,"cardinal-open":Ea,"cardinal-closed":La,monotone:Ua});Il.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Nl=[0,2/3,1/3,0],jl=[0,1/3,2/3,0],Fl=[0,1/6,2/3,1/6];co.svg.line.radial=function(){var t=_a(Va);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Ma.reverse=Ta,Ta.reverse=Ma,co.svg.area=function(){return qa(x)},co.svg.area.radial=function(){var t=qa(Va);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},co.svg.chord=function(){function t(t,s){var l=e(this,a,t,s),c=e(this,o,t,s);return"M"+l.p0+n(l.r,l.p1,l.a1-l.a0)+(r(l,c)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,c.r,c.p0)+n(c.r,c.p1,c.a1-c.a0)+i(c.r,c.p1,l.r,l.p0))+"Z"}function e(t,e,r,n){var i=e.call(t,r,n),a=s.call(t,i,n),o=l.call(t,i,n)-Ho,u=c.call(t,i,n)-Ho;return{r:a,a0:o,a1:u,p0:[a*Math.cos(o),a*Math.sin(o)],p1:[a*Math.cos(u),a*Math.sin(u)]}}function r(t,e){return t.a0==e.a0&&t.a1==e.a1}function n(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Uo)+",1 "+e}function i(t,e,r,n){return"Q 0,0 "+n}var a=xr,o=_r,s=Ha,l=va,c=ma;return t.radius=function(e){return arguments.length?(s=Lt(e),t):s},t.source=function(e){return arguments.length?(a=Lt(e),t):a},t.target=function(e){return arguments.length?(o=Lt(e),t):o},t.startAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.endAngle=function(e){return arguments.length?(c=Lt(e),t):c},t},co.svg.diagonal=function(){function t(t,i){var a=e.call(this,t,i),o=r.call(this,t,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return l=l.map(n),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,r=_r,n=Ga;return t.source=function(r){return arguments.length?(e=Lt(r),t):e},t.target=function(e){return arguments.length?(r=Lt(e),t):r},t.projection=function(e){return arguments.length?(n=e,t):n},t},co.svg.diagonal.radial=function(){var t=co.svg.diagonal(),e=Ga,r=t.projection;return t.projection=function(t){return arguments.length?r(Ya(e=t)):e},t},co.svg.symbol=function(){function t(t,n){return(Dl.get(e.call(this,t,n))||Za)(r.call(this,t,n))}var e=Wa,r=Xa;return t.type=function(r){return arguments.length?(e=Lt(r),t):e},t.size=function(e){return arguments.length?(r=Lt(e),t):r},t};var Dl=co.map({circle:Za,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Ul)),r=e*Ul;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});co.svg.symbolTypes=Dl.keys();var Bl=Math.sqrt(3),Ul=Math.tan(30*Go);zo.transition=function(t){for(var e,r,n=Vl||++Yl,i=to(t),a=[],o=ql||{time:Date.now(),ease:Ln,delay:0,duration:250},s=-1,l=this.length;++sa;a++){i.push(e=[]);for(var r=this[a],s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return $a(i,this.namespace,this.id)},Gl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):G(this,null==e?function(e){e[n][r].tween.remove(t)}:function(i){i[n][r].tween.set(t,e)})},Gl.attr=function(t,e){function r(){this.removeAttribute(s)}function n(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?r:(t+="",function(){var e,r=this.getAttribute(s);return r!==t&&(e=o(r,t),function(t){this.setAttribute(s,e(t))})})}function a(t){return null==t?n:(t+="",function(){var e,r=this.getAttributeNS(s.space,s.local);return r!==t&&(e=o(r,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var o="transform"==t?Zn:_n,s=co.ns.qualify(t);return Qa(this,"attr."+t,e,s.local?a:i)},Gl.attrTween=function(t,e){function r(t,r){var n=e.call(this,t,r,this.getAttribute(i));return n&&function(t){this.setAttribute(i,n(t))}}function n(t,r){var n=e.call(this,t,r,this.getAttributeNS(i.space,i.local));return n&&function(t){this.setAttributeNS(i.space,i.local,n(t))}}var i=co.ns.qualify(t);return this.tween("attr."+t,i.local?n:r)},Gl.style=function(t,e,r){function i(){this.style.removeProperty(t)}function a(e){return null==e?i:(e+="",function(){var i,a=n(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(i=_n(a,e),function(e){this.style.setProperty(t,i(e),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(r in t)this.style(r,t[r],e);return this}r=""}return Qa(this,"style."+t,e,a)},Gl.styleTween=function(t,e,r){function i(i,a){var o=e.call(this,i,a,n(this).getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),r)}}return arguments.length<3&&(r=""),this.tween("style."+t,i)},Gl.text=function(t){return Qa(this,"text",t,Ja)},Gl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},Gl.ease=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].ease:("function"!=typeof t&&(t=co.ease.apply(co,arguments)),G(this,function(n){n[r][e].ease=t}))},Gl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:G(this,"function"==typeof t?function(n,i,a){n[r][e].delay=+t.call(n,n.__data__,i,a)}:(t=+t,function(n){n[r][e].delay=t}))},Gl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:G(this,"function"==typeof t?function(n,i,a){n[r][e].duration=Math.max(1,t.call(n,n.__data__,i,a))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},Gl.each=function(t,e){var r=this.id,n=this.namespace;if(arguments.length<2){var i=ql,a=Vl;try{Vl=r,G(this,function(e,i,a){ql=e[n][r],t.call(e,e.__data__,i,a)})}finally{ql=i,Vl=a}}else G(this,function(i){var a=i[n][r];(a.event||(a.event=co.dispatch("start","end","interrupt"))).on(t,e)});return this},Gl.transition=function(){for(var t,e,r,n,i=this.id,a=++Yl,o=this.namespace,s=[],l=0,c=this.length;c>l;l++){s.push(t=[]);for(var e=this[l],u=0,f=e.length;f>u;u++)(r=e[u])&&(n=r[o][i],eo(r,u,o,a,{time:n.time,ease:n.ease,delay:n.delay+n.duration,duration:n.duration})),t.push(r)}return $a(s,o,a)},co.svg.axis=function(){function t(t){t.each(function(){var t,c=co.select(this),u=this.__chart__||r,f=this.__chart__=r.copy(),h=null==l?f.ticks?f.ticks.apply(f,s):f.domain():l,d=null==e?f.tickFormat?f.tickFormat.apply(f,s):x:e,p=c.selectAll(".tick").data(h,f),g=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Do),v=co.transition(p.exit()).style("opacity",Do).remove(),m=co.transition(p.order()).style("opacity",1),y=Math.max(i,0)+o,b=Yi(f),_=c.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),co.transition(_));g.append("line"),g.append("text");var k,A,M,T,E=g.select("line"),L=m.select("line"),S=p.select("text").text(d),C=g.select("text"),z=m.select("text"),P="top"===n||"left"===n?-1:1;if("bottom"===n||"top"===n?(t=ro,k="x",M="y",A="x2",T="y2",S.attr("dy",0>P?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+P*a+"V0H"+b[1]+"V"+P*a)):(t=no,k="y",M="x",A="y2",T="x2",S.attr("dy",".32em").style("text-anchor",0>P?"end":"start"),w.attr("d","M"+P*a+","+b[0]+"H0V"+b[1]+"H"+P*a)),E.attr(T,P*i),C.attr(M,P*y),L.attr(A,0).attr(T,P*i),z.attr(k,0).attr(M,P*y),f.rangeBand){var R=f,O=R.rangeBand()/2;u=f=function(t){return R(t)+O}}else u.rangeBand?u=f:v.call(t,f,u);g.call(t,u,f),m.call(t,f,f)})}var e,r=co.scale.linear(),n=Xl,i=6,a=6,o=3,s=[10],l=null;return t.scale=function(e){return arguments.length?(r=e,t):r},t.orient=function(e){return arguments.length?(n=e in Wl?e+"":Xl,t):n},t.ticks=function(){return arguments.length?(s=fo(arguments),t):s},t.tickValues=function(e){return arguments.length?(l=e,t):l},t.tickFormat=function(r){return arguments.length?(e=r,t):e},t.tickSize=function(e){var r=arguments.length;return r?(i=+e,a=+arguments[r-1],t):i},t.innerTickSize=function(e){return arguments.length?(i=+e,t):i},t.outerTickSize=function(e){return arguments.length?(a=+e,t):a},t.tickPadding=function(e){return arguments.length?(o=+e,t):o},t.tickSubdivide=function(){return arguments.length&&t},t};var Xl="bottom",Wl={top:1,right:1,bottom:1,left:1};co.svg.brush=function(){function t(n){n.each(function(){var n=co.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",a).on("touchstart.brush",a),o=n.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),n.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=n.selectAll(".resize").data(g,x);s.exit().remove(),s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Zl[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),s.style("display",t.empty()?"none":null);var l,f=co.transition(n),h=co.transition(o);c&&(l=Yi(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),r(f)),u&&(l=Yi(u),h.attr("y",l[0]).attr("height",l[1]-l[0]),i(f)),e(f)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+f[+/e$/.test(t)]+","+h[+/^s/.test(t)]+")"})}function r(t){t.select(".extent").attr("x",f[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",f[1]-f[0])}function i(t){t.select(".extent").attr("y",h[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function a(){function a(){32==co.event.keyCode&&(S||(b=null,z[0]-=f[1],z[1]-=h[1],S=2),T())}function g(){32==co.event.keyCode&&2==S&&(z[0]+=f[1],z[1]+=h[1],S=0,T())}function v(){var t=co.mouse(_),n=!1;x&&(t[0]+=x[0],t[1]+=x[1]),S||(co.event.altKey?(b||(b=[(f[0]+f[1])/2,(h[0]+h[1])/2]),z[0]=f[+(t[0]u?(i=n,n=u):i=u),g[0]!=n||g[1]!=i?(r?s=null:o=null,g[0]=n,g[1]=i,!0):void 0}function y(){v(),A.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null),co.select("body").style("cursor",null),P.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),C(),k({type:"brushend"})}var b,x,_=this,w=co.select(co.event.target),k=l.of(_,arguments),A=co.select(_),M=w.datum(),E=!/^(n|s)$/.test(M)&&c,L=!/^(e|w)$/.test(M)&&u,S=w.classed("extent"),C=$(_),z=co.mouse(_),P=co.select(n(_)).on("keydown.brush",a).on("keyup.brush",g);if(co.event.changedTouches?P.on("touchmove.brush",v).on("touchend.brush",y):P.on("mousemove.brush",v).on("mouseup.brush",y),A.interrupt().selectAll("*").interrupt(),S)z[0]=f[0]-z[0],z[1]=h[0]-z[1];else if(M){var R=+/w$/.test(M),O=+/^n/.test(M);x=[f[1-R]-z[0],h[1-O]-z[1]],z[0]=f[R],z[1]=h[O]}else co.event.altKey&&(b=z.slice());A.style("pointer-events","none").selectAll(".resize").style("display",null),co.select("body").style("cursor",w.style("cursor")),k({type:"brushstart"}),v()}var o,s,l=L(t,"brushstart","brush","brushend"),c=null,u=null,f=[0,0],h=[0,0],d=!0,p=!0,g=Kl[0];return t.event=function(t){t.each(function(){var t=l.of(this,arguments),e={x:f,y:h,i:o,j:s},r=this.__chart__||e;this.__chart__=e,Vl?co.select(this).transition().each("start.brush",function(){o=r.i,s=r.j,f=r.x,h=r.y,t({type:"brushstart"})}).tween("brush:brush",function(){var r=wn(f,e.x),n=wn(h,e.y);return o=s=null,function(i){f=e.x=r(i),h=e.y=n(i),t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i,s=e.j,t({type:"brush",mode:"resize"}),t({type:"brushend"})}):(t({type:"brushstart"}),t({type:"brush",mode:"resize"}),t({type:"brushend"}))})},t.x=function(e){return arguments.length?(c=e,g=Kl[!c<<1|!u],t):c},t.y=function(e){return arguments.length?(u=e,g=Kl[!c<<1|!u],t):u},t.clamp=function(e){return arguments.length?(c&&u?(d=!!e[0],p=!!e[1]):c?d=!!e:u&&(p=!!e),t):c&&u?[d,p]:c?d:u?p:null},t.extent=function(e){var r,n,i,a,l;return arguments.length?(c&&(r=e[0],n=e[1],u&&(r=r[0],n=n[0]),o=[r,n],c.invert&&(r=c(r),n=c(n)),r>n&&(l=r,r=n,n=l),r==f[0]&&n==f[1]||(f=[r,n])),u&&(i=e[0],a=e[1],c&&(i=i[1],a=a[1]),s=[i,a],u.invert&&(i=u(i),a=u(a)),i>a&&(l=i,i=a,a=l),i==h[0]&&a==h[1]||(h=[i,a])),t):(c&&(o?(r=o[0],n=o[1]):(r=f[0],n=f[1],c.invert&&(r=c.invert(r),n=c.invert(n)),r>n&&(l=r,r=n,n=l))),u&&(s?(i=s[0],a=s[1]):(i=h[0],a=h[1],u.invert&&(i=u.invert(i),a=u.invert(a)),i>a&&(l=i,i=a,a=l))),c&&u?[[r,i],[n,a]]:c?[r,n]:u&&[i,a])},t.clear=function(){return t.empty()||(f=[0,0],h=[0,0],o=s=null),t},t.empty=function(){return!!c&&f[0]==f[1]||!!u&&h[0]==h[1]},co.rebind(t,l,"on")};var Zl={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Kl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],$l=vs.format=ws.timeFormat,Ql=$l.utc,Jl=Ql("%Y-%m-%dT%H:%M:%S.%LZ");$l.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?io:Jl,io.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},io.toString=Jl.toString,vs.second=Vt(function(t){return new ms(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),vs.seconds=vs.second.range,vs.seconds.utc=vs.second.utc.range,vs.minute=Vt(function(t){return new ms(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),vs.minutes=vs.minute.range,vs.minutes.utc=vs.minute.utc.range,vs.hour=Vt(function(t){var e=t.getTimezoneOffset()/60;return new ms(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),vs.hours=vs.hour.range,vs.hours.utc=vs.hour.utc.range,vs.month=Vt(function(t){return t=vs.day(t),t.setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),vs.months=vs.month.range,vs.months.utc=vs.month.utc.range;var tc=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],ec=[[vs.second,1],[vs.second,5],[vs.second,15],[vs.second,30],[vs.minute,1],[vs.minute,5],[vs.minute,15],[vs.minute,30],[vs.hour,1],[vs.hour,3],[vs.hour,6],[vs.hour,12],[vs.day,1],[vs.day,2],[vs.week,1],[vs.month,1],[vs.month,3],[vs.year,1]],rc=$l.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",ze]]),nc={range:function(t,e,r){return co.range(Math.ceil(t/r)*r,+e,r).map(oo)},floor:x,ceil:x};ec.year=vs.year,vs.scale=function(){return ao(co.scale.linear(),ec,rc)};var ic=ec.map(function(t){return[t[0].utc,t[1]]}),ac=Ql.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",ze]]);ic.year=vs.year.utc,vs.scale.utc=function(){return ao(co.scale.linear(),ic,ac)},co.text=St(function(t){return t.responseText}),co.json=function(t,e){return Ct(t,"application/json",so,e)},co.html=function(t,e){return Ct(t,"text/html",lo,e)},co.xml=St(function(t){return t.responseXML}),"function"==typeof t&&t.amd?(this.d3=co,t(co)):"object"==typeof r&&r.exports?r.exports=co:this.d3=co}()},{}],114:[function(t,e,r){"use strict";function n(t,e){this.point=t,this.index=e}function i(t,e){for(var r=t.point,n=e.point,i=r.length,a=0;i>a;++a){var o=n[a]-r[a];if(o)return o}return 0}function a(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;t>a;++a){var o=n[a-1],s=n[a];i[a-1]=[o[1],s[1]]}return r&&i.push([-1,i[0][1]],[i[t-1][1],-1]),i}function o(t,e){var r=t.length;if(0===r)return[];var o=t[0].length;if(1>o)return[];if(1===o)return a(r,t,e);for(var c=new Array(r),u=1,f=0;r>f;++f){for(var h=t[f],d=new Array(o+1),p=0,g=0;o>g;++g){var v=h[g];d[g]=v,p+=v*v}d[o]=p,c[f]=new n(d,f),u=Math.max(p,u)}l(c,i),r=c.length;for(var m=new Array(r+o+1),y=new Array(r+o+1),b=(o+1)*(o+1)*u,x=new Array(o+1),f=0;o>=f;++f)x[f]=0;x[o]=b,m[0]=x.slice(),y[0]=-1;for(var f=0;o>=f;++f){var d=x.slice();d[f]=1,m[f+1]=d,y[f+1]=-1}for(var f=0;r>f;++f){var _=c[f];m[f+o+1]=_.point,y[f+o+1]=_.index}var w=s(m,!1);if(w=e?w.filter(function(t){for(var e=0,r=0;o>=r;++r){var n=y[t[r]];if(0>n&&++e>=2)return!1;t[r]=n}return!0}):w.filter(function(t){for(var e=0;o>=e;++e){var r=y[t[e]];if(0>r)return!1;t[e]=r}return!0}),1&o)for(var f=0;f=i)return[];var a,o=new Array(i);if(r===t.length-1)for(a=0;i>a;++a)o[a]=e;else for(a=0;i>a;++a)o[a]=n(t,e,r+1);return o}function i(t,e){var r,n;for(r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e){switch("undefined"==typeof e&&(e=0),typeof t){case"number":if(t>0)return i(0|t,e);break;case"object":if("number"==typeof t.length)return n(t,e,0)}return[]}e.exports=a},{}],116:[function(e,r,n){(function(n,i){(function(){"use strict";function a(t){return"function"==typeof t||"object"==typeof t&&null!==t}function o(t){return"function"==typeof t}function s(t){Y=t}function l(t){K=t}function c(){return function(){n.nextTick(p)}}function u(){return function(){G(p)}}function f(){var t=0,e=new J(p),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){r.data=t=++t%2}}function h(){var t=new MessageChannel;return t.port1.onmessage=p,function(){t.port2.postMessage(0)}}function d(){return function(){setTimeout(p,1)}}function p(){for(var t=0;Z>t;t+=2){var e=rt[t],r=rt[t+1];e(r),rt[t]=void 0,rt[t+1]=void 0}Z=0}function g(){try{var t=e,r=t("vertx");return G=r.runOnLoop||r.runOnContext,u()}catch(n){return d()}}function v(t,e){var r=this,n=r._state;if(n===ot&&!t||n===st&&!e)return this;var i=new this.constructor(y),a=r._result;if(n){var o=arguments[n-1];K(function(){O(n,i,o,a)})}else C(r,i,t,e);return i}function m(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var r=new e(y);return T(r,t),r}function y(){}function b(){return new TypeError("You cannot resolve a promise with itself")}function x(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return lt.error=e,lt}}function w(t,e,r,n){try{t.call(e,r,n)}catch(i){return i}}function k(t,e,r){K(function(t){var n=!1,i=w(r,e,function(r){n||(n=!0,e!==r?T(t,r):L(t,r))},function(e){n||(n=!0,S(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&i&&(n=!0,S(t,i))},t)}function A(t,e){e._state===ot?L(t,e._result):e._state===st?S(t,e._result):C(e,void 0,function(e){T(t,e)},function(e){S(t,e)})}function M(t,e,r){e.constructor===t.constructor&&r===nt&&constructor.resolve===it?A(t,e):r===lt?S(t,lt.error):void 0===r?L(t,e):o(r)?k(t,e,r):L(t,e)}function T(t,e){t===e?S(t,b()):a(e)?M(t,e,_(e)):L(t,e)}function E(t){t._onerror&&t._onerror(t._result),z(t)}function L(t,e){t._state===at&&(t._result=e,t._state=ot,0!==t._subscribers.length&&K(z,t))}function S(t,e){t._state===at&&(t._state=st,t._result=e,K(E,t))}function C(t,e,r,n){var i=t._subscribers,a=i.length;t._onerror=null,i[a]=e,i[a+ot]=r,i[a+st]=n,0===a&&t._state&&K(z,t)}function z(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n,i,a=t._result,o=0;oo;o++)C(n.resolve(t[o]),void 0,e,r);return i}function F(t){var e=this,r=new e(y);return S(r,t),r}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function B(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function U(t){this._id=dt++,this._state=void 0,this._result=void 0,this._subscribers=[],y!==t&&("function"!=typeof t&&D(),this instanceof U?I(this,t):B())}function V(t,e){this._instanceConstructor=t,this.promise=new t(y),Array.isArray(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?L(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&L(this.promise,this._result))):S(this.promise,this._validationError())}function q(){var t;if("undefined"!=typeof i)t=i;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var r=t.Promise;r&&"[object Promise]"===Object.prototype.toString.call(r.resolve())&&!r.cast||(t.Promise=pt)}var H;H=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var G,Y,X,W=H,Z=0,K=function(t,e){rt[Z]=t,rt[Z+1]=e,Z+=2,2===Z&&(Y?Y(p):X())},$="undefined"!=typeof window?window:void 0,Q=$||{},J=Q.MutationObserver||Q.WebKitMutationObserver,tt="undefined"!=typeof n&&"[object process]"==={}.toString.call(n),et="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,rt=new Array(1e3);X=tt?c():J?f():et?h():void 0===$&&"function"==typeof e?g():d();var nt=v,it=m,at=void 0,ot=1,st=2,lt=new P,ct=new P,ut=N,ft=j,ht=F,dt=0,pt=U;U.all=ut,U.race=ft,U.resolve=it,U.reject=ht,U._setScheduler=s,U._setAsap=l,U._asap=K,U.prototype={constructor:U,then:nt,"catch":function(t){return this.then(null,t)}};var gt=V;V.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},V.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===at&&t>r;r++)this._eachEntry(e[r],r)},V.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===it){var i=_(t);if(i===nt&&t._state!==at)this._settledAt(t._state,e,t._result);else if("function"!=typeof i)this._remaining--,this._result[e]=t;else if(r===pt){var a=new r(y);M(a,t,i),this._willSettleAt(a,e)}else this._willSettleAt(new r(function(e){e(t)}),e)}else this._willSettleAt(n(t),e)},V.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===at&&(this._remaining--,t===st?S(n,r):this._result[e]=r),0===this._remaining&&L(n,this._result)},V.prototype._willSettleAt=function(t,e){var r=this;C(t,void 0,function(t){r._settledAt(ot,e,t)},function(t){r._settledAt(st,e,t)})};var vt=q,mt={Promise:pt,polyfill:vt};"function"==typeof t&&t.amd?t(function(){return mt}):"undefined"!=typeof r&&r.exports?r.exports=mt:"undefined"!=typeof this&&(this.ES6Promise=mt),vt()}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:56}],117:[function(t,e,r){"use strict";function n(t){for(var e,r=t.length,n=0;r>n;n++)if(e=t.charCodeAt(n),(9>e||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(8192>e||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(t=+t,0===t&&n(r))return!1}else if("number"!==e)return!1;return 1>t-t}},{}],118:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}function i(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(0>a)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function a(t,e){for(var r=l.malloc(t.length,e),n=t.length,i=0;n>i;++i)r[i]=t[i];return r}function o(t,e){for(var r=1,n=e.length-1;n>=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}function s(t,e,r,i){if(r=r||t.ARRAY_BUFFER,i=i||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(i!==t.DYNAMIC_DRAW&&i!==t.STATIC_DRAW&&i!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=t.createBuffer(),o=new n(t,r,a,0,i);return o.update(e),o}var l=t("typedarray-pool"),c=t("ndarray-ops"),u=t("ndarray"),f=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"],h=n.prototype;h.bind=function(){this.gl.bindBuffer(this.type,this.handle)},h.unbind=function(){this.gl.bindBuffer(this.type,null)},h.dispose=function(){this.gl.deleteBuffer(this.handle)},h.update=function(t,e){if("number"!=typeof e&&(e=-1),this.bind(),"object"==typeof t&&"undefined"!=typeof t.shape){var r=t.dtype;if(f.indexOf(r)<0&&(r="float32"),this.type===this.gl.ELEMENT_ARRAY_BUFFER){var n=gl.getExtension("OES_element_index_uint");r=n&&"uint16"!==r?"uint32":"uint16"}if(r===t.dtype&&o(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=i(this.gl,this.type,this.length,this.usage,t.data,e):this.length=i(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=l.malloc(t.size,r),h=u(s,t.shape);c.assign(h,t),0>e?this.length=i(this.gl,this.type,this.length,this.usage,s,e):this.length=i(this.gl,this.type,this.length,this.usage,s.subarray(0,t.size),e),l.free(s)}}else if(Array.isArray(t)){var d;d=this.type===this.gl.ELEMENT_ARRAY_BUFFER?a(t,"uint16"):a(t,"float32"),0>e?this.length=i(this.gl,this.type,this.length,this.usage,d,e):this.length=i(this.gl,this.type,this.length,this.usage,d.subarray(0,t.length),e),l.free(d)}else if("object"==typeof t&&"number"==typeof t.length)this.length=i(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");t=0|t,0>=t&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=s},{ndarray:253,"ndarray-ops":252,"typedarray-pool":278}],119:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.shader=e,this.buffer=r,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.color=[0,0,0,1]}function i(t,e){var r=a(t.gl,l.vertex,l.fragment),i=o(t.gl),s=new n(t,r,i);return s.update(e),t.addObject(s),s}var a=t("gl-shader"),o=t("gl-buffer"),s=t("typedarray-pool"),l=t("./lib/shaders");e.exports=i;var c=[[1,0,0,1,0,0],[1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,1,0,0],[1,0,0,1,0,0],[1,0,-1,0,0,1],[1,0,-1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,1],[1,0,-1,0,0,1],[-1,0,-1,0,0,1],[-1,0,-1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,1],[-1,0,-1,0,0,1],[0,1,1,0,0,0],[0,1,-1,0,0,0],[0,-1,-1,0,0,0],[0,-1,-1,0,0,0],[0,1,1,0,0,0],[0,-1,1,0,0,0],[0,1,0,-1,1,0],[0,1,0,-1,-1,0],[0,1,0,1,-1,0],[0,1,0,1,1,0],[0,1,0,-1,1,0],[0,1,0,1,-1,0],[0,-1,0,-1,1,0],[0,-1,0,-1,-1,0],[0,-1,0,1,-1,0],[0,-1,0,1,1,0],[0,-1,0,-1,1,0],[0,-1,0,1,-1,0]],u=n.prototype;u.draw=function(){var t=[1,0,0,0,1,0,0,0,1],e=[1,1];return function(){var r=this.plot,n=this.shader,i=this.buffer,a=this.bounds,o=this.numPoints;if(o){var s=r.gl,l=r.dataBox,u=r.viewBox,f=r.pixelRatio,h=a[2]-a[0],d=a[3]-a[1],p=l[2]-l[0],g=l[3]-l[1];t[0]=2*h/p,t[4]=2*d/g,t[6]=2*(a[0]-l[0])/p-1,t[7]=2*(a[1]-l[1])/g-1;var v=u[2]-u[0],m=u[3]-u[1];e[0]=2*f/v,e[1]=2*f/m,i.bind(),n.bind(),n.uniforms.viewTransform=t, +n.uniforms.pixelScale=e,n.uniforms.color=this.color,n.attributes.position.pointer(s.FLOAT,!1,16,0),n.attributes.pixelOffset.pointer(s.FLOAT,!1,16,8),s.drawArrays(s.TRIANGLES,0,o*c.length)}}}(),u.drawPick=function(t){return t},u.pick=function(t,e){return null},u.update=function(t){t=t||{};var e,r,n,i=t.positions||[],a=t.errors||[],o=1;"lineWidth"in t&&(o=+t.lineWidth);var l=5;"capSize"in t&&(l=+t.capSize),this.color=(t.color||[0,0,0,1]).slice();var u=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=this.numPoints=i.length>>1;for(e=0;f>e;++e)r=i[2*e],n=i[2*e+1],u[0]=Math.min(r,u[0]),u[1]=Math.min(n,u[1]),u[2]=Math.max(r,u[2]),u[3]=Math.max(n,u[3]);u[2]===u[0]&&(u[2]+=1),u[3]===u[1]&&(u[3]+=1);var h=1/(u[2]-u[0]),d=1/(u[3]-u[1]),p=u[0],g=u[1],v=s.mallocFloat32(f*c.length*4),m=0;for(e=0;f>e;++e){r=i[2*e],n=i[2*e+1];for(var y=a[4*e],b=a[4*e+1],x=a[4*e+2],_=a[4*e+3],w=0;wA?A*=y:A>0&&(A*=b),0>M?M*=x:M>0&&(M*=_),v[m++]=h*(r-p+A),v[m++]=d*(n-g+M),v[m++]=o*k[2]+(l+o)*k[4],v[m++]=o*k[3]+(l+o)*k[5]}}this.buffer.update(v),s.free(v)},u.dispose=function(){this.plot.removeObject(this),this.shader.dispose(),this.buffer.dispose()}},{"./lib/shaders":120,"gl-buffer":118,"gl-shader":197,"typedarray-pool":278}],120:[function(t,e,r){e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n vec3 scrPosition = viewTransform * vec3(position, 1);\n gl_Position = vec4(\n scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n 0,\n scrPosition.z);\n}\n",fragment:"precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"}},{}],121:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}function i(t,e){for(var r=0;3>r;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}function a(t,e,r,n){for(var i=h[n],a=0;a=1},f.isTransparent=function(){return this.opacity<1},f.drawTransparent=f.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||u,i=r.projection=t.projection||u;r.model=t.model||u,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],c=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var f=0;3>f;++f)e.lineWidth(this.lineWidth[f]),r.capSize=this.capSize[f]*c,e.drawArrays(e.LINES,this.lineOffset[f],this.lineCount[f]);this.vao.unbind()};var h=function(){for(var t=new Array(3),e=0;3>e;++e){for(var r=[],n=1;2>=n;++n)for(var i=-1;1>=i;i+=2){var a=(n+e)%3,o=[0,0,0];o[a]=i,r.push(o)}t[e]=r}return t}();f.update=function(t){t=t||{},"lineWidth"in t&&(this.lineWidth=t.lineWidth,Array.isArray(this.lineWidth)||(this.lineWidth=[this.lineWidth,this.lineWidth,this.lineWidth])),"capSize"in t&&(this.capSize=t.capSize,Array.isArray(this.capSize)||(this.capSize=[this.capSize,this.capSize,this.capSize])),"opacity"in t&&(this.opacity=t.opacity);var e=t.color||[[0,0,0],[0,0,0],[0,0,0]],r=t.position,n=t.error;if(Array.isArray(e[0])||(e=[e,e,e]),r&&n){var o=[],s=r.length,l=0;this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.lineCount=[0,0,0];for(var c=0;3>c;++c){this.lineOffset[c]=l;t:for(var u=0;s>u;++u){for(var f=r[u],h=0;3>h;++h)if(isNaN(f[h])||!isFinite(f[h]))continue t;var d=n[u],p=e[c];if(Array.isArray(p[0])&&(p=e[u]),3===p.length&&(p=[p[0],p[1],p[2],1]),!isNaN(d[0][c])&&!isNaN(d[1][c])){if(d[0][c]<0){var g=f.slice();g[c]+=d[0][c],o.push(f[0],f[1],f[2],p[0],p[1],p[2],p[3],0,0,0,g[0],g[1],g[2],p[0],p[1],p[2],p[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,p,c)}if(d[1][c]>0){var g=f.slice();g[c]+=d[1][c],o.push(f[0],f[1],f[2],p[0],p[1],p[2],p[3],0,0,0,g[0],g[1],g[2],p[0],p[1],p[2],p[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,p,c)}}}this.lineCount[c]=l-this.lineOffset[c]}this.buffer.update(o)}},f.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":122,"gl-buffer":118,"gl-vao":226}],122:[function(t,e,r){"use strict";var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n vec4 worldPosition = model * vec4(position, 1.0);\n worldPosition = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n gl_Position = projection * view * worldPosition;\n fragColor = color;\n fragPosition = position;\n}",a="precision mediump float;\n#define GLSLIFY 1\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = opacity * fragColor;\n}";e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"},{name:"offset",type:"vec3"},{name:"color",type:"vec4"}])}},{"gl-shader":197}],123:[function(t,e,r){"use strict";function n(t){var e=t.getParameter(t.FRAMEBUFFER_BINDING),r=t.getParameter(t.RENDERBUFFER_BINDING),n=t.getParameter(t.TEXTURE_BINDING_2D);return[e,r,n]}function i(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function a(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);y=new Array(r+1);for(var n=0;r>=n;++n){for(var i=new Array(r),a=0;n>a;++a)i[a]=t.COLOR_ATTACHMENT0+a;for(var a=n;r>a;++a)i[a]=t.NONE;y[n]=i}}function o(t){switch(t){case p:throw new Error("gl-fbo: Framebuffer unsupported");case g:throw new Error("gl-fbo: Framebuffer incomplete attachment");case v:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case m:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function s(t,e,r,n,i,a){if(!n)return null;var o=d(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function l(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function c(t){var e=n(t.gl),r=t.gl,a=t.handle=r.createFramebuffer(),c=t._shape[0],u=t._shape[1],f=t.color.length,h=t._ext,d=t._useStencil,p=t._useDepth,g=t._colorType;r.bindFramebuffer(r.FRAMEBUFFER,a);for(var v=0;f>v;++v)t.color[v]=s(r,c,u,g,r.RGBA,r.COLOR_ATTACHMENT0+v);0===f?(t._color_rb=l(r,c,u,r.RGBA4,r.COLOR_ATTACHMENT0),h&&h.drawBuffersWEBGL(y[0])):f>1&&h.drawBuffersWEBGL(y[f]);var m=r.getExtension("WEBGL_depth_texture");m?d?t.depth=s(r,c,u,m.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):p&&(t.depth=s(r,c,u,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):p&&d?t._depth_rb=l(r,c,u,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):p?t._depth_rb=l(r,c,u,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):d&&(t._depth_rb=l(r,c,u,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var b=r.checkFramebufferStatus(r.FRAMEBUFFER);if(b!==r.FRAMEBUFFER_COMPLETE){t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null);for(var v=0;vl;++l)this.color[l]=null;this._color_rb=null,this.depth=null,this._depth_rb=null,this._colorType=n,this._useDepth=a,this._useStencil=o;var u=this,f=[0|e,0|r];Object.defineProperties(f,{0:{get:function(){return u._shape[0]},set:function(t){return u.width=t}},1:{get:function(){return u._shape[1]},set:function(t){return u.height=t}}}),this._shapeVector=f,c(this)}function f(t,e,r){if(t._destroyed)throw new Error("gl-fbo: Can't resize destroyed FBO");if(t._shape[0]!==e||t._shape[1]!==r){var a=t.gl,s=a.getParameter(a.MAX_RENDERBUFFER_SIZE);if(0>e||e>s||0>r||r>s)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var l=n(a),c=0;ce||e>o||0>r||r>o)throw new Error("gl-fbo: Parameters are too large for FBO");n=n||{};var s=1;if("color"in n){if(s=Math.max(0|n.color,0),0>s)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(s>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(s>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+s+" draw buffers")}}var l=t.UNSIGNED_BYTE,c=t.getExtension("OES_texture_float");if(n.float&&s>0){if(!c)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&s>0&&c&&(l=t.FLOAT);var f=!0;"depth"in n&&(f=!!n.depth);var h=!1;return"stencil"in n&&(h=!!n.stencil),new u(t,e,r,l,s,f,h,i)}var d=t("gl-texture2d");e.exports=h;var p,g,v,m,y=null,b=u.prototype;Object.defineProperties(b,{shape:{get:function(){return this._destroyed?[0,0]:this._shapeVector},set:function(t){if(Array.isArray(t)||(t=[0|t,0|t]),2!==t.length)throw new Error("gl-fbo: Shape vector must be length 2");var e=0|t[0],r=0|t[1];return f(this,e,r),[e,r]},enumerable:!1},width:{get:function(){return this._destroyed?0:this._shape[0]},set:function(t){return t=0|t,f(this,t,this._shape[1]),t},enumerable:!1},height:{get:function(){return this._destroyed?0:this._shape[1]},set:function(t){return t=0|t,f(this,this._shape[0],t),t},enumerable:!1}}),b.bind=function(){if(!this._destroyed){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.handle),t.viewport(0,0,this._shape[0],this._shape[1])}},b.dispose=function(){if(!this._destroyed){this._destroyed=!0;var t=this.gl;t.deleteFramebuffer(this.handle),this.handle=null,this.depth&&(this.depth.dispose(),this.depth=null),this._depth_rb&&(t.deleteRenderbuffer(this._depth_rb),this._depth_rb=null);for(var e=0;e2&&!this.usingDashes){var C=this.mitreShader;C.bind();var z=C.uniforms;z.matrix=t,z.color=s,z.screenShape=e,z.radius=l*p,C.attributes.p.pointer(f.FLOAT,!1,48,0),f.drawArrays(f.POINTS,0,u/3|0)}}}}(),h.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0],r=[0,0,0,0];return function(n){var i=this.plot,a=this.pickShader,o=this.lineBuffer,s=this.pickBuffer,l=this.width,c=this.numPoints,u=this.bounds,f=this.vertCount,h=i.gl,d=i.viewBox,p=i.dataBox,g=i.pickPixelRatio,v=u[2]-u[0],m=u[3]-u[1],y=p[2]-p[0],b=p[3]-p[1],x=d[2]-d[0],_=d[3]-d[1];if(this.pickOffset=n,!f)return n+c;t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(u[0]-p[0])/y-1,t[7]=2*(u[1]-p[1])/b-1,e[0]=x,e[1]=_,r[0]=255&n,r[1]=n>>>8&255,r[2]=n>>>16&255,r[3]=n>>>24,a.bind();var w=a.uniforms;w.matrix=t,w.width=l*g,w.pickOffset=r,w.screenShape=e;var k=a.attributes;return o.bind(),k.a.pointer(h.FLOAT,!1,16,0),k.d.pointer(h.FLOAT,!1,16,8),s.bind(),k.pick0.pointer(h.UNSIGNED_BYTE,!1,8,0),k.pick1.pointer(h.UNSIGNED_BYTE,!1,8,4),h.drawArrays(h.TRIANGLES,0,f),n+c}}(),h.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.data;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},h.update=function(t){t=t||{};var e=this.plot.gl;!!t.connectGaps;this.color=(t.color||[0,0,1,1]).slice(),this.width=+(t.width||1),this.fill=(t.fill||[!1,!1,!1,!1]).slice(),this.fillColor=i(t.fillColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);for(var r=t.dashes||[1],n=0,a=0;a1,this.dashPattern=l(e,c(o,[n,1,4],[1,0,0])),this.dashPattern.minFilter=e.NEAREST,this.dashPattern.magFilter=e.NEAREST,this.dashLength=n,u.free(o);var d=t.positions;this.data=d;var p=this.bounds;p[0]=p[1]=1/0,p[2]=p[3]=-(1/0);var g=this.numPoints=d.length>>>1;if(0!==g){for(var a=0;g>a;++a){var v=d[2*a],m=d[2*a+1];isNaN(v)||isNaN(m)||(p[0]=Math.min(p[0],v),p[1]=Math.min(p[1],m),p[2]=Math.max(p[2],v),p[3]=Math.max(p[3],m))}p[0]===p[2]&&(p[2]+=1),p[3]===p[1]&&(p[3]+=1);for(var y=u.mallocFloat32(24*(g-1)),b=u.mallocUint32(12*(g-1)),x=y.length,_=b.length,s=g,w=0;s>1;){var k=--s,v=d[2*s],m=d[2*s+1],A=k-1,M=d[2*A],T=d[2*A+1];if(!(isNaN(v)||isNaN(m)||isNaN(M)||isNaN(T))){w+=1,v=(v-p[0])/(p[2]-p[0]),m=(m-p[1])/(p[3]-p[1]),M=(M-p[0])/(p[2]-p[0]),T=(T-p[1])/(p[3]-p[1]);var E=M-v,L=T-m,S=k|1<<24,C=k-1,z=k,P=k-1|1<<24;y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=L,y[--x]=E,y[--x]=T,y[--x]=M,b[--_]=z,b[--_]=P,y[--x]=-L,y[--x]=-E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C,y[--x]=L,y[--x]=E,y[--x]=m,y[--x]=v,b[--_]=S,b[--_]=C}}this.vertCount=6*w,this.lineBuffer.update(y.subarray(x)),this.pickBuffer.update(b.subarray(_)),u.free(y),u.free(b)}},h.dispose=function(){this.plot.removeObject(this),this.lineBuffer.dispose(),this.pickBuffer.dispose(),this.lineShader.dispose(),this.mitreShader.dispose(),this.fillShader.dispose(),this.pickShader.dispose(),this.dashPattern.dispose()}},{"./lib/shaders":124,"gl-buffer":118,"gl-shader":197,"gl-texture2d":222,ndarray:253,"typedarray-pool":278}],126:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n vec4 projected = projection * view * model * vec4(position, 1.0);\n vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n vec2 tangent = normalize(screenShape * tangentClip.xy);\n vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n worldPosition = position;\n pixelArcLength = arcLength;\n fragColor = color;\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float dashScale;\nuniform float opacity;\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n if(dashWeight < 0.5) {\n discard;\n }\n gl_FragColor = fragColor * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\n#define FLOAT_MAX 1.70141184e38\n#define FLOAT_MIN 1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n highp float av = abs(v);\n\n //Handle special cases\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n //Compute exponent and mantissa\n highp float e = floor(log2(av));\n highp float m = av * pow(2.0, -e) - 1.0;\n \n //Unpack mantissa\n c[1] = floor(128.0 * m);\n m -= c[1] / 128.0;\n c[2] = floor(32768.0 * m);\n m -= c[2] / 32768.0;\n c[3] = floor(8388608.0 * m);\n \n //Unpack exponent\n highp float ebias = e + 127.0;\n c[0] = floor(ebias / 2.0);\n ebias -= c[0] * 2.0;\n c[1] += floor(ebias) * 128.0; \n\n //Unpack sign bit\n c[0] += 128.0 * step(0.0, -v);\n\n //Scale back to range\n return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}",s=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return n(t,i,a,null,s)},r.createPickShader=function(t){return n(t,i,o,null,s)}},{"gl-shader":197}],127:[function(t,e,r){"use strict";function n(t,e){for(var r=0,n=0;3>n;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function i(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;3>r;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function a(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function o(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}function s(t){var e=t.gl||t.scene&&t.scene.gl,r=g(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=v(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=l(e),a=c(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),s=d(new Array(1024),[256,1,4]),f=0;1024>f;++f)s.data[f]=255;var h=u(e,s);h.wrap=e.REPEAT;var p=new o(e,r,n,i,a,h);return p.update(t),p}e.exports=s;var l=t("gl-buffer"),c=t("gl-vao"),u=t("gl-texture2d"),f=t("glsl-read-float"),h=t("binary-search-bounds"),d=t("ndarray"),p=t("./lib/shaders"),g=p.createShader,v=p.createPickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],y=o.prototype;y.isTransparent=function(){return this.opacity<1},y.isOpaque=function(){return this.opacity>=1},y.pickSlots=1,y.setPickBase=function(t){this.pickId=t},y.drawTransparent=y.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,clipBounds:i(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,pickId:this.pickId,clipBounds:i(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.update=function(t){var e,r;this.dirty=!0;var i=!!t.connectGaps;"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var a=t.position||t.positions;if(a){var o=t.color||t.colors||[0,0,0,1],s=t.lineWidth||1,l=[],c=[],u=[],f=0,p=0,g=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],v=!1;t:for(e=1;er;++r){if(isNaN(m[r])||isNaN(y[r])||!isFinite(m[r])||!isFinite(y[r])){if(!i&&l.length>0){for(var b=0;24>b;++b)l.push(l[l.length-12]);p+=2,v=!0}continue t}g[0][r]=Math.min(g[0][r],m[r],y[r]),g[1][r]=Math.max(g[1][r],m[r],y[r])} +var x,_;Array.isArray(o[0])?(x=o[e-1],_=o[e]):x=_=o,3===x.length&&(x=[x[0],x[1],x[2],1]),3===_.length&&(_=[_[0],_[1],_[2],1]);var w;w=Array.isArray(s)?s[e-1]:s;var k=f;if(f+=n(m,y),v){for(r=0;2>r;++r)l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3]);p+=2,v=!1}l.push(m[0],m[1],m[2],y[0],y[1],y[2],k,w,x[0],x[1],x[2],x[3],m[0],m[1],m[2],y[0],y[1],y[2],k,-w,x[0],x[1],x[2],x[3],y[0],y[1],y[2],m[0],m[1],m[2],f,-w,_[0],_[1],_[2],_[3],y[0],y[1],y[2],m[0],m[1],m[2],f,w,_[0],_[1],_[2],_[3]),p+=4}if(this.buffer.update(l),c.push(f),u.push(a[a.length-1].slice()),this.bounds=g,this.vertexCount=p,this.points=u,this.arcLength=c,"dashes"in t){var A=t.dashes,M=A.slice();for(M.unshift(0),e=1;ee;++e){for(r=0;4>r;++r)T.set(e,0,r,0);1&h.le(M,M[M.length-1]*e/255)?T.set(e,0,0,0):T.set(e,0,0,255)}this.texture.setPixels(T)}}},y.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},y.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=f(t.value[0],t.value[1],t.value[2],0),r=h.le(this.arcLength,e);if(0>r)return null;if(r===this.arcLength.length-1)return new a(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],o=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),s=1-o,l=[0,0,0],c=0;3>c;++c)l[c]=s*n[c]+o*i[c];var u=Math.min(.5>o?r:r+1,this.points.length-1);return new a(e,l,u,this.points[u])}},{"./lib/shaders":126,"binary-search-bounds":128,"gl-buffer":118,"gl-texture2d":222,"gl-vao":226,"glsl-read-float":129,ndarray:253}],128:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],129:[function(t,e,r){function n(t,e,r,n){return i[0]=n,i[1]=r,i[2]=e,i[3]=t,a[0]}e.exports=n;var i=new Uint8Array(4),a=new Float32Array(i.buffer)},{}],130:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],f=u*o-s*c,h=-u*a+s*l,d=c*a-o*l,p=r*f+n*h+i*d;return p?(p=1/p,t[0]=f*p,t[1]=(-u*n+i*c)*p,t[2]=(s*n-i*o)*p,t[3]=h*p,t[4]=(u*r-i*l)*p,t[5]=(-s*r+i*a)*p,t[6]=d*p,t[7]=(-c*r+n*l)*p,t[8]=(o*r-n*a)*p,t):null}e.exports=n},{}],131:[function(t,e,r){function n(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}e.exports=n},{}],132:[function(t,e,r){function n(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],133:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],c=t[8],u=t[9],f=t[10],h=t[11],d=t[12],p=t[13],g=t[14],v=t[15],m=e*o-r*a,y=e*s-n*a,b=e*l-i*a,x=r*s-n*o,_=r*l-i*o,w=n*l-i*s,k=c*p-u*d,A=c*g-f*d,M=c*v-h*d,T=u*g-f*p,E=u*v-h*p,L=f*v-h*g;return m*L-y*E+b*T+x*M-_*A+w*k}e.exports=n},{}],134:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,c=r*o,u=n*o,f=n*s,h=i*o,d=i*s,p=i*l,g=a*o,v=a*s,m=a*l;return t[0]=1-f-p,t[1]=u+m,t[2]=h-v,t[3]=0,t[4]=u-m,t[5]=1-c-p,t[6]=d+g,t[7]=0,t[8]=h+v,t[9]=d-g,t[10]=1-c-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],135:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,c=a+a,u=n*s,f=n*l,h=n*c,d=i*l,p=i*c,g=a*c,v=o*s,m=o*l,y=o*c;return t[0]=1-(d+g),t[1]=f+y,t[2]=h-m,t[3]=0,t[4]=f-y,t[5]=1-(u+g),t[6]=p+v,t[7]=0,t[8]=h+m,t[9]=p-v,t[10]=1-(u+d),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}e.exports=n},{}],136:[function(t,e,r){function n(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],137:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],c=e[7],u=e[8],f=e[9],h=e[10],d=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*c-a*o,_=n*l-i*s,w=n*c-a*s,k=i*c-a*l,A=u*g-f*p,M=u*v-h*p,T=u*m-d*p,E=f*v-h*g,L=f*m-d*g,S=h*m-d*v,C=y*S-b*L+x*E+_*T-w*M+k*A;return C?(C=1/C,t[0]=(s*S-l*L+c*E)*C,t[1]=(i*L-n*S-a*E)*C,t[2]=(g*k-v*w+m*_)*C,t[3]=(h*w-f*k-d*_)*C,t[4]=(l*T-o*S-c*M)*C,t[5]=(r*S-i*T+a*M)*C,t[6]=(v*x-p*k-m*b)*C,t[7]=(u*k-h*x+d*b)*C,t[8]=(o*L-s*T+c*A)*C,t[9]=(n*T-r*L-a*A)*C,t[10]=(p*w-g*x+m*y)*C,t[11]=(f*x-u*w-d*y)*C,t[12]=(s*M-o*E-l*A)*C,t[13]=(r*E-n*M+i*A)*C,t[14]=(g*b-p*_-v*y)*C,t[15]=(u*_-f*b+h*y)*C,t):null}e.exports=n},{}],138:[function(t,e,r){function n(t,e,r,n){var a,o,s,l,c,u,f,h,d,p,g=e[0],v=e[1],m=e[2],y=n[0],b=n[1],x=n[2],_=r[0],w=r[1],k=r[2];return Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6&&Math.abs(m-k)<1e-6?i(t):(f=g-_,h=v-w,d=m-k,p=1/Math.sqrt(f*f+h*h+d*d),f*=p,h*=p,d*=p,a=b*d-x*h,o=x*f-y*d,s=y*h-b*f,p=Math.sqrt(a*a+o*o+s*s),p?(p=1/p,a*=p,o*=p,s*=p):(a=0,o=0,s=0),l=h*s-d*o,c=d*a-f*s,u=f*o-h*a,p=Math.sqrt(l*l+c*c+u*u),p?(p=1/p,l*=p,c*=p,u*=p):(l=0,c=0,u=0),t[0]=a,t[1]=l,t[2]=f,t[3]=0,t[4]=o,t[5]=c,t[6]=h,t[7]=0,t[8]=s,t[9]=u,t[10]=d,t[11]=0,t[12]=-(a*g+o*v+s*m),t[13]=-(l*g+c*v+u*m),t[14]=-(f*g+h*v+d*m),t[15]=1,t)}var i=t("./identity");e.exports=n},{"./identity":136}],139:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],f=e[8],h=e[9],d=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*f+w*g,t[1]=b*i+x*l+_*h+w*v,t[2]=b*a+x*c+_*d+w*m,t[3]=b*o+x*u+_*p+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*f+w*g,t[5]=b*i+x*l+_*h+w*v,t[6]=b*a+x*c+_*d+w*m,t[7]=b*o+x*u+_*p+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*f+w*g,t[9]=b*i+x*l+_*h+w*v,t[10]=b*a+x*c+_*d+w*m,t[11]=b*o+x*u+_*p+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*f+w*g,t[13]=b*i+x*l+_*h+w*v,t[14]=b*a+x*c+_*d+w*m,t[15]=b*o+x*u+_*p+w*y,t}e.exports=n},{}],140:[function(t,e,r){function n(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t}e.exports=n},{}],141:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,c,u,f,h,d,p,g,v,m,y,b,x,_,w,k,A,M,T,E,L=n[0],S=n[1],C=n[2],z=Math.sqrt(L*L+S*S+C*C);return Math.abs(z)<1e-6?null:(z=1/z,L*=z,S*=z,C*=z,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],c=e[2],u=e[3],f=e[4],h=e[5],d=e[6],p=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=S*L*o+C*i,_=C*L*o-S*i,w=L*S*o-C*i,k=S*S*o+a,A=C*S*o+L*i,M=L*C*o+S*i,T=S*C*o-L*i,E=C*C*o+a,t[0]=s*b+f*x+g*_,t[1]=l*b+h*x+v*_,t[2]=c*b+d*x+m*_,t[3]=u*b+p*x+y*_,t[4]=s*w+f*k+g*A,t[5]=l*w+h*k+v*A,t[6]=c*w+d*k+m*A,t[7]=u*w+p*k+y*A,t[8]=s*M+f*T+g*E,t[9]=l*M+h*T+v*E,t[10]=c*M+d*T+m*E,t[11]=u*M+p*T+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}e.exports=n},{}],142:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],c=e[8],u=e[9],f=e[10],h=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+c*n,t[5]=o*i+u*n,t[6]=s*i+f*n,t[7]=l*i+h*n,t[8]=c*i-a*n,t[9]=u*i-o*n,t[10]=f*i-s*n,t[11]=h*i-l*n,t}e.exports=n},{}],143:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[8],u=e[9],f=e[10],h=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-c*n,t[1]=o*i-u*n,t[2]=s*i-f*n,t[3]=l*i-h*n,t[8]=a*n+c*i,t[9]=o*n+u*i,t[10]=s*n+f*i,t[11]=l*n+h*i,t}e.exports=n},{}],144:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],c=e[4],u=e[5],f=e[6],h=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+c*n,t[1]=o*i+u*n,t[2]=s*i+f*n,t[3]=l*i+h*n,t[4]=c*i-a*n,t[5]=u*i-o*n,t[6]=f*i-s*n,t[7]=h*i-l*n,t}e.exports=n},{}],145:[function(t,e,r){function n(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}e.exports=n},{}],146:[function(t,e,r){function n(t,e,r){var n,i,a,o,s,l,c,u,f,h,d,p,g=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],c=e[6],u=e[7],f=e[8],h=e[9],d=e[10],p=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=c,t[7]=u,t[8]=f,t[9]=h,t[10]=d,t[11]=p,t[12]=n*g+s*v+f*m+e[12],t[13]=i*g+l*v+h*m+e[13],t[14]=a*g+c*v+d*m+e[14],t[15]=o*g+u*v+p*m+e[15]),t}e.exports=n},{}],147:[function(t,e,r){function n(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}e.exports=n},{}],148:[function(t,e,r){"use strict";function n(t,e){for(var r=[0,0,0,0],n=0;4>n;++n)for(var i=0;4>i;++i)r[i]+=t[4*n+i]*e[n];return r}function i(t,e,r,i,a){for(var o=n(i,n(r,n(e,[t[0],t[1],t[2],1]))),s=0;3>s;++s)o[s]/=o[3];return[.5*a[0]*(1+o[0]),.5*a[1]*(1-o[1])]}function a(t,e){if(2===t.length){for(var r=0,n=0,i=0;2>i;++i)r+=Math.pow(e[i]-t[0][i],2),n+=Math.pow(e[i]-t[1][i],2);return r=Math.sqrt(r),n=Math.sqrt(n),1e-6>r+n?[1,0]:[n/(r+n),r/(n+r)]}if(3===t.length){var a=[0,0];return c(t[0],t[1],t[2],e,a),l(t,a)}return[]}function o(t,e){for(var r=[0,0,0],n=0;no;++o)r[o]+=a*i[o];return r}function s(t,e,r,n,s,l){if(1===t.length)return[0,t[0].slice()];for(var c=new Array(t.length),u=0;up;++p)d+=Math.pow(c[u][p]-e[p],2);h>d&&(h=d,f=u)}for(var g=a(c,e),v=0,u=0;3>u;++u){if(g[u]<-.001||g[u]>1.0001)return null;v+=g[u]}return Math.abs(v-1)>.001?null:[f,o(t,g),g]}var l=t("barycentric"),c=t("polytope-closest-point/lib/closest_point_2d.js");e.exports=s},{barycentric:151,"polytope-closest-point/lib/closest_point_2d.js":153}],149:[function(t,e,r){var n="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n , view\n , projection;\nuniform vec3 eyePosition\n , lightPosition;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}",i="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness,\n float fresnel) {\n\n float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n //Half angle vector\n vec3 H = normalize(lightDirection + viewDirection);\n\n //Geometric term\n float NdotH = max(dot(surfaceNormal, H), 0.0);\n float VdotH = max(dot(viewDirection, H), 0.000001);\n float LdotH = max(dot(lightDirection, H), 0.000001);\n float G1 = (2.0 * NdotH * VdotN) / VdotH;\n float G2 = (2.0 * NdotH * LdotN) / LdotH;\n float G = min(1.0, min(G1, G2));\n \n //Distribution term\n float D = beckmannDistribution_2_0(NdotH, roughness);\n\n //Fresnel term\n float F = pow(1.0 - VdotN, fresnel);\n\n //Multiply terms and done\n return G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n , fresnel\n , kambient\n , kdiffuse\n , kspecular\n , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n , f_lightDirection\n , f_eyeDirection\n , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n \n if(!gl_FrontFacing) {\n N = -N;\n }\n\n float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = litColor * opacity;\n}",a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_color = color;\n f_data = position;\n f_uv = uv;\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n }\n gl_PointSize = pointSize;\n f_color = color;\n f_uv = uv;\n}",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n if(dot(pointR, pointR) > 0.25) {\n discard;\n }\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",c="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n f_id = id;\n f_position = position;\n}",u="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}",f="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute float pointSize;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n gl_Position = projection * view * model * vec4(position, 1.0);\n gl_PointSize = pointSize;\n }\n f_id = id;\n f_position = position;\n}",h="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n}",d="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 contourColor;\n\nvoid main() {\n gl_FragColor = vec4(contourColor,1);\n}\n";r.meshShader={vertex:n,fragment:i,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:a,fragment:o,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:s,fragment:l,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:c,fragment:u,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:f,fragment:u,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:h,fragment:d,attributes:[{name:"position",type:"vec3"}]}},{}],150:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,c,u,f,h,d,p,g,v,m,y,b,x,_,w,k,A,M,T){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=u,this.triangleNormals=h,this.triangleUVs=f,this.triangleIds=c,this.triangleVAO=d,this.triangleCount=0,this.lineWidth=1,this.edgePositions=p,this.edgeColors=v,this.edgeUVs=m,this.edgeIds=g,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=b,this.pointColors=_,this.pointUVs=w,this.pointSizes=k,this.pointIds=x,this.pointVAO=A,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=M,this.contourVAO=T,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=I,this._view=I,this._projection=I,this._resolution=[1,1]}function i(t){for(var e=A({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;256>n;++n){for(var i=e[n],a=0;3>a;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return k(r,[256,256,4],[4,0,1])}function a(t,e,r){for(var n=new Array(e),i=0;e>i;++i)n[i]=0;for(var a=t.length,i=0;a>i;++i)for(var o=t[i],s=0;sn;++n)r[n]=t[n][2];return r}function s(t){var e=v(t,S);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.normal.location=4,e}function l(t){var e=v(t,C);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e}function c(t){var e=v(t,z);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function u(t){var e=v(t,P);return e.attributes.position.location=0,e.attributes.id.location=1,e}function f(t){var e=v(t,R);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function h(t){var e=v(t,O);return e.attributes.position.location=0,e}function d(t){var e=t.gl,r=s(e),i=l(e),a=c(e),o=u(e),d=f(e),p=h(e),g=b(e,k(new Uint8Array([255,255,255,255]),[1,1,4]));g.generateMipmap(),g.minFilter=e.LINEAR_MIPMAP_LINEAR,g.magFilter=e.LINEAR;var v=m(e),x=m(e),_=m(e),w=m(e),A=m(e),M=y(e,[{buffer:v,type:e.FLOAT,size:3},{buffer:A,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:x,type:e.FLOAT,size:4},{buffer:_,type:e.FLOAT,size:2},{buffer:w,type:e.FLOAT,size:3}]),T=m(e),E=m(e),L=m(e),S=m(e),C=y(e,[{buffer:T,type:e.FLOAT,size:3},{buffer:S,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:E,type:e.FLOAT,size:4},{buffer:L,type:e.FLOAT,size:2}]),z=m(e),P=m(e),R=m(e),O=m(e),I=m(e),N=y(e,[{buffer:z,type:e.FLOAT,size:3},{buffer:I,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:P,type:e.FLOAT,size:4},{buffer:R,type:e.FLOAT,size:2},{buffer:O,type:e.FLOAT,size:1}]),j=m(e),F=y(e,[{buffer:j,type:e.FLOAT,size:3}]),D=new n(e,g,r,i,a,o,d,p,v,A,x,_,w,M,T,S,E,L,C,z,I,P,R,O,N,j,F);return D.update(t),D}var p=1e-6,g=1e-6,v=t("gl-shader"),m=t("gl-buffer"),y=t("gl-vao"),b=t("gl-texture2d"),x=t("normals"),_=t("gl-mat4/multiply"),w=t("gl-mat4/invert"),k=t("ndarray"),A=t("colormap"),M=t("simplicial-complex-contour"),T=t("typedarray-pool"),E=t("./lib/shaders"),L=t("./lib/closest-point"),S=E.meshShader,C=E.wireShader,z=E.pointShader,P=E.pickShader,R=E.pointPickShader,O=E.contourShader,I=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],N=n.prototype;N.isOpaque=function(){return this.opacity>=1},N.isTransparent=function(){return this.opacity<1},N.pickSlots=1,N.setPickBase=function(t){this.pickId=t},N.highlight=function(t){if(!t||!this.contourEnable)return void(this.contourCount=0);for(var e=M(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=T.mallocFloat32(6*a),s=0,l=0;a>l;++l)for(var c=r[l],u=0;2>u;++u){var f=c[0];2===c.length&&(f=c[u]);for(var h=n[f][0],d=n[f][1],p=i[f],g=1-p,v=this.positions[h],m=this.positions[d],y=0;3>y;++y)o[s++]=p*v[y]+g*m[y]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),T.free(o)},N.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"lightPosition"in t&&(this.lightPosition=t.lightPosition),"opacity"in t&&(this.opacity=t.opacity),"ambient"in t&&(this.ambientLight=t.ambient),"diffuse"in t&&(this.diffuseLight=t.diffuse),"specular"in t&&(this.specularLight=t.specular),"roughness"in t&&(this.roughness=t.roughness),"fresnel"in t&&(this.fresnel=t.fresnel),t.texture?(this.texture.dispose(),this.texture=b(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(i(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions;if(n&&r){var s=[],l=[],c=[],u=[],f=[],h=[],d=[],v=[],m=[],y=[],_=[],w=[],k=[],A=[];this.cells=r,this.positions=n;var M=t.vertexNormals,T=t.cellNormals,E=void 0===t.vertexNormalsEpsilon?p:t.vertexNormalsEpsilon,L=void 0===t.faceNormalsEpsilon?g:t.faceNormalsEpsilon;t.useFacetNormals&&!T&&(T=x.faceNormals(r,n,L)),T||M||(M=x.vertexNormals(r,n,E));var S=t.vertexColors,C=t.cellColors,z=t.meshColor||[1,1,1,1],P=t.vertexUVs,R=t.vertexIntensity,O=t.cellUVs,I=t.cellIntensity,N=1/0,j=-(1/0);if(!P&&!O)if(R)for(var F=0;Fq;++q)!isNaN(V[q])&&isFinite(V[q])&&(this.bounds[0][q]=Math.min(this.bounds[0][q],V[q]),this.bounds[1][q]=Math.max(this.bounds[1][q],V[q]));var H=0,G=0,Y=0;t:for(var F=0;Fq;++q)if(isNaN(V[q])||!isFinite(V[q]))continue t;y.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?_.push(Z[0],Z[1],Z[2],1):_.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-N)/(j-N),0]:O?O[F]:I?[(I[F]-N)/(j-N),0]:[(V[2]-N)/(j-N),0],w.push(K[0],K[1]),B?k.push(B[W]):k.push(U),A.push(F),Y+=1;break;case 2:for(var q=0;2>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;2>q;++q){var W=X[q],V=n[W];h.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?d.push(Z[0],Z[1],Z[2],1):d.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-N)/(j-N),0]:O?O[F]:I?[(I[F]-N)/(j-N),0]:[(V[2]-N)/(j-N),0],v.push(K[0],K[1]),m.push(F)}G+=1;break;case 3:for(var q=0;3>q;++q)for(var W=X[q],V=n[W],$=0;3>$;++$)if(isNaN(V[$])||!isFinite(V[$]))continue t;for(var q=0;3>q;++q){var W=X[q],V=n[W];s.push(V[0],V[1],V[2]);var Z;Z=S?S[W]:C?C[F]:z,3===Z.length?l.push(Z[0],Z[1],Z[2],1):l.push(Z[0],Z[1],Z[2],Z[3]);var K;K=P?P[W]:R?[(R[W]-N)/(j-N),0]:O?O[F]:I?[(I[F]-N)/(j-N),0]:[(V[2]-N)/(j-N),0],u.push(K[0],K[1]);var Q;Q=M?M[W]:T[F],c.push(Q[0],Q[1],Q[2]),f.push(F)}H+=1}}this.pointCount=Y,this.edgeCount=G,this.triangleCount=H,this.pointPositions.update(y),this.pointColors.update(_),this.pointUVs.update(w),this.pointSizes.update(k),this.pointIds.update(new Uint32Array(A)),this.edgePositions.update(h),this.edgeColors.update(d),this.edgeUVs.update(v),this.edgeIds.update(new Uint32Array(m)),this.trianglePositions.update(s),this.triangleColors.update(l),this.triangleUVs.update(u),this.triangleNormals.update(c),this.triangleIds.update(new Uint32Array(f))}},N.drawTransparent=N.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||I,n=t.view||I,i=t.projection||I,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,contourColor:this.contourColor,texture:0};this.texture.bind(0);var l=new Array(16);_(l,s.view,s.model),_(l,s.projection,l),w(l,l);for(var o=0;3>o;++o)s.eyePosition[o]=l[12+o]/l[15];for(var c=l[15],o=0;3>o;++o)c+=this.lightPosition[o]*l[4*o+3];for(var o=0;3>o;++o){for(var u=l[12+o],f=0;3>f;++f)u+=l[4*f+o]*this.lightPosition[f];s.lightPosition[o]=u/c}if(this.triangleCount>0){var h=this.triShader;h.bind(),h.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}if(this.edgeCount>0&&this.lineWidth>0){var h=this.lineShader;h.bind(),h.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()}if(this.pointCount>0){var h=this.pointShader;h.bind(),h.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}if(this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0){var h=this.contourShader;h.bind(),h.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind()}},N.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||I,n=t.view||I,i=t.projection||I,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255},l=this.pickShader;if(l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0){var l=this.pointPickShader;l.bind(),l.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}},N.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;ao;++o){for(var s=new Array(r+1),l=0;r>=l;++l)s[l]=t[l][o];i[o]=s}i[r]=new Array(r+1);for(var o=0;r>=o;++o)i[r][o]=1;for(var c=new Array(r+1),o=0;r>o;++o)c[o]=e[o];c[r]=1;var u=a(i,c),f=n(u[r+1]);0===f&&(f=1);for(var h=new Array(r+1),o=0;r>=o;++o)h[o]=n(u[o])/f;return h}e.exports=i;var a=t("robust-linear-solve")},{"robust-linear-solve":256}],152:[function(t,e,r){var n=1e-6,i=1e-6;r.vertexNormals=function(t,e,r){for(var i=e.length,a=new Array(i),o=void 0===r?n:r,s=0;i>s;++s)a[s]=[0,0,0];for(var s=0;sx;++x)v[x]=d[x]-p[x],m+=v[x]*v[x],y[x]=g[x]-p[x],b+=y[x]*y[x];if(m*b>o)for(var _=a[u],w=1/Math.sqrt(m*b),x=0;3>x;++x){var k=(x+1)%3,A=(x+2)%3;_[x]+=w*(y[k]*v[A]-y[A]*v[k])}}for(var s=0;i>s;++s){for(var _=a[s],M=0,x=0;3>x;++x)M+=_[x]*_[x];if(M>o)for(var w=1/Math.sqrt(M),x=0;3>x;++x)_[x]*=w;else for(var x=0;3>x;++x)_[x]=0}return a},r.faceNormals=function(t,e,r){for(var n=t.length,a=new Array(n),o=void 0===r?i:r,s=0;n>s;++s){for(var l=t[s],c=new Array(3),u=0;3>u;++u)c[u]=e[l[u]];for(var f=new Array(3),h=new Array(3),u=0;3>u;++u)f[u]=c[1][u]-c[0][u],h[u]=c[2][u]-c[0][u];for(var d=new Array(3),p=0,u=0;3>u;++u){var g=(u+1)%3,v=(u+2)%3;d[u]=f[g]*h[v]-f[v]*h[g],p+=d[u]*d[u]}p=p>o?1/Math.sqrt(p):0;for(var u=0;3>u;++u)d[u]*=p;a[s]=d}return a}},{}],153:[function(t,e,r){"use strict";function n(t,e,r,n,s){i.length=x+_)if(0>x)0>_&&0>h?(_=0,-h>=c?(x=1,y=c+2*h+p):(x=-h/c,y=h*x+p)):(x=0,d>=0?(_=0,y=p):-d>=f?(_=1,y=f+2*d+p):(_=-d/f,y=d*_+p));else if(0>_)_=0,h>=0?(x=0,y=p):-h>=c?(x=1,y=c+2*h+p):(x=-h/c,y=h*x+p);else{var w=1/b;x*=w,_*=w,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p}else{var k,A,M,T;0>x?(k=u+h,A=f+d,A>k?(M=A-k,T=c-2*u+f,M>=T?(x=1,_=0,y=c+2*h+p):(x=M/T,_=1-x,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p)):(x=0,0>=A?(_=1,y=f+2*d+p):d>=0?(_=0,y=p):(_=-d/f,y=d*_+p))):0>_?(k=u+d,A=c+h,A>k?(M=A-k,T=c-2*u+f,M>=T?(_=1,x=0,y=f+2*d+p):(_=M/T,x=1-_,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p)):(_=0,0>=A?(x=1,y=c+2*h+p):h>=0?(x=0,y=p):(x=-h/c,y=h*x+p))):(M=f+d-u-h,0>=M?(x=0,_=1,y=f+2*d+p):(T=c-2*u+f,M>=T?(x=1,_=0,y=c+2*h+p):(x=M/T,_=1-x,y=x*(c*x+u*_+2*h)+_*(u*x+f*_+2*d)+p)))}for(var E=1-x-_,l=0;ly?0:y}var i=new Float64Array(4),a=new Float64Array(4),o=new Float64Array(4);e.exports=n},{}],154:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r=0|Math.max(r,t[n].length);return r-1}function i(t,e){for(var r=t.length,n=f.mallocUint8(r),i=0;r>i;++i)n[i]=t[i]o;++o)for(var s=t[o],e=s.length,l=0;e>l;++l)for(var c=0;l>c;++c){var d=s[c],p=s[l];i[a++]=0|Math.min(d,p),i[a++]=0|Math.max(d,p)}var g=a/2|0;h(u(i,[g,2]));for(var v=2,o=2;a>o;o+=2)i[o-2]===i[o]&&i[o-1]===i[o+1]||(i[v++]=i[o],i[v++]=i[o+1]);return u(i,[v/2|0,2])}function o(t,e,r,n){for(var i=t.data,a=t.shape[0],o=f.mallocDouble(a),s=0,l=0;a>l;++l){var c=i[2*l],h=i[2*l+1];if(r[c]!==r[h]){var d=e[c],p=e[h];i[2*s]=c,i[2*s+1]=h,o[s++]=(p-n)/(p-d)}}return t.shape[0]=s,u(o,[s])}function s(t,e){var r=f.mallocInt32(2*e),n=t.shape[0],i=t.data;r[0]=0;for(var a=0,o=0;n>o;++o){var s=i[2*o];if(s!==a){for(r[2*a+1]=o;++ai;++i)n[i]=[r[2*i],r[2*i+1]];return n}function c(t,e,r,c){r=r||0,"undefined"==typeof c&&(c=n(t));var u=t.length;if(0===u||1>c)return{cells:[],vertexIds:[],vertexWeights:[]};var h=i(e,+r),p=a(t,c),g=o(p,e,h,+r),v=s(p,0|e.length),m=d(c)(t,p.data,v,h),y=l(p),b=[].slice.call(g.data,0,g.shape[0]);return f.free(h),f.free(p.data),f.free(g.data),f.free(v),{cells:m,vertexIds:y,vertexWeights:b}}e.exports=c;var u=t("ndarray"),f=t("typedarray-pool"),h=t("ndarray-sort"),d=t("./lib/codegen")},{"./lib/codegen":155,ndarray:253,"ndarray-sort":158,"typedarray-pool":278}],155:[function(t,e,r){"use strict";function n(t){function e(t){if(!(t.length<=0)){c.push("R.push(");for(var e=0;e0&&c.push(","),c.push("[");for(var n=0;n0&&c.push(","),c.push("B(C,E,c[",i[0],"],c[",i[1],"])")}c.push("]")}c.push(");")}}var r=0,n=new Array(t+1);n[0]=[[]];for(var i=1;t>=i;++i)for(var s=n[i]=o(i),l=0;l>1,v=E[2*m+1];","if(v===b){return m}","if(b1;--i){t+1>i&&c.push("else "),c.push("if(l===",i,"){");for(var u=[],l=0;i>l;++l)u.push("(S[c["+l+"]]<<"+l+")");c.push("var M=",u.join("+"),";if(M===0||M===",(1<i;++i)n[i]=0,i===e&&(n[i]+=.5),i===r&&(n[i]+=.5);return n}function i(t,e){if(0===e||e===(1<=a;++a)if(e&1<=s;++s)~e&1<n;++n)r[n]=i(t,n);return r}e.exports=a;var o=t("convex-hull")},{"convex-hull":102}],157:[function(t,e,r){"use strict";function n(t){switch(t){case"uint8":return[l.mallocUint8,l.freeUint8];case"uint16":return[l.mallocUint16,l.freeUint16];case"uint32":return[l.mallocUint32,l.freeUint32];case"int8":return[l.mallocInt8,l.freeInt8];case"int16":return[l.mallocInt16,l.freeInt16];case"int32":return[l.mallocInt32,l.freeInt32];case"float32":return[l.mallocFloat,l.freeFloat];case"float64":return[l.mallocDouble,l.freeDouble];default:return null}}function i(t){for(var e=[],r=0;t>r;++r)e.push("s"+r);for(var r=0;t>r;++r)e.push("n"+r);for(var r=1;t>r;++r)e.push("d"+r);for(var r=1;t>r;++r)e.push("e"+r);for(var r=1;t>r;++r)e.push("f"+r);return e}function a(t,e){function r(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function a(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}var o=["'use strict'"],s=["ndarrayInsertionSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(i(t.length)),c=n(e),u=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var f=[],h=1;h1){o.push("dptr=0;sptr=ptr");for(var h=t.length-1;h>=0;--h){var d=t[h];0!==d&&o.push(["for(i",d,"=0;i",d,"left){","dptr=0","sptr=cptr-s0");for(var h=1;hb){break __l}"].join(""));for(var h=t.length-1;h>=1;--h)o.push("sptr+=e"+h,"dptr+=f"+h,"}");o.push("dptr=cptr;sptr=cptr-s0");for(var h=t.length-1;h>=0;--h){var d=t[h];0!==d&&o.push(["for(i",d,"=0;i",d,"=0;--h){var d=t[h];0!==d&&o.push(["for(i",d,"=0;i",d,"left)&&("+r("cptr-s0")+">scratch)){",a("cptr",r("cptr-s0")),"cptr-=s0","}",a("cptr","scratch"));if(o.push("}"),t.length>1&&c&&o.push("free(scratch)"),o.push("} return "+s),c){var p=new Function("malloc","free",o.join("\n"));return p(c[0],c[1])}var p=new Function(o.join("\n"));return p()}function o(t,e,r){function a(t){return["(offset+",t,"*s0)"].join("")}function o(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function s(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}function l(e,r,n){if(1===e.length)_.push("ptr0="+a(e[0]));else for(var i=0;i=0;--i){var o=t[i];0!==o&&_.push(["for(i",o,"=0;i",o,"1)for(var i=0;i1?_.push("ptr_shift+=d"+o):_.push("ptr0+=d"+o),_.push("}"))}}function u(e,r,n,i){if(1===r.length)_.push("ptr0="+a(r[0]));else{for(var o=0;o1)for(var o=0;o=1;--o)n&&_.push("pivot_ptr+=f"+o),r.length>1?_.push("ptr_shift+=e"+o):_.push("ptr0+=e"+o),_.push("}")}function f(){t.length>1&&A&&_.push("free(pivot1)","free(pivot2)")}function h(e,r){var n="el"+e,i="el"+r;if(t.length>1){var s="__l"+ ++M;u(s,[n,i],!1,["comp=",o("ptr0"),"-",o("ptr1"),"\n","if(comp>0){tmp0=",n,";",n,"=",i,";",i,"=tmp0;break ",s,"}\n","if(comp<0){break ",s,"}"].join(""))}else _.push(["if(",o(a(n)),">",o(a(i)),"){tmp0=",n,";",n,"=",i,";",i,"=tmp0}"].join(""))}function d(e,r){t.length>1?l([e,r],!1,s("ptr0",o("ptr1"))):_.push(s(a(e),o(a(r))))}function p(e,r,n){if(t.length>1){var i="__l"+ ++M;u(i,[r],!0,[e,"=",o("ptr0"),"-pivot",n,"[pivot_ptr]\n","if(",e,"!==0){break ",i,"}"].join(""))}else _.push([e,"=",o(a(r)),"-pivot",n].join(""))}function g(e,r){t.length>1?l([e,r],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join("")):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join(""))}function v(e,r,n){t.length>1?(l([e,r,n],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join("")),_.push("++"+r,"--"+n)):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","ptr2=",a(n),"\n","++",r,"\n","--",n,"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join(""))}function m(t,e){g(t,e),_.push("--"+e)}function y(e,r,n){t.length>1?l([e,r],!0,[s("ptr0",o("ptr1")),"\n",s("ptr1",["pivot",n,"[pivot_ptr]"].join(""))].join("")):_.push(s(a(e),o(a(r))),s(a(r),"pivot"+n))}function b(e,r){_.push(["if((",r,"-",e,")<=",c,"){\n","insertionSort(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}else{\n",w,"(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}"].join(""))}function x(e,r,n){t.length>1?(_.push(["__l",++M,":while(true){"].join("")),l([e],!0,["if(",o("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",M,"}"].join("")),_.push(n,"}")):_.push(["while(",o(a(e)),"===pivot",r,"){",n,"}"].join(""))}var _=["'use strict'"],w=["ndarrayQuickSort",t.join("d"),e].join(""),k=["left","right","data","offset"].concat(i(t.length)),A=n(e),M=0;_.push(["function ",w,"(",k.join(","),"){"].join(""));var T=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var E=[],L=1;LL;++L)T.push("b_ptr"+L);T.push("ptr3","ptr4","ptr5","ptr6","ptr7","pivot_ptr","ptr_shift","elementSize="+E.join("*")),A?T.push("pivot1=malloc(elementSize)","pivot2=malloc(elementSize)"):T.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")}else T.push("pivot1","pivot2");if(_.push("var "+T.join(",")),h(1,2),h(4,5),h(1,3),h(2,3),h(1,4),h(3,4),h(2,5),h(2,3),h(4,5),t.length>1?l(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",o("ptr1"),"\n","pivot2[pivot_ptr]=",o("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",o("ptr0"),"\n","y=",o("ptr2"),"\n","z=",o("ptr4"),"\n",s("ptr5","x"),"\n",s("ptr6","y"),"\n",s("ptr7","z")].join("")):_.push(["pivot1=",o(a("el2")),"\n","pivot2=",o(a("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",o(a("el1")),"\n","y=",o(a("el3")),"\n","z=",o(a("el5")),"\n",s(a("index1"),"x"),"\n",s(a("index3"),"y"),"\n",s(a("index5"),"z")].join("")),d("index2","left"),d("index4","right"),_.push("if(pivots_are_equal){"),_.push("for(k=less;k<=great;++k){"),p("comp","k",1),_.push("if(comp===0){continue}"),_.push("if(comp<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),_.push("while(true){"),p("comp","great",1),_.push("if(comp>0){"),_.push("great--"),_.push("}else if(comp<0){"),v("k","less","great"),_.push("break"),_.push("}else{"),m("k","great"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}else{"),_.push("for(k=less;k<=great;++k){"),p("comp_pivot1","k",1),_.push("if(comp_pivot1<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),p("comp_pivot2","k",2),_.push("if(comp_pivot2>0){"),_.push("while(true){"),p("comp","great",2),_.push("if(comp>0){"),_.push("if(--greatindex5){"),x("less",1,"++less"),x("great",2,"--great"),_.push("for(k=less;k<=great;++k){"),p("comp_pivot1","k",1),_.push("if(comp_pivot1===0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),p("comp_pivot2","k",2),_.push("if(comp_pivot2===0){"),_.push("while(true){"),p("comp","great",2),_.push("if(comp===0){"),_.push("if(--great1&&A){var S=new Function("insertionSort","malloc","free",_.join("\n"));return S(r,A[0],A[1])}var S=new Function("insertionSort",_.join("\n"));return S(r)}function s(t,e){var r=["'use strict'"],n=["ndarraySortWrapper",t.join("d"),e].join(""),s=["array"];r.push(["function ",n,"(",s.join(","),"){"].join(""));for(var l=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"],u=0;u0?l.push(["d",v,"=s",v,"-d",p,"*n",p].join("")):l.push(["d",v,"=s",v].join("")),p=v);var d=t.length-1-u;0!==d&&(g>0?l.push(["e",d,"=s",d,"-e",g,"*n",g,",f",d,"=",f[d],"-f",g,"*n",g].join("")):l.push(["e",d,"=s",d,",f",d,"=",f[d]].join("")),g=d)}r.push("var "+l.join(","));var m=["0","n0-1","data","offset"].concat(i(t.length));r.push(["if(n0<=",c,"){","insertionSort(",m.join(","),")}else{","quickSort(",m.join(","),")}"].join("")),r.push("}return "+n);var y=new Function("insertionSort","quickSort",r.join("\n")),b=a(t,e),x=o(t,e,b);return y(b,x)}var l=t("typedarray-pool"),c=32;e.exports=s},{"typedarray-pool":278}],158:[function(t,e,r){"use strict";function n(t){var e=t.order,r=t.dtype,n=[e,r],o=n.join(":"),s=a[o];return s||(a[o]=s=i(e,r)),s(t),t}var i=t("./lib/compile_sort.js"),a={};e.exports=n},{"./lib/compile_sort.js":157}],159:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[0,0,0,1,1,0,1,1]),i=o(e,s.boxVert,s.lineFrag);return new n(t,r,i)}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawBox=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o){var s=this.plot,l=this.shader,c=s.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,l.uniforms.lo=t,l.uniforms.hi=e,l.uniforms.color=o,c.drawArrays(c.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],160:[function(t,e,r){"use strict";function n(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function i(t,e){return t-e}function a(t){var e=t.gl,r=o(e),i=s(e,c.gridVert,c.gridFrag),a=s(e,c.tickVert,c.gridFrag),l=new n(t,r,i,a);return l}e.exports=a;var o=t("gl-buffer"),s=t("gl-shader"),l=t("binary-search-bounds"),c=t("./shaders"),u=n.prototype;u.draw=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){for(var n=this.plot,i=this.vbo,a=this.shader,o=this.ticks,s=n.gl,l=n._tickBounds,c=n.dataBox,u=n.viewBox,f=n.gridLineWidth,h=n.gridLineColor,d=n.gridLineEnable,p=n.pixelRatio,g=0;2>g;++g){var v=l[g],m=l[g+2],y=m-v,b=.5*(c[g+2]+c[g]),x=c[g+2]-c[g];e[g]=2*y/x,t[g]=2*(v-b)/x}a.bind(),i.bind(),a.attributes.dataCoord.pointer(),a.uniforms.dataShift=t,a.uniforms.dataScale=e;for(var _=0,g=0;2>g;++g){r[0]=r[1]=0,r[g]=1,a.uniforms.dataAxis=r,a.uniforms.lineWidth=f[g]/(u[g+2]-u[g])*p,a.uniforms.color=h[g];var w=6*o[g].length;d[g]&&w&&s.drawArrays(s.TRIANGLES,_,w),_+=w}}}(),u.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],o=[0,0];return function(){for(var s=this.plot,c=this.vbo,u=this.tickShader,f=this.ticks,h=s.gl,d=s._tickBounds,p=s.dataBox,g=s.viewBox,v=s.pixelRatio,m=s.screenBox,y=m[2]-m[0],b=m[3]-m[1],x=g[2]-g[0],_=g[3]-g[1],w=0;2>w;++w){var k=d[w],A=d[w+2],M=A-k,T=.5*(p[w+2]+p[w]),E=p[w+2]-p[w];e[w]=2*M/E,t[w]=2*(k-T)/E}e[0]*=x/y,t[0]*=x/y,e[1]*=_/b,t[1]*=_/b,u.bind(),c.bind(),u.attributes.dataCoord.pointer();var L=u.uniforms;L.dataShift=t,L.dataScale=e;var S=s.tickMarkLength,C=s.tickMarkWidth,z=s.tickMarkColor,P=0,R=6*f[0].length,O=Math.min(l.ge(f[0],(p[0]-d[0])/(d[2]-d[0]),i),f[0].length),I=Math.min(l.gt(f[0],(p[2]-d[0])/(d[2]-d[0]),i),f[0].length),N=P+6*O,j=6*Math.max(0,I-O),F=Math.min(l.ge(f[1],(p[1]-d[1])/(d[3]-d[1]),i),f[1].length),D=Math.min(l.gt(f[1],(p[3]-d[1])/(d[3]-d[1]),i),f[1].length),B=R+6*F,U=6*Math.max(0,D-F);a[0]=2*(g[0]-S[1])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[1]*v/y,o[1]=C[1]*v/b,U&&(L.color=z[1],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[1]-S[0])/b-1,o[0]=C[0]*v/y,o[1]=S[0]*v/b,j&&(L.color=z[0],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,N,j)),a[0]=2*(g[2]+S[3])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[3]*v/y,o[1]=C[3]*v/b,U&&(L.color=z[3],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,h.drawArrays(h.TRIANGLES,B,U)),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[3]+S[2])/b-1,o[0]=C[2]*v/y,o[1]=S[2]*v/b,j&&(L.color=z[2],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,h.drawArrays(h.TRIANGLES,N,j))}}(),u.update=function(){var t=[1,1,-1,-1,1,-1],e=[1,-1,1,1,-1,-1];return function(r){for(var n=r.ticks,i=r.bounds,a=new Float32Array(18*(n[0].length+n[1].length)),o=(this.plot.zeroLineEnable,0),s=[[],[]],l=0;2>l;++l)for(var c=s[l],u=n[l],f=i[l],h=i[l+2],d=0;dg;++g)a[o++]=p,a[o++]=t[g],a[o++]=e[g]}this.ticks=s,this.vbo.update(a)}}(),u.dispose=function(){this.vbo.dispose(),this.shader.dispose(),this.tickShader.dispose()}},{"./shaders":162,"binary-search-bounds":164,"gl-buffer":118,"gl-shader":197}],161:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[-1,-1,-1,1,1,-1,1,1]),i=o(e,s.lineVert,s.lineFrag),l=new n(t,r,i);return l}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawLine=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o,s){var l=this.plot,c=this.shader,u=l.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,c.uniforms.start=t,c.uniforms.end=e,c.uniforms.width=o*l.pixelRatio,c.uniforms.color=s,u.drawArrays(u.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":162,"gl-buffer":118,"gl-shader":197}],162:[function(t,e,r){"use strict";var n="precision lowp float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n";e.exports={lineVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n vec2 delta = normalize(perp(start - end));\n vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n",lineFrag:n,textVert:"#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n float dataOffset = textCoordinate.z;\n vec2 glyphOffset = textCoordinate.xy;\n mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n glyphMatrix * glyphOffset * textScale + screenOffset;\n gl_Position = vec4(screenCoordinate, 0, 1);\n}\n",textFrag:n,gridVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n gl_Position = vec4(pos, 0, 1);\n}\n",gridFrag:n,boxVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n",tickVert:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"}},{}],163:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r,this.tickOffset=[[],[]],this.tickX=[[],[]],this.labelOffset=[0,0],this.labelCount=[0,0]}function i(t){var e=t.gl,r=a(e),i=o(e,c.textVert,c.textFrag),s=new n(t,r,i);return s}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("text-cache"),l=t("binary-search-bounds"),c=t("./shaders"),u=n.prototype;u.drawTicks=function(){var t=[0,0],e=[0,0],r=[0,0];return function(n){var i=this.plot,a=this.shader,o=this.tickX[n],s=this.tickOffset[n],c=i.gl,u=i.viewBox,f=i.dataBox,h=i.screenBox,d=i.pixelRatio,p=i.tickEnable,g=i.tickPad,v=i.tickColor,m=i.tickAngle,y=(i.tickMarkLength,i.labelEnable),b=i.labelPad,x=i.labelColor,_=i.labelAngle,w=this.labelOffset[n],k=this.labelCount[n],A=l.lt(o,f[n]),M=l.le(o,f[n+2]);t[0]=t[1]=0,t[n]=1,e[n]=(u[2+n]+u[n])/(h[2+n]-h[n])-1;var T=2/h[2+(1^n)]-h[1^n];e[1^n]=T*u[1^n]-1,p[n]&&(e[1^n]-=T*d*g[n],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n],a.uniforms.angle=m[n],c.drawArrays(c.TRIANGLES,s[A],s[M]-s[A]))),y[n]&&k&&(e[1^n]-=T*d*b[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=_[n],c.drawArrays(c.TRIANGLES,w,k)),e[1^n]=T*u[2+(1^n)]-1,p[n+2]&&(e[1^n]+=T*d*g[n+2],M>A&&s[M]>s[A]&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n+2],a.uniforms.angle=m[n+2],c.drawArrays(c.TRIANGLES,s[A],s[M]-s[A]))),y[n+2]&&k&&(e[1^n]+=T*d*b[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=_[n+2],c.drawArrays(c.TRIANGLES,w,k))}}(),u.drawTitle=function(){var t=[0,0],e=[0,0];return function(){var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,o=r.titleCenter,c=r.pixelRatio;if(this.titleCount){for(var u=0;2>u;++u)e[u]=2*(o[u]*c-a[u])/(a[2+u]-a[u])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}}(),u.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var c=0;2>c;++c){var u=a[c],f=a[c+2],h=f-u,d=.5*(o[c+2]+o[c]),p=o[c+2]-o[c],g=l[c],v=l[c+2],m=v-g,y=s[c],b=s[c+2],x=b-y;e[c]=2*h/p*m/x,t[c]=2*(u-d)/p*m/x}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),u.update=function(t){for(var e=[],r=t.ticks,n=t.bounds,i=0;2>i;++i){for(var a=[Math.floor(e.length/3)],o=[-(1/0)],l=r[i],c=0;ci;++i){this.labelOffset[i]=Math.floor(e.length/3);for(var g=s(t.labelFont[i],t.labels[i]).data,p=t.labelSize[i],c=0;cp;++p)if(f[p]&&n[p]<=0&&n[p+2]>=0){var g=e[p]-n[p]*(e[p+2]-e[p])/(n[p+2]-n[p]);0===p?o.drawLine(g,e[1],g,e[3],d[p],h[p]):o.drawLine(e[0],g,e[2],g,d[p],h[p])}}for(var p=0;pp;++p)s.drawTicks(p);this.titleEnable&&s.drawTitle();for(var b=this.overlays,p=0;pc;++c){var u=s[c].slice(0);0!==u.length&&(u.sort(a),l[c]=Math.min(l[c],u[0].x),l[c+2]=Math.max(l[c+2],u[u.length-1].x))}this.grid.update({bounds:l,ticks:s}),this.text.update({bounds:l,ticks:s,labels:t.labels||["x","y"],labelSize:t.labelSize||[12,12],labelFont:t.labelFont||["sans-serif","sans-serif"],title:t.title||"",titleSize:t.titleSize||18,titleFont:t.titleFont||"sans-serif"}),this.setDirty()},h.dispose=function(){this.box.dispose(),this.grid.dispose(),this.text.dispose(),this.line.dispose();for(var t=this.objects.length-1;t>=0;--t)this.objects[t].dispose();this.objects.length=0;for(var t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},h.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},h.removeObject=function(t){for(var e=this.objects,r=0;rh;++h)o=o&&l[h]===s[h],l[h]=s[h];var d=t.clientWidth===u&&t.clientHeight===f;return u=t.clientWidth,f=t.clientHeight,o?!d:(c=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){return n.setMode(t),n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return c},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var d=0,p=0;return o(t,function(e,r,a,o){var s=1/t.clientHeight,l=s*(r-d),u=s*(a-p),f=h.flipX?1:-1,g=h.flipY?1:-1,v=Math.PI*h.rotateSpeed,m=i();if(1&e)o.shift?n.rotate(m,0,0,-l*v):n.rotate(m,f*v*l,-g*v*u,0);else if(2&e)n.pan(m,-h.translateSpeed*l*c,h.translateSpeed*u*c,0);else if(4&e){var y=h.zoomSpeed*u/window.innerHeight*(m-n.lastT())*50;n.pan(m,0,0,c*(Math.exp(y)-1))}d=r,p=a}),s(t,function(t,e,r){var a=h.flipX?1:-1,o=h.flipY?1:-1,s=i();if(Math.abs(t)>Math.abs(e))n.rotate(s,0,0,-t*a*Math.PI*h.rotateSpeed/window.innerWidth);else{var l=h.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,c*(Math.exp(l)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],168:[function(t,e,r){!function(){"use strict";function t(e){e.permitHostObjects___&&e.permitHostObjects___(t)}function r(t){return!(t.substr(0,d.length)==d&&"___"===t.substr(t.length-3))}function n(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[p];if(e&&e.key===t)return e;if(h(t)){e={key:t};try{return f(t,p,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(r){return}}}function i(t){return t.prototype=null,Object.freeze(t)}function a(){y||"undefined"==typeof console||(y=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}if("undefined"==typeof ses||!ses.ok||ses.ok()){"undefined"!=typeof ses&&(ses.weakMapPermitHostObjects=t);var o=!1;if("function"==typeof WeakMap){var s=WeakMap;if("undefined"!=typeof navigator&&/Firefox/.test(navigator.userAgent));else{var l=new s,c=Object.freeze({});if(l.set(c,1),1===l.get(c))return void(e.exports=WeakMap);o=!0}}var u=(Object.prototype.hasOwnProperty,Object.getOwnPropertyNames),f=Object.defineProperty,h=Object.isExtensible,d="weakmap:",p=d+"ident:"+Math.random()+"___";if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof ArrayBuffer&&"function"==typeof Uint8Array){var g=new ArrayBuffer(25),v=new Uint8Array(g);crypto.getRandomValues(v),p=d+"rand:"+Array.prototype.map.call(v,function(t){return(t%36).toString(36)}).join("")+"___"}if(f(Object,"getOwnPropertyNames",{value:function(t){return u(t).filter(r)}}),"getPropertyNames"in Object){var m=Object.getPropertyNames;f(Object,"getPropertyNames",{value:function(t){return m(t).filter(r)}})}!function(){var t=Object.freeze;f(Object,"freeze",{value:function(e){return n(e),t(e)}});var e=Object.seal;f(Object,"seal",{value:function(t){return n(t),e(t)}});var r=Object.preventExtensions;f(Object,"preventExtensions",{value:function(t){return n(t),r(t)}})}();var y=!1,b=0,x=function(){function t(t,e){var r,i=n(t);return i?c in i?i[c]:e:(r=s.indexOf(t),r>=0?l[r]:e)}function e(t){var e=n(t);return e?c in e:s.indexOf(t)>=0}function r(t,e){var r,i=n(t);return i?i[c]=e:(r=s.indexOf(t),r>=0?l[r]=e:(r=s.length,l[r]=e,s[r]=t)),this}function o(t){var e,r,i=n(t);return i?c in i&&delete i[c]:(e=s.indexOf(t),0>e?!1:(r=s.length-1,s[e]=void 0,l[e]=l[r],s[e]=s[r],s.length=r,l.length=r,!0))}this instanceof x||a();var s=[],l=[],c=b++;return Object.create(x.prototype,{get___:{value:i(t)},has___:{value:i(e)},set___:{value:i(r)},delete___:{value:i(o)}})};x.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},"delete":{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof s?!function(){function r(){function e(t,e){return u?c.has(t)?c.get(t):u.get___(t,e):c.get(t,e)}function r(t){return c.has(t)||(u?u.has___(t):!1)}function n(t){var e=!!c.delete(t);return u?u.delete___(t)||e:e}this instanceof x||a();var l,c=new s,u=void 0,f=!1;return l=o?function(t,e){return c.set(t,e),c.has(t)||(u||(u=new x),u.set(t,e)),this}:function(t,e){if(f)try{c.set(t,e)}catch(r){u||(u=new x),u.set___(t,e)}else c.set(t,e);return this},Object.create(x.prototype,{get___:{value:i(e)},has___:{value:i(r)},set___:{value:i(l)},delete___:{value:i(n)},permitHostObjects___:{value:i(function(e){if(e!==t)throw new Error("bogus call to permitHostObjects___");f=!0})}})}o&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=x.prototype,e.exports=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=x)}}()},{}],169:[function(t,e,r){"use strict";function n(t){var e=s.get(t);if(!e||!t.isBuffer(e._triangleBuffer.buffer)){var r=a(t,new Float32Array([-1,-1,-1,4,4,-1]));e=o(t,[{buffer:r,type:t.FLOAT,size:2}]),e._triangleBuffer=r,s.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}var i="undefined"==typeof WeakMap?t("weak-map"):WeakMap,a=t("gl-buffer"),o=t("gl-vao"),s=new i;e.exports=n},{"gl-buffer":118,"gl-vao":226,"weak-map":168}],170:[function(t,e,r){"use strict";function n(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function i(t){this.gl=t,this.pixelRatio=1,this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.autoTicks=!0,this.tickSpacing=[1,1,1],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[10,10,10],this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]},this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont="sans-serif",this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[10,10,10],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[0,0,0],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!1,!1,!1],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._firstInit=!0,this._text=null,this._lines=null,this._background=u(t)}function a(){this.primalOffset=[0,0,0],this.primalMinor=[0,0,0],this.mirrorOffset=[0,0,0],this.mirrorMinor=[0,0,0]}function o(t,e,r,n,i){for(var a=t.primalOffset,o=t.primalMinor,s=t.mirrorOffset,l=t.mirrorMinor,c=n[e],u=0;3>u;++u)if(e!==u){var f=a,h=s,d=o,p=l;c&1<0?(d[u]=-1,p[u]=0):(d[u]=0,p[u]=1)}}function s(t,e){var r=new i(t);return r.update(e),r}e.exports=s;var l=t("./lib/text.js"),c=t("./lib/lines.js"),u=t("./lib/background.js"),f=t("./lib/cube.js"),h=t("./lib/ticks.js"),d=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),p=i.prototype;p.update=function(t){function e(e,r,n){if(n in t){var i,a=t[n],o=this[n];(e?Array.isArray(a)&&Array.isArray(a[0]):Array.isArray(a))?this[n]=i=[r(a[0]),r(a[1]),r(a[2])]:this[n]=i=[r(a),r(a),r(a)];for(var s=0;3>s;++s)if(i[s]!==o[s])return!0}return!1}t=t||{};var r,n=e.bind(this,!1,Number),i=e.bind(this,!1,Boolean),a=e.bind(this,!1,String),o=e.bind(this,!0,function(t){if(Array.isArray(t)){if(3===t.length)return[+t[0],+t[1],+t[2],1];if(4===t.length)return[+t[0],+t[1],+t[2],+t[3]]}return[0,0,0,1]}),s=!1,u=!1;if("bounds"in t)for(var f=t.bounds,d=0;2>d;++d)for(var p=0;3>p;++p)f[d][p]!==this.bounds[d][p]&&(u=!0),this.bounds[d][p]=f[d][p];if("ticks"in t){r=t.ticks,s=!0,this.autoTicks=!1;for(var d=0;3>d;++d)this.tickSpacing[d]=0}else n("tickSpacing")&&(this.autoTicks=!0,u=!0);if(this._firstInit&&("ticks"in t||"tickSpacing"in t||(this.autoTicks=!0),u=!0,s=!0,this._firstInit=!1),u&&this.autoTicks&&(r=h.create(this.bounds,this.tickSpacing),s=!0),s){for(var d=0;3>d;++d)r[d].sort(function(t,e){return t.x-e.x});h.equal(r,this.ticks)?s=!1:this.ticks=r}i("tickEnable"),a("tickFont")&&(s=!0),n("tickSize"),n("tickAngle"),n("tickPad"),o("tickColor");var g=a("labels");a("labelFont")&&(g=!0),i("labelEnable"),n("labelSize"),n("labelPad"),o("labelColor"),i("lineEnable"),i("lineMirror"),n("lineWidth"),o("lineColor"),i("lineTickEnable"),i("lineTickMirror"),n("lineTickLength"),n("lineTickWidth"),o("lineTickColor"),i("gridEnable"),n("gridWidth"),o("gridColor"),i("zeroEnable"),o("zeroLineColor"),n("zeroLineWidth"),i("backgroundEnable"),o("backgroundColor"),this._text?this._text&&(g||s)&&this._text.update(this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont):this._text=l(this.gl,this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont),this._lines&&s&&(this._lines.dispose(),this._lines=null),this._lines||(this._lines=c(this.gl,this.bounds,this.ticks))};var g=[new a,new a,new a],v=[0,0,0],m={model:d,view:d,projection:d};p.isOpaque=function(){return!0},p.isTransparent=function(){return!1},p.drawTransparent=function(t){};var y=[0,0,0],b=[0,0,0],x=[0,0,0];p.draw=function(t){t=t||m;for(var e=this.gl,r=t.model||d,i=t.view||d,a=t.projection||d,s=this.bounds,l=f(r,i,a,s),c=l.cubeEdges,u=l.axis,h=i[12],p=i[13],_=i[14],w=i[15],k=this.pixelRatio*(a[3]*h+a[7]*p+a[11]*_+a[15]*w)/e.drawingBufferHeight,A=0;3>A;++A)this.lastCubeProps.cubeEdges[A]=c[A],this.lastCubeProps.axis[A]=u[A];for(var M=g,A=0;3>A;++A)o(g[A],A,this.bounds,c,u);for(var e=this.gl,T=v,A=0;3>A;++A)this.backgroundEnable[A]?T[A]=u[A]:T[A]=0;this._background.draw(r,i,a,s,T,this.backgroundColor),this._lines.bind(r,i,a,this);for(var A=0;3>A;++A){var E=[0,0,0];u[A]>0?E[A]=s[1][A]:E[A]=s[0][A];for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.gridEnable[S]&&this._lines.drawGrid(S,C,this.bounds,E,this.gridColor[S],this.gridWidth[S]*this.pixelRatio)}for(var L=0;2>L;++L){var S=(A+1+L)%3,C=(A+1+(1^L))%3;this.zeroEnable[C]&&s[0][C]<=0&&s[1][C]>=0&&this._lines.drawZero(S,C,this.bounds,E,this.zeroLineColor[C],this.zeroLineWidth[C]*this.pixelRatio)}}for(var A=0;3>A;++A){this.lineEnable[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].primalOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio),this.lineMirror[A]&&this._lines.drawAxisLine(A,this.bounds,M[A].mirrorOffset,this.lineColor[A],this.lineWidth[A]*this.pixelRatio);for(var z=n(y,M[A].primalMinor),P=n(b,M[A].mirrorMinor),R=this.lineTickLength,L=0;3>L;++L){var O=k/r[5*L];z[L]*=R[L]*O,P[L]*=R[L]*O}this.lineTickEnable[A]&&this._lines.drawAxisTicks(A,M[A].primalOffset,z,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio),this.lineTickMirror[A]&&this._lines.drawAxisTicks(A,M[A].mirrorOffset,P,this.lineTickColor[A],this.lineTickWidth[A]*this.pixelRatio)}this._text.bind(r,i,a,this.pixelRatio);for(var A=0;3>A;++A){for(var I=M[A].primalMinor,N=n(x,M[A].primalOffset),L=0;3>L;++L)this.lineTickEnable[A]&&(N[L]+=k*I[L]*Math.max(this.lineTickLength[L],0)/r[5*L]);if(this.tickEnable[A]){for(var L=0;3>L;++L)N[L]+=k*I[L]*this.tickPad[L]/r[5*L];this._text.drawTicks(A,this.tickSize[A],this.tickAngle[A],N,this.tickColor[A])}if(this.labelEnable[A]){for(var L=0;3>L;++L)N[L]+=k*I[L]*this.labelPad[L]/r[5*L];N[A]+=.5*(s[0][A]+s[1][A]),this._text.drawLabel(A,this.labelSize[A],this.labelAngle[A],N,this.labelColor[A])}}},p.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":171,"./lib/cube.js":172,"./lib/lines.js":173,"./lib/text.js":175,"./lib/ticks.js":176}],171:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}function i(t){for(var e=[],r=[],i=0,l=0;3>l;++l)for(var c=(l+1)%3,u=(l+2)%3,f=[0,0,0],h=[0,0,0],d=-1;1>=d;d+=2){r.push(i,i+2,i+1,i+1,i+2,i+3),f[l]=d,h[l]=d;for(var p=-1;1>=p;p+=2){f[c]=p;for(var g=-1;1>=g;g+=2)f[u]=g,e.push(f[0],f[1],f[2],h[0],h[1],h[2]),i+=1}var v=c;c=u,u=v}var m=a(t,new Float32Array(e)),y=a(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),b=o(t,[{buffer:m,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:m,type:t.FLOAT,size:3,offset:12,stride:24}],y),x=s(t);return x.attributes.position.location=0,x.attributes.normal.location=1,new n(t,m,b,x)}e.exports=i;var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders").bg,l=n.prototype;l.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;3>s;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),l.disable(l.POLYGON_OFFSET_FILL)}},l.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":174,"gl-buffer":118,"gl-vao":226}],172:[function(t,e,r){"use strict";function n(t,e,r){for(var n=0;4>n;++n){t[n]=r[12+n];for(var i=0;3>i;++i)t[n]+=e[i]*r[4*i+n]}}function i(t){for(var e=0;eg;++g){d[2]=a[g][2];for(var b=0;2>b;++b){d[1]=a[b][1];for(var x=0;2>x;++x)d[0]=a[x][0],n(f[l],d,u),l+=1}}for(var _=-1,g=0;8>g;++g){for(var w=f[g][3],k=0;3>k;++k)h[g][k]=f[g][k]/w;0>w&&(0>_?_=g:h[g][2]_){_=0;for(var A=0;3>A;++A){for(var M=(A+2)%3,T=(A+1)%3,E=-1,L=-1,S=0;2>S;++S){var C=S<E||0>L)L>E&&(_|=1<S;++S){var C=S<E&&(_|=1<g;++g)g!==_&&g!==O&&(0>I?I=g:h[I][1]>h[g][1]&&(I=g));for(var N=-1,g=0;3>g;++g){var j=I^1<N&&(N=j);var T=h[j];T[0]g;++g){var j=I^1<F&&(F=j);var T=h[j];T[0]>h[F][0]&&(F=j)}}var D=v;D[0]=D[1]=D[2]=0,D[o.log2(N^I)]=I&N,D[o.log2(I^F)]=I&F;var B=7^F;B===_||B===O?(B=7^N,D[o.log2(F^B)]=B&F):D[o.log2(N^B)]=B&N;for(var U=m,V=_,A=0;3>A;++A)V&1<t;++t)f[t]=[1,1,1,1],h[t]=[1,1,1]}();var g=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]],v=[1,1,1],m=[0,0,0],y={cubeEdges:v,axis:m}},{"bit-twiddle":50,"gl-mat4/invert":137,"gl-mat4/multiply":139,"robust-orientation":259,"split-polygon":178}],173:[function(t,e,r){"use strict";function n(t){return t[0]=t[1]=t[2]=0,t}function i(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function a(t,e,r,n,i,a,o,s){this.gl=t,this.vertBuffer=e,this.vao=r,this.shader=n,this.tickCount=i,this.tickOffset=a,this.gridCount=o,this.gridOffset=s}function o(t,e,r){var n=[],i=[0,0,0],o=[0,0,0],u=[0,0,0],f=[0,0,0];n.push(0,0,1,0,1,1,0,0,-1,0,0,-1,0,1,1,0,1,-1);for(var h=0;3>h;++h){for(var d=n.length/3|0,p=0;ph;++h)for(var p=u[h],g=2;g>=0;--g){var v=c[p[g]];s.push(l*v[0],-l*v[1],t)}}for(var s=(this.gl,[]),l=[0,0,0],c=[0,0,0],u=[0,0,0],d=[0,0,0],p=0;3>p;++p){u[p]=s.length/h|0,o(.5*(t[0][p]+t[1][p]),e[p],r),d[p]=(s.length/h|0)-u[p],l[p]=s.length/h|0;for(var g=0;g=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,c=o%a;0>o?(l=0|-Math.ceil(l),c=0|-c):(l=0|Math.floor(l),c=0|c);var u=""+l;if(0>o&&(u="-"+u),i){for(var f=""+c;f.lengthi;++i){for(var a=[],o=(.5*(t[0][i]+t[1][i]),0);o*e[i]<=t[1][i];++o)a.push({x:o*e[i],text:n(e[i],o)});for(var o=-1;o*e[i]>=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r}function a(t,e){for(var r=0;3>r;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;na?a=0:a>1&&(a=1);for(var o=1-a,s=t.length,l=new Array(s),c=0;s>c;++c)l[c]=a*t[c]+o*r[c];return l}function a(t,e){for(var r=[],a=[],o=n(t[t.length-1],e),s=t[t.length-1],l=t[0],c=0;co&&u>0||o>0&&0>u){var f=i(s,u,l,o);r.push(f),a.push(f.slice())}0>u?a.push(l.slice()):u>0?r.push(l.slice()):(r.push(l.slice()),a.push(l.slice())),o=u}return{positive:r,negative:a}}function o(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&c>0||a>0&&0>c)&&r.push(i(o,c,s,a)),c>=0&&r.push(s.slice()),a=c}return r}function s(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;la&&c>0||a>0&&0>c)&&r.push(i(o,c,s,a)),0>=c&&r.push(s.slice()),a=c}return r}var l=t("robust-dot-product"),c=t("robust-sum");e.exports=a,e.exports.positive=o,e.exports.negative=s},{"robust-dot-product":179,"robust-sum":262}],179:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t[0],e[0]),n=1;na;++a){for(var o=p,s=g,l=0;3>l;++l)s[l]=o[l]=r[l];s[3]=o[3]=1,s[a]+=1,f(s,s,e),s[3]<0&&(t[a]=1/0),o[a]-=1,f(o,o,e),o[3]<0&&(t[a]=1/0);var c=(o[0]/o[3]-s[0]/s[3])*n,u=(o[1]/o[3]-s[1]/s[3])*i;t[a]=.25*Math.sqrt(c*c+u*u)}return t}function a(t,e,r,n,a){var f=e.model||h,p=e.view||h,g=e.projection||h,y=t.bounds,a=a||l(f,p,g,y),b=a.axis;a.edges;c(d,p,f),c(d,g,d);for(var x=v,_=0;3>_;++_)x[_].lo=1/0,x[_].hi=-(1/0),x[_].pixelsPerDataUnit=1/0;var w=o(u(d,d));u(d,d);for(var k=0;3>k;++k){var A=(k+1)%3,M=(k+2)%3,T=m;t:for(var _=0;2>_;++_){var E=[];if(b[k]<0!=!!_){T[k]=y[_][k];for(var L=0;2>L;++L){T[A]=y[L^_][A];for(var S=0;2>S;++S)T[M]=y[S^L^_][M],E.push(T.slice())}for(var L=0;LS;++S)x[S].lo=Math.min(x[S].lo,M[S]),x[S].hi=Math.max(x[S].hi,M[S]),S!==k&&(x[S].pixelsPerDataUnit=Math.min(x[S].pixelsPerDataUnit,Math.abs(C[S])))}}}return x}e.exports=a;var o=t("extract-frustum-planes"),s=t("split-polygon"),l=t("./lib/cube.js"),c=t("gl-mat4/multiply"),u=t("gl-mat4/transpose"),f=t("gl-vec4/transformMat4"),h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),d=new Float32Array(16),p=[0,0,0,1],g=[0,0,0,1],v=[new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0)],m=[0,0,0]},{"./lib/cube.js":172,"extract-frustum-planes":177,"gl-mat4/multiply":139,"gl-mat4/transpose":147,"gl-vec4/transformMat4":227,"split-polygon":178}],181:[function(t,e,r){"use strict";var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n vec3 vertexPosition = mix(coordinates[0],\n mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n vec2 delta = weight * clipOffset * screenShape;\n vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n gl_Position = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n fragColor = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n gl_FragColor = fragColor;\n}"; +e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"},{name:"color",type:"vec3"},{name:"weight",type:"float"}])}},{"gl-shader":197}],182:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n,this.pixelRatio=1,this.bounds=[[-1e3,-1e3,-1e3],[1e3,1e3,1e3]],this.position=[0,0,0],this.lineWidth=[2,2,2],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.enabled=[!0,!0,!0],this.drawSides=[!0,!0,!0],this.axes=null}function i(t,e){function r(t,e,r,n,a,o){var s=[t,e,r,0,0,0,1];s[n+3]=1,s[n]=a,i.push.apply(i,s),s[6]=-1,i.push.apply(i,s),s[n]=o,i.push.apply(i,s),i.push.apply(i,s),s[6]=1,i.push.apply(i,s),s[n]=a,i.push.apply(i,s)}var i=[];r(0,0,0,0,0,1),r(0,0,0,1,0,1),r(0,0,0,2,0,1),r(1,0,0,1,-1,1),r(1,0,0,2,-1,1),r(0,1,0,0,-1,1),r(0,1,0,2,-1,1),r(0,0,1,0,-1,1),r(0,0,1,1,-1,1);var l=a(t,i),c=o(t,[{type:t.FLOAT,buffer:l,size:3,offset:0,stride:28},{type:t.FLOAT,buffer:l,size:3,offset:12,stride:28},{type:t.FLOAT,buffer:l,size:1,offset:24,stride:28}]),u=s(t);u.attributes.position.location=0,u.attributes.color.location=1,u.attributes.weight.location=2;var f=new n(t,l,c,u);return f.update(e),f}var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders/index");e.exports=i;var l=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],c=n.prototype,u=[0,0,0],f=[0,0,0],h=[0,0];c.isTransparent=function(){return!1},c.drawTransparent=function(t){},c.draw=function(t){var e=this.gl,r=this.vao,n=this.shader;r.bind(),n.bind();var i,a=t.model||l,o=t.view||l,s=t.projection||l;this.axes&&(i=this.axes.lastCubeProps.axis);for(var c=u,d=f,p=0;3>p;++p)i&&i[p]<0?(c[p]=this.bounds[0][p],d[p]=this.bounds[1][p]):(c[p]=this.bounds[1][p],d[p]=this.bounds[0][p]);h[0]=e.drawingBufferWidth,h[1]=e.drawingBufferHeight,n.uniforms.model=a,n.uniforms.view=o,n.uniforms.projection=s,n.uniforms.coordinates=[this.position,c,d],n.uniforms.colors=this.colors,n.uniforms.screenShape=h;for(var p=0;3>p;++p)n.uniforms.lineWidth=this.lineWidth[p]*this.pixelRatio,this.enabled[p]&&(r.draw(e.TRIANGLES,6,6*p),this.drawSides[p]&&r.draw(e.TRIANGLES,12,18+12*p));r.unbind()},c.update=function(t){t&&("bounds"in t&&(this.bounds=t.bounds),"position"in t&&(this.position=t.position),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"colors"in t&&(this.colors=t.colors),"enabled"in t&&(this.enabled=t.enabled),"drawSides"in t&&(this.drawSides=t.drawSides))},c.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders/index":181,"gl-buffer":118,"gl-vao":226}],183:[function(t,e,r){"use strict";function n(){this.mouse=[-1,-1],this.screen=null,this.distance=1/0,this.index=null,this.dataCoordinate=null,this.dataPosition=null,this.object=null,this.data=null}function i(t,e){var r=null;try{r=t.getContext("webgl",e),r||(r=t.getContext("experimental-webgl",e))}catch(n){return null}return r}function a(t){var e=Math.round(Math.log(Math.abs(t))/Math.log(10));if(0>e){var r=Math.round(Math.pow(10,-e));return Math.ceil(t*r)/r}if(e>0){var r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function o(t){return"boolean"==typeof t?t:!0}function s(t){function e(){if(!_&&H.autoResize){var t=w.parentNode,e=1,r=1;t&&t!==document.body?(e=t.clientWidth,r=t.clientHeight):(e=window.innerWidth,r=window.innerHeight);var n=0|Math.ceil(e*H.pixelRatio),i=0|Math.ceil(r*H.pixelRatio);if(n!==w.width||i!==w.height){w.width=n,w.height=i;var a=w.style;a.position=a.position||"absolute",a.left="0px",a.top="0px",a.width=e+"px",a.height=r+"px",F=!0}}}function r(){for(var t=O.length,e=j.length,r=0;e>r;++r)N[r]=0;t:for(var r=0;t>r;++r){var n=O[r],i=n.pickSlots;if(i){for(var a=0;e>a;++a)if(N[a]+i<255){I[r]=a,n.setPickBase(N[a]+1),N[a]+=i;continue t}var o=h(A,q);I[r]=e,j.push(o),N.push(i),n.setPickBase(1),e+=1}else I[r]=-1}for(;e>0&&0===N[e-1];)N.pop(),j.pop().dispose()}function s(){return H.contextLost?!0:void(A.isContextLost()&&(H.contextLost=!0,H.mouseListener.enabled=!1,H.selection.object=null,H.oncontextloss&&H.oncontextloss()))}function y(){if(!s()){A.colorMask(!0,!0,!0,!0),A.depthMask(!0),A.disable(A.BLEND),A.enable(A.DEPTH_TEST);for(var t=O.length,e=j.length,r=0;e>r;++r){var n=j[r];n.shape=G,n.begin();for(var i=0;t>i;++i)if(I[i]===r){var a=O[i];a.drawPick&&(a.pixelRatio=1,a.drawPick(V))}n.end()}}}function b(){if(!s()){e();var t=H.camera.tick();V.view=H.camera.matrix,F=F||t,D=D||t,z.pixelRatio=H.pixelRatio,R.pixelRatio=H.pixelRatio;var r=O.length,n=W[0],i=W[1];n[0]=n[1]=n[2]=1/0,i[0]=i[1]=i[2]=-(1/0);for(var o=0;r>o;++o){var l=O[o];l.pixelRatio=H.pixelRatio,l.axes=H.axes,F=F||!!l.dirty,D=D||!!l.dirty;var c=l.bounds;if(c)for(var f=c[0],h=c[1],d=0;3>d;++d)n[d]=Math.min(n[d],f[d]),i[d]=Math.max(i[d],h[d])}var g=H.bounds;if(H.autoBounds)for(var d=0;3>d;++d){if(i[d]d;++d)b=b||Z[0][d]!==g[0][d]||Z[1][d]!==g[1][d],Z[0][d]=g[0][d],Z[1][d]=g[1][d];if(b){for(var x=[0,0,0],o=0;3>o;++o)x[o]=a((g[1][o]-g[0][o])/10);z.autoTicks?z.update({bounds:g,tickSpacing:x}):z.update({bounds:g})}D=D||b,F=F||b;var _=A.drawingBufferWidth,w=A.drawingBufferHeight;q[0]=_,q[1]=w,G[0]=0|Math.max(_/H.pixelRatio,1),G[1]=0|Math.max(w/H.pixelRatio,1),v(B,H.fovy,_/w,H.zNear,H.zFar);for(var o=0;16>o;++o)U[o]=0;U[15]=1;for(var k=0,o=0;3>o;++o)k=Math.max(k,g[1][o]-g[0][o]);for(var o=0;3>o;++o)H.autoScale?U[5*o]=H.aspect[o]/(g[1][o]-g[0][o]):U[5*o]=1/k,H.autoCenter&&(U[12+o]=.5*-U[5*o]*(g[0][o]+g[1][o]));for(var o=0;r>o;++o){var l=O[o];l.axesBounds=g,H.clipToBounds&&(l.clipBounds=g)}if(T.object&&(H.snapToData?R.position=T.dataCoordinate:R.position=T.dataPosition,R.bounds=g),D&&(D=!1,y()),F){H.axesPixels=u(H.axes,V,_,w),H.onrender&&H.onrender(),A.bindFramebuffer(A.FRAMEBUFFER,null),A.viewport(0,0,_,w);var M=H.clearColor;A.clearColor(M[0],M[1],M[2],M[3]),A.clear(A.COLOR_BUFFER_BIT|A.DEPTH_BUFFER_BIT),A.depthMask(!0),A.colorMask(!0,!0,!0,!0),A.enable(A.DEPTH_TEST),A.depthFunc(A.LEQUAL),A.disable(A.BLEND),A.disable(A.CULL_FACE);var S=!1;z.enable&&(S=S||z.isTransparent(),z.draw(V)),R.axes=z,T.object&&R.draw(V),A.disable(A.CULL_FACE);for(var o=0;r>o;++o){var l=O[o];l.axes=z,l.pixelRatio=H.pixelRatio,l.isOpaque&&l.isOpaque()&&l.draw(V),l.isTransparent&&l.isTransparent()&&(S=!0)}if(S){E.shape=q,E.bind(),A.clear(A.DEPTH_BUFFER_BIT),A.colorMask(!1,!1,!1,!1),A.depthMask(!0),A.depthFunc(A.LESS),z.enable&&z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=O[o];l.isOpaque&&l.isOpaque()&&l.draw(V)}A.enable(A.BLEND),A.blendEquation(A.FUNC_ADD),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.colorMask(!0,!0,!0,!0),A.depthMask(!1),A.clearColor(0,0,0,0),A.clear(A.COLOR_BUFFER_BIT),z.isTransparent()&&z.drawTransparent(V);for(var o=0;r>o;++o){var l=O[o];l.isTransparent&&l.isTransparent()&&l.drawTransparent(V)}A.bindFramebuffer(A.FRAMEBUFFER,null),A.blendFunc(A.ONE,A.ONE_MINUS_SRC_ALPHA),A.disable(A.DEPTH_TEST),L.bind(),E.color[0].bind(0),L.uniforms.accumBuffer=0,p(A),A.disable(A.BLEND)}F=!1;for(var o=0;r>o;++o)O[o].dirty=!1}}}function x(){_||H.contextLost||(requestAnimationFrame(x),b())}t=t||{};var _=!1,w=(t.pixelRatio||parseFloat(window.devicePixelRatio),t.canvas);if(!w)if(w=document.createElement("canvas"),t.container){var k=t.container;k.appendChild(w)}else document.body.appendChild(w);var A=t.gl;if(A||(A=i(w,t.glOptions||{premultipliedAlpha:!0,antialias:!0})),!A)throw new Error("webgl not supported");var M=t.bounds||[[-10,-10,-10],[10,10,10]],T=new n,E=d(A,[A.drawingBufferWidth,A.drawingBufferHeight],{preferFloat:!0}),L=m(A),S=t.camera||{eye:[2,0,0],center:[0,0,0],up:[0,1,0],zoomMin:.1,zoomMax:100,mode:"turntable"},C=t.axes||{},z=c(A,C);z.enable=!C.disable;var P=t.spikes||{},R=f(A,P),O=[],I=[],N=[],j=[],F=!0,D=!0,B=new Array(16),U=new Array(16),V={view:null,projection:B,model:U},D=!0,q=[A.drawingBufferWidth,A.drawingBufferHeight],H={gl:A,contextLost:!1,pixelRatio:t.pixelRatio||parseFloat(window.devicePixelRatio),canvas:w,selection:T,camera:l(w,S),axes:z,axesPixels:null,spikes:R,bounds:M,objects:O,shape:q,aspect:t.aspectRatio||[1,1,1],pickRadius:t.pickRadius||10,zNear:t.zNear||.01,zFar:t.zFar||1e3,fovy:t.fovy||Math.PI/4,clearColor:t.clearColor||[0,0,0,0],autoResize:o(t.autoResize),autoBounds:o(t.autoBounds),autoScale:!!t.autoScale,autoCenter:o(t.autoCenter),clipToBounds:o(t.clipToBounds),snapToData:!!t.snapToData,onselect:t.onselect||null,onrender:t.onrender||null,onclick:t.onclick||null,cameraParams:V,oncontextloss:null,mouseListener:null},G=[A.drawingBufferWidth/H.pixelRatio|0,A.drawingBufferHeight/H.pixelRatio|0];H.autoResize&&e(),window.addEventListener("resize",e),H.update=function(t){_||(t=t||{},F=!0,D=!0)},H.add=function(t){_||(t.axes=z,O.push(t),I.push(-1),F=!0,D=!0,r())},H.remove=function(t){if(!_){var e=O.indexOf(t);0>e||(O.splice(e,1),I.pop(),F=!0,D=!0,r())}},H.dispose=function(){if(!_&&(_=!0,window.removeEventListener("resize",e),w.removeEventListener("webglcontextlost",s),H.mouseListener.enabled=!1,!H.contextLost)){z.dispose(),R.dispose();for(var t=0;ts;++s){var l=j[s].query(e,G[1]-r-1,H.pickRadius);if(l){if(l.distance>T.distance)continue;for(var c=0;i>c;++c){var u=O[c];if(I[c]===s){var f=u.pick(l);f&&(T.buttons=t,T.screen=l.coord,T.distance=l.distance,T.object=u,T.index=f.distance,T.dataPosition=f.position,T.dataCoordinate=f.dataCoordinate,T.data=f,o=!0)}}}}}a&&a!==T.object&&(a.highlight&&a.highlight(null),F=!0),T.object&&(T.object.highlight&&T.object.highlight(T.data),F=!0),o=o||T.object!==a,o&&H.onselect&&H.onselect(T),1&t&&!(1&X)&&H.onclick&&H.onclick(T),X=t}}),w.addEventListener("webglcontextlost",s);var W=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],Z=[W[0].slice(),W[1].slice()];return x(),H.redraw=function(){_||(F=!0,b())},H}e.exports=s;var l=t("3d-view-controls"),c=t("gl-axes3d"),u=t("gl-axes3d/properties"),f=t("gl-spikes3d"),h=t("gl-select-static"),d=t("gl-fbo"),p=t("a-big-triangle"),g=t("mouse-change"),v=t("gl-mat4/perspective"),m=t("./lib/shader")},{"./lib/shader":166,"3d-view-controls":167,"a-big-triangle":169,"gl-axes3d":170,"gl-axes3d/properties":180,"gl-fbo":123,"gl-mat4/perspective":140,"gl-select-static":196,"gl-spikes3d":182,"mouse-change":241}],184:[function(t,e,r){"use strict";e.exports={vertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n fragColor = color;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",fragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n",pickVertex:"precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n vec3 xposition = view * vec3(position, 1.0);\n return vec4(\n xposition.xy + scale * offset * xposition.z,\n 0,\n xposition.z);\n}\n\n\n\n\nvoid main() {\n vec4 fragId = id + pickOffset;\n\n fragId.y += floor(fragId.x / 256.0);\n fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n fragId.z += floor(fragId.y / 256.0);\n fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n fragId.w += floor(fragId.z / 256.0);\n fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n fragColor = fragId / 255.0;\n\n gl_Position = computePosition_1_0(\n position,\n offset,\n viewTransform,\n pixelScale);\n}\n",pickFragment:"precision lowp float;\n#define GLSLIFY 1\nvarying vec4 fragColor;\nvoid main() {\n gl_FragColor = fragColor;\n}\n"}},{}],185:[function(t,e,r){"use strict";function n(t){if(t in h)return h[t];var e=u(t,{polygons:!0,font:"sans-serif",textAlign:"left",textBaseline:"alphabetic"}),r=[],n=[];e.forEach(function(t){t.forEach(function(t){for(var e=0;eo;++o)i[o]=Math.min(i[o],r[a+o]),i[2+o]=Math.max(i[2+o],r[a+o]);return h[t]={coords:r,normals:n,bounds:i}}function i(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.offsetBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.numVertices=0,this.pickOffset=0,this.points=null}function a(t,e){var r=t.gl,n=o(r,f.vertex,f.fragment),a=o(r,f.pickVertex,f.pickFragment),l=s(r),c=s(r),u=s(r),h=s(r),d=new i(t,n,a,l,c,u,h);return d.update(e),t.addObject(d),d}e.exports=a;var o=t("gl-shader"),s=t("gl-buffer"),l=t("text-cache"),c=t("typedarray-pool"),u=t("vectorize-text"),f=t("./lib/shaders"),h={},d=i.prototype;!function(){function t(){var t=this.plot,n=this.bounds,i=t.viewBox,a=t.dataBox,o=t.pixelRatio,s=n[2]-n[0],l=n[3]-n[1],c=a[2]-a[0],u=a[3]-a[1];e[0]=2*s/c,e[4]=2*l/u,e[6]=2*(n[0]-a[0])/c-1,e[7]=2*(n[1]-a[1])/u-1;var f=i[2]-i[0],h=i[3]-i[1];r[0]=2*o/f,r[1]=2*o/h}var e=[1,0,0,0,1,0,0,0,1],r=[1,1];d.draw=function(){var n=this.plot,i=this.shader,a=this.numVertices;if(a){var o=n.gl;t.call(this),i.bind(),i.uniforms.pixelScale=r,i.uniforms.viewTransform=e,this.positionBuffer.bind(),i.attributes.position.pointer(),this.offsetBuffer.bind(),i.attributes.offset.pointer(),this.colorBuffer.bind(),i.attributes.color.pointer(o.UNSIGNED_BYTE,!0),o.drawArrays(o.TRIANGLES,0,a)}};var n=[0,0,0,0];d.drawPick=function(i){var a=this.plot,o=this.pickShader,s=this.numVertices,l=a.gl;if(this.pickOffset=i,!s)return i;for(var c=0;4>c;++c)n[c]=i>>8*c&255;return t.call(this),o.bind(),o.uniforms.pixelScale=r,o.uniforms.viewTransform=e,o.uniforms.pickOffset=n,this.positionBuffer.bind(),o.attributes.position.pointer(),this.offsetBuffer.bind(),o.attributes.offset.pointer(),this.idBuffer.bind(),o.attributes.id.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,s),i+this.numPoints}}(),d.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},d.update=function(t){t=t||{};var e=t.positions||[],r=t.colors||[],i=t.glyphs||[],a=t.sizes||[],o=t.borderWidths||[],s=t.borderColors||[];this.points=e;for(var u=this.bounds=[1/0,1/0,-(1/0),-(1/0)],f=0,h=0;h>1;for(var d=0;2>d;++d)u[d]=Math.min(u[d],e[2*h+d]),u[2+d]=Math.max(u[2+d],e[2*h+d])}u[0]===u[2]&&(u[2]+=1),u[3]===u[1]&&(u[3]+=1);for(var p=1/(u[2]-u[0]),g=1/(u[3]-u[1]),v=u[0],m=u[1],y=c.mallocFloat32(2*f),b=c.mallocFloat32(2*f),x=c.mallocUint8(4*f),_=c.mallocUint32(f),w=0,h=0;h=a?i(0,a-1,t,e,r,n):f(0,a-1,t,e,r,n)}function i(t,e,r,n,i,a){for(var o=t+1;e>=o;++o){for(var s=r[o],l=n[2*o],c=n[2*o+1],u=i[o],f=a[o],h=o;h>t;){var d=r[h-1],p=n[2*(h-1)];if((d-s||l-p)>=0)break;r[h]=d,n[2*h]=p,n[2*h+1]=n[2*h-1],i[h]=i[h-1],a[h]=a[h-1],h-=1}r[h]=s,n[2*h]=l,n[2*h+1]=c,i[h]=u,a[h]=f}}function a(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],c=i[t],u=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=c,a[e]=u}function o(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function s(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],c=i[2*t+1],u=a[t],f=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=c,a[r]=u,o[r]=f}function l(t,e,r,n,i,a,o,s,l,c,u){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],c[t]=c[e],u[t]=u[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,c[e]=a,u[e]=o}function c(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function u(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}function f(t,e,r,n,d,p){var g=(e-t+1)/6|0,v=t+g,m=e-g,y=t+e>>1,b=y-g,x=y+g,_=v,w=b,k=y,A=x,M=m,T=t+1,E=e-1,L=0;c(_,w,r,n,d,p)&&(L=_,_=w,w=L),c(A,M,r,n,d,p)&&(L=A,A=M,M=L),c(_,k,r,n,d,p)&&(L=_,_=k,k=L),c(w,k,r,n,d,p)&&(L=w,w=k,k=L),c(_,A,r,n,d,p)&&(L=_,_=A,A=L),c(k,A,r,n,d,p)&&(L=k,k=A,A=L),c(w,M,r,n,d,p)&&(L=w,w=M,M=L),c(w,k,r,n,d,p)&&(L=w,w=k,k=L),c(A,M,r,n,d,p)&&(L=A,A=M,M=L);var S=r[w],C=n[2*w],z=n[2*w+1],P=d[w],R=p[w],O=r[A],I=n[2*A],N=n[2*A+1],j=d[A],F=p[A],D=_,B=k,U=M,V=v,q=y,H=m,G=r[D],Y=r[B],X=r[U];r[V]=G,r[q]=Y,r[H]=X;for(var W=0;2>W;++W){var Z=n[2*D+W],K=n[2*B+W],$=n[2*U+W];n[2*V+W]=Z,n[2*q+W]=K,n[2*H+W]=$}var Q=d[D],J=d[B],tt=d[U];d[V]=Q,d[q]=J,d[H]=tt;var et=p[D],rt=p[B],nt=p[U];p[V]=et,p[q]=rt,p[H]=nt,o(b,t,r,n,d,p),o(x,e,r,n,d,p);for(var it=T;E>=it;++it)if(u(it,S,C,z,P,r,n,d))it!==T&&a(it,T,r,n,d,p),++T;else if(!u(it,O,I,N,j,r,n,d))for(;;){if(u(E,O,I,N,j,r,n,d)){u(E,S,C,z,P,r,n,d)?(s(it,T,E,r,n,d,p),++T,--E):(a(it,E,r,n,d,p),--E);break}if(--E=T-2-t?i(t,T-2,r,n,d,p):f(t,T-2,r,n,d,p),h>=e-(E+2)?i(E+2,e,r,n,d,p):f(E+2,e,r,n,d,p),h>=E-T?i(T,E,r,n,d,p):f(T,E,r,n,d,p)}e.exports=n;var h=32},{}],189:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s){for(var l=r,c=r;n>c;++c){var u=t[2*c],f=t[2*c+1],h=e[c];u>=i&&o>=u&&f>=a&&s>=f&&(c===l?l+=1:(t[2*c]=t[2*l],t[2*c+1]=t[2*l+1],e[c]=e[l],t[2*l]=u,t[2*l+1]=f,e[l]=h,l+=1))}return l}function i(t,e,r){this.pixelSize=t,this.offset=e,this.count=r}function a(t,e,r,a){function l(i,a,o,s,c,u){var f=.5*o,h=s+1,d=c-s;r[_]=d,x[_++]=u;for(var p=0;2>p;++p)for(var g=0;2>g;++g){var v=i+p*f,m=a+g*f,y=n(t,e,h,c,v,m,v+f,m+f);if(y!==h){if(y-h>=Math.max(.9*d,32)){var b=c+s>>>1;l(v,m,f,h,b,u+1),h=b}l(v,m,f,h,y,u+1),h=y}}}var c=t.length>>>1;if(1>c)return[];for(var u=1/0,f=1/0,h=-(1/0),d=-(1/0),p=0;c>p;++p){var g=t[2*p],v=t[2*p+1];u=Math.min(u,g),h=Math.max(h,g),f=Math.min(f,v),d=Math.max(d,v),e[p]=p}u===h&&(h+=1+Math.abs(h)),f===d&&(d+=1+Math.abs(h));var m=1/(h-u),y=1/(d-f),b=Math.max(h-u,d-f);a=a||[0,0,0,0],a[0]=u,a[1]=f,a[2]=h,a[3]=d;var x=o.mallocInt32(c),_=0;l(u,f,b,0,c,0),s(x,t,e,r,c);for(var w=[],k=0,A=c,_=c-1;_>=0;--_){t[2*_]=(t[2*_]-u)*m,t[2*_+1]=(t[2*_+1]-f)*y;var M=x[_];M!==k&&(w.push(new i(b*Math.pow(.5,M),_+1,A-(_+1))),A=_+1,k=M)}return w.push(new i(b*Math.pow(.5,M+1),0,A)),o.free(x),w}var o=t("typedarray-pool"),s=t("./lib/sort");e.exports=a},{"./lib/sort":188,"typedarray-pool":278}],190:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.weightBuffer=n,this.shader=i,this.pickShader=a,this.scales=[],this.size=12,this.borderSize=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.pickOffset=0,this.points=null,this.xCoords=null}function i(t,e){var r=t.gl,i=o(r),s=o(r),l=o(r),c=a(r,u.pointVertex,u.pointFragment),f=a(r,u.pickVertex,u.pickFragment),h=new n(t,i,s,l,c,f);return h.update(e),t.addObject(h),h}var a=t("gl-shader"),o=t("gl-buffer"),s=t("binary-search-bounds"),l=t("snap-points-2d"),c=t("typedarray-pool"),u=t("./lib/shader");e.exports=i;var f=n.prototype;f.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.xCoords&&c.free(this.xCoords),this.plot.removeObject(this)},f.update=function(t){function e(e,r){return e in t?t[e]:r}t=t||{},this.size=e("size",12),this.color=e("color",[1,0,0,1]).slice(),this.borderSize=e("borderSize",1),this.borderColor=e("borderColor",[0,0,0,1]).slice(),this.xCoords&&c.free(this.xCoords);var r=t.positions,n=c.mallocFloat32(r.length),i=c.mallocInt32(r.length>>>1);n.set(r);var a=c.mallocFloat32(r.length);this.points=r,this.scales=l(n,i,a,this.bounds),this.offsetBuffer.update(n),this.pickBuffer.update(i),this.weightBuffer.update(a);for(var o=c.mallocFloat32(r.length>>>1),s=0,u=0;s>>1,this.pickOffset=0},f.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.scales,o=this.offsetBuffer,l=this.pickBuffer,c=this.bounds,u=this.size,f=this.borderSize,h=n.gl,d=n.pickPixelRatio,p=n.viewBox,g=n.dataBox;if(0===this.pointCount)return r;var v=c[2]-c[0],m=c[3]-c[1],y=g[2]-g[0],b=g[3]-g[1],x=(p[2]-p[0])*d/n.pixelRatio,_=(p[3]-p[1])*d/n.pixelRatio,w=Math.min(y/x,b/_);t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(c[0]-g[0])/y-1,t[7]=2*(c[1]-g[1])/b-1,this.pickOffset=r,e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,i.bind(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointSize=d*(u+f),i.uniforms.pickOffset=e,0===this.borderSize?i.uniforms.centerFraction=2:i.uniforms.centerFraction=u/(u+f+1.25),o.bind(),i.attributes.position.pointer(),l.bind(),i.attributes.pickId.pointer(h.UNSIGNED_BYTE);for(var k=this.xCoords,A=(g[0]-c[0]-w*u*d)/v,M=(g[2]-c[0]+w*u*d)/v,T=a.length-1;T>=0;--T){var E=a[T];if(!(E.pixelSize1)){var L=E.offset,S=E.count+L,C=s.ge(k,A,L,S-1),z=s.lt(k,M,C,S-1)+1;z>C&&h.drawArrays(h.POINTS,C,z-C)}}return r+this.pointCount}}(),f.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.scales,i=this.offsetBuffer,a=this.bounds,o=this.size,l=this.borderSize,c=e.gl,u=e.pixelRatio,f=e.viewBox,h=e.dataBox;if(0!==this.pointCount){var d=a[2]-a[0],p=a[3]-a[1],g=h[2]-h[0],v=h[3]-h[1],m=f[2]-f[0],y=f[3]-f[1],b=Math.min(g/m,v/y);t[0]=2*d/g,t[4]=2*p/v,t[6]=2*(a[0]-h[0])/g-1,t[7]=2*(a[1]-h[1])/v-1,r.bind(),r.uniforms.matrix=t,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointSize=u*(o+l),r.uniforms.useWeight=1,0===this.borderSize?r.uniforms.centerFraction=2:r.uniforms.centerFraction=o/(o+l+1.25),i.bind(),r.attributes.position.pointer(),this.weightBuffer.bind(),r.attributes.weight.pointer();for(var x=this.xCoords,_=(h[0]-a[0]-b*o*u)/d,w=(h[2]-a[0]+b*o*u)/d,k=!0,A=n.length-1;A>=0;--A){var M=n[A];if(!(M.pixelSize1)){var T=M.offset,E=M.count+T,L=s.ge(x,_,T,E-1),S=s.lt(x,w,L,E-1)+1;S>L&&c.drawArrays(c.POINTS,L,S-L),k&&(k=!1,r.uniforms.useWeight=0)}}}}}(),f.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":186,"binary-search-bounds":187,"gl-buffer":118,"gl-shader":197,"snap-points-2d":189,"typedarray-pool":278}],191:[function(t,e,r){"use strict";function n(t,e){var r=a[e];if(r||(r=a[e]={}),t in r)return r[t];for(var n=i(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),o=i(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),s=[[1/0,1/0],[-(1/0),-(1/0)]],l=0;lu;++u)s[0][u]=Math.min(s[0][u],c[u]),s[1][u]=Math.max(s[1][u],c[u]);return r[t]=[o,n,s]}var i=t("vectorize-text");e.exports=n;var a={}},{"vectorize-text":280}],192:[function(t,e,r){function n(t,e){var r=i(t,e),n=r.attributes;return n.position.location=0,n.color.location=1,n.glyph.location=2,n.id.location=3,r}var i=t("gl-shader"),a="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = 1.0;\n if(distance(highlightId, id) < 0.0001) {\n scale = highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1);\n vec4 viewPosition = view * worldPosition;\n viewPosition = viewPosition / viewPosition.w;\n vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n \n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float scale = pixelRatio;\n if(distance(highlightId.bgr, id.bgr) < 0.001) {\n scale *= highlightScale;\n }\n\n vec4 worldPosition = model * vec4(position, 1.0);\n vec4 viewPosition = view * worldPosition;\n vec4 clipPosition = projection * viewPosition;\n clipPosition /= clipPosition.w;\n \n gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n interpColor = color;\n pickId = id;\n dataCoordinate = position;\n }\n}",s="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(position, clipBounds[0])) ||\n any(greaterThan(position, clipBounds[1])) ) {\n gl_Position = vec4(0,0,0,0);\n } else {\n float lscale = pixelRatio * scale;\n if(distance(highlightId, id) < 0.0001) {\n lscale *= highlightScale;\n }\n\n vec4 clipCenter = projection * view * model * vec4(position, 1);\n vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n gl_Position = clipPosition;\n interpColor = color;\n pickId = id;\n dataCoordinate = dataPosition;\n }\n}\n",l="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) ||\n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = interpColor * opacity;\n }\n}\n",c="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n if(any(lessThan(dataCoordinate, fragClipBounds[0])) || \n any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n discard;\n } else {\n gl_FragColor = vec4(pickGroup, pickId.bgr);\n }\n}",u=[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"glyph",type:"vec2"},{name:"id",type:"vec4"}],f={vertex:a,fragment:l,attributes:u},h={vertex:o,fragment:l,attributes:u},d={vertex:s,fragment:l,attributes:u},p={vertex:a,fragment:c,attributes:u},g={vertex:o,fragment:c,attributes:u},v={vertex:s,fragment:c,attributes:u};r.createPerspective=function(t){return n(t,f)},r.createOrtho=function(t){return n(t,h)},r.createProject=function(t){return n(t,d)},r.createPickPerspective=function(t){return n(t,p)},r.createPickOrtho=function(t){return n(t,g)},r.createPickProject=function(t){return n(t,v)}},{"gl-shader":197}],193:[function(t,e,r){"use strict";function n(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];return t[0]=e[0]*r+e[4]*n+e[8]*i+e[12]*a,t[1]=e[1]*r+e[5]*n+e[9]*i+e[13]*a,t[2]=e[2]*r+e[6]*n+e[10]*i+e[14]*a,t[3]=e[3]*r+e[7]*n+e[11]*i+e[15]*a, +t}function i(t,e,r,i){return n(i,i,r),n(i,i,e),n(i,i,t)}function a(t,e){this.index=t,this.dataCoordinate=this.position=e}function o(t,e,r,n,i,o,s,l,c,u,f,h){this.gl=t,this.pixelRatio=1,this.shader=e,this.orthoShader=r,this.projectShader=n,this.pointBuffer=i,this.colorBuffer=o,this.glyphBuffer=s,this.idBuffer=l,this.vao=c,this.vertexCount=0,this.lineVertexCount=0,this.opacity=1,this.lineWidth=0,this.projectScale=[2/3,2/3,2/3],this.projectOpacity=[1,1,1],this.pickId=0,this.pickPerspectiveShader=u,this.pickOrthoShader=f,this.pickProjectShader=h,this.points=[],this._selectResult=new a(0,[0,0,0]),this.useOrtho=!0,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.axesProject=[!0,!0,!0],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.highlightId=[1,1,1,1],this.highlightScale=2,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.dirty=!0}function s(t){return t[0]=t[1]=t[2]=0,t}function l(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function c(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function u(t){for(var e=S,r=0;2>r;++r)for(var n=0;3>n;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}function f(t,e,r,n,a){var o,f=e.axesProject,h=e.gl,d=t.uniforms,p=r.model||x,g=r.view||x,v=r.projection||x,y=e.axesBounds,b=u(e.clipBounds);o=e.axes?e.axes.lastCubeProps.axis:[1,1,1],w[0]=2/h.drawingBufferWidth,w[1]=2/h.drawingBufferHeight,t.bind(),d.view=g,d.projection=v,d.screenSize=w,d.highlightId=e.highlightId,d.highlightScale=e.highlightScale,d.clipBounds=b,d.pickGroup=e.pickId/255,d.pixelRatio=e.pixelRatio;for(var _=0;3>_;++_)if(f[_]&&e.projectOpacity[_]<1===n){d.scale=e.projectScale[_],d.opacity=e.projectOpacity[_];for(var S=E,C=0;16>C;++C)S[C]=0;for(var C=0;4>C;++C)S[5*C]=1;S[5*_]=0,o[_]<0?S[12+_]=y[0][_]:S[12+_]=y[1][_],m(S,p,S),d.model=S;var z=(_+1)%3,P=(_+2)%3,R=s(k),O=s(A);R[z]=1,O[P]=1;var I=i(v,g,p,l(M,R)),N=i(v,g,p,l(T,O));if(Math.abs(I[1])>Math.abs(N[1])){var j=I;I=N,N=j,j=R,R=O,O=j;var F=z;z=P,P=F}I[0]<0&&(R[z]=-1),N[1]>0&&(O[P]=-1);for(var D=0,B=0,C=0;4>C;++C)D+=Math.pow(p[4*z+C],2),B+=Math.pow(p[4*P+C],2);R[z]/=Math.sqrt(D),O[P]/=Math.sqrt(B),d.axes[0]=R,d.axes[1]=O,d.fragClipBounds[0]=c(L,b[0],_,-1e8),d.fragClipBounds[1]=c(L,b[1],_,1e8),e.vao.draw(h.TRIANGLES,e.vertexCount),e.lineWidth>0&&(h.lineWidth(e.lineWidth),e.vao.draw(h.LINES,e.lineVertexCount,e.vertexCount))}}function h(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||x,s.view=n.view||x,s.projection=n.projection||x,w[0]=2/o.drawingBufferWidth,w[1]=2/o.drawingBufferHeight,s.screenSize=w,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=P,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}f(e,r,n,i,a),r.vao.unbind()}function d(t){var e=t.gl,r=y.createPerspective(e),n=y.createOrtho(e),i=y.createProject(e),a=y.createPickPerspective(e),s=y.createPickOrtho(e),l=y.createPickProject(e),c=p(e),u=p(e),f=p(e),h=p(e),d=g(e,[{buffer:c,size:3,type:e.FLOAT},{buffer:u,size:4,type:e.FLOAT},{buffer:f,size:2,type:e.FLOAT},{buffer:h,size:4,type:e.UNSIGNED_BYTE,normalized:!0}]),v=new o(e,r,n,i,c,u,f,h,d,a,s,l);return v.update(t),v}var p=t("gl-buffer"),g=t("gl-vao"),v=t("typedarray-pool"),m=t("gl-mat4/multiply"),y=t("./lib/shaders"),b=t("./lib/glyphs"),x=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];e.exports=d;var _=o.prototype;_.pickSlots=1,_.setPickBase=function(t){this.pickId=t},_.isTransparent=function(){if(this.opacity<1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]<1)return!0;return!1},_.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var w=[0,0],k=[0,0,0],A=[0,0,0],M=[0,0,0,1],T=[0,0,0,1],E=x.slice(),L=[0,0,0],S=[[0,0,0],[0,0,0]],C=[-1e8,-1e8,-1e8],z=[1e8,1e8,1e8],P=[C,z];_.draw=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!1,!1)},_.drawTransparent=function(t){var e=this.useOrtho?this.orthoShader:this.shader;h(e,this.projectShader,this,t,!0,!1)},_.drawPick=function(t){var e=this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader;h(e,this.pickProjectShader,this,t,!1,!0)},_.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||0>e)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;3>i;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},_.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},_.update=function(t){if(t=t||{},"perspective"in t&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{var r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-(1/0),-(1/0),-(1/0)],l=t.glyph,c=t.color,u=t.size,f=t.angle,h=t.lineColor,d=0,p=0,g=0,m=n.length;t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_)if(isNaN(x[_])||!isFinite(x[_]))continue t;var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];p+=3*k.cells.length,g+=2*A.edges.length}var T=p+g,E=v.mallocFloat(3*T),L=v.mallocFloat(4*T),S=v.mallocFloat(2*T),C=v.mallocUint32(T),z=[0,a[1]],P=0,R=p,O=[0,0,0,1],I=[0,0,0,1],N=Array.isArray(c)&&Array.isArray(c[0]),j=Array.isArray(h)&&Array.isArray(h[0]);t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_){if(isNaN(x[_])||!isFinite(x[_])){d+=1;continue t}s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_])}var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var k=w[0],A=w[1],M=w[2];if(Array.isArray(c)){var F;if(F=N?c[y]:c,3===F.length){for(var _=0;3>_;++_)O[_]=F[_];O[3]=1}else if(4===F.length)for(var _=0;4>_;++_)O[_]=F[_]}else O[0]=O[1]=O[2]=0,O[3]=1;if(Array.isArray(h)){var F;if(F=j?h[y]:h,3===F.length){for(var _=0;3>_;++_)I[_]=F[_];I[_]=1}else if(4===F.length)for(var _=0;4>_;++_)I[_]=F[_]}else I[0]=I[1]=I[2]=0,I[3]=1;var D=.5;Array.isArray(u)?D=+u[y]:u?D=+u:this.useOrtho&&(D=12);var B=0;Array.isArray(f)?B=+f[y]:f&&(B=+f);for(var U=Math.cos(B),V=Math.sin(B),x=n[y],_=0;3>_;++_)s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_]);a[0]<0?z[0]=a[0]*(1+M[1][0]):a[0]>0&&(z[0]=-a[0]*(1+M[0][0]));for(var q=k.cells,H=k.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*P+X]=x[X];for(var X=0;4>X;++X)L[4*P+X]=O[X];C[P]=d;var W=H[G[Y]];S[2*P]=D*(U*W[0]-V*W[1]+z[0]),S[2*P+1]=D*(V*W[0]+U*W[1]+z[1]),P+=1}for(var q=A.edges,H=A.positions,_=0;_Y;++Y){for(var X=0;3>X;++X)E[3*R+X]=x[X];for(var X=0;4>X;++X)L[4*R+X]=I[X];C[R]=d;var W=H[G[Y]];S[2*R]=D*(U*W[0]-V*W[1]+z[0]),S[2*R+1]=D*(V*W[0]+U*W[1]+z[1]),R+=1}d+=1}this.vertexCount=p,this.lineVertexCount=g,this.pointBuffer.update(E),this.colorBuffer.update(L),this.glyphBuffer.update(S),this.idBuffer.update(new Uint32Array(C)),v.free(E),v.free(L),v.free(S),v.free(C),this.bounds=[o,s],this.points=n,this.pointCount=n.length}},_.dispose=function(){this.shader.dispose(),this.orthoShader.dispose(),this.pickPerspectiveShader.dispose(),this.pickOrthoShader.dispose(),this.vao.dispose(),this.pointBuffer.dispose(),this.colorBuffer.dispose(),this.glyphBuffer.dispose(),this.idBuffer.dispose()}},{"./lib/glyphs":191,"./lib/shaders":192,"gl-buffer":118,"gl-mat4/multiply":139,"gl-vao":226,"typedarray-pool":278}],194:[function(t,e,r){"use strict";r.boxVertex="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n",r.boxFragment="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 color;\n\nvoid main() {\n gl_FragColor = color;\n}\n"},{}],195:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.boxBuffer=e,this.boxShader=r,this.enabled=!0,this.selectBox=[1/0,1/0,-(1/0),-(1/0)],this.borderColor=[0,0,0,1],this.innerFill=!1,this.innerColor=[0,0,0,.25],this.outerFill=!0,this.outerColor=[0,0,0,.5],this.borderWidth=10}function i(t,e){var r=t.gl,i=o(r,[0,0,0,1,1,0,1,1]),l=a(r,s.boxVertex,s.boxFragment),c=new n(t,i,l);return c.update(e),t.addOverlay(c),c}var a=t("gl-shader"),o=t("gl-buffer"),s=t("./lib/shaders");e.exports=i;var l=n.prototype;l.draw=function(){if(this.enabled){var t=this.plot,e=this.selectBox,r=this.borderWidth,n=(this.innerFill,this.innerColor),i=(this.outerFill,this.outerColor),a=this.borderColor,o=t.box,s=t.screenBox,l=t.dataBox,c=t.viewBox,u=t.pixelRatio,f=(e[0]-l[0])*(c[2]-c[0])/(l[2]-l[0])+c[0],h=(e[1]-l[1])*(c[3]-c[1])/(l[3]-l[1])+c[1],d=(e[2]-l[0])*(c[2]-c[0])/(l[2]-l[0])+c[0],p=(e[3]-l[1])*(c[3]-c[1])/(l[3]-l[1])+c[1];if(f=Math.max(f,c[0]),h=Math.max(h,c[1]),d=Math.min(d,c[2]),p=Math.min(p,c[3]),!(f>d||h>p)){o.bind();var g=s[2]-s[0],v=s[3]-s[1];if(this.outerFill&&(o.drawBox(0,0,g,h,i),o.drawBox(0,h,f,p,i),o.drawBox(0,p,g,v,i),o.drawBox(d,h,g,p,i)),this.innerFill&&o.drawBox(f,h,d,p,n),r>0){var m=r*u;o.drawBox(f-m,h-m,d+m,h+m,a),o.drawBox(f-m,p-m,d+m,p+m,a),o.drawBox(f-m,h-m,f+m,p+m,a),o.drawBox(d-m,h-m,d+m,p+m,a)}}}},l.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},l.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":194,"gl-buffer":118,"gl-shader":197}],196:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.coord=[t,e],this.id=r,this.value=n,this.distance=i}function i(t,e,r){this.gl=t,this.fbo=e,this.buffer=r,this._readTimeout=null;var n=this;this._readCallback=function(){n.gl&&(e.bind(),t.readPixels(0,0,e.shape[0],e.shape[1],t.RGBA,t.UNSIGNED_BYTE,n.buffer),n._readTimeout=null)}}function a(t,e){var r=o(t,e),n=s.mallocUint8(e[0]*e[1]*4);return new i(t,r,n)}e.exports=a;var o=t("gl-fbo"),s=t("typedarray-pool"),l=t("ndarray"),c=t("bit-twiddle").nextPow2,u=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(255>_inline_31_arg0_||255>_inline_31_arg1_||255>_inline_31_arg2_||255>_inline_31_arg3_){var _inline_31_l=_inline_31_arg4_-_inline_31_arg6_[0],_inline_31_a=_inline_31_arg5_-_inline_31_arg6_[1],_inline_31_f=_inline_31_l*_inline_31_l+_inline_31_a*_inline_31_a;_inline_31_fthis.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(c(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),f.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},f.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},f.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),c=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=c)return null;var f=[o-a,c-s],h=l(this.buffer,[f[0],f[1],4],[4,4*i[0],1],4*(a+i[0]*s)),d=u(h.hi(f[0],f[1],1),r,r),p=d[0],g=d[1];if(0>p||Math.pow(this.radius,2)=0){for(var A=0|k.type.charAt(k.type.length-1),M=new Array(A),T=0;A>T;++T)M[T]=_.length,x.push(k.name+"["+T+"]"),"number"==typeof k.location?_.push(k.location+T):Array.isArray(k.location)&&k.location.length===A&&"number"==typeof k.location[T]?_.push(0|k.location[T]):_.push(-1);b.push({name:k.name,type:k.type,locations:M})}else b.push({name:k.name,type:k.type,locations:[_.length]}),x.push(k.name),"number"==typeof k.location?_.push(0|k.location):_.push(-1)}for(var E=0,w=0;w<_.length;++w)if(_[w]<0){for(;_.indexOf(E)>=0;)E+=1;_[w]=E}var L=new Array(r.length);a(),d._relink=a,d.types={uniforms:l(r),attributes:l(n)},d.attributes=s(p,d,b,_),Object.defineProperty(d,"uniforms",o(p,d,r,L))},e.exports=a},{"./lib/GLError":198,"./lib/create-attributes":199,"./lib/create-uniforms":200,"./lib/reflect":201,"./lib/runtime-reflect":202,"./lib/shader-cache":203}],198:[function(t,e,r){function n(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}n.prototype=new Error,n.prototype.name="GLError",n.prototype.constructor=n,e.exports=n},{}],199:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}function i(t,e,r,i,a,o,s){for(var l=["gl","v"],c=[],u=0;a>u;++u)l.push("x"+u),c.push("x"+u);l.push("if(x0.length===void 0){return gl.vertexAttrib"+a+"f(v,"+c.join()+")}else{return gl.vertexAttrib"+a+"fv(v,x0)}");var f=Function.apply(null,l),h=new n(t,e,r,i,a,f);Object.defineProperty(o,s,{set:function(e){return t.disableVertexAttribArray(i[r]),f(t,i[r],e),e},get:function(){return h},enumerable:!0})}function a(t,e,r,n,a,o,s){for(var l=new Array(a),c=new Array(a),u=0;a>u;++u)i(t,e,r[u],n,a,l,u),c[u]=l[u];Object.defineProperty(l,"location",{set:function(t){if(Array.isArray(t))for(var e=0;a>e;++e)c[e].location=t[e];else for(var e=0;a>e;++e)c[e].location=t+e;return t},get:function(){for(var t=new Array(a),e=0;a>e;++e)t[e]=n[r[e]];return t},enumerable:!0}),l.pointer=function(e,i,o,s){e=e||t.FLOAT,i=!!i,o=o||a*a,s=s||0;for(var l=0;a>l;++l){var c=n[r[l]];t.vertexAttribPointer(c,a,e,i,o,s+l*a),t.enableVertexAttribArray(c)}};var f=new Array(a),h=t["vertexAttrib"+a+"fv"];Object.defineProperty(o,s,{set:function(e){for(var i=0;a>i;++i){var o=n[r[i]];if(t.disableVertexAttribArray(o),Array.isArray(e[0]))h.call(t,o,e[i]);else{for(var s=0;a>s;++s)f[s]=e[a*i+s];h.call(t,o,f)}}return e},get:function(){return l},enumerable:!0})}function o(t,e,r,n){for(var o={},l=0,c=r.length;c>l;++l){var u=r[l],f=u.name,h=u.type,d=u.locations;switch(h){case"bool":case"int":case"float":i(t,e,d[0],n,1,o,f);break;default:if(h.indexOf("vec")>=0){var p=h.charCodeAt(h.length-1)-48;if(2>p||p>4)throw new s("","Invalid data type for attribute "+f+": "+h);i(t,e,d[0],n,p,o,f)}else{if(!(h.indexOf("mat")>=0))throw new s("","Unknown data type for attribute "+f+": "+h);var p=h.charCodeAt(h.length-1)-48;if(2>p||p>4)throw new s("","Invalid data type for attribute "+f+": "+h);a(t,e,d,n,p,o,f)}}}return o}e.exports=o;var s=t("./GLError"),l=n.prototype;l.pointer=function(t,e,r,n){var i=this,a=i._gl,o=i._locations[i._index];a.vertexAttribPointer(o,i._dimension,t||a.FLOAT,!!e,r||0,n||0),a.enableVertexAttribArray(o)},l.set=function(t,e,r,n){return this._constFunc(this._locations[this._index],t,e,r,n)},Object.defineProperty(l,"location",{get:function(){return this._locations[this._index]},set:function(t){return t!==this._locations[this._index]&&(this._locations[this._index]=0|t,this._wrapper.program=null),0|t}})},{"./GLError":198}],200:[function(t,e,r){"use strict";function n(t){var e=new Function("y","return function(){return y}");return e(t)}function i(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e,r,a){function l(r){var n=new Function("gl","wrapper","locations","return function(){return gl.getUniform(wrapper.program,locations["+r+"])}");return n(t,e,a)}function c(t,e,r){switch(r){case"bool":case"int":case"sampler2D":case"samplerCube":return"gl.uniform1i(locations["+e+"],obj"+t+")";case"float":return"gl.uniform1f(locations["+e+"],obj"+t+")";default:var n=r.indexOf("vec");if(!(n>=0&&1>=n&&r.length===4+n)){if(0===r.indexOf("mat")&&4===r.length){var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new s("","Unknown uniform data type for "+name+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new s("","Unrecognized data type for vector "+name+": "+r)}}}function u(t,e){if("object"!=typeof e)return[[t,e]];var r=[];for(var n in e){var i=e[n],a=t;a+=parseInt(n)+""===n?"["+n+"]":"."+n,"object"==typeof i?r.push.apply(r,u(a,i)):r.push([a,i])}return r}function f(e){for(var n=["return function updateProperty(obj){"],i=u("",e),o=0;o=0&&1>=e&&t.length===4+e){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid data type");return"b"===t.charAt(0)?i(r,!1):i(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+t);return i(r*r,0)}throw new s("","Unknown uniform data type for "+name+": "+t)}}function d(t,e,i){if("object"==typeof i){var o=p(i);Object.defineProperty(t,e,{get:n(o),set:f(i),enumerable:!0,configurable:!1})}else a[i]?Object.defineProperty(t,e,{get:l(i),set:f(i),enumerable:!0,configurable:!1}):t[e]=h(r[i].type)}function p(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var c=1;ca;++a){var o=t.getActiveUniform(e,a);if(o){var s=n(t,o.type);if(o.size>1)for(var l=0;la;++a){var o=t.getActiveAttrib(e,a);o&&i.push({name:o.name,type:n(t,o.type)})}return i}r.uniforms=i,r.attributes=a;var o={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube"},s=null},{}],203:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.id=t,this.src=e,this.type=r,this.shader=n,this.count=a,this.programs=[],this.cache=o}function i(t){this.gl=t,this.shaders=[{},{}],this.programs={}}function a(t,e,r){var n=t.createShader(e);if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){var i=t.getShaderInfoLog(n);try{var a=f(i,r,e)}catch(o){throw console.warn("Failed to format compiler error: "+o),new u(i,"Error compiling shader:\n"+i)}throw new u(i,a.short,a.long)}return n}function o(t,e,r,n,i){var a=t.createProgram();t.attachShader(a,e),t.attachShader(a,r);for(var o=0;on;++n){var a=t.programs[r[n]];a&&(delete t.programs[n],e.deleteProgram(a))}e.deleteShader(this.shader),delete t.shaders[this.type===e.FRAGMENT_SHADER|0][this.src]}};var g=i.prototype;g.getShaderReference=function(t,e){var r=this.gl,i=this.shaders[t===r.FRAGMENT_SHADER|0],o=i[e];if(o&&r.isShader(o.shader))o.count+=1;else{var s=a(r,t,e);o=i[e]=new n(p++,e,t,s,[],1,this)}return o},g.getProgram=function(t,e,r,n){var i=[t.id,e.id,r.join(":"),n.join(":")].join("@"),a=this.programs[i];return a&&this.gl.isProgram(a)||(this.programs[i]=a=o(this.gl,t.shader,e.shader,r,n),t.programs.push(i),e.programs.push(i)),a}},{"./GLError":198,"gl-format-compiler-error":204,"weakmap-shim":214}],204:[function(t,e,r){function n(t,e,r){"use strict";var n=o(e)||"of unknown name (see npm glsl-shader-name)",l="unknown type";void 0!==r&&(l=r===a.FRAGMENT_SHADER?"fragment":"vertex");for(var c=i("Error compiling %s shader %s:\n",l,n),u=i("%s%s",c,t),f=t.split("\n"),h={},d=0;ds;s++)if(g=i(t[s]),"string"===g)v[v.length]=t[s];else if("array"===g){if(c=t[s],c[2])for(n=e[d],l=0;l=0),c[8]){case"b":n=n.toString(2);break;case"c":n=String.fromCharCode(n);break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,c[6]?parseInt(c[6]):0);break;case"e":n=c[7]?n.toExponential(c[7]):n.toExponential();break;case"f":n=c[7]?parseFloat(n).toFixed(c[7]):parseFloat(n);break;case"g":n=c[7]?parseFloat(n).toPrecision(c[7]):parseFloat(n);break;case"o":n=n.toString(8);break;case"s":n=(n=String(n))&&c[7]?n.substring(0,c[7]):n;break;case"u":n>>>=0;break;case"x":n=n.toString(16);break;case"X":n=n.toString(16).toUpperCase()}o.json.test(c[8])?v[v.length]=n:(!o.number.test(c[8])||m&&!c[3]?y="":(y=m?"+":"-",n=n.toString().replace(o.sign,"")),f=c[4]?"0"===c[4]?"0":c[4].charAt(1):" ",h=c[6]-(y+n).length,u=c[6]&&h>0?a(f,h):"",v[v.length]=c[5]?y+n+u:"0"===f?y+u+n:u+y+n)}return v.join("")},r.cache={},r.parse=function(t){for(var e=t,r=[],n=[],i=0;e;){if(null!==(r=o.text.exec(e)))n[n.length]=r[0];else if(null!==(r=o.modulo.exec(e)))n[n.length]="%";else{if(null===(r=o.placeholder.exec(e)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){i|=1;var a=[],s=r[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a[a.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))a[a.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");a[a.length]=l[1]}r[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n[n.length]=r}e=e.substring(r[0].length)}return n};var s=function(t,e,n){return n=(e||[]).slice(0),n.splice(0,0,t),r.apply(null,n)};"undefined"!=typeof n?(n.sprintf=r,n.vsprintf=s):(e.sprintf=r,e.vsprintf=s,"function"==typeof t&&t.amd&&t(function(){return{sprintf:r,vsprintf:s}}))}("undefined"==typeof window?this:window)},{}],212:[function(t,e,r){function n(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:i(e,t)}}var i=t("./hidden-store.js");e.exports=n},{"./hidden-store.js":213}],213:[function(t,e,r){function n(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}e.exports=n},{}],214:[function(t,e,r){function n(){var t=i();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){t(e).value=r},has:function(e){return"value"in t(e)},"delete":function(e){return delete t(e).value}}}var i=t("./create-store.js");e.exports=n},{"./create-store.js":212}],215:[function(t,e,r){"use strict";function n(t){this.plot=t,this.enable=[!0,!0,!1,!1],this.width=[1,1,1,1],this.color=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.center=[1/0,1/0]}function i(t,e){var r=new n(t);return r.update(e),t.addOverlay(r),r}e.exports=i;var a=n.prototype;a.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},a.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),c=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,c,s[0],c,e[0],r[0]),t[1]&&a.drawLine(l,c,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,c,s[2],c,e[2],r[2]),t[3]&&a.drawLine(l,c,l,s[3],e[3],r[3])}},a.dispose=function(){this.plot.removeOverlay(this)}},{}],216:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute vec3 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n worldCoordinate = vec3(uv.zw, f.x);\n vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n vec4 clipPosition = projection * view * worldPosition;\n gl_Position = clipPosition;\n kill = f.y;\n value = f.z;\n planeCoordinate = uv.xy;\n\n //Lighting geometry parameters\n vec4 cameraCoordinate = view * worldPosition;\n cameraCoordinate.xyz /= cameraCoordinate.w;\n lightDirection = lightPosition - cameraCoordinate.xyz;\n eyeDirection = eyePosition - cameraCoordinate.xyz;\n surfaceNormal = normalize((vec4(normal,0) * inverseModel).xyz);\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n float NdotH = max(x, 0.0001);\n float cos2Alpha = NdotH * NdotH;\n float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n float roughness2 = roughness * roughness;\n float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float roughness) {\n return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(surfaceNormal);\n vec3 V = normalize(eyeDirection);\n vec3 L = normalize(lightDirection);\n\n if(gl_FrontFacing) {\n N = -N;\n }\n\n float specular = beckmannSpecular_1_1(L, V, N, roughness);\n float diffuse = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n vec4 surfaceColor = texture2D(colormap, vec2(value, value));\n vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular, 1.0);\n\n gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n",o="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec4 uv;\nattribute float f;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\n planeCoordinate = uv.zw;\n\n //Don't do lighting for contours\n surfaceNormal = vec3(1,0,0);\n eyeDirection = vec3(0,1,0);\n lightDirection = vec3(0,0,1);\n}\n",s="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n float vh = 255.0 * v;\n float upper = floor(vh);\n float lower = fract(vh);\n return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n if(kill > 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\n vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}\n";r.createShader=function(t){var e=n(t,i,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,i,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec3"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,o,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e},r.createPickContourShader=function(t){var e=n(t,o,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"float"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e}},{"gl-shader":197}],217:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],218:[function(t,e,r){"use strict";function n(t){if(t in l)return l[t];for(var e=[],r=0;t>r;++r)e.push("out",r,"s=0.5*(inp",r,"l-inp",r,"r);");for(var n=["array"],i=["junk"],r=0;t>r;++r){n.push("array"),i.push("out"+r+"s");var a=o(t);a[r]=-1,n.push({array:0,offset:a.slice()}),a[r]=1,n.push({array:0,offset:a.slice()}),i.push("inp"+r+"l","inp"+r+"r")}return l[t]=s({args:n,pre:u,post:u,body:{body:e.join(""),args:i.map(function(t){return{name:t,lvalue:0===t.indexOf("out"),rvalue:0===t.indexOf("inp"),count:"junk"!==t|0}}),thisVars:[],localVars:[]},funcName:"fdTemplate"+t})}function i(t){function e(e){for(var r=a-e.length,n=[],i=[],s=[],l=0;a>l;++l)e.indexOf(l+1)>=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),n.push("1"),i.push("s["+l+"]-2"));var c=".lo("+n.join()+").hi("+i.join()+")";if(0===n.length&&(c=""),r>0){o.push("if(1");for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push("&&s[",l,"]>2");o.push("){grad",r,"(src.pick(",s.join(),")",c);for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push(",dst.pick(",s.join(),",",l,")",c);o.push(");")}for(var l=0;l1){dst.set(",s.join(),",",u,",0.5*(src.get(",h.join(),")-src.get(",d.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):o.push("if(s[",u,"]>1){diff(",f,",src.pick(",h.join(),")",c,",src.pick(",d.join(),")",c,");}else{zero(",f,");};");break;case"mirror":0===r?o.push("dst.set(",s.join(),",",u,",0);"):o.push("zero(",f,");");break;case"wrap":var p=s.slice(),g=s.slice();e[l]<0?(p[u]="s["+u+"]-2",g[u]="0"):(p[u]="s["+u+"]-1",g[u]="1"),0===r?o.push("if(s[",u,"]>2){dst.set(",s.join(),",",u,",0.5*(src.get(",p.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",u,",0)};"):o.push("if(s[",u,"]>2){diff(",f,",src.pick(",p.join(),")",c,",src.pick(",g.join(),")",c,");}else{zero(",f,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}r>0&&o.push("};")}var r=t.join(),i=c[r];if(i)return i;for(var a=t.length,o=["function gradient(dst,src){var s=src.shape.slice();"],s=0;1<
s;++s){for(var u=[],d=0;a>d;++d)s&1<=s;++s)v.push("grad"+s),m.push(n(s));v.push(o.join(""));var y=Function.apply(void 0,v),i=y.apply(void 0,m);return l[r]=i,i}function a(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r="string"==typeof r?o(e.dimension,r):o(e.dimension,"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;nr;++r)for(o=o||e.surfaceProject[r],n=0;3>n;++n)s=s||e.contourProject[r][n];for(r=0;3>r;++r){var l=D.projections[r];for(n=0;16>n;++n)l[n]=0;for(n=0;4>n;++n)l[5*n]=1;l[5*r]=0,l[12+r]=e.axesBounds[+(a[r]>0)][r],k(l,t.model,l);var c=D.clipBounds[r];for(i=0;2>i;++i)for(n=0;3>n;++n)c[i][n]=t.clipBounds[i][n];c[0][r]=-1e8,c[1][r]=1e8}return D.showSurface=o,D.showContour=s,D}function s(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=B;n.model=t.model||R,n.view=t.view||R,n.projection=t.projection||R,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=A(n.inverseModel,n.model);for(var i=0;2>i;++i)for(var a=n.clipBounds[i],s=0;3>s;++s)a[s]=Math.min(Math.max(this.clipBounds[i][s],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=V;var l=U;for(k(l,n.view,n.model),k(l,n.projection,l),A(l,l),i=0;3>i;++i)n.eyePosition[i]=l[12+i]/l[15];var c=l[15];for(i=0;3>i;++i)c+=this.lightPosition[i]*l[4*i+3];for(i=0;3>i;++i){var u=l[12+i];for(s=0;3>s;++s)u+=l[4*s+i]*this.lightPosition[s];n.lightPosition[i]=u/c}var f=o(n,this);if(f.showSurface&&e===this.opacity<1){for(this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vertexCount&&this._vao.draw(r.TRIANGLES,this._vertexCount),i=0;3>i;++i)this.surfaceProject[i]&&this.vertexCount&&(this._shader.uniforms.model=f.projections[i],this._shader.uniforms.clipBounds=f.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(f.showContour&&!e){var h=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,h.bind(),h.uniforms=n;var d=this._contourVAO;for(d.bind(),i=0;3>i;++i)for(h.uniforms.permutation=I[i],r.lineWidth(this.contourWidth[i]),s=0;si;++i)for(h.uniforms.model=f.projections[i],h.uniforms.clipBounds=f.clipBounds[i],s=0;3>s;++s)if(this.contourProject[i][s]){h.uniforms.permutation=I[s],r.lineWidth(this.contourWidth[s]);for(var p=0;pi;++i)if(0!==this._dynamicCounts[i])for(h.uniforms.model=n.model,h.uniforms.clipBounds=n.clipBounds,h.uniforms.permutation=I[i],r.lineWidth(this.dynamicWidth[i]),h.uniforms.contourColor=this.dynamicColor[i],h.uniforms.contourTint=this.dynamicTint[i],h.uniforms.height=this.dynamicLevel[i],d.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]),s=0;3>s;++s)this.contourProject[s][i]&&(h.uniforms.model=f.projections[s],h.uniforms.clipBounds=f.clipBounds[s],d.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]));d.unbind()}}function l(t,e){var r=e.shape.slice(),n=t.shape.slice();b.assign(t.lo(1,1).hi(r[0],r[1]),e),b.assign(t.lo(1).hi(r[0],1),e.hi(r[0],1)),b.assign(t.lo(1,n[1]-1).hi(r[0],1),e.lo(0,r[1]-1).hi(r[0],1)),b.assign(t.lo(0,1).hi(1,r[1]),e.hi(1)),b.assign(t.lo(n[0]-1,1).hi(1,r[1]),e.lo(r[0]-1)),t.set(0,0,e.get(0,0)),t.set(0,n[1]-1,e.get(0,r[1]-1)),t.set(n[0]-1,0,e.get(r[0]-1,0)),t.set(n[0]-1,n[1]-1,e.get(r[0]-1,r[1]-1))}function c(t,e){return Array.isArray(t)?[e(t[0]),e(t[1]),e(t[2])]:[e(t),e(t),e(t)]}function u(t){return Array.isArray(t)?3===t.length?[t[0],t[1],t[2],1]:[t[0],t[1],t[2],t[3]]:[0,0,0,1]}function f(t){if(Array.isArray(t)){if(Array.isArray(t))return[u(t[0]),u(t[1]),u(t[2])];var e=u(t);return[e.slice(),e.slice(),e.slice()]}}function h(t){var e=t.gl,r=L(e),n=C(e),i=S(e),o=z(e),s=p(e),l=g(e,[{buffer:s,size:4,stride:P,offset:0},{buffer:s,size:3,stride:P,offset:16},{buffer:s,size:3,stride:P,offset:28}]),c=p(e),u=g(e,[{buffer:c,size:4,stride:20,offset:0},{buffer:c,size:1,stride:20,offset:16}]),f=p(e),h=g(e,[{buffer:f,size:2,type:e.FLOAT}]),d=v(e,1,N,e.RGBA,e.UNSIGNED_BYTE);d.minFilter=e.LINEAR,d.magFilter=e.LINEAR;var m=new a(e,[0,0],[[0,0,0],[0,0,0]],r,n,s,l,d,i,o,c,u,f,h),y={levels:[[],[],[]]};for(var b in t)y[b]=t[b];return y.colormap=y.colormap||"jet",m.update(y),m}e.exports=h;var d=t("bit-twiddle"),p=t("gl-buffer"),g=t("gl-vao"),v=t("gl-texture2d"),m=t("typedarray-pool"),y=t("colormap"),b=t("ndarray-ops"),x=t("ndarray-pack"),_=t("ndarray"),w=t("surface-nets"),k=t("gl-mat4/multiply"),A=t("gl-mat4/invert"),M=t("binary-search-bounds"),T=t("ndarray-gradient"),E=t("./lib/shaders"),L=E.createShader,S=E.createContourShader,C=E.createPickShader,z=E.createPickContourShader,P=40,R=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],O=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],I=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];!function(){for(var t=0;3>t;++t){var e=I[t],r=(t+1)%3,n=(t+2)%3;e[r+0]=1,e[n+3]=1,e[t+6]=1}}();var N=265,j=a.prototype;j.isTransparent=function(){return this.opacity<1},j.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},j.pickSlots=1,j.setPickBase=function(t){this.pickId=t};var F=[0,0,0],D={showSurface:!1,showContour:!1,projections:[R.slice(),R.slice(),R.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]},B={model:R,view:R,projection:R,inverseModel:R.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1},U=R.slice(),V=[1,0,0,0,1,0,0,0,1];j.draw=function(t){return s.call(this,t,!1)},j.drawTransparent=function(t){return s.call(this,t,!0)};var q={model:R,view:R,projection:R,inverseModel:R,clipBounds:[[0,0,0],[0,0,0]],height:0,shape:[0,0],pickId:0,lowerBound:[0,0,0],upperBound:[0,0,0],zOffset:0,permutation:[1,0,0,0,1,0,0,0,1],lightPosition:[0,0,0],eyePosition:[0,0,0]};j.drawPick=function(t){t=t||{};var e=this.gl;e.disable(e.CULL_FACE);var r=q;r.model=t.model||R,r.view=t.view||R,r.projection=t.projection||R,r.shape=this._field[2].shape,r.pickId=this.pickId/255,r.lowerBound=this.bounds[0],r.upperBound=this.bounds[1],r.permutation=V;for(var n=0;2>n;++n)for(var i=r.clipBounds[n],a=0;3>a;++a)i[a]=Math.min(Math.max(this.clipBounds[n][a],-1e8),1e8);var s=o(r,this);if(s.showSurface){for(this._pickShader.bind(),this._pickShader.uniforms=r,this._vao.bind(),this._vao.draw(e.TRIANGLES,this._vertexCount),n=0;3>n;++n)this.surfaceProject[n]&&(this._pickShader.uniforms.model=s.projections[n],this._pickShader.uniforms.clipBounds=s.clipBounds[n],this._vao.draw(e.TRIANGLES,this._vertexCount));this._vao.unbind()}if(s.showContour){var l=this._contourPickShader;l.bind(),l.uniforms=r;var c=this._contourVAO;for(c.bind(),a=0;3>a;++a)for(e.lineWidth(this.contourWidth[a]),l.uniforms.permutation=I[a],n=0;nn;++n)for(l.uniforms.model=s.projections[n],l.uniforms.clipBounds=s.clipBounds[n],a=0;3>a;++a)if(this.contourProject[n][a]){l.uniforms.permutation=I[a],e.lineWidth(this.contourWidth[a]);for(var u=0;u>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var c=r.position;c[0]=c[1]=c[2]=0;for(var u=0;2>u;++u)for(var f=u?a:1-a,h=0;2>h;++h)for(var d=h?l:1-l,p=i+u,g=s+h,v=f*d,m=0;3>m;++m)c[m]+=this._field[m].get(p,g)*v;for(var y=this._pickResult.level,b=0;3>b;++b)if(y[b]=M.le(this.contourLevels[b],c[b]),y[b]<0)this.contourLevels[b].length>0&&(y[b]=0);else if(y[b]Math.abs(_-c[b])&&(y[b]+=1)}for(r.index[0]=.5>a?i:i+1,r.index[1]=.5>l?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1],m=0;3>m;++m)r.dataCoordinate[m]=this._field[m].get(r.index[0],r.index[1]);return r},j.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=c(t.contourWidth,Number)),"showContour"in t&&(this.showContour=c(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),"contourTint"in t&&(this.contourTint=c(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=f(t.contourColor)),"contourProject"in t&&(this.contourProject=c(t.contourProject,function(t){return c(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=f(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=c(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=c(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds);var e=t.field||t.coords&&t.coords[2]||null,r=!1;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var n=(e.shape[0]+2)*(e.shape[1]+2);n>this._field[2].data.length&&(m.freeFloat(this._field[2].data),this._field[2].data=m.mallocFloat(d.nextPow2(n))),this._field[2]=_(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),l(this._field[2],e),this.shape=e.shape.slice();for(var a=this.shape,o=0;2>o;++o)this._field[2].size>this._field[o].data.length&&(m.freeFloat(this._field[o].data),this._field[o].data=m.mallocFloat(this._field[2].size)),this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2]);if(t.coords){var s=t.coords;if(!Array.isArray(s)||3!==s.length)throw new Error("gl-surface: invalid coordinates for x/y");for(o=0;2>o;++o){var u=s[o];for(y=0;2>y;++y)if(u.shape[y]!==a[y])throw new Error("gl-surface: coords have incorrect shape");l(this._field[o],u)}}else if(t.ticks){var h=t.ticks;if(!Array.isArray(h)||2!==h.length)throw new Error("gl-surface: invalid ticks");for(o=0;2>o;++o){var p=h[o];if((Array.isArray(p)||p.length)&&(p=_(p)),p.shape[0]!==a[o])throw new Error("gl-surface: invalid tick length");var g=_(p.data,a);g.stride[o]=p.stride[0],g.stride[1^o]=0,l(this._field[o],g)}}else{for(o=0;2>o;++o){var v=[0,0];v[o]=1,this._field[o]=_(this._field[o].data,[a[0]+2,a[1]+2],v,0)}this._field[0].set(0,0,0);for(var y=0;yo;++o)T(x.pick(o),b[o],"mirror");var k=_(m.mallocFloat(3*b[2].size),[a[0]+2,a[1]+2,3]);for(o=0;oI?(I=Math.max(Math.abs(z),Math.abs(P),Math.abs(R)),1e-8>I?(R=1,P=z=0,I=1):I=1/I):I=1/Math.sqrt(I),k.set(o,y,0,z*I),k.set(o,y,1,P*I),k.set(o,y,2,R*I)}m.free(x.data);var N=[1/0,1/0,1/0],j=[-(1/0),-(1/0),-(1/0)],F=1/0,D=-(1/0),B=(a[0]-1)*(a[1]-1)*6,U=m.mallocFloat(d.nextPow2(10*B)),V=0,q=0;for(o=0;oH;++H)for(var G=0;2>G;++G)for(var Y=0;3>Y;++Y){var X=this._field[Y].get(1+o+H,1+y+G);if(isNaN(X)||!isFinite(X))continue t}for(Y=0;6>Y;++Y){var W=o+O[Y][0],Z=y+O[Y][1],K=this._field[0].get(W+1,Z+1),$=this._field[1].get(W+1,Z+1);X=this._field[2].get(W+1,Z+1);var Q=X;z=k.get(W+1,Z+1,0),P=k.get(W+1,Z+1,1),R=k.get(W+1,Z+1,2),t.intensity&&(Q=t.intensity.get(W,Z)),U[V++]=W,U[V++]=Z,U[V++]=K,U[V++]=$,U[V++]=X,U[V++]=0,U[V++]=Q,U[V++]=z,U[V++]=P,U[V++]=R,N[0]=Math.min(N[0],K),N[1]=Math.min(N[1],$),N[2]=Math.min(N[2],X),F=Math.min(F,Q),j[0]=Math.max(j[0],K),j[1]=Math.max(j[1],$),j[2]=Math.max(j[2],X),D=Math.max(D,Q),q+=1}}for(t.intensityBounds&&(F=+t.intensityBounds[0],D=+t.intensityBounds[1]),o=6;V>o;o+=10)U[o]=(U[o]-F)/(D-F);this._vertexCount=q,this._coordinateBuffer.update(U.subarray(0,V)),m.freeFloat(U),m.free(k.data),this.bounds=[N,j],this.intensity=t.intensity||this._field[2],this.intensityBounds[0]===F&&this.intensityBounds[1]===D||(r=!0),this.intensityBounds=[F,D]}if("levels"in t){var J=t.levels;for(J=Array.isArray(J[0])?J.slice():[[],[],J],o=0;3>o;++o)J[o]=J[o].slice(),J.sort(function(t,e){return t-e});t:for(o=0;3>o;++o){if(J[o].length!==this.contourLevels[o].length){r=!0;break}for(y=0;yet;++et){J=this.contourLevels[et];var rt=[],nt=[],it=[0,0,0];for(o=0;oY;++Y){var st=at.positions[ot[Y]],lt=st[0],ct=0|Math.floor(lt),ut=lt-ct,ft=st[1],ht=0|Math.floor(ft),dt=ft-ht,pt=!1; +e:for(var gt=0;3>gt;++gt){it[gt]=0;var vt=(et+gt+1)%3;for(H=0;2>H;++H){var mt=H?ut:1-ut;for(W=0|Math.min(Math.max(ct+H,0),a[0]),G=0;2>G;++G){var yt=G?dt:1-dt;if(Z=0|Math.min(Math.max(ht+G,0),a[1]),X=2>gt?this._field[vt].get(W,Z):(this.intensity.get(W,Z)-this.intensityBounds[0])/(this.intensityBounds[1]-this.intensityBounds[0]),!isFinite(X)||isNaN(X)){pt=!0;break e}var bt=mt*yt;it[gt]+=bt*X}}}if(pt){if(Y>0){for(var xt=0;5>xt;++xt)tt.pop();q-=1}continue t}tt.push(it[0],it[1],st[0],st[1],it[2]),q+=1}}nt.push(q)}this._contourOffsets[et]=rt,this._contourCounts[et]=nt}var _t=m.mallocFloat(tt.length);for(o=0;ot;++t)m.freeFloat(this._field[t].data)},j.highlight=function(t){if(!t)return this._dynamicCounts=[0,0,0],this.dyanamicLevel=[NaN,NaN,NaN],void(this.highlightLevel=[-1,-1,-1]);for(var e=0;3>e;++e)this.enableHighlight[e]?this.highlightLevel[e]=t.level[e]:this.highlightLevel[e]=-1;var r;if(r=this.snapToData?t.dataCoordinate:t.position,this.enableDynamic[0]&&r[0]!==this.dynamicLevel[0]||this.enableDynamic[1]&&r[1]!==this.dynamicLevel[1]||this.enableDynamic[2]&&r[2]!==this.dynamicLevel[2]){for(var n=0,i=this.shape,a=m.mallocFloat(12*i[0]*i[1]),o=0;3>o;++o)if(this.enableDynamic[o]){this.dynamicLevel[o]=r[o];var s=(o+1)%3,l=(o+2)%3,c=this._field[o],u=this._field[s],f=this._field[l],h=(this.intensity,w(c,r[o])),d=h.cells,p=h.positions;for(this._dynamicOffsets[o]=n,e=0;ev;++v){var y=p[g[v]],b=+y[0],x=0|b,_=0|Math.min(x+1,i[0]),k=b-x,A=1-k,M=+y[1],T=0|M,E=0|Math.min(T+1,i[1]),L=M-T,S=1-L,C=A*S,z=A*L,P=k*S,R=k*L,O=C*u.get(x,T)+z*u.get(x,E)+P*u.get(_,T)+R*u.get(_,E),I=C*f.get(x,T)+z*f.get(x,E)+P*f.get(_,T)+R*f.get(_,E);if(isNaN(O)||isNaN(I)){v&&(n-=1);break}a[2*n+0]=O,a[2*n+1]=I,n+=1}this._dynamicCounts[o]=n-this._dynamicOffsets[o]}else this.dynamicLevel[o]=NaN,this._dynamicCounts[o]=0;this._dynamicBuffer.update(a.subarray(0,2*n)),m.freeFloat(a)}}},{"./lib/shaders":216,"binary-search-bounds":217,"bit-twiddle":50,colormap:100,"gl-buffer":118,"gl-mat4/invert":137,"gl-mat4/multiply":139,"gl-texture2d":222,"gl-vao":226,ndarray:253,"ndarray-gradient":218,"ndarray-ops":252,"ndarray-pack":219,"surface-nets":272,"typedarray-pool":278}],222:[function(t,e,r){"use strict";function n(t){v=[t.LINEAR,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_NEAREST],m=[t.NEAREST,t.LINEAR,t.NEAREST_MIPMAP_NEAREST,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_LINEAR],y=[t.REPEAT,t.CLAMP_TO_EDGE,t.MIRRORED_REPEAT]}function i(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(0>e||e>i||0>r||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function a(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}function o(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function s(t,e,r,n,i,a,s,l){var c=l.dtype,u=l.shape.slice();if(u.length<2||u.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var f=0,h=0,v=o(u,l.stride.slice());"float32"===c?f=t.FLOAT:"float64"===c?(f=t.FLOAT,v=!1,c="float32"):"uint8"===c?f=t.UNSIGNED_BYTE:(f=t.UNSIGNED_BYTE,v=!1,c="uint8");var m=1;if(2===u.length)h=t.LUMINANCE,u=[u[0],u[1],1],l=d(l.data,u,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==u.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===u[2])h=t.ALPHA;else if(2===u[2])h=t.LUMINANCE_ALPHA;else if(3===u[2])h=t.RGB;else{if(4!==u[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");h=t.RGBA}m=u[2]}if(h!==t.LUMINANCE&&h!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(h=i),h!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=l.size,x=s.indexOf(n)<0;if(x&&s.push(n),f===a&&v)0===l.offset&&l.data.length===y?x?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,l.data):x?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,l.data.subarray(l.offset,l.offset+y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,l.data.subarray(l.offset,l.offset+y));else{var _;_=a===t.FLOAT?g.mallocFloat32(y):g.mallocUint8(y);var w=d(_,u,[u[2],u[2]*u[0],1]);f===t.FLOAT&&a===t.UNSIGNED_BYTE?b(w,l):p.assign(w,l),x?t.texImage2D(t.TEXTURE_2D,n,i,u[0],u[1],0,i,a,_.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,u[0],u[1],i,a,_.subarray(0,y)),a===t.FLOAT?g.freeFloat32(_):g.freeUint8(_)}}function l(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function c(t,e,r,n,i){var o=t.getParameter(t.MAX_TEXTURE_SIZE);if(0>e||e>o||0>r||r>o)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var s=l(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new a(t,s,e,r,n,i)}function u(t,e,r,n){var i=l(t);return t.texImage2D(t.TEXTURE_2D,0,r,r,n,e),new a(t,i,0|e.width,0|e.height,r,n)}function f(t,e){var r=e.dtype,n=e.shape.slice(),i=t.getParameter(t.MAX_TEXTURE_SIZE);if(n[0]<0||n[0]>i||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var s=o(n,e.stride.slice()),c=0;"float32"===r?c=t.FLOAT:"float64"===r?(c=t.FLOAT,s=!1,r="float32"):"uint8"===r?c=t.UNSIGNED_BYTE:(c=t.UNSIGNED_BYTE,s=!1,r="uint8");var u=0;if(2===n.length)u=t.LUMINANCE,n=[n[0],n[1],1],e=d(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])u=t.ALPHA;else if(2===n[2])u=t.LUMINANCE_ALPHA;else if(3===n[2])u=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");u=t.RGBA}}c!==t.FLOAT||t.getExtension("OES_texture_float")||(c=t.UNSIGNED_BYTE,s=!1);var f,h,v=e.size;if(s)f=0===e.offset&&e.data.length===v?e.data:e.data.subarray(e.offset,e.offset+v);else{var m=[n[2],n[2]*n[0],1];h=g.malloc(v,r);var y=d(h,n,m,0);"float32"!==r&&"float64"!==r||c!==t.UNSIGNED_BYTE?p.assign(y,e):b(y,e),f=h.subarray(0,v)}var x=l(t);return t.texImage2D(t.TEXTURE_2D,0,u,n[0],n[1],0,u,c,f),s||g.free(h),new a(t,x,n[0],n[1],u,c)}function h(t){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(v||n(t),"number"==typeof arguments[1])return c(t,arguments[1],arguments[2],arguments[3]||t.RGBA,arguments[4]||t.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return c(t,0|arguments[1][0],0|arguments[1][1],arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if("object"==typeof arguments[1]){var e=arguments[1];if(e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e instanceof ImageData)return u(t,e,arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return f(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}var d=t("ndarray"),p=t("ndarray-ops"),g=t("typedarray-pool");e.exports=h;var v=null,m=null,y=null,b=function(t,e){p.muls(t,e,255)},x=a.prototype;Object.defineProperties(x,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;2>e;++e)if(y.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return i(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return t=0|t,i(this,t,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t=0|t,i(this,this._shape[0],t),t}}}),x.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},x.dispose=function(){this.gl.deleteTexture(this.handle)},x.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},x.setPixels=function(t,e,r,n){var i=this.gl;if(this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0,t instanceof HTMLCanvasElement||t instanceof ImageData||t instanceof HTMLImageElement||t instanceof HTMLVideoElement){var a=this._mipLevels.indexOf(n)<0;a?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,t),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,t)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||0>e||0>r)throw new Error("gl-texture2d: Texture dimensions are out of bounds");s(i,e,r,n,this.format,this.type,this._mipLevels,t)}}},{ndarray:253,"ndarray-ops":252,"typedarray-pool":278}],223:[function(t,e,r){"use strict";function n(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;ii;++i)t.disableVertexAttribArray(i)}else{t.bindBuffer(t.ARRAY_BUFFER,null);for(var i=0;n>i;++i)t.disableVertexAttribArray(i)}}e.exports=n},{}],224:[function(t,e,r){"use strict";function n(t){this.gl=t,this._elements=null,this._attributes=null,this._elementsType=t.UNSIGNED_SHORT}function i(t){return new n(t)}var a=t("./do-bind.js");n.prototype.bind=function(){a(this.gl,this._elements,this._attributes)},n.prototype.update=function(t,e,r){this._elements=e,this._attributes=t,this._elementsType=r||this.gl.UNSIGNED_SHORT},n.prototype.dispose=function(){},n.prototype.unbind=function(){},n.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._elements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=i},{"./do-bind.js":223}],225:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.location=t,this.dimension=e,this.a=r,this.b=n,this.c=i,this.d=a}function i(t,e,r){this.gl=t,this._ext=e,this.handle=r,this._attribs=[],this._useElements=!1,this._elementsType=t.UNSIGNED_SHORT}function a(t,e){return new i(t,e,e.createVertexArrayOES())}var o=t("./do-bind.js");n.prototype.bind=function(t){switch(this.dimension){case 1:t.vertexAttrib1f(this.location,this.a);break;case 2:t.vertexAttrib2f(this.location,this.a,this.b);break;case 3:t.vertexAttrib3f(this.location,this.a,this.b,this.c);break;case 4:t.vertexAttrib4f(this.location,this.a,this.b,this.c,this.d)}},i.prototype.bind=function(){this._ext.bindVertexArrayOES(this.handle);for(var t=0;tF;){switch(e=F,B){case f:F=L();break;case h:F=E();break;case d:F=T();break;case p:F=S();break;case g:F=P();break;case w:F=z();break;case v:F=R();break;case u:F=O();break;case x:F=M();break;case c:F=A()}if(e!==F)switch(W[e]){case"\n":H=0,++q;break;default:++H}}return D+=F,W=W.slice(F),V}function n(t){return U.length&&e(U.join("")),B=_,e("(eof)"),V}function A(){return U=U.length?[]:U,"/"===N&&"*"===I?(G=D+F-1,B=f,N=I,F+1):"/"===N&&"/"===I?(G=D+F-1,B=h,N=I,F+1):"#"===I?(B=d,G=D+F,F):/\s/.test(I)?(B=x,G=D+F,F):(Y=/\d/.test(I),X=/[^\w_]/.test(I),G=D+F,B=Y?g:X?p:u,F)}function M(){return/[^\s]/g.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function T(){return"\n"===I&&"\\"!==N?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function E(){return T()}function L(){return"/"===I&&"*"===N?(U.push(I),e(U.join("")),B=c,F+1):(U.push(I),N=I,F+1)}function S(){if("."===N&&/\d/.test(I))return B=v,F;if("/"===N&&"*"===I)return B=f,F;if("/"===N&&"/"===I)return B=h,F;if("."===I&&U.length){for(;C(U););return B=v,F}if(";"===I||")"===I||"("===I){if(U.length)for(;C(U););return e(I),B=c,F+1}var t=2===U.length&&"="!==I;if(/[\w_\d\s]/.test(I)||t){for(;C(U););return B=c,F}return U.push(I),N=I,F+1}function C(t){for(var r,n,i=0;;){if(r=a.indexOf(t.slice(0,t.length+i).join("")),n=a[r],-1===r){if(i--+t.length>0)continue;n=t.slice(0,1).join("")}return e(n),G+=n.length,U=U.slice(n.length),U.length}}function z(){return/[^a-fA-F0-9]/.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function P(){return"."===I?(U.push(I),B=v,N=I,F+1):/[eE]/.test(I)?(U.push(I),B=v,N=I,F+1):"x"===I&&1===U.length&&"0"===U[0]?(B=w,U.push(I),N=I,F+1):/[^\d]/.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function R(){return"f"===I&&(U.push(I),N=I,F+=1),/[eE]/.test(I)?(U.push(I),N=I,F+1):"-"===I&&/[eE]/.test(N)?(U.push(I),N=I,F+1):/[^\d]/.test(I)?(e(U.join("")),B=c,F):(U.push(I),N=I,F+1)}function O(){if(/[^\d\w_]/.test(I)){var t=U.join("");return B=K.indexOf(t)>-1?b:Z.indexOf(t)>-1?y:m,e(U.join("")),B=c,F}return U.push(I),N=I,F+1}var I,N,j,F=0,D=0,B=c,U=[],V=[],q=1,H=0,G=0,Y=!1,X=!1,W="";t=t||{};var Z=o,K=i;return"300 es"===t.version&&(Z=l,K=s),function(t){return V=[],null!==t?r(t):n()}}e.exports=n;var i=t("./lib/literals"),a=t("./lib/operators"),o=t("./lib/builtins"),s=t("./lib/literals-300es"),l=t("./lib/builtins-300es"),c=999,u=9999,f=0,h=1,d=2,p=3,g=4,v=5,m=6,y=7,b=8,x=9,_=10,w=11,k=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":230,"./lib/builtins-300es":229,"./lib/literals":232,"./lib/literals-300es":231,"./lib/operators":233}],229:[function(t,e,r){var n=t("./builtins");n=n.slice().filter(function(t){return!/^(gl\_|texture)/.test(t)}),e.exports=n.concat(["gl_VertexID","gl_InstanceID","gl_Position","gl_PointSize","gl_FragCoord","gl_FrontFacing","gl_FragDepth","gl_PointCoord","gl_MaxVertexAttribs","gl_MaxVertexUniformVectors","gl_MaxVertexOutputVectors","gl_MaxFragmentInputVectors","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformVectors","gl_MaxDrawBuffers","gl_MinProgramTexelOffset","gl_MaxProgramTexelOffset","gl_DepthRangeParameters","gl_DepthRange","trunc","round","roundEven","isnan","isinf","floatBitsToInt","floatBitsToUint","intBitsToFloat","uintBitsToFloat","packSnorm2x16","unpackSnorm2x16","packUnorm2x16","unpackUnorm2x16","packHalf2x16","unpackHalf2x16","outerProduct","transpose","determinant","inverse","texture","textureSize","textureProj","textureLod","textureOffset","texelFetch","texelFetchOffset","textureProjOffset","textureLodOffset","textureProjLod","textureProjLodOffset","textureGrad","textureGradOffset","textureProjGrad","textureProjGradOffset"])},{"./builtins":230}],230:[function(t,e,r){e.exports=["abs","acos","all","any","asin","atan","ceil","clamp","cos","cross","dFdx","dFdy","degrees","distance","dot","equal","exp","exp2","faceforward","floor","fract","gl_BackColor","gl_BackLightModelProduct","gl_BackLightProduct","gl_BackMaterial","gl_BackSecondaryColor","gl_ClipPlane","gl_ClipVertex","gl_Color","gl_DepthRange","gl_DepthRangeParameters","gl_EyePlaneQ","gl_EyePlaneR","gl_EyePlaneS","gl_EyePlaneT","gl_Fog","gl_FogCoord","gl_FogFragCoord","gl_FogParameters","gl_FragColor","gl_FragCoord","gl_FragData","gl_FragDepth","gl_FragDepthEXT","gl_FrontColor","gl_FrontFacing","gl_FrontLightModelProduct","gl_FrontLightProduct","gl_FrontMaterial","gl_FrontSecondaryColor","gl_LightModel","gl_LightModelParameters","gl_LightModelProducts","gl_LightProducts","gl_LightSource","gl_LightSourceParameters","gl_MaterialParameters","gl_MaxClipPlanes","gl_MaxCombinedTextureImageUnits","gl_MaxDrawBuffers","gl_MaxFragmentUniformComponents","gl_MaxLights","gl_MaxTextureCoords","gl_MaxTextureImageUnits","gl_MaxTextureUnits","gl_MaxVaryingFloats","gl_MaxVertexAttribs","gl_MaxVertexTextureImageUnits","gl_MaxVertexUniformComponents","gl_ModelViewMatrix","gl_ModelViewMatrixInverse","gl_ModelViewMatrixInverseTranspose","gl_ModelViewMatrixTranspose","gl_ModelViewProjectionMatrix","gl_ModelViewProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixTranspose","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_Normal","gl_NormalMatrix","gl_NormalScale","gl_ObjectPlaneQ","gl_ObjectPlaneR","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_Point","gl_PointCoord","gl_PointParameters","gl_PointSize","gl_Position","gl_ProjectionMatrix","gl_ProjectionMatrixInverse","gl_ProjectionMatrixInverseTranspose","gl_ProjectionMatrixTranspose","gl_SecondaryColor","gl_TexCoord","gl_TextureEnvColor","gl_TextureMatrix","gl_TextureMatrixInverse","gl_TextureMatrixInverseTranspose","gl_TextureMatrixTranspose","gl_Vertex","greaterThan","greaterThanEqual","inversesqrt","length","lessThan","lessThanEqual","log","log2","matrixCompMult","max","min","mix","mod","normalize","not","notEqual","pow","radians","reflect","refract","sign","sin","smoothstep","sqrt","step","tan","texture2D","texture2DLod","texture2DProj","texture2DProjLod","textureCube","textureCubeLod","texture2DLodEXT","texture2DProjLodEXT","textureCubeLodEXT","texture2DGradEXT","texture2DProjGradEXT","textureCubeGradEXT"]},{}],231:[function(t,e,r){var n=t("./literals");e.exports=n.slice().concat(["layout","centroid","smooth","case","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","uint","uvec2","uvec3","uvec4","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","coherent","restrict","readonly","writeonly","resource","atomic_uint","noperspective","patch","sample","subroutine","common","partition","active","filter","image1D","image2D","image3D","imageCube","iimage1D","iimage2D","iimage3D","iimageCube","uimage1D","uimage2D","uimage3D","uimageCube","image1DArray","image2DArray","iimage1DArray","iimage2DArray","uimage1DArray","uimage2DArray","image1DShadow","image2DShadow","image1DArrayShadow","image2DArrayShadow","imageBuffer","iimageBuffer","uimageBuffer","sampler1DArray","sampler1DArrayShadow","isampler1D","isampler1DArray","usampler1D","usampler1DArray","isampler2DRect","usampler2DRect","samplerBuffer","isamplerBuffer","usamplerBuffer","sampler2DMS","isampler2DMS","usampler2DMS","sampler2DMSArray","isampler2DMSArray","usampler2DMSArray"])},{"./literals":232}],232:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],233:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],234:[function(t,e,r){function n(t,e){var r=i(e),n=[];return n=n.concat(r(t)),n=n.concat(r(null))}var i=t("./index");e.exports=n},{"./index":228}],235:[function(t,e,r){"use strict";function n(t,e,r){this.vertices=t,this.adjacent=e,this.boundary=r,this.lastVisited=-1}function i(t,e,r){this.vertices=t,this.cell=e,this.index=r}function a(t,e){return u(t.vertices,e.vertices)}function o(t){for(var e=["function orient(){var tuple=this.tuple;return test("],r=0;t>=r;++r)r>0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=c[t+1];return i||(i=c),n(i)}function s(t,e,r){this.dimension=t,this.vertices=e,this.simplices=r,this.interior=r.filter(function(t){return!t.boundary}),this.tuple=new Array(t+1);for(var n=0;t>=n;++n)this.tuple[n]=this.vertices[n];var i=f[t];i||(i=f[t]=o(t)),this.orient=i}function l(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(i>=r)throw new Error("Must input at least d+1 points");var a=t.slice(0,i+1),o=c.apply(void 0,a);if(0===o)throw new Error("Input not in general position");for(var l=new Array(i+1),u=0;i>=u;++u)l[u]=u;0>o&&(l[0]=1,l[1]=0);for(var f=new n(l,new Array(i+1),!1),h=f.adjacent,d=new Array(i+2),u=0;i>=u;++u){for(var p=l.slice(),g=0;i>=g;++g)g===u&&(p[g]=-1);var v=p[0];p[0]=p[1],p[1]=v;var m=new n(p,new Array(i+1),!0);h[u]=m,d[u]=m}d[i+1]=f;for(var u=0;i>=u;++u)for(var p=h[u].vertices,y=h[u].adjacent,g=0;i>=g;++g){var b=p[g];if(0>b)y[g]=f;else for(var x=0;i>=x;++x)h[x].vertices.indexOf(b)<0&&(y[g]=h[x])}for(var _=new s(i,a,d),w=!!e,u=i+1;r>u;++u)_.insert(t[u],w);return _.boundary()}e.exports=l;var c=t("robust-orientation"),u=t("simplicial-complex").compareCells;n.prototype.flip=function(){var t=this.vertices[0];this.vertices[0]=this.vertices[1],this.vertices[1]=t;var e=this.adjacent[0];this.adjacent[0]=this.adjacent[1],this.adjacent[1]=e};var f=[],h=s.prototype;h.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){t=o.pop();for(var s=(t.vertices,t.adjacent),l=0;r>=l;++l){var c=s[l];if(c.boundary&&!(c.lastVisited<=-n)){for(var u=c.vertices,f=0;r>=f;++f){var h=u[f];0>h?i[f]=e:i[f]=a[h]}var d=this.orient();if(d>0)return c;c.lastVisited=-n,0===d&&o.push(c)}}}return null},h.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,c=s.adjacent,u=0;n>=u;++u)a[u]=i[l[u]];s.lastVisited=r;for(var u=0;n>=u;++u){var f=c[u];if(!(f.lastVisited>=r)){var h=a[u];a[u]=t;var d=this.orient();if(a[u]=h,0>d){s=f;continue t}f.boundary?f.lastVisited=-r:f.lastVisited=r}}return}return s},h.addPeaks=function(t,e){var r=this.vertices.length-1,o=this.dimension,s=this.vertices,l=this.tuple,c=this.interior,u=this.simplices,f=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,c.push(e);for(var h=[];f.length>0;){var e=f.pop(),d=e.vertices,p=e.adjacent,g=d.indexOf(r);if(!(0>g))for(var v=0;o>=v;++v)if(v!==g){var m=p[v];if(m.boundary&&!(m.lastVisited>=r)){var y=m.vertices;if(m.lastVisited!==-r){for(var b=0,x=0;o>=x;++x)y[x]<0?(b=x,l[x]=t):l[x]=s[y[x]];var _=this.orient();if(_>0){y[b]=r,m.boundary=!1,c.push(m),f.push(m),m.lastVisited=r;continue}m.lastVisited=-r}var w=m.adjacent,k=d.slice(),A=p.slice(),M=new n(k,A,!0);u.push(M);var T=w.indexOf(e);if(!(0>T)){w[T]=M,A[g]=m,k[v]=-1,A[v]=e,p[v]=M,M.flip();for(var x=0;o>=x;++x){var E=k[x];if(!(0>E||E===r)){for(var L=new Array(o-1),S=0,C=0;o>=C;++C){var z=k[C];0>z||C===x||(L[S++]=z)}h.push(new i(L,M,x))}}}}}}h.sort(a);for(var v=0;v+1O||0>I||(P.cell.adjacent[P.index]=R.cell,R.cell.adjacent[R.index]=P.cell)}},h.insert=function(t,e){var r=this.vertices;r.push(t);var n=this.walk(t,e);if(n){for(var i=this.dimension,a=this.tuple,o=0;i>=o;++o){var s=n.vertices[o];0>s?a[o]=t:a[o]=r[s]}var l=this.orient(a);0>l||(0!==l||(n=this.handleBoundaryDegeneracy(n,t)))&&this.addPeaks(t,n)}},h.boundary=function(){for(var t=this.dimension,e=[],r=this.simplices,n=r.length,i=0;n>i;++i){var a=r[i];if(a.boundary){for(var o=new Array(t),s=a.vertices,l=0,c=0,u=0;t>=u;++u)s[u]>=0?o[l++]=s[u]:c=1&u;if(c===(1&t)){var f=o[0];o[0]=o[1],o[1]=f}e.push(o)}}return e}},{"robust-orientation":259,"simplicial-complex":238}],236:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],237:[function(t,e,r){arguments[4][97][0].apply(r,arguments)},{dup:97}],238:[function(t,e,r){"use strict";"use restrict";function n(t){for(var e=0,r=Math.max,n=0,i=t.length;i>n;++n)e=r(e,t[n].length);return e-1}function i(t){for(var e=-1,r=Math.max,n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)e=r(e,a[o]);return e+1}function a(t){for(var e=new Array(t.length),r=0,n=t.length;n>r;++r)e[r]=t[r].slice(0);return e}function o(t,e){var r=t.length,n=t.length-e.length,i=Math.min;if(n)return n;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:var a=t[0]+t[1]-e[0]-e[1];return a?a:i(t[0],t[1])-i(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=i(t[0],t[1]),c=i(e[0],e[1]),a=i(l,t[2])-i(c,e[2]);return a?a:i(l+t[2],o)-i(c+e[2],s);default:var u=t.slice(0);u.sort();var f=e.slice(0);f.sort();for(var h=0;r>h;++h)if(n=u[h]-f[h])return n;return 0}}function s(t,e){return o(t[0],e[0])}function l(t,e){if(e){for(var r=t.length,n=new Array(r),i=0;r>i;++i)n[i]=[t[i],e[i]];n.sort(s);for(var i=0;r>i;++i)t[i]=n[i][0],e[i]=n[i][1];return t}return t.sort(o),t}function c(t){if(0===t.length)return[];for(var e=1,r=t.length,n=1;r>n;++n){var i=t[n];if(o(i,t[n-1])){if(n===e){e++;continue}t[e++]=i}}return t.length=e,t}function u(t,e){for(var r=0,n=t.length-1,i=-1;n>=r;){var a=r+n>>1,s=o(t[a],e);0>=s?(0===s&&(i=a),r=a+1):s>0&&(n=a-1)}return i}function f(t,e){for(var r=new Array(t.length),n=0,i=r.length;i>n;++n)r[n]=[];for(var a=[],n=0,s=e.length;s>n;++n)for(var l=e[n],c=l.length,f=1,h=1<f;++f){a.length=b.popCount(f);for(var d=0,p=0;c>p;++p)f&1<g))for(;;)if(r[g++].push(n),g>=t.length||0!==o(t[g],a))break}return r}function h(t,e){if(!e)return f(c(p(t,0)),t,0);for(var r=new Array(e),n=0;e>n;++n)r[n]=[];for(var n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)r[a[o]].push(n);return r}function d(t){for(var e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0|i.length,o=1,s=1<o;++o){for(var c=[],u=0;a>u;++u)o>>>u&1&&c.push(i[u]);e.push(c)}return l(e)}function p(t,e){if(0>e)return[];for(var r=[],n=(1<r;++r)for(var i=t[r],a=0,o=i.length;o>a;++a){for(var s=new Array(i.length-1),c=0,u=0;o>c;++c)c!==a&&(s[u++]=i[c]);e.push(s)}return l(e)}function v(t,e){for(var r=new x(e),n=0;nr;++r)e[r]=r;return e}e.exports=n},{}],240:[function(t,e,r){e.exports=function(t){return!(null==t||!(t._isBuffer||t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)))}},{}],241:[function(t,e,r){"use strict";function n(t,e){function r(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==g.alt,g.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==g.shift,g.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==g.control,g.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==g.meta,g.meta=!!t.metaKey),e}function n(t,n){var a=i.x(n),o=i.y(n);"buttons"in n&&(t=0|n.buttons),(t!==h||a!==d||o!==p||r(n))&&(h=0|t,d=a||0,p=o||0,e(h,d,p,g))}function a(t){n(0,t)}function o(){(h||d||p||g.shift||g.alt||g.meta||g.control)&&(d=p=0,h=0,g.shift=g.alt=g.control=g.meta=!1,e(0,0,0,g))}function s(t){r(t)&&e(h,d,p,g)}function l(t){0===i.buttons(t)?n(0,t):n(h,t)}function c(t){n(h|i.buttons(t),t)}function u(t){n(h&~i.buttons(t),t)}function f(){v||(v=!0,t.addEventListener("mousemove",l),t.addEventListener("mousedown",c),t.addEventListener("mouseup",u),t.addEventListener("mouseleave",a),t.addEventListener("mouseenter",a),t.addEventListener("mouseout",a),t.addEventListener("mouseover",a),t.addEventListener("blur",o),t.addEventListener("keyup",s),t.addEventListener("keydown",s),t.addEventListener("keypress",s),t!==window&&(window.addEventListener("blur",o),window.addEventListener("keyup",s),window.addEventListener("keydown",s),window.addEventListener("keypress",s)))}e||(e=t,t=window);var h=0,d=0,p=0,g={shift:!1,alt:!1,control:!1,meta:!1},v=!1;f();var m={element:t};return Object.defineProperties(m,{enabled:{get:function(){return v},set:function(t){t&&f()},enumerable:!0},buttons:{get:function(){return h},enumerable:!0},x:{get:function(){return d},enumerable:!0},y:{get:function(){return p},enumerable:!0},mods:{get:function(){return g},enumerable:!0}}),m}e.exports=n;var i=t("mouse-event")},{"mouse-event":242}],242:[function(t,e,r){"use strict";function n(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){var e=t.which;if(2===e)return 4;if(3===e)return 2;if(e>0)return 1<=0)return 1<=0&&r=0&&r+1=0&&n=0&&n+1=0&&s=0&&s+1=0&&i=0&&i+1=0&&l=0&&l+1=0&&h=0&&h+1e;++e)r=+arguments[e+1],i[e]=Math.floor(r),a[e]=r-i[e],o[e]=0<=i[e]&&i[e]e;++e){for(c=1,u=t.offset,l=0;n>l;++l)if(e&1<r;++r){t[r]=o[(n+1)*n+r];for(var i=0;n>i;++i)t[r]+=o[(n+1)*i+r]*e[i]}for(var a=o[(n+1)*(n+1)-1],i=0;n>i;++i)a+=o[(n+1)*i+n]*e[i];for(var s=1/a,r=0;n>r;++r)t[r]*=s;return t}),t}var i=t("ndarray-warp"),a=t("gl-matrix-invert");e.exports=n},{"gl-matrix-invert":247,"ndarray-warp":250}],252:[function(t,e,r){"use strict";function n(t){if(!t)return s;for(var e=0;e>",rrshift:">>>"};!function(){for(var t in l){var e=l[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var c={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in c){var e=c[t];r[t]=a({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=a({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var u={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in u){var e=u[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var f=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;tthis_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=o({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=o({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=a({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=a({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=a({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=o({args:["array","array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":109}],253:[function(t,e,r){function n(t,e){return t[0]-e[0]}function i(){var t,e=this.stride,r=new Array(e.length);for(t=0;te&&(r="View_Nil"+t);var n="generic"===t;if(-1===e){var a="function "+r+"(a){this.data=a;};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+r+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+r+"(a){return new "+r+"(a);}",o=new Function(a);return o()}if(0===e){var a="function "+r+"(a,d) {this.data = a;this.offset = d};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+r+"_copy() {return new "+r+"(this.data,this.offset)};proto.pick=function "+r+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+r+"_get(){return "+(n?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+r+"_set(v){return "+(n?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+r+"(a,b,c,d){return new "+r+"(a,d)}",o=new Function("TrivialArray",a);return o(f[t][0])}var a=["'use strict'"],s=l(e),c=s.map(function(t){return"i"+t}),u="this.offset+"+s.map(function(t){return"this.stride["+t+"]*i"+t}).join("+"),h=s.map(function(t){return"b"+t}).join(","),d=s.map(function(t){return"c"+t}).join(",");a.push("function "+r+"(a,"+h+","+d+",d){this.data=a","this.shape=["+h+"]","this.stride=["+d+"]","this.offset=d|0}","var proto="+r+".prototype","proto.dtype='"+t+"'","proto.dimension="+e),a.push("Object.defineProperty(proto,'size',{get:function "+r+"_size(){return "+s.map(function(t){return"this.shape["+t+"]"}).join("*"),"}})"),1===e?a.push("proto.order=[0]"):(a.push("Object.defineProperty(proto,'order',{get:"),4>e?(a.push("function "+r+"_order(){"),2===e?a.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+c.join(",")+",v){"),n?a.push("return this.data.set("+u+",v)}"):a.push("return this.data["+u+"]=v}"),a.push("proto.get=function "+r+"_get("+c.join(",")+"){"),n?a.push("return this.data.get("+u+")}"):a.push("return this.data["+u+"]}"),a.push("proto.index=function "+r+"_index(",c.join(),"){return "+u+"}"),a.push("proto.hi=function "+r+"_hi("+c.join(",")+"){return new "+r+"(this.data,"+s.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+s.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var p=s.map(function(t){return"a"+t+"=this.shape["+t+"]"}),g=s.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+c.join(",")+"){var b=this.offset,d=0,"+p.join(",")+","+g.join(","));for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){d=i"+v+"|0;b+=c"+v+"*d;a"+v+"-=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+c.join(",")+"){var "+s.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+s.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'){d=i"+v+"|0;if(d<0){c+=b"+v+"*(a"+v+"-1);a"+v+"=ceil(-a"+v+"/d)}else{a"+v+"=ceil(a"+v+"/d)}b"+v+"*=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"b"+t}).join(",")+",c)}");for(var m=new Array(e),y=new Array(e),v=0;e>v;++v)m[v]="a[i"+v+"]",y[v]="b[i"+v+"]";a.push("proto.transpose=function "+r+"_transpose("+c+"){"+c.map(function(t,e){return t+"=("+t+"===undefined?"+e+":"+t+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+r+"(this.data,"+m.join(",")+","+y.join(",")+",this.offset)}"),a.push("proto.pick=function "+r+"_pick("+c+"){var a=[],b=[],c=this.offset");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){c=(c+this.stride["+v+"]*i"+v+")|0}else{a.push(this.shape["+v+"]);b.push(this.stride["+v+"])}");a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+s.map(function(t){return"shape["+t+"]"}).join(",")+","+s.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}");var o=new Function("CTOR_LIST","ORDER",a.join("\n"));return o(f[t],i)}function o(t){if(c(t))return"buffer";if(u)switch(Object.prototype.toString.call(t)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(t)?"array":"generic"}function s(t,e,r,n){if(void 0===t){var i=f.array[0];return i([])}"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var s=e.length;if(void 0===r){r=new Array(s);for(var l=s-1,c=1;l>=0;--l)r[l]=c,c*=e[l]}if(void 0===n){n=0;for(var l=0;s>l;++l)r[l]<0&&(n-=(e[l]-1)*r[l])}for(var u=o(t),h=f[u];h.length<=s+1;)h.push(a(u,h.length-1));var i=h[s+1];return i(t,e,r,n)}var l=t("iota-array"),c=t("is-buffer"),u="undefined"!=typeof Float64Array,f={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=s},{"iota-array":239,"is-buffer":240}],254:[function(t,e,r){"use strict";function n(t,e){if("string"!=typeof t)throw new TypeError("repeat-string expects a string.");if(1===e)return t;if(2===e)return t+t;var r=t.length*e;for(i===t&&"undefined"!=typeof i||(i=t,a="");r>a.length&&e>0&&(1&e&&(a+=t),e>>=1);)t+=t;return a.substr(0,r)}var i,a="";e.exports=n},{}],255:[function(t,e,r){(function(t){e.exports=t.performance&&t.performance.now?function(){return performance.now()}:Date.now||function(){return+new Date}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],256:[function(t,e,r){"use strict";function n(t){for(var e="robustLinearSolve"+t+"d",r=["function ",e,"(A,b){return ["],n=0;t>n;++n){r.push("det([");for(var i=0;t>i;++i){i>0&&r.push(","),r.push("[");for(var a=0;t>a;++a)a>0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(6>t?s[t]:s)}function i(){return[0]}function a(t,e){return[[e[0]],[t[0][0]]]}function o(){for(;c.lengthi;++i)t.push("s"+i),r.push("case ",i,":return s",i,"(A,b);");r.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve"),t.push("CACHE","g",r.join(""));var a=Function.apply(void 0,t);e.exports=a.apply(void 0,c.concat([c,n]));for(var i=0;l>i;++i)e.exports[i]=c[i]}var s=t("robust-determinant"),l=6,c=[i,a];o()},{"robust-determinant":258}],257:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=t[t.length-1],n=e,i=e-2;i>=0;--i){var a=r,o=t[i];r=a+o;var s=r-a,l=o-s;l&&(t[--n]=r,r=l)}for(var c=0,i=n;e>i;++i){var a=t[i],o=r;r=a+o;var s=r-a,l=o-s;l&&(t[c++]=l)}return t[c++]=r,t.length=c,t}e.exports=n},{}],258:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m[",r,"][",n,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("");for(var e=[],r=0;rn;++n)t.push("det"+n),r.push("case ",n,":return det",n,"(m);");r.push("}var det=CACHE[m.length];if(!det)det=CACHE[m.length]=gen(m.length);return det(m);}return robustDeterminant"),t.push("CACHE","gen",r.join(""));var i=Function.apply(void 0,t);e.exports=i.apply(void 0,g.concat([g,l]));for(var n=0;nr;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-1,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;rc;++c)0===(1&c)?e.push.apply(e,s(n(a,c))):r.push.apply(r,s(n(a,c))),l.push("m"+c);var u=o(e),g=o(r),v="orientation"+t+"Exact",m=["function ",v,"(",l.join(),"){var p=",u,",n=",g,",d=sub(p,n);return d[d.length-1];};return ",v].join(""),y=new Function("sum","prod","scale","sub",m);return y(h,f,d,p)}function c(t){var e=_[t.length];return e||(e=_[t.length]=l(t.length)),e.apply(void 0,t)}function u(){for(;_.length<=g;)_.push(l(_.length));for(var t=[],r=["slow"],n=0;g>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;g>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i=n;++n)e.exports[n]=_[n]}var f=t("two-product"),h=t("robust-sum"),d=t("robust-scale"),p=t("robust-subtract"),g=5,v=1.1102230246251565e-16,m=(3+16*v)*v,y=(7+56*v)*v,b=l(3),x=l(4),_=[function(){return 0},function(){return 0},function(t,e){return e[0]-t[0]},function(t,e,r){var n,i=(t[1]-r[1])*(e[0]-r[0]),a=(t[0]-r[0])*(e[1]-r[1]),o=i-a;if(i>0){if(0>=a)return o;n=i+a}else{if(!(0>i))return o;if(a>=0)return o;n=-(i+a)}var s=m*n;return o>=s||-s>=o?o:b(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],c=r[1]-n[1],u=t[2]-n[2],f=e[2]-n[2],h=r[2]-n[2],d=a*c,p=o*l,g=o*s,v=i*c,m=i*l,b=a*s,_=u*(d-p)+f*(g-v)+h*(m-b),w=(Math.abs(d)+Math.abs(p))*Math.abs(u)+(Math.abs(g)+Math.abs(v))*Math.abs(f)+(Math.abs(m)+Math.abs(b))*Math.abs(h),k=y*w; +return _>k||-_>k?_:x(t,e,r,n)}];u()},{"robust-scale":260,"robust-subtract":261,"robust-sum":262,"two-product":276}],260:[function(t,e,r){"use strict";function n(t,e){var r=t.length;if(1===r){var n=i(t[0],e);return n[0]?n:[n[1]]}var o=new Array(2*r),s=[.1,.1],l=[.1,.1],c=0;i(t[0],e,s),s[0]&&(o[c++]=s[0]);for(var u=1;r>u;++u){i(t[u],e,l);var f=s[1];a(f,l[0],s),s[0]&&(o[c++]=s[0]);var h=l[1],d=s[1],p=h+d,g=p-h,v=d-g;s[1]=p,v&&(o[c++]=v)}return s[1]&&(o[c++]=s[1]),0===c&&(o[c++]=0),o.length=c,o}var i=t("two-product"),a=t("two-sum");e.exports=n},{"two-product":276,"two-sum":277}],261:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],-e[0]);var a,o,s=r+i,l=new Array(s),c=0,u=0,f=0,h=Math.abs,d=t[u],p=h(d),g=-e[f],v=h(g);v>p?(o=d,u+=1,r>u&&(d=t[u],p=h(d))):(o=g,f+=1,i>f&&(g=-e[f],v=h(g))),r>u&&v>p||f>=i?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>u&&i>f;)v>p?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=-e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>u;)a=d,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,u+=1,r>u&&(d=t[u]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=-e[f]);return M&&(l[c++]=M),T&&(l[c++]=T),c||(l[c++]=0),l.length=c,l}e.exports=i},{}],262:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],e[0]);var a,o,s=r+i,l=new Array(s),c=0,u=0,f=0,h=Math.abs,d=t[u],p=h(d),g=e[f],v=h(g);v>p?(o=d,u+=1,r>u&&(d=t[u],p=h(d))):(o=g,f+=1,i>f&&(g=e[f],v=h(g))),r>u&&v>p||f>=i?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=e[f],v=h(g)));for(var m,y,b,x,_,w=a+o,k=w-a,A=o-k,M=A,T=w;r>u&&i>f;)v>p?(a=d,u+=1,r>u&&(d=t[u],p=h(d))):(a=g,f+=1,i>f&&(g=e[f],v=h(g))),o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>u;)a=d,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,u+=1,r>u&&(d=t[u]);for(;i>f;)a=g,o=M,w=a+o,k=w-a,A=o-k,A&&(l[c++]=A),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,f+=1,i>f&&(g=e[f]);return M&&(l[c++]=M),T&&(l[c++]=T),c||(l[c++]=0),l.length=c,l}e.exports=i},{}],263:[function(t,e,r){"use strict";function n(t){return t.split("").map(function(t){return t in i?i[t]:""}).join("")}e.exports=n;var i={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"}},{}],264:[function(t,e,r){"use strict";function n(t){return"a"+t}function i(t){return"d"+t}function a(t,e){return"c"+t+"_"+e}function o(t){return"s"+t}function s(t,e){return"t"+t+"_"+e}function l(t){return"o"+t}function c(t){return"x"+t}function u(t){return"p"+t}function f(t,e){return"d"+t+"_"+e}function h(t){return"i"+t}function d(t,e){return"u"+t+"_"+e}function p(t){return"b"+t}function g(t){return"y"+t}function v(t){return"e"+t}function m(t){return"v"+t}function y(t,e,r){for(var n=0,i=0;t>i;++i)e&1<e;++e)F.push(u(e),"+=",d(e,x[t]),";");F.push("}")}function z(t){for(var e=t-1;e>=0;--e)S(e,0);for(var r=[],e=0;I>e;++e)L[e]?r.push(i(e)+".get("+u(e)+")"):r.push(i(e)+"["+u(e)+"]");for(var e=0;b>e;++e)r.push(c(e));F.push(k,"[",T,"++]=phase(",r.join(),");");for(var e=0;t>e;++e)C(e);for(var n=0;I>n;++n)F.push(u(n),"+=",d(n,x[t]),";")}function P(t){for(var e=0;I>e;++e)L[e]?F.push(a(e,0),"=",i(e),".get(",u(e),");"):F.push(a(e,0),"=",i(e),"[",u(e),"];");for(var r=[],e=0;I>e;++e)r.push(a(e,0));for(var e=0;b>e;++e)r.push(c(e));F.push(p(0),"=",k,"[",T,"]=phase(",r.join(),");");for(var n=1;1<n;++n)F.push(p(n),"=",k,"[",T,"+",v(n),"];");for(var o=[],n=1;1<n;++n)o.push("("+p(0)+"!=="+p(n)+")");F.push("if(",o.join("||"),"){");for(var s=[],e=0;N>e;++e)s.push(h(e));for(var e=0;I>e;++e){s.push(a(e,0));for(var n=1;1<n;++n)L[e]?F.push(a(e,n),"=",i(e),".get(",u(e),"+",f(e,n),");"):F.push(a(e,n),"=",i(e),"[",u(e),"+",f(e,n),"];"),s.push(a(e,n))}for(var e=0;1<e;++e)s.push(p(e));for(var e=0;b>e;++e)s.push(c(e));F.push("vertex(",s.join(),");",m(0),"=",w,"[",T,"]=",A,"++;");for(var l=(1<n;++n)if(0===(t&~(1<0;_=_-1&g)x.push(w+"["+T+"+"+v(_)+"]");x.push(m(0));for(var _=0;I>_;++_)1&n?x.push(a(_,l),a(_,g)):x.push(a(_,g),a(_,l));1&n?x.push(d,y):x.push(y,d);for(var _=0;b>_;++_)x.push(c(_));F.push("if(",d,"!==",y,"){","face(",x.join(),")}")}F.push("}",T,"+=1;")}function R(){for(var t=1;1<t;++t)F.push(E,"=",v(t),";",v(t),"=",g(t),";",g(t),"=",E,";")}function O(t,e){if(0>t)return void P(e);z(t),F.push("if(",o(x[t]),">0){",h(x[t]),"=1;"),O(t-1,e|1<r;++r)F.push(u(r),"+=",d(r,x[t]),";");t===N-1&&(F.push(T,"=0;"),R()),S(t,2),O(t-1,e),t===N-1&&(F.push("if(",h(x[N-1]),"&1){",T,"=0;}"),R()),C(t),F.push("}")}var I=L.length,N=x.length;if(2>N)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var j="extractContour"+x.join("_"),F=[],D=[],B=[],U=0;I>U;++U)B.push(n(U));for(var U=0;b>U;++U)B.push(c(U));for(var U=0;N>U;++U)D.push(o(U)+"="+n(0)+".shape["+U+"]|0");for(var U=0;I>U;++U){D.push(i(U)+"="+n(U)+".data",l(U)+"="+n(U)+".offset|0");for(var V=0;N>V;++V)D.push(s(U,V)+"="+n(U)+".stride["+V+"]|0")}for(var U=0;I>U;++U){D.push(u(U)+"="+l(U)),D.push(a(U,0));for(var V=1;1<V;++V){for(var q=[],H=0;N>H;++H)V&1<U;++U)for(var V=0;N>V;++V){var G=[s(U,x[V])];V>0&&G.push(s(U,x[V-1])+"*"+o(x[V-1])),D.push(d(U,x[V])+"=("+G.join("-")+")|0")}for(var U=0;N>U;++U)D.push(h(U)+"=0");D.push(A+"=0");for(var Y=["2"],U=N-2;U>=0;--U)Y.push(o(x[U]));D.push(M+"=("+Y.join("*")+")|0",k+"=mallocUint32("+M+")",w+"=mallocUint32("+M+")",T+"=0"),D.push(p(0)+"=0");for(var V=1;1<V;++V){for(var X=[],W=[],H=0;N>H;++H)V&1<n&&e("Must have at least one array argument");var i=t.scalarArguments||0;0>i&&e("Scalar arg count must be > 0"),"function"!=typeof t.vertex&&e("Must specify vertex creation function"),"function"!=typeof t.cell&&e("Must specify cell creation function"),"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;n>s;++s)a.indexOf(s)>=0?o[s]=!0:o[s]=!1;return b(t.vertex,t.cell,t.phase,i,r,o)}var _=t("typedarray-pool");e.exports=x;var w="V",k="P",A="N",M="Q",T="X",E="T"},{"typedarray-pool":278}],265:[function(t,e,r){function n(t){if(0>t)return Number("0/0");for(var e=s[0],r=s.length-1;r>0;--r)e+=s[r]/(t+r);var n=t+o+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}var i=7,a=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],o=607/128,s=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];e.exports=function l(t){if(.5>t)return Math.PI/(Math.sin(Math.PI*t)*l(1-t));if(t>100)return Math.exp(n(t));t-=1;for(var e=a[0],r=1;i+2>r;r++)e+=a[r]/(t+r);var o=t+i+.5;return Math.sqrt(2*Math.PI)*Math.pow(o,t+.5)*Math.exp(-o)*e},e.exports.log=n},{}],266:[function(t,e,r){"use strict";function n(t){var e=t.length;if(i>e){for(var r=1,n=0;e>n;++n)for(var o=0;n>o;++o)if(t[n]n;++n)s[n]=0;for(var r=1,n=0;e>n;++n)if(!s[n]){var l=1;s[n]=1;for(var o=t[n];o!==n;o=t[o]){if(s[o])return a.freeUint8(s),0;l+=1,s[o]=1}1&l||(r=-r)}return a.freeUint8(s),r}e.exports=n;var i=32,a=t("typedarray-pool")},{"typedarray-pool":278}],267:[function(t,e,r){"use strict";function n(t){var e=t.length;switch(e){case 0:case 1:return 0;case 2:return t[1]}var r,n,i,s=a.mallocUint32(e),l=a.mallocUint32(e),c=0;for(o(t,l),i=0;e>i;++i)s[i]=t[i];for(i=e-1;i>0;--i)n=l[i],r=s[i],s[i]=s[n],s[n]=r,l[i]=l[r],l[r]=n,c=(c+r)*i;return a.freeUint32(l),a.freeUint32(s),c}function i(t,e,r){switch(t){case 0:return r?r:[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}r=r||new Array(t);var n,i,a,o=1;for(r[0]=0,a=1;t>a;++a)r[a]=a,o=o*a|0;for(a=t-1;a>0;--a)n=e/o|0,e=e-n*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}var a=t("typedarray-pool"),o=t("invert-permutation");r.rank=n,r.unrank=i},{"invert-permutation":268,"typedarray-pool":278}],268:[function(t,e,r){"use strict";function n(t,e){e=e||new Array(t.length);for(var r=0;rt)return[];if(0===t)return[[0]];for(var e=0|Math.round(o(t+1)),r=[],n=0;e>n;++n){for(var s=i.unrank(t,n),l=[0],c=0,u=0;u= 0) !== (_inline_1_db >= 0)) {\n _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n }\n }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":109}],271:[function(t,e,r){"use strict";function n(t,e){var r=[];return e=+e||0,i(t.hi(t.shape[0]-1),r,e),r}e.exports=n;var i=t("./lib/zc-core")},{"./lib/zc-core":270}],272:[function(t,e,r){"use strict";function n(t,e){var r=t.length,n=["'use strict';"],i="surfaceNets"+t.join("_")+"d"+e;n.push("var contour=genContour({","order:[",t.join(),"],","scalarArguments: 3,","phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],l=[],c=0;r>c;++c)a.push("d"+c),l.push("d"+c);for(var c=0;1<c;++c)a.push("v"+c),l.push("v"+c);for(var c=0;1<c;++c)a.push("p"+c),l.push("p"+c);a.push("a","b","c"),l.push("a","c"),n.push("vertex:function vertexFunc(",a.join(),"){");for(var u=[],c=0;1<c;++c)u.push("(p"+c+"<<"+c+")");n.push("var m=(",u.join("+"),")|0;if(m===0||m===",(1<<(1<=1<<(1<>>7){");for(var c=0;1<<(1<c;++c){if(1<<(1<128&&c%128===0){f.length>0&&h.push("}}");var d="vExtra"+f.length;n.push("case ",c>>>7,":",d,"(m&0x7f,",l.join(),");break;"),h=["function ",d,"(m,",l.join(),"){switch(m){"],f.push(h)}h.push("case ",127&c,":");for(var p=new Array(r),g=new Array(r),v=new Array(r),m=new Array(r),y=0,b=0;r>b;++b)p[b]=[],g[b]=[],v[b]=0,m[b]=0;for(var b=0;1<b;++b)for(var x=0;r>x;++x){var _=b^1<b)&&!(c&1<<_)!=!(c&1<w?(p[x].push("-v"+b+"-v"+_),v[x]+=2):(p[x].push("v"+b+"+v"+_),v[x]-=2),y+=1;for(var k=0;r>k;++k)k!==x&&(_&1<x;++x)if(0===p[x].length)A.push("d"+x+"-0.5");else{var M="";v[x]<0?M=v[x]+"*c":v[x]>0&&(M="+"+v[x]+"*c");var T=.5*(p[x].length/y),E=.5+.5*(m[x]/y);A.push("d"+x+"-"+E+"-"+T+"*("+p[x].join("+")+M+")/("+g[x].join("+")+")")}h.push("a.push([",A.join(),"]);","break;")}n.push("}},"),f.length>0&&h.push("}}");for(var L=[],c=0;1<c;++c)L.push("v"+c);L.push("c0","c1","p0","p1","a","b","c"),n.push("cell:function cellFunc(",L.join(),"){");var S=s(r-1);n.push("if(p0){b.push(",S.map(function(t){return"["+t.map(function(t){return"v"+t})+"]"}).join(),")}else{b.push(",S.map(function(t){var e=t.slice();return e.reverse(),"["+e.map(function(t){return"v"+t})+"]"}).join(),")}}});function ",i,"(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ",i,";");for(var c=0;co;++o)i[o]=[r[o]],a[o]=[o];return{positions:i,cells:a}}function a(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return i(t,e);var r=t.order.join()+"-"+t.dtype,a=c[r],e=+e||0;return a||(a=c[r]=n(t.order,t.dtype)),a(t,e)}e.exports=a;var o=t("ndarray-extract-contour"),s=t("triangulate-hypercube"),l=t("zero-crossings"),c={}},{"ndarray-extract-contour":264,"triangulate-hypercube":269,"zero-crossings":271}],273:[function(t,e,r){(function(r){"use strict";function n(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;ol;++l){var c=r[s[l]];n[i++]=c[0],n[i++]=c[1]+1.4,a=Math.max(c[0],a)}return{data:n,shape:a}}function i(t,e){var r=s[t];r||(r=s[t]={" ":{data:new Float32Array(0),shape:.2}});var o=r[e];if(!o)if(e.length<=1||!/\d/.test(e))o=r[e]=n(a(e,{triangles:!0,font:t,textAlign:"left",textBaseline:"alphabetic"}));else{for(var l=e.split(/(\d|\s)/),c=new Array(l.length),u=0,f=0,h=0;h0&&(f+=.02);for(var d=new Float32Array(u),p=0,g=-.5*f,h=0;h.5?l/(2-a-o):l/(a+o),a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,l:s}}function o(t,e,r){function n(t,e,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?t+6*(e-t)*r:.5>r?e:2/3>r?t+(e-t)*(2/3-r)*6:t}var i,a,o;if(t=T(t,360),e=T(e,100),r=T(r,100),0===e)i=a=o=r;else{var s=.5>r?r*(1+e):r+e-r*e,l=2*r-s;i=n(l,s,t+1/3),a=n(l,s,t),o=n(l,s,t-1/3)}return{r:255*i,g:255*a,b:255*o}}function s(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=a,l=a-o;if(i=0===a?0:l/a,a==o)n=0;else{switch(a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,v:s}}function l(t,e,r){t=6*T(t,360),e=T(e,100),r=T(r,100);var n=B.floor(t),i=t-n,a=r*(1-e),o=r*(1-i*e),s=r*(1-(1-i)*e),l=n%6,c=[r,o,a,a,s,r][l],u=[s,r,r,o,a,a][l],f=[a,a,s,r,r,o][l];return{r:255*c,g:255*u,b:255*f}}function c(t,e,r,n){var i=[z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function u(t,e,r,n){var i=[z(R(n)),z(U(t).toString(16)),z(U(e).toString(16)),z(U(r).toString(16))];return i.join("")}function f(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s-=r/100,n.s=E(n.s),e(n)}function h(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s+=r/100,n.s=E(n.s),e(n)}function d(t){return e(t).desaturate(100)}function p(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l+=r/100,n.l=E(n.l),e(n)}function g(t,r){r=0===r?0:r||10;var n=e(t).toRgb();return n.r=q(0,V(255,n.r-U(255*-(r/100)))),n.g=q(0,V(255,n.g-U(255*-(r/100)))),n.b=q(0,V(255,n.b-U(255*-(r/100)))),e(n)}function v(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l-=r/100,n.l=E(n.l),e(n)}function m(t,r){var n=e(t).toHsl(),i=(U(n.h)+r)%360;return n.h=0>i?360+i:i,e(n)}function y(t){var r=e(t).toHsl();return r.h=(r.h+180)%360,e(r)}function b(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+120)%360,s:r.s,l:r.l}),e({h:(n+240)%360,s:r.s,l:r.l})]}function x(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+90)%360,s:r.s,l:r.l}),e({h:(n+180)%360,s:r.s,l:r.l}),e({h:(n+270)%360,s:r.s,l:r.l})]}function _(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+72)%360,s:r.s,l:r.l}),e({h:(n+216)%360,s:r.s,l:r.l})]}function w(t,r,n){r=r||6,n=n||30;var i=e(t).toHsl(),a=360/n,o=[e(t)];for(i.h=(i.h-(a*r>>1)+720)%360;--r;)i.h=(i.h+a)%360,o.push(e(i));return o}function k(t,r){r=r||6;for(var n=e(t).toHsv(),i=n.h,a=n.s,o=n.v,s=[],l=1/r;r--;)s.push(e({h:i,s:a,v:o})),o=(o+l)%1;return s}function A(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}function M(t){return t=parseFloat(t),(isNaN(t)||0>t||t>1)&&(t=1),t}function T(t,e){S(t)&&(t="100%");var r=C(t);return t=V(e,q(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),B.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function E(t){return V(1,q(0,t))}function L(t){return parseInt(t,16)}function S(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)}function C(t){return"string"==typeof t&&-1!=t.indexOf("%")}function z(t){return 1==t.length?"0"+t:""+t}function P(t){return 1>=t&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function O(t){return L(t)/255}function I(t){t=t.replace(j,"").replace(F,"").toLowerCase();var e=!1;if(G[t])t=G[t],e=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};var r;return(r=X.rgb.exec(t))?{r:r[1],g:r[2],b:r[3]}:(r=X.rgba.exec(t))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=X.hsl.exec(t))?{h:r[1],s:r[2],l:r[3]}:(r=X.hsla.exec(t))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=X.hsv.exec(t))?{h:r[1],s:r[2],v:r[3]}:(r=X.hsva.exec(t))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=X.hex8.exec(t))?{a:O(r[1]),r:L(r[2]),g:L(r[3]),b:L(r[4]),format:e?"name":"hex8"}:(r=X.hex6.exec(t))?{r:L(r[1]),g:L(r[2]),b:L(r[3]),format:e?"name":"hex"}:(r=X.hex3.exec(t))?{r:L(r[1]+""+r[1]),g:L(r[2]+""+r[2]),b:L(r[3]+""+r[3]),format:e?"name":"hex"}:!1}function N(t){var e,r;return t=t||{level:"AA",size:"small"},e=(t.level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA"),"small"!==r&&"large"!==r&&(r="small"),{level:e,size:r}}var j=/^\s+/,F=/\s+$/,D=0,B=Math,U=B.round,V=B.min,q=B.max,H=B.random;e.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n,i,a,o=this.toRgb();return t=o.r/255,e=o.g/255,r=o.b/255,n=.03928>=t?t/12.92:Math.pow((t+.055)/1.055,2.4),i=.03928>=e?e/12.92:Math.pow((e+.055)/1.055,2.4),a=.03928>=r?r/12.92:Math.pow((r+.055)/1.055,2.4),.2126*n+.7152*i+.0722*a},setAlpha:function(t){return this._a=M(t),this._roundA=U(100*this._a)/100,this},toHsv:function(){var t=s(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=s(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return c(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(){return u(this._r,this._g,this._b,this._a)},toHex8String:function(){return"#"+this.toHex8()},toRgb:function(){return{r:U(this._r),g:U(this._g),b:U(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+U(this._r)+", "+U(this._g)+", "+U(this._b)+")":"rgba("+U(this._r)+", "+U(this._g)+", "+U(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:U(100*T(this._r,255))+"%",g:U(100*T(this._g,255))+"%",b:U(100*T(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%)":"rgba("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":this._a<1?!1:Y[c(this._r,this._g,this._b,!0)]||!1},toFilter:function(t){var r="#"+u(this._r,this._g,this._b,this._a),n=r,i=this._gradientType?"GradientType = 1, ":"";if(t){var a=e(t);n=a.toHex8String()}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+r+",endColorstr="+n+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0,i=!e&&n&&("hex"===t||"hex6"===t||"hex3"===t||"name"===t);return i?"name"===t&&0===this._a?this.toName():this.toRgbString():("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString())},clone:function(){return e(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(p,arguments)},brighten:function(){return this._applyModification(g,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(f,arguments)},saturate:function(){return this._applyModification(h,arguments)},greyscale:function(){return this._applyModification(d,arguments)},spin:function(){return this._applyModification(m,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(w,arguments)},complement:function(){return this._applyCombination(y,arguments)},monochromatic:function(){return this._applyCombination(k,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(b,arguments)},tetrad:function(){return this._applyCombination(x,arguments)}},e.fromRatio=function(t,r){if("object"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&("a"===i?n[i]=t[i]:n[i]=P(t[i]));t=n}return e(t,r)},e.equals=function(t,r){return t&&r?e(t).toRgbString()==e(r).toRgbString():!1},e.random=function(){return e.fromRatio({r:H(),g:H(),b:H()})},e.mix=function(t,r,n){n=0===n?0:n||50;var i,a=e(t).toRgb(),o=e(r).toRgb(),s=n/100,l=2*s-1,c=o.a-a.a;i=l*c==-1?l:(l+c)/(1+l*c),i=(i+1)/2;var u=1-i,f={r:o.r*i+a.r*u,g:o.g*i+a.g*u,b:o.b*i+a.b*u,a:o.a*s+a.a*(1-s)};return e(f)},e.readability=function(t,r){var n=e(t),i=e(r);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},e.isReadable=function(t,r,n){var i,a,o=e.readability(t,r);switch(a=!1,i=N(n),i.level+i.size){case"AAsmall":case"AAAlarge":a=o>=4.5;break;case"AAlarge":a=o>=3;break;case"AAAsmall":a=o>=7}return a},e.mostReadable=function(t,r,n){var i,a,o,s,l=null,c=0;n=n||{},a=n.includeFallbackColors,o=n.level,s=n.size;for(var u=0;uc&&(c=i,l=e(r[u]));return e.isReadable(t,l,{level:o,size:s})||!a?l:(n.includeFallbackColors=!1,e.mostReadable(t,["#fff","#000"],n))};var G=e.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Y=e.hexNames=A(G),X=function(){var t="[-\\+]?\\d+%?",e="[-\\+]?\\d*\\.\\d+%?",r="(?:"+e+")|(?:"+t+")",n="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?",i="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?";return{rgb:new RegExp("rgb"+n),rgba:new RegExp("rgba"+i),hsl:new RegExp("hsl"+n),hsla:new RegExp("hsla"+i),hsv:new RegExp("hsv"+n),hsva:new RegExp("hsva"+i),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();"undefined"!=typeof r&&r.exports?r.exports=e:"function"==typeof t&&t.amd?t(function(){return e}):window.tinycolor=e}()},{}],275:[function(e,r,n){!function(e,i){"object"==typeof n&&"undefined"!=typeof r?i(n):"function"==typeof t&&t.amd?t(["exports"],i):i(e.topojson={})}(this,function(t){"use strict";function e(){}function r(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0),t[0]=(r+=t[0])*i+o,t[1]=(n+=t[1])*a+s}}function n(t){if(!t)return e;var r,n,i=t.scale[0],a=t.scale[1],o=t.translate[0],s=t.translate[1];return function(t,e){e||(r=n=0);var l=(t[0]-o)/i|0,c=(t[1]-s)/a|0;t[0]=l-r,t[1]=c-n,r=l,n=c}}function i(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r}function a(t,e){for(var r=0,n=t.length;n>r;){var i=r+n>>>1;t[i]t?~t:t],a=0,o=n.length;o>a;++a)e.push(r=n[a].slice()),u(r,a);0>t&&i(e,o)}function a(t){return t=t.slice(),u(t,0),t}function o(t){for(var e=[],r=0,i=t.length;i>r;++r)n(t[r],e);return e.length<2&&e.push(e[0].slice()),e}function s(t){for(var e=o(t);e.length<4;)e.push(e[0].slice());return e}function l(t){return t.map(s)}function c(t){var e=t.type;return"GeometryCollection"===e?{type:e,geometries:t.geometries.map(c)}:e in h?{type:e,coordinates:h[e](t)}:null}var u=r(t.transform),f=t.arcs,h={Point:function(t){return a(t.coordinates)},MultiPoint:function(t){return t.coordinates.map(a)},LineString:function(t){return o(t.arcs)},MultiLineString:function(t){return t.arcs.map(o)},Polygon:function(t){return l(t.arcs)},MultiPolygon:function(t){return t.arcs.map(l)}};return c(e)}function c(t,e){function r(e){var r,n=t.arcs[0>e?~e:e],i=n[0];return t.transform?(r=[0,0],n.forEach(function(t){r[0]+=t[0],r[1]+=t[1]})):r=n[n.length-1],0>e?[r,i]:[i,r]}function n(t,e){for(var r in t){var n=t[r];delete e[n.start],delete n.start,delete n.end,n.forEach(function(t){i[0>t?~t:t]=1}),s.push(n)}}var i={},a={},o={},s=[],l=-1;return e.forEach(function(r,n){var i,a=t.arcs[0>r?~r:r];a.length<3&&!a[1][0]&&!a[1][1]&&(i=e[++l],e[l]=r,e[n]=i)}),e.forEach(function(t){var e,n,i=r(t),s=i[0],l=i[1];if(e=o[s])if(delete o[e.end],e.push(t),e.end=l,n=a[l]){delete a[n.start];var c=n===e?e:e.concat(n);a[c.start=e.start]=o[c.end=n.end]=c}else a[e.start]=o[e.end]=e;else if(e=a[l])if(delete a[e.start], +e.unshift(t),e.start=s,n=o[s]){delete o[n.end];var u=n===e?e:n.concat(e);a[u.start=n.start]=o[u.end=e.end]=u}else a[e.start]=o[e.end]=e;else e=[t],a[e.start=s]=o[e.end=l]=e}),n(o,a),n(a,o),e.forEach(function(t){i[0>t?~t:t]||s.push([t])}),s}function u(t){return l(t,f.apply(this,arguments))}function f(t,e,r){function n(t){var e=0>t?~t:t;(u[e]||(u[e]=[])).push({i:t,g:l})}function i(t){t.forEach(n)}function a(t){t.forEach(i)}function o(t){"GeometryCollection"===t.type?t.geometries.forEach(o):t.type in f&&(l=t,f[t.type](t.arcs))}var s=[];if(arguments.length>1){var l,u=[],f={LineString:i,MultiLineString:a,Polygon:a,MultiPolygon:function(t){t.forEach(a)}};o(e),u.forEach(arguments.length<3?function(t){s.push(t[0].i)}:function(t){r(t[0].g,t[t.length-1].g)&&s.push(t[0].i)})}else for(var h=0,d=t.arcs.length;d>h;++h)s.push(h);return{type:"MultiLineString",arcs:c(t,s)}}function h(t){var e=t[0],r=t[1],n=t[2];return Math.abs((e[0]-n[0])*(r[1]-e[1])-(e[0]-r[0])*(n[1]-e[1]))}function d(t){for(var e,r=-1,n=t.length,i=t[n-1],a=0;++re?~e:e]||(i[e]=[])).push(t)})}),a.push(t)}function n(e){return d(l(t,{type:"Polygon",arcs:[e]}).coordinates[0])>0}var i={},a=[],o=[];return e.forEach(function(t){"Polygon"===t.type?r(t.arcs):"MultiPolygon"===t.type&&t.arcs.forEach(r)}),a.forEach(function(t){if(!t._){var e=[],r=[t];for(t._=1,o.push(e);t=r.pop();)e.push(t),t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].forEach(function(t){t._||(t._=1,r.push(t))})})})}}),a.forEach(function(t){delete t._}),{type:"MultiPolygon",arcs:o.map(function(e){var r,a=[];if(e.forEach(function(t){t.forEach(function(t){t.forEach(function(t){i[0>t?~t:t].length<2&&a.push(t)})})}),a=c(t,a),(r=a.length)>1)for(var o,s=n(e[0][0]),l=0;r>l;++l)if(s===n(a[l])){o=a[0],a[0]=a[l],a[l]=o;break}return a})}}function v(t){function e(t,e){t.forEach(function(t){0>t&&(t=~t);var r=i[t];r?r.push(e):i[t]=[e]})}function r(t,r){t.forEach(function(t){e(t,r)})}function n(t,e){"GeometryCollection"===t.type?t.geometries.forEach(function(t){n(t,e)}):t.type in s&&s[t.type](t.arcs,e)}var i={},o=t.map(function(){return[]}),s={LineString:e,MultiLineString:r,Polygon:r,MultiPolygon:function(t,e){t.forEach(function(t){r(t,e)})}};t.forEach(n);for(var l in i)for(var c=i[l],u=c.length,f=0;u>f;++f)for(var h=f+1;u>h;++h){var d,p=c[f],g=c[h];(d=o[p])[l=a(d,g)]!==g&&d.splice(l,0,g),(d=o[g])[l=a(d,p)]!==p&&d.splice(l,0,p)}return o}function m(t,e){return t[1][2]-e[1][2]}function y(){function t(t,e){for(;e>0;){var r=(e+1>>1)-1,i=n[r];if(m(t,i)>=0)break;n[i._=e]=i,n[t._=e=r]=t}}function e(t,e){for(;;){var r=e+1<<1,a=r-1,o=e,s=n[o];if(i>a&&m(n[a],s)<0&&(s=n[o=a]),i>r&&m(n[r],s)<0&&(s=n[o=r]),o===e)break;n[s._=e]=s,n[t._=e=o]=t}}var r={},n=[],i=0;return r.push=function(e){return t(n[e._=i]=e,i++),i},r.pop=function(){if(!(0>=i)){var t,r=n[0];return--i>0&&(t=n[i],e(n[t._=0]=t,0)),r}},r.remove=function(r){var a,o=r._;if(n[o]===r)return o!==--i&&(a=n[i],(m(a,r)<0?t:e)(n[a._=o]=a,o)),o},r}function b(t,e){function i(t){s.remove(t),t[1][2]=e(t),s.push(t)}var a=r(t.transform),o=n(t.transform),s=y();return e||(e=h),t.arcs.forEach(function(t){var r,n,l,c,u=[],f=0;for(n=0,l=t.length;l>n;++n)c=t[n],a(t[n]=[c[0],c[1],1/0],n);for(n=1,l=t.length-1;l>n;++n)r=t.slice(n-1,n+2),r[1][2]=e(r),u.push(r),s.push(r);for(n=0,l=u.length;l>n;++n)r=u[n],r.previous=u[n-1],r.next=u[n+1];for(;r=s.pop();){var h=r.previous,d=r.next;r[1][2]0?r.pop():new ArrayBuffer(t)}function s(t){return new Uint8Array(o(t),0,t)}function l(t){return new Uint16Array(o(2*t),0,t)}function c(t){return new Uint32Array(o(4*t),0,t)}function u(t){return new Int8Array(o(t),0,t)}function f(t){return new Int16Array(o(2*t),0,t)}function h(t){return new Int32Array(o(4*t),0,t)}function d(t){return new Float32Array(o(4*t),0,t)}function p(t){return new Float64Array(o(8*t),0,t)}function g(t){return x?new Uint8ClampedArray(o(t),0,t):s(t)}function v(t){return new DataView(o(t),0,t)}function m(t){t=y.nextPow2(t);var e=y.log2(t),r=k[e];return r.length>0?r.pop():new n(t)}var y=t("bit-twiddle"),b=t("dup");e.__TYPEDARRAY_POOL||(e.__TYPEDARRAY_POOL={UINT8:b([32,0]),UINT16:b([32,0]),UINT32:b([32,0]),INT8:b([32,0]),INT16:b([32,0]),INT32:b([32,0]),FLOAT:b([32,0]),DOUBLE:b([32,0]),DATA:b([32,0]),UINT8C:b([32,0]),BUFFER:b([32,0])});var x="undefined"!=typeof Uint8ClampedArray,_=e.__TYPEDARRAY_POOL;_.UINT8C||(_.UINT8C=b([32,0])),_.BUFFER||(_.BUFFER=b([32,0]));var w=_.DATA,k=_.BUFFER;r.free=function(t){if(n.isBuffer(t))k[y.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|y.log2(e);w[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=a,r.freeArrayBuffer=i,r.freeBuffer=function(t){k[y.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return o(t);switch(e){case"uint8":return s(t);case"uint16":return l(t);case"uint32":return c(t);case"int8":return u(t);case"int16":return f(t);case"int32":return h(t);case"float":case"float32":return d(t);case"double":case"float64":return p(t);case"uint8_clamped":return g(t);case"buffer":return m(t);case"data":case"dataview":return v(t);default:return null}return null},r.mallocArrayBuffer=o,r.mallocUint8=s,r.mallocUint16=l,r.mallocUint32=c,r.mallocInt8=u,r.mallocInt16=f,r.mallocInt32=h,r.mallocFloat32=r.mallocFloat=d,r.mallocFloat64=r.mallocDouble=p,r.mallocUint8Clamped=g,r.mallocDataView=v,r.mallocBuffer=m,r.clearCache=function(){for(var t=0;32>t;++t)_.UINT8[t].length=0,_.UINT16[t].length=0,_.UINT32[t].length=0,_.INT8[t].length=0,_.INT16[t].length=0,_.INT32[t].length=0,_.FLOAT[t].length=0,_.DOUBLE[t].length=0,_.UINT8C[t].length=0,w[t].length=0,k[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":50,buffer:51,dup:115}],279:[function(t,e,r){"use strict";function n(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;n>o;++o)if(a=i,i=t[o],e(i,a)){if(o===r){r++;continue}t[r++]=i}return t.length=r,t}function i(t){for(var e=1,r=t.length,n=t[0],i=t[0],a=1;r>a;++a,i=n)if(i=n,n=t[a],n!==i){if(a===e){e++;continue}t[e++]=n}return t.length=e,t}function a(t,e,r){return 0===t.length?t:e?(r||t.sort(e),n(t,e)):(r||t.sort(),i(t))}e.exports=a},{}],280:[function(t,e,r){"use strict";function n(t,e){return"object"==typeof e&&null!==e||(e={}),i(t,e.canvas||a,e.context||o,e)}e.exports=n;var i=t("./lib/vtext"),a=null,o=null;"undefined"!=typeof document&&(a=document.createElement("canvas"),a.width=8192,a.height=1024,o=a.getContext("2d"))},{"./lib/vtext":281}],281:[function(t,e,r){"use strict";function n(t,e,r){for(var n=e.textAlign||"start",i=e.textBaseline||"alphabetic",a=[1<<30,1<<30],o=[0,0],s=t.length,l=0;s>l;++l)for(var c=t[l],u=0;2>u;++u)a[u]=0|Math.min(a[u],c[u]),o[u]=0|Math.max(o[u],c[u]);var f=0;switch(n){case"center":f=-.5*(a[0]+o[0]);break;case"right":case"end":f=-o[0];break;case"left":case"start":f=-a[0];break;default:throw new Error("vectorize-text: Unrecognized textAlign: '"+n+"'")}var h=0;switch(i){case"hanging":case"top":h=-a[1];break;case"middle":h=-.5*(a[1]+o[1]);break;case"alphabetic":case"ideographic":h=-3*r;break;case"bottom":h=-o[1];break;default:throw new Error("vectorize-text: Unrecoginized textBaseline: '"+i+"'")}var d=1/r;return"lineHeight"in e?d*=+e.lineHeight:"width"in e?d=e.width/(o[0]-a[0]):"height"in e&&(d=e.height/(o[1]-a[1])),t.map(function(t){return[d*(t[0]+f),d*(t[1]+h)]})}function i(t,e,r,n){var i=0|Math.ceil(e.measureText(r).width+2*n);if(i>8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height=l&&o.push(s)}for(;o.length>0;){var c=o.pop();n[c]=!1;for(var u=r[c],s=0;sn;++n){var a=t[n];e=Math.max(e,a[0],a[1])}e=(0|e)+1}e=0|e;for(var o=new Array(e),n=0;e>n;++n)o[n]=[];for(var n=0;r>n;++n){var a=t[n];o[a[0]].push(a[1]),o[a[1]].push(a[0])}for(var s=0;e>s;++s)i(o[s],function(t,e){return t-e});return o}e.exports=n;var i=t("uniq")},{uniq:279}],284:[function(t,e,r){"use strict";function n(t,e){function r(t,e){var r=c[e][t[e]];r.splice(r.indexOf(t),1)}function n(t,n,a){for(var o,s,l,u=0;2>u;++u)if(c[u][n].length>0){o=c[u][n][0],l=u;break}s=o[1^l];for(var f=0;2>f;++f)for(var h=c[f][n],d=0;d0&&(o=p,s=g,l=f)}return a?s:(o&&r(o,l),s)}function a(t,a){var o=c[a][t][0],s=[t];r(o,a);for(var l=o[1^a];;){for(;l!==t;)s.push(l),l=n(s[s.length-2],l,!1);if(c[0][t].length+c[1][t].length===0)break;var u=s[s.length-1],f=t,h=s[1],d=n(u,f,!0);if(i(e[u],e[f],e[h],e[d])<0)break;s.push(t),l=n(u,f)}return s}function o(t,e){return e[1]===e[e.length-1]}for(var s=0|e.length,l=t.length,c=[new Array(s),new Array(s)],u=0;s>u;++u)c[0][u]=[],c[1][u]=[];for(var u=0;l>u;++u){var f=t[u];c[0][f[0]].push(f),c[1][f[1]].push(f)}for(var h=[],u=0;s>u;++u)c[0][u].length+c[1][u].length===0&&h.push([u]);for(var u=0;s>u;++u)for(var d=0;2>d;++d){for(var p=[];c[d][u].length>0;){var g=(c[0][u].length,a(u,d));o(p,g)?p.push.apply(p,g):(p.length>0&&h.push(p),p=g)}p.length>0&&h.push(p)}return h}e.exports=n;var i=t("compare-angle")},{"compare-angle":285}],285:[function(t,e,r){"use strict";function n(t,e,r){var n=s(t[0],-e[0]),i=s(t[1],-e[1]),a=s(r[0],-e[0]),o=s(r[1],-e[1]),u=c(l(n,a),l(i,o));return u[u.length-1]>=0}function i(t,e,r,i){var s=a(e,r,i);if(0===s){var l=o(a(t,e,r)),c=o(a(t,e,i));if(l===c){if(0===l){var u=n(t,e,r),f=n(t,e,i);return u===f?0:u?1:-1}return 0}return 0===c?l>0?-1:n(t,e,i)?-1:1:0===l?c>0?1:n(t,e,r)?1:-1:o(c-l)}var h=a(t,e,r);if(h>0)return s>0&&a(t,e,i)>0?1:-1;if(0>h)return s>0||a(t,e,i)>0?1:-1;var d=a(t,e,i);return d>0?1:n(t,e,r)?1:-1}e.exports=i;var a=t("robust-orientation"),o=t("signum"),s=t("two-sum"),l=t("robust-product"),c=t("robust-sum")},{"robust-orientation":259,"robust-product":286,"robust-sum":262,signum:287,"two-sum":277}],286:[function(t,e,r){"use strict";function n(t,e){if(1===t.length)return a(e,t[0]);if(1===e.length)return a(t,e[0]);if(0===t.length||0===e.length)return[0];var r=[0];if(t.lengtht?-1:t>0?1:0}},{}],288:[function(t,e,r){arguments[4][21][0].apply(r,arguments)},{dup:21}],289:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}function i(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function a(t,e){var r=p(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function o(t,e){var r=t.intervals([]);r.push(e),a(t,r)}function s(t,e){var r=t.intervals([]),n=r.indexOf(e);return 0>n?y:(r.splice(n,1),a(t,r),b)}function l(t,e,r){for(var n=0;n=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function u(t,e){for(var r=0;r>1],a=[],o=[],s=[],r=0;r3*(e+1)?o(this,t):this.left.insert(t):this.left=p([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?o(this,t):this.right.insert(t):this.right=p([t]);else{var r=m.ge(this.leftPoints,t,h),n=m.ge(this.rightPoints,t,d);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]3*(e-1))return s(this,t);var n=this.left.remove(t);return n===x?(this.left=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(t[0]>this.mid){if(!this.right)return y;var a=this.left?this.left.count:0;if(4*a>3*(e-1))return s(this,t);var n=this.right.remove(t);return n===x?(this.right=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(1===this.count)return this.leftPoints[0]===t?x:y;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var o=this,l=this.left;l.right;)o=l,l=l.right;if(o===this)l.right=this.right;else{var c=this.left,n=this.right;o.count-=l.count,o.right=l.left,l.left=c,l.right=n}i(this,l),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?i(this,this.left):i(this,this.right);return b}for(var c=m.ge(this.leftPoints,t,h);cthis.mid){if(this.right){var r=this.right.queryPoint(t,e);if(r)return r}return c(this.rightPoints,t,e)}return u(this.leftPoints,e)},_.queryInterval=function(t,e,r){if(tthis.mid&&this.right){var n=this.right.queryInterval(t,e,r);if(n)return n}return ethis.mid?c(this.rightPoints,t,r):u(this.leftPoints,r)};var w=g.prototype;w.insert=function(t){this.root?this.root.insert(t):this.root=new n(t[0],null,null,[t],[t])},w.remove=function(t){if(this.root){var e=this.root.remove(t);return e===x&&(this.root=null),e!==y}return!1},w.queryPoint=function(t,e){return this.root?this.root.queryPoint(t,e):void 0},w.queryInterval=function(t,e,r){return e>=t&&this.root?this.root.queryInterval(t,e,r):void 0},Object.defineProperty(w,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(w,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":288}],290:[function(t,e,r){"use strict";function n(t,e){var r,n;if(e[0][0]e[1][0])){var i=Math.min(t[0][1],t[1][1]),o=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),l=Math.max(e[0][1],e[1][1]);return s>o?o-s:i>l?i-l:o-l}r=e[1],n=e[0]}var c,u;t[0][1]e[1][0]))return n(e,t);r=e[1],i=e[0]}var o,s;if(t[0][0]t[1][0]))return-n(t,e);o=t[1],s=t[0]}var l=a(r,i,s),c=a(r,i,o);if(0>l){if(0>=c)return l}else if(l>0){if(c>=0)return l}else if(c)return c;if(l=a(s,o,i),c=a(s,o,r),0>l){if(0>=c)return l}else if(l>0){if(c>=0)return l}else if(c)return c;return i[0]-s[0]}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":259}],291:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function i(t){return new n(t._color,t.key,t.value,t.left,t.right,t._count)}function a(t,e){return new n(t,e.key,e.value,e.left,e.right,e._count)}function o(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function s(t,e){this._compare=t,this.root=e}function l(t,e){if(e.left){var r=l(t,e.left);if(r)return r}var r=t(e.key,e.value);return r?r:e.right?l(t,e.right):void 0}function c(t,e,r,n){var i=e(t,n.key);if(0>=i){if(n.left){var a=c(t,e,r,n.left);if(a)return a}var a=r(n.key,n.value);if(a)return a}return n.right?c(t,e,r,n.right):void 0}function u(t,e,r,n,i){var a,o=r(t,i.key),s=r(e,i.key);if(0>=o){if(i.left&&(a=u(t,e,r,n,i.left)))return a;if(s>0&&(a=n(i.key,i.value)))return a}return s>0&&i.right?u(t,e,r,n,i.right):void 0}function f(t,e){this.tree=t,this._stack=e}function h(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function d(t){for(var e,r,n,s,l=t.length-1;l>=0;--l){if(e=t[l],0===l)return void(e._color=m);if(r=t[l-1],r.left===e){if(n=r.right,n.right&&n.right._color===v){if(n=r.right=i(n),s=n.right=i(n.right),r.right=n.left,n.left=r,n.right=s,n._color=r._color,e._color=m,r._color=m,s._color=m,o(r),o(n),l>1){var c=t[l-2];c.left===r?c.left=n:c.right=n}return void(t[l-1]=n)}if(n.left&&n.left._color===v){if(n=r.right=i(n),s=n.left=i(n.left),r.right=s.left,n.left=s.right,s.left=r,s.right=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var c=t[l-2];c.left===r?c.left=s:c.right=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.right=a(v,n));r.right=a(v,n);continue}if(n=i(n),r.right=n.left,n.left=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var c=t[l-2];c.left===r?c.left=n:c.right=n}t[l-1]=n,t[l]=r,l+11){var c=t[l-2];c.right===r?c.right=n:c.left=n}return void(t[l-1]=n)}if(n.right&&n.right._color===v){if(n=r.left=i(n),s=n.right=i(n.right),r.left=s.right,n.right=s.left,s.right=r,s.left=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var c=t[l-2];c.right===r?c.right=s:c.left=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.left=a(v,n));r.left=a(v,n);continue}if(n=i(n),r.left=n.right,n.right=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var c=t[l-2];c.right===r?c.right=n:c.left=n}t[l-1]=n,t[l]=r,l+1t?-1:t>e?1:0}function g(t){return new s(t||p,null)}e.exports=g;var v=0,m=1,y=s.prototype;Object.defineProperty(y,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(y,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(y,"length",{get:function(){return this.root?this.root._count:0}}),y.insert=function(t,e){for(var r=this._compare,i=this.root,l=[],c=[];i;){var u=r(t,i.key);l.push(i),c.push(u),i=0>=u?i.left:i.right}l.push(new n(v,t,e,null,null,1));for(var f=l.length-2;f>=0;--f){var i=l[f];c[f]<=0?l[f]=new n(i._color,i.key,i.value,l[f+1],i.right,i._count+1):l[f]=new n(i._color,i.key,i.value,i.left,l[f+1],i._count+1)}for(var f=l.length-1;f>1;--f){var h=l[f-1],i=l[f];if(h._color===m||i._color===m)break;var d=l[f-2];if(d.left===h)if(h.left===i){var p=d.right;if(!p||p._color!==v){if(d._color=v,d.left=h.right,h._color=m,h.right=d,l[f-2]=h,l[f-1]=i,o(d),o(h),f>=3){var g=l[f-3];g.left===d?g.left=h:g.right=h}break}h._color=m,d.right=a(m,p),d._color=v,f-=1}else{var p=d.right;if(!p||p._color!==v){if(h.right=i.left,d._color=v,d.left=i.right,i._color=m,i.left=h,i.right=d,l[f-2]=i,l[f-1]=h,o(d),o(h),o(i),f>=3){var g=l[f-3];g.left===d?g.left=i:g.right=i}break}h._color=m,d.right=a(m,p),d._color=v,f-=1}else if(h.right===i){var p=d.left;if(!p||p._color!==v){if(d._color=v,d.right=h.left,h._color=m,h.left=d,l[f-2]=h,l[f-1]=i,o(d),o(h),f>=3){var g=l[f-3];g.right===d?g.right=h:g.left=h}break}h._color=m,d.left=a(m,p),d._color=v,f-=1}else{var p=d.left;if(!p||p._color!==v){if(h.left=i.right,d._color=v,d.right=i.left,i._color=m,i.right=h,i.left=d,l[f-2]=i,l[f-1]=h,o(d),o(h),o(i),f>=3){var g=l[f-3];g.right===d?g.right=i:g.left=i}break}h._color=m,d.left=a(m,p),d._color=v,f-=1}}return l[0]._color=m,new s(r,l[0])},y.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return l(t,this.root);case 2:return c(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return u(e,r,this._compare,t,this.root)}},Object.defineProperty(y,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new f(this,t)}}),Object.defineProperty(y,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new f(this,t)}}),y.at=function(t){if(0>t)return new f(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t=e.right._count)break;e=e.right}return new f(this,[])},y.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>=a&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>a&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new f(this,n)},y.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new f(this,n)},y.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new f(this,n);r=0>=i?r.left:r.right}return new f(this,[])},y.remove=function(t){var e=this.find(t);return e?e.remove():this},y.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=0>=n?r.left:r.right}};var b=f.prototype;Object.defineProperty(b,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(b,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),b.clone=function(){return new f(this.tree,this._stack.slice())},b.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new n(r._color,r.key,r.value,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i){var r=t[i];r.left===t[i+1]?e[i]=new n(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count)}if(r=e[e.length-1],r.left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var o=e[a-1];e.push(new n(r._color,o.key,o.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(var i=e.length-2;i>=a;--i)r=e[i],e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count);e[a-1].left=e[a]}if(r=e[e.length-1],r._color===v){var l=e[e.length-2];l.left===r?l.left=null:l.right===r&&(l.right=null),e.pop();for(var i=0;i0?this._stack[this._stack.length-1].key:void 0},enumerable:!0}),Object.defineProperty(b,"value",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1].value:void 0},enumerable:!0}),Object.defineProperty(b,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),b.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),b.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),i=e[e.length-1];r[r.length-1]=new n(i._color,i.key,t,i.left,i.right,i._count);for(var a=e.length-2;a>=0;--a)i=e[a],i.left===e[a+1]?r[a]=new n(i._color,i.key,i.value,r[a+1],i.right,i._count):r[a]=new n(i._color,i.key,i.value,i.left,r[a+1],i._count);return new s(this.tree._compare,r[0])},b.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],292:[function(t,e,r){"use strict";function n(t,e,r){this.slabs=t,this.coordinates=e,this.horizontal=r}function i(t,e){return t.y-e}function a(t,e){for(var r=null;t;){var n,i,o=t.key;o[0][0]s)t=t.left;else if(s>0)if(e[0]!==o[1][0])r=t,t=t.right;else{var l=a(t.right,e);if(l)return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l=a(t.right,e);if(l)return l;t=t.left}}return r}function o(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function s(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}function l(t){for(var e=t.length,r=2*e,i=new Array(r),a=0;e>a;++a){var l=t[a],c=l[0][0]a;){for(var v=i[a].x,m=[];r>a;){var y=i[a];if(y.x!==v)break;a+=1,y.segment[0][0]===y.x&&y.segment[1][0]===y.x?y.create&&(y.segment[0][1]e)return-1;var r=(this.slabs[e],a(this.slabs[e],t)),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var o=null;if(r&&(o=r.key),e>0){var s=a(this.slabs[e-1],t);s&&(o?h(s.key,o)>0&&(o=s.key,n=s.value):(n=s.value,o=s.key))}var l=this.horizontal[e];if(l.length>0){var u=c.ge(l,t[1],i);if(u=l.length)return n;d=l[u]}}if(d.start)if(o){var p=f(o[0],o[1],[t[0],d.y]);o[0][0]>o[1][0]&&(p=-p),p>0&&(n=d.index)}else n=d.index;else d.y!==t[1]&&(n=d.index)}}}return n}},{"./lib/order-segments":290,"binary-search-bounds":288,"functional-red-black-tree":291,"robust-orientation":259}],293:[function(t,e,r){function n(){return!0}function i(t){return function(e,r){var i=t[e];return i?!!i.queryPoint(r,n):!1}}function a(t){for(var e={},r=0;rn)return 1;var i=t[n];if(!i){if(!(n>0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=f(r,o[0],o[1]);if(o[0][0]s)i=i.left;else{if(!(s>0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(0>s))return 0;a=1,i=i.right}}return a}}function s(t){return 1}function l(t){return function(e){return t(e[0],e[1])?0:1}}function c(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}function u(t){for(var e=t.length,r=[],n=[],i=0;e>i;++i)for(var u=t[i],f=u.length,d=f-1,p=0;f>p;d=p++){var g=u[d],v=u[p];g[0]===v[0]?n.push([g,v]):r.push([g,v])}if(0===r.length)return 0===n.length?s:l(a(n));var m=h(r),y=o(m.slabs,m.coordinates);return 0===n.length?y:c(a(n),y)}e.exports=u;var f=t("robust-orientation")[3],h=t("slab-decomposition"),d=t("interval-tree-1d"),p=t("binary-search-bounds")},{"binary-search-bounds":288,"interval-tree-1d":289,"robust-orientation":259,"slab-decomposition":292 +}],294:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function i(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=[];return e}function a(t,e){function r(t){for(var r=t.length,n=[0],i=0;r>i;++i){var a=e[t[i]],o=e[t[(i+1)%r]],s=c(-a[0],a[1]),l=c(-a[0],o[1]),f=c(o[0],a[1]),h=c(o[0],o[1]);n=u(n,u(u(s,l),u(f,h)))}return n[n.length-1]>0}function a(t){for(var e=t.length,r=0;e>r;++r)if(!O[t[r]])return!1;return!0}var d=h(t,e);t=d[0],e=d[1];for(var p=e.length,g=(t.length,o(t,e.length)),v=0;p>v;++v)if(g[v].length%2===1)throw new Error("planar-graph-to-polyline: graph must be manifold");var m=s(t,e);m=m.filter(r);for(var y=m.length,b=new Array(y),x=new Array(y),v=0;y>v;++v){b[v]=v;var _=new Array(y),w=m[v].map(function(t){return e[t]}),k=l([w]),A=0;t:for(var M=0;y>M;++M)if(_[M]=0,v!==M){for(var T=m[M],E=T.length,L=0;E>L;++L){var S=k(e[T[L]]);if(0!==S){0>S&&(_[M]=1,A+=1);continue t}}_[M]=1,A+=1}x[v]=[A,v,_]}x.sort(function(t,e){return e[0]-t[0]});for(var v=0;y>v;++v)for(var _=x[v],C=_[1],z=_[2],M=0;y>M;++M)z[M]&&(b[M]=C);for(var P=i(y),v=0;y>v;++v)P[v].push(b[v]),P[b[v]].push(v);for(var R={},O=n(p,!1),v=0;y>v;++v)for(var T=m[v],E=T.length,M=0;E>M;++M){var I=T[M],N=T[(M+1)%E],j=Math.min(I,N)+":"+Math.max(I,N);if(j in R){var F=R[j];P[F].push(v),P[v].push(F),O[I]=O[N]=!0}else R[j]=v}for(var D=[],B=n(y,-1),v=0;y>v;++v)b[v]!==v||a(m[v])?B[v]=-1:(D.push(v),B[v]=0);for(var d=[];D.length>0;){var U=D.pop(),V=P[U];f(V,function(t,e){return t-e});var q,H=V.length,G=B[U];if(0===G){var T=m[U];q=[T]}for(var v=0;H>v;++v){var Y=V[v];if(!(B[Y]>=0)&&(B[Y]=1^G,D.push(Y),0===G)){var T=m[Y];a(T)||(T.reverse(),q.push(T))}}0===G&&d.push(q)}return d}e.exports=a;var o=t("edges-to-adjacency-list"),s=t("planar-dual"),l=t("point-in-big-polygon"),c=t("two-product"),u=t("robust-sum"),f=t("uniq"),h=t("./lib/trim-leaves")},{"./lib/trim-leaves":282,"edges-to-adjacency-list":283,"planar-dual":284,"point-in-big-polygon":293,"robust-sum":262,"two-product":276,uniq:279}],295:[function(t,e,r){arguments[4][50][0].apply(r,arguments)},{dup:50}],296:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n,n.prototype.length=function(){return this.roots.length},n.prototype.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},n.prototype.find=function(t){for(var e=this.roots;e[t]!==t;){var r=e[t];e[t]=e[r],t=r}return t},n.prototype.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],297:[function(t,e,r){arguments[4][238][0].apply(r,arguments)},{"bit-twiddle":295,dup:238,"union-find":296}],298:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.abs(a(t,e,r)),i=Math.sqrt(Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2));return n/i}function i(t,e,r){function i(t){if(x[t])return 1/0;var r=m[t],i=y[t];return 0>r||0>i?1/0:n(e[t],e[r],e[i])}function a(t,e){var r=M[t],n=M[e];M[t]=n,M[e]=r,T[r]=e,T[n]=t}function s(t){return b[M[t]]}function l(t){return 1&t?t-1>>1:(t>>1)-1}function c(t){for(var e=s(t);;){var r=e,n=2*t+1,i=2*(t+1),o=t;if(L>n){var l=s(n);r>l&&(o=n,r=l)}if(L>i){var c=s(i);r>c&&(o=i)}if(o===t)return t;a(t,o),t=o}}function u(t){for(var e=s(t);t>0;){var r=l(t);if(r>=0){var n=s(r);if(n>e){a(t,r),t=r;continue}}return t}}function f(){if(L>0){var t=M[0];return a(0,L-1),L-=1,c(0),t}return-1}function h(t,e){var r=M[t];return b[r]===e?t:(b[r]=-(1/0),u(t),f(),b[r]=e,L+=1,u(L-1))}function d(t){if(!x[t]){x[t]=!0;var e=m[t],r=y[t];m[r]>=0&&(m[r]=e),y[e]>=0&&(y[e]=r),T[e]>=0&&h(T[e],i(e)),T[r]>=0&&h(T[r],i(r))}}function p(t,e){if(t[e]<0)return e;var r=e,n=e;do{var i=t[n];if(!x[n]||0>i||i===n)break;if(n=i,i=t[n],!x[n]||0>i||i===n)break;n=i,r=t[r]}while(r!==n);for(var a=e;a!==n;a=t[a])t[a]=n;return n}for(var g=e.length,v=t.length,m=new Array(g),y=new Array(g),b=new Array(g),x=new Array(g),_=0;g>_;++_)m[_]=y[_]=-1,b[_]=1/0,x[_]=!1;for(var _=0;v>_;++_){var w=t[_];if(2!==w.length)throw new Error("Input must be a graph");var k=w[1],A=w[0];-1!==y[A]?y[A]=-2:y[A]=k,-1!==m[k]?m[k]=-2:m[k]=A}for(var M=[],T=new Array(g),_=0;g>_;++_){var E=b[_]=i(_);1/0>E?(T[_]=M.length,M.push(_)):T[_]=-1}for(var L=M.length,_=L>>1;_>=0;--_)c(_);for(;;){var S=f();if(0>S||b[S]>r)break;d(S)}for(var C=[],_=0;g>_;++_)x[_]||(T[_]=C.length,C.push(e[_].slice()));var z=(C.length,[]);return t.forEach(function(t){var e=p(m,t[0]),r=p(y,t[1]);if(e>=0&&r>=0&&e!==r){var n=T[e],i=T[r];n!==i&&z.push([n,i])}}),o.unique(o.normalize(z)),{positions:C,edges:z}}e.exports=i;var a=t("robust-orientation"),o=t("simplicial-complex")},{"robust-orientation":259,"simplicial-complex":297}],299:[function(t,e,r){"use strict";e.exports=["",{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0},{path:"M2,2V-2H-2V2Z",backoff:0}]},{}],300:[function(t,e,r){"use strict";var n=t("./arrow_paths"),i=t("../../plots/font_attributes"),a=t("../../plots/cartesian/constants"),o=t("../../lib/extend").extendFlat;e.exports={_isLinkedToArray:!0,text:{valType:"string"},textangle:{valType:"angle",dflt:0},font:o({},i,{}),opacity:{valType:"number",min:0,max:1,dflt:1},align:{valType:"enumerated",values:["left","center","right"],dflt:"center"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)"},borderpad:{valType:"number",min:0,dflt:1},borderwidth:{valType:"number",min:0,dflt:1},showarrow:{valType:"boolean",dflt:!0},arrowcolor:{valType:"color"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1},arrowsize:{valType:"number",min:.3,dflt:1},arrowwidth:{valType:"number",min:.1},ax:{valType:"number",dflt:-10},ay:{valType:"number",dflt:-30},xref:{valType:"enumerated",values:["paper",a.idRegex.x.toString()]},x:{valType:"number"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto"},yref:{valType:"enumerated",values:["paper",a.idRegex.y.toString()]},y:{valType:"number"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"},_deprecated:{ref:{valType:"string"}}}},{"../../lib/extend":376,"../../plots/cartesian/constants":408,"../../plots/font_attributes":421,"./arrow_paths":299}],301:[function(t,e,r){"use strict";function n(t,e){function r(e,r){return c.coerce(t,n,v.layoutAttributes,e,r)}var n={};r("opacity"),r("align"),r("bgcolor");var i=r("bordercolor"),a=f.opacity(i);r("borderpad");var o=r("borderwidth"),s=r("showarrow");s&&(r("arrowcolor",a?n.bordercolor:f.defaultLine),r("arrowhead"),r("arrowsize"),r("arrowwidth",2*(a&&o||1)),r("ax"),r("ay"),c.noneOrAll(t,n,["ax","ay"])),r("text",s?" ":"new text"),r("textangle"),c.coerceFont(r,"font",e.font);for(var l=["x","y"],h=0;2>h;h++){var d=l[h],p={_fullLayout:e},g=u.coerceRef(t,n,p,d),m=.5;if("paper"!==g){var y=u.getFromId(p,g);if(m=y.range[0]+m*(y.range[1]-y.range[0]),-1!==["date","category"].indexOf(y.type)&&"string"==typeof t[d]){var b;"date"===y.type?(b=c.dateTime2ms(t[d]),b!==!1&&(t[d]=b)):(y._categories||[]).length&&(b=y._categories.indexOf(t[d]),-1!==b&&(t[d]=b))}}r(d,m),s||r(d+"anchor")}return c.noneOrAll(t,n,["x","y"]),n}function i(t){var e=t._fullLayout;e.annotations.forEach(function(e){var r=u.getFromId(t,e.xref),n=u.getFromId(t,e.yref);if(r||n){var i=(e._xsize||0)/2,a=e._xshift||0,o=(e._ysize||0)/2,s=e._yshift||0,l=i-a,c=i+a,f=o-s,h=o+s;if(e.showarrow){var d=3*e.arrowsize*e.arrowwidth;l=Math.max(l,d),c=Math.max(c,d),f=Math.max(f,d),h=Math.max(h,d)}r&&r.autorange&&u.expand(r,[r.l2c(e.x)],{ppadplus:c,ppadminus:l}),n&&n.autorange&&u.expand(n,[n.l2c(e.y)],{ppadplus:h,ppadminus:f})}})}function a(t,e,r,n,i,a,o,s){var l=r-t,c=i-t,u=o-i,f=n-e,h=a-e,d=s-a,p=l*d-u*f;if(0===p)return null;var g=(c*d-u*h)/p,v=(c*f-l*h)/p;return 0>v||v>1||0>g||g>1?null:{x:t+l*g,y:e+f*g}}var o=t("d3"),s=t("fast-isnumeric"),l=t("../../plotly"),c=t("../../lib"),u=t("../../plots/cartesian/axes"),f=t("../color"),h=t("../drawing"),d=t("../../lib/svg_text_utils"),p=t("../../lib/setcursor"),g=t("../dragelement"),v=e.exports={};v.ARROWPATHS=t("./arrow_paths"),v.layoutAttributes=t("./attributes"),v.supplyLayoutDefaults=function(t,e){for(var r=t.annotations||[],i=e.annotations=[],a=0;at?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}tt.selectAll("tspan.line").attr({y:0,x:0});var n=W.select(".annotation-math-group"),i=!n.empty(),s=h.bBox((i?n:tt).node()),d=s.width,m=s.height,y=Math.round(d+2*$),b=Math.round(m+2*$);U._w=d,U._h=m;var x=!1;if(["x","y"].forEach(function(e){var n,i=u.getFromId(t,U[e+"ref"]||e),a=(G+("x"===e?0:90))*Math.PI/180,o=y*Math.abs(Math.cos(a))+b*Math.abs(Math.sin(a)),s=U[e+"anchor"];if(i){if(!i.autorange&&(U[e]-i.range[0])*(U[e]-i.range[1])>0)return void(x=!0);H[e]=i._offset+i.l2p(U[e]),n=.5}else n=U[e],"y"===e&&(n=1-n),H[e]="x"===e?S.l+S.w*n:S.t+S.h*n;var l=0;l=U.showarrow?U["a"+e]:o*r(n,s),H[e]+=l,U["_"+e+"type"]=i&&i.type,U["_"+e+"size"]=o,U["_"+e+"shift"]=l}),x)return void W.remove();var w,k;U.showarrow&&(w=c.constrain(H.x-U.ax,1,_.width-1),k=c.constrain(H.y-U.ay,1,_.height-1)),H.x=c.constrain(H.x,1,_.width-1),H.y=c.constrain(H.y,1,_.height-1);var A=$-s.top,M=$-s.left;i?n.select("svg").attr({x:$-1,y:$}):(tt.attr({x:M,y:A}),tt.selectAll("tspan.line").attr({y:A,x:M})),Q.call(h.setRect,Z/2,Z/2,y-Z,b-Z);var T=Math.round(H.x-y/2),E=Math.round(H.y-b/2);W.call(c.setTranslate,T,E);var L="annotations["+e+"]",C=function(r,n){o.select(t).selectAll('.annotation-arrow-g[data-index="'+e+'"]').remove();var i=H.x+r,s=H.y+n,u=c.rotationXYMatrix(G,i,s),h=c.apply2DTransform(u),d=c.apply2DTransform2(u),p=Q.attr("width")/2,m=Q.attr("height")/2,y=[[i-p,s-m,i-p,s+m],[i-p,s+m,i+p,s+m],[i+p,s+m,i+p,s-m],[i+p,s-m,i-p,s-m]].map(d);if(!y.reduce(function(t,e){return t^!!a(w,k,w+1e6,k+1e6,e[0],e[1],e[2],e[3])},!1)){y.forEach(function(t){var e=a(i,s,w,k,t[0],t[1],t[2],t[3]);e&&(i=e.x,s=e.y)});var b=U.arrowwidth,x=U.arrowcolor,_=Y.append("g").style({opacity:f.opacity(x)}).classed("annotation-arrow-g",!0).attr("data-index",String(e)),A=_.append("path").attr("d","M"+i+","+s+"L"+w+","+k).style("stroke-width",b+"px").call(f.stroke,f.rgb(x));v.arrowhead(A,U.arrowhead,"end",U.arrowsize);var M=_.append("path").classed("annotation",!0).classed("anndrag",!0).attr({"data-index":String(e),d:"M3,3H-3V-3H3ZM0,0L"+(i-w)+","+(s-k),transform:"translate("+w+","+k+")"}).style("stroke-width",b+6+"px").call(f.stroke,"rgba(0,0,0,0)").call(f.fill,"rgba(0,0,0,0)");if(t._context.editable){var T,E,C;g.init({element:M.node(),prepFn:function(){var t=c.getTranslate(W);E=t.x,C=t.y,T={},V&&V.autorange&&(T[V._name+".autorange"]=!0),q&&q.autorange&&(T[q._name+".autorange"]=!0)},moveFn:function(t,e){_.attr("transform","translate("+t+","+e+")");var r=h(E,C),n=r[0]+t,i=r[1]+e;W.call(c.setTranslate,n,i),T[L+".x"]=V?U.x+t/V._m:(w+t-S.l)/S.w,T[L+".y"]=q?U.y+e/q._m:1-(k+e-S.t)/S.h,X.attr({transform:"rotate("+G+","+n+","+i+")"})},doneFn:function(e){if(e){l.relayout(t,T);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}};U.showarrow&&C(0,0);var z=c.rotationXYMatrix(G,H.x,H.y),P=c.apply2DTransform(z);if(t._context.editable){var R,O,I;g.init({element:W.node(),prepFn:function(){var t=c.getTranslate(W);R=t.x,O=t.y,I={}},moveFn:function(t,e){W.call(c.setTranslate,R+t,O+e);var r="pointer";if(U.showarrow)I[L+".ax"]=U.ax+t,I[L+".ay"]=U.ay+e,C(t,e);else{if(V)I[L+".x"]=U.x+t/V._m;else{var n=U._xsize/S.w,i=U.x+U._xshift/S.w-n/2;I[L+".x"]=g.align(i+t/S.w,n,0,1,U.xanchor)}if(q)I[L+".y"]=U.y+e/q._m;else{var a=U._ysize/S.h,o=U.y-U._yshift/S.h-a/2;I[L+".y"]=g.align(o-e/S.h,a,0,1,U.yanchor)}V&&q||(r=g.getCursor(V?.5:I[L+".x"],q?.5:I[L+".y"],U.xanchor,U.yanchor))}var s=P(R,O),l=s[0]+t,u=s[1]+e;W.call(c.setTranslate,R+t,O+e),X.attr({transform:"rotate("+G+","+l+","+u+")"}),p(W,r)},doneFn:function(e){if(p(W),e){l.relayout(t,I);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}var b,x=t.layout,_=t._fullLayout;if(!s(e)||-1===e){if(!e&&Array.isArray(i))return x.annotations=i,v.supplyLayoutDefaults(x,_),void v.drawAll(t);if("remove"===i)return delete x.annotations,_.annotations=[],void v.drawAll(t);if(r&&"add"!==i){for(b=0;b<_.annotations.length;b++)v.draw(t,b,r,i);return}e=_.annotations.length,_.annotations.push({})}if(!r&&i){if("remove"===i){for(_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove(),_.annotations.splice(e,1),x.annotations.splice(e,1),b=e;b<_.annotations.length;b++)_._infolayer.selectAll('.annotation[data-index="'+(b+1)+'"]').attr("data-index",String(b)),v.draw(t,b);return}if("add"===i||c.isPlainObject(i)){_.annotations.splice(e,0,{});var w=c.isPlainObject(i)?c.extendFlat({},i):{text:"New text"};for(x.annotations?x.annotations.splice(e,0,w):x.annotations=[w],b=_.annotations.length-1;b>e;b--)_._infolayer.selectAll('.annotation[data-index="'+(b-1)+'"]').attr("data-index",String(b)),v.draw(t,b)}}_._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove();var k=x.annotations[e],A=_.annotations[e];if(k){var M={xref:k.xref,yref:k.yref},T={};"string"==typeof r&&r?T[r]=i:c.isPlainObject(r)&&(T=r);var E=Object.keys(T);for(b=0;bb;b++){var z=C[b];if(void 0===T[z]&&void 0!==k[z]){var P=u.getFromId(t,u.coerceRef(M,{},t,z)),R=u.getFromId(t,u.coerceRef(k,{},t,z)),O=k[z],I=A["_"+z+"type"];if(void 0!==T[z+"ref"]){var N="auto"===k[z+"anchor"],j="x"===z?S.w:S.h,F=(A["_"+z+"size"]||0)/(2*j);if(P&&R)O=(O-P.range[0])/(P.range[1]-P.range[0]),O=R.range[0]+O*(R.range[1]-R.range[0]);else if(P){if(O=(O-P.range[0])/(P.range[1]-P.range[0]),O=P.domain[0]+O*(P.domain[1]-P.domain[0]),N){var D=O+F,B=O-F;2/3>O+B?O=B:O+D>4/3&&(O=D)}}else R&&(N&&(1/3>O?O+=F:O>2/3&&(O-=F)),O=(O-R.domain[0])/(R.domain[1]-R.domain[0]),O=R.range[0]+O*(R.range[1]-R.range[0]))}R&&R===P&&I&&("log"===I&&"log"!==R.type?O=Math.pow(10,O):"log"!==I&&"log"===R.type&&(O=O>0?Math.log(O)/Math.LN10:void 0)),k[z]=O}}var U=n(k,_);_.annotations[e]=U;var V=u.getFromId(t,U.xref),q=u.getFromId(t,U.yref),H={x:0,y:0},G=+U.textangle||0,Y=_._infolayer.append("g").classed("annotation",!0).attr("data-index",String(e)).style("opacity",U.opacity).on("click",function(){t._dragging=!1,t.emit("plotly_clickannotation",{index:e,annotation:k,fullAnnotation:U})}),X=Y.append("g").classed("annotation-text-g",!0).attr("data-index",String(e)),W=X.append("g"),Z=U.borderwidth,K=U.borderpad,$=Z+K,Q=W.append("rect").attr("class","bg").style("stroke-width",Z+"px").call(f.stroke,U.bordercolor).call(f.fill,U.bgcolor),J=U.font,tt=W.append("text").classed("annotation",!0).attr("data-unformatted",U.text).text(U.text);t._context.editable?tt.call(d.makeEditable,W).call(m).on("edit",function(r){U.text=r,this.attr({"data-unformatted":U.text}),this.call(m);var n={};n["annotations["+e+"].text"]=U.text,V&&V.autorange&&(n[V._name+".autorange"]=!0),q&&q.autorange&&(n[q._name+".autorange"]=!0),l.relayout(t,n)}):tt.call(m),X.attr({transform:"rotate("+G+","+H.x+","+H.y+")"}).call(h.setPosition,H.x,H.y)}},v.arrowhead=function(t,e,r,n){s(n)||(n=1);var i=t.node(),a=v.ARROWPATHS[e||0];if(a){"string"==typeof r&&r||(r="end");var l,c,u,d,p=(h.getPx(t,"stroke-width")||1)*n,g=t.style("stroke")||f.defaultLine,m=t.style("stroke-opacity")||1,y=r.indexOf("start")>=0,b=r.indexOf("end")>=0,x=a.backoff*p;if("line"===i.nodeName){if(l={x:+t.attr("x1"),y:+t.attr("y1")},c={x:+t.attr("x2"),y:+t.attr("y2")},u=Math.atan2(l.y-c.y,l.x-c.x),d=u+Math.PI,x){var _=x*Math.cos(u),w=x*Math.sin(u);y&&(l.x-=_,l.y-=w,t.attr({x1:l.x,y1:l.y})),b&&(c.x+=_,c.y+=w,t.attr({x2:c.x,y2:c.y}))}}else if("path"===i.nodeName){var k=i.getTotalLength(),A="";if(y){var M=i.getPointAtLength(0),T=i.getPointAtLength(.1);u=Math.atan2(M.y-T.y,M.x-T.x),l=i.getPointAtLength(Math.min(x,k)),x&&(A="0px,"+x+"px,")}if(b){var E=i.getPointAtLength(k),L=i.getPointAtLength(k-.1);if(d=Math.atan2(E.y-L.y,E.x-L.x),c=i.getPointAtLength(Math.max(0,k-x)),x){var S=A?2*x:x;A+=k-S+"px,"+k+"px"}}else A&&(A+=k+"px");A&&t.style("stroke-dasharray",A)}var C=function(r,n){e>5&&(n=0),o.select(i.parentElement).append("path").attr({"class":t.attr("class"),d:a.path,transform:"translate("+r.x+","+r.y+")rotate("+180*n/Math.PI+")scale("+p+")"}).style({fill:g,opacity:m,"stroke-width":0})};y&&C(l,u),b&&C(c,d)}},v.calcAutorange=function(t){var e=t._fullLayout,r=e.annotations;if(r.length&&t._fullData.length){var n={};r.forEach(function(t){n[t.xref]=!0,n[t.yref]=!0});var a=u.list(t).filter(function(t){return t.autorange&&n[t._id]});if(a.length)return c.syncOrAsync([v.drawAll,i],t)}}},{"../../lib":381,"../../lib/setcursor":389,"../../lib/svg_text_utils":393,"../../plotly":400,"../../plots/cartesian/axes":403,"../color":303,"../dragelement":323,"../drawing":325,"./arrow_paths":299,"./attributes":300,d3:113,"fast-isnumeric":117}],302:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.lightFraction=1e3/11},{}],303:[function(t,e,r){"use strict";function n(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}var i=t("tinycolor2"),a=t("fast-isnumeric"),o=e.exports={},s=t("./attributes");o.defaults=s.defaults,o.defaultLine=s.defaultLine,o.lightLine=s.lightLine,o.background=s.background,o.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},o.rgb=function(t){return o.tinyRGB(i(t))},o.opacity=function(t){return t?i(t).getAlpha():0},o.addOpacity=function(t,e){var r=i(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},o.combine=function(t,e){var r=i(t).toRgb();if(1===r.a)return i(t).toRgbString();var n=i(e||o.background).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},s={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return i(s).toRgbString()},o.stroke=function(t,e){var r=i(e);t.style({stroke:o.tinyRGB(r),"stroke-opacity":r.getAlpha()})},o.fill=function(t,e){var r=i(e);t.style({fill:o.tinyRGB(r),"fill-opacity":r.getAlpha()})},o.clean=function(t){if(t&&"object"==typeof t){var e,r,i,a,s=Object.keys(t);for(e=0;el&&(a[1]-=(ot-l)/2)):r.node()&&!r.classed("js-placeholder")&&(ot=h.bBox(e.node()).height),ot){if(ot+=5,"top"===x.titleside)Q.domain[1]-=ot/M.h,a[1]*=-1;else{Q.domain[0]+=ot/M.h;var u=Math.max(1,r.selectAll("tspan.line").size());a[1]+=(1-u)*l}e.attr("transform","translate("+a+")"),Q.setScale()}}it.selectAll(".cbfills,.cblines,.cbaxis").attr("transform","translate(0,"+Math.round(M.h*(1-Q.domain[1]))+")");var f=it.select(".cbfills").selectAll("rect.cbfill").data(S);f.enter().append("rect").classed("cbfill",!0).style("stroke","none"),f.exit().remove(),f.each(function(t,e){var r=[0===e?E[0]:(S[e]+S[e-1])/2,e===S.length-1?E[1]:(S[e]+S[e+1])/2].map(Q.c2p).map(Math.round);e!==S.length-1&&(r[1]+=r[1]>r[0]?1:-1);var a=z(t).replace("e-",""),o=i(a).toHexString();n.select(this).attr({x:Y,width:Math.max(D,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var d=it.select(".cblines").selectAll("path.cbline").data(x.line.color&&x.line.width?L:[]);return d.enter().append("path").classed("cbline",!0),d.exit().remove(),d.each(function(t){n.select(this).attr("d","M"+Y+","+(Math.round(Q.c2p(t))+x.line.width/2%1)+"h"+D).call(h.lineGroupStyle,x.line.width,C(t),x.line.dash)}),Q._axislayer.selectAll("g."+Q._id+"tick,path").remove(),Q._pos=Y+D+(x.outlinewidth||0)/2-("outside"===x.ticks?1:0),Q.side="right",c.syncOrAsync([function(){return s.doTicks(t,Q,!0)},function(){if(-1===["top","bottom"].indexOf(x.titleside)){var e=Q.titlefont.size,r=Q._offset+Q._length/2,i=M.l+(Q.position||0)*M.w+("right"===Q.side?10+e*(Q.showticklabels?1:.5):-10-e*(Q.showticklabels?.5:0));w("h"+Q._id+"title",{avoid:{selection:n.select(t).selectAll("g."+Q._id+"tick"),side:x.titleside,offsetLeft:M.l,offsetTop:M.t,maxShift:A.width},attributes:{x:i,y:r,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])}function w(e,r){var n,i=b();n=o.traceIs(i,"markerColorscale")?"marker.colorbar.title":"colorbar.title";var a={propContainer:Q,propName:n,traceIndex:i.index,dfltName:"colorscale",containerGroup:it.select(".cbtitle")},s="h"===e.charAt(0)?e.substr(1):"h"+e;it.selectAll("."+s+",."+s+"-math-group").remove(),p.draw(t,e,u(a,r||{}))}function k(){var r=D+x.outlinewidth/2+h.bBox(Q._axislayer.node()).width;if(N=at.select("text"),N.node()&&!N.classed("js-placeholder")){var n,i=at.select(".h"+Q._id+"title-math-group").node();n=i&&-1!==["top","bottom"].indexOf(x.titleside)?h.bBox(i).width:h.bBox(at.node()).right-Y-M.l,r=Math.max(r,n)}var a=2*x.xpad+r+x.borderwidth+x.outlinewidth/2,s=Z-K;it.select(".cbbg").attr({x:Y-x.xpad-(x.borderwidth+x.outlinewidth)/2,y:K-H,width:Math.max(a,2),height:Math.max(s+2*H,2)}).call(d.fill,x.bgcolor).call(d.stroke,x.bordercolor).style({"stroke-width":x.borderwidth}),it.selectAll(".cboutline").attr({x:Y,y:K+x.ypad+("top"===x.titleside?ot:0),width:Math.max(D,2),height:Math.max(s-2*x.ypad-ot,2)}).call(d.stroke,x.outlinecolor).style({fill:"None","stroke-width":x.outlinewidth});var l=({center:.5,right:1}[x.xanchor]||0)*a;it.attr("transform","translate("+(M.l-l)+","+M.t+")"),o.autoMargin(t,e,{x:x.x,y:x.y,l:a*({right:1,center:.5}[x.xanchor]||0),r:a*({left:1,center:.5}[x.xanchor]||0),t:s*({bottom:1,middle:.5}[x.yanchor]||0),b:s*({top:1,middle:.5}[x.yanchor]||0)})}var A=t._fullLayout,M=A._size;if("function"!=typeof x.fillcolor&&"function"!=typeof x.line.color)return void A._infolayer.selectAll("g."+e).remove();var T,E=n.extent(("function"==typeof x.fillcolor?x.fillcolor:x.line.color).domain()),L=[],S=[],C="function"==typeof x.line.color?x.line.color:function(){return x.line.color},z="function"==typeof x.fillcolor?x.fillcolor:function(){return x.fillcolor},P=x.levels.end+x.levels.size/100,R=x.levels.size,O=1.001*E[0]-.001*E[1],I=1.001*E[1]-.001*E[0];for(T=x.levels.start;0>(T-P)*R;T+=R)T>O&&I>T&&L.push(T);if("function"==typeof x.fillcolor)if(x.filllevels)for(P=x.filllevels.end+x.filllevels.size/100,R=x.filllevels.size,T=x.filllevels.start;0>(T-P)*R;T+=R)T>E[0]&&T1){var nt=Math.pow(10,Math.floor(Math.log(rt)/Math.LN10));tt*=nt*c.roundUp(rt/nt,[2,5,10]),(Math.abs(x.levels.start)/x.levels.size+1e-6)%1<2e-6&&(Q.tick0=0)}Q.dtick=tt}Q.domain=[W+G,W+V-G],Q.setScale();var it=A._infolayer.selectAll("g."+e).data([0]);it.enter().append("g").classed(e,!0).each(function(){var t=n.select(this);t.append("rect").classed("cbbg",!0),t.append("g").classed("cbfills",!0),t.append("g").classed("cblines",!0),t.append("g").classed("cbaxis",!0).classed("crisp",!0),t.append("g").classed("cbtitleunshift",!0).append("g").classed("cbtitle",!0),t.append("rect").classed("cboutline",!0),t.select(".cbtitle").datum(0)}),it.attr("transform","translate("+Math.round(M.l)+","+Math.round(M.t)+")");var at=it.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(M.l)+",-"+Math.round(M.t)+")");Q._axislayer=it.select(".cbaxis");var ot=0;if(-1!==["top","bottom"].indexOf(x.titleside)){var st,lt=M.l+(x.x+q)*M.w,ct=Q.titlefont.size;st="top"===x.titleside?(1-(W+V-G))*M.h+M.t+3+.75*ct:(1-(W+G))*M.h+M.t-3-.25*ct,w(Q._id+"title",{attributes:{x:lt,y:st,"text-anchor":"start"}})}var ut=c.syncOrAsync([o.previousPromises,_,o.previousPromises,k],t);if(ut&&ut.then&&(t._promises||[]).push(ut),t._context.editable){var ft,ht,dt;l.init({element:it.node(),prepFn:function(){ft=it.attr("transform"),f(it)},moveFn:function(t,e){it.attr("transform",ft+" translate("+t+","+e+")"),ht=l.align(X+t/M.w,B,0,1,x.xanchor),dt=l.align(W-e/M.h,V,0,1,x.yanchor);var r=l.getCursor(ht,dt,x.xanchor,x.yanchor);f(it,r)},doneFn:function(e){f(it),e&&void 0!==ht&&void 0!==dt&&a.restyle(t,{"colorbar.x":ht,"colorbar.y":dt},b().index)}})}return ut}function b(){var r,n,i=e.substr(2);for(r=0;ru*f?i.RdBu:u>=0?i.Reds:i.Blues,l.colorscale=h,s.reversescale&&(h=a(h)),s.colorscale=h)}},{"../../lib":381,"./flip_scale":313,"./scales":320}],311:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":320}],312:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./is_valid_scale"),l=t("./flip_scale");e.exports=function(t,e,r,c,u){var f=u.prefix,h=u.cLetter,d=f.slice(0,f.length-1),p=f?i.nestedProperty(t,d).get()||{}:t,g=f?i.nestedProperty(e,d).get()||{}:e,v=p[h+"min"],m=p[h+"max"],y=p.colorscale,b=n(v)&&n(m)&&m>v;c(f+h+"auto",!b),c(f+h+"min"),c(f+h+"max");var x;void 0!==y&&(x=!s(y)),c(f+"autocolorscale",x);var _=c(f+"colorscale"),w=c(f+"reversescale");if(w&&(g.colorscale=l(_)),"marker.line."!==f){var k;f&&(k=a(p));var A=c(f+"showscale",k);A&&o(p,g,r)}}},{"../../lib":381,"../colorbar/defaults":305,"../colorbar/has_colorbar":307,"./flip_scale":313,"./is_valid_scale":317,"fast-isnumeric":117}],313:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n}},{}],314:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./default_scale"),a=t("./is_valid_scale_array");e.exports=function(t,e){function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return e||(e=i),t?("string"==typeof t&&(r(),"string"==typeof t&&r()),a(t)?t:e):e}},{"./default_scale":311,"./is_valid_scale_array":318,"./scales":320}],315:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("./is_valid_scale");e.exports=function(t,e){var r=e?i.nestedProperty(t,e).get()||{}:t,o=r.color,s=!1;if(Array.isArray(o))for(var l=0;lh;h++)l=t[h],u[h]=e+l[0]*(r-e),f[h]=i(l[1]).toRgb();var d=n.scale.linear().domain(u).interpolate(n.interpolateObject).range(f);return function(t){if(a(t)){var n=o.constrain(t,e,r),l=d(n);return i(l).toRgbString()}return i(t).isValid()?t:s.defaultLine}}},{"../../lib":381,"../color":303,d3:113,"fast-isnumeric":117,tinycolor2:274}],320:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]]}},{}],321:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,i){var a=(t-r)/(n-r),o=a+e/(n-r),s=(a+o)/2;return"left"===i||"bottom"===i?a:"center"===i||"middle"===i?s:"right"===i||"top"===i?o:2/3-s>a?a:o>4/3-s?o:s}},{}],322:[function(t,e,r){"use strict";var n=t("../../lib"),i=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,a){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===a?0:"middle"===a?1:"top"===a?2:n.constrain(Math.floor(3*e),0,2),i[e][t]}},{"../../lib":381}],323:[function(t,e,r){"use strict";function n(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function i(t){t._dragging=!1,t._replotPending&&a.plot(t)}var a=t("../../plotly"),o=t("../../lib"),s=t("../../plots/cartesian/constants"),l=e.exports={};l.align=t("./align"),l.getCursor=t("./cursor");var c=t("./unhover");l.unhover=c.wrapped,l.unhoverRaw=c.raw,l.init=function(t){function e(e){return p._dragged=!1,p._dragging=!0,c=e.clientX,u=e.clientY,d=e.target,f=(new Date).getTime(),f-p._mouseDownTimev&&(g=Math.max(g-1,1)),t.doneFn&&t.doneFn(p._dragged,g),!p._dragged){var r=document.createEvent("MouseEvents");r.initEvent("click",!0,!0),d.dispatchEvent(r)}return i(p),p._dragged=!1,o.pauseEvent(e)}var c,u,f,h,d,p=o.getPlotDiv(t.element)||{},g=1,v=s.DBLCLICKDELAY;p._mouseDownTime||(p._mouseDownTime=0),t.element.onmousedown=e,t.element.style.pointerEvents="all"}},{"../../lib":381,"../../plotly":400,"../../plots/cartesian/constants":408,"./align":321,"./cursor":322,"./unhover":324}],324:[function(t,e,r){"use strict";var n=t("../../lib/events"),i=e.exports={};i.wrapped=function(t,e,r){"string"==typeof t&&(t=document.getElementById(t)),t._hoverTimer&&(clearTimeout(t._hoverTimer),t._hoverTimer=void 0),i.raw(t,e,r)},i.raw=function(t,e){var r=t._fullLayout;e||(e={}),e.target&&n.triggerHandler(t,"plotly_beforehover",e)===!1||(r._hoverlayer.selectAll("g").remove(),e.target&&t._hoverdata&&t.emit("plotly_unhover",{points:t._hoverdata}),t._hoverdata=void 0)}},{"../../lib/events":375}],325:[function(t,e,r){"use strict";function n(t,e,r,n){var a=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],c=Math.pow(a*a+o*o,x/2),u=Math.pow(s*s+l*l,x/2),f=(u*u*a-c*c*s)*n,h=(u*u*o-c*c*l)*n,d=3*u*(c+u),p=3*c*(c+u);return[[i.round(e[0]+(d&&f/d),2),i.round(e[1]+(d&&h/d),2)],[i.round(e[0]-(p&&f/p),2),i.round(e[1]-(p&&h/p),2)]]}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../plots/plots"),s=t("../color"),l=t("../colorscale"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),h=t("../../traces/scatter/subtypes"),d=t("../../traces/scatter/make_bubble_size_func"),p=e.exports={};p.font=function(t,e,r,n){e&&e.family&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(s.fill,n)},p.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},p.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},p.setRect=function(t,e,r,n,i){t.call(p.setPosition,e,r).call(p.setSize,n,i)},p.translatePoints=function(t,e,r){t.each(function(t){var n=t.xp||e.c2p(t.x),o=t.yp||r.c2p(t.y),s=i.select(this);a(n)&&a(o)?"text"===this.nodeName?s.attr("x",n).attr("y",o):s.attr("transform","translate("+n+","+o+")"):s.remove()})},p.getPx=function(t,e){return Number(t.style(e).replace(/px$/,""))},p.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:1>e?1:Math.round(e):r||0},p.lineGroupStyle=function(t,e,r,n){t.style("fill","none").each(function(t){var a=(((t||[])[0]||{}).trace||{}).line||{},o=e||a.width||0,l=n||a.dash||"";i.select(this).call(s.stroke,r||a.color).call(p.dashLine,l,o)})},p.dashLine=function(t,e,r){var n=Math.max(r,3);"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},p.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=i.select(this);try{r.call(s.fill,e[0].trace.fillcolor)}catch(n){console.log(n,t),r.remove()}})};var g=t("./symbol_defs");p.symbolNames=[],p.symbolFuncs=[],p.symbolNeedLines={},p.symbolNoDot={},p.symbolList=[],Object.keys(g).forEach(function(t){var e=g[t];p.symbolList=p.symbolList.concat([e.n,t,e.n+100,t+"-open"]),p.symbolNames[e.n]=t,p.symbolFuncs[e.n]=e.f,e.needLine&&(p.symbolNeedLines[e.n]=!0),e.noDot?p.symbolNoDot[e.n]=!0:p.symbolList=p.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"])});var v=p.symbolNames.length,m="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";p.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),t=p.symbolNames.indexOf(t),t>=0&&(t+=e)}return t%100>=v||t>=400?0:Math.floor(Math.max(t,0))},p.pointStyle=function(t,e){if(t.size()){var r=e.marker,n=r.line;if(o.traceIs(e,"symbols")){var a=d(e);t.attr("d",function(t){var n;n="various"===t.ms||"various"===r.size?3:h.isBubble(e)?a(t.ms):(r.size||6)/2,t.mrc=n;var i=p.symbolNumber(t.mx||r.symbol)||0,o=i%100;return t.om=i%200>=100,p.symbolFuncs[o](n)+(i>=200?m:"")}).style("opacity",function(t){return(t.mo+1||r.opacity+1)-1})}var l=(e._input||{}).marker||{},c=p.tryColorscale(r,l,""),u=p.tryColorscale(r,l,"line.");t.each(function(t){var e,a,o;t.so?(o=n.outlierwidth,a=n.outliercolor,e=r.outliercolor):(o=(t.mlw+1||n.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,a="mlc"in t?t.mlcc=u(t.mlc):Array.isArray(n.color)?s.defaultLine:n.color,e="mc"in t?t.mcc=c(t.mc):Array.isArray(r.color)?s.defaultLine:r.color||"rgba(0,0,0,0)");var l=i.select(this);t.om?l.call(s.stroke,e).style({"stroke-width":(o||1)+"px",fill:"none"}):(l.style("stroke-width",o+"px").call(s.fill,e),o&&l.call(s.stroke,a))})}},p.tryColorscale=function(t,e,r){var n=c.nestedProperty(t,r+"color").get(),i=c.nestedProperty(t,r+"colorscale").get(),o=c.nestedProperty(t,r+"cauto").get(),s=c.nestedProperty(t,r+"cmin"),u=c.nestedProperty(t,r+"cmax"),f=s.get(),h=u.get();return i&&Array.isArray(n)?(!o&&a(f)&&a(h)||(f=1/0,h=-(1/0),n.forEach(function(t){a(t)&&(f>t&&(f=+t),t>h&&(h=+t))}),f>h&&(f=0,h=1),s.set(f),u.set(h),c.nestedProperty(e,r+"cmin").set(f),c.nestedProperty(e,r+"cmax").set(h)),l.makeScaleFunction(i,f,h)):c.identity};var y={start:1,end:-1,middle:0,bottom:1,top:-1},b=1.3;p.textPointStyle=function(t,e){t.each(function(t){var r=i.select(this),n=t.tx||e.text;if(!n||Array.isArray(n))return void r.remove();var o=t.tp||e.textposition,s=-1!==o.indexOf("top")?"top":-1!==o.indexOf("bottom")?"bottom":"middle",l=-1!==o.indexOf("left")?"end":-1!==o.indexOf("right")?"start":"middle",c=t.ts||e.textfont.size,f=t.mrc?t.mrc/.8+1:0;c=a(c)&&c>0?c:0,r.call(p.font,t.tf||e.textfont.family,c,t.tc||e.textfont.color).attr("text-anchor",l).text(n).call(u.convertToTspans);var h=i.select(this.parentNode),d=r.selectAll("tspan.line"),g=((d[0].length||1)-1)*b+1,v=y[l]*f,m=.75*c+y[s]*f+(y[s]-1)*g*c/2;h.attr("transform","translate("+v+","+m+")"),g>1&&d.attr({x:r.attr("x"),y:r.attr("y")})})};var x=.5;p.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,i="M"+t[0],a=[];for(r=1;rr;r++)o.push(n(t[r-1],t[r],t[r+1],e));for(o.push(n(t[a-1],t[a],t[0],e)),r=1;a>=r;r++)i+="C"+o[r-1][1]+" "+o[r][0]+" "+t[r];return i+="C"+o[a][1]+" "+o[0][0]+" "+t[0]+"Z"};var _={hv:function(t,e){return"H"+i.round(e[0],2)+"V"+i.round(e[1],2)},vh:function(t,e){return"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},hvh:function(t,e){return"H"+i.round((t[0]+e[0])/2,2)+"V"+i.round(e[1],2)+"H"+i.round(e[0],2)},vhv:function(t,e){return"V"+i.round((t[1]+e[1])/2,2)+"H"+i.round(e[0],2)+"V"+i.round(e[1],2)}},w=function(t,e){return"L"+i.round(e[0],2)+","+i.round(e[1],2)};p.steps=function(t){var e=_[t]||w;return function(t){for(var r="M"+i.round(t[0][0],2)+","+i.round(t[0][1],2),n=1;n=A&&(i.selectAll("[data-bb]").attr("data-bb",null),k=[]),t.setAttribute("data-bb",k.length),k.push(l),c.extendFlat({},l)},p.setClipUrl=function(t,e){if(!e)return void t.attr("clip-path",null);var r="#"+e,n=i.select("base");n.size()&&n.attr("href")&&(r=window.location.href+r),t.attr("clip-path","url("+r+")")}},{"../../constants/xmlns_namespaces":369,"../../lib":381,"../../lib/svg_text_utils":393,"../../plots/plots":452,"../../traces/scatter/make_bubble_size_func":567,"../../traces/scatter/subtypes":573,"../color":303,"../colorscale":316,"./symbol_defs":326,d3:113,"fast-isnumeric":117}],326:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+","+r+"H"+e+"L0,-"+i+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+",-"+r+"H"+e+"L0,"+i+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M"+r+",-"+e+"V"+e+"L-"+i+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+r+",-"+e+"V"+e+"L"+i+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(t*-.309,2),o=n.round(.809*t,2);return"M"+e+","+a+"L"+r+","+o+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(e*-.309,2),c=n.round(.118*e,2),u=n.round(.809*e,2),f=n.round(.382*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+c+"L"+o+","+u+"L0,"+f+"L-"+o+","+u+"L-"+a+","+c+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0}}},{d3:113}],327:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"]},symmetric:{valType:"boolean"},array:{valType:"data_array"},arrayminus:{valType:"data_array"},value:{valType:"number",min:0,dflt:10},valueminus:{valType:"number",min:0,dflt:10},traceref:{valType:"integer",min:0,dflt:0},tracerefminus:{valType:"integer",min:0,dflt:0},copy_ystyle:{valType:"boolean"},copy_zstyle:{valType:"boolean"},color:{valType:"color"},thickness:{valType:"number",min:0,dflt:2},width:{valType:"number",min:0},_deprecated:{opacity:{valType:"number"}}}},{}],328:[function(t,e,r){"use strict";function n(t,e,r,n){var a=e["error_"+n]||{},l=a.visible&&-1!==["linear","log"].indexOf(r.type),c=[];if(l){for(var u=s(a),f=0;fs;s++)o[s]={x:r[s],y:i[s]};return o[0].trace=t,n.calc({calcdata:[o],_fullLayout:e}),o},n.plot=t("./plot"),n.style=t("./style"),n.hoverInfo=function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys)),(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}},{"./attributes":327,"./calc":328,"./defaults":330,"./plot":332,"./style":333}],332:[function(t,e,r){"use strict";function n(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../lib"),s=t("../../traces/scatter/subtypes");e.exports=function(t,e){var r=e.x(),l=e.y();t.each(function(t){var e=t[0].trace,c=e.error_x||{},u=e.error_y||{},f=s.hasMarkers(e)&&e.marker.maxdisplayed>0;if(u.visible||c.visible){var h=i.select(this).selectAll("g.errorbar").data(o.identity);h.enter().append("g").classed("errorbar",!0),h.each(function(t){var e=i.select(this),o=n(t,r,l);if(!f||t.vis){var s;if(u.visible&&a(o.x)&&a(o.yh)&&a(o.ys)){var h=u.width;s="M"+(o.x-h)+","+o.yh+"h"+2*h+"m-"+h+",0V"+o.ys,o.noYS||(s+="m-"+h+",0h"+2*h),e.append("path").classed("yerror",!0).attr("d",s)}if(c.visible&&a(o.y)&&a(o.xh)&&a(o.xs)){var d=(c.copy_ystyle?u:c).width;s="M"+o.xh+","+(o.y-d)+"v"+2*d+"m0,-"+d+"H"+o.xs,o.noXS||(s+="m0,-"+d+"v"+2*d),e.append("path").classed("xerror",!0).attr("d",s)}}})}})}},{"../../lib":381,"../../traces/scatter/subtypes":573,d3:113,"fast-isnumeric":117}],333:[function(t,e,r){"use strict";var n=t("d3"),i=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},a=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(i.stroke,r.color),a.copy_ystyle&&(a=r),o.selectAll("path.xerror").style("stroke-width",a.thickness+"px").call(i.stroke,a.color)})}},{"../color":303,d3:113}],334:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants");e.exports={_isLinkedToArray:!0,source:{valType:"string"},layer:{valType:"enumerated",values:["below","above"],dflt:"above"},sizex:{valType:"number",dflt:0},sizey:{valType:"number",dflt:0},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain"},opacity:{valType:"number",min:0,max:1,dflt:1},x:{valType:"number",dflt:0},y:{valType:"number",dflt:0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper"}}},{"../../plots/cartesian/constants":408}],335:[function(t,e,r){"use strict";function n(t,e,r){function n(r,n){return a.coerce(t,e,o,r,n)}e=e||{},n("source"),n("layer"),n("x"),n("y"),n("xanchor"),n("yanchor"),n("sizex"),n("sizey"),n("sizing"),n("opacity");for(var s=0;2>s;s++){var l={_fullLayout:r},c=["x","y"][s];i.coerceRef(t,e,l,c,"paper")}return e}var i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./attributes");e.exports=function(t,e){if(t.images&&Array.isArray(t.images))for(var r=t.images,i=e.images=[],a=0;a=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],339:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat;e.exports={bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.defaultLine},borderwidth:{valType:"number",min:0,dflt:0},font:a({},n,{}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"]},tracegroupgap:{valType:"number",min:0,dflt:10},x:{valType:"number",min:-2,max:3,dflt:1.02},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"}}},{"../../lib/extend":376,"../../plots/font_attributes":421,"../color/attributes":302}],340:[function(t,e,r){"use strict";e.exports={scrollBarWidth:4,scrollBarHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],341:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/plots"),a=t("./attributes"),o=t("./helpers");e.exports=function(t,e,r){function s(t,e){return n.coerce(h,d,a,t,e)}for(var l,c,u,f,h=t.legend||{},d=e.legend={},p=0,g="normal",v=0;v1);if(y!==!1){if(s("bgcolor",e.paper_bgcolor),s("bordercolor"),s("borderwidth"),n.coerceFont(s,"font",e.font),s("orientation"),"h"===d.orientation){var b=t.xaxis;b&&b.rangeslider&&b.rangeslider.visible?(l=0,u="left",c=1.1,f="bottom"):(l=0,u="left",c=-.1,f="top")}s("traceorder",g),o.isGrouped(e.legend)&&s("tracegroupgap"),s("x",l),s("xanchor",u),s("y",c),s("yanchor",f),n.noneOrAll(h,d,["x","y"])}}},{"../../lib":381,"../../plots/plots":452,"./attributes":339,"./helpers":344}],342:[function(t,e,r){"use strict";function n(t,e){function r(r){u.util.convertToTspans(r,function(){r.selectAll("tspan.line").attr({x:r.attr("x")}),t.call(a,e)})}var n=t.data()[0][0],i=e._fullLayout,o=n.trace,s=h.traceIs(o,"pie"),l=o.index,c=s?n.label:o.name,f=t.selectAll("text.legendtext").data([0]);f.enter().append("text").classed("legendtext",!0),f.attr({x:40,y:0,"data-unformatted":c}).style("text-anchor","start").classed("user-select-none",!0).call(p.font,i.legend.font).text(c),e._context.editable&&!s?f.call(u.util.makeEditable).call(r).on("edit",function(t){this.attr({"data-unformatted":t}),this.text(t).call(r),this.text()||(t=" "),u.restyle(e,"name",t,l)}):f.call(r)}function i(t,e){var r=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],n=t.selectAll("rect").data([0]);n.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(g.fill,"rgba(0,0,0,0)"),n.on("click",function(){if(!e._dragged){var n,i,a=t.data()[0][0],o=e._fullData,s=a.trace,l=s.legendgroup,c=[];if(h.traceIs(s,"pie")){var f=a.label,d=r.indexOf(f);-1===d?r.push(f):r.splice(d,1),u.relayout(e,"hiddenlabels",r)}else{if(""===l)c=[s.index];else for(var p=0;ptspan"),d=h[0].length||1;r=l*d,n=u.node()&&p.bBox(u.node()).width;var g=l*(.3+(1-d)/2);u.attr("y",g),h.attr("y",g)}r=Math.max(r,16)+3,a.attr({x:0,y:-r/2,height:r}),i.height=r,i.width=n}function o(t,e,r){var n=t._fullLayout,i=n.legend,a=i.borderwidth,o=b.isGrouped(i);if(b.isVertical(i))o&&e.each(function(t,e){f.setTranslate(this,0,e*i.tracegroupgap)}),i.width=0,i.height=0,r.each(function(t){var e=t[0],r=e.height,n=e.width;f.setTranslate(this,a,5+a+i.height+r/2),i.height+=r,i.width=Math.max(i.width,n)}),i.width+=45+2*a,i.height+=10+2*a,o&&(i.height+=(i._lgroupsLength-1)*i.tracegroupgap),r.selectAll(".legendtoggle").attr("width",(t._context.editable?0:i.width)+40),i.width=Math.ceil(i.width),i.height=Math.ceil(i.height);else if(o){i.width=0,i.height=0;for(var s=[i.width],l=e.data(),u=0,h=l.length;h>u;u++){var d=l[u].map(function(t){return t[0].width}),p=40+Math.max.apply(null,d);i.width+=i.tracegroupgap+p,s.push(i.width)}e.each(function(t,e){f.setTranslate(this,s[e],0)}),e.each(function(){var t=c.select(this),e=t.selectAll("g.traces"),r=0;e.each(function(t){var e=t[0],n=e.height;f.setTranslate(this,0,5+a+r+n/2),r+=n}),i.height=Math.max(i.height,r)}),i.height+=10+2*a,i.width+=2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}else i.width=0,i.height=0,r.each(function(t){var e=t[0],r=40+e.width,n=i.tracegroupgap||5;f.setTranslate(this,a+i.width,5+a+e.height/2),i.width+=n+r,i.height=Math.max(i.height,e.height)}),i.width+=2*a,i.height+=10+2*a,i.width=Math.ceil(i.width),i.height=Math.ceil(i.height),r.selectAll(".legendtoggle").attr("width",t._context.editable?0:i.width)}function s(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center");var i="top";x.isBottomAnchor(r)?i="bottom":x.isMiddleAnchor(r)&&(i="middle"),h.autoMargin(t,"legend",{x:r.x,y:r.y,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:r.height*({top:1,middle:.5}[i]||0),t:r.height*({bottom:1,middle:.5}[i]||0)})}function l(t){var e=t._fullLayout,r=e.legend,n="left";x.isRightAnchor(r)?n="right":x.isCenterAnchor(r)&&(n="center"),h.autoMargin(t,"legend",{x:r.x,y:.5,l:r.width*({right:1,center:.5}[n]||0),r:r.width*({left:1,center:.5}[n]||0),b:0,t:0})}var c=t("d3"),u=t("../../plotly"),f=t("../../lib"),h=t("../../plots/plots"),d=t("../dragelement"),p=t("../drawing"),g=t("../color"),v=t("./constants"),m=t("./get_legend_data"),y=t("./style"),b=t("./helpers"),x=t("./anchor_utils");e.exports=function(t){function e(t,e){T.attr("data-scroll",e).call(f.setTranslate,0,e),E.call(p.setRect,j,t,v.scrollBarWidth,v.scrollBarHeight),A.select("rect").attr({y:b.borderwidth-e})}var r=t._fullLayout,a="legend"+r._uid;if(r._infolayer&&t.calcdata){var b=r.legend,_=r.showlegend&&m(t.calcdata,b),w=r.hiddenlabels||[];if(!r.showlegend||!_.length)return r._infolayer.selectAll(".legend").remove(),r._topdefs.select("#"+a).remove(),void h.autoMargin(t,"legend");"undefined"==typeof t.firstRender?t.firstRender=!0:t.firstRender&&(t.firstRender=!1);var k=r._infolayer.selectAll("g.legend").data([0]);k.enter().append("g").attr({"class":"legend","pointer-events":"all"});var A=r._topdefs.selectAll("#"+a).data([0]);A.enter().append("clipPath").attr("id",a).append("rect");var M=k.selectAll("rect.bg").data([0]);M.enter().append("rect").attr({"class":"bg","shape-rendering":"crispEdges"}).call(g.stroke,b.bordercolor).call(g.fill,b.bgcolor).style("stroke-width",b.borderwidth+"px");var T=k.selectAll("g.scrollbox").data([0]);T.enter().append("g").attr("class","scrollbox");var E=k.selectAll("rect.scrollbar").data([0]);E.enter().append("rect").attr({"class":"scrollbar",rx:20,ry:2,width:0,height:0}).call(g.fill,"#808BA4");var L=T.selectAll("g.groups").data(_);L.enter().append("g").attr("class","groups"),L.exit().remove();var S=L.selectAll("g.traces").data(f.identity);S.enter().append("g").attr("class","traces"),S.exit().remove(),S.call(y).style("opacity",function(t){var e=t[0].trace;return h.traceIs(e,"pie")?-1!==w.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){c.select(this).call(n,t).call(i,t)}),t.firstRender&&(o(t,L,S),s(t));var C=0,z=r.width,P=0,R=r.height;o(t,L,S),b.height>R?l(t):s(t);var O=r._size,I=O.l+O.w*b.x,N=O.t+O.h*(1-b.y);x.isRightAnchor(b)?I-=b.width:x.isCenterAnchor(b)&&(I-=b.width/2),x.isBottomAnchor(b)?N-=b.height:x.isMiddleAnchor(b)&&(N-=b.height/2);var j=b.width,F=O.w;j>F?(I=O.l,j=F):(I+j>z&&(I=z-j),C>I&&(I=C),j=Math.min(z-I,b.width));var D=b.height,B=O.h;D>B?(N=O.t,D=B):(N+D>R&&(N=R-D),P>N&&(N=P),D=Math.min(R-N,b.height)),f.setTranslate(k,I,N),M.attr({width:j-b.borderwidth,height:D-b.borderwidth,x:b.borderwidth/2,y:b.borderwidth/2});var U=T.attr("data-scroll")||0;if(f.setTranslate(T,0,U),A.select("rect").attr({width:j-2*b.borderwidth,height:D-2*b.borderwidth,x:b.borderwidth-U,y:b.borderwidth}),T.call(p.setClipUrl,a),b.height-D>0&&!t._context.staticPlot){M.attr({width:j-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin}),A.select("rect").attr({width:j-2*b.borderwidth+v.scrollBarWidth+v.scrollBarMargin}),t.firstRender&&e(v.scrollBarMargin,0);var V=D-v.scrollBarHeight-2*v.scrollBarMargin,q=b.height-D,H=v.scrollBarMargin,G=0;e(H,G),k.on("wheel",null),k.on("wheel",function(){G=f.constrain(T.attr("data-scroll")-c.event.deltaY/V*q,-q,0),H=v.scrollBarMargin-G/q*V,e(H,G),c.event.preventDefault()}),E.on(".drag",null),T.on(".drag",null);var Y=c.behavior.drag().on("drag",function(){H=f.constrain(c.event.y-v.scrollBarHeight/2,v.scrollBarMargin,v.scrollBarMargin+V),G=-(H-v.scrollBarMargin)/V*q,e(H,G)});E.call(Y),T.call(Y)}if(t._context.editable){var X,W,Z,K;k.classed("cursor-move",!0),d.init({element:k.node(),prepFn:function(){var t=f.getTranslate(k);Z=t.x,K=t.y},moveFn:function(t,e){var r=Z+t,n=K+e;f.setTranslate(k,r,n),X=d.align(r,0,O.l,O.l+O.w,b.xanchor),W=d.align(n,0,O.t+O.h,O.t,b.yanchor)},doneFn:function(e){e&&void 0!==X&&void 0!==W&&u.relayout(t,{"legend.x":X,"legend.y":W})}})}}}},{"../../lib":381,"../../plotly":400,"../../plots/plots":452,"../color":303,"../dragelement":323,"../drawing":325,"./anchor_utils":338,"./constants":340,"./get_legend_data":343,"./helpers":344,"./style":346,d3:113}],343:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("./helpers");e.exports=function(t,e){function r(t,r){if(""!==t&&i.isGrouped(e))-1===l.indexOf(t)?(l.push(t),c=!0,s[t]=[[r]]):s[t].push([r]);else{var n="~~i"+f;l.push(n),s[n]=[[r]],f++}}var a,o,s={},l=[],c=!1,u={},f=0;for(a=0;aa;a++)m=s[l[a]],y[a]=i.isReversed(e)?m.reverse():m;else{for(y=[new Array(b)],a=0;b>a;a++)m=s[l[a]][0],y[0][i.isReversed(e)?b-a-1:a]=m;b=1}return e._lgroupsLength=b,y}},{"../../plots/plots":452,"./helpers":344}],344:[function(t,e,r){"use strict";var n=t("../../plots/plots");r.legendGetsTrace=function(t){return t.visible&&n.traceIs(t,"showLegend")},r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{"../../plots/plots":452}],345:[function(t,e,r){"use strict";var n=e.exports={};n.layoutAttributes=t("./attributes"),n.supplyLayoutDefaults=t("./defaults"),n.draw=t("./draw"),n.style=t("./style")},{"./attributes":339,"./defaults":341,"./draw":342,"./style":346}],346:[function(t,e,r){"use strict";function n(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,n=d.hasLines(e),i=l.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);i.enter().append("path").classed("js-fill",!0),i.exit().remove(),i.attr("d","M5,0h30v6h-30z").call(f.fillGroupStyle);var a=l.select(this).select(".legendlines").selectAll("path").data(n?[t]:[]);a.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),a.exit().remove(),a.call(f.lineGroupStyle)}function i(t){function e(t,e,r){var n=c.nestedProperty(o,t).get(),i=Array.isArray(n)&&e?e(n):n;if(r){if(ir[1])return r[1]}return i}function r(t){return t[0]}var n,i,a=t[0],o=a.trace,s=d.hasMarkers(o),u=d.hasText(o),h=d.hasLines(o);if(s||u||h){var p={},g={};s&&(p.mc=e("marker.color",r),p.mo=e("marker.opacity",c.mean,[.2,1]),p.ms=e("marker.size",c.mean,[2,16]),p.mlc=e("marker.line.color",r),p.mlw=e("marker.line.width",c.mean,[0,5]),g.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),h&&(g.line={width:e("line.width",r,[0,10])}),u&&(p.tx="Aa",p.tp=e("textposition",r),p.ts=10,p.tc=e("textfont.color",r),p.tf=e("textfont.family",r)),n=[c.minExtend(a,p)],i=c.minExtend(o,g)}var v=l.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(s?n:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(f.pointStyle,i),s&&(n[0].mrc=3);var y=v.selectAll("g.pointtext").data(u?n:[]);y.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),y.exit().remove(),y.selectAll("text").call(f.textPointStyle,i)}function a(t){var e=t[0].trace,r=e.marker||{},n=r.line||{},i=l.select(this).select("g.legendpoints").selectAll("path.legendbar").data(u.traceIs(e,"bar")?[t]:[]);i.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),i.exit().remove(),i.each(function(t){var e=(t.mlw+1||n.width+1)-1,i=l.select(this);i.style("stroke-width",e+"px").call(h.fill,t.mc||r.color),e&&i.call(h.stroke,t.mlc||n.color)})}function o(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendbox").data(u.traceIs(e,"box")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(t){var r=(t.lw+1||e.line.width+1)-1,n=l.select(this);n.style("stroke-width",r+"px").call(h.fill,t.fc||e.fillcolor),r&&n.call(h.stroke,t.lc||e.line.color)})}function s(t){var e=t[0].trace,r=l.select(this).select("g.legendpoints").selectAll("path.legendpie").data(u.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(p,t[0],e)}var l=t("d3"),c=t("../../lib"),u=t("../../plots/plots"),f=t("../drawing"),h=t("../color"),d=t("../../traces/scatter/subtypes"),p=t("../../traces/pie/style_one");e.exports=function(t){t.each(function(t){var e=l.select(this),r=e.selectAll("g.legendfill").data([t]);r.enter().append("g").classed("legendfill",!0);var n=e.selectAll("g.legendlines").data([t]);n.enter().append("g").classed("legendlines",!0);var i=e.selectAll("g.legendsymbols").data([t]);i.enter().append("g").classed("legendsymbols",!0),i.style("opacity",t[0].trace.opacity),i.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(a).each(o).each(s).each(n).each(i)}},{"../../lib":381,"../../plots/plots":452,"../../traces/pie/style_one":552,"../../traces/scatter/subtypes":573,"../color":303,"../drawing":325,d3:113}],347:[function(t,e,r){"use strict";function n(t,e){var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o={};if("zoom"===n){for(var s,l,u="in"===i?.5:2,h=(1+u)/2,d=(1-u)/2,p=c.Axes.list(t,null,!0),v=0;vy;y++){var b=s[y];h=m[b]={};for(var x=0;x1)return n(["resetViews","toggleHover"]),o(v,r);u&&(n(["zoom3d","pan3d","orbitRotation","tableRotation"]),n(["resetCameraDefault3d","resetCameraLastSave3d"]),n(["hoverClosest3d"])),h&&(n(["zoomInGeo","zoomOutGeo","resetGeo"]),n(["hoverClosestGeo"]));var m=i(s),y=[];return((c||p)&&!m||g)&&(y=["zoom2d","pan2d"]),(c||g)&&a(l)&&(y.push("select2d"),y.push("lasso2d")),y.length&&n(y),!c&&!p||m||g||n(["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]),c&&d?n(["toggleHover"]):p?n(["hoverClosestGl2d"]):c?n(["hoverClosestCartesian","hoverCompareCartesian"]):d&&n(["hoverClosestPie"]),o(v,r)}function i(t){for(var e=l.Axes.list({_fullLayout:t},null,!0),r=!0,n=0;n0);if(h){var d=i(e,r,s);l("x",d[0]),l("y",d[1]),a.noneOrAll(t,e,["x","y"]),l("xanchor"),l("yanchor"),a.coerceFont(l,"font",r.font),l("bgcolor"),l("bordercolor"),l("borderwidth")}}},{"../../lib":381,"./attributes":350,"./button_attributes":351,"./constants":352}],354:[function(t,e,r){"use strict";function n(t){for(var e=m.list(t,"x",!0),r=[],n=0;ne){var r=e;e=t,t=r}s.setAttributes(w,{"data-min":t,"data-max":e}),s.setAttributes(R,{x:t,width:e-t}),s.setAttributes(M,{width:t}),s.setAttributes(T,{x:e,width:p-e}),s.setAttributes(E,{transform:"translate("+(t-v-1)+")"}),s.setAttributes(C,{transform:"translate("+e+")"})}var f=t._fullLayout,h=f._infolayer.selectAll("g.range-slider"),d=f.xaxis.rangeslider,p=f._size.w,g=(f.height-f.margin.b-f.margin.t)*d.thickness,v=2,m=Math.floor(d.borderwidth/2),y=f.margin.l,b=f.height-g-f.margin.b,x=0,_=p,w=document.createElementNS(o,"g");s.setAttributes(w,{"class":"range-slider","data-min":x,"data-max":_,"pointer-events":"all",transform:"translate("+y+","+b+")"});var k=document.createElementNS(o,"rect"),A=d.borderwidth%2===0?d.borderwidth:d.borderwidth-1;s.setAttributes(k,{fill:d.bgcolor,stroke:d.bordercolor,"stroke-width":d.borderwidth,height:g+A,width:p+A,transform:"translate(-"+m+", -"+m+")","shape-rendering":"crispEdges"});var M=document.createElementNS(o,"rect");s.setAttributes(M,{x:0,width:x,height:g,fill:"rgba(0,0,0,0.4)"});var T=document.createElementNS(o,"rect");s.setAttributes(T,{x:_,width:p-_,height:g,fill:"rgba(0,0,0,0.4)"});var E=document.createElementNS(o,"g"),L=document.createElementNS(o,"rect"),S=document.createElementNS(o,"rect");s.setAttributes(E,{transform:"translate("+(x-v-1)+")"}),s.setAttributes(L,{width:10,height:g,x:-6,fill:"transparent",cursor:"col-resize"}),s.setAttributes(S,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(E,[S,L]);var C=document.createElementNS(o,"g"),z=document.createElementNS(o,"rect"),P=document.createElementNS(o,"rect");s.setAttributes(C,{transform:"translate("+_+")"}),s.setAttributes(z,{width:10,height:g,x:-2,fill:"transparent",cursor:"col-resize"}),s.setAttributes(P,{width:v,height:g/2,y:g/4,rx:1,fill:"white",stroke:"#666","shape-rendering":"crispEdges"}),s.appendChildren(C,[P,z]);var R=document.createElementNS(o,"rect");s.setAttributes(R,{x:x,width:_-x,height:g,cursor:"ew-resize",fill:"transparent"}),w.addEventListener("mousedown",function(t){function r(t){var r,n,f=+t.clientX-a;switch(i){case R:w.style.cursor="ew-resize",r=+s+f,n=+l+f,u(r,n),c(e(r),e(n));break;case L:w.style.cursor="col-resize",r=+s+f,n=+l,u(r,n),c(e(r),e(n));break;case z:w.style.cursor="col-resize",r=+s,n=+l+f,u(r,n),c(e(r),e(n));break;default:w.style.cursor="ew-resize",r=o,n=o+f,u(r,n),c(e(r),e(n))}}function n(){window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",n),w.style.cursor="auto"}var i=t.target,a=t.clientX,o=a-w.getBoundingClientRect().left,s=w.getAttribute("data-min"),l=w.getAttribute("data-max");window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)}),d.range||(d.range=i.getAutoRange(f.xaxis));var O=l(t,p,g);s.appendChildren(w,[k,O,M,T,R,E,C]),r(f.xaxis.range[0],f.xaxis.range[1]),h.data([0]).enter().append(function(){return d.setRange=r,w})}},{"../../constants/xmlns_namespaces":369,"../../lib":381,"../../plotly":400,"../../plots/cartesian/axes":403,"./helpers":360,"./range_plot":362}],359:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(t,e){return n.coerce(s,l,i,t,e)}if(t[r].rangeslider){var s="object"==typeof t[r].rangeslider?t[r].rangeslider:{},l=e[r].rangeslider={};if(o("bgcolor"),o("bordercolor"),o("borderwidth"),o("thickness"),o("visible"),o("range"),l.range&&!e[r].autorange){var c=l.range,u=e[r].range;c[0]=Math.min(c[0],u[0]),c[1]=Math.max(c[1],u[1])}else e[r]._needsExpand=!0;l.visible&&a.forEach(function(t){var r=e[t]||{};r.fixedrange=!0,e[t]=r})}}},{"../../lib":381,"./attributes":357}],360:[function(t,e,r){"use strict";r.setAttributes=function(t,e){for(var r in e)t.setAttribute(r,e[r])},r.appendChildren=function(t,e){for(var r=0;rl;l++){var c=s[l],u={_fullLayout:e},f=x.coerceRef(t,n,u,c);if("path"!==o){var h=.25,d=.75;if("paper"!==f){var p=x.getFromId(u,f),g=a(p);h=g(p.range[0]+h*(p.range[1]-p.range[0])),d=g(p.range[0]+d*(p.range[1]-p.range[0]))}r(c+"0",h),r(c+"1",d)}}return"path"===o?r("path"):b.noneOrAll(t,n,["x0","x1","y0","y1"]),n}function i(t){return"category"===t.type?t.c2l:t.d2l}function a(t){return"category"===t.type?t.l2c:t.l2d}function o(t,e){t.layout.shapes=e,k.supplyLayoutDefaults(t.layout,t._fullLayout),k.drawAll(t)}function s(t){delete t.layout.shapes,t._fullLayout.shapes=[],k.drawAll(t)}function l(t,e,r){for(var n=0;ne;i--)h(t,i).selectAll('[data-index="'+(i-1)+'"]').attr("data-index",i),k.draw(t,i)}function f(t,e,r,o){function s(e){var r=e.append("path").attr(z).style("opacity",S.opacity).call(_.stroke,P).call(_.fill,S.fillcolor).call(w.dashLine,S.line.dash,S.line.width);C&&r.call(w.setClipUrl,"clip"+t._fullLayout._uid+C)}var l,c;h(t,e).selectAll('[data-index="'+e+'"]').remove();var u=t.layout.shapes[e];if(u){var f={xref:u.xref,yref:u.yref},p={};"string"==typeof r&&r?p[r]=o:b.isPlainObject(r)&&(p=r);var v=Object.keys(p);for(l=0;ll;l++){var k=y[l];if(void 0===p[k]&&void 0!==u[k]){var A,M=k.charAt(0),T=x.getFromId(t,x.coerceRef(f,{},t,M)),E=x.getFromId(t,x.coerceRef(u,{},t,M)),L=u[k];void 0!==p[M+"ref"]&&(T?(A=i(T)(L),L=(A-T.range[0])/(T.range[1]-T.range[0])):L=(L-E.domain[0])/(E.domain[1]-E.domain[0]),E?(A=E.range[0]+L*(E.range[1]-E.range[0]),L=a(E)(A)):L=T.domain[0]+L*(T.domain[1]-T.domain[0])),u[k]=L}}var S=n(u,t._fullLayout);t._fullLayout.shapes[e]=S;var C,z={"data-index":e,"fill-rule":"evenodd",d:g(t,S)},P=S.line.width?S.line.color:"rgba(0,0,0,0)";if("below"!==S.layer)C=(S.xref+S.yref).replace(/paper/g,""),s(t._fullLayout._shapeUpperLayer);else if("paper"===S.xref&&"paper"===S.yref)C="",s(t._fullLayout._shapeLowerLayer);else{var R,O=t._fullLayout._plots||{},I=Object.keys(O);for(l=0,c=I.length;c>l;l++)R=O[I[l]],C=I[l],d(t,S,R.id)&&s(R.shapelayer)}}}function h(t,e){var r=t._fullLayout.shapes[e],n=t._fullLayout._shapeUpperLayer;return r?"below"===r.layer&&(n="paper"===r.xref&&"paper"===r.yref?t._fullLayout._shapeLowerLayer:t._fullLayout._shapeSubplotLayer):console.log("getShapeLayer: undefined shape: index",e),n}function d(t,e,r){var n=y.Axes.getFromId(t,r,"x")._id,i=y.Axes.getFromId(t,r,"y")._id;return"below"===e.layer&&(n===e.xref||i===e.yref)}function p(t){return function(e){return t(e.replace("_"," "))}}function g(t,e){var r,n,a,o,s=e.type,l=x.getFromId(t,e.xref),c=x.getFromId(t,e.yref),u=t._fullLayout._size;if(l?(r=i(l),n=function(t){return l._offset+l.l2p(r(t,!0))}):n=function(t){return u.l+u.w*t},c?(a=i(c),o=function(t){return c._offset+c.l2p(a(t,!0))}):o=function(t){return u.t+u.h*(1-t)},"path"===s)return l&&"date"===l.type&&(n=p(n)),c&&"date"===c.type&&(o=p(o)),k.convertPath(e.path,n,o);var f=n(e.x0),h=n(e.x1),d=o(e.y0),g=o(e.y1);if("line"===s)return"M"+f+","+d+"L"+h+","+g;if("rect"===s)return"M"+f+","+d+"H"+h+"V"+g+"H"+f+"Z";var v=(f+h)/2,m=(d+g)/2,y=Math.abs(v-f),b=Math.abs(m-d),_="A"+y+","+b,w=v+y+","+m,A=v+","+(m-b);return"M"+w+_+" 0 1,1 "+A+_+" 0 0,1 "+w+"Z"}function v(t,e,r,n,i){var a="category"===t.type?Number:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var o,s,l,c,u,f=1/0,h=-(1/0),d=n.match(A);for("date"===t.type&&(a=p(a)),o=0;ou&&(f=u),u>h&&(h=u)));return h>=f?[f,h]:void 0}}var m=t("fast-isnumeric"),y=t("../../plotly"),b=t("../../lib"),x=t("../../plots/cartesian/axes"),_=t("../color"),w=t("../drawing"),k=e.exports={};k.layoutAttributes=t("./attributes"),k.supplyLayoutDefaults=function(t,e){for(var r=t.shapes||[],i=e.shapes=[],a=0;as&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),console.log("ignoring extra params in segment "+t)),i+l})},k.calcAutorange=function(t){var e,r,n,i,a,o=t._fullLayout,s=o.shapes;if(s.length&&t._fullData.length)for(e=0;eh?r=h:(u.left-=b.offsetLeft,u.right-=b.offsetLeft,u.top-=b.offsetTop,u.bottom-=b.offsetTop,b.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(u,t,c)&&(r=Math.max(r,o*(t[b.side]-u[a])+c))}),r=Math.min(h,r)),r>0||0>h){var d={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[b.side];e.attr("transform","translate("+d+")")}}}function p(){E=0,L=!0,S=z,k._infolayer.select("."+e).attr({"data-unformatted":S}).text(S).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)})}var g=r.propContainer,v=r.propName,m=r.traceIndex,y=r.dfltName,b=r.avoid||{},x=r.attributes,_=r.transform,w=r.containerGroup,k=t._fullLayout,A=g.titlefont.family,M=g.titlefont.size,T=g.titlefont.color,E=1,L=!1,S=g.title.trim();""===S&&(E=0),S.match(/Click to enter .+ title/)&&(E=.2,L=!0),w||(w=k._infolayer.selectAll(".g-"+e).data([0]),w.enter().append("g").classed("g-"+e,!0));var C=w.selectAll("text").data([0]);C.enter().append("text"),C.text(S).attr("class",e),C.attr({"data-unformatted":S}).call(f);var z="Click to enter "+y+" title";t._context.editable?(S||p(),C.call(u.makeEditable).on("edit",function(e){void 0!==m?a.restyle(t,v,e,m):a.relayout(t,v,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(f)}).on("input",function(t){this.text(t||" ").attr(x).selectAll("tspan.line").attr(x)})):S&&!S.match(/Click to enter .+ title/)||C.remove(),C.classed("js-placeholder",L)}},{"../../lib":381,"../../lib/svg_text_utils":393,"../../plotly":400,"../../plots/plots":452,"../color":303,"../drawing":325,d3:113,"fast-isnumeric":117}],366:[function(t,e,r){"use strict";e.exports={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}},{}],367:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],368:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],369:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],370:[function(t,e,r){"use strict";var n=t("./plotly");r.version="1.12.0",r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.setPlotConfig=t("./plot_api/set_plot_config"),r.register=n.register,r.toImage=t("./plot_api/to_image"),r.downloadImage=t("./snapshot/download"),r.Icons=t("../build/ploticon"),r.Plots=n.Plots,r.Fx=n.Fx,r.Snapshot=n.Snapshot,r.PlotSchema=n.PlotSchema,r.Queue=n.Queue,r.d3=t("d3")},{"../build/ploticon":2,"./plot_api/set_plot_config":398,"./plot_api/to_image":399,"./plotly":400,"./snapshot/download":467,d3:113}],371:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],372:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){Array.isArray(t)&&(e[r]=t[n])}},{}],373:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("./nested_property"),o=t("../components/colorscale/get_scale"),s=(Object.keys(t("../components/colorscale/scales")),/^([2-9]|[1-9][0-9]+)$/);r.valObjects={data_array:{coerceFunction:function(t,e,r){Array.isArray(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)}},"boolean":{coerceFunction:function(t,e,r){t===!0||t===!1?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,i){!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&ti.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if(n.strict===!0&&"string"!=typeof t)return void e.set(r);var i=String(t);void 0===t||n.noBlank===!0&&!i?e.set(r):e.set(i)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?(Math.abs(t)>180&&(t-=360*Math.round(t/360)),e.set(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r){var n=r.length;return"string"==typeof t&&t.substr(0,n)===r&&s.test(t.substr(n))?void e.set(t):void e.set(r)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"!=typeof t)return void e.set(r);if(-1!==n.extras.indexOf(t))return void e.set(t);for(var i=t.split("+"),a=0;a2)return!1;var l=o[0].split("-");if(l.length>3||3!==l.length&&o[1])return!1;if(4===l[0].length)r=Number(l[0]);else{if(2!==l[0].length)return!1;var c=(new Date).getFullYear();r=((Number(l[0])-c+70)%100+200)%100+c-70}return s(r)?1===l.length?new Date(r,0,1).getTime():(n=Number(l[1])-1,l[1].length>2||!(n>=0&&11>=n)?!1:2===l.length?new Date(r,n,1).getTime():(i=Number(l[2]),l[2].length>2||!(i>=1&&31>=i)?!1:(i=new Date(r,n,i).getTime(),o[1]?(l=o[1].split(":"),l.length>3?!1:(a=Number(l[0]),l[0].length>2||!(a>=0&&23>=a)?!1:(i+=36e5*a,1===l.length?i:(n=Number(l[1]),l[1].length>2||!(n>=0&&59>=n)?!1:(i+=6e4*n,2===l.length?i:(t=Number(l[2]),t>=0&&60>t?i+1e3*t:!1)))))):i))):!1},r.isDateTime=function(t){return r.dateTime2ms(t)!==!1},r.ms2DateTime=function(t,e){if("undefined"==typeof o)return void console.log("d3 is not defined");e||(e=0);var r=new Date(t),i=o.time.format("%Y-%m-%d")(r);return 7776e6>e?(i+=" "+n(r.getHours(),2),432e6>e&&(i+=":"+n(r.getMinutes(),2),108e5>e&&(i+=":"+n(r.getSeconds(),2),3e5>e&&(i+="."+n(r.getMilliseconds(),3)))),i.replace(/([:\s]00)*\.?[0]*$/,"")):i};var l={H:["%H:%M:%S~%L","%H:%M:%S","%H:%M"],I:["%I:%M:%S~%L%p","%I:%M:%S%p","%I:%M%p"],D:["%H","%I%p","%Hh"]},c={Y:["%Y~%m~%d","%Y%m%d","%y%m%d","%m~%d~%Y","%d~%m~%Y"],Yb:["%b~%d~%Y","%d~%b~%Y","%Y~%d~%b","%Y~%b~%d"],y:["%m~%d~%y","%d~%m~%y","%y~%m~%d"],yb:["%b~%d~%y","%d~%b~%y","%y~%d~%b","%y~%b~%d"]},u=o.time.format.utc,f={Y:{H:["%Y~%m~%dT%H:%M:%S","%Y~%m~%dT%H:%M:%S~%L"].map(u),I:[],D:["%Y%m%d%H%M%S","%Y~%m","%m~%Y"].map(u)},Yb:{H:[],I:[],D:["%Y~%b","%b~%Y"].map(u)},y:{H:[],I:[],D:[]},yb:{H:[],I:[],D:[]}};["Y","Yb","y","yb"].forEach(function(t){c[t].forEach(function(e){f[t].D.push(u(e)),["H","I","D"].forEach(function(r){l[r].forEach(function(n){var i=f[t][r];i.push(u(e+"~"+n)),i.push(u(n+"~"+e))})})})});var h=/[a-z]*/g,d=function(t){return t.substr(0,3)},p=/(mon|tue|wed|thu|fri|sat|sun|the|of|st|nd|rd|th)/g,g=/[\s,\/\-\.\(\)]+/g,v=/~?([ap])~?m(~|$)/,m=function(t,e){return e+"m "},y=/\d\d\d\d/,b=/(^|~)[a-z]{3}/,x=/[ap]m/,_=/:/,w=/q([1-4])/,k=["31~mar","30~jun","30~sep","31~dec"],A=function(t,e){return k[e-1]},M=/ ?([+\-]\d\d:?\d\d|Z)$/;r.parseDate=function(t){if(t.getTime)return t;if("string"!=typeof t)return!1;t=t.toLowerCase().replace(h,d).replace(p,"").replace(g,"~").replace(v,m).replace(w,A).trim().replace(M,"");var e,r,n=null,o=i(t),s=a(t);e=f[o][s],r=e.length;for(var l=0;r>l&&!(n=e[l].parse(t));l++);if(!(n instanceof Date))return!1;var c=n.getTimezoneOffset();return n.setTime(n.getTime()+60*c*1e3),n}},{d3:113,"fast-isnumeric":117}],375:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i={init:function(t){if(t._ev instanceof n)return t;var e=new n;return t._ev=e,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t.emit=function(r,n){"undefined"!=typeof jQuery&&jQuery(t).trigger(r,n),e.emit(r,n)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;lp;p++){o=t[p];for(s in o)l=h[s],c=o[s],e&&c&&(i(c)||(u=a(c)))?(u?(u=!1,f=l&&a(l)?l:[]):f=l&&i(l)?l:{},h[s]=n([f,c],e,r)):("undefined"!=typeof c||r)&&(h[s]=c)}return h}var i=t("./is_plain_object.js"),a=Array.isArray;r.extendFlat=function(){return n(arguments,!1,!1)},r.extendDeep=function(){return n(arguments,!0,!1)},r.extendDeepAll=function(){return n(arguments,!0,!0)}},{"./is_plain_object.js":382}],377:[function(t,e,r){"use strict";e.exports=function(t){for(var e=[],r=0;ry;y++)f=s(p,y),d=l(e,y),m[y]=n(f,d);else m=n(p,e);return m}var s=t("tinycolor2"),l=t("fast-isnumeric"),c=t("../components/colorscale/make_scale_function"),u=t("../components/color/attributes").defaultLine,f=t("./str2rgbarray"),h=1;e.exports=o},{"../components/color/attributes":302,"../components/colorscale/make_scale_function":319,"./str2rgbarray":392,"fast-isnumeric":117,tinycolor2:274}],380:[function(t,e,r){"use strict";function n(t){for(var e=0;(e=t.indexOf("",e))>=0;){var r=t.indexOf("",e);if(e>r)break;t=t.slice(0,e)+l(t.slice(e+5,r))+t.slice(r+6)}return t}function i(t){return t.replace(/\/g,"\n")}function a(t){return t.replace(/\<.*\>/g,"")}function o(t){for(var e=0;(e=t.indexOf("&",e))>=0;){var r=t.indexOf(";",e);if(e>r)e+=1;else{var n=c[t.slice(e+1,r)];t=n?t.slice(0,e)+n+t.slice(r+1):t.slice(0,e)+t.slice(r+1)}}return t}function s(t){return""+o(a(n(i(t))))}var l=t("superscript-text"),c={mu:"\u03bc",amp:"&",lt:"<",gt:">"};e.exports=s},{"superscript-text":263}],381:[function(t,e,r){"use strict";var n=t("d3"),i=e.exports={};i.nestedProperty=t("./nested_property"),i.isPlainObject=t("./is_plain_object");var a=t("./coerce");i.valObjects=a.valObjects,i.coerce=a.coerce,i.coerce2=a.coerce2,i.coerceFont=a.coerceFont;var o=t("./dates");i.dateTime2ms=o.dateTime2ms,i.isDateTime=o.isDateTime,i.ms2DateTime=o.ms2DateTime, +i.parseDate=o.parseDate;var s=t("./search");i.findBin=s.findBin,i.sorterAsc=s.sorterAsc,i.sorterDes=s.sorterDes,i.distinctVals=s.distinctVals,i.roundUp=s.roundUp;var l=t("./stats");i.aggNums=l.aggNums,i.len=l.len,i.mean=l.mean,i.variance=l.variance,i.stdev=l.stdev,i.interp=l.interp;var c=t("./matrix");i.init2dArray=c.init2dArray,i.transposeRagged=c.transposeRagged,i.dot=c.dot,i.translationMatrix=c.translationMatrix,i.rotationMatrix=c.rotationMatrix,i.rotationXYMatrix=c.rotationXYMatrix,i.apply2DTransform=c.apply2DTransform,i.apply2DTransform2=c.apply2DTransform2;var u=t("./extend");i.extendFlat=u.extendFlat,i.extendDeep=u.extendDeep,i.extendDeepAll=u.extendDeepAll,i.notifier=t("./notifier"),i.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;ar?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},i.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},i.identity=function(t){return t},i.randstr=function f(t,e,r){if(r||(r=16),void 0===e&&(e=24),0>=e)return"0";var n,i,a,o=Math.log(Math.pow(2,e))/Math.log(r),s="";for(n=2;o===1/0;n*=2)o=Math.log(Math.pow(2,e/n))/Math.log(r)*n;var l=o-Math.floor(o);for(n=0;n-1||c!==1/0&&c>=Math.pow(2,e)?f(t,e,r):s},i.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={};return r.optionList=[],r._newoption=function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)},r["_"+e]=t,r},i.smooth=function(t,e){if(e=Math.round(e)||0,2>e)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,c=new Array(l),u=new Array(o);for(r=0;l>r;r++)c[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;o>r;r++){for(a=0,n=0;l>n;n++)i=r+n+1-e,-o>i?i-=s*Math.round(i/s):i>=s&&(i-=s*Math.floor(i/s)),0>i?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*c[n];u[r]=a}return u},i.syncOrAsync=function(t,e,r){function n(){return i.markTime("async done "+o.name),i.syncOrAsync(t,e,r)}for(var a,o;t.length;){if(o=t.splice(0,1)[0],a=o(e),a&&a.then)return a.then(n).then(void 0,i.promiseError);i.markTime("sync done "+o.name)}return r&&r(e)},i.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},i.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;ni;i++)e[i][r]=t[i]},i.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,o,s=3,l=Object.keys(t);for(n=0;n1?n+a[1]:"";if(i&&(a.length>1||o.length>4))for(;r.test(o);)o=o.replace(r,"$1"+i+"$2");return o+s}},{"./coerce":373,"./dates":374,"./extend":376,"./is_plain_object":382,"./matrix":383,"./nested_property":384,"./notifier":385,"./search":388,"./stats":391,d3:113}],382:[function(t,e,r){"use strict";e.exports=function(t){return"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],383:[function(t,e,r){"use strict";r.init2dArray=function(t,e){for(var r=new Array(t),n=0;t>n;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,i=t.length;for(e=0;i>e;e++)n=Math.max(n,t[e].length);var a=new Array(n);for(e=0;n>e;e++)for(a[e]=new Array(i),r=0;i>r;r++)a[e][r]=t[r][e];return a},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,i,a=t.length;if(t[0].length)for(n=new Array(a),i=0;a>i;i++)n[i]=r.dot(t[i],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),i=0;ii;i++)n+=t[i]*e[i];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],384:[function(t,e,r){"use strict";function n(t,e){return function(){var r,i,a,o,s,l=t;for(o=0;o=0;e--){if(n=t[e],o=!1,Array.isArray(n))for(r=n.length-1;r>=0;r--)c(n[r])?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)c(n[a[r]])&&!i(n[a[r]],a[r])?delete n[a[r]]:o=!0;if(o)return}}function c(t){return void 0===t||null===t?!0:"object"!=typeof t?!1:Array.isArray(t)?!t.length:!Object.keys(t).length}function u(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}var f=t("fast-isnumeric");e.exports=function(t,e){if(f(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,l=e.split(".");sr||r>a||o>n||n>s?!1:!e||!c(t)}function r(t,e){var r=t[0],l=t[1];if(i>r||r>a||o>l||l>s)return!1;var c,u,f,h,d,p=n.length,g=n[0][0],v=n[0][1],m=0;for(c=1;p>c;c++)if(u=g,f=v,g=n[c][0],v=n[c][1],h=Math.min(u,g),!(h>r||r>Math.max(u,g)||l>Math.max(f,v)))if(l=l&&r!==h&&m++}return m%2===1}var n=t.slice(),i=n[0][0],a=i,o=n[0][1],s=o;n.push(n[0]);for(var l=1;la;a++)if(o=[t[a][0]-l[0],t[a][1]-l[1]],s=n(o,c),0>s||s>u||Math.abs(n(o,h))>i)return!0;return!1};i.filter=function(t,e){function r(r){t.push(r);var s=n.length,l=i;n.splice(o+1);for(var c=l+1;c1){var s=t.pop();r(s)}return{addPt:r,raw:t,filtered:n}}},{"./matrix":383}],387:[function(t,e,r){"use strict";function n(t,e){for(var r,n=[],a=0;a=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;rt}function i(t,e){return e>=t}function a(t,e){return t>e}function o(t,e){return t>=e}var s=t("fast-isnumeric");r.findBin=function(t,e,r){if(s(e.start))return r?Math.ceil((t-e.start)/e.size)-1:Math.floor((t-e.start)/e.size);var l,c,u=0,f=e.length,h=0;for(c=e[e.length-1]>=e[0]?r?n:i:r?o:a;f>u&&h++<100;)l=Math.floor((u+f)/2),c(e[l],t)?u=l+1:f=l;return h>90&&console.log("Long binary search..."),u-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;n>s;s++)e[s+1]>e[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,c=r?Math.ceil:Math.floor;a>i&&o++<100;)n=c((i+a)/2),e[n]<=t?i=n+s:a=n-l;return e[i]}},{"fast-isnumeric":117}],389:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],390:[function(t,e,r){"use strict";var n=t("../components/color"),i=function(){};e.exports=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=i);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=n.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1}},{"../components/color":303}],391:[function(t,e,r){"use strict";var n=t("fast-isnumeric");r.aggNums=function(t,e,i,a){var o,s;if(a||(a=i.length),n(e)||(e=!1),Array.isArray(i[0])){for(s=new Array(a),o=0;a>o;o++)s[o]=r.aggNums(t,e,i[o]);i=s}for(o=0;a>o;o++)n(e)?n(i[o])&&(e=t(+e,+i[o])):e=i[o];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.variance=function(t,e,i){return e||(e=r.len(t)),n(i)||(i=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-i,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if(e=e*t.length-.5,0>e)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"fast-isnumeric":117}],392:[function(t,e,r){"use strict";function n(t){return t=i(t),a.str2RgbaArray(t.toRgbString())}var i=t("tinycolor2"),a=t("arraytools");e.exports=n},{arraytools:49,tinycolor2:274}],393:[function(t,e,r){"use strict";function n(t,e){return t.node().getBoundingClientRect()[e]}function i(t){return t.replace(/(<|<|<)/g,"\\lt ").replace(/(>|>|>)/g,"\\gt ")}function a(t,e,r){var n="math-output-"+l.Lib.randstr([],64),a=c.select("body").append("div").attr({id:n}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text(i(t));MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var e=c.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())console.log("There was an error in the tex syntax.",t),r();else{var n=a.select("svg").node().getBoundingClientRect();r(a.select(".MathJax_SVG"),e,n)}a.remove()})}function o(t){for(var e=l.util.html_entity_decode(t),r=e.split(/(<[^<>]*>)/).map(function(t){var e=t.match(/<(\/?)([^ >]*)\s*(.*)>/i),r=e&&e[2].toLowerCase(),n=h[r];if(void 0!==n){var i=e[1],a=e[3],o=a.match(/^style\s*=\s*"([^"]+)"\s*/i);if("a"===r){if(i)return"";if("href"!==a.substr(0,4).toLowerCase())return"";var s=document.createElement("a");return s.href=a.substr(4).replace(/["'=]/g,""),-1===d.indexOf(s.protocol)?"":'"}if("br"===r)return"
";if(i)return"sup"===r?'':"sub"===r?'':"";var c=""}return l.util.xml_entity_encode(t).replace(/");i>0;i=r.indexOf("
",i+1))n.push(i);var a=0;n.forEach(function(t){for(var e=t+a,n=r.slice(0,e),i="",o=n.length-1;o>=0;o--){var s=n[o].match(/<(\/?).*>/i);if(s&&"
"!==n[o]){s[1]||(i=n[o]);break}}i&&(r.splice(e+1,0,i),r.splice(e,0,""),a+=2)});var o=r.join(""),s=o.split(/
/gi);return s.length>1&&(r=s.map(function(t,e){return''+t+""})),r.join("")}function s(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),c=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-c.top+"px",left:a()-c.left+"px","z-index":1e3}),this}}var l=t("../plotly"),c=t("d3"),u=t("../constants/xmlns_namespaces"),f=e.exports={};c.selection.prototype.appendSVG=function(t){for(var e=['',t,""].join(""),r=(new DOMParser).parseFromString(e,"application/xml"),n=r.documentElement.firstChild;n;)this.node().appendChild(this.node().ownerDocument.importNode(n,!0)),n=n.nextSibling;return r.querySelector("parsererror")?(console.log(r.querySelector("parsererror div").textContent),null):c.select(this.node().lastChild)},f.html_entity_decode=function(t){var e=c.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"<"===t?"<":"&rt;"===t?">":e.html(t).text()});return e.remove(),r},f.xml_entity_encode=function(t){return t.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")},f.convertToTspans=function(t,e){function r(){d.empty()||(p=u.attr("class")+"-math",d.select("svg."+p).remove()),t.text("").style({visibility:"visible","white-space":"pre"}),h=t.appendSVG(s),h||t.text(i),t.select("a").size()&&t.style("pointer-events","all"),e&&e.call(u)}var i=t.text(),s=o(i),u=t,f=!u.attr("data-notex")&&s.match(/([^$]*)([$]+[^$]*[$]+)([^$]*)/),h=i,d=c.select(u.node().parentNode);if(!d.empty()){var p=u.attr("class")?u.attr("class").split(" ")[0]:"text";p+="-math",d.selectAll("svg."+p).remove(),d.selectAll("g."+p+"-group").remove(),t.style({visibility:null});for(var g=t.node();g&&g.removeAttribute;g=g.parentNode)g.removeAttribute("data-bb");if(f){var v=l.Lib.getPlotDiv(u.node());(v&&v._promises||[]).push(new Promise(function(t){u.style({visibility:"hidden"});var i={fontSize:parseInt(u.style("font-size"),10)};a(f[2],i,function(i,a,o){d.selectAll("svg."+p).remove(),d.selectAll("g."+p+"-group").remove();var s=i&&i.select("svg");if(!s||!s.node())return r(),void t();var l=d.append("g").classed(p+"-group",!0).attr({"pointer-events":"none"});l.node().appendChild(s.node()),a&&a.node()&&s.node().insertBefore(a.node().cloneNode(!0),s.node().firstChild),s.attr({"class":p,height:o.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var c=u.style("fill")||"black";s.select("g").attr({fill:c,stroke:c});var f=n(s,"width"),h=n(s,"height"),g=+u.attr("x")-f*{start:0,middle:.5,end:1}[u.attr("text-anchor")||"start"],v=parseInt(u.style("font-size"),10)||n(u,"height"),m=-v/4;"y"===p[0]?(l.attr({transform:"rotate("+[-90,+u.attr("x"),+u.attr("y")]+") translate("+[-f/2,m-h/2]+")"}),s.attr({x:+u.attr("x"),y:+u.attr("y")})):"l"===p[0]?s.attr({x:u.attr("x"),y:m-h/2}):"a"===p[0]?s.attr({x:0,y:m}):s.attr({x:g,y:+u.attr("y")+m-h/2}),e&&e.call(u,l),t(l)})}))}else r();return t}};var h={sup:'font-size:70%" dy="-0.6em',sub:'font-size:70%" dy="0.3em',b:"font-weight:bold",i:"font-style:italic",a:"",span:"",br:"",em:"font-style:italic;font-weight:bold"},d=["http:","https:","mailto:"],p=new RegExp("]*)?/?>","g");f.plainText=function(t){return(t||"").replace(p," ")},f.makeEditable=function(t,e,r){function n(){a(),o.style({opacity:0});var t,e=h.attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&c.select(o.node().parentNode).select(t).style({opacity:0})}function i(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}function a(){var t=c.select(l.Lib.getPlotDiv(o.node())),e=t.select(".svg-container"),n=e.append("div");n.classed("plugin-editable editable",!0).style({position:"absolute","font-family":o.style("font-family")||"Arial","font-size":o.style("font-size")||12,color:r.fill||o.style("fill")||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-parseFloat(o.style("font-size"))/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||o.attr("data-unformatted")).call(s(o,e,r)).on("blur",function(){o.text(this.textContent).style({opacity:1});var t,e=c.select(this).attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&c.select(o.node().parentNode).select(t).style({opacity:0});var r=this.textContent;c.select(this).transition().duration(0).remove(),c.select(document).on("mouseup",null),u.edit.call(o,r)}).on("focus",function(){var t=this;c.select(document).on("mouseup",function(){return c.event.target===t?!1:void(document.activeElement===n.node()&&n.node().blur())})}).on("keyup",function(){27===c.event.which?(o.style({opacity:1}),c.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),u.cancel.call(o,this.textContent)):(u.input.call(o,this.textContent),c.select(this).call(s(o,e,r)))}).on("keydown",function(){13===c.event.which&&this.blur()}).call(i)}r||(r={});var o=this,u=c.dispatch("edit","input","cancel"),f=c.select(this.node()).style({"pointer-events":"all"}),h=e||f;return e&&f.style({"pointer-events":"none"}),r.immediate?n():h.on("click",n),c.rebind(this,u,"on")}},{"../constants/xmlns_namespaces":369,"../plotly":400,d3:113}],394:[function(t,e,r){"use strict";var n=e.exports={},i=t("../plots/geo/constants").locationmodeToLayer,a=t("topojson").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../plots/geo/constants":422,topojson:275}],395:[function(t,e,r){"use strict";function n(t){var e;if("string"==typeof t){if(e=document.getElementById(t),null===e)throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t}function i(t,e){t._fullLayout._paperdiv.style("background","white"),P.defaultConfig.setBackground(t,e)}function a(t,e){t._context||(t._context=R.extendFlat({},P.defaultConfig));var r=t._context;e&&(Object.keys(e).forEach(function(t){t in r&&("setBackground"===t&&"opaque"===e[t]?r[t]=i:r[t]=e[t])}),e.plot3dPixelRatio&&!r.plotGlPixelRatio&&(r.plotGlPixelRatio=r.plot3dPixelRatio)),r.staticPlot&&(r.editable=!1,r.autosizable=!1,r.scrollZoom=!1,r.doubleClick=!1,r.showTips=!1,r.showLink=!1,r.displayModeBar=!1)}function o(t,e,r){var n=S.select(t).selectAll(".plot-container").data([0]);n.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=n.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e),r&&(t.layout=r),P.micropolar.manager.fillLayout(t),"initial"===t._fullLayout.autosize&&t._context.autosizable&&(w(t,{}),t._fullLayout.autosize=r.autosize=!0),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=P.micropolar.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var a=t.framework.svg(),o=1,s=t._fullLayout.title;""!==s&&s||(o=0);var l="Click to enter title",c=function(){this.call(P.util.convertToTspans)},u=a.select(".title-group text").call(c);if(t._context.editable){u.attr({"data-unformatted":s}),s&&s!==l||(o=.2,u.attr({"data-unformatted":l}).text(l).style({opacity:o}).on("mouseover.opacity",function(){S.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){S.select(this).transition().duration(1e3).style("opacity",0)}));var f=function(){this.call(P.util.makeEditable).on("edit",function(e){t.framework({layout:{title:e}}),this.attr({"data-unformatted":e}).text(e).call(c),this.call(f)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(c)})};u.call(f)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),N.addLinks(t),Promise.resolve()}function s(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1);var n=P.Axes.list({_fullLayout:t});for(e=0;ee;e++){var o=t.annotations[e];o.ref&&("paper"===o.ref?(o.xref="paper",o.yref="paper"):"data"===o.ref&&(o.xref="x",o.yref="y"),delete o.ref),l(o,"xref"),l(o,"yref")}void 0===t.shapes||Array.isArray(t.shapes)||(console.log("shapes must be an array"),delete t.shapes);var s=(t.shapes||[]).length;for(e=0;s>e;e++){var c=t.shapes[e];l(c,"xref"),l(c,"yref")}var u=t.legend;u&&(u.x>3?(u.x=1.02,u.xanchor="left"):u.x<-2&&(u.x=-.02,u.xanchor="right"),u.y>3?(u.y=1.02,u.yanchor="bottom"):u.y<-2&&(u.y=-.02,u.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var h=N.getSubplotIds(t,"gl3d");for(e=0;er;++r)b[r]=v[e]+m*y[2+4*r];d.camera={eye:{x:b[0],y:b[1],z:b[2]},center:{x:v[0],y:v[1],z:v[2]},up:{x:y[1],y:y[5],z:y[9]}},delete d.cameraposition}}return R.markTime("finished rest of cleanLayout, starting color"),F.clean(t),R.markTime("finished cleanLayout color.clean"),t}function l(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=P.Axes.cleanId(r,n))}function c(t,e){for(var r=[],n=(t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid})),i=0;ia&&(s=R.randstr(n),-1!==r.indexOf(s));a++);o.uid=R.randstr(n),n.push(o.uid)}if(r.push(o.uid),"histogramy"===o.type&&"xbins"in o&&!("ybins"in o)&&(o.ybins=o.xbins,delete o.xbins),o.error_y&&"opacity"in o.error_y){var l=F.defaults,c=o.error_y.color||(N.traceIs(o,"bar")?F.defaultLine:l[i%l.length]);o.error_y.color=F.addOpacity(F.rgb(c),F.opacity(c)*o.error_y.opacity),delete o.error_y.opacity}if("bardir"in o&&("h"!==o.bardir||!N.traceIs(o,"bar")&&"histogram"!==o.type.substr(0,9)||(o.orientation="h",x(o)),delete o.bardir),"histogramy"===o.type&&x(o),"histogramx"!==o.type&&"histogramy"!==o.type||(o.type="histogram"),"scl"in o&&(o.colorscale=o.scl,delete o.scl),"reversescl"in o&&(o.reversescale=o.reversescl,delete o.reversescl),o.xaxis&&(o.xaxis=P.Axes.cleanId(o.xaxis,"x")),o.yaxis&&(o.yaxis=P.Axes.cleanId(o.yaxis,"y")),N.traceIs(o,"gl3d")&&o.scene&&(o.scene=N.subplotsRegistry.gl3d.cleanId(o.scene)),N.traceIs(o,"pie")||(Array.isArray(o.textposition)?o.textposition=o.textposition.map(u):o.textposition&&(o.textposition=u(o.textposition))),N.traceIs(o,"2dMap")&&("YIGnBu"===o.colorscale&&(o.colorscale="YlGnBu"),"YIOrRd"===o.colorscale&&(o.colorscale="YlOrRd")),N.traceIs(o,"markerColorscale")&&o.marker){var h=o.marker;"YIGnBu"===h.colorscale&&(h.colorscale="YlGnBu"),"YIOrRd"===h.colorscale&&(h.colorscale="YlOrRd")}if("surface"===o.type&&R.isPlainObject(o.contours)){var d=["x","y","z"];for(a=0;an?a.push(i+n):a.push(n);return a}function p(t,e,r){var n,i;for(n=0;n=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||0>i&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function g(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),p(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&p(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function v(t,e,r){var n,i;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n=0&&l0){var s=_(t._boundingBoxMargins),l=s.left+s.right,c=s.bottom+s.top,u=a._container.node().getBoundingClientRect(),f=1-2*o.frameMargins;i=Math.round(f*(u.width-l)),n=Math.round(f*(u.height-c))}else r=window.getComputedStyle(t),n=parseFloat(r.height)||a.height,i=parseFloat(r.width)||a.width;return Math.abs(a.width-i)>1||Math.abs(a.height-n)>1?(a.height=t.layout.height=n,a.width=t.layout.width=i):"initial"!==a.autosize&&(delete e.autosize,a.autosize=t.layout.autosize=!0),N.sanitizeMargins(a),e}function k(t){var e=S.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),"initial"===r.autosize&&(w(t,{}),r.autosize=!0,t.layout.autosize=!0),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([0]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._geocontainer=r._paperdiv.selectAll(".geo-container").data([0]),r._geocontainer.enter().append("div").classed("geo-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var n=[];S.selectAll("defs").each(function(){this.id&&n.push(this.id.split("-")[1])}),r._uid=R.randstr(n)}r._paperdiv.selectAll(".main-svg").attr(W.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=i.append("g").classed("imagelayer",!0),r._shapeLowerLayer=i.append("g").classed("shapelayer",!0);var a=P.Axes.getSubplots(t);a.join("")!==Object.keys(t._fullLayout._plots||{}).join("")&&A(t,a),r._has("cartesian")&&M(t,a),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0);var o=r._paper.selectAll(".layer-subplot");r._imageSubplotLayer=o.selectAll(".imagelayer"),r._shapeSubplotLayer=o.selectAll(".shapelayer");var s=r._paper.append("g").classed("layer-above",!0);r._imageUpperLayer=s.append("g").classed("imagelayer",!0),r._shapeUpperLayer=s.append("g").classed("shapelayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0),r._geoimages=r._paper.append("g").classed("geoimages",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework");var l=R.syncOrAsync([T,function(){return P.Axes.doTicks(t,"redraw")},j.init],t);return l&&l.then&&t._promises.push(l),l}function A(t,e){function r(e,r){return function(){return P.Axes.getFromId(t,e,r)}}for(var n,i,a=t._fullLayout._plots={},o=0;o0,_=P.Axes.getSubplots(t).join(""),w=Object.keys(t._fullLayout._plots||{}).join(""),A=w===_;x?t.framework===k&&!b&&A||(t.framework=k,k(t)):A?b&&k(t):(t.framework=k,k(t)),b&&P.Axes.saveRangeInitial(t);var M=t._fullLayout,E=!t.calcdata||t.calcdata.length!==(t.data||[]).length;E&&h(t);for(var L=0;LY.range[0]?[1,2]:[2,1]);else{var W=Y.range[0],Z=Y.range[1];"log"===O?(0>=W&&0>=Z&&i(q+".autorange",!0),0>=W?W=Z/1e6:0>=Z&&(Z=W/1e6),i(q+".range[0]",Math.log(W)/Math.LN10),i(q+".range[1]",Math.log(Z)/Math.LN10)):(i(q+".range[0]",Math.pow(10,W)),i(q+".range[1]",Math.pow(10,Z)))}else i(q+".autorange",!0)}if("reverse"===D)H.range?H.range.reverse():(i(q+".autorange",!0),H.range=[1,0]),G.autorange?_=!0:x=!0;else if("annotations"===z.parts[0]||"shapes"===z.parts[0]){var K=z.parts[1],$=z.parts[0],Q=p[$]||[],J=P[R.titleCase($)],tt=Q[K]||{};2===z.parts.length&&("add"===v[C]||R.isPlainObject(v[C])?E[C]="remove":"remove"===v[C]?-1===K?(E[$]=Q,delete E[C]):E[C]=tt:console.log("???",v)),!a(tt,"x")&&!a(tt,"y")||R.containsAny(C,["color","opacity","align","dash"])||(_=!0),J.draw(t,K,z.parts.slice(2).join("."),v[C]),delete v[C]}else if("images"===z.parts[0]){var rt=R.objectFromPath(e,O);R.extendDeepAll(t.layout,rt),U.supplyLayoutDefaults(t.layout,t._fullLayout),U.draw(t)}else 0===z.parts[0].indexOf("scene")?x=!0:0===z.parts[0].indexOf("geo")?x=!0:0===z.parts[0].indexOf("ternary")?x=!0:!g._has("gl2d")||-1===C.indexOf("axis")&&"plot_bgcolor"!==z.parts[0]?"hiddenlabels"===C?_=!0:-1!==z.parts[0].indexOf("legend")?m=!0:-1!==C.indexOf("title")?y=!0:-1!==z.parts[0].indexOf("bgcolor")?b=!0:z.parts.length>1&&R.containsAny(z.parts[1],["tick","exponent","grid","zeroline"])?y=!0:-1!==C.indexOf(".linewidth")&&-1!==C.indexOf("axis")?y=b=!0:z.parts.length>1&&-1!==z.parts[1].indexOf("line")?b=!0:z.parts.length>1&&"mirror"===z.parts[1]?y=b=!0:"margin.pad"===C?y=b=!0:"margin"===z.parts[0]||"autorange"===z.parts[1]||"rangemode"===z.parts[1]||"type"===z.parts[1]||"domain"===z.parts[1]||C.match(/^(bar|box|font)/)?_=!0:-1!==["hovermode","dragmode"].indexOf(C)?k=!0:-1===["hovermode","dragmode","height","width","autosize"].indexOf(C)&&(x=!0):x=!0,z.set(O)}I&&I.add(t,et,[t,E],et,[t,M]),v.autosize&&(v=w(t,v)),(v.height||v.width||v.autosize)&&(_=!0);var nt=Object.keys(v),it=[N.previousPromises];if(x||_)it.push(function(){return t.layout=void 0,_&&(t.calcdata=void 0),P.plot(t,"",p)});else if(nt.length&&(N.supplyDefaults(t),g=t._fullLayout,m&&it.push(function(){return V.draw(t),N.previousPromises(t)}),b&&it.push(T),y&&it.push(function(){return P.Axes.doTicks(t,"redraw"),L(t),N.previousPromises(t)}),k)){var at;for(X(t),at=N.getSubplotIds(g,"gl3d"),d=0;d1)};c(r.width)&&c(r.height)||s(new Error("Height and width should be pixel values."));var u=n.clone(e,{format:"png",height:r.height,width:r.width}),f=u.td;f.style.position="absolute",f.style.left="-5000px",document.body.appendChild(f);var h=n.getRedrawFunc(f);a.plot(f,u.data,u.layout,u.config).then(h).then(l).then(function(e){t(e)}).catch(function(t){s(t)})});return s}var i=t("fast-isnumeric"),a=t("../plotly"),o=t("../lib");e.exports=n},{"../lib":381,"../plotly":400,"../snapshot":469,"fast-isnumeric":117}],400:[function(t,e,r){"use strict";t("es6-promise").polyfill(),r.Lib=t("./lib"),r.util=t("./lib/svg_text_utils"),r.Queue=t("./lib/queue"),t("../build/plotcss"),r.MathJaxConfig=t("./fonts/mathjax_config"),r.defaultConfig=t("./plot_api/plot_config");var n=r.Plots=t("./plots/plots");r.Axes=t("./plots/cartesian/axes"),r.Fx=t("./plots/cartesian/graph_interact"),r.micropolar=t("./plots/polar/micropolar"),r.Color=t("./components/color"),r.Drawing=t("./components/drawing"),r.Colorscale=t("./components/colorscale"),r.Colorbar=t("./components/colorbar"),r.ErrorBars=t("./components/errorbars"),r.Annotations=t("./components/annotations"),r.Shapes=t("./components/shapes"),r.Legend=t("./components/legend"),r.Images=t("./components/images"),r.ModeBar=t("./components/modebar"),r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;ec&&u>e&&(void 0===i[r]?a[f]=T.tickText(t,e):a[f]=s(t,e,String(i[r])),f++);return f=864e5?t._tickround="d":r>=36e5?t._tickround="H":r>=6e4?t._tickround="M":r>=1e3?t._tickround="S":t._tickround=3-Math.round(Math.log(r/2)/Math.LN10);else{b(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01),e="log"===t.type?Math.pow(10,Math.max(t.range[0],t.range[1])):Math.max(Math.abs(t.range[0]),Math.abs(t.range[1]));var n=Math.floor(Math.log(e)/Math.LN10+.01);Math.abs(n)>3&&("SI"===t.exponentformat||"B"===t.exponentformat?t._tickexponent=3*Math.round((n-1)/3):t._tickexponent=n)}else"M"===r.charAt(0)?t._tickround=2===r.length?"m":"y":t._tickround=null}function o(t,e){var r=t.match(U),n=new Date(e);if(r){var i=Math.min(+r[1]||6,6),a=String(e/1e3%1+2.0000005).substr(2,i).replace(/0+$/,"")||"0";return y.time.format(t.replace(U,a))(n)}return y.time.format(t)(n)}function s(t,e,r){var n=t.tickfont||t._gd._fullLayout.font;return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}function l(t,e,r,n){var i,a=e.x,s=t._tickround,l=new Date(a),c="";r&&t.hoverformat?i=o(t.hoverformat,a):t.tickformat?i=o(t.tickformat,a):(n&&(b(s)?s+=2:s={y:"m",m:"d",d:"H",H:"M",M:"S",S:2}[s]),"y"===s?i=I(l):"m"===s?i=N(l):(a!==t._tmin||r||(c="
"+I(l)),"d"===s?i=j(l):"H"===s?i=F(l):(a!==t._tmin||r||(c="
"+j(l)+", "+I(l)),i=D(l),"M"!==s&&(i+=B(l),"S"!==s&&(i+=h(m(a/1e3,1),t,"none",r).substr(1)))))),e.text=i+c}function c(t,e,r,n,i){var a=t.dtick,o=e.x;if(!n||"string"==typeof a&&"L"===a.charAt(0)||(a="L3"),t.tickformat||"string"==typeof a&&"L"===a.charAt(0))e.text=h(Math.pow(10,o),t,i,n);else if(b(a)||"D"===a.charAt(0)&&m(o+.01,1)<.1)if(-1!==["e","E","power"].indexOf(t.exponentformat)){var s=Math.round(o);0===s?e.text=1:1===s?e.text="10":s>1?e.text="10"+s+"":e.text="10\u2212"+-s+"",e.fontSize*=1.25}else e.text=h(Math.pow(10,o),t,"","fakehover"),"D1"===a&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6);else{if("D"!==a.charAt(0))throw"unrecognized dtick "+String(a);e.text=String(Math.round(Math.pow(10,m(o,1)))),e.fontSize*=.75}if("D1"===t.dtick){var l=String(e.text).charAt(0);"0"!==l&&"1"!==l||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(0>o?.5:.25)))}}function u(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r=""),e.text=String(r)}function f(t,e,r,n,i){"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide"),e.text=h(e.x,t,i,n)}function h(t,e,r,n){var i=0>t,o=e._tickround,s=r||e.exponentformat||"B",l=e._tickexponent,c=e.tickformat;if(n){var u={exponentformat:e.exponentformat,dtick:"none"===e.showexponent?e.dtick:b(t)?Math.abs(t)||1:1,range:"none"===e.showexponent?e.range:[0,t||1]};a(u),o=(Number(u._tickround)||0)+4,l=u._tickexponent,e.hoverformat&&(c=e.hoverformat)}if(c)return y.format(c)(t).replace(/-/g,"\u2212");var f=Math.pow(10,-o)/2;if("none"===s&&(l=0),t=Math.abs(t),f>t)t="0",i=!1;else{if(t+=f,l&&(t*=Math.pow(10,-l),o+=l),0===o)t=String(Math.floor(t));else if(0>o){t=String(Math.round(t)),t=t.substr(0,t.length+o);for(var h=o;0>h;h++)t+="0"}else{t=String(t);var d=t.indexOf(".")+1;d&&(t=t.substr(0,d+o).replace(/\.?0+$/,""))}t=_.numSeparate(t,e._gd._fullLayout.separators)}if(l&&"hide"!==s){var p;p=0>l?"\u2212"+-l:"power"!==s?"+"+l:String(l),"e"===s||("SI"===s||"B"===s)&&(l>12||-15>l)?t+="e"+p:"E"===s?t+="E"+p:"power"===s?t+="×10"+p+"":"B"===s&&9===l?t+="B":"SI"!==s&&"B"!==s||(t+=V[l/3+5])}return i?"\u2212"+t:t}function d(t,e){var r,n,i=[];for(r=0;r1)for(n=1;n2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},T.getAutoRange=function(t){var e,r=[],n=t._min[0].val,i=t._max[0].val;for(e=1;e0&&u>0&&f/u>h&&(l=o,c=s,h=f/u);return n===i?r=d?[n+1,"normal"!==t.rangemode?0:n-1]:["normal"!==t.rangemode?0:n-1,n+1]:h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode&&l.val>=0?l={val:0,pad:0}:"nonnegative"===t.rangemode&&(l.val-h*l.pad<0&&(l={val:0,pad:0}),c.val<0&&(c={val:1,pad:0})),h=(c.val-l.val)/(t._length-l.pad-c.pad)),r=[l.val-h*l.pad,c.val+h*c.pad],r[0]===r[1]&&(r=[r[0]-1,r[0]+1]),d&&r.reverse()),r},T.doAutoRange=function(t){t._length||t.setScale();var e=t._min&&t._max&&t._min.length&&t._max.length;if(t.autorange&&e){t.range=T.getAutoRange(t);var r=t._gd.layout[t._name];r||(t._gd.layout[t._name]=r={}),r!==t&&(r.range=t.range.slice(),r.autorange=t.autorange)}},T.saveRangeInitial=function(t,e){for(var r=T.list(t,"",!0),n=!1,i=0;ip&&(p=g/10),c=t.c2l(p),u=t.c2l(g),y&&(c=Math.min(0,c),u=Math.max(0,u)),n(c)){for(d=!0,o=0;o=h?d=!1:s.val>=c&&s.pad<=h&&(t._min.splice(o,1),o--);d&&t._min.push({val:c,pad:y&&0===c?0:h})}if(n(u)){for(d=!0,o=0;o=u&&s.pad>=f?d=!1:s.val<=u&&s.pad<=f&&(t._max.splice(o,1),o--);d&&t._max.push({val:u,pad:y&&0===u?0:f})}}}if((t.autorange||t._needsExpand)&&e){t._min||(t._min=[]),t._max||(t._max=[]),r||(r={}),t._m||t.setScale();var a,o,s,l,c,u,f,h,d,p,g,v=e.length,m=r.padded?.05*t._length:0,y=r.tozero&&("linear"===t.type||"-"===t.type),x=n((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),_=n((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),w=n(r.vpadplus||r.vpad),k=n(r.vpadminus||r.vpad);for(a=0;6>a;a++)i(a);for(a=v-1;a>5;a--)i(a)}},T.autoBin=function(t,e,r,n){function i(t){return(1+100*(t-d)/f.dtick)%100<2}var a=_.aggNums(Math.min,null,t),o=_.aggNums(Math.max,null,t);if("category"===e.type)return{start:a-.5,end:o+.5,size:1};var s;if(r)s=(o-a)/r;else{var l=_.distinctVals(t),c=Math.pow(10,Math.floor(Math.log(l.minDiff)/Math.LN10)),u=c*_.roundUp(l.minDiff/c,[.9,1.9,4.9,9.9],!0);s=Math.max(u,2*_.stdev(t)/Math.pow(t.length,n?.25:.4))}var f={type:"log"===e.type?"linear":e.type,range:[a,o]};T.autoTicks(f,s);var h,d=T.tickIncrement(T.tickFirst(f),f.dtick,"reverse");if("number"==typeof f.dtick){for(var p=0,g=0,v=0,m=0,y=0;yg&&(p>.3*x||i(a)||i(o))){var w=f.dtick/2;d+=a>d+w?w:-w}var k=1+Math.floor((o-d)/f.dtick);h=d+k*f.dtick}else for(h=d;o>=h;)h=T.tickIncrement(h,f.dtick);return{start:d,end:h,size:f.dtick}},T.calcTicks=function(t){if("array"===t.tickmode)return n(t);if("auto"===t.tickmode||!t.dtick){var e,r=t.nticks;r||("category"===t.type?(e=t.tickfont?1.2*(t.tickfont.size||12):15,r=t._length/e):(e="y"===t._id.charAt(0)?40:80,r=_.constrain(t._length/e,4,9)+1)),T.autoTicks(t,Math.abs(t.range[1]-t.range[0])/r),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t._forceTick0)}t.tick0||(t.tick0="date"===t.type?new Date(2e3,0,1).getTime():0),a(t),t._tmin=T.tickFirst(t);var i=t.range[1]=s:s>=l)&&(o.push(l),!(o.length>1e3));l=T.tickIncrement(l,t.dtick,i));t._tmax=o[o.length-1];for(var c=new Array(o.length),u=0;u157788e5?(e/=315576e5,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="M"+12*i(e,r,S)):e>12096e5?(e/=26298e5,t.dtick="M"+i(e,1,C)):e>432e5?(t.dtick=i(e,864e5,P),t.tick0=new Date(2e3,0,2).getTime()):e>18e5?t.dtick=i(e,36e5,C):e>3e4?t.dtick=i(e,6e4,z):e>500?t.dtick=i(e,1e3,z):(r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));else if("log"===t.type)if(t.tick0=0,e>.7)t.dtick=Math.ceil(e);else if(Math.abs(t.range[1]-t.range[0])<1){var n=1.5*Math.abs((t.range[1]-t.range[0])/e);e=Math.abs(Math.pow(10,t.range[1])-Math.pow(10,t.range[0]))/n,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="L"+i(e,r,S)}else t.dtick=e>.3?"D2":"D1";else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):(t.tick0=0,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,S));if(0===t.dtick&&(t.dtick=1),!b(t.dtick)&&"string"!=typeof t.dtick){var a=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(a)}},T.tickIncrement=function(t,e,r){var n=r?-1:1;if(b(e))return t+n*e;var i=e.charAt(0),a=n*Number(e.substr(1));if("M"===i){var o=new Date(t);return o.setMonth(o.getMonth()+a)}if("L"===i)return Math.log(Math.pow(10,t)+a)/Math.LN10;if("D"===i){var s="D2"===e?O:R,l=t+.01*n,c=_.roundUp(m(l,1),s,r);return Math.floor(l)+Math.log(y.round(Math.pow(10,c),1))/Math.LN10}throw"unrecognized dtick "+String(e)},T.tickFirst=function(t){var e=t.range[1]n:n>c;)c=T.tickIncrement(c,i,e);return c}if("L"===u)return Math.log(r((Math.pow(10,n)-a)/f)*f+a)/Math.LN10;if("D"===u){var h="D2"===i?O:R,d=_.roundUp(m(n,1),h,e);return Math.floor(n)+Math.log(y.round(Math.pow(10,d),1))/Math.LN10}throw"unrecognized dtick "+String(i)};var I=y.time.format("%Y"),N=y.time.format("%b %Y"),j=y.time.format("%b %-d"),F=y.time.format("%b %-d %Hh"),D=y.time.format("%H:%M"),B=y.time.format(":%S"),U=/%(\d?)f/g;T.tickText=function(t,e,r){function n(n){var i;return void 0===n?!0:r?"none"===n:(i={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==i)}var i,a,o=s(t,e),h="array"===t.tickmode,d=r||h;if(h&&Array.isArray(t.ticktext)){var p=Math.abs(t.range[1]-t.range[0])/1e4;for(a=0;a1&&er&&(A=90),i(u,A)}c._lastangle=A}return o(e),e+" done"}function l(){c._boundingBox=r.node().getBoundingClientRect()}var u=r.selectAll("g."+C).data(L,S);if(!c.showticklabels||!b(n))return u.remove(),void o(e);var f,h,p,m,x;"x"===v?(x="bottom"===B?1:-1,f=function(t){return t.dx+I*x},m=n+(O+R)*x,h=function(t){return t.dy+m+t.fontSize*("bottom"===B?1:-.5)},p=function(t){return b(t)&&0!==t&&180!==t?0>t*x?"end":"start":"middle"}):(x="right"===B?1:-1,h=function(t){return t.dy+t.fontSize/2-I*x},f=function(t){return t.dx+n+(O+R+(90===Math.abs(c.tickangle)?t.fontSize/2:0))*x},p=function(t){return b(t)&&90===Math.abs(t)?"middle":"right"===B?"start":"end"});var k=0,A=0,T=[];u.enter().append("g").classed(C,1).append("text").attr("text-anchor","middle").each(function(e){var r=y.select(this),n=t._promises.length;r.call(M.setPosition,f(e),h(e)).call(M.font,e.font,e.fontSize,e.fontColor).text(e.text).call(w.convertToTspans),n=t._promises[n],n?T.push(t._promises.pop().then(function(){i(r,c.tickangle)})):i(r,c.tickangle)}),u.exit().remove(),u.each(function(t){k=Math.max(k,t.fontSize)}),i(u,c._lastangle||c.tickangle);var E=_.syncOrAsync([a,s,l]);return E&&E.then&&t._promises.push(E),E}function o(e){if(!r){var n,i,a,o,s=E.getFromId(t,e),l=y.select(t).selectAll("g."+e+"tick"),c={selection:l,side:s.side},f=e.charAt(0),h=t._fullLayout._size,d=1.5,p=s.titlefont.size;if(l.size()){var g=y.select(l.node().parentNode).attr("transform").match(/translate\(([-\.\d]+),([-\.\d]+)\)/);g&&(c.offsetLeft=+g[1],c.offsetTop=+g[2])}"x"===f?(i="free"===s.anchor?{_offset:h.t+(1-(s.position||0))*h.h,_length:0}:E.getFromId(t,s.anchor),a=s._offset+s._length/2,o=i._offset+("top"===s.side?-10-p*(d+(s.showticklabels?1:0)):i._length+10+p*(d+(s.showticklabels?1.5:.5))),s.rangeslider&&s.rangeslider.visible&&s._boundingBox&&(o+=(u.height-u.margin.b-u.margin.t)*s.rangeslider.thickness+s._boundingBox.height),c.side||(c.side="bottom")):(i="free"===s.anchor?{_offset:h.l+(s.position||0)*h.w,_length:0}:E.getFromId(t,s.anchor),o=s._offset+s._length/2,a=i._offset+("right"===s.side?i._length+10+p*(d+(s.showticklabels?1:.5)):-10-p*(d+(s.showticklabels?.5:0))),n={rotate:"-90",offset:0},c.side||(c.side="left")),k.draw(t,e+"title",{propContainer:s,propName:s._name+".title",dfltName:f.toUpperCase()+" axis",avoid:c,transform:n,attributes:{x:a,y:o,"text-anchor":"middle"}})}}function s(t,e){return t.visible!==!0||t.xaxis+t.yaxis!==e?!1:x.Plots.traceIs(t,"bar")&&t.orientation==={x:"h",y:"v"}[v]?!0:t.fill&&t.fill.charAt(t.fill.length-1)===v}function l(e,r,i){var a=e.gridlayer,o=e.zerolinelayer,l=e["hidegrid"+v]?[]:V,u=c._gridpath||"M0,0"+("x"===v?"v":"h")+r._length,f=a.selectAll("path."+z).data(c.showgrid===!1?[]:l,S);if(f.enter().append("path").classed(z,1).classed("crisp",1).attr("d",u).each(function(t){c.zeroline&&("linear"===c.type||"-"===c.type)&&Math.abs(t.x)g;g++){var y=c.mirrors[o._id+h[g]];"ticks"!==y&&"labels"!==y||(f[g]=!0)}return void 0!==n[2]&&(f[2]=!0),f.forEach(function(t,e){var r=n[e],i=U[e];t&&b(r)&&(d+=p(r+R*i,i*c.ticklen))}),i(r,d),l(e,o,t),a(r,n[3])}}).filter(function(t){return t&&t.then});return H.length?Promise.all(H):0},T.swap=function(t,e){for(var r=d(t,e),n=0;n2*n}function u(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a2*n}var f=t("fast-isnumeric"),h=t("tinycolor2").mix,d=t("../../lib"),p=t("../plots"),g=t("../../components/color/attributes").lightFraction,v=t("./layout_attributes"),m=t("./tick_value_defaults"),y=t("./tick_mark_defaults"),b=t("./tick_label_defaults"),x=t("./category_order_defaults"),_=t("./set_convert"),w=t("./ordered_categories"),k=t("./clean_datum"),A=t("./axis_ids");e.exports=function(t,e,r,i){function a(r,n){return d.coerce2(t,e,v,r,n)}var o=i.letter,s=i.font||{},l="Click to enter "+(i.title||o.toUpperCase()+" axis")+" title";i.name&&(e._name=i.name,e._id=A.name2id(i.name));var c=r("type");"-"===c&&(n(e,i.data),"-"===e.type?e.type="linear":c=t.type=e.type),_(e);var u=r("color"),p=u===t.color?u:s.color;r("title",l),d.coerceFont(r,"titlefont",{family:s.family,size:Math.round(1.2*s.size),color:p});var k=2===(t.range||[]).length&&f(t.range[0])&&f(t.range[1]),M=r("autorange",!k); +M&&r("rangemode");var T=r("range",[-1,"x"===o?6:4]);T[0]===T[1]&&(e.range=[T[0]-1,T[0]+1]),d.noneOrAll(t.range,e.range,[0,1]),r("fixedrange"),m(t,e,r,c),b(t,e,r,c,i),y(t,e,r,i),x(t,e,r);var E=a("linecolor",u),L=a("linewidth"),S=r("showline",!!E||!!L);S||(delete e.linecolor,delete e.linewidth),(S||e.ticks)&&r("mirror");var C=a("gridcolor",h(u,i.bgColor,g).toRgbString()),z=a("gridwidth"),P=r("showgrid",i.showGrid||!!C||!!z);P||(delete e.gridcolor,delete e.gridwidth);var R=a("zerolinecolor",u),O=a("zerolinewidth"),I=r("zeroline",i.showGrid||!!R||!!O);return I||(delete e.zerolinecolor,delete e.zerolinewidth),e._initialCategories="category"===c?w(o,e.categoryorder,e.categoryarray,i.data):[],e}},{"../../components/color/attributes":302,"../../lib":381,"../plots":452,"./axis_ids":405,"./category_order_defaults":406,"./clean_datum":407,"./layout_attributes":412,"./ordered_categories":414,"./set_convert":417,"./tick_label_defaults":418,"./tick_mark_defaults":419,"./tick_value_defaults":420,"fast-isnumeric":117,tinycolor2:274}],405:[function(t,e,r){"use strict";function n(t,e,r){function n(t,r){for(var n=Object.keys(t),i=/^[xyz]axis[0-9]*/,a=[],o=0;o0;a&&(n="array");var o=r("categoryorder",n);"array"===o&&r("categoryarray"),a||"array"!==o||(e.categoryorder="trace")}}},{}],407:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t){try{if("object"==typeof t&&null!==t&&t.getTime)return i.ms2DateTime(t);if("string"!=typeof t&&!n(t))return"";t=t.toString().replace(/['"%,$# ]/g,"")}catch(e){console.log(e,t)}return t}},{"../../lib":381,"fast-isnumeric":117}],408:[function(t,e,r){"use strict";e.exports={idRegex:{x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},attrRegex:{x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},BADNUM:void 0,xAxisMatch:/^xaxis[0-9]*$/,yAxisMatch:/^yaxis[0-9]*$/,AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,DBLCLICKDELAY:300,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,MAXDIST:20,YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,BENDPX:1.5,REDRAWDELAY:50}},{}],409:[function(t,e,r){"use strict";function n(t,e){var r,n=t.range[e],i=Math.abs(n-t.range[1-e]);return"date"===t.type?c.ms2DateTime(n,i):"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,o.format("."+r+"g")(Math.pow(10,n))):(r=Math.floor(Math.log(Math.abs(n))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,o.format("."+String(r)+"g")(n))}function i(t,e){return t?"nsew"===t?"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}function a(t){o.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var o=t("d3"),s=t("tinycolor2"),l=t("../../plotly"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../components/color"),h=t("../../components/drawing"),d=t("../../lib/setcursor"),p=t("../../components/dragelement"),g=t("./axes"),v=t("./select"),m=t("./constants"),y=!0;e.exports=function(t,e,r,o,b,x,_,w){function k(t,e){for(var r=0;r.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+ht+", "+dt+")").attr("d",ot+"Z"),ut=ft.append("path").attr("class","zoombox-corners").style({fill:f.background,stroke:f.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+ht+", "+dt+")").attr("d","M0,0Z"),T();for(var a=0;ai?(lt="",it.r=it.l,it.t=it.b,ut.attr("d","M0,0Z")):(it.t=0,it.b=V,lt="x",ut.attr("d","M"+(it.l-.5)+","+(nt-H-.5)+"h-3v"+(2*H+1)+"h3ZM"+(it.r+.5)+","+(nt-H-.5)+"h3v"+(2*H+1)+"h-3Z")):!Z||i.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),ut.transition().style("opacity",1).duration(200),st=!0)}function L(t,e,r){var n,i,a;for(n=0;nzoom back out","long"),y=!1)))}function C(e,r){var i=1===(_+w).length;if(e)I();else if(2!==r||i){if(1===r&&i){var a=_?B[0]:D[0],o="s"===_||"w"===w?0:1,s=a._name+".range["+o+"]",c=n(a,o),f="left",h="middle";if(a.fixedrange)return;_?(h="n"===_?"top":"bottom","right"===a.side&&(f="right")):"e"===w&&(f="right"),J.call(u.makeEditable,null,{immediate:!0,background:j.paper_bgcolor,text:String(c),fill:a.tickfont?a.tickfont.color:"#444",horizontalAlign:f,verticalAlign:h}).on("edit",function(e){var r="category"===a.type?a.c2l(e):a.d2l(e);void 0!==r&&l.relayout(t,s,r)})}}else O()}function z(e){function r(t,e,r){if(!t.fixedrange){A(t.range);var n=t.range,i=n[0]+(n[1]-n[0])*e;t.range=[i+(n[0]-i)*r,i+(n[1]-i)*r]}}if(t._context.scrollZoom||j._enablescrollzoom){var n=t.querySelector(".plotly");if(!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(gt);var i=-e.deltaY;if(isFinite(i)||(i=e.wheelDelta/10),!isFinite(i))return void console.log("did not find wheel motion attributes",e);var a,o=Math.exp(-Math.min(Math.max(i,-20),20)/100),s=mt.draglayer.select(".nsewdrag").node().getBoundingClientRect(),l=(e.clientX-s.left)/s.width,u=pt[0]+pt[2]*l,f=(s.bottom-e.clientY)/s.height,h=pt[1]+pt[3]*(1-f);if(w){for(a=0;a=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function i(t,e,r){for(var i=1-e,a=0,o=0;o0;n--)r.push(e);return r}function i(t,e){for(var r=[],n=0;nj||j>D.width||0>F||F>D.height)return _.unhoverRaw(t,e)}else j="xpx"in e?e.xpx:p[0]._length/2,F="ypx"in e?e.ypx:v[0]._length/2;if(x="xval"in e?n(d,e.xval):i(p,j),A="yval"in e?n(d,e.yval):i(v,F),!g(x[0])||!g(A[0]))return console.log("Plotly.Fx.hover failed",e,t),_.unhoverRaw(t,e)}var B=1/0;for(T=0;T1||-1!==L.hoverinfo.indexOf("name")?L.name:void 0,index:!1,distance:Math.min(B,k.MAXDIST),color:b.defaultLine,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},O=I.length,"array"===C){var U=e[T];"pointNumber"in U?(R.index=U.pointNumber,C="closest"):(C="","xval"in U&&(z=U.xval,C="x"),"yval"in U&&(P=U.yval,C=C?"closest":"y"))}else z=x[S],P=A[S];if(L._module&&L._module.hoverPoints){var V=L._module.hoverPoints(R,z,P,C);if(V)for(var q,H=0;HO&&(I.splice(0,O),B=I[0].distance)}if(0===I.length)return _.unhoverRaw(t,e);var G="y"===y&&N.length>1;I.sort(function(t,e){return t.distance-e.distance});var Y=b.combine(a.plot_bgcolor||b.background,a.paper_bgcolor),X={hovermode:y,rotateLabels:G,bgColor:Y,container:a._hoverlayer,outerContainer:a._paperdiv},W=c(I,X);u(I,G?"xa":"ya"),f(W,G);var Z=t._hoverdata,K=[];for(M=0;M128?"#000":b.background;if(t.name&&void 0===t.zLabelVal){var u=document.createElement("p");u.innerHTML=t.name,r=u.textContent||"",r.length>15&&(r=r.substr(0,12)+"...")}void 0!==t.extraText&&(n+=t.extraText),void 0!==t.zLabel?(void 0!==t.xLabel&&(n+="x: "+t.xLabel+"
"),void 0!==t.yLabel&&(n+="y: "+t.yLabel+"
"),n+=(n?"z: ":"")+t.zLabel):M&&t[i+"Label"]===g?n=t[("x"===i?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(n=t.yLabel):n=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(n+=(n?"
":"")+t.text),""===n&&(""===r&&e.remove(),n=r);var f=e.select("text.nums").style("fill",c).call(x.setPosition,0,0).text(n).attr("data-notex",1).call(y.convertToTspans);f.selectAll("tspan.line").call(x.setPosition,0,0);var h=e.select("text.name"),v=0;r&&r!==n?(h.style("fill",l).text(r).call(x.setPosition,0,0).attr("data-notex",1).call(y.convertToTspans),h.selectAll("tspan.line").call(x.setPosition,0,0),v=h.node().getBoundingClientRect().width+2*P):(h.remove(),e.select("rect").remove()),e.select("path").style({fill:l,stroke:c});var m,k,E=f.node().getBoundingClientRect(),L=t.xa._offset+(t.x0+t.x1)/2,S=t.ya._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),R=Math.abs(t.y1-t.y0),O=E.width+z+P+v;t.ty0=_-E.top,t.bx=E.width+2*P,t.by=E.height+2*P,t.anchor="start",t.txwidth=E.width,t.tx2width=v,t.offset=0,a?(t.pos=L,m=A>=S+R/2+O,k=S-R/2-O>=0,"top"!==t.idealAlign&&m||!k?m?(S+=R/2,t.anchor="start"):t.anchor="middle":(S-=R/2,t.anchor="end")):(t.pos=S,m=w>=L+C/2+O,k=L-C/2-O>=0,"left"!==t.idealAlign&&m||!k?m?(L+=C/2,t.anchor="start"):t.anchor="middle":(L-=C/2,t.anchor="end")),f.attr("text-anchor",t.anchor),v&&h.attr("text-anchor",t.anchor),e.attr("transform","translate("+L+","+S+")"+(a?"rotate("+T+")":""))}),S}function u(t,e){function r(t){var e=t[0],r=t[t.length-1];if(i=e.pmin-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-e.pmax,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(.01>a)){if(-.01>i){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var c=0;for(o=0;oe.pmax&&c++;for(o=t.length-1;o>=0&&!(0>=c);o--)l=t[o],l.pos>e.pmax-1&&(l.del=!0,c--);for(o=0;o=c);o++)if(l=t[o],l.pos=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(0>=c);o--)l=t[o],l.pos+l.dp+l.size>e.pmax&&(l.del=!0,c--)}}}for(var n,i,a,o,s,l,c,u=0,f=t.map(function(t,r){var n=t[e];return[{i:r,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===n._id.charAt(0)?L:1)/2,pmin:n._offset,pmax:n._offset+n._length}]}).sort(function(t,e){return t[0].posref-e[0].posref});!n&&u<=t.length;){for(u++,n=!0,o=0;o.01&&p.pmin===g.pmin&&p.pmax===g.pmax){for(s=d.length-1;s>=0;s--)d[s].dp+=i;for(h.push.apply(h,d),f.splice(o+1,1),c=0,s=h.length-1;s>=0;s--)c+=h[s].dp;for(a=c/h.length,s=h.length-1;s>=0;s--)h[s].dp-=a;n=!1}else o++}f.forEach(r)}for(o=f.length-1;o>=0;o--){var v=f[o];for(s=v.length-1;s>=0;s--){var m=v[s],y=t[m.i];y.offset=m.dp,y.del=m.del}}}function f(t,e){t.each(function(t){var r=d.select(this);if(t.del)return void r.remove();var n="end"===t.anchor?-1:1,i=r.select("text.nums"),a={start:1,end:-1,middle:0}[t.anchor],o=a*(z+P),s=o+a*(t.txwidth+P),l=0,c=t.offset;"middle"===t.anchor&&(o-=t.tx2width/2,s-=t.tx2width/2),e&&(c*=-C,l=t.offset*S),r.select("path").attr("d","middle"===t.anchor?"M-"+t.bx/2+",-"+t.by/2+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(n*z+l)+","+(z+c)+"v"+(t.by/2-z)+"h"+n*t.bx+"v-"+t.by+"H"+(n*z+l)+"V"+(c-z)+"Z"),i.call(x.setPosition,o+l,c+t.ty0-t.by/2+P).selectAll("tspan.line").attr({x:i.attr("x"),y:i.attr("y")}),t.tx2width&&(r.select("text.name, text.name tspan.line").call(x.setPosition,s+a*P+l,c+t.ty0-t.by/2+P),r.select("rect").call(x.setRect,s+(a-1)*t.tx2width/2+l,c-t.by/2-1,t.tx2width,t.by+2))})}function h(t,e,r){if(!e.target)return!1;if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}var d=t("d3"),p=t("tinycolor2"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../lib/events"),y=t("../../lib/svg_text_utils"),b=t("../../components/color"),x=t("../../components/drawing"),_=t("../../components/dragelement"),w=t("./axes"),k=t("./constants"),A=t("./dragbox"),M=e.exports={};M.unhover=_.unhover,M.layoutAttributes={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom"},hovermode:{valType:"enumerated",values:["x","y","closest",!1]}},M.supplyLayoutDefaults=function(t,e,r){function n(r,n){return v.coerce(t,e,M.layoutAttributes,r,n)}n("dragmode");var i;if(e._has("cartesian")){var a=e._isHoriz=M.isHoriz(r);i=a?"y":"x"}else i="closest";n("hovermode",i)},M.isHoriz=function(t){for(var e=!0,r=0;rt._lastHoverTime+k.HOVERMINTIME?(o(t,e,r),void(t._lastHoverTime=Date.now())):void(t._hoverTimer=setTimeout(function(){o(t,e,r),t._lastHoverTime=Date.now(),t._hoverTimer=void 0},k.HOVERMINTIME))},M.getDistanceFunction=function(t,e,r,n){return"closest"===t?n||a(e,r):"x"===t?e:r},M.getClosest=function(t,e,r){if(r.index!==!1)r.index>=0&&r.indext*e||0===t?k.MAXDIST*(.6-.3/Math.max(3,Math.abs(t-e))):1/0}},{"../../components/color":303,"../../components/dragelement":323,"../../components/drawing":325,"../../lib":381,"../../lib/events":375,"../../lib/svg_text_utils":393,"./axes":403,"./constants":408,"./dragbox":409,d3:113,"fast-isnumeric":117,tinycolor2:274}],411:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../plots"),a=t("./constants");r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=a.idRegex,r.attrRegex=a.attrRegex,r.attributes=t("./attributes"),r.plot=function(t){function e(t,e){for(var r=[],n=0;nf[1]-.01&&(e.domain=[0,1]),i.noneOrAll(t.domain,e.domain,[0,1])}return e}},{"../../lib":381,"fast-isnumeric":117}],416:[function(t,e,r){"use strict";function n(t){return t._id}var i=t("../../lib/polygon"),a=t("../../components/color"),o=t("./axes"),s=t("./constants"),l=i.filter,c=i.tester,u=s.MINSELECT;e.exports=function(t,e,r,i,f){function h(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function d(t,e){return t-e}var p,g=i.gd._fullLayout._zoomlayer,v=i.element.getBoundingClientRect(),m=i.plotinfo.x()._offset,y=i.plotinfo.y()._offset,b=e-v.left,x=r-v.top,_=b,w=x,k="M"+b+","+x,A=i.xaxes[0]._length,M=i.yaxes[0]._length,T=i.xaxes.map(n),E=i.yaxes.map(n),L=i.xaxes.concat(i.yaxes);"lasso"===f&&(p=l([[b,x]],s.BENDPX));var S=g.selectAll("path.select-outline").data([1,2]);S.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t}).attr("transform","translate("+m+", "+y+")").attr("d",k+"Z");var C,z,P,R,O,I=g.append("path").attr("class","zoombox-corners").style({fill:a.background,stroke:a.defaultLine,"stroke-width":1}).attr("transform","translate("+m+", "+y+")").attr("d","M0,0Z"),N=[],j=i.gd,F=[];for(C=0;C0)return Math.log(e)/Math.LN10;if(0>=e&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*u*Math.abs(n-i))}return o.BADNUM}function r(t){return Math.pow(10,t)}function c(t){return i(t)?Number(t):o.BADNUM}var u=10;if(t.c2l="log"===t.type?e:c,t.l2c="log"===t.type?r:c,t.l2d=function(e){return t.c2d(t.l2c(e))},t.p2d=function(e){return t.l2d(t.p2l(e))},t.setScale=function(){var e,r=t._gd._fullLayout._size;if(t._categories||(t._categories=[]),t.overlaying){var n=l.getFromId(t._gd,t.overlaying);t.domain=n.domain}for(t.range&&2===t.range.length&&t.range[0]!==t.range[1]||(t.range=[-1,1]),e=0;2>e;e++)i(t.range[e])||(t.range[e]=i(t.range[1-e])?t.range[1-e]*(e?10:.1):e?1:-1),t.range[e]<-(Number.MAX_VALUE/2)?t.range[e]=-(Number.MAX_VALUE/2):t.range[e]>Number.MAX_VALUE/2&&(t.range[e]=Number.MAX_VALUE/2);if("y"===t._id.charAt(0)?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[0]-t.range[1]),t._b=-t._m*t.range[1]):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[1]-t.range[0]),t._b=-t._m*t.range[0]),!isFinite(t._m)||!isFinite(t._b))throw a.notifier("Something went wrong with axis scaling","long"),t._gd._replotting=!1,new Error("axis scaling")},t.l2p=function(e){return i(e)?n.round(t._b+t._m*e,2):o.BADNUM},t.p2l=function(e){return(e-t._b)/t._m},t.c2p=function(e,r){return t.l2p(t.c2l(e,r))},t.p2c=function(e){return t.l2c(t.p2l(e))},-1!==["linear","log","-"].indexOf(t.type))t.c2d=c,t.d2c=function(t){return t=s(t),i(t)?Number(t):o.BADNUM},t.d2l=function(e,r){return"log"===t.type?t.c2l(t.d2c(e),r):t.d2c(e)};else if("date"===t.type){if(t.c2d=function(t){return i(t)?a.ms2DateTime(t):o.BADNUM},t.d2c=function(t){return i(t)?Number(t):a.dateTime2ms(t)},t.d2l=t.d2c,t.range&&t.range.length>1)try{var f=t.range.map(a.dateTime2ms);!i(t.range[0])&&i(f[0])&&(t.range[0]=f[0]),!i(t.range[1])&&i(f[1])&&(t.range[1]=f[1])}catch(h){console.log(h,t.range)}}else"category"===t.type&&(t.c2d=function(e){return t._categories[Math.round(e)]},t.d2c=function(e){null!==e&&void 0!==e&&-1===t._categories.indexOf(e)&&t._categories.push(e);var r=t._categories.indexOf(e);return-1===r?o.BADNUM:r},t.d2l=t.d2c);t.makeCalcdata=function(e,r){var n,i,a;if(r in e)for(n=e[r],i=new Array(n.length),a=0;an?"0":"1.0"}var r=this.framework,n=r.select("g.choroplethlayer"),i=r.select("g.scattergeolayer"),a=this.projection,o=this.path,s=this.clipAngle;r.selectAll("path.basepath").attr("d",o),r.selectAll("path.graticulepath").attr("d",o),n.selectAll("path.choroplethlocation").attr("d",o),n.selectAll("path.basepath").attr("d",o),i.selectAll("path.js-line").attr("d",o),null!==s?(i.selectAll("path.point").style("opacity",e).attr("transform",t),i.selectAll("text").style("opacity",e).attr("transform",t)):(i.selectAll("path.point").attr("transform",t),i.selectAll("text").attr("transform",t))}},{"../../components/color":303,"../../components/drawing":325,"../../constants/xmlns_namespaces":369,"../../lib/filter_visible":377,"../../lib/topojson_utils":394,"../../plots/cartesian/axes":403,"./constants":422,"./projections":430,"./set_scale":431,"./zoom":432,"./zoom_reset":433,d3:113,topojson:275}],424:[function(t,e,r){"use strict";var n=t("./geo"),i=t("../../plots/plots");r.name="geo",r.attr="geo",r.idRoot="geo",r.idRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"geo");void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var o=0;o=n}function a(t,e){for(var r=e[0],n=e[1],i=!1,a=0,o=t.length,s=o-1;o>a;s=a++){var l=t[a],c=l[0],u=l[1],f=t[s],h=f[0],d=f[1];u>n^d>n&&(h-c)*(n-u)/(d-u)+c>r&&(i=!i)}return i}function o(t){return t?t/Math.sin(t):1}function s(t){return t>1?P:-1>t?-P:Math.asin(t)}function l(t){return t>1?0:-1>t?z:Math.acos(t)}function c(t,e){var r=(2+P)*Math.sin(e);e/=2;for(var n=0,i=1/0;10>n&&Math.abs(i)>S;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(z*(4+z))*t*(1+Math.cos(e)),2*Math.sqrt(z/(4+z))*Math.sin(e)]}function u(t,e){function r(r,n){var i=j(r/e,n);return i[0]*=t,i}return arguments.length<2&&(e=t),1===e?j:e===1/0?h:(r.invert=function(r,n){var i=j.invert(r/t,n);return i[0]*=e,i},r)}function f(){var t=2,e=N(u),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}function h(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function d(t,e){return[3*t/(2*z)*Math.sqrt(z*z/3-e*e),e]}function p(t,e){return[t,1.25*Math.log(Math.tan(z/4+.4*e))]}function g(t){return function(e){var r,n=t*Math.sin(e),i=30;do e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e));while(Math.abs(r)>S&&--i>0);return e/2}}function v(t,e,r){function n(r,n){return[t*r*Math.cos(n=i(n)),e*Math.sin(n)]}var i=g(r);return n.invert=function(n,i){var a=s(i/e);return[n/(t*Math.cos(a)),s((2*a+Math.sin(2*a))/r)]},n}function m(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(-.013791+n*(.003971*r-.001529*n))),e*(1.007226+r*(.015085+n*(-.044475+.028874*r-.005916*n)))]}function y(t,e){var r,n=Math.min(18,36*Math.abs(e)/z),i=Math.floor(n),a=n-i,o=(r=D[i])[0],s=r[1],l=(r=D[++i])[0],c=r[1],u=(r=D[Math.min(19,++i)])[0],f=r[1];return[t*(l+a*(u-o)/2+a*a*(u-2*l+o)/2),(e>0?P:-P)*(c+a*(f-s)/2+a*a*(f-2*c+s)/2)]}function b(t,e){return[t*Math.cos(e),e]}function x(t,e){var r=Math.cos(e),n=o(l(r*Math.cos(t/=2)));return[2*r*Math.sin(t)*n,Math.sin(e)*n]}function _(t,e){var r=x(t,e);return[(r[0]+t/P)/2,(r[1]+e)/2]}t.geo.project=function(t,e){var n=e.stream;if(!n)throw new Error("not yet supported");return(t&&w.hasOwnProperty(t.type)?w[t.type]:r)(t,n)};var w={Feature:e,FeatureCollection:function(t,r){return{type:"FeatureCollection",features:t.features.map(function(t){return e(t,r)})}}},k=[],A=[],M={point:function(t,e){k.push([t,e])},result:function(){var t=k.length?k.length<2?{type:"Point",coordinates:k[0]}:{type:"MultiPoint",coordinates:k}:null;return k=[],t}},T={lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){k.length&&(A.push(k),k=[])},result:function(){var t=A.length?A.length<2?{type:"LineString",coordinates:A[0]}:{type:"MultiLineString",coordinates:A}:null;return A=[],t}},E={polygonStart:n,lineStart:n,point:function(t,e){k.push([t,e])},lineEnd:function(){var t=k.length;if(t){do k.push(k[0].slice());while(++t<4);A.push(k),k=[]}},polygonEnd:n,result:function(){if(!A.length)return null;var t=[],e=[];return A.forEach(function(r){i(r)?t.push([r]):e.push(r)}),e.forEach(function(e){var r=e[0];t.some(function(t){return a(t[0],r)?(t.push(e),!0):void 0})||t.push([e])}),A=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},L={Point:M,MultiPoint:M,LineString:T,MultiLineString:T,Polygon:E,MultiPolygon:E,Sphere:E},S=1e-6,C=S*S,z=Math.PI,P=z/2,R=(Math.sqrt(z),z/180),O=180/z,I=t.geo.projection,N=t.geo.projectionMutator;t.geo.interrupt=function(e){function r(t,r){for(var n=0>r?-1:1,i=l[+(0>r)],a=0,o=i.length-1;o>a&&t>i[a][2][0];++a);var s=e(t-i[a][1][0],r);return s[0]+=e(i[a][1][0],n*r>n*i[a][0][1]?i[a][0][1]:r)[0],s}function n(){s=l.map(function(t){return t.map(function(t){var r,n=e(t[0][0],t[0][1])[0],i=e(t[2][0],t[2][1])[0],a=e(t[1][0],t[0][1])[1],o=e(t[1][0],t[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})})}function i(){for(var e=1e-6,r=[],n=0,i=l[0].length;i>n;++n){var o=l[0][n],s=180*o[0][0]/z,c=180*o[0][1]/z,u=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[s+e,c+e],[s+e,u-e],[f-e,u-e],[f-e,h+e]],30))}for(var n=l[1].length-1;n>=0;--n){var o=l[1][n],s=180*o[0][0]/z,c=180*o[0][1]/z,u=180*o[1][1]/z,f=180*o[2][0]/z,h=180*o[2][1]/z;r.push(a([[f-e,h-e],[f-e,u+e],[s+e,u+e],[s+e,c-e]],30))}return{type:"Polygon",coordinates:[t.merge(r)]}}function a(t,e){for(var r,n,i,a=-1,o=t.length,s=t[0],l=[];++ac;++c)l.push([s[0]+c*n,s[1]+c*i]);s=r}return l.push(r),l}function o(t,e){return Math.abs(t[0]-e[0])n)],a=l[+(0>n)],c=0,u=i.length;u>c;++c){var f=i[c];if(f[0][0]<=t&&tS&&--i>0);return[t/(.8707+(a=n*n)*(-.131979+a*(-.013791+a*a*a*(.003971-.001529*a)))),n]},(t.geo.naturalEarth=function(){return I(m)}).raw=m;var D=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];D.forEach(function(t){t[1]*=1.0144}),y.invert=function(t,e){var r=e/P,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],c=l-o,u=l-2*s+o,f=2*(Math.abs(r)-s)/c,h=u/c,d=f*(1-h*f*(1-2*h*f));if(d>=0||1===a){n=(e>=0?5:-5)*(d+i);var p,g=50;do i=Math.min(18,Math.abs(n)/5),a=Math.floor(i),d=i-a,o=D[a][1],s=D[a+1][1],l=D[Math.min(19,a+2)][1],n-=(p=(e>=0?P:-P)*(s+d*(l-o)/2+d*d*(l-2*s+o)/2)-e)*O;while(Math.abs(p)>C&&--g>0); +break}}while(--a>=0);var v=D[a][0],m=D[a+1][0],y=D[Math.min(19,a+2)][0];return[t/(m+d*(y-v)/2+d*d*(y-2*m+v)/2),n*R]},(t.geo.robinson=function(){return I(y)}).raw=y,b.invert=function(t,e){return[t/Math.cos(e),e]},(t.geo.sinusoidal=function(){return I(b)}).raw=b,x.invert=function(t,e){if(!(t*t+4*e*e>z*z+S)){var r=t,n=e,i=25;do{var a,o=Math.sin(r),s=Math.sin(r/2),c=Math.cos(r/2),u=Math.sin(n),f=Math.cos(n),h=Math.sin(2*n),d=u*u,p=f*f,g=s*s,v=1-p*c*c,m=v?l(f*c)*Math.sqrt(a=1/v):a=0,y=2*m*f*s-t,b=m*u-e,x=a*(p*g+m*f*c*d),_=a*(.5*o*h-2*m*u*s),w=.25*a*(h*s-m*u*p*o),k=a*(d*c+m*g*f),A=_*w-k*x;if(!A)break;var M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]}},(t.geo.aitoff=function(){return I(x)}).raw=x,_.invert=function(t,e){var r=t,n=e,i=25;do{var a,o=Math.cos(n),s=Math.sin(n),c=Math.sin(2*n),u=s*s,f=o*o,h=Math.sin(r),d=Math.cos(r/2),p=Math.sin(r/2),g=p*p,v=1-f*d*d,m=v?l(o*d)*Math.sqrt(a=1/v):a=0,y=.5*(2*m*o*p+r/P)-t,b=.5*(m*s+n)-e,x=.5*a*(f*g+m*o*d*u)+.5/P,_=a*(h*c/4-m*s*p),w=.125*a*(c*p-m*s*f*h),k=.5*a*(u*d+m*g*o)+.5,A=_*w-k*x,M=(b*_-y*k)/A,T=(y*w-b*x)/A;r-=M,n-=T}while((Math.abs(M)>S||Math.abs(T)>S)&&--i>0);return[r,n]},(t.geo.winkel3=function(){return I(_)}).raw=_}e.exports=n},{}],431:[function(t,e,r){"use strict";function n(t,e){var r=t.projection,n=t.lonaxis,o=t.lataxis,l=t.domain,c=t.framewidth||0,u=e.w*(l.x[1]-l.x[0]),f=e.h*(l.y[1]-l.y[0]),h=n.range[0]+s,d=n.range[1]-s,p=o.range[0]+s,g=o.range[1]-s,v=n._fullRange[0]+s,m=n._fullRange[1]-s,y=o._fullRange[0]+s,b=o._fullRange[1]-s;r._translate0=[e.l+u/2,e.t+f/2];var x=d-h,_=g-p,w=[h+x/2,p+_/2],k=r._rotate;r._center=[w[0]+k[0],w[1]+k[1]];var A=function(e){function n(t){return Math.min(_*u/(t[1][0]-t[0][0]),_*f/(t[1][1]-t[0][1]))}var o,s,l,x,_=e.scale(),w=r._translate0,k=i(h,p,d,g),A=i(v,y,m,b);l=a(e,k),o=n(l),x=a(e,A),r._fullScale=n(x),e.scale(o),l=a(e,k),s=[w[0]-l[0][0]+c,w[1]-l[0][1]+c],r._translate=s,e.translate(s),l=a(e,k),t._isAlbersUsa||e.clipExtent(l),o=r.scale*o,r._scale=o,t._width=Math.round(l[1][0])+c,t._height=Math.round(l[1][1])+c,t._marginX=(u-Math.round(l[1][0]))/2,t._marginY=(f-Math.round(l[1][1]))/2};return A}function i(t,e,r,n){var i=(r-t)/4;return{type:"Polygon",coordinates:[[[t,e],[t,n],[t+i,n],[t+2*i,n],[t+3*i,n],[r,n],[r,e],[r-i,e],[r-2*i,e],[r-3*i,e],[t,e]]]}}function a(t,e){return o.geo.path().projection(t).bounds(e)}var o=t("d3"),s=t("./constants/").clipPad;e.exports=n},{"./constants/":422,d3:113}],432:[function(t,e,r){"use strict";function n(t,e){var r;return(r=e._isScoped?a:e._clipAngle?s:o)(t,e.projection)}function i(t,e){var r=e._fullScale;return _.behavior.zoom().translate(t.translate()).scale(t.scale()).scaleExtent([.5*r,100*r])}function a(t,e){function r(){_.select(this).style(A)}function n(){o.scale(_.event.scale).translate(_.event.translate),t.render()}function a(){_.select(this).style(M)}var o=t.projection,s=i(o,e);return s.on("zoomstart",r).on("zoom",n).on("zoomend",a),s}function o(t,e){function r(t){return v.invert(t)}function n(t){var e=v(r(t));return Math.abs(e[0]-t[0])>y||Math.abs(e[1]-t[1])>y}function a(){_.select(this).style(A),l=_.mouse(this),c=v.rotate(),u=v.translate(),f=c,h=r(l)}function o(){return d=_.mouse(this),n(l)?(m.scale(v.scale()),void m.translate(v.translate())):(v.scale(_.event.scale),v.translate([u[0],_.event.translate[1]]),h?r(d)&&(g=r(d),p=[f[0]+(g[0]-h[0]),c[1],c[2]],v.rotate(p),f=p):(l=d,h=r(l)),void t.render())}function s(){_.select(this).style(M)}var l,c,u,f,h,d,p,g,v=t.projection,m=i(v,e),y=2;return m.on("zoomstart",a).on("zoom",o).on("zoomend",s),m}function s(t,e){function r(t){m++||t({type:"zoomstart"})}function n(t){t({type:"zoom"})}function a(t){--m||t({type:"zoomend"})}var o,s=t.projection,d={r:s.rotate(),k:s.scale()},p=i(s,e),g=x(p,"zoomstart","zoom","zoomend"),m=0,y=p.on;return p.on("zoomstart",function(){_.select(this).style(A);var t=_.mouse(this),e=s.rotate(),i=e,a=s.translate(),m=c(e);o=l(s,t),y.call(p,"zoom",function(){var r=_.mouse(this);if(s.scale(d.k=_.event.scale),o){if(l(s,r)){s.rotate(e).translate(a);var c=l(s,r),p=f(o,c),y=v(u(m,p)),b=d.r=h(y,o,i);isFinite(b[0])&&isFinite(b[1])&&isFinite(b[2])||(b=i),s.rotate(b),i=b}}else t=r,o=l(s,t);n(g.of(this,arguments))}),r(g.of(this,arguments))}).on("zoomend",function(){_.select(this).style(M),y.call(p,"zoom",null),a(g.of(this,arguments))}).on("zoom.redraw",function(){t.render()}),_.rebind(p,g,"on")}function l(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&m(r)}function c(t){var e=.5*t[0]*w,r=.5*t[1]*w,n=.5*t[2]*w,i=Math.sin(e),a=Math.cos(e),o=Math.sin(r),s=Math.cos(r),l=Math.sin(n),c=Math.cos(n);return[a*s*c+i*o*l,i*s*c-a*o*l,a*o*c+i*s*l,a*s*l-i*o*c]}function u(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],l=e[2],c=e[3];return[r*o-n*s-i*l-a*c,r*s+n*o+i*c-a*l,r*l-n*c+i*o+a*s,r*c+n*l-i*s+a*o]}function f(t,e){if(t&&e){var r=b(t,e),n=Math.sqrt(y(r,r)),i=.5*Math.acos(Math.max(-1,Math.min(1,y(t,e)))),a=Math.sin(i)/n;return n&&[Math.cos(i),r[2]*a,-r[1]*a,r[0]*a]}}function h(t,e,r){var n=g(e,2,t[0]);n=g(n,1,t[1]),n=g(n,0,t[2]-r[2]);var i,a,o=e[0],s=e[1],l=e[2],c=n[0],u=n[1],f=n[2],h=Math.atan2(s,o)*k,p=Math.sqrt(o*o+s*s);Math.abs(u)>p?(a=(u>0?90:-90)-h,i=0):(a=Math.asin(u/p)*k-h,i=Math.sqrt(p*p-u*u));var v=180-a-2*h,m=(Math.atan2(f,c)-Math.atan2(l,i))*k,y=(Math.atan2(f,c)-Math.atan2(l,-i))*k,b=d(r[0],r[1],a,m),x=d(r[0],r[1],v,y);return x>=b?[a,m,r[2]]:[v,y,r[2]]}function d(t,e,r,n){var i=p(r-t),a=p(n-e);return Math.sqrt(i*i+a*a)}function p(t){return(t%360+540)%360-180}function g(t,e,r){var n=r*w,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function v(t){return[Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),1-2*(t[1]*t[1]+t[2]*t[2]))*k,Math.asin(Math.max(-1,Math.min(1,2*(t[0]*t[2]-t[3]*t[1]))))*k,Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),1-2*(t[2]*t[2]+t[3]*t[3]))*k]}function m(t){var e=t[0]*w,r=t[1]*w,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function y(t,e){for(var r=0,n=0,i=t.length;i>n;++n)r+=t[n]*e[n];return r}function b(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function x(t){for(var e=0,r=arguments.length,n=[];++ed;++d){for(e=c[d],r=t[this.scene[e]._name],n=/Click to enter .+ title/.test(r.title)?"":r.title,p=0;2>=p;p+=2)this.labelEnable[d+p]=!1,this.labels[d+p]=o(n),this.labelColor[d+p]=s(r.titlefont.color),this.labelFont[d+p]=r.titlefont.family,this.labelSize[d+p]=r.titlefont.size,this.labelPad[d+p]=this.getLabelPad(e,r),this.tickEnable[d+p]=!1,this.tickColor[d+p]=s((r.tickfont||{}).color),this.tickAngle[d+p]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[d+p]=this.getTickPad(r),this.tickMarkLength[d+p]=0,this.tickMarkWidth[d+p]=r.tickwidth||0,this.tickMarkColor[d+p]=s(r.tickcolor),this.borderLineEnable[d+p]=!1,this.borderLineColor[d+p]=s(r.linecolor),this.borderLineWidth[d+p]=r.linewidth||0;u=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!u,l=this.hasAxisInAltrPos(e,r)&&!u,i=r.mirror||!1,f=u?-1!==String(i).indexOf("all"):!!i,h=u?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[d]=!0:l&&(this.labelEnable[d+2]=!0),a?this.tickEnable[d]=r.showticklabels:l&&(this.tickEnable[d+2]=r.showticklabels),(a||f)&&(this.borderLineEnable[d]=r.showline),(l||f)&&(this.borderLineEnable[d+2]=r.showline),(a||h)&&(this.tickMarkLength[d]=this.getTickMarkLength(r)),(l||h)&&(this.tickMarkLength[d+2]=this.getTickMarkLength(r)),this.gridLineEnable[d]=r.showgrid,this.gridLineColor[d]=s(r.gridcolor),this.gridLineWidth[d]=r.gridwidth,this.zeroLineEnable[d]=r.zeroline,this.zeroLineColor[d]=s(r.zerolinecolor),this.zeroLineWidth[d]=r.zerolinewidth}},l.hasSharedAxis=function(t){var e=this.scene,r=a.Plots.getSubplotIds(e.fullLayout,"gl2d"),n=a.Axes.findSubplotsWithAxis(r,t);return 0!==n.indexOf(e.id)},l.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},l.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},l.getLabelPad=function(t,e){var r=1.5,n=e.titlefont.size,i=e.showticklabels;return"xaxis"===t?"top"===e.side?-10+n*(r+(i?1:0)):-10+n*(r+(i?.5:0)):"yaxis"===t?"right"===e.side?10+n*(r+(i?1:.5)):10+n*(r+(i?.5:0)):void 0},l.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},l.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e},e.exports=i},{"../../lib/html2unicode":380,"../../lib/str2rgbarray":392,"../../plotly":400}],436:[function(t,e,r){"use strict";var n=t("./scene2d"),i=t("../plots"),a=t("../../constants/xmlns_namespaces");r.name="gl2d",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex={x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},r.attrRegex={x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},r.attributes=t("../cartesian/attributes"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"gl2d"),o=0;or;++r){var n=t[r],i=e[r];if(n.length!==i.length)return!0;for(var a=0;ao;++o,--s)for(var l=0;r>l;++l)for(var c=0;4>c;++c){var u=i[4*(r*o+l)+c];i[4*(r*o+l)+c]=i[4*(r*s+l)+c],i[4*(r*s+l)+c]=u}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),d=h.createImageData(r,n);d.data.set(i),h.putImageData(d,0,0);var p;switch(t){case"jpeg":p=f.toDataURL("image/jpeg");break;case"webp":p=f.toDataURL("image/webp");break;default:p=f.toDataURL("image/png")}return this.staticPlot&&this.container.removeChild(a),p},m.computeTickMarks=function(){this.xaxis._length=this.glplot.viewBox[2]-this.glplot.viewBox[0],this.yaxis._length=this.glplot.viewBox[3]-this.glplot.viewBox[1];for(var t=[s.calcTicks(this.xaxis),s.calcTicks(this.yaxis)],e=0;2>e;++e)for(var r=0;rk;++k)w[k]=Math.min(w[k],a.bounds[k]),w[k+2]=Math.max(w[k+2],a.bounds[k+2])}var A;for(n=0;2>n;++n)w[n]>w[n+2]&&(w[n]=-1,w[n+2]=1),A=this[v[n]],A._length=y.viewBox[n+2]-y.viewBox[n],s.doAutoRange(A);y.ticks=this.computeTickMarks();var M=this.xaxis.range,T=this.yaxis.range;y.dataBox=[M[0],T[0],M[1],T[1]],y.merge(r),o.update(y),this.glplot.draw()},m.draw=function(){if(!this.stopped){requestAnimationFrame(this.redraw);var t=this.glplot,e=this.camera,r=e.mouseListener,n=this.fullLayout;this.cameraChanged();var i=r.x*t.pixelRatio,a=this.canvas.height-t.pixelRatio*r.y;if(e.boxEnabled&&"zoom"===n.dragmode)this.selectBox.enabled=!0,this.selectBox.selectBox=[Math.min(e.boxStart[0],e.boxEnd[0]),Math.min(e.boxStart[1],e.boxEnd[1]),Math.max(e.boxStart[0],e.boxEnd[0]),Math.max(e.boxStart[1],e.boxEnd[1])],t.setDirty();else{this.selectBox.enabled=!1;var o=n._size,s=this.xaxis.domain,c=this.yaxis.domain,u=t.pick(i/t.pixelRatio+o.l+s[0]*o.w,a/t.pixelRatio-(o.t+(1-c[1])*o.h));if(u&&n.hovermode){var f=u.object._trace.handlePick(u);if(f&&(!this.lastPickResult||this.lastPickResult.trace!==f.trace||this.lastPickResult.dataCoord[0]!==f.dataCoord[0]||this.lastPickResult.dataCoord[1]!==f.dataCoord[1])){var h=this.lastPickResult=f;this.spikes.update({center:u.dataCoord}),h.screenCoord=[((t.viewBox[2]-t.viewBox[0])*(u.dataCoord[0]-t.dataBox[0])/(t.dataBox[2]-t.dataBox[0])+t.viewBox[0])/t.pixelRatio,(this.canvas.height-(t.viewBox[3]-t.viewBox[1])*(u.dataCoord[1]-t.dataBox[1])/(t.dataBox[3]-t.dataBox[1])-t.viewBox[1])/t.pixelRatio];var d=h.hoverinfo;if("all"!==d){var p=d.split("+");-1===p.indexOf("x")&&(h.traceCoord[0]=void 0),-1===p.indexOf("y")&&(h.traceCoord[1]=void 0),-1===p.indexOf("z")&&(h.traceCoord[2]=void 0),-1===p.indexOf("text")&&(h.textLabel=void 0),-1===p.indexOf("name")&&(h.name=void 0)}l.loneHover({x:h.screenCoord[0],y:h.screenCoord[1],xLabel:this.hoverFormatter("xaxis",h.traceCoord[0]),yLabel:this.hoverFormatter("yaxis",h.traceCoord[1]),zLabel:h.traceCoord[2],text:h.textLabel,name:h.name,color:h.color},{container:this.svgContainer}),this.lastPickResult={dataCoord:u.dataCoord}}}else!u&&this.lastPickResult&&(this.spikes.update({}),this.lastPickResult=null,l.loneUnhover(this.svgContainer))}t.draw()}},m.hoverFormatter=function(t,e){if(void 0!==e){var r=this[t];return s.tickText(r,r.c2l(e),"hover").text}}},{"../../lib/html2unicode":380,"../../lib/show_no_webgl_msg":390,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"./camera":434,"./convert":435,"gl-plot2d":165,"gl-select-box":195,"gl-spikes2d":215}],438:[function(t,e,r){"use strict";function n(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]),"zoomMin"in e&&(r[0]=e.zoomMin),"zoomMax"in e&&(r[1]=e.zoomMax);var n=a({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],c=0,u=t.clientWidth,f=t.clientHeight,h={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=i(),r=this.delay,a=e-2*r;n.idle(e-r),n.recalcMatrix(a),n.flush(e-(100+2*r));for(var o=!0,s=n.computedMatrix,h=0;16>h;++h)o=o&&l[h]===s[h],l[h]=s[h];var d=t.clientWidth===u&&t.clientHeight===f;return u=t.clientWidth,f=t.clientHeight,o?!d:(c=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(h,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),a=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var o=i();n._active.lookAt(o,r,a,e),n._active.lookAt(o+500,r,a,[0,0,1]),n._active.flush(o)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return c},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var d=0,p=0;return o(t,function(e,r,a,o){var s="rotate"===h.keyBindingMode,l="pan"===h.keyBindingMode,u="zoom"===h.keyBindingMode,f=!!o.control,g=!!o.alt,v=!!o.shift,m=!!(1&e),y=!!(2&e),b=!!(4&e),x=1/t.clientHeight,_=x*(r-d),w=x*(a-p),k=h.flipX?1:-1,A=h.flipY?1:-1,M=i(),T=Math.PI*h.rotateSpeed;if((s&&m&&!f&&!g&&!v||m&&!f&&!g&&v)&&n.rotate(M,k*T*_,-A*T*w,0),(l&&m&&!f&&!g&&!v||y||m&&f&&!g&&!v)&&n.pan(M,-h.translateSpeed*_*c,h.translateSpeed*w*c,0),u&&m&&!f&&!g&&!v||b||m&&!f&&g&&!v){var E=-h.zoomSpeed*w/window.innerHeight*(M-n.lastT())*100;n.pan(M,0,0,c*(Math.exp(E)-1))}return d=r,p=a,!0}),s(t,function(t,e){var r=h.flipX?1:-1,a=h.flipY?1:-1,o=i();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*h.rotateSpeed/window.innerWidth);else{var s=-h.zoomSpeed*a*e/window.innerHeight*(o-n.lastT())/100;n.pan(o,0,0,c*(Math.exp(s)-1))}},!0),h}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":39,"mouse-change":241,"mouse-wheel":245,"right-now":255}],439:[function(t,e,r){"use strict";function n(t,e){for(var r=0;3>r;++r){var n=s[r];e[n]._gd=t}}var i=t("./scene"),a=t("../plots"),o=t("../../constants/xmlns_namespaces"),s=["xaxis","yaxis","zaxis"];r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,o=a.getSubplotIds(e,"gl3d");e._paperdiv.style({width:e.width+"px",height:e.height+"px"}),t._context.setBackground(t,e.paper_bgcolor);for(var s=0;sr;++r){var n=t[c[r]];e.labels[r]=o(n.title),"titlefont"in n&&(n.titlefont.color&&(e.labelColor[r]=s(n.titlefont.color)),n.titlefont.family&&(e.labelFont[r]=n.titlefont.family),n.titlefont.size&&(e.labelSize[r]=n.titlefont.size)),"showline"in n&&(e.lineEnable[r]=n.showline),"linecolor"in n&&(e.lineColor[r]=s(n.linecolor)),"linewidth"in n&&(e.lineWidth[r]=n.linewidth),"showgrid"in n&&(e.gridEnable[r]=n.showgrid),"gridcolor"in n&&(e.gridColor[r]=s(n.gridcolor)),"gridwidth"in n&&(e.gridWidth[r]=n.gridwidth),"log"===n.type?e.zeroEnable[r]=!1:"zeroline"in n&&(e.zeroEnable[r]=n.zeroline),"zerolinecolor"in n&&(e.zeroLineColor[r]=s(n.zerolinecolor)),"zerolinewidth"in n&&(e.zeroLineWidth[r]=n.zerolinewidth),"ticks"in n&&n.ticks?e.lineTickEnable[r]=!0:e.lineTickEnable[r]=!1,"ticklen"in n&&(e.lineTickLength[r]=e._defaultLineTickLength[r]=n.ticklen),"tickcolor"in n&&(e.lineTickColor[r]=s(n.tickcolor)),"tickwidth"in n&&(e.lineTickWidth[r]=n.tickwidth),"tickangle"in n&&(e.tickAngle[r]="auto"===n.tickangle?0:Math.PI*-n.tickangle/180),"showticklabels"in n&&(e.tickEnable[r]=n.showticklabels),"tickfont"in n&&(n.tickfont.color&&(e.tickColor[r]=s(n.tickfont.color)),n.tickfont.family&&(e.tickFont[r]=n.tickfont.family),n.tickfont.size&&(e.tickSize[r]=n.tickfont.size)),"mirror"in n?-1!==["ticks","all","allticks"].indexOf(n.mirror)?(e.lineTickMirror[r]=!0,e.lineMirror[r]=!0):n.mirror===!0?(e.lineTickMirror[r]=!1,e.lineMirror[r]=!0):(e.lineTickMirror[r]=!1,e.lineMirror[r]=!1):e.lineMirror[r]=!1,"showbackground"in n&&n.showbackground!==!1?(e.backgroundEnable[r]=!0, +e.backgroundColor[r]=s(n.backgroundcolor)):e.backgroundEnable[r]=!1}},e.exports=i},{"../../../lib/html2unicode":380,"../../../lib/str2rgbarray":392,arraytools:49}],444:[function(t,e,r){"use strict";function n(t,e,r,n){for(var a=r("bgcolor"),l=i.combine(a,n.paper_bgcolor),c=Object.keys(o.camera),u=0;ue;++e){var r=t[o[e]];this.enabled[e]=r.showspikes,this.colors[e]=a(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness}},e.exports=i},{"../../../lib/str2rgbarray":392}],447:[function(t,e,r){"use strict";function n(t){for(var e=new Array(3),r=0;3>r;++r){for(var n=t[r],i=new Array(n.length),a=0;au;++u){var f=i[s[u]];if(f._length=(r[u].hi-r[u].lo)*r[u].pixelsPerDataUnit/t.dataScale[u],Math.abs(f._length)===1/0)c[u]=[];else{f.range[0]=r[u].lo/t.dataScale[u],f.range[1]=r[u].hi/t.dataScale[u],f._m=1/(t.dataScale[u]*r[u].pixelsPerDataUnit),f.range[0]===f.range[1]&&(f.range[0]-=1,f.range[1]+=1);var h=f.tickmode;if("auto"===f.tickmode){f.tickmode="linear";var d=f.nticks||a.Lib.constrain(f._length/40,4,9);a.Axes.autoTicks(f,Math.abs(f.range[1]-f.range[0])/d)}for(var p=a.Axes.calcTicks(f),g=0;gu;++u){l[u]=.5*(t.glplot.bounds[0][u]+t.glplot.bounds[1][u]);for(var g=0;2>g;++g)e.bounds[g][u]=t.glplot.bounds[g][u]}t.contourLevels=n(c)}e.exports=i;var a=t("../../../plotly"),o=t("../../../lib/html2unicode"),s=["xaxis","yaxis","zaxis"],l=[0,0,0]},{"../../../lib/html2unicode":380,"../../../plotly":400}],448:[function(t,e,r){"use strict";function n(t,e){var r,n,i=[0,0,0,0];for(r=0;4>r;++r)for(n=0;4>n;++n)i[n]+=t[4*r+n]*e[r];return i}function i(t,e){var r=n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])));return r}e.exports=i},{}],449:[function(t,e,r){"use strict";function n(t){function e(e,r){if("string"==typeof r)return r;var n=t.fullSceneLayout[e];return g.tickText(n,n.c2l(r),"hover").text}var r,n=t.svgContainer,i=t.container.getBoundingClientRect(),a=i.width,o=i.height;n.setAttributeNS(null,"viewBox","0 0 "+a+" "+o),n.setAttributeNS(null,"width",a),n.setAttributeNS(null,"height",o),A(t),t.glplot.axes.update(t.axesOptions);for(var s=Object.keys(t.traces),l=null,c=t.glplot.selection,u=0;ua;++a)l=u[T[a]],_(l);t?Array.isArray(t)||(t=[t]):t=[];var h=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]];for(a=0;ao;++o)h[0][o]>h[1][o]?d[o]=1:h[1][o]===h[0][o]?d[o]=1:d[o]=1/(h[1][o]-h[0][o]);for(this.dataScale=d,a=0;aa;++a){if(l=u[T[a]],c=l.type,c in x?(x[c].acc*=d[a],x[c].count+=1):x[c]={acc:d[a],count:1},l.autorange){for(y[0][a]=1/0,y[1][a]=-(1/0),o=0;oy[1][a])y[0][a]=-1,y[1][a]=1;else{var k=y[1][a]-y[0][a];y[0][a]-=k/32,y[1][a]+=k/32}}else{var A=u[T[a]].range;y[0][a]=A[0],y[1][a]=A[1]}y[0][a]===y[1][a]&&(y[0][a]-=1,y[1][a]+=1),b[a]=y[1][a]-y[0][a],this.glplot.bounds[0][a]=y[0][a]*d[a],this.glplot.bounds[1][a]=y[1][a]*d[a]}var M=[1,1,1];for(a=0;3>a;++a){l=u[T[a]],c=l.type;var E=x[c];M[a]=Math.pow(E.acc,1/E.count)/d[a]}var L,S=4;if("auto"===u.aspectmode)L=Math.max.apply(null,M)/Math.min.apply(null,M)<=S?M:[1,1,1];else if("cube"===u.aspectmode)L=[1,1,1];else if("data"===u.aspectmode)L=M;else{if("manual"!==u.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var C=u.aspectratio;L=[C.x,C.y,C.z]}u.aspectratio.x=f.aspectratio.x=L[0],u.aspectratio.y=f.aspectratio.y=L[1],u.aspectratio.z=f.aspectratio.z=L[2],this.glplot.aspect=L;var z=u.domain||null,P=e._size||null;if(z&&P){var R=this.container.style;R.position="absolute",R.left=P.l+z.x[0]*P.w+"px",R.top=P.t+(1-z.y[1])*P.h+"px",R.width=P.w*(z.x[1]-z.x[0])+"px",R.height=P.h*(z.y[1]-z.y[0])+"px"}this.glplot.redraw()}},M.destroy=function(){this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null},M.setCameraToDefault=function(){this.setCamera({eye:{x:1.25,y:1.25,z:1.25},center:{x:0,y:0,z:0},up:{x:0,y:0,z:1}})},M.getCamera=function(){return this.glplot.camera.view.recalcMatrix(this.camera.view.lastT()),c(this.glplot.camera)},M.setCamera=function(t){var e={};e[this.id]=t,this.glplot.camera.lookAt.apply(this,l(t)),this.graphDiv.emit("plotly_relayout",e)},M.saveCamera=function(t){function e(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return e[i[r]]&&t[i[r]][a[n]]===e[i[r]][a[n]]}var r=this.getCamera(),n=d.nestedProperty(t,this.id+".camera"),i=n.get(),a=!1;if(void 0===i)a=!0;else for(var o=0;3>o;o++)for(var s=0;3>s;s++)if(!e(r,i,o,s)){a=!0;break}return a&&n.set(r),a},M.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},M.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(u),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;o>a;++a,--o)for(var s=0;r>s;++s)for(var l=0;4>l;++l){var c=i[4*(r*a+s)+l];i[4*(r*a+s)+l]=i[4*(r*o+s)+l],i[4*(r*o+s)+l]=c}var f=document.createElement("canvas");f.width=r,f.height=n;var h=f.getContext("2d"),d=h.createImageData(r,n);d.data.set(i),h.putImageData(d,0,0);var p;switch(t){case"jpeg":p=f.toDataURL("image/jpeg");break;case"webp":p=f.toDataURL("image/webp");break;default:p=f.toDataURL("image/png")}return this.staticMode&&this.container.removeChild(u),p},e.exports=a},{"../../lib":381,"../../lib/show_no_webgl_msg":390,"../../lib/str2rgbarray":392,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"../../plots/plots":452,"./camera":438,"./layout/convert":443,"./layout/spikes":446,"./layout/tick_marks":447,"./project":448,"./set_convert":450,"gl-plot3d":183}],450:[function(t,e,r){"use strict";var n=t("../cartesian/axes"),i=function(){};e.exports=function(t){n.setConvert(t),t.setScale=i}},{"../cartesian/axes":403}],451:[function(t,e,r){"use strict";var n=t("../plotly"),i=t("./font_attributes"),a=t("../components/color/attributes"),o=n.Lib.extendFlat;e.exports={font:{family:o({},i.family,{dflt:'"Open Sans", verdana, arial, sans-serif'}),size:o({},i.size,{dflt:12}),color:o({},i.color,{dflt:a.defaultLine})},title:{valType:"string",dflt:"Click to enter Plot title"},titlefont:o({},i,{}),autosize:{valType:"enumerated",values:[!0,!1,"initial"]},width:{valType:"number",min:10,dflt:700},height:{valType:"number",min:10,dflt:450},margin:{l:{valType:"number",min:0,dflt:80},r:{valType:"number",min:0,dflt:80},t:{valType:"number",min:0,dflt:100},b:{valType:"number",min:0,dflt:80},pad:{valType:"number",min:0,dflt:0},autoexpand:{valType:"boolean",dflt:!0}},paper_bgcolor:{valType:"color",dflt:a.background},plot_bgcolor:{valType:"color",dflt:a.background},separators:{valType:"string",dflt:".,"},hidesources:{valType:"boolean",dflt:!1},smith:{valType:"enumerated",values:[!1],dflt:!1},showlegend:{valType:"boolean"},_composedModules:{"*":"Fx"},_nestedModules:{xaxis:"Axes",yaxis:"Axes",scene:"gl3d",geo:"geo",legend:"Legend",annotations:"Annotations",shapes:"Shapes",images:"Images",ternary:"ternary"}}},{"../components/color/attributes":302,"../plotly":400,"./font_attributes":421}],452:[function(t,e,r){"use strict";function n(t){return"object"==typeof t&&(t=t.type),t}function i(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#","class":"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){f.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}function a(t,e){for(var r,n=Object.keys(e),i=0;i=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var s=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),c=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&i(t,s),l.text(s.text()&&c.text()?" - ":"")},f.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=o.select(t).append("div").attr("id","hiddenform").style("display","none"),n=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"}),i=n.append("input").attr({type:"text",name:"data"});return i.node().value=f.graphJson(t,!1,"keepdata"),n.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1},f.supplyDefaults=function(t){var e,r,n=t._fullLayout||{},i=t._fullLayout={},o=t.layout||{},s=t._fullData||[],u=t._fullData=[],h=t.data||[],d=i._modules=[],p=i._basePlotModules=[];for(f.supplyLayoutGlobalDefaults(o,i),i._dataLength=h.length,e=0;ea&&(e=(r-1)/(i.l+i.r),i.l=Math.floor(e*i.l),i.r=Math.floor(e*i.r)),0>o&&(e=(n-1)/(i.t+i.b),i.t=Math.floor(e*i.t),i.b=Math.floor(e*i.b))}},f.autoMargin=function(t,e,r){var n=t._fullLayout;if(n._pushmargin||(n._pushmargin={}),n.margin.autoexpand!==!1){if(r){var i=void 0===r.pad?12:r.pad;r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];t._replotting||f.doAutoMargin(t)}},f.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),a=Math.max(e.margin.r||0,0),o=Math.max(e.margin.t||0,0),c=Math.max(e.margin.b||0,0),u=e._pushmargin;return e.margin.autoexpand!==!1&&(u.base={l:{val:0,size:i},r:{val:1,size:a},t:{val:1,size:o},b:{val:0,size:c}},Object.keys(u).forEach(function(t){var r=u[t].l||{},n=u[t].b||{},l=r.val,f=r.size,h=n.val,d=n.size;Object.keys(u).forEach(function(t){if(s(f)&&u[t].r){var r=u[t].r.val,n=u[t].r.size;if(r>l){var p=(f*r+(n-e.width)*l)/(r-l),g=(n*(1-l)+(f-e.width)*(1-r))/(r-l);p>=0&&g>=0&&p+g>i+a&&(i=p,a=g)}}if(s(d)&&u[t].t){var v=u[t].t.val,m=u[t].t.size;if(v>h){var y=(d*v+(m-e.height)*h)/(v-h),b=(m*(1-h)+(d-e.height)*(1-v))/(v-h);y>=0&&b>=0&&y+b>c+o&&(c=y,o=b)}}})})),r.l=Math.round(i),r.r=Math.round(a),r.t=Math.round(o),r.b=Math.round(c),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,t._replotting||"{}"===n||n===JSON.stringify(e._size)?void 0:l.plot(t)},f.graphJson=function(t,e,r,n,i){function a(t){if("function"==typeof t)return null;if(c.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0&&!c.isPlainObject(t.stream))continue}else if("keepall"!==r&&(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0))continue;i[e]=a(t[e])}return i}return Array.isArray(t)?t.map(a):t&&t.getTime?c.ms2DateTime(t):t}(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&f.supplyDefaults(t);var o=i?t._fullData:t.data,s=i?t._fullLayout:t.layout,l={data:(o||[]).map(function(t){var r=a(t);return e&&delete r.fit,r})};return e||(l.layout=a(s)),t.framework&&t.framework.isPolar&&(l=t.framework.getConfig()),"object"===n?l:JSON.stringify(l)}},{"../components/color":303,"../lib":381,"../plotly":400,"./attributes":401,"./font_attributes":421,"./layout_attributes":451,d3:113,"fast-isnumeric":117}],453:[function(t,e,r){"use strict";var n=t("../../traces/scatter/attributes"),i=n.marker;e.exports={r:n.r,t:n.t,marker:{color:i.color,size:i.size,symbol:i.symbol,opacity:i.opacity}}},{"../../traces/scatter/attributes":554}],454:[function(t,e,r){"use strict";function n(t,e){var r={showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}};return a({},e,r)}var i=t("../cartesian/layout_attributes"),a=t("../../lib/extend").extendFlat,o=a({},i.domain,{});e.exports={radialaxis:n("radial",{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:n("angular",{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}}},{"../../lib/extend":376,"../cartesian/layout_attributes":412}],455:[function(t,e,r){var n=t("../../plotly"),i=t("d3"),a=e.exports={version:"0.2.2",manager:t("./micropolar_manager")},o=n.Lib.extendDeepAll;a.Axis=function(){function t(t){r=t||r;var c=l.data,f=l.layout;return("string"==typeof r||r.nodeName)&&(r=i.select(r)),r.datum(c).each(function(t,r){function l(t,e){return s(t)%360+f.orientation}var c=t.slice();u={data:a.util.cloneJson(c),layout:a.util.cloneJson(f)};var h=0;c.forEach(function(t,e){t.color||(t.color=f.defaultColorRange[h],h=(h+1)%f.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:i.rgb(t.color).darker().toString()),u.data[e].color=t.color,u.data[e].strokeColor=t.strokeColor,u.data[e].strokeDash=t.strokeDash,u.data[e].strokeSize=t.strokeSize});var d=c.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||r===!0}),p=!1,g=d.map(function(t,e){return p=p||"undefined"!=typeof t.groupId,t});if(p){var v=i.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),m=[],y=v.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],m.push(r),r=a.util.sumArrays(t.r,r)}),t.values});d=i.merge(y)}d.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var b=Math.min(f.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2;b=Math.max(10,b);var x,_=[f.margin.left+b,f.margin.top+b];if(p){var w=i.max(a.util.sumArrays(a.util.arrayLast(d).r[0],a.util.arrayLast(m)));x=[0,w]}else x=i.extent(a.util.flattenArray(d.map(function(t,e){return t.r})));f.radialAxis.domain!=a.DATAEXTENT&&(x[0]=0),n=i.scale.linear().domain(f.radialAxis.domain!=a.DATAEXTENT&&f.radialAxis.domain?f.radialAxis.domain:x).range([0,b]),u.layout.radialAxis.domain=n.domain();var k,A=a.util.flattenArray(d.map(function(t,e){return t.t})),M="string"==typeof A[0];M&&(A=a.util.deduplicate(A),k=A.slice(),A=i.range(A.length),d=d.map(function(t,e){var r=t;return t.t=[A],p&&(r.yStack=t.yStack),r}));var T=d.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===d.length,E=null===f.needsEndSpacing?M||!T:f.needsEndSpacing,L=f.angularAxis.domain&&f.angularAxis.domain!=a.DATAEXTENT&&!M&&f.angularAxis.domain[0]>=0,S=L?f.angularAxis.domain:i.extent(A),C=Math.abs(A[1]-A[0]);T&&!M&&(C=0);var z=S.slice();E&&M&&(z[1]+=C);var P=f.angularAxis.ticksCount||4;P>8&&(P=P/(P/8)+P%8),f.angularAxis.ticksStep&&(P=(z[1]-z[0])/P);var R=f.angularAxis.ticksStep||(z[1]-z[0])/(P*(f.minorTicks+1));k&&(R=Math.max(Math.round(R),1)),z[2]||(z[2]=R);var O=i.range.apply(this,z);if(O=O.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=i.scale.linear().domain(z.slice(0,2)).range("clockwise"===f.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=s.domain(),u.layout.angularAxis.endPadding=E?C:0,e=i.select(this).select("svg.chart-root"),"undefined"==typeof e||e.empty()){var I="' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '",N=(new DOMParser).parseFromString(I,"application/xml"),j=this.appendChild(this.ownerDocument.importNode(N.documentElement,!0));e=i.select(j)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var F,D=e.select(".chart-group"),B={fill:"none",stroke:f.tickColor},U={"font-size":f.font.size,"font-family":f.font.family,fill:f.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){ +return" "+t+" 0 "+f.font.outlineColor}).join(",")};if(f.showLegend){F=e.select(".legend-group").attr({transform:"translate("+[b,f.margin.top]+")"}).style({display:"block"});var V=d.map(function(t,e){var r=a.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});a.Legend().config({data:d.map(function(t,e){return t.name||"Element"+e}),legendConfig:o({},a.Legend.defaultConfig().legendConfig,{container:F,elements:V,reverseOrder:f.legend.reverseOrder})})();var q=F.node().getBBox();b=Math.min(f.width-q.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2,b=Math.max(10,b),_=[f.margin.left+b,f.margin.top+b],n.range([0,b]),u.layout.radialAxis.domain=n.domain(),F.attr("transform","translate("+[_[0]+b,_[1]-b]+")")}else F=e.select(".legend-group").style({display:"none"});e.attr({width:f.width,height:f.height}).style({opacity:f.opacity}),D.attr("transform","translate("+_+")").style({cursor:"crosshair"});var H=[(f.width-(f.margin.left+f.margin.right+2*b+(q?q.width:0)))/2,(f.height-(f.margin.top+f.margin.bottom+2*b))/2];if(H[0]=Math.max(0,H[0]),H[1]=Math.max(0,H[1]),e.select(".outer-group").attr("transform","translate("+H+")"),f.title){var G=e.select("g.title-group text").style(U).text(f.title),Y=G.node().getBBox();G.attr({x:_[0]-Y.width/2,y:_[1]-b-20})}var X=e.select(".radial.axis-group");if(f.radialAxis.gridLinesVisible){var W=X.selectAll("circle.grid-circle").data(n.ticks(5));W.enter().append("circle").attr({"class":"grid-circle"}).style(B),W.attr("r",n),W.exit().remove()}X.select("circle.outside-circle").attr({r:b}).style(B);var Z=e.select("circle.background-circle").attr({r:b}).style({fill:f.backgroundColor,stroke:f.stroke});if(f.radialAxis.visible){var K=i.svg.axis().scale(n).ticks(5).tickSize(5);X.call(K).attr({transform:"rotate("+f.radialAxis.orientation+")"}),X.selectAll(".domain").style(B),X.selectAll("g>text").text(function(t,e){return this.textContent+f.radialAxis.ticksSuffix}).style(U).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===f.radialAxis.tickOrientation?"rotate("+-f.radialAxis.orientation+") translate("+[0,U["font-size"]]+")":"translate("+[0,U["font-size"]]+")"}}),X.selectAll("g>line").style({stroke:"black"})}var $=e.select(".angular.axis-group").selectAll("g.angular-tick").data(O),Q=$.enter().append("g").classed("angular-tick",!0);$.attr({transform:function(t,e){return"rotate("+l(t,e)+")"}}).style({display:f.angularAxis.visible?"block":"none"}),$.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(f.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(f.minorTicks+1)==0)}).style(B),Q.selectAll(".minor").style({stroke:f.minorTickColor}),$.select("line.grid-line").attr({x1:f.tickLength?b-f.tickLength:0,x2:b}).style({display:f.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(U);var J=$.select("text.axis-text").attr({x:b+f.labelOffset,dy:".35em",transform:function(t,e){var r=l(t,e),n=b+f.labelOffset,i=f.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?270>r&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(180>=r&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:f.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(f.minorTicks+1)!=0?"":k?k[t]+f.angularAxis.ticksSuffix:t+f.angularAxis.ticksSuffix}).style(U);f.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(f.minorTicks+1)!=0?"":f.angularAxis.rewriteTicks(this.textContent,e)});var tt=i.max(D.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));F.attr({transform:"translate("+[b+tt,f.margin.top]+")"});var et=e.select("g.geometry-group").selectAll("g").size()>0,rt=e.select("g.geometry-group").selectAll("g.geometry").data(d);if(rt.enter().append("g").attr({"class":function(t,e){return"geometry geometry"+e}}),rt.exit().remove(),d[0]||et){var nt=[];d.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=s,r.container=rt.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=f.orientation,r.direction=f.direction,r.index=e,nt.push({data:t,geometryConfig:r})});var it=i.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(nt),at=[];it.forEach(function(t,e){"unstacked"===t.key?at=at.concat(t.values.map(function(t,e){return[t]})):at.push(t.values)}),at.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return o(a[r].defaultConfig(),t)});a[r]().config(n)()})}var ot,st,lt=e.select(".guides-group"),ct=e.select(".tooltips-group"),ut=a.tooltipPanel().config({container:ct,fontSize:8})(),ft=a.tooltipPanel().config({container:ct,fontSize:8})(),ht=a.tooltipPanel().config({container:ct,hasTick:!0})();if(!M){var dt=lt.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});D.on("mousemove.angular-guide",function(t,e){var r=a.util.getMousePos(Z).angle;dt.attr({x2:-b,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-f.orientation)%360;ot=s.invert(n);var i=a.util.convertToCartesian(b+12,r+180);ut.text(a.util.round(ot)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){lt.select("line").style({opacity:0})})}var pt=lt.select("circle").style({stroke:"grey",fill:"none"});D.on("mousemove.radial-guide",function(t,e){var r=a.util.getMousePos(Z).radius;pt.attr({r:r}).style({opacity:.5}),st=n.invert(a.util.getMousePos(Z).radius);var i=a.util.convertToCartesian(r,f.radialAxis.orientation);ft.text(a.util.round(st)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){pt.style({opacity:0}),ht.hide(),ut.hide(),ft.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(t,r){var n=i.select(this),o=n.style("fill"),s="black",l=n.style("opacity")||1;if(n.attr({"data-opacity":l}),"none"!=o){n.attr({"data-fill":o}),s=i.hsl(o).darker().toString(),n.style({fill:s,opacity:1});var c={t:a.util.round(t[0]),r:a.util.round(t[1])};M&&(c.t=k[t[0]]);var u="t: "+c.t+", r: "+c.r,f=this.getBoundingClientRect(),h=e.node().getBoundingClientRect(),d=[f.left+f.width/2-H[0]-h.left,f.top+f.height/2-H[1]-h.top];ht.config({color:s}).text(u),ht.move(d)}else o=n.style("stroke"),n.attr({"data-stroke":o}),s=i.hsl(o).darker().toString(),n.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){return 0!=i.event.which?!1:void(i.select(this).attr("data-fill")&&ht.show())}).on("mouseout.tooltip",function(t,e){ht.hide();var r=i.select(this),n=r.attr("data-fill");n?r.style({fill:n,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})}),h}var e,r,n,s,l={data:[],layout:{}},c={},u={},f=i.dispatch("hover"),h={};return h.render=function(e){return t(e),this},h.config=function(t){if(!arguments.length)return l;var e=a.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),o(l.data[e],a.Axis.defaultConfig().data[0]),o(l.data[e],t)}),o(l.layout,a.Axis.defaultConfig().layout),o(l.layout,e.layout),this},h.getLiveConfig=function(){return u},h.getinputConfig=function(){return c},h.radialScale=function(t){return n},h.angularScale=function(t){return s},h.svg=function(){return e},i.rebind(h,f,"on"),h},a.Axis.defaultConfig=function(t,e){var r={data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:i.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}};return r},a.util={},a.DATAEXTENT="dataExtent",a.AREA="AreaChart",a.LINE="LinePlot",a.DOT="DotPlot",a.BAR="BarChart",a.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},a.util._extend=function(t,e){for(var r in t)e[r]=t[r]},a.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},a.util.dataFromEquation2=function(t,e){var r=e||6,n=i.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180,i=t(n);return[e,i]});return n},a.util.dataFromEquation=function(t,e,r){var n=e||6,a=[],o=[];i.range(0,360+n,n).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},a.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return i.range(e).map(function(t,e){return r[e]||r[0]})},a.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=a.util.ensureArray(t[e],r)}),t},a.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},a.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},a.util.sumArrays=function(t,e){return i.zip(t,e).map(function(t,e){return i.sum(t)})},a.util.arrayLast=function(t){return t[t.length-1]},a.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},a.util.flattenArray=function(t){for(var e=[];!a.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},a.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},a.util.convertToCartesian=function(t,e){var r=e*Math.PI/180,n=t*Math.cos(r),i=t*Math.sin(r);return[n,i]},a.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},a.util.getMousePos=function(t){var e=i.mouse(t.node()),r=e[0],n=e[1],a={};return a.x=r,a.y=n,a.pos=e,a.angle=180*(Math.atan2(n,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+n*n),a},a.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;a>i;i++)e=t[i],e in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},a.util.duplicates=function(t){return Object.keys(a.util.duplicatesCount(t))},a.util.translator=function(t,e,r,n){if(n){var i=r.slice();r=e,e=i}var a=e.reduce(function(t,e){return"undefined"!=typeof t?t[e]:void 0},t);"undefined"!=typeof a&&(e.reduce(function(t,r,n){return"undefined"!=typeof t?(n===e.length-1&&delete t[r],t[r]):void 0},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=a),t[e]},t))},a.PolyChart=function(){function t(){var t=r[0].geometryConfig,e=t.container;"string"==typeof e&&(e=i.select(e)),e.datum(r).each(function(e,r){function n(e,r){var n=t.radialScale(e[1]),i=(t.angularScale(e[0])+t.orientation)*Math.PI/180;return{r:n,t:i}}function a(t){var e=t.r*Math.cos(t.t),r=t.r*Math.sin(t.t);return{x:e,y:r}}var o=!!e[0].data.yStack,l=e.map(function(t,e){return o?i.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):i.zip(t.data.t[0],t.data.r[0])}),c=t.angularScale,u=t.radialScale.domain()[0],f={};f.bar=function(r,n,a){var o=e[a].data,s=t.radialScale(r[1])-t.radialScale(0),l=t.radialScale(r[2]||0),u=o.barWidth;i.select(this).attr({"class":"mark bar",d:"M"+[[s+l,-u/2],[s+l,u/2],[l,u/2],[l,-u/2]].join("L")+"Z",transform:function(e,r){return"rotate("+(t.orientation+c(e[0]))+")"}})},f.dot=function(t,r,o){var s=t[2]?[t[0],t[1]+t[2]]:t,l=i.svg.symbol().size(e[o].data.dotSize).type(e[o].data.dotType)(t,r);i.select(this).attr({"class":"mark dot",d:l,transform:function(t,e){var r=a(n(s));return"translate("+[r.x,r.y]+")"}})};var h=i.svg.line.radial().interpolate(e[0].data.lineInterpolation).radius(function(e){return t.radialScale(e[1])}).angle(function(e){return t.angularScale(e[0])*Math.PI/180});f.line=function(r,n,a){var o=r[2]?l[a].map(function(t,e){return[t[0],t[1]+t[2]]}):l[a];if(i.select(this).each(f.dot).style({opacity:function(t,r){return+e[a].data.dotVisible},fill:v.stroke(r,n,a)}).attr({"class":"mark dot"}),!(n>0)){var s=i.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({"class":"line",d:h(o),transform:function(e,r){return"rotate("+(t.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return v.fill(r,n,a)},"fill-opacity":0,stroke:function(t,e){return v.stroke(r,n,a)},"stroke-width":function(t,e){return v["stroke-width"](r,n,a)},"stroke-dasharray":function(t,e){return v["stroke-dasharray"](r,n,a)},opacity:function(t,e){return v.opacity(r,n,a)},display:function(t,e){return v.display(r,n,a)}})}};var d=t.angularScale.range(),p=Math.abs(d[1]-d[0])/l[0].length*Math.PI/180,g=i.svg.arc().startAngle(function(t){return-p/2}).endAngle(function(t){return p/2}).innerRadius(function(e){return t.radialScale(u+(e[2]||0))}).outerRadius(function(e){return t.radialScale(u+(e[2]||0))+t.radialScale(e[1])});f.arc=function(e,r,n){i.select(this).attr({"class":"mark arc",d:g,transform:function(e,r){return"rotate("+(t.orientation+c(e[0])+90)+")"}})};var v={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,n){return s[e[n].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return"undefined"==typeof e[n].data.visible||e[n].data.visible?"block":"none"}},m=i.select(this).selectAll("g.layer").data(l);m.enter().append("g").attr({"class":"layer"});var y=m.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({"class":"mark"}),y.style(v).each(f[t.geometryType]),y.exit().remove(),m.exit().remove()})}var e,r=[a.PolyChart.defaultConfig()],n=i.dispatch("hover"),s={solid:"none",dash:[5,2],dot:[2,5]};return t.config=function(t){return arguments.length?(t.forEach(function(t,e){r[e]||(r[e]={}),o(r[e],a.PolyChart.defaultConfig()),o(r[e],t)}),this):r},t.getColorScale=function(){return e},i.rebind(t,n,"on"),t},a.PolyChart.defaultConfig=function(){var t={data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:i.scale.category20()}};return t},a.BarChart=function(){return a.PolyChart()},a.BarChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"bar"}};return t},a.AreaChart=function(){return a.PolyChart()},a.AreaChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"arc"}};return t},a.DotPlot=function(){return a.PolyChart()},a.DotPlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"dot",dotType:"circle"}};return t},a.LinePlot=function(){return a.PolyChart()},a.LinePlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"line"}};return t},a.Legend=function(){function t(){var r=e.legendConfig,n=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=o({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=i.merge(n);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||"undefined"==typeof r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var s=r.container;("string"==typeof s||s.nodeName)&&(s=i.select(s));var l=a.map(function(t,e){return t.color}),c=r.fontSize,u=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,f=u?r.height:c*a.length,h=s.classed("legend-group",!0),d=h.selectAll("svg").data([0]),p=d.enter().append("svg").attr({width:300,height:f+c,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});p.append("g").classed("legend-axis",!0),p.append("g").classed("legend-marks",!0);var g=i.range(a.length),v=i.scale[u?"linear":"ordinal"]().domain(g).range(l),m=i.scale[u?"linear":"ordinal"]().domain(g)[u?"range":"rangePoints"]([0,f]),y=function(t,e){var r=3*e;return"line"===t?"M"+[[-e/2,-e/12],[e/2,-e/12],[e/2,e/12],[-e/2,e/12]]+"Z":-1!=i.svg.symbolTypes.indexOf(t)?i.svg.symbol().type(t).size(r)():i.svg.symbol().type("square").size(r)()};if(u){var b=d.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);b.enter().append("stop"),b.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),d.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var x=d.select(".legend-marks").selectAll("path.legend-mark").data(a);x.enter().append("path").classed("legend-mark",!0),x.attr({transform:function(t,e){return"translate("+[c/2,m(e)+c/2]+")"},d:function(t,e){var r=t.symbol;return y(r,c)},fill:function(t,e){return v(e)}}),x.exit().remove()}var _=i.svg.axis().scale(m).orient("right"),w=d.select("g.legend-axis").attr({transform:"translate("+[u?r.colorBandWidth:c,c/2]+")"}).call(_);return w.selectAll(".domain").style({fill:"none",stroke:"none"}),w.selectAll("line").style({fill:"none",stroke:u?r.textColor:"none"}),w.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),t}var e=a.Legend.defaultConfig(),r=i.dispatch("hover");return t.config=function(t){return arguments.length?(o(e,t),this):e},i.rebind(t,r,"on"),t},a.Legend.defaultConfig=function(t,e){var r={data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}};return r},a.tooltipPanel=function(){var t,e,r,n={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+a.tooltipPanel.uid++,l=10,c=function(){t=n.container.selectAll("g."+s).data([0]);var i=t.enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=i.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=i.append("text").attr({dx:n.padding+l,dy:.3*+n.fontSize}),c};return c.text=function(a){var o=i.hsl(n.color).l,s=o>=.5?"#aaa":"white",u=o>=.5?"black":"white",f=a||"";e.style({fill:u,"font-size":n.fontSize+"px"}).text(f);var h=n.padding,d=e.node().getBBox(),p={fill:n.color,stroke:s,"stroke-width":"2px"},g=d.width+2*h+l,v=d.height+2*h;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[n.hasTick?0:l,0],[l,v/4],[l,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[l,-v/2+2*h]+")"}),t.style({display:"block"}),c},c.move=function(e){return t?(t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),c):void 0},c.hide=function(){return t?(t.style({display:"none"}),c):void 0},c.show=function(){return t?(t.style({display:"block"}),c):void 0},c.config=function(t){return o(n,t),c},c},a.tooltipPanel.uid=1,a.adapter={},a.adapter.plotly=function(){var t={};return t.convert=function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=o({},t),i=[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]];return i.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",n.dotVisible===!0?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var n=a.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var i=n.indexOf(t.geometry);-1!=i&&(r.data[e].groupId=i)})}if(t.layout){var s=o({},t.layout),l=[[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]];if(l.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&"undefined"!=typeof s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&"undefined"!=typeof s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&"undefined"!=typeof s.margin.t){var c=["t","r","b","l","pad"],u=["top","right","bottom","left","pad"],f={};i.entries(s.margin).forEach(function(t,e){f[u[c.indexOf(t.key)]]=t.value}),s.margin=f}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r},t}},{"../../plotly":400,"./micropolar_manager":456,d3:113}],456:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("d3"),a=t("./undo_manager"),o=e.exports={},s=n.Lib.extendDeepAll;o.framework=function(t){function e(e,a){return a&&(f=a),i.select(i.select(f).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),r=r?s(r,e):e,c||(c=n.micropolar.Axis()),u=n.micropolar.adapter.plotly().convert(r),c.config(u).render(f),t.data=r.data,t.layout=r.layout,o.fillLayout(t),r}var r,l,c,u,f,h=new a;return e.isPolar=!0,e.svg=function(){return c.svg()},e.getConfig=function(){return r},e.getLiveConfig=function(){return n.micropolar.adapter.plotly().convert(c.getLiveConfig(),!0)},e.getLiveScales=function(){return{t:c.angularScale(),r:c.radialScale()}},e.setUndoPoint=function(){var t=this,e=n.micropolar.util.cloneJson(r);!function(e,r){h.add({undo:function(){r&&t(r)},redo:function(){t(e)}})}(e,l),l=n.micropolar.util.cloneJson(e)},e.undo=function(){h.undo()},e.redo=function(){h.redo()},e},o.fillLayout=function(t){var e=i.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:n.Color.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../plotly":400,"./undo_manager":457,d3:113}],457:[function(t,e,r){"use strict";e.exports=function(){function t(t,e){return t?(i=!0,t[e](),i=!1,this):this}var e,r=[],n=-1,i=!1;return{add:function(t){return i?this:(r.splice(n+1,r.length-n),r.push(t),n=r.length-1,this)},setCallback:function(t){e=t},undo:function(){var i=r[n];return i?(t(i,"undo"),n-=1,e&&e(i.undo),this):this},redo:function(){var i=r[n+1];return i?(t(i,"redo"),n+=1,e&&e(i.redo),this):this},clear:function(){r=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return ng;g++){var v=d[g];s=t[v]?t[v]:t[v]={},e[v]=l={},o("domain."+h,[g/p,(g+1)/p]),o("domain."+{x:"y",y:"x"}[h]),a.id=v,f(s,l,o,a)}}},{"../lib":381,"./plots":452}],459:[function(t,e,r){"use strict";var n=t("./ternary"),i=t("../../plots/plots");r.name="ternary",r.attr="subplot",r.idRoot="ternary",r.idRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^ternary([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"ternary"),o=0;o=o&&(d.min=0,p.min=0,g.min=0,t.aaxis&&delete t.aaxis.min,t.baxis&&delete t.baxis.min,t.caxis&&delete t.caxis.min)}var i=t("../../../components/color"),a=t("../../subplot_defaults"),o=t("./layout_attributes"),s=t("./axis_defaults"),l=["aaxis","baxis","caxis"];e.exports=function(t,e,r){a(t,e,r,{type:"ternary",attributes:o,handleDefaults:n,font:e.font,paper_bgcolor:e.paper_bgcolor})}},{"../../../components/color":303,"../../subplot_defaults":458,"./axis_defaults":462,"./layout_attributes":464}],464:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("./axis_attributes");e.exports={domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},bgcolor:{valType:"color",dflt:n.background},sum:{valType:"number",dflt:1,min:0},aaxis:i,baxis:i,caxis:i}},{"../../../components/color/attributes":302,"./axis_attributes":461}],465:[function(t,e,r){"use strict";function n(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.init(e),this.makeFramework()}function i(t){a.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}var a=t("d3"),o=t("tinycolor2"),s=t("../../plotly"),l=t("../../lib"),c=t("../../components/color"),u=t("../../components/drawing"),f=t("../cartesian/set_convert"),h=t("../../lib/extend").extendFlat,d=t("../cartesian/axes"),p=t("../../lib/filter_visible"),g=t("../../components/dragelement"),v=t("../../components/titles"),m=t("../cartesian/select"),y=t("../cartesian/constants"),b=t("../cartesian/graph_interact");e.exports=n;var x=n.prototype;x.init=function(t){this.container=t._ternarylayer,this.defs=t._defs,this.layoutId=t._uid,this.traceHash={}},x.plot=function(t,e){var r,n=this,i=e[n.id],a=e._size;l.getPlotDiv(n.plotContainer.node())!==n.graphDiv&&(n.init(n.graphDiv._fullLayout),n.makeFramework()),n.adjustLayout(i,a);var o=n.traceHash,s={};for(r=0;r_*y?(a=y,i=a*_):(i=m,a=i/_),o=g*i/m,s=v*a/y,r=e.l+e.w*d-i/2,n=e.t+e.h*(1-p)-a/2,l.x0=r,l.y0=n,l.w=i,l.h=a,l.sum=b,l.xaxis={type:"linear",range:[x+2*k-b,b-x-2*w],domain:[d-o/2,d+o/2],_id:"x",_gd:l.graphDiv},f(l.xaxis),l.xaxis.setScale(),l.yaxis={type:"linear",range:[x,b-w-k],domain:[p-s/2,p+s/2],_id:"y",_gd:l.graphDiv},f(l.yaxis),l.yaxis.setScale();var A=l.yaxis.domain[0],M=l.aaxis=h({},t.aaxis,{range:[x,b-w-k],side:"left",_counterangle:30,tickangle:(+t.aaxis.tickangle||0)-30,domain:[A,A+s*_],_axislayer:l.layers.aaxis,_gridlayer:l.layers.agrid,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l"+a+",-"+i/2});f(M);var T=l.baxis=h({},t.baxis,{range:[b-x-k,w],side:"bottom",_counterangle:30,domain:l.xaxis.domain,_axislayer:l.layers.baxis,_gridlayer:l.layers.bgrid,_counteraxis:l.aaxis,_pos:0,_gd:l.graphDiv,_id:"x",_length:i,_gridpath:"M0,0l-"+i/2+",-"+a});f(T),M._counteraxis=T;var E=l.caxis=h({},t.caxis,{range:[b-x-w,k],side:"right",_counterangle:30,tickangle:(+t.caxis.tickangle||0)+30,domain:[A,A+s*_],_axislayer:l.layers.caxis,_gridlayer:l.layers.cgrid,_counteraxis:l.baxis,_pos:0,_gd:l.graphDiv,_id:"y",_length:i,_gridpath:"M0,0l-"+a+","+i/2});f(E);var L="M"+r+","+(n+a)+"h"+i+"l-"+i/2+",-"+a+"Z";l.clipDef.select("path").attr("d",L),l.layers.plotbg.select("path").attr("d",L);var S="translate("+r+","+n+")";l.plotContainer.selectAll(".scatterlayer,.maplayer,.zoom").attr("transform",S);var C="translate("+r+","+(n+a)+")";l.layers.baxis.attr("transform",C),l.layers.bgrid.attr("transform",C);var z="translate("+(r+i/2)+","+n+")rotate(30)";l.layers.aaxis.attr("transform",z),l.layers.agrid.attr("transform",z);var P="translate("+(r+i/2)+","+n+")rotate(-30)";l.layers.caxis.attr("transform",P),l.layers.cgrid.attr("transform",P),l.drawAxes(!0),l.plotContainer.selectAll(".crisp").classed("crisp",!1);var R=l.layers.axlines;R.select(".aline").attr("d",M.showline?"M"+r+","+(n+a)+"l"+i/2+",-"+a:"M0,0").call(c.stroke,M.linecolor||"#000").style("stroke-width",(M.linewidth||0)+"px"),R.select(".bline").attr("d",T.showline?"M"+r+","+(n+a)+"h"+i:"M0,0").call(c.stroke,T.linecolor||"#000").style("stroke-width",(T.linewidth||0)+"px"),R.select(".cline").attr("d",E.showline?"M"+(r+i/2)+","+n+"l"+i/2+","+a:"M0,0").call(c.stroke,E.linecolor||"#000").style("stroke-width",(E.linewidth||0)+"px")},x.drawAxes=function(t){var e=this,r=e.graphDiv,n=e.id.substr(7)+"title",i=e.aaxis,a=e.baxis,o=e.caxis;if(d.doTicks(r,i,!0),d.doTicks(r,a,!0),d.doTicks(r,o,!0),t){var s=Math.max(i.showticklabels?i.tickfont.size/2:0,(o.showticklabels?.75*o.tickfont.size:0)+("outside"===o.ticks?.87*o.ticklen:0));v.draw(r,"a"+n,{propContainer:i,propName:e.id+".aaxis.title",dfltName:"Component A",attributes:{x:e.x0+e.w/2,y:e.y0-i.titlefont.size/3-s,"text-anchor":"middle"}});var l=(a.showticklabels?a.tickfont.size:0)+("outside"===a.ticks?a.ticklen:0)+3;v.draw(r,"b"+n,{propContainer:a,propName:e.id+".baxis.title",dfltName:"Component B",attributes:{x:e.x0-l,y:e.y0+e.h+.83*a.titlefont.size+l,"text-anchor":"middle"}}),v.draw(r,"c"+n,{propContainer:o,propName:e.id+".caxis.title",dfltName:"Component C",attributes:{x:e.x0+e.w+l,y:e.y0+e.h+.83*o.titlefont.size+l,"text-anchor":"middle"}})}};var w=y.MINZOOM/2+.87,k="m-0.87,.5h"+w+"v3h-"+(w+5.2)+"l"+(w/2+2.6)+",-"+(.87*w+4.5)+"l2.6,1.5l-"+w/2+","+.87*w+"Z",A="m0.87,.5h-"+w+"v3h"+(w+5.2)+"l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-2.6,1.5l"+w/2+","+.87*w+"Z",M="m0,1l"+w/2+","+.87*w+"l2.6,-1.5l-"+(w/2+2.6)+",-"+(.87*w+4.5)+"l-"+(w/2+2.6)+","+(.87*w+4.5)+"l2.6,1.5l"+w/2+",-"+.87*w+"Z",T="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z",E=!0;x.initInteractions=function(){function t(t,e,r){var n=j.getBoundingClientRect();x=e-n.left,w=r-n.top,L={a:N.aaxis.range[0],b:N.baxis.range[1],c:N.caxis.range[1]},C=L,S=N.aaxis.range[1]-L.a,z=o(N.graphDiv._fullLayout[N.id].bgcolor).getLuminance(),P="M0,"+N.h+"L"+N.w/2+", 0L"+N.w+","+N.h+"Z",R=!1,O=D.append("path").attr("class","zoombox").style({fill:z>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",P),I=D.append("path").attr("class","zoombox-corners").style({fill:c.background,stroke:c.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),p()}function e(t,e){return 1-e/N.h}function r(t,e){return 1-(t+(N.h-e)/Math.sqrt(3))/N.w}function n(t,e){return(t-(N.h-e)/Math.sqrt(3))/N.w}function a(t,i){var a=x+t,o=w+i,s=Math.max(0,Math.min(1,e(x,w),e(a,o))),l=Math.max(0,Math.min(1,r(x,w),r(a,o))),c=Math.max(0,Math.min(1,n(x,w),n(a,o))),u=(s/2+c)*N.w,f=(1-s/2-l)*N.w,h=(u+f)/2,d=f-u,p=(1-s)*N.h,g=p-d/_;d.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),I.transition().style("opacity",1).duration(200),R=!0)}function u(t,e){if(C===L)return 2===e&&v(),i(F);i(F);var r={};r[N.id+".aaxis.min"]=C.a,r[N.id+".baxis.min"]=C.b,r[N.id+".caxis.min"]=C.c,s.relayout(F,r),E&&F.data&&F._context.showTips&&(l.notifier("Double-click to
zoom back out","long"),E=!1)}function f(){L={a:N.aaxis.range[0],b:N.baxis.range[1],c:N.caxis.range[1]},C=L}function h(t,e){var r=t/N.xaxis._m,n=e/N.yaxis._m;C={a:L.a-n,b:L.b+(r+n)/2,c:L.c-(r-n)/2};var i=[C.a,C.b,C.c].sort(),a={a:i.indexOf(C.a),b:i.indexOf(C.b),c:i.indexOf(C.c)};i[0]<0&&(i[1]+i[0]/2<0?(i[2]+=i[0]+i[1],i[0]=i[1]=0):(i[2]+=i[0]/2,i[1]+=i[0]/2,i[0]=0),C={a:i[a.a],b:i[a.b],c:i[a.c]},e=(L.a-C.a)*N.yaxis._m,t=(L.c-C.c-L.b+C.b)*N.xaxis._m);var o="translate("+(N.x0+t)+","+(N.y0+e)+")";N.plotContainer.selectAll(".scatterlayer,.maplayer").attr("transform",o),N.aaxis.range=[C.a,N.sum-C.b-C.c],N.baxis.range=[N.sum-C.a-C.c,C.b],N.caxis.range=[N.sum-C.a-C.b,C.c],N.drawAxes(!1),N.plotContainer.selectAll(".crisp").classed("crisp",!1)}function d(t,e){if(t){var r={};r[N.id+".aaxis.min"]=C.a,r[N.id+".baxis.min"]=C.b,r[N.id+".caxis.min"]=C.c,s.relayout(F,r)}else 2===e&&v()}function p(){N.plotContainer.selectAll(".select-outline").remove()}function v(){var t={};t[N.id+".aaxis.min"]=0,t[N.id+".baxis.min"]=0,t[N.id+".caxis.min"]=0,F.emit("plotly_doubleclick",null),s.relayout(F,t)}var x,w,L,S,C,z,P,R,O,I,N=this,j=N.layers.plotbg.select("path").node(),F=N.graphDiv,D=N.layers.zoom,B={element:j,gd:F,plotinfo:{plot:D},doubleclick:v,subplot:N.id,prepFn:function(e,r,n){B.xaxes=[N.xaxis],B.yaxes=[N.yaxis];var i=F._fullLayout.dragmode;e.shiftKey&&(i="pan"===i?"zoom":"pan"),"lasso"===i?B.minDrag=1:B.minDrag=void 0,"zoom"===i?(B.moveFn=a,B.doneFn=u,t(e,r,n)):"pan"===i?(B.moveFn=h,B.doneFn=d,f(),p()):"select"!==i&&"lasso"!==i||m(e,r,n,B,i)}};g.init(B),j.onmousemove=function(t){b.hover(F,t,N.id),F._fullLayout._lasthover=j,F._fullLayout._hoversubplot=N.id},j.onmouseout=function(t){F._dragging||g.unhover(F,t)},j.onclick=function(t){b.click(F,t)},F._fullLayout._plots||(F._fullLayout._plots={}),F._fullLayout._plots[N.id]={overlays:[],xaxis:N.xaxis,yaxis:N.yaxis,x:function(){return N.xaxis},y:function(){return N.yaxis}}}},{"../../components/color":303,"../../components/dragelement":323,"../../components/drawing":325,"../../components/titles":365,"../../lib":381,"../../lib/extend":376,"../../lib/filter_visible":377,"../../plotly":400,"../cartesian/axes":403,"../cartesian/constants":408,"../cartesian/graph_interact":410,"../cartesian/select":416,"../cartesian/set_convert":417,d3:113,tinycolor2:274}],466:[function(t,e,r){"use strict";function n(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}function i(t){var e=["xaxis","yaxis","zaxis"];return e.indexOf(t.slice(0,5))>-1}var a=t("../plotly"),o=a.Lib.extendFlat,s=a.Lib.extendDeep;e.exports=function(t,e){t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var r,l=t.data,c=t.layout,u=s([],l),f=s({},c,n(e.tileClass));if(e.width&&(f.width=e.width),e.height&&(f.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){f.annotations=[];var h=Object.keys(f);for(r=0;rl;l++)n(r[l])&&d.push({p:r[l],s:s[l],b:0});return a(e,"marker")&&o(e,e.marker.color,"marker","c"),a(e,"marker.line")&&o(e,e.marker.line.color,"marker.line","c"),d}},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":315,"../../plots/cartesian/axes":403,"fast-isnumeric":117}],476:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../scatter/xy_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,l,r,i)}var f=a(t,e,u);return f?(u("orientation",e.x&&!e.y?"h":"v"),u("text"),o(t,e,u,r,c),s(t,e,i.defaultLine,{axis:"y"}),void s(t,e,i.defaultLine,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/color":303,"../../components/errorbars/defaults":330,"../../lib":381,"../bar/style_defaults":484,"../scatter/xy_defaults":575,"./attributes":474}],477:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../components/errorbars"),a=t("../../components/color");e.exports=function(t,e,r,o){var s,l=t.cd,c=l[0].trace,u=l[0].t,f=t.xa,h=t.ya,d="closest"===o?u.barwidth/2:u.dbar*(1-f._gd._fullLayout.bargap)/2;s="closest"!==o?function(t){return t.p}:"h"===c.orientation?function(t){return t.y}:function(t){return t.x};var p,g;"h"===c.orientation?(p=function(t){return n.inbox(t.b-e,t.x-e)+(t.x-e)/(t.x-t.b)},g=function(t){var e=s(t)-r;return n.inbox(e-d,e+d)}):(g=function(t){return n.inbox(t.b-r,t.y-r)+(t.y-r)/(t.y-t.b)},p=function(t){var r=s(t)-e;return n.inbox(r-d,r+d)});var v=n.getDistanceFunction(o,p,g);if(n.getClosest(l,v,t),t.index!==!1){var m=l[t.index],y=m.mcc||c.marker.color,b=m.mlcc||c.marker.line.color,x=m.mlw||c.marker.line.width;return a.opacity(y)?t.color=y:a.opacity(b)&&x&&(t.color=b),"h"===c.orientation?(t.x0=t.x1=f.c2p(m.x,!0),t.xLabelVal=m.s,t.y0=h.c2p(s(m)-d,!0),t.y1=h.c2p(s(m)+d,!0),t.yLabelVal=m.p):(t.y0=t.y1=h.c2p(m.y,!0),t.yLabelVal=m.s,t.x0=f.c2p(s(m)-d,!0),t.x1=f.c2p(s(m)+d,!0),t.xLabelVal=m.p),m.tx&&(t.text=m.tx),i.hoverInfo(m,c,t),[t]}}},{"../../components/color":303,"../../components/errorbars":331,"../../plots/cartesian/graph_interact":410}],478:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","oriented","markerColorscale","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":411,"../scatter/colorbar":557,"./arrays_to_calcdata":473,"./attributes":474,"./calc":475,"./defaults":476,"./hover":477,"./layout_attributes":479,"./layout_defaults":480,"./plot":481,"./set_positions":482,"./style":483}],479:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:""},bargap:{valType:"number",min:0,max:1},bargroupgap:{valType:"number",min:0,max:1,dflt:0}}},{}],480:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function s(r,n){return a.coerce(t,e,o,r,n)}for(var l=!1,c=!1,u=!1,f={},h=0;h=2?a(t):t>e?Math.ceil(t):Math.floor(t)}var h,d,p,g;if("h"===s.orientation?(p=u.c2p(r.poffset+e.p,!0),g=u.c2p(r.poffset+e.p+r.barwidth,!0),h=c.c2p(e.b,!0),d=c.c2p(e.s+e.b,!0)):(h=c.c2p(r.poffset+e.p,!0),d=c.c2p(r.poffset+e.p+r.barwidth,!0),g=u.c2p(e.s+e.b,!0),p=u.c2p(e.b,!0)),!(i(h)&&i(d)&&i(p)&&i(g)&&h!==d&&p!==g))return void n.select(this).remove();var v=(e.mlw+1||s.marker.line.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,m=n.round(v/2%1,2);if(!t._context.staticPlot){var y=o.opacity(e.mc||s.marker.color),b=1>y||v>.01?a:l;h=b(h,d),d=b(d,h),p=b(p,g),g=b(g,p)}n.select(this).attr("d","M"+h+","+p+"V"+g+"H"+d+"V"+p+"Z")})}),h.call(s.plot,e)}},{"../../components/color":303,"../../components/errorbars":331,"../../lib":381,"./arrays_to_calcdata":473,d3:113,"fast-isnumeric":117}],482:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axes"),o=t("../../lib");e.exports=function(t,e){var r,s,l=t._fullLayout,c=e.x(),u=e.y();["v","h"].forEach(function(f){function h(e){function r(t){t[p]=t.p+h}var n=[];e.forEach(function(e){t.calcdata[e].forEach(function(t){n.push(t.p)})});var i=o.distinctVals(n),s=i.vals,c=i.minDiff,u=!1,f=[];"group"===l.barmode&&e.forEach(function(e){u||(t.calcdata[e].forEach(function(t){u||f.forEach(function(e){Math.abs(t.p-e)_&&(S=!0,M=_),_>A+R&&(S=!0,A=_))}a.expand(m,[M,A],{tozero:!0,padded:S})}else{var O=function(t){return t[g]=t.s,t.s};for(r=0;r1||0===s.bargap&&0===s.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),e.selectAll("g.points").each(function(t){var e=t[0].trace,r=e.marker,o=r.line,s=(e._input||{}).marker||{},l=a.tryColorscale(r,s,""),c=a.tryColorscale(r,s,"line.");n.select(this).selectAll("path").each(function(t){var e,a,s=(t.mlw+1||o.width+1)-1,u=n.select(this);e="mc"in t?t.mcc=l(t.mc):Array.isArray(r.color)?i.defaultLine:r.color,u.style("stroke-width",s+"px").call(i.fill,e),s&&(a="mlc"in t?t.mlcc=c(t.mlc):Array.isArray(o.color)?i.defaultLine:o.color,u.call(i.stroke,a))})}),e.call(o.style)}},{"../../components/color":303,"../../components/drawing":325,"../../components/errorbars":331,d3:113}],484:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width")}},{"../../components/color":303,"../../components/colorscale/defaults":312,"../../components/colorscale/has_colorscale":315}],485:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/color/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=o.line;e.exports={y:{valType:"data_array"},x:{valType:"data_array"},x0:{valType:"any"},y0:{valType:"any"},whiskerwidth:{valType:"number",min:0,max:1,dflt:.5},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1},jitter:{valType:"number",min:0,max:1},pointpos:{valType:"number",min:-2,max:2},orientation:{valType:"enumerated",values:["v","h"]},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)"},symbol:a({},o.symbol,{arrayOk:!1}),opacity:a({},o.opacity,{arrayOk:!1,dflt:1}),size:a({},o.size,{arrayOk:!1}),color:a({},o.color,{arrayOk:!1}),line:{color:a({},s.color,{arrayOk:!1,dflt:i.defaultLine}),width:a({},s.width,{arrayOk:!1,dflt:0}),outliercolor:{valType:"color"},outlierwidth:{valType:"number",min:0,dflt:1}}},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2}},fillcolor:n.fillcolor}},{"../../components/color/attributes":302,"../../lib/extend":376,"../scatter/attributes":554}],486:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes");e.exports=function(t,e){function r(t,e,r,a,o){var s;return r in e?p=a.makeCalcdata(e,r):(s=r+"0"in e?e[r+"0"]:"name"in e&&("category"===a.type||n(e.name)&&-1!==["linear","log"].indexOf(a.type)||i.isDateTime(e.name)&&"date"===a.type)?e.name:t.numboxes,s=a.d2c(s),p=o.map(function(){return s})),p}function o(t,e,r,a,o){var s,l,c,u,f=a.length,h=e.length,d=[],p=[];for(s=0;f>s;++s)l=a[s],t[s]={pos:l},p[s]=l-o,d[s]=[];for(p.push(a[f-1]+o),s=0;h>s;++s)u=e[s],n(u)&&(c=i.findBin(r[s],p),c>=0&&h>c&&d[c].push(u));return d}function s(t,e){var r,n,a,o;for(o=0;o1,m=r.dPos*(1-h.boxgap)*(1-h.boxgroupgap)/(v?t.numboxes:1),y=v?2*r.dPos*(-.5+(r.boxnum+.5)/t.numboxes)*(1-h.boxgap):0,b=m*g.whiskerwidth;return g.visible!==!0||r.emptybox?void a.select(this).remove():("h"===g.orientation?(l=p,f=d):(l=d,f=p),r.bPos=y,r.bdPos=m,n(),a.select(this).selectAll("path.box").data(o.identity).enter().append("path").attr("class","box").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=l.c2p(t.pos+y-b,!0),s=l.c2p(t.pos+y+b,!0),c=f.c2p(t.q1,!0),u=f.c2p(t.q3,!0),h=o.constrain(f.c2p(t.med,!0),Math.min(c,u)+1,Math.max(c,u)-1),d=f.c2p(g.boxpoints===!1?t.min:t.lf,!0),p=f.c2p(g.boxpoints===!1?t.max:t.uf,!0);"h"===g.orientation?a.select(this).attr("d","M"+h+","+r+"V"+n+"M"+c+","+r+"V"+n+"H"+u+"V"+r+"ZM"+c+","+e+"H"+d+"M"+u+","+e+"H"+p+(0===g.whiskerwidth?"":"M"+d+","+i+"V"+s+"M"+p+","+i+"V"+s)):a.select(this).attr("d","M"+r+","+h+"H"+n+"M"+r+","+c+"H"+n+"V"+u+"H"+r+"ZM"+e+","+c+"V"+d+"M"+e+","+u+"V"+p+(0===g.whiskerwidth?"":"M"+i+","+d+"H"+s+"M"+i+","+p+"H"+s))}),g.boxpoints&&a.select(this).selectAll("g.points").data(function(t){return t.forEach(function(t){t.t=r,t.trace=g}),t}).enter().append("g").attr("class","points").selectAll("path").data(function(t){var e,r,n,a,s,l,f,h="all"===g.boxpoints?t.val:t.val.filter(function(e){return et.uf}),d=(t.q3-t.q1)*u,p=[],v=0;if(g.jitter){for(e=0;et.lo&&(n.so=!0),n})}).enter().append("path").call(s.translatePoints,d,p),void(g.boxmean&&a.select(this).selectAll("path.mean").data(o.identity).enter().append("path").attr("class","mean").style("fill","none").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=f.c2p(t.mean,!0),o=f.c2p(t.mean-t.sd,!0),s=f.c2p(t.mean+t.sd,!0);"h"===g.orientation?a.select(this).attr("d","M"+i+","+r+"V"+n+("sd"!==g.boxmean?"":"m0,0L"+o+","+e+"L"+i+","+r+"L"+s+","+e+"Z")):a.select(this).attr("d","M"+r+","+i+"H"+n+("sd"!==g.boxmean?"":"m0,0L"+e+","+o+"L"+r+","+i+"L"+e+","+s+"Z"))})))})}},{"../../components/drawing":325,"../../lib":381,d3:113}],493:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib");e.exports=function(t,e){var r,o,s,l,c=t._fullLayout,u=e.x(),f=e.y(),h=["v","h"];for(o=0;ol&&(e.z=u.slice(0,l)),s("locationmode"),s("text"),s("marker.line.color"),s("marker.line.width"),i(t,e,o,s,{prefix:"",cLetter:"z"}),void s("hoverinfo",1===o._dataLength?"location+z+text":void 0)):void(e.visible=!1)}},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":495}],498:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./plot").plot,n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":424,"../heatmap/colorbar":512,"./attributes":495,"./calc":496,"./defaults":497,"./plot":499}],499:[function(t,e,r){"use strict";function n(t,e){function r(e){var r=t.mockAxis;return o.tickText(r,r.c2l(e),"hover").text}var n=e.hoverinfo;if("none"===n)return function(t){delete t.nameLabel,delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("name"),s=-1!==i.indexOf("location"),l=-1!==i.indexOf("z"),c=-1!==i.indexOf("text"),u=!a&&s;return function(t){var n=[];u?t.nameLabel=t.id:(a&&(t.nameLabel=e.name),s&&n.push(t.id)),l&&n.push(r(t.z)),c&&n.push(t.tx),t.textLabel=n.join("
")}}function i(t){return function(e,r){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:r,location:e.id,z:e.z}]}}}var a=t("d3"),o=t("../../plots/cartesian/axes"),s=t("../../plots/cartesian/graph_interact"),l=t("../../components/color"),c=t("../../components/drawing"),u=t("../../components/colorscale/get_scale"),f=t("../../components/colorscale/make_scale_function"),h=t("../../lib/topojson_utils").getTopojsonFeatures,d=t("../../lib/geo_location_utils").locationToFeature,p=t("../../lib/array_to_calc_item"),g=t("../../plots/geo/constants"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){for(var r,n=[],i=t.locations,a=i.length,o=h(t,e),s=(t.marker||{}).line||{},l=0;a>l;l++)r=d(t.locationmode,i[l],o),void 0!==r&&(r.z=t.z[l],void 0!==t.text&&(r.tx=t.text[l]),p(s.color,r,"mlc",l),p(s.width,r,"mlw",l),n.push(r));return n.length>0&&(n[0].trace=t),n},m.plot=function(t,e,r){var o,l=t.framework,c=l.select("g.choroplethlayer"),u=l.select("g.baselayer"),f=l.select("g.baselayeroverchoropleth"),h=g.baseLayersOverChoropleth,d=c.selectAll("g.trace.choropleth").data(e,function(t){return t.uid});d.enter().append("g").attr("class","trace choropleth"),d.exit().remove(),d.each(function(e){function r(e,r){if(t.showHover){var n=t.projection(e.properties.ct);c(e),s.loneHover({x:n[0],y:n[1],name:e.nameLabel,text:e.textLabel},{container:t.hoverContainer.node()}),f=u(e,r),t.graphDiv.emit("plotly_hover",f)}}function o(e,r){t.graphDiv.emit("plotly_click",u(e,r))}var l=m.calcGeoJSON(e,t.topojson),c=n(t,e),u=i(e),f=null,h=a.select(this).selectAll("path.choroplethlocation").data(l);h.enter().append("path").classed("choroplethlocation",!0).on("mouseover",r).on("click",o).on("mouseout",function(){s.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",f)}).on("mousedown",function(){s.loneUnhover(t.hoverContainer)}).on("mouseup",r),h.exit().remove()}),f.selectAll("*").remove();for(var p=0;pr;r++)e=f[r],d[r]=e[0]*(t.zmax-t.zmin)+t.zmin,p[r]=e[1];var g=n.extent([t.zmin,t.zmax,a.start,a.start+l*(c-1)]),v=g[t.zminr;r++)e=f[r],d[r]=(e[0]*(c+u-1)-u/2)*l+o,p[r]=e[1];var y=n.scale.linear().interpolate(n.interpolateRgb).domain(d).range(p);return y}},{"../../components/colorscale/get_scale":314,d3:113}],507:[function(t,e,r){"use strict";function n(t,e,r){_.markTime("in Contour.plot");var n=r[0].trace,a=r[0].x,s=r[0].y,c=n.contours,u=n.uid,f=e.x(),h=e.y(),v=t._fullLayout,b="contour"+u,x=i(c,e,r[0]);if(n.visible!==!0)return v._paper.selectAll("."+b+",.hm"+u).remove(),void v._infolayer.selectAll(".cb"+u).remove();"heatmap"===c.coloring?(n.zauto&&n.autocontour===!1&&(n._input.zmin=n.zmin=c.start-c.size/2,n._input.zmax=n.zmax=n.zmin+x.length*c.size),k(t,e,[r])):v._paper.selectAll(".hm"+u).remove(),o(x),l(x);var w=f.c2p(a[0],!0),A=f.c2p(a[a.length-1],!0),M=h.c2p(s[0],!0),T=h.c2p(s[s.length-1],!0),E=[[w,T],[A,T],[A,M],[w,M]],L=d(e,r,b);p(L,E,c),g(L,x,E,c),m(L,x,c),y(L,e,r[0],E),_.markTime("done Contour.plot")}function i(t,e,r){for(var n=t.size||1,i=[],a=t.start;at?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);if(5===r||10===r){var n=(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4;return t>n?5===r?713:1114:5===r?104:208}return 15===r?0:r}function o(t){var e,r,n,i,o,s,l,c,u,f=t[0].z,h=f.length,d=f[0].length,p=2===h||2===d;for(r=0;h-1>r;r++)for(i=[],0===r&&(i=i.concat(A)),r===h-2&&(i=i.concat(M)),e=0;d-1>e;e++)for(n=i.slice(),0===e&&(n=n.concat(T)),e===d-2&&(n=n.concat(E)),o=e+","+r,s=[[f[r][e],f[r][e+1]],[f[r+1][e],f[r+1][e+1]]],u=0;ui;i++){if(s>20?(s=S[s][(l[0]||l[1])<0?0:1],t.crossings[o]=C[s]):delete t.crossings[o],l=L[s],!l){console.log("found bad marching index",s,e,t.level);break}if(d.push(h(t,e,l)),e[0]+=l[0],e[1]+=l[1],u(d[d.length-1],d[d.length-2])&&d.pop(),o=e.join(","),o===a&&l.join(",")===p||r&&(l[0]&&(e[0]<0||e[0]>v-2)||l[1]&&(e[1]<0||e[1]>g-2)))break;s=t.crossings[o]}1e4===i&&console.log("Infinite loop in contour?");var m,y,b,x,_,w,k,A=u(d[0],d[d.length-1]),M=0,T=.2*t.smoothing,E=[],z=0;for(i=1;i=z;i--)if(m=E[i],P>m){for(b=0,y=i-1;y>=z&&m+E[y]b&&m+E[b]e;)e++,r=Object.keys(i.crossings)[0].split(",").map(Number),s(i,r);1e4===e&&console.log("Infinite loop in contour?")}}function c(t,e,r){var n=0,i=0;return t>20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==A.indexOf(t)?i=1:-1!==T.indexOf(t)?n=1:-1!==M.indexOf(t)?i=-1:n=-1,[n,i]}function u(t,e){return Math.abs(t[0]-e[0])<.01&&Math.abs(t[1]-e[1])<.01}function f(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}function h(t,e,r){var n=e[0]+Math.max(r[0],0),i=e[1]+Math.max(r[1],0),a=t.z[i][n],o=t.xaxis,s=t.yaxis;if(r[1]){var l=(t.level-a)/(t.z[i][n+1]-a);return[o.c2p((1-l)*t.x[n]+l*t.x[n+1],!0),s.c2p(t.y[i],!0)]}var c=(t.level-a)/(t.z[i+1][n]-a);return[o.c2p(t.x[n],!0),s.c2p((1-c)*t.y[i]+c*t.y[i+1],!0)]}function d(t,e,r){var n=t.plot.select(".maplayer").selectAll("g.contour."+r).data(e);return n.enter().append("g").classed("contour",!0).classed(r,!0),n.exit().remove(),n}function p(t,e,r){var n=t.selectAll("g.contourbg").data([0]);n.enter().append("g").classed("contourbg",!0);var i=n.selectAll("path").data("fill"===r.coloring?[0]:[]);i.enter().append("path"),i.exit().remove(),i.attr("d","M"+e.join("L")+"Z").style("stroke","none")}function g(t,e,r,n){var i=t.selectAll("g.contourfill").data([0]);i.enter().append("g").classed("contourfill",!0);var a=i.selectAll("path").data("fill"===n.coloring?e:[]);a.enter().append("path"),a.exit().remove(),a.each(function(t){var e=v(t,r);e?x.select(this).attr("d",e).style("stroke","none"):x.select(this).remove()})}function v(t,e){function r(t){return Math.abs(t[1]-e[0][1])<.01}function n(t){return Math.abs(t[1]-e[2][1])<.01}function i(t){return Math.abs(t[0]-e[0][0])<.01}function a(t){return Math.abs(t[0]-e[2][0])<.01}for(var o,s,l,c,u,f,h=t.edgepaths.length||t.z[0][0]l;l++){if(!o){console.log("missing end?",d,t);break}for(r(o)&&!a(o)?s=e[1]:i(o)?s=e[0]:n(o)?s=e[3]:a(o)&&(s=e[2]),u=0;u=0&&(s=v,c=u):Math.abs(o[1]-s[1])<.01?Math.abs(o[1]-v[1])<.01&&(v[0]-o[0])*(s[0]-v[0])>=0&&(s=v,c=u):console.log("endpt to newendpt is not vert. or horz.",o,s,v)}if(o=s,c>=0)break;h+="L"+s}if(c===t.edgepaths.length){console.log("unclosed perimeter path");break}d=c,g=-1===p.indexOf(d),g&&(d=p[0],h+="Z")}for(d=0;de;e++)s.push(1);for(e=0;a>e;e++)i.push(s.slice());for(e=0;eo;o++)for(n=i(l,o),u[o]=new Array(n),s=0;n>s;s++)u[o][s]=e(a(l,o,s));return u}function i(t,e,r,n,i,a){var o,s,l,c=[],u=h.traceIs(t,"contour"),f=h.traceIs(t,"histogram"),d=h.traceIs(t,"gl2d");if(Array.isArray(e)&&!f&&"category"!==a.type){e=e.map(a.d2c);var p=e.length;if(!(i>=p))return u?e.slice(0,i):e.slice(0,i+1);if(u||d)c=e.slice(0,i);else if(1===i)c=[e[0]-.5,e[0]+.5];else{for(c=[1.5*e[0]-.5*e[1]],l=1;p>l;l++)c.push(.5*(e[l-1]+e[l]));c.push(1.5*e[p-1]-.5*e[p-2])}if(i>p){var g=c[c.length-1],v=g-c[c.length-2];for(l=p;i>l;l++)g+=v,c.push(g)}}else for(s=n||1,o=void 0===r?0:f||"category"===a.type?r:a.d2c(r),l=u||d?0:-.5;i>l;l++)c.push(o+s*l);return c}function a(t){return.5-.25*Math.min(1,.5*t)}function o(t,e,r){var n,i,o=1;if(Array.isArray(r))for(n=0;nn&&o>y;n++)o=l(t,e,a(o));return o>y&&console.log("interp2d didn't converge quickly",o),t}function s(t){var e,r,n,i,a,o,s,l,c=[],u={},f=[],h=t[0],d=[],p=[0,0,0],g=m(t);for(r=0;rn;n++)void 0===d[n]&&(o=(void 0!==d[n-1]?1:0)+(void 0!==d[n+1]?1:0)+(void 0!==e[n]?1:0)+(void 0!==h[n]?1:0),o?(0===r&&o++,0===n&&o++,r===t.length-1&&o++,n===d.length-1&&o++,4>o&&(u[[r,n]]=[r,n,o]),c.push([r,n,o])):f.push([r,n]));for(;f.length;){for(s={},l=!1,a=f.length-1;a>=0;a--)i=f[a],r=i[0],n=i[1],o=((u[[r-1,n]]||p)[2]+(u[[r+1,n]]||p)[2]+(u[[r,n-1]]||p)[2]+(u[[r,n+1]]||p)[2])/20,o&&(s[i]=[r,n,o],f.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)u[i]=s[i],c.push(s[i])}return c.sort(function(t,e){return e[2]-t[2]})}function l(t,e,r){var n,i,a,o,s,l,c,u,f,h,d,p,g,v=0;for(o=0;os;s++)l=b[s],c=t[i+l[0]],c&&(u=c[a+l[1]],void 0!==u&&(0===h?p=g=u:(p=Math.min(p,u),g=Math.max(g,u)),f++,h+=u));if(0===f)throw"iterateInterp2d order is wrong: no defined neighbors";t[i][a]=h/f,void 0===d?4>f&&(v=1):(t[i][a]=(1+r)*t[i][a]-r*d,g>p&&(v=Math.max(v,Math.abs(t[i][a]-d)/(g-p))))}return v}var c=t("fast-isnumeric"),u=t("../../lib"),f=t("../../plots/cartesian/axes"),h=t("../../plots/plots"),d=t("../histogram2d/calc"),p=t("../../components/colorscale/calc"),g=t("./has_columns"),v=t("./convert_column_xyz"),m=t("./max_row_length");e.exports=function(t,e){function r(t){E=e._input.zsmooth=e.zsmooth=!1,u.notifier("cannot fast-zsmooth: "+t)}u.markTime("start convert x&y");var a,l,c,y,b,x,_,w,k=f.getFromId(t,e.xaxis||"x"),A=f.getFromId(t,e.yaxis||"y"),M=h.traceIs(e,"contour"),T=h.traceIs(e,"histogram"),E=M?"best":e.zsmooth;if(k._minDtick=0,A._minDtick=0,u.markTime("done convert x&y"),T){var L=d(t,e);a=L.x,l=L.x0,c=L.dx,y=L.y,b=L.y0,x=L.dy,_=L.z}else g(e)&&v(e,k,A),a=e.x?k.makeCalcdata(e,"x"):[],y=e.y?A.makeCalcdata(e,"y"):[],l=e.x0||0,c=e.dx||1,b=e.y0||0,x=e.dy||1,_=n(e),(M||e.connectgaps)&&(e._emptypoints=s(_),e._interpz=o(_,e._emptypoints,e._interpz));if("fast"===E)if("log"===k.type||"log"===A.type)r("log axis found");else if(!T){if(a.length){var S=(a[a.length-1]-a[0])/(a.length-1),C=Math.abs(S/100);for(w=0;wC){r("x scale is not linear");break}}if(y.length&&"fast"===E){var z=(y[y.length-1]-y[0])/(y.length-1),P=Math.abs(z/100);for(w=0;wP){r("y scale is not linear");break}}}var R=m(_),O="scaled"===e.xtype?"":e.x,I=i(e,O,l,c,R,k),N="scaled"===e.ytype?"":e.y,j=i(e,N,b,x,_.length,A);f.expand(k,I),f.expand(A,j);var F={x:I,y:j,z:_};if(p(e,_,"","z"),M&&e.contours&&"heatmap"===e.contours.coloring){var D="contour"===e.type?"heatmap":"histogram2d";F.xfill=i(D,O,l,c,R,k),F.yfill=i(D,N,b,x,_.length,A)}return[F]};var y=.01,b=[[-1,0],[1,0],[0,-1],[0,1]]},{"../../components/colorscale/calc":310,"../../lib":381,"../../plots/cartesian/axes":403,"../../plots/plots":452,"../histogram2d/calc":531,"./convert_column_xyz":513,"./has_columns":515,"./max_row_length":518,"fast-isnumeric":117}],512:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,c="cb"+r.uid,u=s(r.colorscale),f=r.zmin,h=r.zmax;if(i(f)||(f=a.aggNums(Math.min,null,r.z)),i(h)||(h=a.aggNums(Math.max,null,r.z)),t._fullLayout._infolayer.selectAll("."+c).remove(),!r.showscale)return void o.autoMargin(t,c);var d=e[0].t.cb=l(t,c);d.fillcolor(n.scale.linear().domain(u.map(function(t){return f+t[0]*(h-f)})).range(u.map(function(t){return t[1]}))).filllevels({start:f,end:h,size:(h-f)/254}).options(r.colorbar)(),a.markTime("done colorbar")}},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":314,"../../lib":381,"../../plots/plots":452,d3:113,"fast-isnumeric":117}],513:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a=t.x.slice(),o=t.y.slice(),s=t.z,l=t.text,c=Math.min(a.length,o.length,s.length),u=void 0!==l&&!Array.isArray(l[0]);for(ci;i++)a[i]=e.d2c(a[i]),o[i]=r.d2c(o[i]);var f,h,d,p=n.distinctVals(a),g=p.vals,v=n.distinctVals(o),m=v.vals,y=n.init2dArray(m.length,g.length);for(u&&(d=n.init2dArray(m.length,g.length)),i=0;c>i;i++)f=n.findBin(a[i]+p.minDiff/2,g),h=n.findBin(o[i]+v.minDiff/2,m),y[h][f]=s[i],u&&(d[h][f]=l[i]);t.x=g,t.y=m,t.z=y,u&&(t.text=d)}},{"../../lib":381}],514:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./has_columns"),a=t("./xyz_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function c(r,i){return n.coerce(t,e,s,r,i)}var u=a(t,e,c);return u?(c("text"),c("zsmooth"),c("connectgaps",i(e)&&e.zsmooth!==!1),void o(t,e,l,c,{prefix:"",cLetter:"z"})):void(e.visible=!1)}},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":510,"./has_columns":515,"./xyz_defaults":521}],515:[function(t,e,r){"use strict";e.exports=function(t){return!Array.isArray(t.z[0])}},{}],516:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../lib");e.exports=function(t,e,r,a,o){if(!(t.distancec||c>=m[0].length||0>u||u>m.length)return}else{if(n.inbox(e-g[0],e-g[g.length-1])>n.MAXDIST||n.inbox(r-v[0],r-v[v.length-1])>n.MAXDIST)return;if(o){var w;for(b=[2*g[0]-g[1]],w=1;w0;)_=v.c2p(C[M]),M--;for(x>_&&(w=_,_=x,x=w,N=!0),M=0;void 0===k&&M0;)A=m.c2p(z[M]),M--;if(k>A&&(w=k,k=A,A=w,j=!0),P&&(C=r[0].xfill,z=r[0].yfill),"fast"!==R){var F="best"===R?0:.5;x=Math.max(-F*v._length,x),_=Math.min((1+F)*v._length,_),k=Math.max(-F*m._length,k),A=Math.min((1+F)*m._length,A)}var D=Math.round(_-x),B=Math.round(A-k);if(!(0>=D||0>=B)){var U,V;"fast"===R?(U=I,V=O):(U=D,V=B);var q=document.createElement("canvas");q.width=U,q.height=V;var H,G,Y=q.getContext("2d"),X=i.scale.linear().domain(S.map(function(t){return t[0]})).range(S.map(function(t){var e=a(t[1]).toRgb();return[e.r,e.g,e.b,e.a]})).clamp(!0);"fast"===R?(H=N?function(t){return I-1-t}:o.identity,G=j?function(t){return O-1-t}:o.identity):(H=function(t){return o.constrain(Math.round(v.c2p(C[t])-x),0,D)},G=function(t){return o.constrain(Math.round(m.c2p(z[t])-k),0,B)});var W,Z,K,$,Q,J,tt=G(0),et=[tt,tt],rt=N?0:1,nt=j?0:1,it=0,at=0,ot=0,st=0;if(o.markTime("done init png"),R){var lt=0,ct=new Uint8Array(D*B*4);if("best"===R){var ut,ft,ht,dt=new Array(C.length),pt=new Array(z.length),gt=new Array(D);for(M=0;MM;M++)gt[M]=n(M,dt);for(Z=0;B>Z;Z++)for(ut=n(Z,pt),ft=T[ut.bin0],ht=T[ut.bin1],M=0;D>M;M++,lt+=4)J=d(ft,ht,gt[M],ut),h(ct,lt,J)}else for(Z=0;O>Z;Z++)for(Q=T[Z],et=G(Z),M=0;D>M;M++)J=f(Q[M],1),lt=4*(et*D+H(M)),h(ct,lt,J);var vt=Y.createImageData(D,B);vt.data.set(ct),Y.putImageData(vt,0,0)}else for(Z=0;O>Z;Z++)if(Q=T[Z],et.reverse(),et[nt]=G(Z+1),et[0]!==et[1]&&void 0!==et[0]&&void 0!==et[1])for(K=H(0),W=[K,K],M=0;I>M;M++)W.reverse(),W[rt]=H(M+1),W[0]!==W[1]&&void 0!==W[0]&&void 0!==W[1]&&($=Q[M],J=f($,(W[1]-W[0])*(et[1]-et[0])),Y.fillStyle="rgba("+J.join(",")+")",Y.fillRect(W[0],et[0],W[1]-W[0],et[1]-et[0]));o.markTime("done filling png"),at=Math.round(at/it),ot=Math.round(ot/it),st=Math.round(st/it);var mt=a("rgb("+at+","+ot+","+st+")");t._hmpixcount=(t._hmpixcount||0)+it,t._hmlumcount=(t._hmlumcount||0)+it*mt.getLuminance();var yt=e.plot.select(".imagelayer").selectAll("g.hm."+b).data([0]);yt.enter().append("g").classed("hm",!0).classed(b,!0),yt.exit().remove();var bt=yt.selectAll("image").data(r);bt.enter().append("svg:image"),bt.exit().remove(),bt.attr({xmlns:c.svg,"xlink:href":q.toDataURL("image/png"),height:B,width:D,x:x,y:k,preserveAspectRatio:"none"}),o.markTime("done showing png")}}var i=t("d3"),a=t("tinycolor2"),o=t("../../lib"),s=t("../../plots/plots"),l=t("../../components/colorscale/get_scale"),c=t("../../constants/xmlns_namespaces"),u=t("./max_row_length");e.exports=function(t,e,r){for(var i=0;i0&&(n=!0);for(var s=0;si;i++)e[i]?(t[i]/=e[i],n+=t[i]):t[i]=null;return n}},{}],524:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){var e=r(t+"bins.start"),n=r(t+"bins.end"),i=r("autobin"+t,!(e&&n));r(i?"nbins"+t:t+"bins.size")}),e}},{}],525:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,i){var a=i[e];return n(a)?(a=Number(a),r[t]+=a,a):0},avg:function(t,e,r,i,a){var o=i[e];return n(o)&&(o=Number(o),r[t]+=o,a[t]++),0},min:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]>a)return r[t]=a,a-r[t]}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]r&&c.length<5e3;)g=a.tickIncrement(r,b.size),c.push((r+g)/2),u.push(S),x&&_.push(r),E&&w.push(1/(g-r)),P&&k.push(0),r=g;var R=u.length;for(r=0;r=0&&R>m&&(A+=C(m,r,u,y,k));P&&(A=l(u,k)),z&&z(u,A,w);var O=Math.min(c.length,u.length),I=[],N=0,j=O-1;for(r=0;O>r;r++)if(u[r]){N=r;break}for(r=O-1;r>N;r--)if(u[r]){j=r;break}for(r=N;j>=r;r++)n(c[r])&&n(u[r])&&I.push({p:c[r],s:u[r],b:0});return I}}},{"../../lib":381,"../../plots/cartesian/axes":403,"./average":523,"./bin_functions":525,"./norm_functions":529,"fast-isnumeric":117}],527:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("./bin_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,c){function u(r,i){return n.coerce(t,e,l,r,i)}var f=u("x"),h=u("y");u("text");var d=u("orientation",h&&!f?"h":"v"),p=e["v"===d?"x":"y"];if(!p||!p.length)return void(e.visible=!1);var g=e["h"===d?"x":"y"];g&&u("histfunc");var v="h"===d?["y"]:["x"];a(t,e,u,v),o(t,e,u,r,c),s(t,e,i.defaultLine,{axis:"y"}),s(t,e,i.defaultLine,{axis:"x",inherit:"y"})}},{"../../components/color":303,"../../components/errorbars/defaults":330,"../../lib":381,"../bar/style_defaults":484,"./attributes":522,"./bin_defaults":524}],528:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.style=t("../bar/style"),n.colorbar=t("../scatter/colorbar"),n.hoverPoints=t("../bar/hover"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":411,"../bar/hover":477,"../bar/layout_attributes":479,"../bar/layout_defaults":480,"../bar/plot":481,"../bar/set_positions":482,"../bar/style":483,"../scatter/colorbar":557,"./attributes":522,"./calc":526,"./defaults":527}],529:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,i=0;r>i;i++)t[i]*=n},probability:function(t,e){for(var r=t.length,n=0;r>n;n++)t[n]/=e},density:function(t,e,r,n){var i=t.length;n=n||1;for(var a=0;i>a;a++)t[a]*=r[a]*n},"probability density":function(t,e,r,n){var i=t.length;n&&(e/=n);for(var a=0;i>a;a++)t[a]*=r[a]/e}}},{}],530:[function(t,e,r){"use strict";var n=t("../histogram/attributes"),i=t("../heatmap/attributes");e.exports={x:n.x,y:n.y,z:{valType:"data_array"},marker:{color:{valType:"data_array"}},histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zauto:i.zauto,zmin:i.zmin,zmax:i.zmax,colorscale:i.colorscale,autocolorscale:i.autocolorscale,reversescale:i.reversescale,showscale:i.showscale,zsmooth:i.zsmooth,_nestedModules:{colorbar:"Colorbar"}}},{"../heatmap/attributes":510,"../histogram/attributes":522}],531:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../histogram/bin_functions"),o=t("../histogram/norm_functions"),s=t("../histogram/average");e.exports=function(t,e){var r,l,c,u,f,h,d=i.getFromId(t,e.xaxis||"x"),p=e.x?d.makeCalcdata(e,"x"):[],g=i.getFromId(t,e.yaxis||"y"),v=e.y?g.makeCalcdata(e,"y"):[],m=Math.min(p.length,v.length);p.length>m&&p.splice(m,p.length-m),v.length>m&&v.splice(m,v.length-m),n.markTime("done convert data"),!e.autobinx&&"xbins"in e||(e.xbins=i.autoBin(p,d,e.nbinsx,"2d"),"histogram2dcontour"===e.type&&(e.xbins.start-=e.xbins.size,e.xbins.end+=e.xbins.size),e._input.xbins=e.xbins),!e.autobiny&&"ybins"in e||(e.ybins=i.autoBin(v,g,e.nbinsy,"2d"),"histogram2dcontour"===e.type&&(e.ybins.start-=e.ybins.size,e.ybins.end+=e.ybins.size),e._input.ybins=e.ybins),n.markTime("done autoBin"),f=[];var y,b,x=[],_=[],w="string"==typeof e.xbins.size?[]:e.xbins,k="string"==typeof e.xbins.size?[]:e.ybins,A=0,M=[],T=e.histnorm,E=e.histfunc,L=-1!==T.indexOf("density"),S="max"===E||"min"===E,C=S?null:0,z=a.count,P=o[T],R=!1,O=[],I=[],N="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";N&&"count"!==E&&(R="avg"===E,z=a[E]);var j=e.xbins,F=j.end+(j.start-i.tickIncrement(j.start,j.size))/1e6;for(h=j.start;F>h;h=i.tickIncrement(h,j.size))x.push(C),Array.isArray(w)&&w.push(h),R&&_.push(0);Array.isArray(w)&&w.push(h);var D=x.length;for(r=e.xbins.start,l=(h-r)/D,r+=l/2,j=e.ybins,F=j.end+(j.start-i.tickIncrement(j.start,j.size))/1e6,h=j.start;F>h;h=i.tickIncrement(h,j.size))f.push(x.concat()),Array.isArray(k)&&k.push(h),R&&M.push(_.concat());Array.isArray(k)&&k.push(h);var B=f.length;for(c=e.ybins.start,u=(h-c)/B,c+=u/2,L&&(O=x.map(function(t,e){return Array.isArray(w)?1/(w[e+1]-w[e]):1/l}),I=f.map(function(t,e){return Array.isArray(k)?1/(k[e+1]-k[e]):1/u})),n.markTime("done making bins"),h=0;m>h;h++)y=n.findBin(p[h],w),b=n.findBin(v[h],k),y>=0&&D>y&&b>=0&&B>b&&(A+=z(y,h,f[b],N,M[b]));if(R)for(b=0;B>b;b++)A+=s(f[b],M[b]);if(P)for(b=0;B>b;b++)P(f[b],A,O,I[b]);return n.markTime("done binning"),{x:p,x0:r,dx:l,y:v,y0:c,dy:u,z:f}}},{"../../lib":381,"../../plots/cartesian/axes":403,"../histogram/average":523,"../histogram/bin_functions":525,"../histogram/norm_functions":529}],532:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./sample_defaults"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r){function s(r,i){return n.coerce(t,e,o,r,i)}i(t,e,s),s("zsmooth"),a(t,e,r,s,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":530,"./sample_defaults":534}],533:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../heatmap/calc"),n.plot=t("../heatmap/plot"),n.colorbar=t("../heatmap/colorbar"),n.style=t("../heatmap/style"),n.hoverPoints=t("../heatmap/hover"),n.moduleType="trace",n.name="histogram2d",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":411,"../heatmap/calc":511,"../heatmap/colorbar":512,"../heatmap/hover":516,"../heatmap/plot":519,"../heatmap/style":520,"./attributes":530,"./defaults":532}],534:[function(t,e,r){"use strict";var n=t("../histogram/bin_defaults");e.exports=function(t,e,r){var i=r("x"),a=r("y");if(!(i&&i.length&&a&&a.length))return void(e.visible=!1);var o=r("z")||r("marker.color");o&&r("histfunc");var s=["x","y"];n(t,e,r,s)}},{"../histogram/bin_defaults":524}],535:[function(t,e,r){"use strict";var n=t("../histogram2d/attributes"),i=t("../contour/attributes");e.exports={x:n.x,y:n.y,z:n.z,marker:n.marker,histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zauto:i.zauto,zmin:i.zmin,zmax:i.zmax,colorscale:i.colorscale,autocolorscale:i.autocolorscale,reversescale:i.reversescale,showscale:i.showscale,autocontour:i.autocontour,ncontours:i.ncontours,contours:i.contours,line:i.line,_nestedModules:{colorbar:"Colorbar"}}},{"../contour/attributes":500,"../histogram2d/attributes":530}],536:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../histogram2d/sample_defaults"),a=t("../contour/style_defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}i(t,e,l);var c=n.coerce2(t,e,o,"contours.start"),u=n.coerce2(t,e,o,"contours.end"),f=l("autocontour",!(c&&u));l(f?"ncontours":"contours.size"),a(t,e,l,s)}},{"../../lib":381,"../contour/style_defaults":509,"../histogram2d/sample_defaults":534,"./attributes":535}],537:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../contour/calc"),n.plot=t("../contour/plot"),n.style=t("../contour/style"),n.colorbar=t("../contour/colorbar"),n.hoverPoints=t("../contour/hover"),n.moduleType="trace",n.name="histogram2dcontour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","contour","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":411,"../contour/calc":501,"../contour/colorbar":502,"../contour/hover":504,"../contour/plot":507,"../contour/style":508,"./attributes":535,"./defaults":536}],538:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../surface/attributes"),a=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},i:{valType:"data_array"},j:{valType:"data_array"},k:{valType:"data_array"},delaunayaxis:{valType:"enumerated",values:["x","y","z"],dflt:"z"},alphahull:{valType:"number",dflt:-1},intensity:{valType:"data_array"},color:{valType:"color"},vertexcolor:{valType:"data_array"},facecolor:{valType:"data_array"},opacity:a({},i.opacity),flatshading:{valType:"boolean",dflt:!1},contour:{show:a({},i.contours.x.show,{}),color:a({},i.contours.x.color),width:a({},i.contours.x.width)},colorscale:n.colorscale,reversescale:n.reversescale,showscale:n.showscale,lightposition:{x:a({},i.lightposition.x,{dflt:1e5}),y:a({},i.lightposition.y,{dflt:1e5}),z:a({},i.lightposition.z,{dflt:0})},lighting:a({},{vertexnormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-12},facenormalsepsilon:{valType:"number",min:0,max:1,dflt:1e-6}},i.lighting),_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":309,"../../lib/extend":376,"../surface/attributes":599}],539:[function(t,e,r){"use strict";function n(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.color="#fff",this.data=null,this.showContour=!1}function i(t){return t.map(function(t){var e=t[0],r=c(t[1]),n=r.toRgb();return{index:e,rgb:[n.r,n.g,n.b,1]}})}function a(t){return t.map(d)}function o(t,e,r){for(var n=new Array(t.length),i=0;i0)s=f(t.alphahull,l);else{var c=["x","y","z"].indexOf(t.delaunayaxis);s=u(l.map(function(t){return[t[(c+1)%3],t[(c+2)%3]]}))}var p={positions:l,cells:s,lightPosition:[t.lightposition.x,t.lightposition.y,t.lightposition.z],ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,vertexNormalsEpsilon:t.lighting.vertexnormalsepsilon,faceNormalsEpsilon:t.lighting.facenormalsepsilon,opacity:t.opacity,contourEnable:t.contour.show,contourColor:d(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",p.vertexIntensity=t.intensity,p.colormap=i(t.colorscale)):t.vertexcolor?(this.color=t.vertexcolors[0],p.vertexColors=a(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],p.cellColors=a(t.facecolor)):(this.color=t.color,p.meshColor=d(t.color)),this.mesh.update(p)},p.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=s},{"../../lib/str2rgbarray":392,"alpha-shape":40,"convex-hull":102,"delaunay-triangulate":114,"gl-mesh3d":150,tinycolor2:274}],540:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorbar/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}function l(t){var e=t.map(function(t){var e=s(t);return e&&Array.isArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var c=l(["x","y","z"]),u=l(["i","j","k"]);return c?(u&&u.forEach(function(t){for(var e=0;el||(c=p[r],void 0!==c&&""!==c||(c=r),c=String(c),void 0===y[c]&&(y[c]=!0,u=a(e.marker.colors[r]),u.isValid()?(u=o.addOpacity(u,u.getAlpha()),m[c]||(m[c]=u)):m[c]?u=m[c]:(u=!1,b=!0),f=-1!==_.indexOf(c),f||(x+=l),g.push({v:l,label:c,color:u,i:r,hidden:f}))));if(e.sort&&g.sort(function(t,e){return e.v-t.v}),b)for(r=0;r")}return g};var l},{"../../components/color":303,"./helpers":546,"fast-isnumeric":117,tinycolor2:274}],545:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}var s=n.coerceFont,l=o("values");if(!Array.isArray(l)||!l.length)return void(e.visible=!1);var c=o("labels");Array.isArray(c)||(o("label0"),o("dlabel"));var u=o("marker.line.width");u&&o("marker.line.color");var f=o("marker.colors");Array.isArray(f)||(e.marker.colors=[]),o("scalegroup");var h=o("text"),d=o("textinfo",Array.isArray(h)?"text+percent":"percent");if(o("hoverinfo",1===a._dataLength?"label+text+value+percent":void 0),d&&"none"!==d){var p=o("textposition"),g=Array.isArray(p)||"auto"===p,v=g||"inside"===p,m=g||"outside"===p;if(v||m){var y=s(o,"textfont",a.font);v&&s(o,"insidetextfont",y),m&&s(o,"outsidetextfont",y)}}o("domain.x"),o("domain.y"),o("hole"),o("sort"),o("direction"),o("rotation"),o("pull")}},{"../../lib":381,"./attributes":542}],546:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)}},{"../../lib":381}],547:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":542,"./base_plot":543,"./calc":544,"./defaults":545,"./layout_attributes":548,"./layout_defaults":549,"./plot":550,"./style":551,"./style_one":552}],548:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array"}}},{}],549:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e){function r(r,a){return n.coerce(t,e,i,r,a)}r("hiddenlabels")}},{"../../lib":381,"./layout_attributes":548}],550:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,o=Math.PI*Math.min(e.v/r.vTotal,.5),s=1-r.trace.hole,l=i(e,r),c={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(c.scale>=1)return c;var u=a+1/(2*Math.tan(o)),f=r.r*Math.min(1/(Math.sqrt(u*u+.5)+u),s/(Math.sqrt(a*a+s/2)+a)),h={scale:2*f/t.height,rCenter:Math.cos(f/r.r)-f*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},d=1/a,p=d+1/(2*Math.tan(o)),g=r.r*Math.min(1/(Math.sqrt(p*p+.5)+p),s/(Math.sqrt(d*d+s/2)+d)),v={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},m=v.scale>h.scale?v:h;return c.scale<1&&m.scale>c.scale?m:c}function i(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function a(t,e){var r=e.pxmid[0],n=e.pxmid[1],i=t.width/2,a=t.height/2;return 0>r&&(i*=-1),0>n&&(a*=-1),{scale:1,rCenter:1,rotate:0,x:i+Math.abs(a)*(i>0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}function o(t,e){function r(t,e){return t.pxmid[1]-e.pxmid[1]}function n(t,e){return e.pxmid[1]-t.pxmid[1]}function i(t,r){r||(r={});var n,i,a,s,h,d,g=r.labelExtraY+(o?r.yLabelMax:r.yLabelMin),v=o?t.yLabelMin:t.yLabelMax,m=o?t.yLabelMax:t.yLabelMin,y=t.cyFinal+c(t.px0[1],t.px1[1]),b=g-v;if(b*f>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(i=0;i=e.pull[a.i]||((t.pxmid[1]-a.pxmid[1])*f>0?(s=a.cyFinal+c(a.px0[1],a.px1[1]),b=s-v-t.labelExtraY,b*f>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-y)*f>0&&(n=3*u*Math.abs(i-p.indexOf(t)),h=a.cxFinal+l(a.px0[0],a.px1[0]),d=h+n-(t.cxFinal+t.pxmid[0])-t.labelExtraX,d*u>0&&(t.labelExtraX+=d)))}var a,o,s,l,c,u,f,h,d,p,g,v,m;for(o=0;2>o;o++)for(s=o?r:n,c=o?Math.max:Math.min,f=o?1:-1,a=0;2>a;a++){for(l=a?Math.max:Math.min,u=a?1:-1,h=t[o][a],h.sort(s),d=t[1-o][a],p=d.concat(h),v=[],g=0;gu&&(u=s.pull[a]);o.r=Math.min(r/c(s.tilt,Math.sin(l),s.depth),n/c(s.tilt,Math.cos(l),s.depth))/(2+2*u),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===d.indexOf(s.scalegroup)&&d.push(s.scalegroup)}for(a=0;af.vTotal/2?1:0)}function c(t,e,r){if(!t)return 1;var n=Math.sin(t*Math.PI/180);return Math.max(.01,r*n*Math.abs(e)+2*Math.sqrt(1-n*n*e*e))}var u=t("d3"),f=t("../../plots/cartesian/graph_interact"),h=t("../../components/color"),d=t("../../components/drawing"),p=t("../../lib/svg_text_utils"),g=t("./helpers");e.exports=function(t,e){var r=t._fullLayout;s(e,r._size);var c=r._pielayer.selectAll("g.trace").data(e);c.enter().append("g").attr({"stroke-linejoin":"round","class":"trace"}),c.exit().remove(),c.order(),c.each(function(e){var s=u.select(this),c=e[0],v=c.trace,m=0,y=(v.depth||0)*c.r*Math.sin(m)/2,b=v.tiltaxis||0,x=b*Math.PI/180,_=[y*Math.sin(x),y*Math.cos(x)],w=c.r*Math.cos(m),k=s.selectAll("g.part").data(v.tilt?["top","sides"]:["top"]);k.enter().append("g").attr("class",function(t){return t+" part"}),k.exit().remove(),k.order(),l(e),s.selectAll(".top").each(function(){var s=u.select(this).selectAll("g.slice").data(e);s.enter().append("g").classed("slice",!0),s.exit().remove();var l=[[[],[]],[[],[]]],m=!1;s.each(function(o){function s(e){var n=t._fullLayout,a=t._fullData[v.index],s=a.hoverinfo;if("all"===s&&(s="label+text+value+percent+name"),!t._dragging&&n.hovermode!==!1&&"none"!==s&&s){var l=i(o,c),u=k+o.pxmid[0]*(1-l),h=A+o.pxmid[1]*(1-l),d=r.separators,p=[]; +-1!==s.indexOf("label")&&p.push(o.label),a.text&&a.text[o.i]&&-1!==s.indexOf("text")&&p.push(a.text[o.i]),-1!==s.indexOf("value")&&p.push(g.formatPieValue(o.v,d)),-1!==s.indexOf("percent")&&p.push(g.formatPiePercent(o.v/c.vTotal,d)),f.loneHover({x0:u-l*c.r,x1:u+l*c.r,y:h,text:p.join("
"),name:-1!==s.indexOf("name")?a.name:void 0,color:o.color,idealAlign:o.pxmid[0]<0?"left":"right"},{container:n._hoverlayer.node(),outerContainer:n._paper.node()}),f.hover(t,e,"pie"),E=!0}}function h(e){t.emit("plotly_unhover",{points:[e]}),E&&(f.loneUnhover(r._hoverlayer.node()),E=!1)}function y(){t._hoverdata=[o],t._hoverdata.trace=e.trace,f.click(t,{target:!0})}function x(t,e,r,n){return"a"+n*c.r+","+n*w+" "+b+" "+o.largeArc+(r?" 1 ":" 0 ")+n*(e[0]-t[0])+","+n*(e[1]-t[1])}if(o.hidden)return void u.select(this).selectAll("path,g").remove();l[o.pxmid[1]<0?0:1][o.pxmid[0]<0?0:1].push(o);var k=c.cx+_[0],A=c.cy+_[1],M=u.select(this),T=M.selectAll("path.surface").data([o]),E=!1;if(T.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),M.select("path.textline").remove(),M.on("mouseover",s).on("mouseout",h).on("click",y),v.pull){var L=+(Array.isArray(v.pull)?v.pull[o.i]:v.pull)||0;L>0&&(k+=L*o.pxmid[0],A+=L*o.pxmid[1])}o.cxFinal=k,o.cyFinal=A;var S=v.hole;if(o.v===c.vTotal){var C="M"+(k+o.px0[0])+","+(A+o.px0[1])+x(o.px0,o.pxmid,!0,1)+x(o.pxmid,o.px0,!0,1)+"Z";S?T.attr("d","M"+(k+S*o.px0[0])+","+(A+S*o.px0[1])+x(o.px0,o.pxmid,!1,S)+x(o.pxmid,o.px0,!1,S)+"Z"+C):T.attr("d",C)}else{var z=x(o.px0,o.px1,!0,1);if(S){var P=1-S;T.attr("d","M"+(k+S*o.px1[0])+","+(A+S*o.px1[1])+x(o.px1,o.px0,!1,S)+"l"+P*o.px0[0]+","+P*o.px0[1]+z+"Z")}else T.attr("d","M"+k+","+A+"l"+o.px0[0]+","+o.px0[1]+z+"Z")}var R=Array.isArray(v.textposition)?v.textposition[o.i]:v.textposition,O=M.selectAll("g.slicetext").data(o.text&&"none"!==R?[0]:[]);O.enter().append("g").classed("slicetext",!0),O.exit().remove(),O.each(function(){var t=u.select(this).selectAll("text").data([0]);t.enter().append("text").attr("data-notex",1),t.exit().remove(),t.text(o.text).attr({"class":"slicetext",transform:"","data-bb":"","text-anchor":"middle",x:0,y:0}).call(d.font,"outside"===R?v.outsidetextfont:v.insidetextfont).call(p.convertToTspans),t.selectAll("tspan.line").attr({x:0,y:0});var e,r=d.bBox(t.node());"outside"===R?e=a(r,o):(e=n(r,o,c),"auto"===R&&e.scale<1&&(t.call(d.font,v.outsidetextfont),v.outsidetextfont.family===v.insidetextfont.family&&v.outsidetextfont.size===v.insidetextfont.size||(t.attr({"data-bb":""}),r=d.bBox(t.node())),e=a(r,o)));var i=k+o.pxmid[0]*e.rCenter+(e.x||0),s=A+o.pxmid[1]*e.rCenter+(e.y||0);e.outside&&(o.yLabelMin=s-r.height/2,o.yLabelMid=s,o.yLabelMax=s+r.height/2,o.labelExtraX=0,o.labelExtraY=0,m=!0),t.attr("transform","translate("+i+","+s+")"+(e.scale<1?"scale("+e.scale+")":"")+(e.rotate?"rotate("+e.rotate+")":"")+"translate("+-(r.left+r.right)/2+","+-(r.top+r.bottom)/2+")")})}),m&&o(l,v),s.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=u.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var n=t.cxFinal+t.pxmid[0],i=t.cyFinal+t.pxmid[1],a="M"+n+","+i,o=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],l=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);a+=Math.abs(s)>Math.abs(l)?"l"+l*t.pxmid[0]/t.pxmid[1]+","+l+"H"+(n+t.labelExtraX+o):"l"+t.labelExtraX+","+s+"v"+(l-s)+"h"+o}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+o;e.append("path").classed("textline",!0).call(h.stroke,v.outsidetextfont.color).attr({"stroke-width":Math.min(2,v.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){c.selectAll("tspan").each(function(){var t=u.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":303,"../../components/drawing":325,"../../lib/svg_text_utils":393,"../../plots/cartesian/graph_interact":410,"./helpers":546,d3:113}],551:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0],r=e.trace,a=n.select(this);a.style({opacity:r.opacity}),a.selectAll(".top path.surface").each(function(t){n.select(this).call(i,t,r)})})}},{"./style_one":552,d3:113}],552:[function(t,e,r){"use strict";var n=t("../../components/color");e.exports=function(t,e,r){var i=r.marker.line.color;Array.isArray(i)&&(i=i[e.i]||n.defaultLine);var a=r.marker.line.width||0;Array.isArray(a)&&(a=a[e.i]||0),t.style({"stroke-width":a,fill:e.color}).call(n.stroke,i)}},{"../../components/color":303}],553:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){var e=t[0].trace,r=e.marker;if(n.mergeArray(e.text,t,"tx"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf")),r&&r.line){var i=r.line;n.mergeArray(r.opacity,t,"mo"),n.mergeArray(r.symbol,t,"mx"),n.mergeArray(r.color,t,"mc"),n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw")}}},{"../../lib":381}],554:[function(t,e,r){"use strict";var n=t("../../components/drawing");t("./constants");e.exports={x:{valType:"data_array"},x0:{valType:"any",dflt:0},dx:{valType:"number",dflt:1},y:{valType:"data_array"},y0:{valType:"any",dflt:0},dy:{valType:"number",dflt:1},text:{valType:"string",dflt:"",arrayOk:!0},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"]},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear"},smoothing:{valType:"number",min:0,max:1.3,dflt:1},dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid"}},connectgaps:{valType:"boolean",dflt:!1},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none"},fillcolor:{valType:"color"},marker:{symbol:{valType:"enumerated",values:n.symbolList,dflt:"circle",arrayOk:!0},opacity:{valType:"number",min:0,max:1,arrayOk:!0},size:{valType:"number",min:0,dflt:6,arrayOk:!0},color:{valType:"color",arrayOk:!0},maxdisplayed:{valType:"number",min:0,dflt:0},sizeref:{valType:"number",dflt:1},sizemin:{valType:"number",min:0,dflt:0},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter"},colorscale:{valType:"colorscale"},cauto:{valType:"boolean",dflt:!0},cmax:{valType:"number",dflt:null},cmin:{valType:"number",dflt:null},autocolorscale:{valType:"boolean",dflt:!0},reversescale:{valType:"boolean",dflt:!1},showscale:{valType:"boolean",dflt:!1},line:{color:{valType:"color",arrayOk:!0},width:{valType:"number",min:0,arrayOk:!0},colorscale:{valType:"colorscale"},cauto:{valType:"boolean",dflt:!0},cmax:{valType:"number",dflt:null},cmin:{valType:"number",dflt:null},autocolorscale:{valType:"boolean",dflt:!0},reversescale:{valType:"boolean",dflt:!1}}},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0},textfont:{family:{valType:"string",noBlank:!0,strict:!0,arrayOk:!0},size:{valType:"number",min:1,arrayOk:!0},color:{valType:"color",arrayOk:!0}},r:{valType:"data_array"},t:{valType:"data_array"},_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/drawing":325,"./constants":558}],555:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./subtypes"),s=t("./marker_colorscale_calc");e.exports=function(t,e){var r=i.getFromId(t,e.xaxis||"x"),l=i.getFromId(t,e.yaxis||"y");a.markTime("in Scatter.calc");var c=r.makeCalcdata(e,"x");a.markTime("finished convert x");var u=l.makeCalcdata(e,"y");a.markTime("finished convert y");var f,h,d,p=Math.min(c.length,u.length);r._minDtick=0,l._minDtick=0,c.length>p&&c.splice(p,c.length-p),u.length>p&&u.splice(p,u.length-p);var g={padded:!0},v={padded:!0};if(o.hasMarkers(e)){if(f=e.marker,h=f.size,Array.isArray(h)){var m={type:"linear"};i.setConvert(m),h=m.makeCalcdata(e.marker,"size"),h.length>p&&h.splice(p,h.length-p)}var y,b=1.6*(e.marker.sizeref||1);y="area"===e.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/b),3)}:function(t){return Math.max((t||0)/b,3)},g.ppad=v.ppad=Array.isArray(h)?h.map(y):y(h)}s(e),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||c[0]===c[p-1]&&u[0]===u[p-1]?e.error_y.visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(o.hasMarkers(e)||o.hasText(e))||(g.padded=!1,g.ppad=0):g.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||c[0]===c[p-1]&&u[0]===u[p-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(v.padded=!1):v.tozero=!0,a.markTime("ready for Axes.expand"),i.expand(r,c,g),a.markTime("done expand x"),i.expand(l,u,v),a.markTime("done expand y");var x=new Array(p);for(d=0;p>d;d++)x[d]=n(c[d])&&n(u[d])?{x:c[d],y:u[d]}:{x:!1,y:!1};return void 0!==typeof h&&a.mergeArray(h,x,"ms"),t.firstscatter=!1,x}},{"../../lib":381,"../../plots/cartesian/axes":403,"./marker_colorscale_calc":568,"./subtypes":573,"fast-isnumeric":117}],556:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i,a;for(e=0;e=0;i--)if(a=t[i],"scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}},{}],557:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,c=r.marker,u="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+u).remove(),void 0===c||!c.showscale)return void o.autoMargin(t,u);var f=s(c.colorscale),h=c.color,d=c.cmin,p=c.cmax;i(d)||(d=a.aggNums(Math.min,null,h)),i(p)||(p=a.aggNums(Math.max,null,h));var g=e[0].t.cb=l(t,u);g.fillcolor(n.scale.linear().domain(f.map(function(t){return d+t[0]*(p-d)})).range(f.map(function(t){return t[1]}))).filllevels({start:d,end:p,size:(p-d)/254}).options(c.colorbar)(),a.markTime("done colorbar")}},{"../../components/colorbar/draw":306,"../../components/colorscale/get_scale":314,"../../lib":381,"../../plots/plots":452,d3:113,"fast-isnumeric":117}],558:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20}},{}],559:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./attributes"),a=t("./constants"),o=t("./subtypes"),s=t("./xy_defaults"),l=t("./marker_defaults"),c=t("./line_defaults"),u=t("./line_shape_defaults"),f=t("./text_defaults"),h=t("./fillcolor_defaults"),d=t("../../components/errorbars/defaults");e.exports=function(t,e,r,p){function g(r,a){return n.coerce(t,e,i,r,a)}var v=s(t,e,g),m=vi(f))break;l=f,y=g[0]*p[0]+g[1]*p[1],y>v?(v=y,c=f,d=!1):m>y&&(m=y,u=f,d=!0)}if(d?(C[z++]=c,l!==u&&(C[z++]=u)):(u!==s&&(C[z++]=u),l!==c&&(C[z++]=c)),C[z++]=l,o>=t.length||!f)break;C[z++]=f,s=f}}else C[z++]=c}E.push(C.slice(0,z))}return E}},{"../../plots/cartesian/axes":403}],566:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=r("line.shape");"spline"===n&&r("line.smoothing")}},{}],567:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t){var e=t.marker,r=e.sizeref||1,i=e.sizemin||0,a="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=a(t/2);return n(e)&&e>0?Math.max(e,i):0}}},{"fast-isnumeric":117}],568:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t){if(a.hasMarkers(t)){var e=t.marker;n(t,"marker")&&i(t,e.color,"marker","c"),n(t,"marker.line")&&i(t,e.line.color,"marker.line","c")}}},{"../../components/colorscale/calc":310,"../../components/colorscale/has_colorscale":315,"./subtypes":573}],569:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l){var c,u=o.isBubble(t),f=(t.line||{}).color;f&&(r=f),l("marker.symbol"),l("marker.opacity",u?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),c=f&&e.marker.color!==f?f:u?n.background:n.defaultLine,l("marker.line.color",c),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",u?1:0),u&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode"))}},{"../../components/color":303,"../../components/colorscale/defaults":312,"../../components/colorscale/has_colorscale":315,"./subtypes":573}],570:[function(t,e,r){"use strict";function n(t,e,r){var n=e.x(),a=e.y(),o=i.extent(n.range.map(n.l2c)),s=i.extent(a.range.map(a.l2c));r.forEach(function(t,e){var n=t[0].trace;if(l.hasMarkers(n)){var i=n.marker.maxdisplayed;if(0!==i){var a=t.filter(function(t){return t.x>=o[0]&&t.x<=o[1]&&t.y>=s[0]&&t.y<=s[1]}),c=Math.ceil(a.length/i),u=0;r.forEach(function(t,r){var n=t[0].trace;l.hasMarkers(n)&&n.marker.maxdisplayed>0&&e>r&&u++});var f=Math.round(u*c/3+Math.floor(u/3)*c/7.1);t.forEach(function(t){delete t.vis}),a.forEach(function(t,e){0===Math.round((e+f)%c)&&(t.vis=!0)})}}})}var i=t("d3"),a=t("../../lib"),o=t("../../components/drawing"),s=t("../../components/errorbars"),l=t("./subtypes"),c=t("./arrays_to_calcdata"),u=t("./line_points");e.exports=function(t,e,r){function f(t){return t.filter(function(t){return t.vis})}n(t,e,r);var h=e.x(),d=e.y(),p=e.plot.select(".scatterlayer").selectAll("g.trace.scatter").data(r);p.enter().append("g").attr("class","trace scatter").style("stroke-miterlimit",2),p.call(s.plot,e);var g,v,m,y,b="";p.each(function(t){var e=t[0].trace,r=e.line,n=i.select(this);if(e.visible===!0&&(v=e.fill.charAt(e.fill.length-1),"x"!==v&&"y"!==v&&(v=""),t[0].node3=n,c(t),l.hasLines(e)||"none"!==e.fill)){var a,s,f,p,x,_="",w="";g="tozero"===e.fill.substr(0,6)||"toself"===e.fill||"to"===e.fill.substr(0,2)&&!b?n.append("path").classed("js-fill",!0):null,y&&(m=y.datum(t)),y=n.append("path").classed("js-fill",!0),-1!==["hv","vh","hvh","vhv"].indexOf(r.shape)?(f=o.steps(r.shape),p=o.steps(r.shape.split("").reverse().join(""))):f=p="spline"===r.shape?function(t){var e=t[t.length-1];return t[0][0]===e[0]&&t[0][1]===e[1]?o.smoothclosed(t.slice(1),r.smoothing):o.smoothopen(t,r.smoothing)}:function(t){return"M"+t.join("L")},x=function(t){return p(t.reverse())};var k=u(t,{xaxis:h,yaxis:d,connectGaps:e.connectgaps,baseTolerance:Math.max(r.width||1,3)/4,linear:"linear"===r.shape});if(k.length){for(var A=k[0][0],M=k[k.length-1],T=M[M.length-1],E=0;E1&&n.append("path").classed("js-line",!0).attr("d",a)}g?A&&T&&(v?("y"===v?A[1]=T[1]=d.c2p(0,!0):"x"===v&&(A[0]=T[0]=h.c2p(0,!0)),g.attr("d",_+"L"+T+"L"+A+"Z")):g.attr("d",_+"Z")):"tonext"===e.fill.substr(0,6)&&_&&b&&("tonext"===e.fill?m.attr("d",_+"Z"+b+"Z"):m.attr("d",_+"L"+b.substr(1)+"Z")),b=w}}}),p.selectAll("path:not([d])").remove(),p.append("g").attr("class","points").each(function(t){var e=t[0].trace,r=i.select(this),n=l.hasMarkers(e),s=l.hasText(e);!n&&!s||e.visible!==!0?r.remove():(n&&r.selectAll("path.point").data(e.marker.maxdisplayed?f:a.identity).enter().append("path").classed("point",!0).call(o.translatePoints,h,d),s&&r.selectAll("g").data(e.marker.maxdisplayed?f:a.identity).enter().append("g").append("text").call(o.translatePoints,h,d))})}},{"../../components/drawing":325,"../../components/errorbars":331,"../../lib":381,"./arrays_to_calcdata":553,"./line_points":565,"./subtypes":573,d3:113}],571:[function(t,e,r){"use strict";var n=t("./subtypes"),i=.2;e.exports=function(t,e){var r,a,o,s,l=t.cd,c=t.xaxis,u=t.yaxis,f=[],h=l[0].trace,d=h.index,p=h.marker;if(n.hasMarkers(h)||n.hasText(h)){var g=Array.isArray(p.opacity)?1:p.opacity;if(e===!1)for(r=0;rs;s++){for(var l=[[0,0,0],[0,0,0]],c=0;3>c;c++)if(r[c])for(var u=0;2>u;u++)l[u][c]=r[c][s][u];o[s]=l}return o}var o=t("../../components/errorbars/compute_error");e.exports=a},{"../../components/errorbars/compute_error":329}],579:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.linePlot=null,this.scatterPlot=null,this.errorBars=null,this.textMarkers=null,this.delaunayMesh=null,this.color=null,this.mode="",this.dataPoints=[],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.textLabels=null,this.data=null}function i(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;ni;i++){var a=t[i];a&&a.copy_zstyle!==!1&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=b(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}function o(t){var e=[0,0];return Array.isArray(t)?[0,-1]:(t.indexOf("bottom")>=0&&(e[1]+=1),t.indexOf("top")>=0&&(e[1]-=1),t.indexOf("left")>=0&&(e[0]-=1),t.indexOf("right")>=0&&(e[0]+=1),e)}function s(t,e){return e(4*t)}function l(t){return k[t]}function c(t,e,r,n,i){var a=null;if(Array.isArray(t)){a=[];for(var o=0;e>o;o++)void 0===t[o]?a[o]=n:a[o]=r(t[o],i)}else a=r(t,y.identity);return a}function u(t,e){var r,n,i,u,f,h,d=[],p=t.fullSceneLayout,g=t.dataScale,v=p.xaxis,m=p.yaxis,w=p.zaxis,k=e.marker,M=e.line,T=e.x||[],E=e.y||[],L=e.z||[],S=T.length;for(n=0;S>n;n++)i=v.d2l(T[n])*g[0],u=m.d2l(E[n])*g[1],f=w.d2l(L[n])*g[2],d[n]=[i,u,f];if(Array.isArray(e.text))h=e.text;else if(void 0!==e.text)for(h=new Array(S),n=0;S>n;n++)h[n]=e.text;if(r={position:d,mode:e.mode,text:h},"line"in e&&(r.lineColor=b(M.color),r.lineWidth=M.width,r.lineDashes=M.dash),"marker"in e){var C=_(e);r.scatterColor=x(k,1,S),r.scatterSize=c(k.size,S,s,20,C),r.scatterMarker=c(k.symbol,S,l,"\u25cf"),r.scatterLineWidth=k.line.width,r.scatterLineColor=x(k.line,1,S),r.scatterAngle=0}"textposition"in e&&(r.textOffset=o(e.textposition),r.textColor=x(e.textfont,1,S),r.textSize=c(e.textfont.size,S,y.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var z=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;3>n;++n){var P=e.projection[z[n]];(r.project[n]=P.show)&&(r.projectOpacity[n]=P.opacity,r.projectScale[n]=P.scale)}r.errorBounds=A(e,g);var R=a([e.error_x,e.error_y,e.error_z]);return r.errorColor=R.color,r.errorLineWidth=R.lineWidth,r.errorCapSize=R.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=b(e.surfacecolor),r}function f(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}function h(t,e){var r=new n(t,e.uid);return r.update(e),r}var d=t("gl-line3d"),p=t("gl-scatter3d"),g=t("gl-error3d"),v=t("gl-mesh3d"),m=t("delaunay-triangulate"),y=t("../../lib"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/make_bubble_size_func"),w=t("../../constants/gl3d_dashes"),k=t("../../constants/gl_markers"),A=t("./calc_errors"),M=n.prototype;M.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels&&void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel="";var e=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},M.update=function(t){var e,r,n,a,o=this.scene.glplot.gl,s=w.solid;this.data=t;var l=u(this.scene,t);"mode"in l&&(this.mode=l.mode),"lineDashes"in l&&l.lineDashes in w&&(s=w[l.lineDashes]),this.color=f(l.scatterColor)||f(l.lineColor),this.dataPoints=l.position,e={gl:o,position:l.position,color:l.lineColor,lineWidth:l.lineWidth||1,dashes:s[0],dashScale:s[1],opacity:t.opacity,connectGaps:t.connectgaps},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=d(e),this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var c=t.opacity;if(t.marker&&t.marker.opacity&&(c*=t.marker.opacity),r={gl:o,position:l.position,color:l.scatterColor,size:l.scatterSize,glyph:l.scatterMarker,opacity:c,orthographic:!0,lineWidth:l.scatterLineWidth,lineColor:l.scatterLineColor,project:l.project,projectScale:l.projectScale,projectOpacity:l.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=p(r),this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),a={gl:o,position:l.position,glyph:l.text,color:l.textColor,size:l.textSize,angle:l.textAngle,alignment:l.textOffset,font:l.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=l.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(a):(this.textMarkers=p(a),this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:o,position:l.position,color:l.errorColor,error:l.errorBounds,lineWidth:l.errorLineWidth,capSize:l.errorCapSize,opacity:t.opacity},this.errorBars?l.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):l.errorBounds&&(this.errorBars=g(n),this.scene.glplot.add(this.errorBars)),l.delaunayAxis>=0){var h=i(l.position,l.delaunayColor,l.delaunayAxis);h.opacity=t.opacity,this.delaunayMesh?this.delaunayMesh.update(h):(h.gl=o,this.delaunayMesh=v(h),this.scene.glplot.add(this.delaunayMesh))}else this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose(),this.delaunayMesh=null)},M.dispose=function(){this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose()),this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose()),this.errorBars&&(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose()),this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose()),this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose())},e.exports=h},{"../../constants/gl3d_dashes":367,"../../constants/gl_markers":368,"../../lib":381,"../../lib/gl_format_color":379,"../../lib/str2rgbarray":392,"../scatter/make_bubble_size_func":567,"./calc_errors":578,"delaunay-triangulate":114,"gl-error3d":121,"gl-line3d":127,"gl-mesh3d":150,"gl-scatter3d":193}],580:[function(t,e,r){"use strict";function n(t,e,r){var n=0,i=r("x"),a=r("y"),o=r("z");return i&&a&&o&&(n=Math.min(i.length,a.length,o.length),n=0&&h("surfacecolor",p||g);for(var v=["x","y","z"],m=0;3>m;++m){var y="projection."+v[m];h(y+".show")&&(h(y+".opacity"),h(y+".scale"))}c(t,e,r,{axis:"z"}),c(t,e,r,{axis:"y",inherit:"z"}),c(t,e,r,{axis:"x",inherit:"z"})}},{"../../components/errorbars/defaults":330,"../../lib":381,"../scatter/line_defaults":564,"../scatter/marker_defaults":569,"../scatter/subtypes":573,"../scatter/text_defaults":574,"./attributes":576}],581:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../constants/gl_markers":368,"../../plots/gl3d":439,"../scatter/colorbar":557,"./attributes":576,"./calc":577,"./convert":579,"./defaults":580}],582:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=n.line,l=o.line;e.exports={lon:{valType:"data_array"},lat:{valType:"data_array"},locations:{valType:"data_array"},locationmode:{valType:"enumerated",values:["ISO-3","USA-states","country names"],dflt:"ISO-3"},mode:a({},n.mode,{dflt:"markers"}),text:a({},n.text,{}),line:{color:s.color,width:s.width,dash:s.dash},marker:{symbol:o.symbol,opacity:o.opacity,size:o.size,sizeref:o.sizeref,sizemin:o.sizemin,sizemode:o.sizemode,color:o.color,colorscale:o.colorscale,cauto:o.cauto,cmax:o.cmax,cmin:o.cmin,autocolorscale:o.autocolorscale,reversescale:o.reversescale,showscale:o.showscale,line:{color:l.color,width:l.width,colorscale:l.colorscale,cauto:l.cauto,cmax:l.cmax,cmin:l.cmin,autocolorscale:l.autocolorscale,reversescale:l.reversescale}},textfont:n.textfont,textposition:n.textposition,hoverinfo:a({},i.hoverinfo,{flags:["lon","lat","location","text","name"]}),_nestedModules:{"marker.colorbar":"Colorbar"}}},{"../../lib/extend":376,"../../plots/attributes":401,"../scatter/attributes":554}],583:[function(t,e,r){"use strict";var n=t("../scatter/marker_colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(e),r}},{"../scatter/marker_colorscale_calc":568}],584:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=0,o=r("locations");return o?(r("locationmode"),a=o.length):(n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length),an;n++)r[n]=[t.lon[n],t.lat[n]];return{type:"LineString",coordinates:r,trace:t}}function a(t,e){function r(e){var r=t.mockAxis;return c.tickText(r,r.c2l(e),"hover").text+"\xb0"}var n=e.hoverinfo;if("none"===n)return function(t){delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("location")&&Array.isArray(e.locations),o=-1!==i.indexOf("lon"),s=-1!==i.indexOf("lat"),l=-1!==i.indexOf("text");return function(t){var n=[];a?n.push(t.location):o&&s?n.push("("+r(t.lon)+", "+r(t.lat)+")"):o?n.push("lon: "+r(t.lon)):s&&n.push("lat: "+r(t.lat)),l&&n.push(t.tx||e.text),t.textLabel=n.join("
")}}function o(t){var e=Array.isArray(t.locations);return function(r,n){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:n,lon:r.lon,lat:r.lat,location:e?r.location:null}]}}}var s=t("d3"),l=t("../../plots/cartesian/graph_interact"),c=t("../../plots/cartesian/axes"),u=t("../../lib/topojson_utils").getTopojsonFeatures,f=t("../../lib/geo_location_utils").locationToFeature,h=t("../../lib/array_to_calc_item"),d=t("../../components/color"),p=t("../../components/drawing"),g=t("../scatter/subtypes"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){var r,i,a,o,s=[],l=Array.isArray(t.locations);l?(o=t.locations,r=o.length,i=u(t,e),a=function(t,e){var r=f(t.locationmode,o[e],i);return void 0!==r?r.properties.ct:void 0}):(r=t.lon.length,a=function(t,e){return[t.lon[e],t.lat[e]]});for(var c=0;r>c;c++){var h=a(t,c);if(h){var d={lon:h[0],lat:h[1],location:l?t.locations[c]:null};n(t,d,c),s.push(d)}}return s.length>0&&(s[0].trace=t),s},m.plot=function(t,e){var r=t.framework.select(".scattergeolayer").selectAll("g.trace.scattergeo").data(e,function(t){return t.uid});r.enter().append("g").attr("class","trace scattergeo"),r.exit().remove(),r.selectAll("*").remove(),r.each(function(t){var e=s.select(this);g.hasLines(t)&&e.selectAll("path.js-line").data([i(t)]).enter().append("path").classed("js-line",!0)}),r.each(function(e){function r(r,n){if(t.showHover){var i=t.projection([r.lon,r.lat]);h(r),l.loneHover({x:i[0],y:i[1],name:v?e.name:void 0,text:r.textLabel,color:r.mc||(e.marker||{}).color},{container:t.hoverContainer.node()}),y=d(r,n),t.graphDiv.emit("plotly_hover",y)}}function n(e,r){t.graphDiv.emit("plotly_click",d(e,r))}var i=s.select(this),c=g.hasMarkers(e),u=g.hasText(e);if(c||u){var f=m.calcGeoJSON(e,t.topojson),h=a(t,e),d=o(e),p=e.hoverinfo,v="all"===p||-1!==p.indexOf("name"),y=null;c&&i.selectAll("path.point").data(f).enter().append("path").classed("point",!0).on("mouseover",r).on("click",n).on("mouseout",function(){l.loneUnhover(t.hoverContainer),t.graphDiv.emit("plotly_unhover",y)}).on("mousedown",function(){l.loneUnhover(t.hoverContainer)}).on("mouseup",r),u&&i.selectAll("g").data(f).enter().append("g").append("text")}}),m.style(t)},m.style=function(t){var e=t.framework.selectAll("g.trace.scattergeo");e.style("opacity",function(t){return t.opacity}),e.each(function(t){s.select(this).selectAll("path.point").call(p.pointStyle,t),s.select(this).selectAll("text").call(p.textPointStyle,t)}),e.selectAll("path.js-line").style("fill","none").each(function(t){var e=t.trace,r=e.line||{};s.select(this).call(d.stroke,r.color).call(p.dashLine,r.dash||"",r.width||0)})}},{"../../components/color":303,"../../components/drawing":325,"../../lib/array_to_calc_item":372,"../../lib/geo_location_utils":378,"../../lib/topojson_utils":394,"../../plots/cartesian/axes":403,"../../plots/cartesian/graph_interact":410,"../scatter/subtypes":573,"./attributes":582,d3:113}],587:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../constants/gl2d_dashes"),a=t("../../constants/gl_markers"),o=t("../../lib/extend").extendFlat,s=n.line,l=n.marker,c=l.line;e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:o({},n.text,{}),mode:{valType:"flaglist",flags:["lines","markers"],extras:["none"]},line:{color:s.color,width:s.width,dash:{valType:"enumerated",values:Object.keys(i),dflt:"solid"}},marker:{color:l.color,symbol:{valType:"enumerated",values:Object.keys(a),dflt:"circle",arrayOk:!0},size:l.size,sizeref:l.sizeref,sizemin:l.sizemin,sizemode:l.sizemode,opacity:l.opacity,colorscale:l.colorscale,cauto:l.cauto,cmax:l.cmax,cmin:l.cmin,autocolorscale:l.autocolorscale,reversescale:l.reversescale,showscale:l.showscale,line:{color:c.color,width:c.width,colorscale:c.colorscale,cauto:c.cauto,cmax:c.cmax,cmin:c.cmin,autocolorscale:c.autocolorscale,reversescale:c.reversescale}},connectgaps:n.connectgaps,fill:o({},n.fill,{values:["none","tozeroy","tozerox"]}),fillcolor:n.fillcolor,_nestedModules:{error_x:"ErrorBars",error_y:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../constants/gl2d_dashes":366,"../../constants/gl_markers":368,"../../lib/extend":376,"../scatter/attributes":554}],588:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.pickXData=[],this.pickYData=[],this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.connectgaps=!0,this.idToIndex=[],this.bounds=[0,0,0,0],this.hasLines=!1,this.lineOptions={positions:new Float32Array(0),color:[0,0,0,1],width:1,fill:[!1,!1,!1,!1],fillColor:[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],dashes:[1]},this.line=d(t.glplot,this.lineOptions),this.line._trace=this,this.hasErrorX=!1,this.errorXOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorX=p(t.glplot,this.errorXOptions),this.errorX._trace=this,this.hasErrorY=!1,this.errorYOptions={positions:new Float32Array(0),errors:new Float32Array(0),lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorY=p(t.glplot,this.errorYOptions),this.errorY._trace=this,this.hasMarkers=!1,this.scatterOptions={positions:new Float32Array(0),sizes:[],colors:[],glyphs:[],borderWidths:[],borderColors:[],size:12,color:[0,0,0,1],borderSize:1,borderColor:[0,0,0,1]},this.scatter=f(t.glplot,this.scatterOptions),this.scatter._trace=this,this.fancyScatter=h(t.glplot,this.scatterOptions),this.fancyScatter._trace=this}function i(t,e,r){return Array.isArray(e)||(e=[e]),a(t,e,r)}function a(t,e,r){for(var n=new Array(r),i=e[0],a=0;r>a;++a)n[a]=t(a>=e.length?i:e[a]);return n}function o(t,e,r){return l(S(t,r),L(e,r),r)}function s(t,e,r,n){var i=x(t,e,n);return i=Array.isArray(i[0])?i:a(v.identity,[i],n),l(i,L(r,n),n)}function l(t,e,r){for(var n=new Array(4*r),i=0;r>i;++i){for(var a=0;3>a;++a)n[4*i+a]=t[i][a];n[4*i+3]=t[i][3]*e[i]}return n}function c(t,e){if(void 0===Float32Array.slice){for(var r=new Float32Array(e),n=0;e>n;n++)r[n]=t[n];return r}return t.slice(0,e)}function u(t,e){var r=new n(t,e.uid);return r.update(e),r}var f=t("gl-scatter2d"),h=t("gl-scatter2d-fancy"),d=t("gl-line2d"),p=t("gl-error2d"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../plots/cartesian/axes"),y=t("../../components/errorbars"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/subtypes"),w=t("../scatter/make_bubble_size_func"),k=t("../scatter/get_trace_color"),A=t("../../constants/gl_markers"),M=t("../../constants/gl2d_dashes"),T=["xaxis","yaxis"],E=n.prototype;E.handlePick=function(t){var e=t.pointId;return(t.object!==this.line||this.connectgaps)&&(e=this.idToIndex[t.pointId]),{trace:this,dataCoord:t.dataCoord,traceCoord:[this.pickXData[e],this.pickYData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:Array.isArray(this.color)?this.color[e]:this.color,name:this.name,hoverinfo:this.hoverinfo}},E.isFancy=function(t){if("linear"!==this.scene.xaxis.type)return!0;if("linear"!==this.scene.yaxis.type)return!0;if(!t.x||!t.y)return!0;var e=t.marker||{};if(Array.isArray(e.symbol)||"circle"!==e.symbol||Array.isArray(e.size)||Array.isArray(e.line.width)||Array.isArray(e.opacity))return!0;var r=e.color;if(Array.isArray(r))return!0;var n=Array.isArray(e.line.color);return Array.isArray(n)?!0:this.hasErrorX?!0:!!this.hasErrorY};var L=i.bind(null,function(t){return+t}),S=i.bind(null,b),C=i.bind(null,function(t){return A[t]||"\u25cf"});E.update=function(t){t.visible!==!0?(this.hasLines=!1,this.hasErrorX=!1,this.hasErrorY=!1,this.hasMarkers=!1):(this.hasLines=_.hasLines(t),this.hasErrorX=t.error_x.visible===!0,this.hasErrorY=t.error_y.visible===!0,this.hasMarkers=_.hasMarkers(t)),this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.connectgaps=!!t.connectgaps,this.isFancy(t)?this.updateFancy(t):this.updateFast(t),this.color=k(t,{})},E.updateFast=function(t){for(var e,r,n=this.xData=this.pickXData=t.x,i=this.yData=this.pickYData=t.y,a=n.length,o=new Array(a),s=new Float32Array(2*a),l=this.bounds,u=0,f=0,h=0;a>h;++h)e=n[h],r=i[h],g(e)&&g(r)&&(o[u++]=h,s[f++]=e,s[f++]=r,l[0]=Math.min(l[0],e),l[1]=Math.min(l[1],r),l[2]=Math.max(l[2],e),l[3]=Math.max(l[3],r));s=c(s,f),this.idToIndex=o,this.updateLines(t,s),this.updateError("X",t),this.updateError("Y",t);var d;if(this.hasMarkers){this.scatterOptions.positions=s;var p=b(t.marker.color),v=b(t.marker.line.color),m=t.opacity*t.marker.opacity;p[3]*=m,this.scatterOptions.color=p,v[3]*=m,this.scatterOptions.borderColor=v,d=t.marker.size,this.scatterOptions.size=d,this.scatterOptions.borderSize=t.marker.line.width,this.scatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions),this.expandAxesFast(l,d)},E.updateFancy=function(t){var e=this.scene,r=e.xaxis,n=e.yaxis,a=this.bounds,o=this.pickXData=r.makeCalcdata(t,"x").slice(),l=this.pickYData=n.makeCalcdata(t,"y").slice();this.xData=o.slice(),this.yData=l.slice();var u,f,h,d,p,g,v,m,b=y.calcFromTrace(t,e.fullLayout),x=o.length,_=new Array(x),k=new Float32Array(2*x),A=new Float32Array(4*x),M=new Float32Array(4*x),T=0,E=0,S=0,z=0,P="log"===r.type?function(t){return r.d2l(t)}:function(t){return t},R="log"===n.type?function(t){return n.d2l(t)}:function(t){return t};for(u=0;x>u;++u)this.xData[u]=h=P(o[u]),this.yData[u]=d=R(l[u]),isNaN(h)||isNaN(d)||(_[T++]=u,k[E++]=h,k[E++]=d,p=A[S++]=h-b[u].xs||0,g=A[S++]=b[u].xh-h||0,A[S++]=0,A[S++]=0,M[z++]=0,M[z++]=0,v=M[z++]=d-b[u].ys||0,m=M[z++]=b[u].yh-d||0,a[0]=Math.min(a[0],h-p),a[1]=Math.min(a[1],d-v),a[2]=Math.max(a[2],h+g),a[3]=Math.max(a[3],d+m));k=c(k,E),this.idToIndex=_,this.updateLines(t,k),this.updateError("X",t,k,A),this.updateError("Y",t,k,M);var O;if(this.hasMarkers){this.scatterOptions.positions=k,this.scatterOptions.sizes=new Array(T),this.scatterOptions.glyphs=new Array(T),this.scatterOptions.borderWidths=new Array(T),this.scatterOptions.colors=new Array(4*T),this.scatterOptions.borderColors=new Array(4*T);var I,N=w(t),j=t.marker,F=j.opacity,D=t.opacity,B=s(j,F,D,x),U=C(j.symbol,x),V=L(j.line.width,x),q=s(j.line,F,D,x);for(O=i(N,j.size,x),u=0;T>u;++u)for(I=_[u],this.scatterOptions.sizes[u]=4*O[I],this.scatterOptions.glyphs[u]=U[I],this.scatterOptions.borderWidths[u]=.5*V[I],f=0;4>f;++f)this.scatterOptions.colors[4*u+f]=B[4*I+f],this.scatterOptions.borderColors[4*u+f]=q[4*I+f];this.fancyScatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array(0),this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions),this.expandAxesFancy(o,l,O)},E.updateLines=function(t,e){var r;if(this.hasLines){var n=e;if(!t.connectgaps){var i=0,a=this.xData,o=this.yData;for(n=new Float32Array(2*a.length),r=0;ro;o++)r=this.scene[T[o]],n=r._min,n||(n=[]),n.push({val:t[o],pad:a}),i=r._max,i||(i=[]),i.push({val:t[o+2],pad:a})},E.expandAxesFancy=function(t,e,r){var n=this.scene,i={padded:!0,ppad:r};m.expand(n.xaxis,t,i),m.expand(n.yaxis,e,i)},E.dispose=function(){this.line.dispose(),this.errorX.dispose(),this.errorY.dispose(),this.scatter.dispose(),this.fancyScatter.dispose()},e.exports=u},{"../../components/errorbars":331,"../../constants/gl2d_dashes":366,"../../constants/gl_markers":368,"../../lib":381,"../../lib/gl_format_color":379,"../../lib/str2rgbarray":392,"../../plots/cartesian/axes":403,"../scatter/get_trace_color":561,"../scatter/make_bubble_size_func":567,"../scatter/subtypes":573,"fast-isnumeric":117,"gl-error2d":119,"gl-line2d":125,"gl-scatter2d":190,"gl-scatter2d-fancy":185}],589:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/xy_defaults"),s=t("../scatter/marker_defaults"),l=t("../scatter/line_defaults"),c=t("../scatter/fillcolor_defaults"),u=t("../../components/errorbars/defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function d(r,i){return n.coerce(t,e,f,r,i)}var p=o(t,e,d);return p?(d("text"),d("mode",pr;r++)y=e.a[r],b=e.b[r],x=e.c[r],n(y)&&n(b)&&n(x)?(y=+y,b=+b,x=+x,_=v/(y+b+x),1!==_&&(y*=_,b*=_,x*=_),k=y,w=x-b,M[r]={x:w,y:k,a:y,b:b,c:x}):M[r]={x:!1,y:!1};var T,E;if(o.hasMarkers(e)&&(T=e.marker,E=T.size,Array.isArray(E))){var L={type:"linear"};i.setConvert(L),E=L.makeCalcdata(e.marker,"size"),E.length>A&&E.splice(A,E.length-A)}return s(e),void 0!==typeof E&&a.mergeArray(E,M,"ms"),M}},{"../../lib":381,"../../plots/cartesian/axes":403,"../scatter/marker_colorscale_calc":568,"../scatter/subtypes":573,"fast-isnumeric":117}],593:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/line_shape_defaults"),c=t("../scatter/text_defaults"),u=t("../scatter/fillcolor_defaults"),f=t("./attributes");e.exports=function(t,e,r,h){function d(r,i){return n.coerce(t,e,f,r,i)}var p,g=d("a"),v=d("b"),m=d("c");if(g?(p=g.length,v?(p=Math.min(p,v.length),m&&(p=Math.min(p,m.length))):p=m?Math.min(p,m.length):0):v&&m&&(p=Math.min(v.length,m.length)),!p)return void(e.visible=!1);g&&p"),s}}},{"../../plots/cartesian/axes":403,"../scatter/hover":562}],595:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scatterternary",n.basePlotModule=t("../../plots/ternary"),n.categories=["ternary","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../plots/ternary":459,"../scatter/colorbar":557,"./attributes":591,"./calc":592,"./defaults":593,"./hover":594,"./plot":596,"./select":597,"./style":598}],596:[function(t,e,r){"use strict";var n=t("../scatter/plot");e.exports=function(t,e){for(var r={x:function(){return t.xaxis},y:function(){return t.yaxis},plot:t.plotContainer},i=new Array(e.length),a=t.graphDiv.calcdata,o=0;oe){for(var r=g/e,n=[0|Math.floor(t[0].shape[0]*r+1),0|Math.floor(t[0].shape[1]*r+1)],i=n[0]*n[1],o=0;or;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},v.update=function(t){var e,r=this.scene,n=r.fullSceneLayout,a=this.surface,s=t.opacity,l=i(t.colorscale,s),u=t.z,h=t.x,d=t.y,g=n.xaxis,v=n.yaxis,m=n.zaxis,y=r.dataScale,b=u[0].length,x=u.length,_=[c(new Float32Array(b*x),[b,x]),c(new Float32Array(b*x),[b,x]),c(new Float32Array(b*x),[b,x])],w=_[0],k=_[1],A=r.contourLevels;this.data=t,f(_[2],function(t,e){return m.d2l(u[e][t])*y[2]}),Array.isArray(h[0])?f(w,function(t,e){return g.d2l(h[e][t])*y[0]}):f(w,function(t){return g.d2l(h[t])*y[0]}),Array.isArray(d[0])?f(k,function(t,e){return v.d2l(d[e][t])*y[1]}):f(k,function(t,e){return v.d2l(d[e])*y[1]});var M={colormap:l,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:1};if(M.intensityBounds=[t.cmin,t.cmax],t.surfacecolor){var T=c(new Float32Array(b*x),[b,x]);f(T,function(e,r){return t.surfacecolor[r][e]}),_.push(T)}else M.intensityBounds[0]*=y[2],M.intensityBounds[1]*=y[2];this.dataScale=o(_),t.surfacecolor&&(M.intensity=_.pop()),"opacity"in t&&t.opacity<1&&(M.opacity=.25*t.opacity);var E=[!0,!0,!0],L=["x","y","z"];for(e=0;3>e;++e){var S=t.contours[L[e]];E[e]=S.highlight,M.showContour[e]=S.show||S.highlight,M.showContour[e]&&(M.contourProject[e]=[S.project.x,S.project.y,S.project.z],S.show?(this.showContour[e]=!0,M.levels[e]=A[e],a.highlightColor[e]=M.contourColor[e]=p(S.color),S.usecolormap?a.highlightTint[e]=M.contourTint[e]=0:a.highlightTint[e]=M.contourTint[e]=1,M.contourWidth[e]=S.width):this.showContour[e]=!1,S.highlight&&(M.dynamicColor[e]=p(S.highlightcolor),M.dynamicWidth[e]=S.highlightwidth))}M.coords=_,a.update(M),a.visible=t.visible,a.enableDynamic=E,a.snapToData=!0,"lighting"in t&&(a.ambientLight=t.lighting.ambient,a.diffuseLight=t.lighting.diffuse,a.specularLight=t.lighting.specular,a.roughness=t.lighting.roughness,a.fresnel=t.lighting.fresnel),"lightposition"in t&&(void 0===a.lightPosition?a.lightPosition=[t.lightposition.x,t.lightposition.y,t.lightposition.z]:(a.lightPosition.x=t.lightposition.x,a.lightPosition.y=t.lightposition.y,a.lightPosition.z=t.lightposition.z)),s&&1>s&&(a.supportsTransparency=!0)},v.dispose=function(){this.scene.glplot.remove(this.surface),this.surface.dispose()},e.exports=s},{"../../lib/str2rgbarray":392,"gl-surface3d":221,ndarray:253,"ndarray-fill":246,"ndarray-homography":251, +"ndarray-ops":252,tinycolor2:274}],603:[function(t,e,r){"use strict";function n(t,e,r){e in t&&!(r in t)&&(t[r]=t[e])}var i=t("../../lib"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,n){return i.coerce(t,e,o,r,n)}var c,u,f=l("z");if(!f)return void(e.visible=!1);var h=f[0].length,d=f.length;if(l("x"),l("y"),!Array.isArray(e.x))for(e.x=[],c=0;h>c;++c)e.x[c]=c;if(l("text"),!Array.isArray(e.y))for(e.y=[],c=0;d>c;++c)e.y[c]=c;["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","lightposition.x","lightposition.y","lightposition.z","hidesurface","opacity"].forEach(function(t){l(t)});var p=l("surfacecolor");l("colorscale");var g=["x","y","z"];for(c=0;3>c;++c){var v="contours."+g[c],m=l(v+".show"),y=l(v+".highlight");if(m||y)for(u=0;3>u;++u)l(v+".project."+g[u]);m&&(l(v+".color"),l(v+".width"),l(v+".usecolormap")),y&&(l(v+".highlightcolor"),l(v+".highlightwidth"))}p||(n(t,"zmin","cmin"),n(t,"zmax","cmax"),n(t,"zauto","cauto")),a(t,e,s,l,{prefix:"",cLetter:"c"})}},{"../../components/colorscale/defaults":312,"../../lib":381,"./attributes":599}],604:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("./colorbar"),n.calc=t("./calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="surface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","noOpacity"],n.meta={},e.exports=n},{"../../plots/gl3d":439,"./attributes":599,"./calc":600,"./colorbar":601,"./convert":602,"./defaults":603}]},{},[12])(12)}); \ No newline at end of file From 5c5c715e4f1d236a1291f31698e68aa892be9565 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Mon, 20 Jun 2016 15:54:41 -0400 Subject: [PATCH 19/21] Animation interrupts --- src/plot_api/plot_api.js | 89 +++++++++++++++----------- src/plots/cartesian/transition_axes.js | 7 ++ 2 files changed, 60 insertions(+), 36 deletions(-) diff --git a/src/plot_api/plot_api.js b/src/plot_api/plot_api.js index 4fe6299c97a..c37126383b1 100644 --- a/src/plot_api/plot_api.js +++ b/src/plot_api/plot_api.js @@ -1545,8 +1545,6 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces, newLayou transitionOpts.cascade = transitionOpts.cascade === undefined ? 0 : transitionOpts.cascade; transitionOpts.leadingEdgeRestyle = transitionOpts.leadingEdgeRestyle === undefined ? false : transitionOpts.leadingEdgeRestyle; - gd = getGraphDiv(gd); - if(isNumeric(traces)) traces = [traces]; else if(!Array.isArray(traces) || !traces.length) { traces = gd._fullData.map(function (v,i) {return i;}); @@ -1556,46 +1554,46 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces, newLayou var animatedTraces = []; - for (i = 0; i < traces.length; i++) { - var traceIdx = traces[i]; - var trace = gd._fullData[traceIdx]; - var module = trace._module; + function beginAnimation () { + for (i = 0; i < traces.length; i++) { + var traceIdx = traces[i]; + var trace = gd._fullData[traceIdx]; + var module = trace._module; - if (!module.animatable) { - continue; - } + if (!module.animatable) { + continue; + } - animatedTraces.push(traceIdx); + animatedTraces.push(traceIdx); - newTraceData = newData[i]; - curData = gd.data[traces[i]]; + newTraceData = newData[i]; + curData = gd.data[traces[i]]; - for (var ai in newTraceData) { - var value = newTraceData[ai]; - Lib.nestedProperty(curData, ai).set(value); - } + for (var ai in newTraceData) { + var value = newTraceData[ai]; + Lib.nestedProperty(curData, ai).set(value); + } - var traceIdx = traces[i]; - if (gd.data[traceIdx].marker && gd.data[traceIdx].marker.size) { - gd._fullData[traceIdx].marker.size = gd.data[traceIdx].marker.size - } - if (gd.data[traceIdx].error_y && gd.data[traceIdx].error_y.array) { - gd._fullData[traceIdx].error_y.array = gd.data[traceIdx].error_y.array - } - if (gd.data[traceIdx].error_x && gd.data[traceIdx].error_x.array) { - gd._fullData[traceIdx].error_x.array = gd.data[traceIdx].error_x.array + var traceIdx = traces[i]; + if (gd.data[traceIdx].marker && gd.data[traceIdx].marker.size) { + gd._fullData[traceIdx].marker.size = gd.data[traceIdx].marker.size + } + if (gd.data[traceIdx].error_y && gd.data[traceIdx].error_y.array) { + gd._fullData[traceIdx].error_y.array = gd.data[traceIdx].error_y.array + } + if (gd.data[traceIdx].error_x && gd.data[traceIdx].error_x.array) { + gd._fullData[traceIdx].error_x.array = gd.data[traceIdx].error_x.array + } + gd._fullData[traceIdx].x = gd.data[traceIdx].x; + gd._fullData[traceIdx].y = gd.data[traceIdx].y; + gd._fullData[traceIdx].z = gd.data[traceIdx].z; + gd._fullData[traceIdx].key = gd.data[traceIdx].key; } - gd._fullData[traceIdx].x = gd.data[traceIdx].x; - gd._fullData[traceIdx].y = gd.data[traceIdx].y; - gd._fullData[traceIdx].z = gd.data[traceIdx].z; - gd._fullData[traceIdx].key = gd.data[traceIdx].key; - gd._fullData[traceIdx].r = gd.data[traceIdx].r; - gd._fullData[traceIdx].t = gd.data[traceIdx].t; - } - doCalcdata(gd, animatedTraces); + doCalcdata(gd, animatedTraces); - ErrorBars.calc(gd); + ErrorBars.calc(gd); + } /*function doSetPositions () { var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'); @@ -1621,6 +1619,8 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces, newLayou var restyleList = []; var relayoutList = []; + var completionTimeout = null; + var completion = null; function doAnimations () { var a, i, j; @@ -1639,11 +1639,28 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces, newLayou if (!transitionOpts.leadingEdgeRestyle) { return new Promise(function(resolve, reject) { - setTimeout(resolve, transitionOpts.duration); + completion = resolve; + completionTimeout = setTimeout(resolve, transitionOpts.duration); }); } } + function executeInterrupt () { + var ret; + clearTimeout(completionTimeout); + + if (completion) { + console.log('complete!'); + completion(); + } + + if (gd._animationInterrupt) { + ret = gd._animationInterrupt(); + gd._animationInterrupt = null; + } + return ret; + } + /*for (var i = 0; i < animatedTraces.length; i++) { var trace = gd._fullData[animatedTraces[i]]; var module = trace._module; @@ -1689,7 +1706,7 @@ Plotly.animate = function animate (gd, newData, transitionOpts, traces, newLayou } } - var seq = [Plots.previousPromises]; + var seq = [Plots.previousPromises, executeInterrupt, beginAnimation]; seq.push(doAnimations); seq = seq.concat(restyleList); diff --git a/src/plots/cartesian/transition_axes.js b/src/plots/cartesian/transition_axes.js index 15bf0e4cf73..1825ee772d3 100644 --- a/src/plots/cartesian/transition_axes.js +++ b/src/plots/cartesian/transition_axes.js @@ -236,6 +236,13 @@ module.exports = function transitionAxes(gd, newLayout, transitionConfig) { return new Promise(function (resolve, reject) { var t1, t2, raf; + gd._animationInterrupt = function () { + reject(); + cancelAnimationFrame(raf); + raf = null; + transitionTail(); + }; + function doFrame () { t2 = Date.now(); From b75280fdbf03c27a9acce7e8174de38ed27e1c13 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Tue, 21 Jun 2016 10:20:01 -0400 Subject: [PATCH 20/21] Remove linepoint override --- src/traces/scatter/line_points.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/traces/scatter/line_points.js b/src/traces/scatter/line_points.js index df5e40bb7e3..60d7e3c77ea 100644 --- a/src/traces/scatter/line_points.js +++ b/src/traces/scatter/line_points.js @@ -60,7 +60,7 @@ module.exports = function linePoints(d, opts) { function getTolerance(pt) { var xFrac = pt[0] / xa._length, yFrac = pt[1] / ya._length; - return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance * 0; + return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance; } function ptDist(pt1, pt2) { From 990787e25aaa89c631b34f2dc1920096265e60c2 Mon Sep 17 00:00:00 2001 From: Ricky Reusser Date: Tue, 21 Jun 2016 11:59:09 -0400 Subject: [PATCH 21/21] Removed unused logic --- src/plots/cartesian/transition_axes.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/plots/cartesian/transition_axes.js b/src/plots/cartesian/transition_axes.js index 1825ee772d3..b6f1d404022 100644 --- a/src/plots/cartesian/transition_axes.js +++ b/src/plots/cartesian/transition_axes.js @@ -117,17 +117,14 @@ module.exports = function transitionAxes(gd, newLayout, transitionConfig) { var viewBox = [0, 0, xa2._length, ya2._length]; - var editX = true; - var editY = true; + var xScaleFactor = xa2._length / viewBox[2], + yScaleFactor = ya2._length / viewBox[3]; - var xScaleFactor = editX ? xa2._length / viewBox[2] : 1, - yScaleFactor = editY ? ya2._length / viewBox[3] : 1; + var clipDx = viewBox[0], + clipDy = viewBox[1]; - var clipDx = editX ? viewBox[0] : 0, - clipDy = editY ? viewBox[1] : 0; - - var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0, - fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0; + var fracDx = (viewBox[0] / viewBox[2] * xa2._length), + fracDy = (viewBox[1] / viewBox[3] * ya2._length); var plotDx = xa2._offset - fracDx, plotDy = ya2._offset - fracDy;